Pro-Coder commited on
Commit
148a8ea
·
verified ·
1 Parent(s): a9204bf

Delete app.py

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