from ultralytics import YOLO from PIL import Image import gradio as gr from huggingface_hub import snapshot_download import os import shutil def initialize_model_path(): is_huggingface = os.environ.get("SPACE_ID") is not None if is_huggingface: REPO_ID = "mail2kandan/guitar_watch_openvino_model" print("Downloading model from Hugging Face...") # Create a temp directory for the model model_dir = os.path.join(os.getcwd(), 'guitar_openvino_model') os.makedirs(model_dir, exist_ok=True) # Download complete model directory downloaded_path = snapshot_download(repo_id=REPO_ID) # Copy files to our model directory for ext in ['.xml', '.bin']: src = os.path.join(downloaded_path, f'best{ext}') dst = os.path.join(model_dir, f'best{ext}') if os.path.exists(src): shutil.copy2(src, dst) print(f"Copied {src} to {dst}") else: raise Exception(f"Required model file best{ext} not found in repository") # Verify both files exist in the new directory if os.path.exists(os.path.join(model_dir, 'best.xml')) and \ os.path.exists(os.path.join(model_dir, 'best.bin')): print(f"Using model directory: {model_dir}") return model_dir else: raise Exception("Model files not found in target directory after copying") else: local_path = r'C:\Manikandan\NYP\ITI107\Assignment_draft\output_models\best_openvino_model' print(f"Using local model from: {local_path}") return local_path # Initialize model path once MODEL_PATH = initialize_model_path() def predict(pilimg, conf_threshold, iou_threshold): try: if pilimg is None: return None print(f"Loading model from: {MODEL_PATH}") print(f"Model path exists: {os.path.exists(MODEL_PATH)}") if os.path.isfile(MODEL_PATH): print(f"Found these files in directory: {os.listdir(os.path.dirname(MODEL_PATH))}") model = YOLO(MODEL_PATH, task='detect') result = model.predict(pilimg, conf=conf_threshold, iou=iou_threshold) img_bgr = result[0].plot() return Image.fromarray(img_bgr[..., ::-1]) except Exception as e: print(f"Error during prediction: {str(e)}") # Print full error traceback for debugging import traceback print(traceback.format_exc()) return None with gr.Blocks() as demo: # Header gr.HTML("""
Powered by YOLOv8
© 2025 Guitar & Watch Detection - 9027941P - Manikandan Sadhasivam