-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp_professional.py
More file actions
1469 lines (1308 loc) · 61.6 KB
/
app_professional.py
File metadata and controls
1469 lines (1308 loc) · 61.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Professional Streamlit Web Interface for Skin Cancer Classification
Model: HybridViT (CNN + Vision Transformer)
Version: 3.0 - Professional UI with Blue Theme
"""
import os
import time
import torch
import torch.nn as nn
import streamlit as st
import google.generativeai as genai
from PIL import Image
import numpy as np
import pandas as pd
import timm
from torchvision import transforms
import plotly.graph_objects as go
# ========================== PAGE CONFIG ==========================
st.set_page_config(
page_title="Skin Cancer AI Detection",
page_icon="⚕",
layout="wide",
initial_sidebar_state="expanded"
)
# ========================== LANGUAGE SETTINGS ==========================
# Initialize language in session state
if 'language' not in st.session_state:
st.session_state.language = 'vi' # Default to Vietnamese
# Language dictionary
TRANSLATIONS = {
'vi': {
'title': 'HỆ THỐNG PHÁT HIỆN UNG THƯ DA BẰNG AI',
'subtitle': 'Phân loại tổn thương da với HybridViT (CNN + Vision Transformer)',
'upload_title': 'TẢI ẢNH LÊN',
'upload_help': 'Tải ảnh da cần phân tích (JPG, PNG)',
'analyzing': 'Đang phân tích ảnh...',
'prediction_result': 'KẾT QUẢ DỰ ĐOÁN',
'confidence': 'Độ tin cậy',
'top5_predictions': 'TOP 5 DỰ ĐOÁN',
'disease_info': 'THÔNG TIN VỀ',
'consult_doctor': 'QUAN TRỌNG: Kết quả chỉ mang tính tham khảo. Luôn tham khảo bác sĩ da liễu!',
'system_info': 'THÔNG TIN HỆ THỐNG',
'model_version': 'Phiên bản',
'architecture': 'Kiến trúc',
'dataset': 'Dataset',
'accuracy': 'Độ chính xác',
'classes': 'Số lớp',
'how_to_use': 'HƯỚNG DẪN SỬ DỤNG',
'step1': 'Tải ảnh da lên hệ thống',
'step2': 'AI tự động phân tích và nhận diện',
'step3': 'Xem kết quả, biểu đồ và thông tin chi tiết',
'step4': 'Tham khảo bác sĩ để chẩn đoán chuyên sâu',
'model_info': 'THÔNG TIN MODEL',
'warning': 'LƯU Ý Y TẾ',
'warning_text': 'Ứng dụng này CHỈ hỗ trợ tham khảo, KHÔNG thay thế chẩn đoán y khoa chuyên nghiệp. Luôn tham khảo bác sĩ da liễu có chứng chỉ!',
# Flowchart
'workflow_title': 'Quy trình phân tích AI',
'flow_step1': 'Chuẩn bị ảnh',
'flow_step2': 'Tải ảnh lên',
'flow_step3': 'AI phân tích',
'flow_step4': 'Nhận kết quả',
'flow_step5': 'Tham khảo bác sĩ',
# Disease types
'diseases_title': '⚕ Hệ thống có thể phát hiện 9 loại tổn thương da',
# Sidebar
'system_ai': 'HỆ THỐNG AI',
'device': 'Thiết bị:',
'status': 'Trạng thái:',
'ready': 'Sẵn sàng',
'guide_title': 'HƯỚNG DẪN SỬ DỤNG',
'guide_step1': 'Tải ảnh tổn thương da lên hệ thống',
'guide_step2': 'AI tự động phân tích và nhận diện',
'guide_step3': 'Xem kết quả, biểu đồ và thông tin chi tiết',
'guide_step4': 'Tham khảo bác sĩ để chẩn đoán chuyên sâu',
'important_note': 'LƯU Ý QUAN TRỌNG',
'note_text': 'Kết quả AI chỉ mang tính chất tham khảo. Luôn tham khảo ý kiến bác sĩ chuyên khoa để có chẩn đoán chính xác.',
'cannot_load_model': 'Không thể tải model từ:',
'ensure_model': 'Vui lòng đảm bảo file \'best_model.pt\' có trong thư mục gốc.',
# Gemini advice
'advice_title': 'Tư vấn chăm sóc (AI)',
'advice_desc': 'Gợi ý hành động an toàn dựa trên dự đoán AI. KHÔNG thay thế tư vấn y khoa và KHÔNG kê thuốc.',
'advice_textarea': 'Mô tả thêm triệu chứng / thời gian xuất hiện (tùy chọn)',
'advice_btn': 'Lấy gợi ý chăm sóc',
'advice_loading': 'Đang lấy gợi ý từ Gemini...',
'advice_result_title': 'Gợi ý hành động',
'advice_missing_key': 'Chưa thiết lập GEMINI_API_KEY. Vui lòng thêm vào biến môi trường hoặc st.secrets.',
'advice_error': 'Không thể lấy gợi ý từ Gemini. Vui lòng thử lại.',
'advice_disclaimer': 'Gợi ý chỉ mang tính tham khảo, không chẩn đoán hay kê đơn. Luôn gặp bác sĩ chuyên khoa.'
},
'en': {
'title': 'AI-POWERED SKIN CANCER DETECTION SYSTEM',
'subtitle': 'Skin Lesion Classification with HybridViT (CNN + Vision Transformer)',
'upload_title': 'UPLOAD IMAGE',
'upload_help': 'Upload skin image for analysis (JPG, PNG)',
'analyzing': 'Analyzing image...',
'prediction_result': 'PREDICTION RESULT',
'confidence': 'Confidence',
'top5_predictions': 'TOP 5 PREDICTIONS',
'disease_info': 'INFORMATION ABOUT',
'consult_doctor': 'IMPORTANT: Results are for reference only. Always consult a dermatologist!',
'system_info': 'SYSTEM INFORMATION',
'model_version': 'Version',
'architecture': 'Architecture',
'dataset': 'Dataset',
'accuracy': 'Accuracy',
'classes': 'Classes',
'how_to_use': 'HOW TO USE',
'step1': 'Upload skin image to system',
'step2': 'AI automatically analyzes and identifies',
'step3': 'View results, charts and detailed information',
'step4': 'Consult doctor for professional diagnosis',
'model_info': 'MODEL INFORMATION',
'warning': 'MEDICAL DISCLAIMER',
'warning_text': 'This application is for REFERENCE ONLY and does NOT replace professional medical diagnosis. Always consult a certified dermatologist!',
# Flowchart
'workflow_title': 'AI Analysis Workflow',
'flow_step1': 'Prepare Image',
'flow_step2': 'Upload Image',
'flow_step3': 'AI Analysis',
'flow_step4': 'Get Results',
'flow_step5': 'Consult Doctor',
# Disease types
'diseases_title': '⚕ System can detect 9 types of skin lesions',
# Sidebar
'system_ai': 'AI SYSTEM',
'device': 'Device:',
'status': 'Status:',
'ready': 'Ready',
'guide_title': 'USER GUIDE',
'guide_step1': 'Upload skin lesion image to system',
'guide_step2': 'AI automatically analyzes and identifies',
'guide_step3': 'View results, charts and detailed information',
'guide_step4': 'Consult doctor for professional diagnosis',
'important_note': 'IMPORTANT NOTE',
'note_text': 'AI results are for reference only. Always consult a specialist for accurate diagnosis.',
'cannot_load_model': 'Cannot load model from:',
'ensure_model': 'Please ensure \'best_model.pt\' file exists in the root directory.',
# Gemini advice
'advice_title': 'Care advice (AI)',
'advice_desc': 'Safety-first guidance based on the AI prediction. Not medical advice and never prescriptive.',
'advice_textarea': 'Describe additional symptoms / duration (optional)',
'advice_btn': 'Get care suggestions',
'advice_loading': 'Fetching suggestions from Gemini...',
'advice_result_title': 'Suggested actions',
'advice_missing_key': 'GEMINI_API_KEY is not set. Please provide via environment variable or st.secrets.',
'advice_error': 'Unable to fetch advice from Gemini. Please try again.',
'advice_disclaimer': 'This is reference-only guidance, not a diagnosis or prescription. Always see a specialist.'
}
}
def t(key: str) -> str:
"""Get translated text based on current language"""
lang = st.session_state.get('language', 'vi')
return TRANSLATIONS.get(lang, TRANSLATIONS['vi']).get(key, key)
# ========================== MODEL ARCHITECTURE ==========================
class ChannelAttention(nn.Module):
def __init__(self, in_channels, reduction=16):
super().__init__()
self.avg_pool = nn.AdaptiveAvgPool2d(1)
self.max_pool = nn.AdaptiveMaxPool2d(1)
self.mlp = nn.Sequential(
nn.Linear(in_channels, in_channels // reduction, bias=False),
nn.ReLU(),
nn.Linear(in_channels // reduction, in_channels, bias=False)
)
self.sigmoid = nn.Sigmoid()
def forward(self, x):
b, c, _, _ = x.size()
avg_out = self.mlp(self.avg_pool(x).view(b, c))
max_out = self.mlp(self.max_pool(x).view(b, c))
out = avg_out + max_out
out = self.sigmoid(out).view(b, c, 1, 1)
return x * out
class SpatialAttention(nn.Module):
def __init__(self, kernel_size=7):
super().__init__()
self.conv = nn.Conv2d(2, 1, kernel_size, padding=kernel_size//2, bias=False)
self.sigmoid = nn.Sigmoid()
def forward(self, x):
avg_out = torch.mean(x, dim=1, keepdim=True)
max_out, _ = torch.max(x, dim=1, keepdim=True)
x_cat = torch.cat([avg_out, max_out], dim=1)
out = self.sigmoid(self.conv(x_cat))
return x * out
class CBAM(nn.Module):
def __init__(self, in_channels, reduction=16, kernel_size=7):
super().__init__()
self.channel_att = ChannelAttention(in_channels, reduction)
self.spatial_att = SpatialAttention(kernel_size)
def forward(self, x):
x = self.channel_att(x)
x = self.spatial_att(x)
return x
class CNNExtractorCBAM(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Sequential(
nn.Conv2d(3, 32, 3, padding=1),
nn.BatchNorm2d(32),
nn.ReLU(),
nn.MaxPool2d(2)
)
self.conv2 = nn.Sequential(
nn.Conv2d(32, 64, 3, padding=1),
nn.BatchNorm2d(64),
nn.ReLU(),
nn.MaxPool2d(2)
)
self.conv3 = nn.Sequential(
nn.Conv2d(64, 128, 3, padding=1),
nn.BatchNorm2d(128),
nn.ReLU(),
nn.MaxPool2d(2)
)
self.cbam = CBAM(128)
def forward(self, x):
x = self.conv1(x)
x = self.conv2(x)
x = self.conv3(x)
x = self.cbam(x)
return x
class PatchEmbed(nn.Module):
def __init__(self, in_ch=128, patch=2, embed_dim=768):
super().__init__()
self.proj = nn.Conv2d(in_ch, embed_dim, kernel_size=patch, stride=patch)
def forward(self, x):
x = self.proj(x)
x = x.flatten(2).transpose(1, 2)
return x
class HybridViT(nn.Module):
def __init__(self, num_classes=9):
super().__init__()
self.cnn = CNNExtractorCBAM()
self.patch_embed = PatchEmbed()
self.vit = timm.create_model('vit_base_patch16_224', pretrained=False)
self.vit.patch_embed = None
self.classifier = nn.Linear(self.vit.embed_dim, num_classes)
def forward(self, x):
x = self.cnn(x)
x = self.patch_embed(x)
cls_token = self.vit.cls_token.expand(x.shape[0], -1, -1)
x = torch.cat((cls_token, x), dim=1)
x = x + self.vit.pos_embed
x = self.vit.blocks(x)
x = self.vit.norm(x)
logits = self.classifier(x[:, 0])
return logits
# ========================== CONFIGURATION ==========================
# Get the absolute path to ensure model is found
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
# Try multiple possible locations for the model file
POSSIBLE_MODEL_PATHS = [
os.path.join(BASE_DIR, "best_model_CNN_CBAM_ViT.pt"),
os.path.join(BASE_DIR, "model", "best_model_CNN_CBAM_ViT.pt"),
os.path.join(BASE_DIR, "best_model.pt"),
os.path.join(BASE_DIR, "model", "best_model.pt"),
"best_model_CNN_CBAM_ViT.pt", # Relative path
"best_model.pt", # Fallback
]
# Find the first existing model file
CHECKPOINT_PATH = None
for path in POSSIBLE_MODEL_PATHS:
if os.path.exists(path):
CHECKPOINT_PATH = path
break
# If no model found locally, will be downloaded from Google Drive
if CHECKPOINT_PATH is None:
CHECKPOINT_PATH = os.path.join(BASE_DIR, "best_model_CNN_CBAM_ViT.pt")
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
NUM_CLASSES = 9
GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY") or st.secrets.get("GEMINI_API_KEY", None)
CLASS_NAMES = [
'Actinic Keratosis',
'Basal Cell Carcinoma',
'Dermatofibroma',
'Melanoma',
'Nevus',
'Pigmented Benign Keratosis',
'Seborrheic Keratosis',
'Squamous Cell Carcinoma',
'Vascular Lesion'
]
CLASS_NAMES_VI = [
'Sừng hóa quang hóa',
'Ung thư tế bào đáy',
'U xơ da',
'Ung thư hắc tố',
'Nốt ruồi',
'Sừng hóa lành tính có sắc tố',
'Sừng hóa tiết nhờn',
'Ung thư tế bào vảy',
'Tổn thương mạch máu'
]
CLASS_INFO = {
'Actinic Keratosis': {
'name_vi': 'Sừng hóa quang hóa',
'description': 'Tổn thương da tiền ung thư do tiếp xúc ánh nắng mặt trời kéo dài',
'risk': 'Trung bình',
'treatment': 'Có thể điều trị bằng đông lạnh, thuốc bôi tại chỗ hoặc liệu pháp quang động lực',
'color': '#2196F3',
'gradient': 'linear-gradient(135deg, #2196F3 0%, #1976D2 100%)'
},
'Basal Cell Carcinoma': {
'name_vi': 'Ung thư tế bào đáy',
'description': 'Loại ung thư da phổ biến nhất, phát triển chậm và hiếm khi lan rộng',
'risk': 'Thấp-Trung bình',
'treatment': 'Phẫu thuật cắt bỏ, phẫu thuật Mohs hoặc xạ trị',
'color': '#E53935',
'gradient': 'linear-gradient(135deg, #E53935 0%, #C62828 100%)'
},
'Dermatofibroma': {
'name_vi': 'U xơ da',
'description': 'Khối u xơ lành tính, thường vô hại',
'risk': 'Thấp',
'treatment': 'Thường không cần điều trị, có thể phẫu thuật nếu gây khó chịu',
'color': '#1E88E5',
'gradient': 'linear-gradient(135deg, #1E88E5 0%, #1565C0 100%)'
},
'Melanoma': {
'name_vi': 'Ung thư hắc tố',
'description': 'Dạng ung thư da nguy hiểm nhất, có thể lan nhanh',
'risk': 'Cao',
'treatment': 'Cần chú ý y tế ngay - phẫu thuật, liệu pháp miễn dịch, điều trị nhắm mục tiêu',
'color': '#D32F2F',
'gradient': 'linear-gradient(135deg, #D32F2F 0%, #B71C1C 100%)'
},
'Nevus': {
'name_vi': 'Nốt ruồi',
'description': 'Nốt ruồi thông thường, thường lành tính',
'risk': 'Rất thấp',
'treatment': 'Theo dõi các thay đổi, loại bỏ nếu nghi ngờ',
'color': '#42A5F5',
'gradient': 'linear-gradient(135deg, #42A5F5 0%, #1E88E5 100%)'
},
'Pigmented Benign Keratosis': {
'name_vi': 'Sừng hóa lành tính có sắc tố',
'description': 'Đốm hoặc mảng nâu không ung thư',
'risk': 'Rất thấp',
'treatment': 'Không cần điều trị, có thể loại bỏ vì mục đích thẩm mỹ',
'color': '#0288D1',
'gradient': 'linear-gradient(135deg, #0288D1 0%, #01579B 100%)'
},
'Seborrheic Keratosis': {
'name_vi': 'Sừng hóa tiết nhờn',
'description': 'U lành tính phổ biến ở người lớn tuổi',
'risk': 'Rất thấp',
'treatment': 'Không cần điều trị, có thể loại bỏ vì lý do thẩm mỹ',
'color': '#1976D2',
'gradient': 'linear-gradient(135deg, #1976D2 0%, #0D47A1 100%)'
},
'Squamous Cell Carcinoma': {
'name_vi': 'Ung thư tế bào vảy',
'description': 'Loại ung thư da phổ biến thứ hai, có thể lan rộng nếu không điều trị',
'risk': 'Trung bình',
'treatment': 'Phẫu thuật cắt bỏ, xạ trị hoặc hóa trị tại chỗ',
'color': '#1565C0',
'gradient': 'linear-gradient(135deg, #1565C0 0%, #0D47A1 100%)'
},
'Vascular Lesion': {
'name_vi': 'Tổn thương mạch máu',
'description': 'Tình trạng da liên quan đến mạch máu',
'risk': 'Thấp',
'treatment': 'Liệu pháp laser, phẫu thuật nếu cần',
'color': '#039BE5',
'gradient': 'linear-gradient(135deg, #039BE5 0%, #0277BD 100%)'
}
}
# Image preprocessing
transform = transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
])
# ========================== DOWNLOAD MODEL ==========================
def download_model_from_drive():
"""Download model from Google Drive with progress bar"""
import gdown
import requests
from tqdm import tqdm
# Google Drive file ID từ link
file_id = "1QGJOCE4DIaqbj5DfMmfXoYL8D20xJ8XI"
url = f"https://drive.google.com/uc?export=download&id={file_id}"
# Thêm spacing để tránh bị header che
st.write("")
st.write("")
st.toast("⬇ Đang tải model từ Google Drive... (330MB)")
progress_bar = st.progress(0)
try:
# Download với gdown
output = gdown.download(id=file_id, output=CHECKPOINT_PATH, quiet=False)
if output and os.path.exists(CHECKPOINT_PATH):
progress_bar.progress(100)
file_size = os.path.getsize(CHECKPOINT_PATH) / (1024**2)
st.toast(f"✓ Tải model thành công! ({file_size:.1f}MB)")
time.sleep(10) # Hiển thị 10s
progress_bar.empty()
return True
else:
st.toast("Không thể tải model. Vui lòng thử lại.")
return False
except Exception as e:
st.toast(f"Lỗi: {str(e)}")
return False
# ========================== LOAD MODEL ==========================
@st.cache_resource(show_spinner=False)
def _load_model_from_checkpoint(checkpoint_path, device, num_classes):
"""Internal function to load model from checkpoint file - cached"""
model = HybridViT(num_classes=num_classes).to(device)
# Try loading without weights_only first (for older PyTorch versions)
try:
checkpoint = torch.load(checkpoint_path, map_location=device, weights_only=True)
except TypeError:
# Fallback for older PyTorch versions
checkpoint = torch.load(checkpoint_path, map_location=device)
# Checkpoint có thể là state_dict trực tiếp hoặc dictionary có key 'model_state_dict'
if isinstance(checkpoint, dict) and 'model_state_dict' in checkpoint:
model.load_state_dict(checkpoint['model_state_dict'])
else:
# Checkpoint là state_dict trực tiếp
model.load_state_dict(checkpoint)
model.eval()
return model
def load_model(checkpoint_path, device, num_classes):
"""Load model with auto-download if needed"""
# Kiểm tra file có tồn tại không
if not os.path.exists(checkpoint_path):
# Tải từ Google Drive nếu chưa có
download_success = download_model_from_drive()
if not download_success:
return None, False, "download_failed"
# Load model từ checkpoint (cached)
try:
model = _load_model_from_checkpoint(checkpoint_path, device, num_classes)
return model, True, "loaded"
except Exception as e:
return None, False, f"error: {str(e)}"
# Load model và hiển thị thông báo
st.write("")
st.write("")
# Load model (chỉ chạy 1 lần khi app start)
if 'model_initialized' not in st.session_state:
with st.spinner("Đang load model..."):
model, model_loaded, load_status = load_model(CHECKPOINT_PATH, DEVICE, NUM_CLASSES)
st.session_state.model = model
st.session_state.model_loaded = model_loaded
st.session_state.load_status = load_status
st.session_state.model_initialized = True
# Hiển thị toast dựa trên kết quả
if model_loaded:
st.toast("✓ Model đã sẵn sàng!")
elif "error" in load_status:
st.toast(f"❌ {load_status.replace('error: ', '')}")
elif load_status == "download_failed":
st.toast("❌ Không thể tải model từ Google Drive")
else:
# Lấy từ session state
model = st.session_state.model
model_loaded = st.session_state.model_loaded
load_status = st.session_state.load_status
# ========================== PREDICTION FUNCTION ==========================
def predict(image):
"""Predict skin lesion type"""
if not model_loaded:
return None, None, None, None
img_tensor = transform(image).unsqueeze(0).to(DEVICE)
with torch.no_grad():
outputs = model(img_tensor)
probabilities = torch.softmax(outputs, dim=1)[0]
pred_idx = probabilities.argmax().item()
pred_class = CLASS_NAMES[pred_idx]
pred_class_vi = CLASS_NAMES_VI[pred_idx]
confidence = probabilities[pred_idx].item()
return pred_class, pred_class_vi, confidence, probabilities.cpu().numpy()
def generate_gemini_advice(pred_class, pred_class_vi, risk, confidence, user_notes, lang_code):
"""Call Gemini to produce safety-first care advice (no prescriptions)."""
if not GEMINI_API_KEY:
return None, 'missing_key'
try:
genai.configure(api_key=GEMINI_API_KEY)
# Try different model names that may be available (newest to oldest)
model_names_to_try = [
"gemini-2.0-flash-exp",
"gemini-1.5-pro",
"gemini-1.5-flash",
"gemini-pro",
"gemini-3.0",
]
model = None
last_error = None
for model_name in model_names_to_try:
try:
test_model = genai.GenerativeModel(model_name)
# Try a simple test to verify the model works
test_response = test_model.generate_content("test")
model = test_model
break
except Exception as e:
last_error = str(e)
continue
if model is None:
# Fallback: try to get first available model
try:
available_models = [m for m in genai.list_models() if 'generateContent' in m.supported_generation_methods]
if available_models:
model_name = available_models[0].name.replace('models/', '')
model = genai.GenerativeModel(model_name)
except Exception as e:
last_error = str(e)
if model is None:
error_msg = f"Không thể kết nối Gemini API. Lỗi: {last_error}"
return None, error_msg
lang_label = 'Vietnamese' if lang_code == 'vi' else 'English'
prompt = f"""
You are a dermatology decision-support assistant. Provide concise, safety-first guidance.
Inputs:
- Predicted condition: {pred_class} ({pred_class_vi})
- Risk tier: {risk}
- Model confidence: {confidence*100:.1f}%
- User-described symptoms: {user_notes or 'N/A'}
Output language: {lang_label}
Rules:
- Do NOT prescribe or name specific drugs or treatments.
- Do NOT give detailed self-treatment steps; emphasize seeing a specialist for procedures/meds.
- Structure the reply in 4 short bullet points: (1) severity & urgency, (2) immediate self-care basics (non-pharmacologic), (3) when to see a dermatologist, (4) red-flag signs that require urgent care.
- Keep total under 120 words.
"""
response = model.generate_content(prompt)
return response.text, None
except Exception as e:
return None, str(e)
# ========================== VISUALIZATION FUNCTIONS ==========================
def plot_probabilities_chart(probs, class_names_vi):
"""Create horizontal bar chart"""
df = pd.DataFrame({
'Class': class_names_vi,
'Probability': probs * 100
}).sort_values('Probability', ascending=True)
colors = ['#E3F2FD' if p < 10 else '#90CAF9' if p < 30 else '#42A5F5' if p < 60 else '#1976D2'
for p in df['Probability']]
fig = go.Figure(data=[
go.Bar(
y=df['Class'],
x=df['Probability'],
orientation='h',
marker=dict(
color=colors,
line=dict(color='#1565C0', width=1.5),
cornerradius=8
),
text=[f'{p:.1f}%' for p in df['Probability']],
textposition='outside',
textfont=dict(size=13, family='Inter', color='#0D47A1'),
hovertemplate='<b>%{y}</b><br>Xác suất: %{x:.2f}%<extra></extra>'
)
])
fig.update_layout(
xaxis_title="Xác suất (%)",
yaxis_title="",
height=380,
font=dict(size=12, family='Inter', color='#0D47A1'),
plot_bgcolor='rgba(227,242,253,0.2)',
paper_bgcolor='white',
xaxis=dict(
showgrid=True,
gridcolor='rgba(33,150,243,0.1)',
range=[0, max(df['Probability']) * 1.15],
tickfont=dict(color='#1565C0', size=12)
),
yaxis=dict(
tickfont=dict(size=12, color='#1565C0')
),
margin=dict(l=20, r=120, t=20, b=50)
)
return fig
def plot_confidence_gauge(confidence):
"""Create confidence gauge"""
color = '#E53935' if confidence < 0.5 else '#FB8C00' if confidence < 0.7 else '#1976D2'
fig = go.Figure(go.Indicator(
mode="gauge+number",
value=confidence * 100,
domain={'x': [0, 1], 'y': [0, 1]},
number={'suffix': "%", 'font': {'size': 56, 'color': '#0D47A1'}},
gauge={
'axis': {
'range': [None, 100],
'tickwidth': 2,
'tickcolor': '#1976D2',
'tickfont': {'size': 14, 'color': '#1565C0'}
},
'bar': {'color': color, 'thickness': 0.85},
'bgcolor': "white",
'borderwidth': 3,
'bordercolor': '#E3F2FD',
'steps': [
{'range': [0, 50], 'color': '#FFEBEE'},
{'range': [50, 70], 'color': '#FFF3E0'},
{'range': [70, 100], 'color': '#E3F2FD'}
],
}
))
fig.update_layout(
height=260,
margin=dict(l=30, r=30, t=10, b=10),
paper_bgcolor='rgba(227,242,253,0.2)',
font={'family': 'Inter'}
)
return fig
def plot_top_predictions(probs, class_names_vi, top_n=5):
"""Create donut chart for top predictions"""
top_idx = np.argsort(probs)[::-1][:top_n]
top_probs = probs[top_idx]
top_names = [class_names_vi[i] for i in top_idx]
colors = ['#0D47A1', '#1565C0', '#1976D2', '#1E88E5', '#42A5F5']
fig = go.Figure(data=[
go.Pie(
labels=top_names,
values=top_probs * 100,
hole=0.65,
marker=dict(
colors=colors,
line=dict(color='white', width=3)
),
textfont=dict(size=14, family='Inter', color='white'),
textposition='inside',
hovertemplate='<b>%{label}</b><br>%{value:.2f}%<extra></extra>'
)
])
fig.update_layout(
height=320,
showlegend=True,
legend=dict(
orientation="v",
yanchor="middle",
y=0.5,
xanchor="left",
x=1.02,
font=dict(size=13, family='Inter', color='#1565C0'),
bgcolor='rgba(227,242,253,0.3)',
bordercolor='#1976D2',
borderwidth=1
),
margin=dict(l=30, r=30, t=20, b=20),
paper_bgcolor='rgba(227,242,253,0.2)'
)
return fig
# ========================== CUSTOM CSS ==========================
def load_custom_css():
st.markdown("""
<style>
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap');
.main {
background: linear-gradient(135deg, #1976D2 0%, #0D47A1 100%);
font-family: 'Inter', sans-serif;
}
.block-container {
padding: 1.5rem 1.5rem;
background: linear-gradient(to bottom, #ffffff 0%, #f8fbff 100%);
border-radius: 20px;
margin: 15px;
box-shadow: 0 15px 40px rgba(13,71,161,0.12);
max-width: 1400px;
}
section[data-testid="stSidebar"] {
background: linear-gradient(180deg, #1976D2 0%, #0D47A1 100%);
width: 25rem !important;
min-width: 25rem !important;
max-width: 25rem !important;
}
section[data-testid="stSidebar"] * {
color: white !important;
}
section[data-testid="stSidebar"] > div:first-child {
width: 25rem !important;
}
.stButton>button {
background: linear-gradient(135deg, #1976D2 0%, #0D47A1 100%);
color: white;
border: none;
border-radius: 12px;
padding: 16px 40px;
font-weight: 700;
font-size: 16px;
transition: all 0.3s;
box-shadow: 0 8px 24px rgba(25,118,210,0.35);
letter-spacing: 0.8px;
text-transform: uppercase;
width: 100%;
}
.stButton>button:hover {
transform: translateY(-3px);
box-shadow: 0 12px 32px rgba(25,118,210,0.45);
}
.stTabs [data-baseweb="tab-list"] {
gap: 8px;
background: rgba(227,242,253,0.3);
padding: 10px;
border-radius: 14px;
}
.stTabs [data-baseweb="tab"] {
border-radius: 10px;
padding: 14px 28px;
font-weight: 600;
color: #1565C0;
font-size: 15px;
}
.stTabs [aria-selected="true"] {
background: linear-gradient(135deg, #1976D2 0%, #0D47A1 100%);
color: white !important;
}
img {
border-radius: 16px;
box-shadow: 0 8px 24px rgba(0,0,0,0.1);
}
hr {
margin: 1rem 0;
border: none;
height: 2px;
background: linear-gradient(90deg, transparent, #1976D2, transparent);
}
.stAlert {
border-radius: 12px;
border-left: 4px solid;
padding: 12px 16px;
}
::-webkit-scrollbar {
width: 10px;
height: 10px;
}
::-webkit-scrollbar-track {
background: #E3F2FD;
border-radius: 10px;
}
::-webkit-scrollbar-thumb {
background: linear-gradient(135deg, #1976D2 0%, #0D47A1 100%);
border-radius: 10px;
}
code {
background: rgba(227,242,253,0.5);
color: #0D47A1;
padding: 4px 10px;
border-radius: 6px;
font-weight: 600;
}
.metric-card {
background: white;
padding: 24px;
border-radius: 16px;
border-left: 5px solid #1976D2;
box-shadow: 0 4px 12px rgba(25,118,210,0.1);
margin: 12px 0;
}
.section-header {
text-align: center;
padding: 14px;
background: linear-gradient(135deg, rgba(25,118,210,0.08) 0%, rgba(13,71,161,0.08) 100%);
border-radius: 12px;
margin: 15px 0 10px 0;
border: 2px solid rgba(25,118,210,0.15);
}
.section-title {
color: #1565C0;
margin: 0;
font-size: 1.3rem;
font-weight: 700;
letter-spacing: -0.3px;
}
</style>
""", unsafe_allow_html=True)
# ========================== MAIN APPLICATION ==========================
def main():
load_custom_css()
# Language selector in sidebar
with st.sidebar:
lang_col1, lang_col2 = st.columns(2)
with lang_col1:
if st.button("Tiếng Việt", use_container_width=True,
type="primary" if st.session_state.language == 'vi' else "secondary"):
st.session_state.language = 'vi'
st.rerun()
with lang_col2:
if st.button("English", use_container_width=True,
type="primary" if st.session_state.language == 'en' else "secondary"):
st.session_state.language = 'en'
st.rerun()
st.markdown("<div style='margin-top: 10px;'></div>", unsafe_allow_html=True)
# Header - compact with translation
st.markdown(f"""
<div style='text-align: center; margin-bottom: 1rem;'>
<h1 style='
background: linear-gradient(135deg, #1976D2 0%, #0D47A1 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
font-size: 2.2rem;
font-weight: 900;
margin-bottom: 0.3rem;
letter-spacing: -1px;
'>⚕ {t('title')}</h1>
<p style='color: #1565C0; font-size: 0.95rem; font-weight: 500;'>
{t('subtitle')}
</p>
</div>
""", unsafe_allow_html=True)
# Sidebar
with st.sidebar:
# System Status Card
status_bg = '#4CAF50' if model_loaded else '#F44336'
status_text = ('✓ ' + t('ready')) if model_loaded else '✗ Error'
st.markdown(f"""
<div style='
background: linear-gradient(135deg, #1976D2 0%, #0D47A1 100%);
padding: 25px;
border-radius: 16px;
color: white;
margin-bottom: 25px;
box-shadow: 0 8px 24px rgba(25,118,210,0.35);
'>
<h2 style='margin: 0 0 18px 0; text-align: center; font-size: 1.5rem; font-weight: 800;'>
⚕ {t('system_ai')}
</h2>
<div style='background: rgba(255,255,255,0.15); padding: 15px; border-radius: 12px; margin-top: 15px;'>
<div style='display: flex; justify-content: space-between; margin-bottom: 12px;'>
<span style='font-weight: 600;'>▣ {t('device')}</span>
<span style='background: rgba(255,255,255,0.25); padding: 4px 12px; border-radius: 6px; font-weight: 700;'>{DEVICE.upper()}</span>
</div>
<div style='display: flex; justify-content: space-between;'>
<span style='font-weight: 600;'>▣ {t('status')}</span>
<span style='background: {status_bg}; padding: 4px 12px; border-radius: 6px; font-weight: 700;'>{status_text}</span>
</div>
</div>
</div>
""", unsafe_allow_html=True)
# Quick Guide with icons
st.markdown(f"""
<div style='
background: linear-gradient(135deg, rgba(76,175,80,0.1) 0%, rgba(56,142,60,0.05) 100%);
padding: 20px;
border-radius: 12px;
border: 2px solid rgba(76,175,80,0.3);
margin-bottom: 20px;
'>
<h3 style='color: #2E7D32; margin: 0 0 18px 0; text-align: center; font-weight: 800; font-size: 1.15rem;'>
{t('guide_title')}
</h3>
<div style='color: #2E7D32; line-height: 1.9;'>
<div style='margin: 10px 0; display: flex; align-items: flex-start;'>
<span style='background: #4CAF50; color: white; padding: 4px 10px; border-radius: 50%; margin-right: 12px; font-weight: 700; font-size: 0.9rem;'>①</span>
<span style='font-weight: 600;'>{t('guide_step1')}</span>
</div>
<div style='margin: 10px 0; display: flex; align-items: flex-start;'>
<span style='background: #4CAF50; color: white; padding: 4px 10px; border-radius: 50%; margin-right: 12px; font-weight: 700; font-size: 0.9rem;'>②</span>
<span style='font-weight: 600;'>{t('guide_step2')}</span>
</div>
<div style='margin: 10px 0; display: flex; align-items: flex-start;'>
<span style='background: #4CAF50; color: white; padding: 4px 10px; border-radius: 50%; margin-right: 12px; font-weight: 700; font-size: 0.9rem;'>③</span>
<span style='font-weight: 600;'>{t('guide_step3')}</span>
</div>
<div style='margin: 10px 0; display: flex; align-items: flex-start;'>
<span style='background: #4CAF50; color: white; padding: 4px 10px; border-radius: 50%; margin-right: 12px; font-weight: 700; font-size: 0.9rem;'>④</span>
<span style='font-weight: 600;'>{t('guide_step4')}</span>
</div>
</div>
</div>
""", unsafe_allow_html=True)
# Statistics card
st.markdown(f"""
<div style='
background: linear-gradient(135deg, rgba(255,152,0,0.1) 0%, rgba(245,124,0,0.05) 100%);
padding: 20px;
border-radius: 12px;
border: 2px solid rgba(255,152,0,0.3);
margin-bottom: 20px;
'>
<h3 style='color: #E65100; margin: 0 0 18px 0; text-align: center; font-weight: 800; font-size: 1.15rem;'>
{t('model_info')}
</h3>
<div style='color: #E65100; font-weight: 600; line-height: 1.9;'>
<div style='margin: 10px 0; padding: 10px; background: rgba(255,255,255,0.5); border-radius: 8px;'>
<span style='opacity: 0.8;'>{t('model_version')}:</span> <span style='float: right; font-weight: 800;'>3.0</span>
</div>
<div style='margin: 10px 0; padding: 10px; background: rgba(255,255,255,0.5); border-radius: 8px;'>
<span style='opacity: 0.8;'>{t('architecture')}:</span> <span style='float: right; font-weight: 800;'>HybridViT</span>
</div>
<div style='margin: 10px 0; padding: 10px; background: rgba(255,255,255,0.5); border-radius: 8px;'>
<span style='opacity: 0.8;'>{t('dataset')}:</span> <span style='float: right; font-weight: 800;'>ISIC 2018</span>
</div>
<div style='margin: 10px 0; padding: 10px; background: rgba(255,255,255,0.5); border-radius: 8px;'>
<span style='opacity: 0.8;'>{t('accuracy')}:</span> <span style='float: right; font-weight: 800;'>85%+</span>
</div>