File size: 13,019 Bytes
0fe504c
820626f
 
0fe504c
 
 
820626f
 
0fe504c
820626f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0fe504c
 
820626f
0fe504c
 
820626f
0fe504c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
820626f
 
0fe504c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
820626f
0fe504c
820626f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
451d32c
820626f
 
 
 
 
 
451d32c
820626f
 
 
 
 
 
 
 
451d32c
820626f
 
 
 
 
 
 
 
451d32c
820626f
 
 
451d32c
820626f
 
 
 
 
451d32c
820626f
 
 
 
 
 
451d32c
820626f
 
 
451d32c
820626f
 
 
 
 
451d32c
820626f
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
import gradio as gr
import replicate
import openai
import trimesh
import numpy as np
from PIL import Image
import requests
import io
import tempfile
import random
import os

# Set API tokens
os.environ["REPLICATE_API_TOKEN"] = "r8_Pc64F8EPrJ6PiNIIvaBUZcOGmiLC3Jp1gELYB"
OPENAI_API_KEY = "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"

# Initialize the Replicate client
rep_client = replicate.Client()

# Material defects structure
material_defects = {
    "Steel": ["Rust and Corrosion", "Pitting Corrosion", "Surface Cracks", "Wear Patterns", "Spalling", "Scaling"],
    "Glass": ["Cracks", "Chips", "Scratches", "Frosting"],
    "Aluminum": ["Corrosion", "Scratches and Dents", "Anodizing Wear"],
    "Wood": ["Rot and Decay", "Cracks and Splits", "Weathering"],
    "Plastics and Polymers": ["Cracking and Crazing", "UV Degradation", "Heat Distortion"],
    "Rubber": ["Cracking", "Hardening and Brittleness", "Surface Wear"],
    "Composite Materials": ["Delamination", "Impact Damage", "Fiber Wearing"],
    "Ceramics": ["Crackling", "Chipping and Pitting", "Glaze Deterioration"]
}

# Function to ask rail defect question
def ask_rail_defect_question(question, model_name='ft:gpt-3.5-turbo-0125:personal::99NsSAeQ'):
    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."
    response = openai.ChatCompletion.create(
        model=model_name,
        messages=[
            {"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."},
            {"role": "user", "content": structured_prompt}
        ],
    )
    refined_description = response.choices[0].message['content']
    return refined_description.strip()

# Function to generate images from prompts
def generate_images(prompt):
    prediction = rep_client.predictions.create(
        version="ac732df83cea7fff18b8472768c88ad041fa750ff7682a21affe81863cbe77e",
        input={"prompt": prompt}
    )
    prediction.wait()
    if prediction.status == "succeeded":
        image_url = prediction.output[0]
        response = requests.get(image_url)
        image = Image.open(io.BytesIO(response.content))
        return image
    return "Failed to generate texture image"

# Function to create data URL from PIL image
def image_to_data_url(pil_image):
    buffered = io.BytesIO()
    pil_image.save(buffered, format="JPEG")
    base64_image = base64.b64encode(buffered.getvalue()).decode('utf-8')
    return f"data:image/jpeg;base64,{base64_image}"

# Function to inpaint images
def inpaint_texture(image, prompt):
    if isinstance(image, np.ndarray):
        image = Image.fromarray(image)
    
    image_data_url = image_to_data_url(image)
       
    input = {
      "image": image_data_url,
      "prompt": prompt,
      "scheduler": "K_EULER_ANCESTRAL",
      "num_outputs": 1,
      "guidance_scale": 7.5,
      "num_inference_steps": 100,
      "image_guidance_scale": 1.5
    }

    prediction = rep_client.predictions.create(
        version="30c1d0b916a6f8efce20493f5d61ee27491ab2a60437c13c588468b9810ec23f",
        input = input
    )
    prediction.wait()
    if prediction.status == "succeeded":
        image_url = prediction.output[0]
        response = requests.get(image_url)
        image = Image.open(io.BytesIO(response.content))
        return image
    return "Failed to generate inpainted texture image"

