Spaces:
Runtime error
Runtime error
Download app.py from sid221/caption-Magic: direct link, hf CLI and curl.
- Browser
- Download file 2.13 kB
-
https://huggingface.co/spaces/sid221/caption-Magic/resolve/main/app.py
- Command line
-
hf download hf://spaces/sid221/caption-Magic/app.py
-
curl -L -o app.py https://huggingface.co/spaces/sid221/caption-Magic/resolve/main/app.py
2.13 kB
| from fastapi import FastAPI, UploadFile, File, Form | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from PIL import Image | |
| import io | |
| import torch | |
| from transformers import BlipProcessor, BlipForConditionalGeneration | |
| from caption_generator import generate_captions | |
| # ---------------------------- | |
| # Create FastAPI App | |
| # ---------------------------- | |
| app = FastAPI() | |
| # Enable CORS (important for frontend connection) | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], # OK for hackathon | |
| allow_credentials=True, | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| # ---------------------------- | |
| # Load Model Once At Startup | |
| # ---------------------------- | |
| try: | |
| device = "cuda" if torch.cuda.is_available() else "cpu" | |
| processor = BlipProcessor.from_pretrained( | |
| "Salesforce/blip-image-captioning-base" | |
| ) | |
| model = BlipForConditionalGeneration.from_pretrained( | |
| "Salesforce/blip-image-captioning-base" | |
| ).to(device) | |
| print("✅ BLIP model loaded successfully.") | |
| except Exception as e: | |
| print("❌ Failed to load model:", e) | |
| processor, model = None, None | |
| # ---------------------------- | |
| # Root Test Route | |
| # ---------------------------- | |
| def root(): | |
| return {"message": "AI Caption Generator Backend Running 🚀"} | |
| # ---------------------------- | |
| # Generate Caption Endpoint | |
| # ---------------------------- | |
| async def generate_caption( | |
| file: UploadFile = File(...), | |
| tone: str = Form("casual") | |
| ): | |
| if processor is None or model is None: | |
| return {"status": "error", "message": "Model not loaded properly ❌"} | |
| try: | |
| contents = await file.read() | |
| image = Image.open(io.BytesIO(contents)).convert("RGB") | |
| captions = generate_captions( | |
| image=image, | |
| processor=processor, | |
| model=model, | |
| tone=tone | |
| ) | |
| return { | |
| "status": "success", | |
| "captions": captions, | |
| "emoji": "✨🔥" | |
| } | |
| except Exception as e: | |
| return { | |
| "status": "error", | |
| "message": str(e) | |
| } | |