sheikh987 commited on
Commit
de8dfff
·
verified ·
1 Parent(s): e6fb44c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +78 -20
app.py CHANGED
@@ -1,42 +1,100 @@
 
1
  import torch
2
- import timm
 
 
3
  from huggingface_hub import hf_hub_download
4
- import gradio as gr
 
5
 
6
  DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
7
 
8
- # Repo iyo filename sax ah
9
  CLASS_REPO_ID = "sheikh987/efficientnet-b3-skin"
10
  CLASS_MODEL_FILENAME = "efficientnet_b3_skin_model.pth"
 
11
 
12
- # Download model-ka Hugging Face hub
13
  try:
14
  class_model_path = hf_hub_download(
15
  repo_id=CLASS_REPO_ID,
16
  filename=CLASS_MODEL_FILENAME,
17
- cache_dir="/tmp" # important in Spaces
18
  )
19
- print(f"✅ Model downloaded to: {class_model_path}")
20
- except Exception as e:
21
- raise gr.Error(f"Failed to download model: {e}")
22
-
23
- # Auto-detect state_dict vs full model
24
- try:
25
  checkpoint = torch.load(class_model_path, map_location=DEVICE)
26
-
 
27
  if isinstance(checkpoint, dict):
28
- # state_dict case
29
  classification_model = timm.create_model(
30
- 'efficientnet_b3', pretrained=False, num_classes=7
31
  ).to(DEVICE)
32
- classification_model.load_state_dict(checkpoint)
33
- print("✅ Loaded as state_dict")
34
  else:
35
- # full model case
36
  classification_model = checkpoint.to(DEVICE)
37
- print("✅ Loaded as full model")
38
 
39
  classification_model.eval()
40
- print("✅ Classification model is ready.")
 
41
  except Exception as e:
42
- raise gr.Error(f"Failed to load classification model: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
  import torch
3
+ from PIL import Image
4
+ import numpy as np
5
+ import json
6
  from huggingface_hub import hf_hub_download
7
+ import timm
8
+ from torchvision import transforms
9
 
10
  DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
11
 
12
+ # --- Download and Load Classification Model (EfficientNet-B3) ---
13
  CLASS_REPO_ID = "sheikh987/efficientnet-b3-skin"
14
  CLASS_MODEL_FILENAME = "efficientnet_b3_skin_model.pth"
15
+ NUM_CLASSES = 7
16
 
 
17
  try:
18
  class_model_path = hf_hub_download(
19
  repo_id=CLASS_REPO_ID,
20
  filename=CLASS_MODEL_FILENAME,
21
+ cache_dir="/tmp"
22
  )
 
 
 
 
 
 
23
  checkpoint = torch.load(class_model_path, map_location=DEVICE)
24
+
25
+ # Auto-detect state_dict vs full model
26
  if isinstance(checkpoint, dict):
 
27
  classification_model = timm.create_model(
28
+ 'efficientnet_b3', pretrained=False, num_classes=NUM_CLASSES
29
  ).to(DEVICE)
30
+ classification_model.load_state_dict(checkpoint, strict=False)
 
31
  else:
 
32
  classification_model = checkpoint.to(DEVICE)
 
33
 
34
  classification_model.eval()
35
+ print("✅ Classification model loaded successfully.")
36
+
37
  except Exception as e:
38
+ raise gr.Error(f"Failed to load the classification model: {e}")
39
+
40
+
41
+ # --- Load Knowledge Base ---
42
+ try:
43
+ with open('knowledge_base.json', 'r') as f:
44
+ knowledge_base = json.load(f)
45
+ except FileNotFoundError:
46
+ raise gr.Error("knowledge_base.json not found. Upload it to the Space.")
47
+
48
+ idx_to_class_abbr = {0: 'MEL', 1: 'NV', 2: 'BCC', 3: 'AKIEC', 4: 'BKL', 5: 'DF', 6: 'VASC'}
49
+
50
+ # --- Image Transform ---
51
+ transform_classify = transforms.Compose([
52
+ transforms.Resize((300, 300)),
53
+ transforms.ToTensor(),
54
+ transforms.Normalize(mean=[0.485, 0.456, 0.406],
55
+ std=[0.229, 0.224, 0.225]),
56
+ ])
57
+
58
+
59
+ # --- Pipeline Function ---
60
+ def classify_image(input_image):
61
+ if input_image is None:
62
+ return None, "Please upload an image."
63
+
64
+ class_input_tensor = transform_classify(input_image).unsqueeze(0).to(DEVICE)
65
+
66
+ with torch.no_grad():
67
+ logits = classification_model(class_input_tensor)
68
+ probs = torch.nn.functional.softmax(logits, dim=1)
69
+
70
+ confidence, predicted_idx = torch.max(probs, 1)
71
+ confidence_percent = confidence.item() * 100
72
+ predicted_abbr = idx_to_class_abbr[predicted_idx.item()]
73
+ info = knowledge_base.get(predicted_abbr, {})
74
+
75
+ # Build output
76
+ info_text = (
77
+ f"**Predicted Condition:** {info.get('full_name', 'N/A')} ({predicted_abbr})\n"
78
+ f"**Confidence:** {confidence_percent:.2f}%\n\n"
79
+ f"**Description:**\n{info.get('description', 'No description available.')}\n\n"
80
+ f"**Common Causes:**\n" + "\n".join([f"• {c}" for c in info.get('causes', ['N/A'])]) + "\n\n"
81
+ f"**Common Treatments:**\n" + "\n".join([f"• {t}" for t in info.get('common_treatments', ['N/A'])]) + "\n\n"
82
+ f"**--- IMPORTANT DISCLAIMER ---**\n{info.get('disclaimer', '')}"
83
+ )
84
+
85
+ return input_image, info_text
86
+
87
+
88
+ # --- Gradio Interface ---
89
+ iface = gr.Interface(
90
+ fn=classify_image,
91
+ inputs=gr.Image(type="pil", label="Upload Skin Image"),
92
+ outputs=[gr.Image(type="pil", label="Input Image"),
93
+ gr.Markdown(label="Analysis Result")],
94
+ title="AI Skin Lesion Classifier",
95
+ description="Upload a skin lesion image and the AI EfficientNet-B3 model will classify it.\n\n"
96
+ "**DISCLAIMER:** This is NOT a diagnosis. Always consult a qualified dermatologist."
97
+ )
98
+
99
+ if __name__ == "__main__":
100
+ iface.launch()