M3ash commited on
Commit
0394d06
·
verified ·
1 Parent(s): 170145a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +124 -41
app.py CHANGED
@@ -1,48 +1,131 @@
1
- import tensorflow as tf
2
- import numpy as np
3
- import json
4
  import gradio as gr
 
 
 
 
 
5
  from PIL import Image
 
 
 
6
 
7
- # Load model
8
- model = tf.keras.models.load_model("DermNet_Samples.keras")
9
 
10
- # Load metadata
11
  with open("dermnet_disease.json", "r") as f:
12
- disease_info = json.load(f)
13
-
14
- class_names = list(disease_info.keys())
15
-
16
- def load_and_prep_image(img, img_size=(224, 224)):
17
- img = img.resize(img_size)
18
- img_array = tf.keras.preprocessing.image.img_to_array(img)
19
- img_array = tf.expand_dims(img_array, axis=0)
20
- img_array = tf.keras.applications.efficientnet.preprocess_input(img_array)
21
- return img_array
22
-
23
- def predict(img):
24
- img_array = load_and_prep_image(img)
25
- pred = model.predict(img_array)[0]
26
- pred_class = class_names[np.argmax(pred)]
27
- confidence = float(np.max(pred))
28
- info = disease_info.get(pred_class, {})
29
-
30
- result = f"🧬 **Disease Prediction:** {pred_class} ({confidence:.2%})\n\n"
31
- result += f"📖 **Description:** {info['description']}\n\n"
32
- result += f"🩺 **Symptoms:** {', '.join(info['symptoms'])}\n\n"
33
- result += f"🧪 **Causes:** {', '.join(info['causes'])}\n\n"
34
- result += f"💊 **Treatments:** {', '.join(info['treatments'])}\n\n"
35
- result += f"🧍‍♂️ **Contagious:** {'Yes' if info['is_contagious'] else 'No'}"
36
-
37
- return result
38
-
39
- # Gradio interface
40
- demo = gr.Interface(
41
- fn=predict_disease,
42
- inputs=gr.Image(type="pil"),
43
- outputs="markdown",
44
- title="🧪 Skin Disease Classifier",
45
- description="Upload a skin image to classify and learn about the predicted skin condition.",
46
- examples=None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
  )
48
  demo.launch(debug=True)
 
 
 
 
1
  import gradio as gr
2
+ import numpy as np
3
+ from tensorflow.keras.models import load_model
4
+ from tensorflow.keras.preprocessing import image
5
+ from gtts import gTTS
6
+ from deep_translator import GoogleTranslator
7
  from PIL import Image
8
+ import tempfile
9
+ import json
10
+ import os
11
 
12
+ # === Load model ===
13
+ model = load_model("DermNet_Samples.keras")
14
 
15
+ # === Load metadata ===
16
  with open("dermnet_disease.json", "r") as f:
17
+ disease_metadata = json.load(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.",
50
+ 'Atopic Dermatitis': "Moisturize your skin frequently, avoid known irritants, and apply anti-inflammatory creams as prescribed.",
51
+ 'Bullous Disease': "Avoid trauma to the skin and seek immediate care, as these conditions may be autoimmune-related.",
52
+ 'Cellulitis Impetigo and other Bacterial Infections': "Keep the area clean and take antibiotics as prescribed by a healthcare provider.",
53
+ 'Eczema': "Avoid hot showers, use mild soap, and moisturize daily. Severe cases may require corticosteroid creams.",
54
+ 'Exanthems and Drug Eruptions': "Stop using the suspected medication and consult a healthcare provider urgently.",
55
+ 'Hair Loss Alopecia and other Hair Diseases': "Be gentle with hair, avoid tight hairstyles, and consult a doctor for treatment options.",
56
+ 'Herpes HPV and other STDs': "Avoid direct contact during outbreaks and use antiviral medication as prescribed.",
57
+ 'Light Diseases and Disorders of Pigmentation': "Use sunscreen regularly and seek expert evaluation for sudden pigmentation changes.",
58
+ 'Lupus and other Connective Tissue diseases': "Avoid sunlight exposure and follow the treatment prescribed by a rheumatologist.",
59
+ 'Melanoma Skin Cancer Nevi and Moles': "Monitor for any skin changes in moles and consult a dermatologist for screening.",
60
+ 'Nail Fungus and other Nail Disease': "Keep nails dry and trimmed; antifungal treatments may be required for infections.",
61
+ 'Poison Ivy and other Contact Dermatitis': "Avoid contact with allergens and use anti-itch or steroid creams as directed.",
62
+ 'Psoriasis pictures Lichen Planus and related diseases': "Keep skin moisturized and use medicated creams. Stress management can help.",
63
+ 'Scabies Lyme Disease and other Infestations and Bites': "Apply prescribed topical treatments and wash all clothes and bedding.",
64
+ 'Seborrheic Keratoses and other Benign Tumors': "Usually harmless, but removal may be done for cosmetic reasons. Consult a dermatologist.",
65
+ 'Systemic Disease': "Skin symptoms may reflect an internal condition. Immediate medical consultation is advised.",
66
+ 'Tinea Ringworm Candidiasis and other Fungal Infections': "Apply antifungal cream regularly and keep the area dry. Avoid sharing personal items.",
67
+ 'Urticaria Hives': "Avoid known allergens and take antihistamines. If persistent, consult a doctor.",
68
+ 'Vascular Tumors': "Some vascular tumors are harmless, but others may need medical imaging or removal.",
69
+ 'Vasculitis': "Seek medical care promptly, as vasculitis may indicate an underlying autoimmune disorder.",
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",
76
+ "Yoruba": "yo",
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
  demo.launch(debug=True)