import os import time import requests from PIL import Image from io import BytesIO from fastapi import APIRouter, HTTPException from scripts.data_model import ImageInput, ImageOutput from utils.pipeline import load_model from utils.log import logger router = APIRouter() BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MODEL_PATH = os.path.join(BASE_DIR, "ml-models", "vit-human-pose-classification/") def download_image(url): """Download and open an image from a URL.""" try: response = requests.get(url) response.raise_for_status() return Image.open(BytesIO(response.content)).convert("RGB") except Exception as e: raise HTTPException(status_code=400, detail=f"Failed to download image: {e}") @router.post( "/image_classification", response_model=ImageOutput, summary="Image Classification", description="Classify the image using a pre-trained model." ) def image_classification(input: ImageInput)-> ImageOutput: try: pipe = load_model(MODEL_PATH, is_image_model=True) # image = download_image(input.url) urls = [str(x) for x in input.url] logger.info(f"Image URLs: {urls}") start = time.time() output = pipe(urls) end = time.time() prediction_time = int((end-start)*1000) labels_and_scores = [{"label": x['label'], "score": x['score']} for x in output] return ImageOutput( user_id=input.user_id, url=input.url, model_name="vit-human-pose-classification", labels=[x['label'] for x in labels_and_scores], scores=[x['score'] for x in labels_and_scores], prediction_time=prediction_time ) except Exception as e: return {"error": f"Failed to process image classification: {str(e)}"}, 500