Baskar2005 commited on
Commit
476e588
1 Parent(s): 292e0f4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +57 -43
app.py CHANGED
@@ -1,9 +1,9 @@
1
  import tensorflow as tf
2
- import random
3
  from PIL import Image
4
  from tensorflow import keras
5
  import numpy as np
6
  import os
 
7
  import logging
8
  from tensorflow.keras.preprocessing import image as keras_image
9
  from huggingface_hub import from_pretrained_keras
@@ -15,16 +15,12 @@ logging.basicConfig(level=logging.INFO)
15
 
16
  class DiseaseDetectionApp:
17
  def __init__(self):
18
-
19
- self.class_names = [
20
- "Normal",
21
- "PNEUMONIA",
22
- ]
23
-
24
- keras.utils.set_random_seed(42)
25
- self.model = from_pretrained_keras("ryefoxlime/PneumoniaDetection")
26
- self.client=AzureOpenAI()
27
 
 
 
 
 
 
28
 
29
  def predict_disease(self, image_path):
30
  """
@@ -37,36 +33,36 @@ class DiseaseDetectionApp:
37
  - predicted_disease: string
38
  """
39
  try:
40
- # Load the image file, resizing it to the dimensions expected by the model
41
- img = keras_image.load_img(image_path, target_size=(224, 224)) # Adjust target_size according to your model's expected input dimensions
42
-
43
- # Convert the image to a numpy array
44
- img_array = keras_image.img_to_array(img)
45
 
46
- # Add an additional dimension to the array: (1, height, width, channels)
47
- img_array = tf.expand_dims(img_array, 0) # Model expects a batch of images, but we're only passing a single image
48
 
49
- # Make predictions
50
- predictions =self.model.predict(img_array)
51
 
52
- # Extract the predicted class and confidence
53
- predict_class = self.class_names[np.argmax(predictions[0])]
54
- # confidence = round(100 * np.max(predictions[0]), 2)
 
 
55
 
56
- return predict_class
 
 
 
57
 
58
  except Exception as e:
59
  logging.error(f"Error predicting disease: {str(e)}")
60
  return None
61
 
62
  def classify_disease(self,image_path):
63
-
64
  disease_name=self.predict_disease(image_path)
65
  print(disease_name)
66
- if disease_name=="PNEUMONIA":
67
  conversation = [
68
  {"role": "system", "content": "You are a medical assistant"},
69
- {"role": "user", "content": f""" your task describe(classify) about the given disease as summary only in 3 lines.
70
  ```{disease_name}```
71
  """}
72
  ]
@@ -74,23 +70,20 @@ class DiseaseDetectionApp:
74
  response = self.client.chat.completions.create(
75
  model="ChatGPT",
76
  messages=conversation,
77
- temperature=0,
78
  max_tokens=1000
79
  )
80
  # Get the generated topics message
81
-
82
  result = response.choices[0].message.content
83
  return disease_name,result
84
 
85
  elif disease_name=="Normal":
86
  result="No problem in your xray image"
87
  return disease_name,result
88
-
89
- else:
90
- logging.error("Error classify_disease disease")
91
- return "Something went wrong"
92
 
93
- def unzip_image_data(self):
 
94
  """
95
  Unzips an image dataset into a specified directory.
96
 
@@ -98,8 +91,8 @@ class DiseaseDetectionApp:
98
  str: The path to the directory containing the extracted image files.
99
  """
100
  try:
101
- with ZipFile("image_dataset.zip","r") as extract:
102
- directory_path="dataset_image"
103
  extract.extractall(f"{directory_path}")
104
  return f"{directory_path}"
105
 
@@ -107,14 +100,14 @@ class DiseaseDetectionApp:
107
  logging.error(f"An error occurred during extraction: {e}")
108
  return ""
109
 
110
- def example_images(self):
111
  """
112
  Unzips the image dataset and generates a list of paths to the individual image files and use image for showing example
113
 
114
  Returns:
115
  List[str]: A list of file paths to each image in the dataset.
116
  """
117
- image_dataset_folder = self.unzip_image_data()
118
  image_extensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tiff', '.webp']
119
  image_count = len([name for name in os.listdir(image_dataset_folder) if os.path.isfile(os.path.join(image_dataset_folder, name)) and os.path.splitext(name)[1].lower() in image_extensions])
120
  example=[]
@@ -122,16 +115,25 @@ class DiseaseDetectionApp:
122
  for name in os.listdir(image_dataset_folder):
123
  path=(os.path.join(os.path.dirname(image_dataset_folder),os.path.join(image_dataset_folder,name)))
124
  example.append(path)
125
- print()
126
  return example
127
-
 
 
 
 
 
 
 
 
128
 
129
  def gradio_interface(self):
130
 
131
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
132
  gr.HTML("""<center><h1>Pneumonia Disease Detection</h1></center>""")
133
 
134
- exam_img=self.example_images()
 
135
  with gr.Row():
136
  input_image =gr.Image(type="filepath",sources="upload")
137
  with gr.Column():
@@ -142,14 +144,26 @@ class DiseaseDetectionApp:
142
  button =gr.Button(value="Detect The Disease")
143
 
144
  button.click(self.classify_disease,[input_image],[output,classify_disease_])
 
145
  gr.Examples(
146
- examples=exam_img,
 
147
  inputs=[input_image],
148
  outputs=[output,classify_disease_],
149
  fn=self.classify_disease,
 
150
  cache_examples=False)
151
-
152
-
 
 
 
 
 
 
 
 
 
153
  demo.launch(debug=True)
154
 
155
  if __name__ == "__main__":
 
