GulAk8902 commited on
Commit
ea6ef3b
·
verified ·
1 Parent(s): 78cbb13

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +181 -156
app.py CHANGED
@@ -1,157 +1,182 @@
1
- import gradio as gr
2
- import numpy as np
3
- from PIL import Image
4
- import torch
5
- import torch.nn.functional as F
6
-
7
- # Temporary placeholder function - replace with your actual model later
8
- def predict_skin_lesion(image):
9
- """
10
- Placeholder prediction function
11
- Replace this with your actual ResNet50 model inference
12
- """
13
-
14
- # Skin lesion classes
15
- classes = [
16
- "Actinic Keratoses",
17
- "Basal Cell Carcinoma",
18
- "Benign Keratosis-like Lesions",
19
- "Dermatofibroma",
20
- "Melanocytic Nevi (Normal)",
21
- "Melanoma",
22
- "Vascular Lesions"
23
- ]
24
-
25
- # Placeholder prediction (random for now)
26
- # TODO: Replace with actual model.predict(image)
27
- confidence_scores = np.random.dirichlet(np.ones(len(classes)), size=1)[0]
28
-
29
- # Get top prediction
30
- top_prediction_idx = np.argmax(confidence_scores)
31
- top_class = classes[top_prediction_idx]
32
- top_confidence = float(confidence_scores[top_prediction_idx])
33
-
34
- # Create confidence dictionary for gradio
35
- predictions = {classes[i]: float(confidence_scores[i]) for i in range(len(classes))}
36
-
37
- # Risk assessment based on prediction
38
- if top_class in ["Melanoma", "Basal Cell Carcinoma"] and top_confidence > 0.6:
39
- risk_level = "⚠️ YÜKSEK RİSK - Dermatolog konsültasyonu önerilir"
40
- risk_color = "#FF6B6B"
41
- elif top_confidence > 0.4:
42
- risk_level = "⚡ ORTA RİSK - Takip önerilir"
43
- risk_color = "#FFE66D"
44
- else:
45
- risk_level = "✅ DÜŞÜK RİSK - Rutin kontrol"
46
- risk_color = "#4ECDC4"
47
-
48
- return predictions, f"<div style='padding: 10px; background-color: {risk_color}; border-radius: 5px; color: white; font-weight: bold;'>{risk_level}</div>"
49
-
50
- # Custom CSS for better UI
51
- css = """
52
- .gradio-container {
53
- max-width: 900px;
54
- margin: 0 auto;
55
- }
56
-
57
- .title {
58
- text-align: center;
59
- color: #2E86AB;
60
- margin-bottom: 20px;
61
- }
62
-
63
- .description {
64
- text-align: center;
65
- color: #666;
66
- margin-bottom: 30px;
67
- }
68
-
69
- .risk-box {
70
- margin-top: 15px;
71
- text-align: center;
72
- }
73
- """
74
-
75
- # Create Gradio interface
76
- with gr.Blocks(css=css, title="Cilt Lezyonu AI Analizi") as demo:
77
-
78
- # Header
79
- gr.Markdown(
80
- """
81
- # 🔬 Cilt Lezyonu AI Analizi
82
- ### Yapay zeka destekli cilt kanseri erken teşhis sistemi
83
-
84
- **Nasıl kullanılır:**
85
- 1. Cilt lezyonu fotoğrafını yükleyin
86
- 2. AI analizi bekleyin (30 saniye)
87
- 3. Sonuçları değerlendirin
88
- 4. Gerekirse uzman hekime başvurun
89
-
90
- ⚠️ **Uyarı:** Bu sistem sadece ön değerlendirme amaçlıdır. Kesin tanı için mutlaka doktora başvurun.
91
- """,
92
- elem_classes=["description"]
93
- )
94
-
95
- with gr.Row():
96
- with gr.Column(scale=1):
97
- # Input
98
- input_image = gr.Image(
99
- label="📸 Cilt Lezyonu Fotoğrafı",
100
- type="pil",
101
- elem_id="input-image"
102
- )
103
-
104
- # Analyze button
105
- analyze_btn = gr.Button(
106
- "🔍 Analiz Et",
107
- variant="primary",
108
- size="lg"
109
- )
110
-
111
- with gr.Column(scale=1):
112
- # Outputs
113
- prediction_output = gr.Label(
114
- label="📊 AI Tahmin Sonuçları",
115
- num_top_classes=7
116
- )
117
-
118
- risk_output = gr.HTML(
119
- label="⚠️ Risk Değerlendirmesi"
120
- )
121
-
122
- # Examples section
123
- gr.Markdown("### 📋 Örnek Görüntüler (Test için)")
124
- gr.Examples(
125
- examples=[
126
- # Add example image paths here later
127
- # ["example_melanoma.jpg"],
128
- # ["example_nevus.jpg"],
129
- ],
130
- inputs=input_image,
131
- label="Örnek görüntülere tıklayın"
132
- )
133
-
134
- # Footer
135
- gr.Markdown(
136
- """
137
- ---
138
- **Geliştiren:** AI Healthcare Team | **Teknoloji:** ResNet50 + Transfer Learning | **Dataset:** HAM10000
139
-
140
- 📞 **Acil Durum:** 112 | 🏥 **Dermatoloji Kliniği:** [Randevu Al](https://www.turkiye.gov.tr)
141
- """
142
- )
143
-
144
- # Set up the interface interaction
145
- analyze_btn.click(
146
- fn=predict_skin_lesion,
147
- inputs=input_image,
148
- outputs=[prediction_output, risk_output]
149
- )
150
-
151
- # Launch the app
152
- if __name__ == "__main__":
153
- demo.launch(
154
- share=True,
155
- server_name="0.0.0.0",
156
- server_port=7860
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
157
  )
 
