ariankhalfani commited on
Commit
771b1be
·
verified ·
1 Parent(s): e3021c4

Delete app-ori.py

Browse files
Files changed (1) hide show
  1. app-ori.py +0 -286
app-ori.py DELETED
@@ -1,286 +0,0 @@
1
- import gradio as gr
2
- from ultralytics import YOLO
3
- import cv2
4
- import numpy as np
5
- from PIL import Image, ImageDraw, ImageFont
6
- import base64
7
- from io import BytesIO
8
- import tempfile
9
- import os
10
- from pathlib import Path
11
- import shutil
12
-
13
- # Load YOLOv8 model
14
- model = YOLO("best.pt")
15
-
16
- # Create directories if not present
17
- uploaded_folder = Path('Uploaded_Picture')
18
- predicted_folder = Path('Predicted_Picture')
19
- uploaded_folder.mkdir(parents=True, exist_ok=True)
20
- predicted_folder.mkdir(parents=True, exist_ok=True)
21
-
22
- # Path for HTML database file
23
- html_db_file = Path('patient_predictions.html')
24
-
25
- # Initialize HTML database file if not present
26
- if not html_db_file.exists():
27
- with open(html_db_file, 'w') as f:
28
- f.write("<html><body><h1>Patient Prediction Database</h1>")
29
-
30
- def predict_image(input_image, name, age, medical_record, sex):
31
- if input_image is None:
32
- return None, "Please Input The Image"
33
-
34
- # Convert Gradio input image (PIL Image) to numpy array
35
- image_np = np.array(input_image)
36
-
37
- # Ensure the image is in the correct format
38
- if len(image_np.shape) == 2: # grayscale to RGB
39
- image_np = cv2.cvtColor(image_np, cv2.COLOR_GRAY2RGB)
40
- elif image_np.shape[2] == 4: # RGBA to RGB
41
- image_np = cv2.cvtColor(image_np, cv2.COLOR_RGBA2RGB)
42
-
43
- # Perform prediction
44
- results = model(image_np)
45
-
46
- # Draw bounding boxes on the image
47
- image_with_boxes = image_np.copy()
48
- raw_predictions = []
49
-
50
- if results[0].boxes:
51
- # Sort the results by confidence and take the highest confidence one
52
- highest_confidence_result = max(results[0].boxes, key=lambda x: x.conf.item())
53
-
54
- # Determine the label based on the class index
55
- class_index = highest_confidence_result.cls.item()
56
- if class_index == 0:
57
- label = "Immature"
58
- color = (0, 255, 255) # Yellow for Immature
59
- elif class_index == 1:
60
- label = "Mature"
61
- color = (255, 0, 0) # Red for Mature
62
- else:
63
- label = "Normal"
64
- color = (0, 255, 0) # Green for Normal
65
-
66
- confidence = highest_confidence_result.conf.item()
67
- xmin, ymin, xmax, ymax = map(int, highest_confidence_result.xyxy[0])
68
-
69
- # Draw the bounding box
70
- cv2.rectangle(image_with_boxes, (xmin, ymin), (xmax, ymax), color, 2)
71
-
72
- # Enlarge font scale and thickness
73
- font_scale = 1.0
74
- thickness = 2
75
-
76
- # Calculate label background size
77
- (text_width, text_height), baseline = cv2.getTextSize(f'{label} {confidence:.2f}', cv2.FONT_HERSHEY_SIMPLEX, font_scale, thickness)
78
- cv2.rectangle(image_with_boxes, (xmin, ymin - text_height - baseline), (xmin + text_width, ymin), (0, 0, 0), cv2.FILLED)
79
-
80
- # Put the label text with black background
81
- cv2.putText(image_with_boxes, f'{label} {confidence:.2f}', (xmin, ymin - 10), cv2.FONT_HERSHEY_SIMPLEX, font_scale, (255, 255, 255), thickness)
82
-
83
- raw_predictions.append(f"Label: {label}, Confidence: {confidence:.2f}, Box: [{xmin}, {ymin}, {xmax}, {ymax}]")
84
-
85
- raw_predictions_str = "\n".join(raw_predictions)
86
-
87
- # Convert to PIL image for further processing
88
- pil_image_with_boxes = Image.fromarray(image_with_boxes)
89
-
90
- # Add text and watermark
91
- pil_image_with_boxes = add_text_and_watermark(pil_image_with_boxes, name, age, medical_record, sex, label)
92
-
93
- # Save images to directories
94
- image_name = f"{name}-{age}-{sex}-{medical_record}.png"
95
- input_image.save(uploaded_folder / image_name)
96
- pil_image_with_boxes.save(predicted_folder / image_name)
97
-
98
- # Convert the predicted image to base64 for embedding in HTML
99
- buffered = BytesIO()
100
- pil_image_with_boxes.save(buffered, format="PNG")
101
- predicted_image_base64 = base64.b64encode(buffered.getvalue()).decode()
102
-
103
- # Append the prediction to the HTML database
104
- append_patient_info_to_html(name, age, medical_record, sex, label, predicted_image_base64)
105
-
106
- return pil_image_with_boxes, raw_predictions_str
107
-
108
- # Function to add watermark
109
- def add_watermark(image):
110
- try:
111
- logo = Image.open('image-logo.png').convert("RGBA")
112
- image = image.convert("RGBA")
113
-
114
- # Resize logo
115
- basewidth = 100
116
- wpercent = (basewidth / float(logo.size[0]))
117
- hsize = int((float(wpercent) * logo.size[1]))
118
- logo = logo.resize((basewidth, hsize), Image.LANCZOS)
119
-
120
- # Position logo
121
- position = (image.width - logo.width - 10, image.height - logo.height - 10)
122
-
123
- # Composite image
124
- transparent = Image.new('RGBA', (image.width, image.height), (0, 0, 0, 0))
125
- transparent.paste(image, (0, 0))
126
- transparent.paste(logo, position, mask=logo)
127
-
128
- return transparent.convert("RGB")
129
- except Exception as e:
130
- print(f"Error adding watermark: {e}")
131
- return image
132
-
133
- # Function to add text and watermark
134
- def add_text_and_watermark(image, name, age, medical_record, sex, label):
135
- draw = ImageDraw.Draw(image)
136
-
137
- # Load a larger font (adjust the size as needed)
138
- font_size = 24 # Example font size
139
- try:
140
- font = ImageFont.truetype("font.ttf", size=font_size)
141
- except IOError:
142
- font = ImageFont.load_default()
143
- print("Error: cannot open resource, using default font.")
144
-
145
- text = f"Name: {name}, Age: {age}, Medical Record: {medical_record}, Sex: {sex}, Result: {label}"
146
-
147
- # Calculate text bounding box
148
- text_bbox = draw.textbbox((0, 0), text, font=font)
149
- text_width, text_height = text_bbox[2] - text_bbox[0], text_bbox[3] - text_bbox[1]
150
- text_x = 20
151
- text_y = 40
152
- padding = 10
153
-
154
- # Draw a filled rectangle for the background
155
- draw.rectangle(
156
- [text_x - padding, text_y - padding, text_x + text_width + padding, text_y + text_height + padding],
157
- fill="black"
158
- )
159
-
160
- # Draw text on top of the rectangle
161
- draw.text((text_x, text_y), text, fill=(255, 255, 255, 255), font=font)
162
-
163
- # Add watermark to the image
164
- image_with_watermark = add_watermark(image)
165
-
166
- return image_with_watermark
167
-
168
- def append_patient_info_to_html(name, age, medical_record, sex, result, predicted_image_base64):
169
- # Check if the HTML file is empty or if the table structure is missing
170
- if os.stat(html_db_file).st_size == 0: # Empty file, create the table structure
171
- with open(html_db_file, 'a') as f:
172
- f.write("""
173
- <html>
174
- <head><title>Patient Prediction Database</title></head>
175
- <body>
176
- <h1>Patient Prediction Database</h1>
177
- <table border="1" style="width:100%; border-collapse: collapse; text-align: center;">
178
- <thead>
179
- <tr>
180
- <th>Name</th>
181
- <th>Age</th>
182
- <th>Medical Record</th>
183
- <th>Sex</th>
184
- <th>Result</th>
185
- <th>Predicted Image</th>
186
- </tr>
187
- </thead>
188
- <tbody>
189
- """)
190
-
191
- # Check if this patient already exists to prevent duplicate entries
192
- # This can be improved by checking unique identifiers like `medical_record`
193
- # Assuming the uniqueness of the medical record
194
-
195
- html_entry = f"""
196
- <tr>
197
- <td>{name}</td>
198
- <td>{age}</td>
199
- <td>{medical_record}</td>
200
- <td>{sex}</td>
201
- <td>{result}</td>
202
- <td><img src="data:image/png;base64,{predicted_image_base64}" alt="Predicted Image" width="150"></td>
203
- </tr>
204
- """
205
-
206
- with open(html_db_file, 'a') as f:
207
- f.write(html_entry)
208
-
209
- # Ensure we only add the closing tags once
210
- if "</tbody></table></body></html>" not in open(html_db_file).read():
211
- with open(html_db_file, 'a') as f:
212
- f.write("""
213
- </tbody>
214
- </table>
215
- </body>
216
- </html>
217
- """)
218
-
219
- return str(html_db_file) # Return the HTML file path for download
220
-
221
- # Function to download the folders
222
- def download_folder(folder):
223
- zip_path = os.path.join(tempfile.gettempdir(), f"{folder}.zip")
224
-
225
- # Zip the folder
226
- shutil.make_archive(zip_path.replace('.zip', ''), 'zip', folder)
227
-
228
- return zip_path
229
-
230
- # Gradio Interface
231
- def interface(name, age, medical_record, sex, input_image):
232
- if input_image is None:
233
- return None, "Please upload an image.", None
234
-
235
- output_image, raw_result = predict_image(input_image, name, age, medical_record, sex)
236
-
237
- # Return the current state of the HTML file with all predictions
238
- return output_image, raw_result, str(html_db_file)
239
-
240
- # Download Functions
241
- def download_predicted_folder():
242
- return download_folder(predicted_folder)
243
-
244
- def download_uploaded_folder():
245
- return download_folder(uploaded_folder)
246
-
247
- # Launch Gradio Interface
248
-
249
- with gr.Blocks() as demo:
250
- with gr.Column():
251
- gr.Markdown("# Cataract Detection System")
252
- gr.Markdown("Upload an image to detect cataract and add patient details.")
253
- gr.Markdown("This application uses YOLOv8 with mAP=0.981")
254
-
255
- with gr.Column():
256
- name = gr.Textbox(label="Name")
257
- age = gr.Number(label="Age")
258
- medical_record = gr.Number(label="Medical Record")
259
- sex = gr.Radio(["Male", "Female"], label="Sex")
260
- input_image = gr.Image(type="pil", label="Upload an Image", image_mode="RGB")
261
-
262
- with gr.Column():
263
- submit_btn = gr.Button("Submit")
264
- output_image = gr.Image(type="pil", label="Predicted Image")
265
-
266
- with gr.Row():
267
- raw_result = gr.Textbox(label="Prediction Result")
268
-
269
- with gr.Row():
270
- download_html_btn = gr.Button("Download Patient Information (HTML)")
271
- download_uploaded_btn = gr.Button("Download Uploaded Images")
272
- download_predicted_btn = gr.Button("Download Predicted Images")
273
-
274
- # Add file download output components for the uploaded and predicted images
275
- patient_info_file = gr.File(label="Patient Information HTML File")
276
- uploaded_folder_file = gr.File(label="Uploaded Images Zip File")
277
- predicted_folder_file = gr.File(label="Predicted Images Zip File")
278
-
279
- # Connect functions with components
280
- submit_btn.click(fn=interface, inputs=[name, age, medical_record, sex, input_image], outputs=[output_image, raw_result])
281
- download_html_btn.click(fn=append_patient_info_to_html, inputs=[name, age, medical_record, sex, raw_result], outputs=patient_info_file)
282
- download_uploaded_btn.click(fn=download_uploaded_folder, outputs=uploaded_folder_file)
283
- download_predicted_btn.click(fn=download_predicted_folder, outputs=predicted_folder_file)
284
-
285
- # Launch Gradio app
286
- demo.launch()