Spaces:
Runtime error
Runtime error
Update src/streamlit_app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136import streamlit as stimport numpy as npimport cv2import osimport sysfrom PIL import Imageimport traceback# Configure the appst.set_page_config(page_title="Object Detection App",page_icon="๐",layout="wide")# Display environment info if needed for debuggingif "debug" in st.experimental_get_query_params():st.write("Python version:", sys.version)st.write("Environment variables:", dict(os.environ))st.write("Current working directory:", os.getcwd())st.write("Directory contents:", os.listdir())# Create a sidebarst.sidebar.title("Object Detection App")st.sidebar.markdown("""This app uses Detectron2 to detect objects in images.""")# Display loading messagewith st.spinner("Loading dependencies..."):try:import torchfrom detectron2.engine import DefaultPredictorfrom detectron2.config import get_cfgfrom detectron2 import model_zoofrom detectron2.utils.visualizer import Visualizerfrom detectron2.data import MetadataCatalogst.sidebar.success("โ Dependencies loaded successfully!")except Exception as e:st.error(f"Failed to load dependencies: {e}")st.error(traceback.format_exc())st.stop()# Load the model@st.cache_resourcedef load_model():try:# Configure the modelcfg = get_cfg()cfg.merge_from_file(model_zoo.get_config_file("COCO-Detection/faster_rcnn_R_50_FPN_3x.yaml"))cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.5cfg.MODEL.WEIGHTS = model_zoo.get_checkpoint_url("COCO-Detection/faster_rcnn_R_50_FPN_3x.yaml")# Use CPU for inference (more reliable in container environment)cfg.MODEL.DEVICE = "cpu"# Initialize predictorpredictor = DefaultPredictor(cfg)return predictor, cfgexcept Exception as e:st.error(f"Error loading model: {e}")st.error(traceback.format_exc())return None, None# Main functiondef main():st.title("๐ Object Detection")st.markdown("""Upload an image to detect objects using Detectron2's Faster R-CNN model.""")# Load modelwith st.spinner("Loading model..."):predictor, cfg = load_model()if predictor is None:st.error("Failed to load the model. Check the error messages.")return# File uploaderuploaded_file = st.file_uploader("Choose an image file", type=["jpg", "jpeg", "png"])if uploaded_file is not None:try:# Read and display the imageimage = Image.open(uploaded_file)st.image(image, caption="Uploaded Image", use_column_width=True)# Convert to numpy arrayimage_array = np.array(image.convert("RGB"))# Perform inferencewith st.spinner("Detecting objects..."):outputs = predictor(image_array)# Get instancesinstances = outputs["instances"].to("cpu")# Create visualizerv = Visualizer(image_array,metadata=MetadataCatalog.get(cfg.DATASETS.TRAIN[0] if len(cfg.DATASETS.TRAIN) else "coco_2017_val"),scale=1.2)# Draw predictionsresult = v.draw_instance_predictions(instances)result_image = result.get_image()# Display resultst.image(result_image, caption="Detection Result", use_column_width=True)# Show detection informationif len(instances) > 0:st.subheader(f"Detected {len(instances)} objects")# Get class namesmetadata = MetadataCatalog.get(cfg.DATASETS.TRAIN[0] if len(cfg.DATASETS.TRAIN) else "coco_2017_val")class_names = metadata.thing_classes# Show detectionsfor i in range(len(instances)):score = instances.scores[i].item()class_id = instances.pred_classes[i].item()class_name = class_names[class_id]box = instances.pred_boxes[i].tensor.numpy()[0]st.write(f"**{class_name}**: {score:.2f} confidence")else:st.info("No objects detected in this image.")except Exception as e:st.error(f"Error processing image: {e}")st.error(traceback.format_exc())if __name__ == "__main__":main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143import streamlit as stimport numpy as npfrom PIL import Imageimport cv2import osimport sys# Set page configurationst.set_page_config(page_title="Object Detection",page_icon="๐",layout="wide")# Display app headerst.title("๐ Object Detection with Detectron2")st.markdown("""Upload an image to detect objects using Facebook AI Research's Detectron2 model.""")# Setup sidebarwith st.sidebar:st.header("About")st.markdown("This app uses Detectron2 to detect objects in images.")# Show environment info for debuggingif st.checkbox("Show Environment Info", False):st.write("Python version:", sys.version)st.write("Working directory:", os.getcwd())st.write("Directory contents:", os.listdir())# Import Detectron2 with error handlingtry:import torchfrom detectron2 import model_zoofrom detectron2.engine import DefaultPredictorfrom detectron2.config import get_cfgfrom detectron2.utils.visualizer import Visualizerfrom detectron2.data import MetadataCatalogexcept Exception as e:st.error(f"Failed to import required libraries: {str(e)}")st.error("Please check that all dependencies are correctly installed.")st.stop()# Load the model@st.cache_resourcedef load_detectron_model():"""Load the Detectron2 model with caching"""try:# Set up configurationcfg = get_cfg()cfg.merge_from_file(model_zoo.get_config_file("COCO-Detection/faster_rcnn_R_50_FPN_3x.yaml"))cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.5 # Set threshold for object detectioncfg.MODEL.WEIGHTS = model_zoo.get_checkpoint_url("COCO-Detection/faster_rcnn_R_50_FPN_3x.yaml")cfg.MODEL.DEVICE = "cpu" # Use CPU# Create predictorpredictor = DefaultPredictor(cfg)return predictor, cfgexcept Exception as e:st.error(f"Error loading model: {str(e)}")return None, None# Process the imagedef process_image(image, predictor):"""Run object detection on the image"""# Convert PIL Image to OpenCV format (RGB to BGR)img = np.array(image.convert("RGB"))# Run inferenceoutputs = predictor(img)# Get the instancesinstances = outputs["instances"].to("cpu")return img, instances# Visualize the resultsdef visualize_results(img, instances, metadata):"""Create visualization of detection results"""v = Visualizer(img, metadata=metadata, scale=1.2)out = v.draw_instance_predictions(instances)return out.get_image()# Main app logicdef main():# Load model with a spinnerwith st.spinner("Loading model... (this may take a moment on first run)"):predictor, cfg = load_detectron_model()if predictor is None:st.error("Failed to load the detection model.")return# Get metadatametadata = MetadataCatalog.get(cfg.DATASETS.TRAIN[0] if len(cfg.DATASETS.TRAIN) else "coco_2017_val")# Create file uploaderuploaded_file = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"])# Process the uploaded imageif uploaded_file is not None:try:# Display the original imageimage = Image.open(uploaded_file)st.image(image, caption="Uploaded Image", width=400)# Process the imagewith st.spinner("Detecting objects..."):img, instances = process_image(image, predictor)# Check if any objects were detectedif len(instances) > 0:# Visualize the resultsresult_img = visualize_results(img, instances, metadata)# Display the resultst.image(result_img, caption="Detection Result", width=800)# Show detection detailsst.subheader(f"Detected {len(instances)} objects")class_names = metadata.get("thing_classes", None)# Display each detectionfor i in range(len(instances)):score = instances.scores[i].item()class_id = instances.pred_classes[i].item()if class_names:label = class_names[class_id]else:label = f"Class {class_id}"st.write(f"**{label}** (Confidence: {score:.2f})")else:st.info("No objects detected in this image.")except Exception as e:st.error(f"Error processing image: {str(e)}")if __name__ == "__main__":main()
src/streamlit_app.py+90-83