Spaces:
Sleeping
Sleeping
| # app/main.py | |
| from fastapi import FastAPI, HTTPException | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from pydantic import BaseModel, HttpUrl | |
| from PIL import Image | |
| import requests | |
| import io | |
| from app.models.animal_vision import predict_animal | |
| from app.models.plant_vision import predict_plant | |
| app = FastAPI( | |
| title="BIONEXUS Image Intelligence API", | |
| version="1.0.0" | |
| ) | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], | |
| allow_credentials=True, | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| class ImageURLRequest(BaseModel): | |
| image_url: HttpUrl | |
| def load_image_from_url(url) -> Image.Image: | |
| url = str(url) | |
| headers = { | |
| "User-Agent": ( | |
| "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " | |
| "AppleWebKit/537.36 (KHTML, like Gecko) " | |
| "Chrome/121.0.0.0 Safari/537.36" | |
| ), | |
| "Accept": "image/avif,image/webp,image/apng,image/*,*/*;q=0.8", | |
| "Accept-Language": "en-US,en;q=0.9", | |
| "Referer": url | |
| } | |
| try: | |
| response = requests.get( | |
| url, | |
| headers=headers, | |
| timeout=10 | |
| ) | |
| response.raise_for_status() | |
| except requests.RequestException as e: | |
| raise HTTPException( | |
| status_code=400, | |
| detail=f"Failed to download image: {str(e)}" | |
| ) | |
| try: | |
| image = Image.open(io.BytesIO(response.content)).convert("RGB") | |
| except Exception: | |
| raise HTTPException( | |
| status_code=400, | |
| detail="Invalid or unsupported image format" | |
| ) | |
| return image | |
| async def animal_predict(payload: ImageURLRequest): | |
| image = load_image_from_url(payload.image_url) | |
| return predict_animal(image) | |
| async def plant_predict(payload: ImageURLRequest): | |
| image = load_image_from_url(payload.image_url) | |
| return predict_plant(image) | |