sparsh007 commited on
Commit
1baca7f
·
verified ·
1 Parent(s): ac1f121

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +188 -0
app.py ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import gradio as gr
3
+ from PIL import Image
4
+ import os
5
+ import zipfile
6
+
7
+ # Load the YOLOv5 model (ensure the path is correct)
8
+ model = torch.hub.load(
9
+ 'ultralytics/yolov5', 'custom', path='best-3.pt'
10
+ )
11
+
12
+ # Global variables to store images and labels for carousel functionality
13
+ processed_images = []
14
+ label_contents = []
15
+ processed_image_paths = []
16
+
17
+ # Temporary folder for saving processed files
18
+ TEMP_DIR = "temp_processed"
19
+ os.makedirs(TEMP_DIR, exist_ok=True)
20
+
21
+ # Function to process all uploaded images
22
+ def process_images(files):
23
+ global processed_images, label_contents, processed_image_paths
24
+ processed_images = []
25
+ label_contents = []
26
+ processed_image_paths = []
27
+
28
+ # Clear the temp directory
29
+ for f in os.listdir(TEMP_DIR):
30
+ os.remove(os.path.join(TEMP_DIR, f))
31
+
32
+ for i, file_path in enumerate(files):
33
+ # Open the image using the file path
34
+ img = Image.open(file_path)
35
+
36
+ # Run inference
37
+ results = model(img)
38
+
39
+ # Convert results to Image format for display
40
+ results.render()
41
+ if hasattr(results, 'ims'):
42
+ output_image = Image.fromarray(results.ims[0])
43
+ else:
44
+ output_image = Image.fromarray(results.imgs[0])
45
+
46
+ # Save the processed image and its labels
47
+ processed_images.append(output_image)
48
+
49
+ # Generate YOLO-format labels as a string
50
+ label_content = ""
51
+ for *box, conf, cls in results.xywh[0]:
52
+ class_id = int(cls)
53
+ x_center, y_center, width, height = box
54
+ label_content += f"{class_id} {x_center} {y_center} {width} {height}\n"
55
+ label_contents.append(label_content)
56
+
57
+ # Save the image to the temp folder
58
+ image_path = os.path.join(TEMP_DIR, f"processed_image_{i}.png")
59
+ output_image.save(image_path)
60
+ processed_image_paths.append(image_path)
61
+
62
+ # Save the label content to a text file
63
+ label_filename = f"annotation_{i}.txt"
64
+ label_path = os.path.join(TEMP_DIR, label_filename)
65
+ with open(label_path, "w") as label_file:
66
+ label_file.write(label_content)
67
+
68
+ # Return the first image and its labels
69
+ if processed_images:
70
+ return processed_images[0], label_contents[0], 0 # Start with index 0
71
+ else:
72
+ return None, "No images found.", 0
73
+
74
+ # Function to create and return the path to the ZIP file for download
75
+ def create_zip():
76
+ zip_filename = "processed_images_annotations.zip"
77
+ zip_path = os.path.join(TEMP_DIR, zip_filename)
78
+
79
+ # Remove existing ZIP file if it exists
80
+ if os.path.exists(zip_path):
81
+ os.remove(zip_path)
82
+
83
+ with zipfile.ZipFile(zip_path, 'w') as z:
84
+ # Add images and labels to the ZIP file
85
+ for image_path in processed_image_paths:
86
+ z.write(image_path, os.path.basename(image_path))
87
+ # Get index from image filename
88
+ image_filename = os.path.basename(image_path)
89
+ base_name, ext = os.path.splitext(image_filename)
90
+ index = base_name.split('_')[-1]
91
+ # Construct label filename
92
+ label_filename = f"annotation_{index}.txt"
93
+ label_path = os.path.join(TEMP_DIR, label_filename)
94
+ z.write(label_path, label_filename)
95
+
96
+ return zip_path # Return the file path as a string
97
+
98
+ # Function to navigate through images
99
+ def next_image(index):
100
+ global processed_images, label_contents
101
+ if processed_images:
102
+ index = (index + 1) % len(processed_images)
103
+ return processed_images[index], label_contents[index], index
104
+ else:
105
+ return None, "No images processed.", index
106
+
107
+ def prev_image(index):
108
+ global processed_images, label_contents
109
+ if processed_images:
110
+ index = (index - 1) % len(processed_images)
111
+ return processed_images[index], label_contents[index], index
112
+ else:
113
+ return None, "No images processed.", index
114
+
115
+ # Gradio interface
116
+ with gr.Blocks() as interface:
117
+ # Welcome message and general instructions
118
+ gr.Markdown("## Welcome to the Construction Image Processing App!")
119
+ gr.Markdown("""
120
+ This app allows you to upload multiple construction-related images, process them using a custom YOLO model, and download the processed images along with their YOLO-format annotations.
121
+
122
+ ### How to Use:
123
+ 1. **Upload**: Upload multiple images for processing.
124
+ 2. **View**: Navigate through the processed images using the 'Previous' and 'Next' buttons.
125
+ 3. **Download**: Download all processed images and annotations as a ZIP file.
126
+
127
+ Follow the instructions below to get started!
128
+ """)
129
+
130
+ # Step 1: Upload Instructions
131
+ gr.Markdown("### Step 1: Upload Your Images")
132
+ gr.Markdown("Upload multiple construction-related image files that you want to process using the model. The supported file types are JPEG and PNG.")
133
+
134
+ # Multiple file input and display area
135
+ file_input = gr.Files(label="Upload multiple image files", type="filepath")
136
+ image_display = gr.Image(label="Processed Image")
137
+ label_display = gr.Textbox(label="YOLO Annotation for the Processed Image")
138
+
139
+ # Step 2: Navigation Instructions
140
+ gr.Markdown("### Step 2: View Your Processed Images")
141
+ gr.Markdown("After processing, use the 'Previous Image' and 'Next Image' buttons to navigate through the processed images and view their annotations.")
142
+
143
+ # Buttons for carousel navigation
144
+ prev_button = gr.Button("Previous Image")
145
+ next_button = gr.Button("Next Image")
146
+
147
+ # Hidden state to store current index
148
+ current_index = gr.State(0)
149
+
150
+ # Step 3: Download Instructions
151
+ gr.Markdown("### Step 3: Download All Processed Images and Annotations")
152
+ gr.Markdown("Click the 'Prepare and Download All' button to download a ZIP file containing all processed images and YOLO annotations.")
153
+
154
+ # Button to download all processed images and annotations as a ZIP file
155
+ download_button = gr.Button("Prepare and Download All")
156
+ download_file = gr.File()
157
+
158
+ # Define functionality when files are uploaded
159
+ file_input.change(
160
+ process_images,
161
+ inputs=file_input,
162
+ outputs=[image_display, label_display, current_index]
163
+ )
164
+
165
+ # Define functionality for next and previous buttons
166
+ next_button.click(
167
+ next_image,
168
+ inputs=current_index,
169
+ outputs=[image_display, label_display, current_index]
170
+ )
171
+ prev_button.click(
172
+ prev_image,
173
+ inputs=current_index,
174
+ outputs=[image_display, label_display, current_index]
175
+ )
176
+
177
+ # Define functionality for the download button to zip the files and allow download
178
+ def prepare_download():
179
+ zip_path = create_zip()
180
+ return zip_path
181
+
182
+ download_button.click(
183
+ prepare_download,
184
+ outputs=download_file
185
+ )
186
+
187
+ # Launch the interface
188
+ interface.launch(share=True)