Rahatara commited on
Commit
02b83f7
·
verified ·
1 Parent(s): b4e578d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +225 -2
app.py CHANGED
@@ -1,14 +1,123 @@
1
  import gradio as gr
 
 
2
  import trimesh
3
  import numpy as np
4
  from PIL import Image
 
 
5
  import tempfile
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
  # Function to visualize texture based on selection criteria
8
  def visualize_dynamic_texture(predefined_section, x_min, x_max, y_min, y_max, z_min, z_max):
9
  # Load the original mesh
10
  mesh = trimesh.load('train.glb', force='mesh')
11
- rust_texture = Image.open('rust_steel.png').convert('RGB')
12
 
13
  # Predefined sections
14
  if predefined_section == 'right compartments':
@@ -86,4 +195,118 @@ with gr.Blocks() as app:
86
  for input_component in inputs:
87
  input_component.change(fn=update_model, inputs=inputs, outputs=modified_model)
88
 
89
- app.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
+ import replicate
3
+ import openai
4
  import trimesh
5
  import numpy as np
6
  from PIL import Image
7
+ import requests
8
+ import io
9
  import tempfile
10
+ import os
11
+
12
+ # Set API tokens
13
+ os.environ["REPLICATE_API_TOKEN"] = "r8_Pc64F8EPrJ6PiNIIvaBUZcOGmiLC3Jp1gELYB"
14
+ # Initialize the Replicate client
15
+ rep_client = replicate.Client()
16
+
17
+ # Set your OpenAI API key
18
+ OPENAI_API_KEY = "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"
19
+ openai.api_key = OPENAI_API_KEY
20
+
21
+ # Initialize the Replicate client
22
+ rep_client = replicate.Client()
23
+
24
+ #--------------------------------2D Defect Simulator----------------------
25
+
26
+ predefined_defects = [
27
+ "Missing bolts on railway track",
28
+ "Cracks on railway track",
29
+ "Overgrown vegetation near railway track",
30
+ "Broken railings on railway bridge",
31
+ "Debris on railway track",
32
+ "Damaged railway platform"
33
+ ]
34
+
35
+ # Material defects structure
36
+ material_defects = {
37
+ "Steel": ["Rust and Corrosion", "Pitting Corrosion", "Surface Cracks", "Wear Patterns", "Spalling", "Scaling"],
38
+ "Glass": ["Cracks", "Chips", "Scratches", "Frosting"],
39
+ "Aluminum": ["Corrosion", "Scratches and Dents", "Anodizing Wear"],
40
+ "Wood": ["Rot and Decay", "Cracks and Splits", "Weathering"],
41
+ "Plastics and Polymers": ["Cracking and Crazing", "UV Degradation", "Heat Distortion"],
42
+ "Rubber": ["Cracking", "Hardening and Brittleness", "Surface Wear"],
43
+ "Composite Materials": ["Delamination", "Impact Damage", "Fiber Wearing"],
44
+ "Ceramics": ["Crackling", "Chipping and Pitting", "Glaze Deterioration"]
45
+ }
46
+
47
+ # Function to ask rail defect question
48
+ def ask_rail_defect_question(question):
49
+ structured_prompt = f"Translate the following user input into a concise, detailed visual description for a 3D model based on this input: '{question}'. Focus only on the defect’s appearance, texture qualities, and visual effects it would have on the material. Start the description directly with no extra words."
50
+ response = openai.ChatCompletion.create(
51
+ model='gpt-3.5-turbo',
52
+ messages=[
53
+ {"role": "system", "content": "Provide a concise, detailed visual description of the material's defect texture, focusing on visual and tactile qualities. Do not include any additional context or introductory phrases. Imagine the textures on railway components, but describe only the texture and material."},
54
+ {"role": "user", "content": structured_prompt}
55
+ ],
56
+ )
57
+ refined_description = response.choices[0].message['content']
58
+ return refined_description.strip()
59
+
60
+ # Function to generate images from prompts
61
+ def generate_images(prompt):
62
+ prediction = rep_client.predictions.create(
63
+ version="ac732df83cea7fff18b8472768c88ad041fa750ff7682a21affe81863cbe77e4",
64
+ input={"prompt": prompt}
65
+ )
66
+ prediction.wait()
67
+ if prediction.status == "succeeded":
68
+ image_url = prediction.output[0]
69
+ response = requests.get(image_url)
70
+ image = Image.open(io.BytesIO(response.content))
71
+ image.save("defect.png")
72
+ return image
73
+ return None
74
+
75
+ # Function to create data URL from PIL image
76
+ def image_to_data_url(pil_image):
77
+ buffered = io.BytesIO()
78
+ pil_image.save(buffered, format="JPEG")
79
+ base64_image = base64.b64encode(buffered.getvalue()).decode('utf-8')
80
+ return f"data:image/jpeg;base64,{base64_image}"
81
+
82
+ # Function to inpaint images
83
+ def inpaint_texture(image, prompt):
84
+ if isinstance(image, np.ndarray):
85
+ image = Image.fromarray(image)
86
+
87
+ image_data_url = image_to_data_url(image)
88
+
89
+ input = {
90
+ "image": image_data_url,
91
+ "prompt": prompt,
92
+ "scheduler": "K_EULER_ANCESTRAL",
93
+ "num_outputs": 1,
94
+ "guidance_scale": 7.5,
95
+ "num_inference_steps": 100,
96
+ "image_guidance_scale": 1.5
97
+ }
98
+
99
+ prediction = rep_client.predictions.create(
100
+ version="30c1d0b916a6f8efce20493f5d61ee27491ab2a60437c13c588468b9810ec23f",
101
+ input = input
102
+ )
103
+ prediction.wait()
104
+ if prediction.status == "succeeded":
105
+ image_url = prediction.output[0]
106
+ response = requests.get(image_url)
107
+ image = Image.open(io.BytesIO(response.content))
108
+ image.save("defect.png")
109
+ return image
110
+ return None
111
+
112
+ # Function to update defect options
113
+ def update_defect_options(selected_material):
114
+ return gr.update(value='', choices=material_defects[selected_material])
115
 
