Baskar2005 commited on
Commit
80e9ff1
1 Parent(s): d7b6e79

Upload 4 files

Browse files
Files changed (4) hide show
  1. Normal_dataset.zip +3 -0
  2. Tuberclosis_dataset.zip +3 -0
  3. app.py +171 -0
  4. requirements.txt +3 -0
Normal_dataset.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b1eef41a054a65d47a5bcbfd4620a64563a0d9624b402dd8666a92146efe13f1
3
+ size 796090
Tuberclosis_dataset.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7d16409f760033644d976755cbac28046c1822c87d1ca620e0205e185cf0e11c
3
+ size 379194
app.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 logging
7
+ from tensorflow.keras.preprocessing import image as keras_image
8
+ from huggingface_hub import from_pretrained_keras
9
+ from openai import AzureOpenAI
10
+ import gradio as gr
11
+ from zipfile import ZipFile
12
+
13
+ logging.basicConfig(level=logging.INFO)
14
+
15
+ class DiseaseDetectionApp:
16
+ def __init__(self):
17
+
18
+
19
+ self.class_names =['Normal', 'Tuberculosis']
20
+ self.model =tf.keras.models.load_model("chest_xray_tuberclosis_prediction_model.keras")
21
+ self.client=AzureOpenAI()
22
+
23
+
24
+ def predict_disease(self, image_path):
25
+ """
26
+ Predict the disease present in the X-Ray image.
27
+
28
+ Args:
29
+ - image_data: PIL image data
30
+
31
+ Returns:
32
+ - predicted_disease: string
33
+ """
34
+ try:
35
+
36
+ # Load the image file, resizing it to the dimensions expected by the model
37
+ img = keras_image.load_img(image_path, target_size=(256, 256)) # Adjust target_size according to your model's expected input dimensions
38
+
39
+ # Convert the image to a numpy array
40
+ img_array = keras_image.img_to_array(img)
41
+
42
+ # Add an additional dimension to the array: (1, height, width, channels)
43
+ img_array = tf.expand_dims(img_array, 0) # Model expects a batch of images, but we're only passing a single image
44
+ # print(img_array)
45
+ # Make predictions
46
+ predictions = self.model.predict(img_array)
47
+
48
+ # Extract the predicted class and confidence
49
+ predict_class =self.class_names[np.argmax(predictions[0])]
50
+ confidence = round(100 * np.max(predictions[0]), 2)
51
+ return predict_class
52
+
53
+ except Exception as e:
54
+ logging.error(f"Error predicting disease: {str(e)}")
55
+ return None
56
+
57
+ def classify_disease(self,image_path):
58
+
59
+ disease_name=self.predict_disease(image_path)
60
+ print(disease_name)
61
+ if disease_name=="Tuberculosis":
62
+ conversation = [
63
+ {"role": "system", "content": "You are a medical assistant"},
64
+ {"role": "user", "content": f""" your task describe(classify) about the given disease as a summary only in 3 lines.
65
+ ```{disease_name}```
66
+ """}
67
+ ]
68
+ # Generate completion using ChatGPT model
69
+ response = self.client.chat.completions.create(
70
+ model="ChatGPT",
71
+ messages=conversation,
72
+ temperature=0,
73
+ max_tokens=1000
74
+ )
75
+ # Get the generated topics message
76
+
77
+ result = response.choices[0].message.content
78
+ return disease_name,result
79
+
80
+ elif disease_name=="Normal":
81
+ result="No problem in your xray image"
82
+ return disease_name,result
83
+
84
+
85
+
86
+ def unzip_image_data(self,filespath):
87
+ """
88
+ Unzips an image dataset into a specified directory.
89
+
90
+ Returns:
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="dataset_image"
96
+ extract.extractall(f"{directory_path}")
97
+ return f"{directory_path}"
98
+
99
+ except Exception as e:
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=[]
114
+ for i in range(image_count):
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="Tuberclosis_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>Tuberclosis 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():
140
+ output=gr.Label(label="Disease Name")
141
+ with gr.Row():
142
+ classify_disease_=gr.Textbox(label="About disease")
143
+ with gr.Row():
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="Tuberclosis 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__":
170
+ app = DiseaseDetectionApp()
171
+ result=app.gradio_interface()
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ openai
2
+ gradio
3
+ tensorflow