Spaces:
Runtime error
Runtime error
File size: 2,028 Bytes
d69a219 |
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 |
from fastapi import FastAPI
from pymongo import MongoClient
from sentence_transformers import SentenceTransformer
from PIL import Image
from io import BytesIO
import numpy as np
import requests
from bson import ObjectId
import os
# ===============================================================
# π FastAPI App
# ===============================================================
app = FastAPI(title="Educational Placemat Embedding API")
# ===============================================================
# π Database Connection
# ===============================================================
MONGO_URI = "mongodb+srv://anna_db_user:6zxpOoyMUqnpxrBS@similaritysearch.xblvd4g.mongodb.net/"
client = MongoClient(MONGO_URI)
db = client["similaritysearch"]
# ===============================================================
# π§© Load Lightweight CLIP Model
# ===============================================================
os.makedirs("/tmp/model_cache", exist_ok=True)
model = SentenceTransformer(
"sentence-transformers/clip-ViT-B-16",
cache_folder="/tmp/model_cache"
)
# ===============================================================
# πΌοΈ Endpoint β Generate Image Embedding
# ===============================================================
@app.post("/generate_embedding")
def generate_embedding(data: dict):
"""
Generate a CLIP embedding for an image from URL and store it in MongoDB.
"""
img_url = data["thumbnail"]
image = Image.open(BytesIO(requests.get(img_url).content)).convert("RGB").resize((512, 512))
emb = model.encode(image, convert_to_numpy=True, normalize_embeddings=True)
db.images.update_one({"_id": ObjectId(data["_id"])}, {"$set": {"embedding": emb.tolist()}})
return {"message": "β
Embedding added successfully"}
# ===============================================================
# π Root route
# ===============================================================
@app.get("/")
def home():
return {"status": "running", "model": "clip-ViT-B-16"}
|