116
  # Function to visualize texture based on selection criteria
117
  def visualize_dynamic_texture(predefined_section, x_min, x_max, y_min, y_max, z_min, z_max):
118
  # Load the original mesh
119
  mesh = trimesh.load('train.glb', force='mesh')
120
+ rust_texture = Image.open('defect.png').convert('RGB')
121
 
122
  # Predefined sections
123
  if predefined_section == 'right compartments':
 
195
  for input_component in inputs:
196
  input_component.change(fn=update_model, inputs=inputs, outputs=modified_model)
197
 
198
+ gr.Markdown("### 3D Defect Simulator Tabs")
199
+ with gr.Tabs():
200
+ with gr.Tab("Predefined Defect Texture"):
201
+ with gr.Row():
202
+ material_input = gr.Dropdown(choices=list(material_defects.keys()), label="Select Material")
203
+ defect_input = gr.Dropdown(choices=[], label="Select Defect Type")
204
+ generate_button = gr.Button("Generate Texture")
205
+ image_output = gr.Image(label="Generated Texture")
206
+ model_output_predefined = gr.Model3D(label="3D Model with Applied Texture")
207
+
208
+ material_input.change(fn=update_defect_options, inputs=[material_input], outputs=[defect_input])
209
+ generate_button.click(
210
+ fn=lambda material, defect: generate_images(ask_rail_defect_question(f"Describe the texture of {defect} on {material}")),
211
+ inputs=[material_input, defect_input],
212
+ outputs=[image_output]
213
+ )
214
+
215
+ visualize_button_predefined = gr.Button("Visualize 3D Model")
216
+ visualize_button_predefined.click(
217
+ fn=update_model,
218
+ inputs=[section_dropdown, x_min_slider, x_max_slider, y_min_slider, y_max_slider, z_min_slider, z_max_slider],
219
+ outputs=[model_output_predefined]
220
+ )
221
+
222
+ with gr.Tab("Custom Defect Texture"):
223
+ with gr.Row():
224
+ custom_prompt_input = gr.Textbox(label="Enter Custom Prompt for Texture", placeholder="Describe any texture detail you need.")
225
+ refine_button = gr.Button("Refine Prompt")
226
+ refined_prompt_output = gr.Textbox(label="Refined Prompt", placeholder="This will show the refined prompt.")
227
+
228
+ with gr.Row():
229
+ generate_button = gr.Button("Generate Texture")
230
+ custom_image_output = gr.Image(label="Generated Texture")
231
+ model_output_custom = gr.Model3D(label="3D Model with Applied Texture")
232
+
233
+ # Refine the input prompt
234
+ refine_button.click(
235
+ fn=lambda prompt: ask_rail_defect_question(prompt),
236
+ inputs=[custom_prompt_input],
237
+ outputs=[refined_prompt_output]
238
+ )
239
+
240
+ # Use the refined prompt to generate the texture image
241
+ generate_button.click(
242
+ fn=lambda prompt: generate_images(prompt),
243
+ inputs=[refined_prompt_output],
244
+ outputs=[custom_image_output]
245
+ )
246
+
247
+ visualize_button_custom = gr.Button("Visualize 3D Model")
248
+ visualize_button_custom.click(
249
+ fn=update_model,
250
+ inputs=[section_dropdown, x_min_slider, x_max_slider, y_min_slider, y_max_slider, z_min_slider, z_max_slider],
251
+ outputs=[model_output_custom]
252
+ )
253
+
254
+ with gr.Tab("Inpaint Defect Texture"):
255
+ with gr.Row():
256
+ image_input = gr.Image(label="Upload Image for Inpainting")
257
+ inpaint_prompt_input = gr.Textbox(label="Enter Prompt for Texture Inpainting")
258
+ inpaint_button = gr.Button("Generate Inpainted Texture")
259
+ inpaint_image_output = gr.Image(label="Generated Inpainted Texture")
260
+ model_output_inpaint = gr.Model3D(label="3D Model with Applied Texture")
261
+
262
+ # Use the images and prompt to generate the inpainted texture image
263
+ inpaint_button.click(
264
+ fn=lambda img, prompt: inpaint_texture(img, prompt),
265
+ inputs=[image_input, inpaint_prompt_input],
266
+ outputs=[inpaint_image_output]
267
+ )
268
+
269
+ visualize_button_inpaint = gr.Button("Visualize 3D Model")
270
+ visualize_button_inpaint.click(
271
+ fn=update_model,
272
+ inputs=[section_dropdown, x_min_slider, x_max_slider, y_min_slider, y_max_slider, z_min_slider, z_max_slider],
273
+ outputs=[model_output_inpaint]
274
+ )
275
+
276
+ with gr.Tab("2D Defect Simulator"):
277
+ with gr.Tabs():
278
+ with gr.Tab("Current Defects"):
279
+ with gr.Row():
280
+ prompt_input = gr.Dropdown(choices=predefined_defects, label="Select a prompt")
281
+ number_input_dropdown = gr.Number(label="Number of images to generate", value=1, minimum=1, maximum=10)
282
+ submit_button_dropdown = gr.Button("Generate")
283
+ image_outputs_dropdown = gr.Gallery()
284
+
285
+ def on_submit_click_dropdown(prompt, number_of_images):
286
+ images = process_railway_defects(prompt, number_of_images)
287
+ return images
288
+
289
+ submit_button_dropdown.click(
290
+ fn=on_submit_click_dropdown,
291
+ inputs=[prompt_input, number_input_dropdown],
292
+ outputs=image_outputs_dropdown
293
+ )
294
+
295
+ with gr.Tab("Custom Defect"):
296
+ with gr.Row():
297
+ custom_prompt_input = gr.Textbox(label="Custom Defect")
298
+ number_input_custom = gr.Number(label="Number of images to generate", value=1, minimum=1, maximum=10)
299
+ submit_button_custom = gr.Button("Generate")
300
+ image_outputs_custom = gr.Gallery()
301
+
302
+ def on_submit_click_custom(custom_prompt, number_of_images):
303
+ images = process_railway_defects(custom_prompt, number_of_images)
304
+ return images
305
+
306
+ submit_button_custom.click(
307
+ fn=on_submit_click_custom,
308
+ inputs=[custom_prompt_input, number_input_custom],
309
+ outputs=image_outputs_custom
310
+ )
311
+
312
+ app.launch()