ariankhalfani commited on
Commit
99de52c
1 Parent(s): 2c1e728

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +41 -84
app.py CHANGED
@@ -151,18 +151,15 @@ def submit_result(name, patient_id, input_image, predicted_image, result):
151
  conn = sqlite3.connect('results.db')
152
  c = conn.cursor()
153
 
154
- # Encode input image
155
  input_image_np = np.array(input_image)
156
  _, input_buffer = cv2.imencode('.png', cv2.cvtColor(input_image_np, cv2.COLOR_RGB2BGR))
157
  input_image_bytes = input_buffer.tobytes()
158
 
159
- # Encode predicted image
160
  predicted_image_np = np.array(predicted_image)
161
  predicted_image_rgb = cv2.cvtColor(predicted_image_np, cv2.COLOR_RGB2BGR) # Ensure correct color conversion
162
  _, predicted_buffer = cv2.imencode('.png', predicted_image_rgb)
163
  predicted_image_bytes = predicted_buffer.tobytes()
164
 
165
- # Insert into database
166
  c.execute("INSERT INTO results (name, patient_id, input_image, predicted_image, result) VALUES (?, ?, ?, ?, ?)",
167
  (name, patient_id, input_image_bytes, predicted_image_bytes, result))
168
  conn.commit()
@@ -173,12 +170,21 @@ def submit_result(name, patient_id, input_image, predicted_image, result):
173
  def view_database():
174
  conn = sqlite3.connect('results.db')
175
  c = conn.cursor()
176
- c.execute("SELECT name, patient_id, result FROM results")
177
  rows = c.fetchall()
178
  conn.close()
179
 
180
  # Convert to pandas DataFrame for better display in Gradio
181
- df = pd.DataFrame(rows, columns=["Name", "Patient ID", "Result"])
 
 
 
 
 
 
 
 
 
182
 
183
  return df
184
 
@@ -190,93 +196,44 @@ def download_file(choice):
190
  elif choice == "Database (.html)":
191
  conn = sqlite3.connect('results.db')
192
  c = conn.cursor()
193
- c.execute("SELECT * FROM results")
194
  rows = c.fetchall()
195
  conn.close()
196
-
197
- df = pd.DataFrame(rows, columns=["ID", "Name", "Patient ID", "Input Image", "Predicted Image", "Result"])
198
-
199
- # Convert DataFrame to HTML
200
- with tempfile.NamedTemporaryFile(delete=False, suffix='.html') as temp_file:
201
- df.to_html(temp_file.name)
202
- return temp_file.name
203
  else:
204
- conn = sqlite3.connect('results.db')
205
- c = conn.cursor()
206
- c.execute("SELECT predicted_image FROM results ORDER BY id DESC LIMIT 1")
207
- row = c.fetchone()
208
- conn.close()
209
- if row:
210
- image_bytes = row[0]
211
- with tempfile.NamedTemporaryFile(delete=False, suffix='.png') as temp_file:
212
- temp_file.write(image_bytes)
213
- temp_file.flush() # Ensure all data is written before closing
214
- return temp_file.name
215
- else:
216
- raise FileNotFoundError("No images found in the database.")
217
 
218
  # Initialize the database
219
  init_db()
220
 
221
- # Gradio Interface
222
- def interface(name, patient_id, input_image):
223
- if input_image is None:
224
- return "Please upload an image."
225
-
226
- output_image, raw_result = predict_image(input_image, name, patient_id)
227
- submit_status = submit_result(name, patient_id, input_image, output_image, raw_result)
228
-
229
- return output_image, raw_result, submit_status
230
-
231
- # View Database Function
232
- def view_db_interface():
233
- df = view_database()
234
- return df
235
-
236
- # Download Function
237
- def download_interface(choice):
238
- try:
239
- file_path = download_file(choice)
240
- with open(file_path, "rb") as file:
241
- return file.read(), file_path.split('/')[-1]
242
- except FileNotFoundError as e:
243
- return str(e), None
244
-
245
- # Gradio Blocks
246
  with gr.Blocks() as demo:
247
- with gr.Column():
248
- gr.Markdown("# Cataract Detection System")
249
- gr.Markdown("Upload an image to detect cataract and add patient details.")
250
- gr.Image("PR_curve.png", label="Model PR Curve")
251
- gr.Markdown("This application uses YOLOv8 with mAP=0.981")
 
 
 
 
 
 
 
252
 
