Knowcer / src /app.py
lp128396's picture
Update src/app.py
c455afd verified
import os
# Forcefully override Hugging Face cache directory
os.environ["HF_HOME"] = "/tmp/huggingface"
os.environ["XDG_CACHE_HOME"] = "/tmp/.cache"
os.environ["STREAMLIT_HOME"] = "/tmp/.streamlit"
import streamlit as st
import pandas as pd
import tensorflow as tf
from tensorflow.keras.models import load_model
from PIL import Image
import numpy as np
from huggingface_hub import hf_hub_download
st.title("lung cancer detection")
st.write("Upload an image of a lung X-ray to detect lung cancer.")
# Download model from Hugging Face model hub
model_path = hf_hub_download(
repo_id="lp128396/lung_cancer_model", # 👈 replace with your actual username and repo
filename="lung_cancer_model.keras",
cache_dir=os.getenv("HF_HOME")
)
model = tf.keras.models.load_model(model_path)
#model = load_model('lung_cancer_model.keras')
#for uploading a image
img = st.file_uploader("Choose a image file", type=["jpg", "jpeg", "png","webp"])
# Check if an image file is uploaded
if img is not None and img.name.endswith(('jpg', 'jpeg', 'png','webp')):
# Display the image
image = Image.open(img)
st.image(image, caption='Uploaded Image', use_container_width=True)
# --- Image preprocessing steps ---
image = image.resize((256, 256)) # replace with your model’s input size
image_array = np.array(image)
#🎯 Optional: Auto-detect input size
#You can dynamically get the expected input shape like this:
#input_size = model.input_shape[1:3] # (height, width)
#Image = image.resize(input_size)
if image_array.shape[-1] == 4: # RGBA to RGB
image_array = image_array[:, :, :3]
image_array = image_array / 255.0 # normalize if model was trained on normalized images
image_array = np.expand_dims(image_array, axis=0) # add batch dimension
class_name_map = {
"lung_acc": "Adenocarcinoma (Cancerous)",
"lung_n": "Normal (Non-Cancerous)",
"lung_scc": "Squamous Carcinoma (Cancerous)"
}
# List must match order in which the model was trained
original_class_names = ["lung_acc", "lung_n", "lung_scc"]
# Make prediction
prediction = model.predict(image_array)
predicted_class = np.argmax(prediction)
predicted_key = original_class_names[predicted_class]
predicted_label = class_name_map[predicted_key]
# Show result
st.success(f"Prediction: {predicted_label} (Confidence: {prediction[0][predicted_class]:.2f})")
else:
st.info("📷 Upload a lung microscope image to get started.")