Spaces:
Runtime error
Runtime error
Create main.py
Browse files
main.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI
|
| 2 |
+
from pymongo import MongoClient
|
| 3 |
+
from sentence_transformers import SentenceTransformer
|
| 4 |
+
from PIL import Image
|
| 5 |
+
from io import BytesIO
|
| 6 |
+
import numpy as np
|
| 7 |
+
import requests
|
| 8 |
+
from bson import ObjectId
|
| 9 |
+
import os
|
| 10 |
+
|
| 11 |
+
# ===============================================================
|
| 12 |
+
# π FastAPI App
|
| 13 |
+
# ===============================================================
|
| 14 |
+
app = FastAPI(title="Educational Placemat Embedding API")
|
| 15 |
+
|
| 16 |
+
# ===============================================================
|
| 17 |
+
# π Database Connection
|
| 18 |
+
# ===============================================================
|
| 19 |
+
MONGO_URI = "mongodb+srv://anna_db_user:6zxpOoyMUqnpxrBS@similaritysearch.xblvd4g.mongodb.net/"
|
| 20 |
+
client = MongoClient(MONGO_URI)
|
| 21 |
+
db = client["similaritysearch"]
|
| 22 |
+
|
| 23 |
+
# ===============================================================
|
| 24 |
+
# π§© Load Lightweight CLIP Model
|
| 25 |
+
# ===============================================================
|
| 26 |
+
os.makedirs("/tmp/model_cache", exist_ok=True)
|
| 27 |
+
model = SentenceTransformer(
|
| 28 |
+
"sentence-transformers/clip-ViT-B-16",
|
| 29 |
+
cache_folder="/tmp/model_cache"
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
# ===============================================================
|
| 33 |
+
# πΌοΈ Endpoint β Generate Image Embedding
|
| 34 |
+
# ===============================================================
|
| 35 |
+
@app.post("/generate_embedding")
|
| 36 |
+
def generate_embedding(data: dict):
|
| 37 |
+
"""
|
| 38 |
+
Generate a CLIP embedding for an image from URL and store it in MongoDB.
|
| 39 |
+
"""
|
| 40 |
+
img_url = data["thumbnail"]
|
| 41 |
+
image = Image.open(BytesIO(requests.get(img_url).content)).convert("RGB").resize((512, 512))
|
| 42 |
+
emb = model.encode(image, convert_to_numpy=True, normalize_embeddings=True)
|
| 43 |
+
db.images.update_one({"_id": ObjectId(data["_id"])}, {"$set": {"embedding": emb.tolist()}})
|
| 44 |
+
return {"message": "β
Embedding added successfully"}
|
| 45 |
+
|
| 46 |
+
# ===============================================================
|
| 47 |
+
# π Root route
|
| 48 |
+
# ===============================================================
|
| 49 |
+
@app.get("/")
|
| 50 |
+
def home():
|
| 51 |
+
return {"status": "running", "model": "clip-ViT-B-16"}
|