M3ash commited on
Commit
6bdeeea
Β·
verified Β·
1 Parent(s): 5852027

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +89 -41
app.py CHANGED
@@ -18,32 +18,22 @@ with open("dermnet_disease.json", "r") as f:
18
 
19
  # === Class names must match the model's output order ===
20
  class_names = [
21
- 'Acne and Rosacea',
22
- 'Actinic Keratosis Basal Cell Carcinoma and other Malignant Lesions',
23
- 'Atopic Dermatitis',
24
- 'Bullous Disease',
25
- 'Cellulitis Impetigo and other Bacterial Infections',
26
- 'Eczema',
27
- 'Exanthems and Drug Eruptions',
28
- 'Hair Loss Alopecia and other Hair Diseases',
29
- 'Herpes HPV and other STDs',
30
- 'Light Diseases and Disorders of Pigmentation',
31
- 'Lupus and other Connective Tissue diseases',
32
- 'Melanoma Skin Cancer Nevi and Moles',
33
- 'Nail Fungus and other Nail Disease',
34
- 'Poison Ivy and other Contact Dermatitis',
35
  'Psoriasis pictures Lichen Planus and related diseases',
36
  'Scabies Lyme Disease and other Infestations and Bites',
37
- 'Seborrheic Keratoses and other Benign Tumors',
38
- 'Systemic Disease',
39
- 'Tinea Ringworm Candidiasis and other Fungal Infections',
40
- 'Urticaria Hives',
41
- 'Vascular Tumors',
42
- 'Vasculitis',
43
  'Warts Molluscum and other Viral Infections'
44
  ]
45
 