1
+ import gradio as gr
2
+ import torch
3
+ from transformers import ViTForImageClassification, ViTImageProcessor
4
+ from PIL import Image
5
+ import numpy as np
6
+
7
+ # Senin model'inin sınıfları (config'den)
8
+ class_names = {
9
+ 0: "Enfeksiyonel",
10
+ 1: "Ekzama",
11
+ 2: "Akne",
12
+ 3: "Pigment",
13
+ 4: "Benign",
14
+ 5: "Malign",
15
+ 6: "Acne",
16
+ 7: "Actinic Keratosis",
17
+ 8: "Basal Cell Carcinoma",
18
+ 9: "Benign Keratosis",
19
+ 10: "Dermatofibroma",
20
+ 11: "Melanocytic Nevus",
21
+ 12: "Melanoma",
22
+ 13: "Vascular Lesion",
23
+ 14: "Warts/Molluscum"
24
+ }
25
+
26
+ # Risk assessment mapping
27
+ risk_categories = {
28
+ "high_risk": [5, 12, 8], # Malign, Melanoma, Basal Cell Carcinoma
29
+ "medium_risk": [7, 0, 13], # Actinic Keratosis, Enfeksiyonel, Vascular
30
+ "low_risk": [1, 2, 3, 4, 6, 9, 10, 11, 14] # Diğerleri
31
+ }
32
+
33
+ @gr.cache
34
+ def load_model():
35
+ """Senin trained ViT modelini yükle"""
36
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
37
+
38
+ # Model ve processor yükle (local files'dan)
39
+ model = ViTForImageClassification.from_pretrained("./", local_files_only=True)
40
+ processor = ViTImageProcessor.from_pretrained("google/vit-base-patch16-224-in21k")
41
+
42
+ model.to(device)
43
+ model.eval()
44
+
45
+ return model, processor, device
46
+
47
+ def predict_skin_condition(image):
48
+ """Ana prediction fonksiyonu"""
49
+
50
+ if image is None:
51
+ return {}, "Lütfen bir görüntü yükleyin"
52
+
53
+ try:
54
+ # Model yükle
55
+ model, processor, device = load_model()
56
+
57
+ # Image preprocessing
58
+ inputs = processor(images=image, return_tensors="pt")
59
+ inputs = {k: v.to(device) for k, v in inputs.items()}
60
+
61
+ # Prediction
62
+ with torch.no_grad():
63
+ outputs = model(**inputs)
64
+ logits = outputs.logits
65
+ probabilities = torch.softmax(logits, dim=-1)[0]
66
+
67
+ # Results dictionary oluştur
68
+ results = {}
69
+ for idx, prob in enumerate(probabilities):
70
+ if idx in class_names:
71
+ results[class_names[idx]] = float(prob)
72
+
73
+ # En yüksek tahmin
74
+ top_pred_idx = torch.argmax(probabilities).item()
75
+ top_class = class_names[top_pred_idx]
76
+ confidence = float(probabilities[top_pred_idx])
77
+
78
+ # Risk assessment
79
+ risk_html = get_risk_assessment(top_pred_idx, confidence, top_class)
80
+
81
+ return results, risk_html
82
+
83
+ except Exception as e:
84
+ return {}, f"Hata oluştu: {str(e)}"
85
+
86
+ def get_risk_assessment(pred_idx, confidence, class_name):
87
+ """Risk değerlendirmesi yap"""
88
+
89
+ if pred_idx in risk_categories["high_risk"] and confidence > 0.7:
90
+ risk_level = "🚨 YÜKSEK RİSK"
91
+ message = f"<strong>{class_name}</strong> tespit edildi. Dermatolog konsültasyonu ÖNERİLİR."
92
+ color = "#FF4444"
93
+ elif pred_idx in risk_categories["medium_risk"] and confidence > 0.5:
94
+ risk_level = "⚠️ ORTA RİSK"
95
+ message = f"<strong>{class_name}</strong> tespit edildi. Takip önerilir."
96
+ color = "#FF8800"
97
+ else:
98
+ risk_level = "✅ DÜŞÜK RİSK"
99
+ message = f"<strong>{class_name}</strong> tespit edildi. Rutin kontrol yeterli."
100
+ color = "#00AA44"
101
+
102
+ return f"""
103
+ <div style='padding: 15px; background-color: {color}; color: white; border-radius: 10px; text-align: center; margin: 10px 0;'>
104
+ <h3 style='margin: 0 0 10px 0;'>{risk_level}</h3>
105
+ <p style='margin: 0; font-size: 16px;'>{message}</p>
106
+ <p style='margin: 5px 0 0 0; font-size: 14px;'>Güven Skoru: {confidence:.1%}</p>
107
+ </div>
108
+ """
109
+
110
+ # CSS styling
111
+ css = """
112
+ .gradio-container {
113
+ max-width: 1000px;
114
+ margin: 0 auto;
115
+ font-family: 'Segoe UI', sans-serif;
116
+ }
117
+ .title {
118
+ text-align: center;
119
+ color: #2E86AB;
120
+ margin-bottom: 20px;
121
+ }
122
+ """
123
+
124
+ # Gradio interface
125
+ with gr.Blocks(css=css, title="ViT Cilt Hastalığı Analizi") as demo:
126
+
127
+ gr.Markdown("""
128
+ # 🔬 ViT Cilt Hastalığı AI Analizi
129
+ ### 15 farklı cilt hastalığını tespit eden yapay zeka sistemi
130
+ **Accuracy: %97 | Model: Vision Transformer | Classes: 15**
131
+
132
+ ---
133
+ """)
134
+
135
+ with gr.Row():
136
+ with gr.Column(scale=1):
137
+ input_image = gr.Image(
138
+ label="📸 Cilt Görüntüsü Yükleyin",
139
+ type="pil",
140
+ height=400
141
+ )
142
+
143
+ predict_btn = gr.Button(
144
+ "🔍 AI Analizi Başlat",
145
+ variant="primary",
146
+ size="lg"
147
+ )
148
+
149
+ with gr.Column(scale=1):
150
+ prediction_output = gr.Label(
151
+ label="📊 Tahmin Sonuçları",
152
+ num_top_classes=5
153
+ )
154
+
155
+ risk_output = gr.HTML(
156
+ label="⚠️ Risk Değerlendirmesi"
157
+ )
158
+
159
+ # Sınıf açıklamaları
160
+ gr.Markdown("""
161
+ ### 📋 Tespit Edilen Hastalık Kategorileri:
162
+
163
+ **Yüksek Risk:** Malign, Melanoma, Basal Cell Carcinoma
164
+ **Orta Risk:** Actinic Keratosis, Enfeksiyonel, Vascular Lesion
165
+ **Düşük Risk:** Ekzama, Akne, Pigment, Benign, Dermatofibroma, vb.
166
+
167
+ ⚠️ **Önemli:** Bu sistem sadece ön değerlendirme içindir. Kesin tanı için doktora başvurun.
168
+ """)
169
+
170
+ # Event handling
171
+ predict_btn.click(
172
+ fn=predict_skin_condition,
173
+ inputs=input_image,
174
+ outputs=[prediction_output, risk_output]
175
+ )
176
+
177
+ if __name__ == "__main__":
178
+ demo.launch(
179
+ share=True,
180
+ server_name="0.0.0.0",
181
+ server_port=7860
182
  )