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
4 |
+
import trimesh
|
5 |
+
import numpy as np
|
6 |
+
from PIL import Image
|
7 |
+
import requests
|
8 |
+
import io
|
9 |
+
import tempfile
|
10 |
+
|
11 |
+
# Set API tokens
|
12 |
+
os.environ["REPLICATE_API_TOKEN"] = "r8_Pc64F8EPrJ6PiNIIvaBUZcOGmiLC3Jp1gELYB"
|
13 |
+
OPENAI_API_KEY = "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"
|
14 |
+
|
15 |
+
# Initialize the Replicate client
|
16 |
+
rep_client = replicate.Client()
|
17 |
+
|
18 |
+
# Material defects structure
|
19 |
+
material_defects = {
|
20 |
+
"Steel": ["Rust and Corrosion", "Pitting Corrosion", "Surface Cracks", "Wear Patterns", "Spalling", "Scaling"],
|
21 |
+
"Glass": ["Cracks", "Chips", "Scratches", "Frosting"],
|
22 |
+
"Aluminum": ["Corrosion", "Scratches and Dents", "Anodizing Wear"],
|
23 |
+
"Wood": ["Rot and Decay", "Cracks and Splits", "Weathering"],
|
24 |
+
"Plastics and Polymers": ["Cracking and Crazing", "UV Degradation", "Heat Distortion"],
|
25 |
+
"Rubber": ["Cracking", "Hardening and Brittleness", "Surface Wear"],
|
26 |
+
"Composite Materials": ["Delamination", "Impact Damage", "Fiber Wearing"],
|
27 |
+
"Ceramics": ["Crackling", "Chipping and Pitting", "Glaze Deterioration"]
|
28 |
+
}
|
29 |
+
|
30 |
+
# Function to ask rail defect question
|
31 |
+
def ask_rail_defect_question(question, model_name='ft:gpt-3.5-turbo-0125:personal::99NsSAeQ'):
|
32 |
+
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."
|
33 |
+
response = openai.ChatCompletion.create(
|
34 |
+
model=model_name,
|
35 |
+
messages=[
|
36 |
+
{"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."},
|
37 |
+
{"role": "user", "content": structured_prompt}
|
38 |
+
],
|
39 |
+
)
|
40 |
+
refined_description = response.choices[0].message['content']
|
41 |
+
return refined_description.strip()
|
42 |
+
|
43 |
+
# Function to generate images from prompts
|
44 |
+
def generate_images(prompt):
|
45 |
+
prediction = rep_client.predictions.create(
|
46 |
+
version="ac732df83cea7fff18b8472768c88ad041fa750ff7682a21affe81863cbe77e",
|
47 |
+
input={"prompt": prompt}
|
48 |
+
)
|
49 |
+
prediction.wait()
|
50 |
+
if prediction.status == "succeeded":
|
51 |
+
image_url = prediction.output[0]
|
52 |
+
response = requests.get(image_url)
|
53 |
+
image = Image.open(io.BytesIO(response.content))
|
54 |
+
return image
|
55 |
+
return "Failed to generate texture image"
|
56 |
+
|
57 |
+
# Function to create data URL from PIL image
|
58 |
+
def image_to_data_url(pil_image):
|
59 |
+
buffered = io.BytesIO()
|
60 |
+
pil_image.save(buffered, format="JPEG")
|
61 |
+
base64_image = base64.b64encode(buffered.getvalue()).decode('utf-8')
|
62 |
+
return f"data:image/jpeg;base64,{base64_image}"
|
63 |
+
|
64 |
+
# Function to inpaint images
|
65 |
+
def inpaint_texture(image, prompt):
|
66 |
+
if isinstance(image, np.ndarray):
|
67 |
+
image = Image.fromarray(image)
|
68 |
+
|
69 |
+
image_data_url = image_to_data_url(image)
|
70 |
+
|
71 |
+
input = {
|
72 |
+
"image": image_data_url,
|
73 |
+
"prompt": prompt,
|
74 |
+
"scheduler": "K_EULER_ANCESTRAL",
|
75 |
+
"num_outputs": 1,
|
76 |
+
"guidance_scale": 7.5,
|
77 |
+
"num_inference_steps": 100,
|
78 |
+
"image_guidance_scale": 1.5
|
79 |
+
}
|
80 |
+
|
81 |
+
prediction = rep_client.predictions.create(
|
82 |
+
version="30c1d0b916a6f8efce20493f5d61ee27491ab2a60437c13c588468b9810ec23f",
|
83 |
+
input = input
|
84 |
+
)
|
85 |
+
prediction.wait()
|
86 |
+
if prediction.status == "succeeded":
|
87 |
+
image_url = prediction.output[0]
|
88 |
+
response = requests.get(image_url)
|
89 |
+
image = Image.open(io.BytesIO(response.content))
|
90 |
+
return image
|
91 |
+
return "Failed to generate inpainted texture image"
|
92 |
+
|
93 |
+
# Function to update defect options
|
94 |
+
def update_defect_options(selected_material):
|
95 |
+
return gr.update(value='', choices=material_defects[selected_material])
|
96 |
+
|
97 |
+
# Function to visualize texture based on selection criteria
|
98 |
+
def visualize_dynamic_texture(predefined_section, x_min, x_max, y_min, y_max, z_min, z_max, custom_texture_path):
|
99 |
+
# Load the original mesh
|
100 |
+
mesh = trimesh.load('train.glb', force='mesh')
|
101 |
+
custom_texture = Image.open(custom_texture_path).convert('RGB')
|
102 |
+
|
103 |
+
# Predefined sections
|
104 |
+
if predefined_section == 'right compartments':
|
105 |
+
selected_indices = np.where(mesh.vertices[:, 0] > (train_bounds[0][0] + train_bounds[1][0]) / 2)[0]
|
106 |
+
elif predefined_section == 'left compartments':
|
107 |
+
selected_indices = np.where(mesh.vertices[:, 0] <= (train_bounds[0][0] + train_bounds[1][0]) / 2)[0]
|
108 |
+
elif predefined_section == 'freight_body':
|
109 |
+
selected_indices = np.where((mesh.vertices[:, 0] >= train_bounds[0][0]) & (mesh.vertices[:, 0] <= train_bounds[1][0]) &
|
110 |
+
(mesh.vertices[:, 2] <= (train_bounds[0][2] + train_bounds[1][2]) / 2))[0]
|
111 |
+
elif predefined_section == 'custom':
|
112 |
+
# Use custom sliders for custom section
|
113 |
+
selected_indices = np.where((mesh.vertices[:, 0] >= x_min) & (mesh.vertices[:, 0] <= x_max) &
|
114 |
+
(mesh.vertices[:, 1] >= y_min) & (mesh.vertices[:, 1] <= y_max) &
|
115 |
+
(mesh.vertices[:, 2] >= z_min) & (mesh.vertices[:, 2] <= z_max))[0]
|
116 |
+
else:
|
117 |
+
selected_indices = np.array([])
|
118 |
+
|
119 |
+
# Initialize UV mapping
|
120 |
+
uv = np.random.rand(len(mesh.vertices), 2)
|
121 |
+
new_uv = np.zeros_like(uv)
|
122 |
+
new_uv[selected_indices, :] = uv[selected_indices, :]
|
123 |
+
|
124 |
+
# Create material and apply the new texture
|
125 |
+
material = trimesh.visual.texture.SimpleMaterial(image=custom_texture)
|
126 |
+
color_visuals = trimesh.visual.TextureVisuals(uv=new_uv, image=custom_texture, material=material)
|
127 |
+
textured_mesh = trimesh.Trimesh(vertices=mesh.vertices, faces=mesh.faces, visual=color_visuals, validate=True, process=False)
|
128 |
+
|
129 |
+
# Save the mesh to a temporary file
|
130 |
+
temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.glb')
|
131 |
+
textured_mesh.export(temp_file.name, file_type='glb')
|
132 |
+
temp_file.close()
|
133 |
+
return temp_file.name
|
134 |
+
|
135 |
+
# Load train model to establish bounding box ranges
|
136 |
+
train_model = trimesh.load('train.glb', force='mesh')
|
137 |
+
train_bounds = train_model.bounds
|
138 |
+
|
139 |
+
# Get slider ranges based on train model bounds
|
140 |
+
x_min_range, x_max_range = train_bounds[0][0], train_bounds[1][0]
|
141 |
+
y_min_range, y_max_range = train_bounds[0][1], train_bounds[1][1]
|
142 |
+
z_min_range, z_max_range = train_bounds[0][2], train_bounds[1][2]
|
143 |
+
|
144 |
+
# Gradio app interface setup
|
145 |
+
with gr.Blocks() as app:
|
146 |
+
with gr.Tabs():
|
147 |
+
with gr.Tab("3D Defect Simulator"):
|
148 |
+
with gr.Tabs():
|
149 |
+
with gr.Tab("Predefined Defect Texture"):
|
150 |
+
with gr.Row():
|
151 |
+
material_input = gr.Dropdown(choices=list(material_defects.keys()), label="Select Material")
|
152 |
+
defect_input = gr.Dropdown(choices=[], label="Select Defect Type")
|
153 |
+
generate_button = gr.Button("Generate Texture")
|
154 |
+
image_output = gr.Image(label="Generated Texture")
|
155 |
+
|
156 |
+
material_input.change(fn=update_defect_options, inputs=[material_input], outputs=[defect_input])
|
157 |
+
generate_button.click(
|
158 |
+
fn=lambda material, defect: generate_images(ask_rail_defect_question(f"Describe the texture of {defect} on {material}")),
|
159 |
+
inputs=[material_input, defect_input],
|
160 |
+
outputs=[image_output]
|
161 |
+
)
|
162 |
+
|
163 |
+
with gr.Tab("Custom Defect Texture"):
|
164 |
+
with gr.Row():
|
165 |
+
custom_prompt_input = gr.Textbox(label="Enter Custom Prompt for Texture", placeholder="Describe any texture detail you need.")
|
166 |
+
refine_button = gr.Button("Refine Prompt")
|
167 |
+
refined_prompt_output = gr.Textbox(label="Refined Prompt", placeholder="This will show the refined prompt.")
|
168 |
+
|
169 |
+
with gr.Row():
|
170 |
+
generate_button = gr.Button("Generate Texture")
|
171 |
+
custom_image_output = gr.Image(label="Generated Texture")
|
172 |
+
|
173 |
+
# Refine the input prompt
|
174 |
+
refine_button.click(
|
175 |
+
fn=lambda prompt: ask_rail_defect_question(prompt),
|
176 |
+
inputs=[custom_prompt_input],
|
177 |
+
outputs=[refined_prompt_output]
|
178 |
+
)
|
179 |
+
|
180 |
+
# Use the refined prompt to generate the texture image
|
181 |
+
generate_button.click(
|
182 |
+
fn=lambda prompt: generate_images(prompt),
|
183 |
+
inputs=[refined_prompt_output],
|
184 |
+
outputs=[custom_image_output]
|
185 |
+
)
|
186 |
+
|
187 |
+
with gr.Tab("Inpaint Defect Texture"):
|
188 |
+
with gr.Row():
|
189 |
+
image_input = gr.Image(label="Upload Image for Inpainting")
|
190 |
+
inpaint_prompt_input = gr.Textbox(label="Enter Prompt for Texture Inpainting")
|
191 |
+
inpaint_button = gr.Button("Generate Inpainted Texture")
|
192 |
+
inpaint_image_output = gr.Image(label="Generated Inpainted Texture")
|
193 |
+
|
194 |
+
# Use the images and prompt to generate the inpainted texture image
|
195 |
+
inpaint_button.click(
|
196 |
+
fn=lambda img, prompt: inpaint_texture(img, prompt),
|
197 |
+
inputs=[image_input, inpaint_prompt_input],
|
198 |
+
outputs=[inpaint_image_output]
|
199 |
+
)
|
200 |
+
|
201 |
+
with gr.Tab("Apply Custom Texture"):
|
202 |
+
with gr.Row():
|
203 |
+
predefined_section = gr.Radio(choices=['right compartments', 'left compartments', 'freight_body', 'custom'], label="Select Section", value='custom')
|
204 |
+
custom_texture_path = gr.Textbox(label="Path to Custom Texture Image")
|
205 |
+
|
206 |
+
with gr.Row(visible=True) as custom_controls:
|
207 |
+
x_min_slider = gr.Slider(minimum=x_min_range, maximum=x_max_range, step=0.01, label="X Min", value=x_min_range)
|
208 |
+
x_max_slider = gr.Slider(minimum=x_min_range, maximum=x_max_range, step=0.01, label="X Max", value=x_max_range)
|
209 |
+
|
210 |
+
y_min_slider = gr.Slider(minimum=y_min_range, maximum=y_max_range, step=0.01, label="Y Min", value=y_min_range)
|
211 |
+
y_max_slider = gr.Slider(minimum=y_min_range, maximum=y_max_range, step=0.01, label="Y Max", value=y_max_range)
|
212 |
+
|
213 |
+
z_min_slider = gr.Slider(minimum=z_min_range, maximum=z_max_range, step=0.01, label="Z Min", value=z_min_range)
|
214 |
+
z_max_slider = gr.Slider(minimum=z_min_range, maximum=z_max_range, step=0.01, label="Z Max", value=z_max_range)
|
215 |
+
|
216 |
+
# Toggle visibility of custom controls
|
217 |
+
def toggle_custom_controls(predefined_section):
|
218 |
+
return gr.update(visible=(predefined_section == 'custom'))
|
219 |
+
|
220 |
+
predefined_section.change(fn=toggle_custom_controls, inputs=[predefined_section], outputs=custom_controls)
|
221 |
+
|
222 |
+
# Update model dynamically
|
223 |
+
def update_model(predefined_section, x_min, x_max, y_min, y_max, z_min, z_max, custom_texture_path):
|
224 |
+
return visualize_dynamic_texture(predefined_section, x_min, x_max, y_min, y_max, z_min, z_max, custom_texture_path)
|
225 |
+
|
226 |
+
# Add event listeners for real-time updates when sliders or dropdown change
|
227 |
+
inputs = [predefined_section, x_min_slider, x_max_slider, y_min_slider, y_max_slider, z_min_slider, z_max_slider, custom_texture_path]
|
228 |
+
for input_component in inputs:
|
229 |
+
input_component.change(fn=update_model, inputs=inputs, outputs=modified_model)
|
230 |
+
|
231 |
+
app.launch()
|