File size: 6,537 Bytes
e8a9524
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
327b96a
e8a9524
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from flask import Flask, request, jsonify, render_template
from flask_cors import CORS
import os, io, tempfile, requests

import numpy as np
from PIL import Image
import cv2
import tensorflow as tf

import torch
from torchvision import models, transforms

# =======================
# LLaMA CPP (CPU FAST)
# =======================
from llama_cpp import Llama

# =====================
# APP CONFIG
# =====================
app = Flask(__name__)
CORS(app)

UPLOAD_FOLDER = "uploads"
os.makedirs(UPLOAD_FOLDER, exist_ok=True)

CLASS_LABELS = ["benign", "malignant", "normal"]
ALLOWED_EXT = {"jpg", "jpeg", "png"}

device = "cpu"

# =====================
# HUGGING FACE MODELS
# =====================
HF_BASE = "https://huggingface.co/mani880740255/skin_care_tflite/resolve/main/"

HF_MODELS = {
    "tflite": HF_BASE + "skin_model_quantized.tflite",
    "mobilenetv2": HF_BASE + "skin_cancer_mobilenetv2%20(1).h5",
    "b3": HF_BASE + "efficientnet_b3_skin_cancer.pth"
}

# =====================
# TINYLLAMA GGUF CONFIG
# =====================
LLM_PATH = "tinyllama-1.1b-chat-v1.0.Q2_K.gguf"

print("🔄 Loading TinyLlama GGUF (CPU)...")

llm = Llama(
    model_path=LLM_PATH,
    n_ctx=512,
    n_threads=4,
    n_batch=128,
    verbose=False
)

print("✅ TinyLlama loaded")

SYSTEM_PROMPT = (
    "You are a skin health assistant. "
    "Do not diagnose diseases. "
    "Explain in simple language. "
    "Give general precautions. "
    "Always recommend consulting a dermatologist. "
    "Add a medical disclaimer."
)

# =====================
# HELPERS
# =====================
def allowed_file(name):
    return "." in name and name.rsplit(".", 1)[1].lower() in ALLOWED_EXT


def download_file(url):
    r = requests.get(url)
    if r.status_code != 200:
        raise Exception(f"Model download failed: {url}")
    return io.BytesIO(r.content)

# =====================
# IMAGE MODELS
# =====================
def predict_tflite(img_path):
    model_bytes = download_file(HF_MODELS["tflite"])
    interpreter = tf.lite.Interpreter(model_content=model_bytes.read())
    interpreter.allocate_tensors()

    input_details = interpreter.get_input_details()
    output_details = interpreter.get_output_details()

    img = cv2.imread(img_path)
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    img = cv2.resize(img, (224, 224))
    img = img.astype("float32") / 255.0
    img = np.expand_dims(img, axis=0)

    interpreter.set_tensor(input_details[0]["index"], img)
    interpreter.invoke()

    preds = interpreter.get_tensor(output_details[0]["index"])[0]
    idx = int(np.argmax(preds))

    return CLASS_LABELS[idx], float(preds[idx]), preds.tolist()


def predict_keras(img_path):
    model_bytes = download_file(HF_MODELS["mobilenetv2"])

    with tempfile.NamedTemporaryFile(suffix=".h5", delete=False) as tmp:
        tmp.write(model_bytes.read())
        tmp_path = tmp.name

    try:
        model = tf.keras.models.load_model(tmp_path)

        img = Image.open(img_path).convert("RGB")
        img = img.resize((224, 224))
        img = np.array(img) / 255.0
        img = np.expand_dims(img, axis=0)

        preds = model.predict(img, verbose=0)[0]
        idx = int(np.argmax(preds))

        return CLASS_LABELS[idx], float(preds[idx]), preds.tolist()
    finally:
        os.remove(tmp_path)


def predict_b3(img_path):
    model_bytes = download_file(HF_MODELS["b3"])

    model = models.efficientnet_b3(weights=None)
    model.classifier[1] = torch.nn.Linear(1536, 3)

    with tempfile.NamedTemporaryFile(suffix=".pth", delete=False) as tmp:
        tmp.write(model_bytes.read())
        tmp_path = tmp.name

    try:
        model.load_state_dict(torch.load(tmp_path, map_location="cpu"))
        model.eval()

        transform = transforms.Compose([
            transforms.Resize((300, 300)),
            transforms.ToTensor()
        ])

        img = Image.open(img_path).convert("RGB")
        img = transform(img).unsqueeze(0)

        with torch.no_grad():
            out = model(img)
            probs = torch.softmax(out, dim=1)[0]

        idx = int(torch.argmax(probs))
        return CLASS_LABELS[idx], float(probs[idx]), probs.tolist()
    finally:
        os.remove(tmp_path)

# =====================
# CHATBOT (FAST)
# =====================
def llm_chat_response(user_message, prediction=None, confidence=None):

    context = ""
    if prediction and confidence:
        context = f"AI result: {prediction} ({confidence*100:.1f}%)."

    prompt = f"""
<|system|>
{SYSTEM_PROMPT}
{context}

<|user|>
{user_message}

<|assistant|>
"""

    output = llm(
        prompt,
        max_tokens=120,
        temperature=0.2,
        top_p=0.9,
        stop=["<|user|>"]
    )

    return output["choices"][0]["text"].strip()

# =====================
# ROUTES
# =====================
@app.route("/")
def home():
    return render_template("index.html")


@app.route("/predict", methods=["POST"])
def predict():
    if "image" not in request.files or "model" not in request.form:
        return jsonify({"error": "image + model required"}), 400

    model_choice = request.form["model"]
    file = request.files["image"]

    if model_choice not in HF_MODELS or not allowed_file(file.filename):
        return jsonify({"error": "invalid model or file"}), 400

    path = os.path.join(UPLOAD_FOLDER, file.filename)
    file.save(path)

    try:
        if model_choice == "tflite":
            pred, conf, probs = predict_tflite(path)
        elif model_choice == "mobilenetv2":
            pred, conf, probs = predict_keras(path)
        else:
            pred, conf, probs = predict_b3(path)

        return jsonify({
            "model_used": model_choice,
            "prediction": pred,
            "confidence": conf,
            "probabilities": {
                CLASS_LABELS[i]: probs[i] for i in range(3)
            }
        })
    finally:
        os.remove(path)


@app.route("/chat", methods=["POST"])
def chat():
    data = request.get_json()
    user_msg = data.get("message", "").strip()

    if not user_msg:
        return jsonify({"reply": "Please ask a skin health related question."})

    reply = llm_chat_response(
        user_msg,
        data.get("prediction"),
        data.get("confidence")
    )

    return jsonify({
        "reply": reply,
        "disclaimer": "⚠️ This chatbot is for educational purposes only and not a medical diagnosis."
    })

# =====================
# LOCAL RUN
# =====================
if __name__ == "__main__":
    app.run(host="0.0.0.0", port=7860)