Spaces:
Runtime error
Runtime error
| 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() | |