Pro-Coder commited on
Commit
14562b5
·
verified ·
1 Parent(s): 704e821

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -210
app.py DELETED
@@ -1,210 +0,0 @@
1
- """
2
- Skin Disease Detection — Demo
3
- ------------------------------
4
- A Gradio app for Hugging Face Spaces with two tabs:
5
- 1. Image Diagnosis — upload (or pick a test image) and get a classifier
6
- prediction plus a plain-language, LLM-generated explanation.
7
- 2. Chat Assistant — a cautious chatbot that discusses skin-health topics
8
- in general terms.
9
-
10
- IMPORTANT: This is an educational / demo tool only. It is NOT a medical
11
- device and does NOT provide real diagnoses. See DISCLAIMER below.
12
- """
13
-
14
- import os
15
-
16
- import gradio as gr
17
- import spaces
18
- from transformers import pipeline
19
- from huggingface_hub import InferenceClient
20
-
21
- # ---------------------------------------------------------------------------
22
- # Config — override any of these via Space "Variables and secrets"
23
- # ---------------------------------------------------------------------------
24
- IMAGE_MODEL_ID = os.environ.get("IMAGE_MODEL_ID", "Anwarkh1/Skin_Cancer-Image_Classification")
25
- CHAT_MODEL_ID = os.environ.get("CHAT_MODEL_ID", "HuggingFaceH4/zephyr-7b-beta")
26
- HF_TOKEN = os.environ.get("HF_TOKEN") # add as a Space SECRET to enable the chatbot
27
-
28
- DISCLAIMER = (
29
- "⚠️ **Demo only — not a medical device.** This tool does not provide a real "
30
- "diagnosis. Always consult a licensed dermatologist or doctor about any skin concern, "
31
- "especially a spot that is new, changing, bleeding, or growing."
32
- )
33
-
34
- # Friendly descriptions for the HAM10000-style label set used by the default model
35
- CLASS_INFO = {
36
- "actinic keratoses": "A rough, scaly patch caused by sun damage; can occasionally progress to skin cancer if untreated.",
37
- "basal cell carcinoma": "The most common type of skin cancer; usually slow-growing and rarely spreads.",
38
- "benign keratosis-like lesions": "Non-cancerous growths such as seborrheic keratoses or solar lentigines.",
39
- "dermatofibroma": "A common benign skin nodule, often on the legs; usually harmless.",
40
- "melanocytic nevi": "Ordinary moles; almost always benign.",
41
- "melanoma": "The most serious type of skin cancer; early evaluation matters.",
42
- "vascular lesions": "Blood-vessel-related marks such as angiomas; usually benign.",
43
- }
44
-
45
- SYSTEM_PROMPT = (
46
- "You are a friendly, cautious skin-health assistant inside a DEMO application. "
47
- "You are NOT a doctor and must never claim to diagnose anyone. "
48
- "You can explain general skin-condition concepts, explain what classifier labels mean, "
49
- "and encourage users to see a licensed dermatologist for anything concerning. "
50
- "Never give a definitive diagnosis, never prescribe treatment or dosages. "
51
- "If a user describes an urgent symptom (rapid growth, bleeding, severe pain, sudden "
52
- "changes to a mole), tell them to seek in-person medical care promptly. "
53
- "Keep answers concise — 3 to 6 sentences."
54
- )
55
-
56
- # ---------------------------------------------------------------------------
57
- # Lazy-loaded models (so the Space boots fast and only loads on first use)
58
- # ---------------------------------------------------------------------------
59
- _classifier = None
60
-
61
-
62
- def get_classifier():
63
- global _classifier
64
- if _classifier is None:
65
- import torch
66
-
67
- device = 0 if torch.cuda.is_available() else -1
68
- _classifier = pipeline("image-classification", model=IMAGE_MODEL_ID, device=device)
69
- return _classifier
70
-
71
-
72
- def get_chat_client():
73
- if not HF_TOKEN:
74
- return None
75
- return InferenceClient(model=CHAT_MODEL_ID, token=HF_TOKEN)
76
-
77
-
78
- # ---------------------------------------------------------------------------
79
- # Image diagnosis tab
80
- # ---------------------------------------------------------------------------
81
- @spaces.GPU
82
- def diagnose_image(image):
83
- """Run the image classifier and, if a chat model is configured, ask it
84
- for a short plain-language explanation of the top prediction."""
85
- if image is None:
86
- return "Please upload an image or pick one of the test images first."
87
-
88
- try:
89
- clf = get_classifier()
90
- preds = clf(image, top_k=5)
91
- except Exception as e:
92
- return f"**Model error:** {e}\n\nMake sure `IMAGE_MODEL_ID` is a valid image-classification model."
93
-
94
- lines = ["### 🔬 Classifier prediction (demo only — not a real diagnosis)\n"]
95
- for p in preds:
96
- label = p["label"]
97
- score = p["score"] * 100
98
- info = CLASS_INFO.get(label.lower(), "")
99
- info_txt = f" \n _{info}_" if info else ""
100
- lines.append(f"- **{label}** — {score:.1f}%{info_txt}")
101
-
102
- client = get_chat_client()
103
- if client is not None:
104
- top = preds[0]["label"]
105
- others = ", ".join(p["label"] for p in preds[1:3])
106
- prompt = (
107
- f"An image classifier in a DEMO app predicted the top possible skin-lesion "
108
- f"category as '{top}' ({preds[0]['score']*100:.1f}% confidence), with other "
109
- f"candidates including {others}. In 3-4 short, plain-language sentences, explain "
110
- f"generally what the top category means, make clear this is not a diagnosis, and "
111
- f"suggest seeing a dermatologist, especially if the spot is new, changing, or bleeding."
112
- )
113
- try:
114
- resp = client.chat_completion(
115
- messages=[
116
- {"role": "system", "content": SYSTEM_PROMPT},
117
- {"role": "user", "content": prompt},
118
- ],
119
- max_tokens=250,
120
- )
121
- explanation = resp.choices[0].message.content
122
- lines.append(f"\n### 🤖 Assistant explanation\n{explanation}")
123
- except Exception as e:
124
- lines.append(f"\n_(Chat explanation unavailable: {e})_")
125
- else:
126
- lines.append(
127
- "\n_Add an `HF_TOKEN` secret to this Space to also get a plain-language "
128
- "explanation from the chat model here._"
129
- )
130
-
131
- lines.append(f"\n---\n{DISCLAIMER}")
132
- return "\n".join(lines)
133
-
134
-
135
- # ---------------------------------------------------------------------------
136
- # Chat tab
137
- # ---------------------------------------------------------------------------
138
- def chat_respond(message, history):
139
- client = get_chat_client()
140
- if client is None:
141
- return (
142
- "⚠️ Chat isn't configured yet. Add an `HF_TOKEN` secret to this Space "
143
- "(Settings → Variables and secrets) to enable the chatbot."
144
- )
145
-
146
- messages = [{"role": "system", "content": SYSTEM_PROMPT}]
147
- for turn in history:
148
- # supports both the legacy (user, bot) tuple format and the
149
- # newer {"role": ..., "content": ...} messages format
150
- if isinstance(turn, dict):
151
- messages.append(turn)
152
- else:
153
- user_msg, bot_msg = turn
154
- messages.append({"role": "user", "content": user_msg})
155
- if bot_msg:
156
- messages.append({"role": "assistant", "content": bot_msg})
157
- messages.append({"role": "user", "content": message})
158
-
159
- try:
160
- resp = client.chat_completion(messages=messages, max_tokens=400)
161
- return resp.choices[0].message.content
162
- except Exception as e:
163
- return f"Sorry, I hit an error talking to the model: {e}"
164
-
165
-
166
- # ---------------------------------------------------------------------------
167
- # UI
168
- # ---------------------------------------------------------------------------
169
- EXAMPLES_DIR = "examples"
170
- example_images = []
171
- if os.path.isdir(EXAMPLES_DIR):
172
- example_images = [
173
- os.path.join(EXAMPLES_DIR, f)
174
- for f in sorted(os.listdir(EXAMPLES_DIR))
175
- if f.lower().endswith((".jpg", ".jpeg", ".png"))
176
- ]
177
-
178
- with gr.Blocks(title="Skin Disease Detection — Demo") as demo:
179
- gr.Markdown("# 🩺 Skin Disease Detection — Demo")
180
- gr.Markdown(DISCLAIMER)
181
-
182
- with gr.Tab("📷 Image Diagnosis"):
183
- with gr.Row():
184
- with gr.Column():
185
- img_in = gr.Image(type="pil", label="Upload a skin image")
186
- if example_images:
187
- gr.Examples(examples=example_images, inputs=img_in, label="Or try a test image")
188
- else:
189
- gr.Markdown(
190
- "_No bundled test images found. Run `scripts/download_examples.py` "
191
- "before deploying, or just upload your own image._"
192
- )
193
- analyze_btn = gr.Button("Analyze image", variant="primary")
194
- with gr.Column():
195
- result_md = gr.Markdown()
196
- analyze_btn.click(diagnose_image, inputs=img_in, outputs=result_md)
197
-
198
- with gr.Tab("💬 Chat Assistant"):
199
- gr.ChatInterface(
200
- fn=chat_respond,
201
- description="Ask general questions about skin conditions. " + DISCLAIMER,
202
- )
203
-
204
- gr.Markdown(
205
- "---\nBuilt with 🤗 Transformers + Gradio. "
206
- f"Image model: `{IMAGE_MODEL_ID}` · Chat model: `{CHAT_MODEL_ID}`"
207
- )
208
-
209
- if __name__ == "__main__":
210
- demo.launch()