253
- with gr.Column():
254
- name = gr.Textbox(label="Name")
255
- patient_id = gr.Textbox(label="Patient ID")
256
- input_image = gr.Image(type="pil", label="Upload an Image", image_mode="RGB")
257
-
258
- with gr.Column():
259
- submit_btn = gr.Button("Submit")
260
- output_image = gr.Image(type="pil", label="Predicted Image")
261
-
262
- with gr.Row():
263
- raw_result = gr.Textbox(label="Raw Result", lines=5)
264
- submit_status = gr.Textbox(label="Submission Status")
265
-
266
- submit_btn.click(fn=interface, inputs=[name, patient_id, input_image], outputs=[output_image, raw_result, submit_status])
267
-
268
- with gr.Column():
269
- view_db_btn = gr.Button("View Database")
270
- db_output = gr.Dataframe(label="Database Records")
271
-
272
- view_db_btn.click(fn=view_db_interface, inputs=[], outputs=[db_output])
273
-
274
- with gr.Column():
275
- download_choice = gr.Radio(["Database (.db)", "Predicted Image (.png)", "Database (.html)"], label="Choose the file to download:")
276
- download_btn = gr.Button("Download")
277
- download_output = gr.File(label="Download File")
278
-
279
- download_btn.click(fn=download_interface, inputs=[download_choice], outputs=[download_output])
280
 
281
- # Launch the Gradio app
282
  demo.launch()
 
151
  conn = sqlite3.connect('results.db')
152
  c = conn.cursor()
153
 
 
154
  input_image_np = np.array(input_image)
155
  _, input_buffer = cv2.imencode('.png', cv2.cvtColor(input_image_np, cv2.COLOR_RGB2BGR))
156
  input_image_bytes = input_buffer.tobytes()
157
 
 
158
  predicted_image_np = np.array(predicted_image)
159
  predicted_image_rgb = cv2.cvtColor(predicted_image_np, cv2.COLOR_RGB2BGR) # Ensure correct color conversion
160
  _, predicted_buffer = cv2.imencode('.png', predicted_image_rgb)
161
  predicted_image_bytes = predicted_buffer.tobytes()
162
 
 
163
  c.execute("INSERT INTO results (name, patient_id, input_image, predicted_image, result) VALUES (?, ?, ?, ?, ?)",
164
  (name, patient_id, input_image_bytes, predicted_image_bytes, result))
165
  conn.commit()
 
170
  def view_database():
171
  conn = sqlite3.connect('results.db')
172
  c = conn.cursor()
173
+ c.execute("SELECT name, patient_id, input_image, predicted_image, result FROM results")
174
  rows = c.fetchall()
175
  conn.close()
176
 
177
  # Convert to pandas DataFrame for better display in Gradio
178
+ df = pd.DataFrame(rows, columns=["Name", "Patient ID", "Input Image", "Predicted Image", "Raw Result"])
179
+
180
+ # Decode images from BLOB and convert to displayable format
181
+ def decode_image(image_blob):
182
+ image_np = np.frombuffer(image_blob, dtype=np.uint8)
183
+ image = cv2.imdecode(image_np, cv2.IMREAD_COLOR)
184
+ return image
185
+
186
+ df["Input Image"] = df["Input Image"].apply(lambda x: decode_image(x))
187
+ df["Predicted Image"] = df["Predicted Image"].apply(lambda x: decode_image(x))
188
 
189
  return df
190
 
 
196
  elif choice == "Database (.html)":
197
  conn = sqlite3.connect('results.db')
198
  c = conn.cursor()
199
+ c.execute("SELECT name, patient_id, input_image, predicted_image, result FROM results")
200
  rows = c.fetchall()
201
  conn.close()
202
+ df = pd.DataFrame(rows, columns=["Name", "Patient ID", "Input Image", "Predicted Image", "Raw Result"])
203
+ html = df.to_html()
204
+ with tempfile.NamedTemporaryFile(delete=False, suffix='.html') as f:
205
+ f.write(html.encode())
206
+ return f.name
 
 
207
  else:
208
+ # Handle other download options if necessary
209
+ pass
 
 
 
 
 
 
 
 
 
 
 
210
 
211
  # Initialize the database
212
  init_db()
213
 
214
+ # Define the Gradio interface
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
215
  with gr.Blocks() as demo:
216
+ with gr.Tab("YOLOv8 Inference"):
217
+ with gr.Row():
218
+ input_image = gr.Image(label="Input Image", type="pil")
219
+ with gr.Row():
220
+ name = gr.Textbox(label="Patient Name")
221
+ patient_id = gr.Textbox(label="Patient ID")
222
+ with gr.Row():
223
+ submit_button = gr.Button("Submit")
224
+ predicted_image = gr.Image(label="Predicted Image")
225
+ with gr.Row():
226
+ result = gr.Textbox(label="Raw Result", lines=5)
227
+ submit_button.click(predict_image, inputs=[input_image, name, patient_id], outputs=[predicted_image, result])
228
 
229
+ with gr.Tab("View Database"):
230
+ view_button = gr.Button("View Database")
231
+ database_output = gr.DataFrame(label="Database Records")
232
+ view_button.click(view_database, outputs=database_output)
233
+
234
+ download_choice = gr.Radio(["Database (.db)", "Database (.html)", "Predicted Image (.png)"], label="Choose the file to download:")
235
+ download_button = gr.Button("Download")
236
+ download_button.click(download_file, inputs=download_choice, outputs=gr.File())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
237
 
238
+ # Launch the interface
239
  demo.launch()