File size: 2,437 Bytes
a00518a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import tensorflow as tf
import numpy as np
from PIL import Image
import os
import google.generativeai as genai  # ✅ Gemini API

# ---------------- Load model ----------------
MODEL_PATH = "final_model.h5"
if not os.path.exists(MODEL_PATH):
    raise FileNotFoundError(f"{MODEL_PATH} not found. Place your trained model in the project folder.")

model = tf.keras.models.load_model(MODEL_PATH)

# ---------------- Gemini API ----------------
# 1. Go to https://aistudio.google.com/app/apikey to create a FREE API key
# 2. Replace below with your API key
GEMINI_API_KEY = "AIzaSyC6LKYAB5F1B_j3BOBVFB9xt1-rPbZIMF0"  
genai.configure(api_key=GEMINI_API_KEY)

gemini_model = genai.GenerativeModel("gemini-1.5-flash")  # ✅ Free, fast model

# ---------------- Prediction + Explanation ----------------
def predict_and_explain(image):
    # Preprocess image
    img = image.resize((224, 224))  # Adjust if your model uses a different size
    img_array = np.array(img) / 255.0
    img_array = np.expand_dims(img_array, axis=0)
    
    # Predict
    prediction = model.predict(img_array)[0][0]
    if prediction > 0.5:
        result = f"🟥 Malignant (Cancer Detected) with {prediction*100:.2f}% confidence"
        prompt = "Explain in simple terms to a patient what it means that this skin lesion is Malignant."
    else:
        result = f"🟩 Benign (No Cancer) with {(1-prediction)*100:.2f}% confidence"
        prompt = "Explain in simple terms to a patient what it means that this skin lesion is Benign."
    
    # Generate explanation using Gemini
    explanation = "Explanation not available."
    try:
        response = gemini_model.generate_content(prompt)
        explanation = response.text
    except Exception as e:
        explanation = f"AI explanation failed: {e}"
    
    return result, explanation

# ---------------- Gradio UI ----------------
demo = gr.Interface(
    fn=predict_and_explain,
    inputs=gr.Image(type="pil", label="Upload Skin Lesion Image"),
    outputs=[gr.Textbox(label="Prediction"), gr.Textbox(label="Explanation")],
    title="🧬 Skin Cancer Detection with AI Explanation (Gemini)",
    description="Upload a skin lesion image. The model predicts if it is Malignant or Benign and explains the result in simple terms."
)

# ---------------- Launch ----------------
if __name__ == "__main__":
    demo.launch()