# Function to update defect options
def update_defect_options(selected_material):
    return gr.update(value='', choices=material_defects[selected_material])

# Function to visualize texture based on selection criteria
def visualize_dynamic_texture(image, predefined_section, x_min, x_max, y_min, y_max, z_min, z_max):
    # Load the original mesh
    mesh = trimesh.load('train.glb', force='mesh')
    custom_texture = image.convert('RGB')

    # Predefined sections
    if predefined_section == 'right compartments':
        selected_indices = np.where(mesh.vertices[:, 0] > (train_bounds[0][0] + train_bounds[1][0]) / 2)[0]
    elif predefined_section == 'left compartments':
        selected_indices = np.where(mesh.vertices[:, 0] <= (train_bounds[0][0] + train_bounds[1][0]) / 2)[0]
    elif predefined_section == 'freight_body':
        selected_indices = np.where((mesh.vertices[:, 0] >= train_bounds[0][0]) & (mesh.vertices[:, 0] <= train_bounds[1][0]) &
                                    (mesh.vertices[:, 2] <= (train_bounds[0][2] + train_bounds[1][2]) / 2))[0]
    elif predefined_section == 'custom':
        # Use custom sliders for custom section
        selected_indices = np.where((mesh.vertices[:, 0] >= x_min) & (mesh.vertices[:, 0] <= x_max) &
                                    (mesh.vertices[:, 1] >= y_min) & (mesh.vertices[:, 1] <= y_max) &
                                    (mesh.vertices[:, 2] >= z_min) & (mesh.vertices[:, 2] <= z_max))[0]
    else:
        selected_indices = np.array([])

    # Initialize UV mapping
    uv = np.random.rand(len(mesh.vertices), 2)
    new_uv = np.zeros_like(uv)
    new_uv[selected_indices, :] = uv[selected_indices, :]

    # Create material and apply the new texture
    material = trimesh.visual.texture.SimpleMaterial(image=custom_texture)
    color_visuals = trimesh.visual.TextureVisuals(uv=new_uv, image=custom_texture, material=material)
    textured_mesh = trimesh.Trimesh(vertices=mesh.vertices, faces=mesh.faces, visual=color_visuals, validate=True, process=False)

    # Save the mesh to a temporary file
    temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.glb')
    textured_mesh.export(temp_file.name, file_type='glb')
    temp_file.close()
    return temp_file.name

# Load train model to establish bounding box ranges
train_model = trimesh.load('train.glb', force='mesh')
train_bounds = train_model.bounds

# Get slider ranges based on train model bounds
x_min_range, x_max_range = train_bounds[0][0], train_bounds[1][0]
y_min_range, y_max_range = train_bounds[0][1], train_bounds[1][1]
z_min_range, z_max_range = train_bounds[0][2], train_bounds[1][2]