1
  import tensorflow as tf
 
2
  from PIL import Image
3
  from tensorflow import keras
4
  import numpy as np
5
  import os
6
+ import random
7
  import logging
8
  from tensorflow.keras.preprocessing import image as keras_image
9
  from huggingface_hub import from_pretrained_keras
 
15
 
16
  class DiseaseDetectionApp:
17
  def __init__(self):
 
 
 
 
 
 
 
 
 
18
 
19
+
20
+ self.class_names =['Normal', 'Pneumonia']
21
+ self.model =tf.keras.models.load_model("pneumonia_xray_prediction.keras")
22
+ self.client=AzureOpenAI()
23
+
24
 
25
  def predict_disease(self, image_path):
26
  """
 
33
  - predicted_disease: string
34
  """
35
  try:
 
 
 
 
 
36
 
37
+ # Load the image file, resizing it to the dimensions expected by the model
38
+ img = keras_image.load_img(image_path, target_size=(256, 256)) # Adjust target_size according to your model's expected input dimensions
39
 
40
+ # Convert the image to a numpy array
41
+ img_array = keras_image.img_to_array(img)
42
 
43
+ # Add an additional dimension to the array: (1, height, width, channels)
44
+ img_array = tf.expand_dims(img_array, 0) # Model expects a batch of images, but we're only passing a single image
45
+ # print(img_array)
46
+ # Make predictions
47
+ predictions = self.model.predict(img_array)
48
 
49
+ # Extract the predicted class and confidence
50
+ predict_class =self.class_names[np.argmax(predictions[0])]
51
+ confidence = round(100 * np.max(predictions[0]), 2)
52
+ return predict_class
53
 
54
  except Exception as e:
55
  logging.error(f"Error predicting disease: {str(e)}")
56
  return None
57
 
58
  def classify_disease(self,image_path):
59
+
60
  disease_name=self.predict_disease(image_path)
61
  print(disease_name)
62
+ if disease_name=="Pneumonia":
63
  conversation = [
64
  {"role": "system", "content": "You are a medical assistant"},
65
+ {"role": "user", "content": f""" your task describe(classify) about the given disease as a summary only in 5 lines.
66
  ```{disease_name}```
67
  """}
68
  ]
 
70
  response = self.client.chat.completions.create(
71
  model="ChatGPT",
72
  messages=conversation,
73
+ temperature=0.4,
74
  max_tokens=1000
75
  )
76
  # Get the generated topics message
77
+
78
  result = response.choices[0].message.content
79
  return disease_name,result
80
 
81
  elif disease_name=="Normal":
82
  result="No problem in your xray image"
83
  return disease_name,result
 
 
 
 
84
 
85
+
86
+ def unzip_image_data(self,filespath):
87
  """
88
  Unzips an image dataset into a specified directory.
89
 
 
91
  str: The path to the directory containing the extracted image files.
92
  """
93
  try:
94
+ with ZipFile(filespath,"r") as extract:
95
+ directory_path = random.randrange(100)
96
  extract.extractall(f"{directory_path}")
97
  return f"{directory_path}"
98
 
 
100
  logging.error(f"An error occurred during extraction: {e}")
101
  return ""
102
 
103
+ def example_images(self,filespath):
104
  """
105
  Unzips the image dataset and generates a list of paths to the individual image files and use image for showing example
106
 
107
  Returns:
108
  List[str]: A list of file paths to each image in the dataset.
109
  """
110
+ image_dataset_folder = self.unzip_image_data(filespath)
111
  image_extensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tiff', '.webp']
112
  image_count = len([name for name in os.listdir(image_dataset_folder) if os.path.isfile(os.path.join(image_dataset_folder, name)) and os.path.splitext(name)[1].lower() in image_extensions])
113
  example=[]
 
115
  for name in os.listdir(image_dataset_folder):
116
  path=(os.path.join(os.path.dirname(image_dataset_folder),os.path.join(image_dataset_folder,name)))
117
  example.append(path)
118
+
119
  return example
120
+
121
+ def get_example_image(self):
122
+ normal_image="Normal_dataset.zip"
123
+ tuberclosis_image="Pnemonia_dataset.zip"
124
+
125
+ normal_image_unziped=self.example_images(normal_image)
126
+ tuberclosis_image_unziped=self.example_images(tuberclosis_image)
127
+
128
+ return normal_image_unziped,tuberclosis_image_unziped
129
 
130
  def gradio_interface(self):
131
 
132
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
133
  gr.HTML("""<center><h1>Pneumonia Disease Detection</h1></center>""")
134
 
135
+ normal_image,tuberclosis_image=self.get_example_image()
136
+
137
  with gr.Row():
138
  input_image =gr.Image(type="filepath",sources="upload")
139
  with gr.Column():
 
144
  button =gr.Button(value="Detect The Disease")
145
 
146
  button.click(self.classify_disease,[input_image],[output,classify_disease_])
147
+
148
  gr.Examples(
149
+ examples=normal_image,
150
+ label="Normal X-ray Images",
151
  inputs=[input_image],
152
  outputs=[output,classify_disease_],
153
  fn=self.classify_disease,
154
+ examples_per_page=5,
155
  cache_examples=False)
156
+
157
+ gr.Examples(
158
+ examples=tuberclosis_image,
159
+ label="Pneumonia X-ray Images",
160
+ inputs=[input_image],
161
+ outputs=[output,classify_disease_],
162
+ examples_per_page=5,
163
+ fn=self.classify_disease,
164
+ cache_examples=False)
165
+
166
+
167
  demo.launch(debug=True)
168
 
169
  if __name__ == "__main__":