Baskar2005 commited on
Commit
498f257
1 Parent(s): 6f32d20

Create app.py

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