Spaces:
Running
Running
added classes selection and examples input
Browse files4 unmodified lines56789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293944 unmodified linesfrom PIL import Imagefrom ultralytics import YOLO# --- COMPATIBILITY FIX ---plt = platform.system()if plt != 'Windows':pathlib.WindowsPath = pathlib.PosixPath# --- CONFIGURATION ---MODEL_FILES = {"CalvingCatcherV2": "calvingcatcherV2.pt","CalvingCatcherV1": "calvingcatcherV1.pt"}# Lazy load models to save memory on startup if neededMODELS = {name: YOLO(path) for name, path in MODEL_FILES.items()}# --- STYLING ---CUSTOM_CSS = """.bebas-font { font-family: 'Bebas Neue', sans-serif !important; text-transform: uppercase; }.roboto-font { font-family: 'Roboto', sans-serif !important; }.primary-btn { background-color: #386938 !important; color: white !important; }"""DESCRIPTION = """### 🐮 CalvingCatcher AI**CalvingCatcher AI** is an informative open-source computer vision model designed to monitor your herd 24/7.It analyzes footage to detect critical signs related to the calving process."""# --- LOGIC ---def predict(img, model_name, conf_threshold):if img is None:return None# Run inferencemodel = MODELS[model_name]results = model(img, conf=conf_threshold)# Get the plotted image (BGR -> RGB)res_plotted = results[0].plot()return Image.fromarray(res_plotted[:, :, ::-1])# Prepare Examplesexample_folder = "examples"example_list = [[os.path.join(example_folder, f), "CalvingCatcherV2", 0.7]for f in os.listdir(example_folder)if f.lower().endswith(('.png', '.jpg', '.jpeg'))] if os.path.isdir(example_folder) else []# --- INTERFACE ---with gr.Blocks(css=CUSTOM_CSS, theme=gr.themes.Soft(primary_hue="green")) as demo:gr.Markdown(DESCRIPTION)with gr.Row():with gr.Column():input_img = gr.Image(type="pil", label="Upload Barn Image")with gr.Row():model_drop = gr.Dropdown(choices=list(MODELS.keys()),value="CalvingCatcherV2",label="Select Model")conf_slider = gr.Slider(minimum=0.1, maximum=1.0, value=0.3,label="Confidence Threshold")predict_btn = gr.Button("Run Detection", variant="primary", elem_classes="primary-btn")with gr.Column():output_img = gr.Image(type="pil", label="Detection Result")if example_list:gr.Examples(examples=example_list,inputs=[input_img, model_drop, conf_slider],outputs=output_img,fn=predict,cache_examples=False)predict_btn.click(fn=predict,inputs=[input_img, model_drop, conf_slider],outputs=output_img)4 unmodified lines567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381394 unmodified linesfrom PIL import Imagefrom ultralytics import YOLOplt = platform.system()if plt != 'Windows':pathlib.WindowsPath = pathlib.PosixPathMODELS = {"CalvingCatcherV2": YOLO("calvingcatcherV2.pt"),"CalvingCatcherV1": YOLO("calvingcatcherV1.pt")}CLASS_LABELS = {0: "tail_up",1: "amniotic_fluid",2: "legs",3: "head",4: "calf",5: "placenta"}EMERALD_GREEN = "#386938"CUSTOM_CSS = """@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap');@import url('https://fonts.googleapis.com/css2?family=Bebas+Neue&display=swap');.bebas-font {font-family: 'Bebas Neue', 'Bebas Kai', sans-serif !important;text-transform: uppercase;letter-spacing: 1px;}.roboto-font {font-family: 'Roboto', sans-serif !important;}.primary-btn {background-color: #386938 !important;border: none !important;font-family: 'Bebas Neue', sans-serif !important;font-size: 1.2rem !important;color: white !important;}.gradio-container label span {font-family: 'Roboto', sans-serif !important;font-weight: bold;}"""DESCRIPTION_TEXT = """**CalvingCatcher AI** is an informative open-source computer vision model designed to monitor your herd 24/7.It analyzes footage to detect critical signs related to the calving process."""def predict(img, model_name, conf_threshold, selected_class_names):if img is None:return Noneselected_indices = [idx for idx, name in CLASS_LABELS.items()if name in selected_class_names]if not selected_indices:return imgselected_model = MODELS[model_name]results = selected_model(img, conf=conf_threshold, classes=selected_indices)for result in results:result.names = CLASS_LABELSres_plotted = results[0].plot()return Image.fromarray(res_plotted[:, :, ::-1])example_folder = "examples"example_images = [os.path.join(example_folder, f)for f in os.listdir(example_folder)if f.lower().endswith(('.png', '.jpg', '.jpeg'))] if os.path.exists(example_folder) else []with gr.Blocks(css=CUSTOM_CSS, theme=gr.themes.Soft(primary_hue="green"), title="CalvingCatcher AI") as demo:with gr.Column(elem_classes="roboto-font"):gr.Markdown("# 🐮 CalvingCatcher AI", elem_classes="bebas-font")gr.Markdown(DESCRIPTION_TEXT, elem_classes="roboto-font")with gr.Row():with gr.Column():input_img = gr.Image(type="pil", label="Upload Barn Image")with gr.Row():model_drop = gr.Dropdown(choices=list(MODELS.keys()),value="CalvingCatcherV2",label="Select Model")conf_slider = gr.Slider(minimum=0.1,maximum=1.0,value=0.3,label="Confidence Threshold",info="Higher values mean fewer but more certain detections.")class_selector = gr.CheckboxGroup(choices=list(CLASS_LABELS.values()),value=list(CLASS_LABELS.values()),label="Filter Classes",info="Select which classes should be detected.")predict_btn = gr.Button("Run Detection", variant="primary", elem_classes="roboto-font")with gr.Column():output_img = gr.Image(type="pil", label="Detection Result")if example_images:gr.Markdown("### 📸 Try an Example:", elem_classes="bebas-font")gr.Examples(examples=example_images,inputs=input_img,label=None)predict_btn.click(fn=predict,inputs=[input_img, model_drop, conf_slider, class_selector],outputs=output_img)
app.py+99-54