SuriRaja commited on
Commit
2580458
Β·
verified Β·
1 Parent(s): 35642b7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +37 -27
app.py CHANGED
@@ -3,29 +3,30 @@
3
  import gradio as gr
4
  from PIL import Image
5
  import torch
 
6
  from transformers import AutoImageProcessor, AutoModelForImageClassification
7
 
8
- # Load model and processor
9
  model_name = "Anwarkh1/Skin_Cancer-Image_Classification"
10
  processor = AutoImageProcessor.from_pretrained(model_name)
11
  model = AutoModelForImageClassification.from_pretrained(model_name)
12
  label_map = model.config.id2label
13
 
14
- # Descriptions for each class
15
  condition_info = {
16
- "actinic keratoses": "Precancerous rough, scaly patches on sun-exposed skin.",
17
- "basal cell carcinoma": "Common skin cancer, slow-growing and rarely spreads.",
18
- "benign keratosis-like lesions": "Non-cancerous growths, may resemble warts or sun spots.",
19
- "dermatofibroma": "Harmless small bumps often on legs, firm to the touch.",
20
- "melanocytic nevi": "Common moles, generally benign unless changing in shape/size.",
21
- "melanoma": "Serious skin cancer; early detection is critical.",
22
- "vascular lesions": "Birthmarks or red/purple patches from abnormal blood vessels."
23
  }
24
 
25
- # Prediction logic
26
  def classify_skin(image: Image.Image):
27
  if image is None:
28
- return "Please upload or capture an image.", "", ""
29
 
30
  image = image.convert("RGB")
31
  inputs = processor(images=image, return_tensors="pt")
@@ -35,33 +36,42 @@ def classify_skin(image: Image.Image):
35
  logits = outputs.logits
36
  probs = torch.nn.functional.softmax(logits, dim=1)[0]
37
 
38
- # Prepare full result table
39
  threshold = 0.40
40
- result_table = ""
41
- summary = []
 
42
  for idx, prob in enumerate(probs):
43
  label = label_map[idx]
44
- confidence = prob.item()
45
- status = "βœ… Positive" if confidence > threshold else "❌ Negative"
46
- desc = condition_info.get(label.lower(), "No description.")
47
- result_table += f"**{label.capitalize()}**: {confidence * 100:.2f}% β€” {status}\n> {desc}\n\n"
48
- if confidence > threshold:
49
- summary.append(label.capitalize())
 
 
 
 
 
 
 
 
 
 
 
50
 
51
- final_summary = "πŸ” **Likely Condition(s):** " + (", ".join(summary) if summary else "None detected above threshold.")
52
- return result_table, final_summary, "⚠️ This tool is not a diagnosis. Always consult a certified dermatologist."
53
 
54
- # Gradio interface
55
  demo = gr.Interface(
56
  fn=classify_skin,
57
  inputs=gr.Image(type="pil", label="πŸ“· Upload or Capture Skin Image"),
58
  outputs=[
59
- gr.Markdown(label="πŸ”¬ Detailed Predictions"),
60
- gr.Textbox(label="🧾 Summary"),
61
- gr.Textbox(label="Disclaimer", max_lines=2)
62
  ],
63
  title="AI Skin Condition Classifier",
64
- description="Upload or take a photo of a skin condition to get predictions using a pre-trained AI model. Powered by Hugging Face Transformers."
65
  )
66
 
67
  if __name__ == "__main__":
 
3
  import gradio as gr
4
  from PIL import Image
5
  import torch
6
+ import pandas as pd
7
  from transformers import AutoImageProcessor, AutoModelForImageClassification
8
 
9
+ # Load model
10
  model_name = "Anwarkh1/Skin_Cancer-Image_Classification"
11
  processor = AutoImageProcessor.from_pretrained(model_name)
12
  model = AutoModelForImageClassification.from_pretrained(model_name)
13
  label_map = model.config.id2label
14
 
15
+ # Skin condition descriptions (simple language)
16
  condition_info = {
17
+ "actinic keratoses": "Dry, rough patch – sometimes early sign of skin cancer.",
18
+ "basal cell carcinoma": "Slow-growing skin cancer. Common but treatable.",
19
+ "benign keratosis-like lesions": "Non-cancerous growth. Like age spots or warts.",
20
+ "dermatofibroma": "Small, firm bump. Usually harmless.",
21
+ "melanocytic nevi": "Just a mole. Normal unless changing.",
22
+ "melanoma": "Dangerous skin cancer. Needs fast treatment.",
23
+ "vascular lesions": "Red or purple patches from blood vessels."
24
  }
25
 
26
+ # AI logic
27
  def classify_skin(image: Image.Image):
28
  if image is None:
29
+ return pd.DataFrame(), "Please upload or take a photo."
30
 
31
  image = image.convert("RGB")
32
  inputs = processor(images=image, return_tensors="pt")
 
36
  logits = outputs.logits
37
  probs = torch.nn.functional.softmax(logits, dim=1)[0]
38
 
 
39
  threshold = 0.40
40
+ data = []
41
+ likely_conditions = []
42
+
43
  for idx, prob in enumerate(probs):
44
  label = label_map[idx]
45
+ conf = prob.item()
46
+ status = "βœ… Positive" if conf > threshold else "❌ Negative"
47
+ data.append({
48
+ "Condition": label.capitalize(),
49
+ "Confidence (%)": f"{conf*100:.2f}",
50
+ "Status": status,
51
+ "What it means": condition_info[label.lower()]
52
+ })
53
+ if conf > threshold:
54
+ likely_conditions.append(label.capitalize())
55
+
56
+ df = pd.DataFrame(data)
57
+ summary_text = (
58
+ "🧾 **Summary:** " +
59
+ (", ".join(likely_conditions) if likely_conditions else "No major concern seen by AI.") +
60
+ "\n\nπŸ“’ Please check with a real doctor for correct diagnosis."
61
+ )
62
 
63
+ return df, summary_text
 
64
 
65
+ # Gradio Interface
66
  demo = gr.Interface(
67
  fn=classify_skin,
68
  inputs=gr.Image(type="pil", label="πŸ“· Upload or Capture Skin Image"),
69
  outputs=[
70
+ gr.Dataframe(headers=["Condition", "Confidence (%)", "Status", "What it means"]),
71
+ gr.Markdown()
 
72
  ],
73
  title="AI Skin Condition Classifier",
74
+ description="Upload a photo of a skin issue. The AI will check 7 common conditions and suggest what looks likely. For support only β€” not a replacement for a real doctor."
75
  )
76
 
77
  if __name__ == "__main__":