shivakumar4147 commited on
Commit
bff9d29
Β·
verified Β·
1 Parent(s): 486eab0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +73 -40
app.py CHANGED
@@ -1,40 +1,73 @@
1
- import gradio as gr
2
- import tensorflow as tf
3
- import numpy as np
4
- from PIL import Image
5
-
6
- # ---------- Load your trained model ----------
7
- model = tf.keras.models.load_model("final_model.h5")
8
-
9
- # ---------- Prediction function ----------
10
- def predict(image):
11
- # Resize the input image to the size your model expects (update if different)
12
- img = image.resize((224, 224)) # change size if your model was trained differently
13
- img_array = np.array(img) / 255.0 # normalize
14
-
15
- # Expand dimensions for batch
16
- img_array = np.expand_dims(img_array, axis=0)
17
-
18
- # Predict
19
- prediction = model.predict(img_array)[0][0] # assumes binary classification
20
-
21
- # Convert probability to label
22
- if prediction > 0.5:
23
- result = f"πŸŸ₯ Malignant (Cancer Detected) with {prediction*100:.2f}% confidence"
24
- else:
25
- result = f"🟩 Benign (No Cancer) with {(1-prediction)*100:.2f}% confidence"
26
-
27
- return result
28
-
29
- # ---------- Define Gradio UI ----------
30
- demo = gr.Interface(
31
- fn=predict,
32
- inputs=gr.Image(type="pil", label="Upload Skin Lesion Image"),
33
- outputs=gr.Textbox(label="Prediction"),
34
- title="🧬 Skin Cancer Detection",
35
- description="Upload a skin lesion image and the model will predict whether it is Benign or Malignant."
36
- )
37
-
38
- # ---------- Launch ----------
39
- if __name__ == "__main__":
40
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import tensorflow as tf
3
+ import numpy as np
4
+ from PIL import Image
5
+ import os
6
+ import google.generativeai as genai # βœ… Gemini API
7
+
8
+ # ---------------- Load Model ----------------
9
+ MODEL_PATH = "final_model.h5"
10
+ if not os.path.exists(MODEL_PATH):
11
+ raise FileNotFoundError(
12
+ f"{MODEL_PATH} not found. Please upload your trained model (final_model.h5)."
13
+ )
14
+
15
+ # Load Keras model
16
+ model = tf.keras.models.load_model(MODEL_PATH)
17
+
18
+ # ---------------- Gemini API ----------------
19
+ # 1. Get a free API key: https://aistudio.google.com/app/apikey
20
+ # 2. On Hugging Face, store your key as a secret:
21
+ # Settings β†’ Repository secrets β†’ Add "GEMINI_API_KEY"
22
+ GEMINI_API_KEY = os.getenv("AIzaSyC6LKYAB5F1B_j3BOBVFB9xt1-rPbZIMF0") # βœ… safer than hardcoding
23
+
24
+ if GEMINI_API_KEY:
25
+ genai.configure(api_key=GEMINI_API_KEY)
26
+ gemini_model = genai.GenerativeModel("gemini-1.5-flash") # βœ… Free, fast model
27
+ else:
28
+ gemini_model = None
29
+ print("⚠️ Warning: GEMINI_API_KEY not set. Explanations will be skipped.")
30
+
31
+ # ---------------- Prediction + Explanation ----------------
32
+ def predict_and_explain(image: Image.Image):
33
+ # Preprocess image for model
34
+ img = image.resize((224, 224)) # Adjust to your training input size
35
+ img_array = np.array(img) / 255.0
36
+ img_array = np.expand_dims(img_array, axis=0)
37
+
38
+ # Model prediction
39
+ prediction = model.predict(img_array, verbose=0)[0][0]
40
+
41
+ if prediction > 0.5:
42
+ result = f"πŸŸ₯ Malignant (Cancer Detected) β€” Confidence: {prediction*100:.2f}%"
43
+ prompt = "Explain in simple terms to a patient what it means that this skin lesion is malignant."
44
+ else:
45
+ result = f"🟩 Benign (No Cancer) β€” Confidence: {(1-prediction)*100:.2f}%"
46
+ prompt = "Explain in simple terms to a patient what it means that this skin lesion is benign."
47
+
48
+ # Generate explanation with Gemini
49
+ explanation = "⚠️ Gemini explanation not available (API key missing)."
50
+ if gemini_model:
51
+ try:
52
+ response = gemini_model.generate_content(prompt)
53
+ explanation = response.text
54
+ except Exception as e:
55
+ explanation = f"⚠️ AI explanation failed: {str(e)}"
56
+
57
+ return result, explanation
58
+
59
+ # ---------------- Gradio UI ----------------
60
+ demo = gr.Interface(
61
+ fn=predict_and_explain,
62
+ inputs=gr.Image(type="pil", label="πŸ“€ Upload Skin Lesion Image"),
63
+ outputs=[
64
+ gr.Textbox(label="πŸ”Ž Prediction", interactive=False),
65
+ gr.Textbox(label="πŸ“– Explanation (AI-powered)", interactive=False),
66
+ ],
67
+ title="🧬 Skin Cancer Detection with AI Explanation (Gemini)",
68
+ description="Upload a skin lesion image. The model predicts if it is **Malignant** or **Benign** and Gemini explains the result in simple terms.",
69
+ )
70
+
71
+ # ---------------- Launch ----------------
72
+ if __name__ == "__main__":
73
+ demo.launch()