File size: 2,134 Bytes
5c14626
 
 
 
35063fc
 
5c14626
 
 
 
 
 
 
 
 
 
 
 
35063fc
5c14626
 
 
 
 
 
 
 
 
 
35063fc
 
 
 
 
 
 
 
 
 
 
5c14626
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35063fc
5c14626
 
 
 
 
35063fc
 
 
 
 
 
5c14626
 
 
35063fc
 
5c14626
 
 
 
 
 
35063fc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
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
# ----------------------------

@app.get("/")
def root():
    return {"message": "AI Caption Generator Backend Running 🚀"}


# ----------------------------
# Generate Caption Endpoint
# ----------------------------

@app.post("/generate")
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)
        }