Spaces:
Sleeping
Sleeping
Create app.py
Browse files12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576import iofrom typing import Listfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi import FastAPI, File, UploadFilefrom fastapi.responses import JSONResponsefrom PIL import Imageimport torchfrom torchvision import transforms
from image_captioning.config import TrainingConfig, get_devicefrom image_captioning.dataset import IMAGENET_MEAN, IMAGENET_STD, create_tokenizerfrom image_captioning.model import ImageCaptioningModel
app = FastAPI(title="Image Captioning API (HF Space)")app.add_middleware( CORSMiddleware, allow_origins=["*"], # Allows all domains. For security, replace with your GitHub Pages URL later. allow_credentials=True, allow_methods=["*"], allow_headers=["*"],)
@app.get("/")async def root(): return {"message": "Image Captioning API is running. Use /docs for the UI or POST /caption for captions."}
@app.post("/caption")async def get_caption(file: UploadFile = File(...)): # Your existing logic to process the image and generate a caption # result = model.predict(image) return {"caption": "The generated caption text here"} device = get_device()training_cfg = TrainingConfig(max_caption_length=50)tokenizer = create_tokenizer()model = ImageCaptioningModel(training_cfg=training_cfg)model.to(device)model.eval()
CHECKPOINT_PATH = "best_model.pt"state_dict = torch.load(CHECKPOINT_PATH, map_location=device)model.load_state_dict(state_dict)
preprocess = transforms.Compose( [ transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize(mean=IMAGENET_MEAN, std=IMAGENET_STD), ])
@app.get("/health")async def health() -> dict: return {"status": "ok"}
@app.post("/caption")async def caption_image(file: UploadFile = File(...)) -> JSONResponse: try: contents = await file.read() image = Image.open(io.BytesIO(contents)).convert("RGB") except Exception as exc: return JSONResponse(status_code=400, content={"error": f"Invalid image: {exc}"})
tensor = preprocess(image).unsqueeze(0).to(device)
with torch.no_grad(): captions: List[str] = model.generate( images=tensor, max_length=50, num_beams=1, )
return JSONResponse({"caption": captions[0]})app.pyAdded+76