# Gradio app interface setup
with gr.Blocks() as app:
    with gr.Tabs():
        with gr.Tab("3D Defect Simulator"):
            with gr.Tabs():
                with gr.Tab("Predefined Defect Texture"):
                    with gr.Row():
                        material_input = gr.Dropdown(choices=list(material_defects.keys()), label="Select Material")
                        defect_input = gr.Dropdown(choices=[], label="Select Defect Type")
                        generate_button = gr.Button("Generate Texture")
                    image_output = gr.Image(label="Generated Texture")
                    model_output = gr.Model3D(label="3D Model with Applied Texture")

                    material_input.change(fn=update_defect_options, inputs=[material_input], outputs=[defect_input])
                    generate_button.click(
                        fn=lambda material, defect: generate_images(ask_rail_defect_question(f"Describe the texture of {defect} on {material}")),
                        inputs=[material_input, defect_input],
                        outputs=[image_output]
                    )

                    def apply_texture_predefined(image):
                        return visualize_dynamic_texture(image, 'right compartments', x_min_range, x_max_range, y_min_range, y_max_range, z_min_range, z_max_range)
                    
                    generate_button.click(
                        fn=apply_texture_predefined,
                        inputs=[image_output],
                        outputs=[model_output]
                    )

                with gr.Tab("Custom Defect Texture"):
                    with gr.Row():
                        custom_prompt_input = gr.Textbox(label="Enter Custom Prompt for Texture", placeholder="Describe any texture detail you need.")
                        refine_button = gr.Button("Refine Prompt")
                    refined_prompt_output = gr.Textbox(label="Refined Prompt", placeholder="This will show the refined prompt.")

                    with gr.Row():
                        generate_button = gr.Button("Generate Texture")
                    custom_image_output = gr.Image(label="Generated Texture")
                    model_output_custom = gr.Model3D(label="3D Model with Applied Texture")

                    # Refine the input prompt
                    refine_button.click(
                        fn=lambda prompt: ask_rail_defect_question(prompt),
                        inputs=[custom_prompt_input],
                        outputs=[refined_prompt_output]
                    )

                    # Use the refined prompt to generate the texture image
                    generate_button.click(
                        fn=lambda prompt: generate_images(prompt),
                        inputs=[refined_prompt_output],
                        outputs=[custom_image_output]
                    )

                    def apply_texture_custom(image):
                        return visualize_dynamic_texture(image, 'custom', x_min_range, x_max_range, y_min_range, y_max_range, z_min_range, z_max_range)
                    
                    generate_button.click(
                        fn=apply_texture_custom,
                        inputs=[custom_image_output],
                        outputs=[model_output_custom]
                    )

                with gr.Tab("Inpaint Defect Texture"):
                    with gr.Row():
                        image_input = gr.Image(label="Upload Image for Inpainting")
                        inpaint_prompt_input = gr.Textbox(label="Enter Prompt for Texture Inpainting")
                        inpaint_button = gr.Button("Generate Inpainted Texture")
                    inpaint_image_output = gr.Image(label="Generated Inpainted Texture")
                    model_output_inpaint = gr.Model3D(label="3D Model with Applied Texture")

                    # Use the images and prompt to generate the inpainted texture image
                    inpaint_button.click(
                        fn=lambda img, prompt: inpaint_texture(img, prompt),
                        inputs=[image_input, inpaint_prompt_input],
                        outputs=[inpaint_image_output]
                    )

                    def apply_texture_inpaint(image):
                        return visualize_dynamic_texture(image, 'right compartments', x_min_range, x_max_range, y_min_range, y_max_range, z_min_range, z_max_range)
                    
                    inpaint_button.click(
                        fn=apply_texture_inpaint,
                        inputs=[inpaint_image_output],
                        outputs=[model_output_inpaint]
                    )

        with gr.Tab("2D Defect Simulator"):
            with gr.Tabs():
                with gr.Tab("Current Defects"):
                    with gr.Row():
                        prompt_input = gr.Dropdown(choices=predefined_defects, label="Select a prompt")
                        number_input_dropdown = gr.Number(label="Number of images to generate", value=1, minimum=1, maximum=10)
                        submit_button_dropdown = gr.Button("Generate")
                    image_outputs_dropdown = gr.Gallery()

                    def on_submit_click_dropdown(prompt, number_of_images):
                        images = process_railway_defects(prompt, number_of_images)
                        return images

                    submit_button_dropdown.click(
                        fn=on_submit_click_dropdown,
                        inputs=[prompt_input, number_input_dropdown],
                        outputs=image_outputs_dropdown
                    )

                with gr.Tab("Custom Defect"):
                    with gr.Row():
                        custom_prompt_input = gr.Textbox(label="Custom Defect")
                        number_input_custom = gr.Number(label="Number of images to generate", value=1, minimum=1, maximum=10)
                        submit_button_custom = gr.Button("Generate")
                    image_outputs_custom = gr.Gallery()

                    def on_submit_click_custom(custom_prompt, number_of_images):
                        images = process_railway_defects(custom_prompt, number_of_images)
                        return images

                    submit_button_custom.click(
                        fn=on_submit_click_custom,
                        inputs=[custom_prompt_input, number_input_custom],
                        outputs=image_outputs_custom
                    )

app.launch()