46
- # === Short health tips in English ===
47
  original_tips = {
48
  'Acne and Rosacea': "Wash your face twice daily and use gentle skin products. For serious breakouts, consult a dermatologist.",
49
  'Actinic Keratosis Basal Cell Carcinoma and other Malignant Lesions': "Protect your skin from sun exposure and consult a dermatologist immediately if any skin changes appear.",
@@ -70,6 +60,7 @@ original_tips = {
70
  'Warts Molluscum and other Viral Infections': "Avoid scratching, maintain hygiene, and use antiviral or cryotherapy treatments as needed."
71
  }
72
 
 
73
  tts_lang_codes = {
74
  "English": "en",
75
  "Hausa": "ha",
@@ -77,55 +68,112 @@ tts_lang_codes = {
77
  "Igbo": "ig"
78
  }
79
 
80
- # === Text + TTS for Tip and Recommendation ===
81
  def generate_tip_audio(disease, language):
82
  tip = original_tips.get(disease, "Maintain good hygiene and seek professional care.")
83
- base_tip = f"{tip} Contact a dermatologist for better treatment."
84
- translated_tip = GoogleTranslator(source='en', target=tts_lang_codes[language]).translate(base_tip)
85
 
86
- tts = gTTS(text=f"{disease}. {translated_tip}", lang=tts_lang_codes[language])
87
  temp_audio = tempfile.NamedTemporaryFile(delete=False, suffix=".mp3")
88
  tts.save(temp_audio.name)
89
  return translated_tip, temp_audio.name
90
 
91
- # === Prediction, Translation, Metadata ===
 
 
 
 
 
 
 
 
 
 
 
92
  def predict_and_translate(img, language):
93
  img = img.resize((224, 224))
94
  img_array = image.img_to_array(img)
95
  img_array = np.expand_dims(img_array, axis=0) / 255.0
96
 
97
- prediction = model.predict(img_array)
98
- predicted_index = np.argmax(prediction)
99
- predicted_class = class_names[predicted_index]
100
 
101
- # Get and format metadata
102
- meta = disease_metadata.get(predicted_class, {})
 
 
 
 
 
 
 
103
  meta_text = f"**Description**: {meta.get('description', 'N/A')}\n\n"
104
  meta_text += f"**Symptoms**: {', '.join(meta.get('symptoms', []))}\n\n"
105
  meta_text += f"**Causes**: {', '.join(meta.get('causes', []))}\n\n"
106
  meta_text += f"**Treatments**: {', '.join(meta.get('treatments', []))}\n\n"
107
  meta_text += f"**Is Contagious?**: {meta.get('is_contagious', 'Unknown')}"
108
 
109
- # Generate multilingual health tip + TTS
110
- translated_tip, audio_path = generate_tip_audio(predicted_class, language)
 
 
 
111
 
112
- return predicted_class, meta_text, translated_tip, audio_path
 
 
 
 
 
 
113
 
114
 
115
- # === Gradio Interface ===
116
- interface = gr.Interface(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
117
  fn=predict_and_translate,
118
  inputs=[
119
- gr.Image(type="pil", label="Upload Skin Image"),
120
  gr.Radio(choices=["English", "Hausa", "Yoruba", "Igbo"], label="Select Language", value="English")
121
  ],
122
  outputs=[
123
- gr.Text(label="Predicted Disease"),
 
124
  gr.Text(label="Disease Metadata"),
125
  gr.Text(label="Health Tip (Translated)"),
126
- gr.Audio(label="Health Tip Audio")
127
  ],
128
- title="🧠 AI-Powered Skin Disease Classifier",
129
- description="Upload a skin image. Get a disease prediction, multilingual health tips, audio advice, and dermatologist recommendation."
 
 
 
 
 
 
 
 
 
 
 
 
 
130
  )
131
  interface.launch()
 
18
 
19
  # === Class names must match the model's output order ===
20
  class_names = [
21
+ 'Acne and Rosacea', 'Actinic Keratosis Basal Cell Carcinoma and other Malignant Lesions',
22
+ 'Atopic Dermatitis', 'Bullous Disease',
23
+ 'Cellulitis Impetigo and other Bacterial Infections', 'Eczema',
24
+ 'Exanthems and Drug Eruptions', 'Hair Loss Alopecia and other Hair Diseases',
25
+ 'Herpes HPV and other STDs', 'Light Diseases and Disorders of Pigmentation',
26
+ 'Lupus and other Connective Tissue diseases', 'Melanoma Skin Cancer Nevi and Moles',
27
+ 'Nail Fungus and other Nail Disease', 'Poison Ivy and other Contact Dermatitis',
 
 
 
 
 
 
 
28
  'Psoriasis pictures Lichen Planus and related diseases',
29
  'Scabies Lyme Disease and other Infestations and Bites',
30
+ 'Seborrheic Keratoses and other Benign Tumors', 'Systemic Disease',
31
+ 'Tinea Ringworm Candidiasis and other Fungal Infections', 'Urticaria Hives',
32
+ 'Vascular Tumors', 'Vasculitis',
 
 
 
33
  'Warts Molluscum and other Viral Infections'
34
  ]
35
 
36
+ # === Health tips ===
37
  original_tips = {
38
  'Acne and Rosacea': "Wash your face twice daily and use gentle skin products. For serious breakouts, consult a dermatologist.",
39
  'Actinic Keratosis Basal Cell Carcinoma and other Malignant Lesions': "Protect your skin from sun exposure and consult a dermatologist immediately if any skin changes appear.",
 
60
  'Warts Molluscum and other Viral Infections': "Avoid scratching, maintain hygiene, and use antiviral or cryotherapy treatments as needed."
61
  }
62
 
63
+ # === Language codes ===
64
  tts_lang_codes = {
65
  "English": "en",
66
  "Hausa": "ha",
 
68
  "Igbo": "ig"
69
  }
70
 
71
+ # === TTS Function ===
72
  def generate_tip_audio(disease, language):
73
  tip = original_tips.get(disease, "Maintain good hygiene and seek professional care.")
74
+ sentence = f"This disease is most likely {disease}. The health tip for this predicted disease is: {tip}. Contact a dermatologist for better treatment."
75
+ translated_tip = GoogleTranslator(source='en', target=tts_lang_codes[language]).translate(sentence)
76
 
77
+ tts = gTTS(text=translated_tip, lang=tts_lang_codes[language])
78
  temp_audio = tempfile.NamedTemporaryFile(delete=False, suffix=".mp3")
79
  tts.save(temp_audio.name)
80
  return translated_tip, temp_audio.name
81
 
82
+ # === Classifier Function ===
83
+ def generate_tip_audio(disease, language, translated_tip):
84
+ message = (
85
+ f"This disease is most likely to be {disease}. "
86
+ f"The health tip for this predicted disease is: {translated_tip}"
87
+ )
88
+ lang_code = tts_lang_codes.get(language, "en")
89
+ tts = gTTS(text=message, lang=lang_code)
90
+ temp_audio = tempfile.NamedTemporaryFile(delete=False, suffix=".mp3")
91
+ tts.save(temp_audio.name)
92
+ return temp_audio.name
93
+
94
  def predict_and_translate(img, language):
95
  img = img.resize((224, 224))
96
  img_array = image.img_to_array(img)
97
  img_array = np.expand_dims(img_array, axis=0) / 255.0
98
 
99
+ prediction = model.predict(img_array)[0]
100
+ top_indices = prediction.argsort()[-3:][::-1] # Top 3 predictions
101
+ top_probs = [(class_names[i], int(prediction[i] * 100)) for i in top_indices]
102
 
103
+ most_likely_class, most_likely_prob = top_probs[0]
104
+
105
+ # Translate tip
106
+ tip_text = original_tips.get(most_likely_class, "Maintain good hygiene and seek professional care.")
107
+ tip_text += " Contact a dermatologist for better treatment."
108
+ translated_tip = GoogleTranslator(source='en', target=tts_lang_codes[language]).translate(tip_text)
109
+
110
+ # Metadata
111
+ meta = disease_metadata.get(most_likely_class, {})
112
  meta_text = f"**Description**: {meta.get('description', 'N/A')}\n\n"
113
  meta_text += f"**Symptoms**: {', '.join(meta.get('symptoms', []))}\n\n"
114
  meta_text += f"**Causes**: {', '.join(meta.get('causes', []))}\n\n"
115
  meta_text += f"**Treatments**: {', '.join(meta.get('treatments', []))}\n\n"
116
  meta_text += f"**Is Contagious?**: {meta.get('is_contagious', 'Unknown')}"
117
 
118
+ # Prepare Audio
119
+ audio_path = generate_tip_audio(most_likely_class, language, translated_tip)
120
+
121
+ # Format top predictions string
122
+ prediction_summary = "\n".join([f"{name}: {prob}%" for name, prob in top_probs])
123
 
124
+ return (
125
+ f"This disease is most likely to be: {most_likely_class} ({most_likely_prob}%)",
126
+ prediction_summary,
127
+ meta_text,
128
+ f"The health tip for this predicted disease is:\n{translated_tip}",
129
+ audio_path
130
+ )
131
 
132
 
133
+ # === AI Assistant Bot ===
134
+ def ai_assistant_bot(message):
135
+ message = message.lower()
136
+ if "hello" in message or "hi" in message:
137
+ return "πŸ‘‹ Hello! How can I assist you with skin diseases or this app?"
138
+ elif "symptom" in message:
139
+ return "Upload an image to get the predicted disease and its symptoms."
140
+ elif "treatment" in message:
141
+ return "I'll give treatment advice once a disease is predicted."
142
+ elif "tip" in message:
143
+ return "Tips will appear after prediction in your selected language."
144
+ elif "thank" in message:
145
+ return "You're welcome! 😊"
146
+ else:
147
+ return "I'm your AI Assistant. Ask me about skin conditions, translations, or app usage."
148
+
149
+ # === Main Interface ===
150
+ skin_disease_interface = gr.Interface(
151
  fn=predict_and_translate,
152
  inputs=[
153
+ gr.Image(type="pil", label="Upload or Capture Skin Image", sources=["upload", "webcam"]),
154
  gr.Radio(choices=["English", "Hausa", "Yoruba", "Igbo"], label="Select Language", value="English")
155
  ],
156
  outputs=[
157
+ gr.Text(label="Most Likely Disease Prediction"),
158
+ gr.Text(label="Top 3 Predictions with Probabilities"),
159
  gr.Text(label="Disease Metadata"),
160
  gr.Text(label="Health Tip (Translated)"),
161
+ gr.Audio(label="Text-to-Speech Health Tip")
162
  ],
163
+ title="🧠 AI Skin Disease Classifier",
164
+ description="Upload an image to get disease prediction, health tips, TTS, and detailed metadata."
165
+ )
166
+
167
+ chatbot_interface = gr.Interface(
168
+ fn=ai_assistant_bot,
169
+ inputs=gr.Textbox(lines=2, placeholder="Ask the AI Assistant about skin diseases or the app..."),
170
+ outputs="text",
171
+ title="πŸ’¬ AI Assistant Chatbot"
172
+ )
173
+
174
+ # === Combined UI ===
175
+ gr.TabbedInterface(
176
+ [skin_disease_interface, chatbot_interface],
177
+ ["πŸ“· Skin Classifier", "πŸ€– Chatbot Assistant"]
178
  )
179
  interface.launch()