vikram0B commited on
Commit
b506a99
·
verified ·
1 Parent(s): f963fc5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +66 -25
app.py CHANGED
@@ -2,54 +2,95 @@ import gradio as gr
2
  import tensorflow as tf
3
  import numpy as np
4
  from PIL import Image
5
- import google.generativeai as genai
6
  import os
7
  import markdown2
8
 
9
- # Load TensorFlow model
10
- model = tf.saved_model.load('model')
11
- labels = ['cataract', 'diabetic_retinopathy', 'glaucoma', 'normal']
12
 
13
  # Configure Gemini API
14
- genai.configure(api_key=os.getenv("AIzaSyClC-moPGp4ONPUQ0FnNjMPh035AN7oqtY"))
15
-
16
- # Generate AI-based explanation for the predicted disease
17
- def get_disease_detail(disease):
18
- prompt = (
19
- "Create a text congratulating on healthy eyes with tips to keep them healthy."
20
- if disease == "normal" else
21
- f"Diagnosis: {disease}\n\n"
22
- f"What is {disease}?\nCauses and suggestions to prevent {disease}."
23
- )
 
 
 
 
 
 
 
 
 
 
 
24
  try:
25
  response = genai.GenerativeModel("gemini-1.5-flash").generate_content(prompt)
26
- return markdown2.markdown(response.text.strip() if response and response.text else "No response.")
27
  except Exception as e:
28
  return f"Error: {e}"
29
 
30
- # Process and predict uploaded image
31
  def predict_image(image):
32
- img_array = np.expand_dims(np.array(image.resize((224, 224))).astype(np.float32) / 255.0, axis=0)
33
- predictions = model.signatures['serving_default'](tf.convert_to_tensor(img_array, dtype=tf.float32))['output_0']
 
 
 
 
 
 
 
 
34
 
35
- top_label = labels[np.argmax(predictions.numpy())]
36
  explanation = get_disease_detail(top_label)
37
 
38
- return {top_label: predictions.numpy().max()}, explanation
39
 
40
  # Example images
41
- example_images = [[f"exp_eye_images/{img}"] for img in ["0_right_h.png", "03fd50da928d_dr.png", "108_right_h.png", "1062_right_c.png", "1084_right_c.png", "image_1002_g.jpg"]]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
  # Gradio Interface
44
  interface = gr.Interface(
45
  fn=predict_image,
46
  inputs=gr.Image(type="pil"),
47
- outputs=[gr.Label(num_top_classes=1, label="Prediction"), gr.HTML(label="Explanation", elem_classes=["scrollable-html"])],
 
 
 
48
  examples=example_images,
49
- title="DR Predictor",
50
- description=("Upload an eye fundus image, and the model predicts the condition."),
 
 
 
51
  allow_flagging="never",
52
- css=".scrollable-html {height: 206px; overflow-y: auto; border: 1px solid #ccc; padding: 10px; box-sizing: border-box;}"
53
  )
54
 
55
  interface.launch(share=True)
 
2
  import tensorflow as tf
3
  import numpy as np
4
  from PIL import Image
5
+ import google.generativeai as genai
6
  import os
7
  import markdown2
8
 
9
+ # Load the TensorFlow model
10
+ model_path = 'model'
11
+ model = tf.saved_model.load(model_path)
12
 
13
  # Configure Gemini API
14
+ api_key = os.getenv("GOOGLE_API_KEY")
15
+ api_key = "AIzaSyClC-moPGp4ONPUQ0FnNjMPh035AN7oqtY"
16
+
17
+ genai.configure(api_key=api_key)
18
+
19
+
20
+ labels = ['cataract', 'diabetic_retinopathy', 'glaucoma', 'normal']
21
+
22
+ def get_disease_detail(disease_name):
23
+ if disease_name == "normal":
24
+ prompt = (
25
+ "Create a text that congratulates having healthy eyes and gives bullet point tips to keep eyes healthy."
26
+ )
27
+ else:
28
+ prompt = (
29
+ f"Diagnosis: {disease_name}\n\n"
30
+ "What is it?\n(Description about {disease_name})\n\n"
31
+ "What causes it?\n(Explain what causes {disease_name})\n\n"
32
+ "Suggestion\n(Suggestion to user)\n\n"
33
+ "Reminder: Always seek professional help, such as a doctor."
34
+ )
35
  try:
36
  response = genai.GenerativeModel("gemini-1.5-flash").generate_content(prompt)
37
+ return markdown2.markdown(response.text.strip())
38
  except Exception as e:
39
  return f"Error: {e}"
40
 
 
41
  def predict_image(image):
42
+ image_resized = image.resize((224, 224))
43
+ image_array = np.array(image_resized).astype(np.float32) / 255.0
44
+ image_array = np.expand_dims(image_array, axis=0)
45
+
46
+ predictions = model.signatures['serving_default'](tf.convert_to_tensor(image_array, dtype=tf.float32))['output_0']
47
+
48
+ # Highest prediction
49
+ top_index = np.argmax(predictions.numpy(), axis=1)[0]
50
+ top_label = labels[top_index]
51
+ top_probability = predictions.numpy()[0][top_index]
52
 
 
53
  explanation = get_disease_detail(top_label)
54
 
55
+ return {top_label: top_probability}, explanation
56
 
57
  # Example images
58
+ example_images = [
59
+ ["exp_eye_images/0_right_h.png"],
60
+ ["exp_eye_images/03fd50da928d_dr.png"],
61
+ ["exp_eye_images/108_right_h.png"],
62
+ ["exp_eye_images/1062_right_c.png"],
63
+ ["exp_eye_images/1084_right_c.png"],
64
+ ["exp_eye_images/image_1002_g.jpg"]
65
+ ]
66
+
67
+ # Custom CSS for HTML height
68
+ css = """
69
+ .scrollable-html {
70
+ height: 206px;
71
+ overflow-y: auto;
72
+ border: 1px solid #ccc;
73
+ padding: 10px;
74
+ box-sizing: border-box;
75
+ }
76
+ """
77
 
78
  # Gradio Interface
79
  interface = gr.Interface(
80
  fn=predict_image,
81
  inputs=gr.Image(type="pil"),
82
+ outputs=[
83
+ gr.Label(num_top_classes=1, label="Prediction"),
84
+ gr.HTML(label="Explanation", elem_classes=["scrollable-html"])
85
+ ],
86
  examples=example_images,
87
+ title="DR PREDICTOR",
88
+ description=(
89
+ "Upload an image of an eye fundus, and the model will predict it.\n\n"
90
+ "**Disclaimer:** This model is intended as a form of learning process in the field of health-related machine learning and was trained with a limited amount and variety of data with a total of about 4000 data, so the prediction results may not always be correct. There is still a lot of room for improvisation on this model in the future."
91
+ ),
92
  allow_flagging="never",
93
+ css=css
94
  )
95
 
96
  interface.launch(share=True)