Spaces:
Runtime error
Runtime error
Commit
·
0d5f8a4
1
Parent(s):
bb08dc6
Fix CLIrrr2 model issue in app.py
Browse files
app.py
CHANGED
|
@@ -2,173 +2,114 @@
|
|
| 2 |
import os
|
| 3 |
import uuid
|
| 4 |
import io
|
| 5 |
-
import base64
|
| 6 |
from PIL import Image
|
| 7 |
import gradio as gr
|
| 8 |
-
import numpy as np
|
| 9 |
-
|
| 10 |
-
# CLIP via Sentence-Transformers (text+image to same 512-dim space)
|
| 11 |
from sentence_transformers import SentenceTransformer
|
| 12 |
-
|
| 13 |
-
# Gemini (Google) client
|
| 14 |
from google import genai
|
| 15 |
-
|
| 16 |
-
# Qdrant client & helpers
|
| 17 |
from qdrant_client import QdrantClient
|
| 18 |
from qdrant_client.http.models import VectorParams, Distance, PointStruct
|
| 19 |
|
| 20 |
-
# -------------------------
|
| 21 |
-
# CONFIG (reads env vars)
|
| 22 |
-
# -------------------------
|
| 23 |
GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY")
|
| 24 |
QDRANT_URL = os.environ.get("QDRANT_URL")
|
| 25 |
QDRANT_API_KEY = os.environ.get("QDRANT_API_KEY")
|
| 26 |
|
| 27 |
-
|
| 28 |
-
# Initialize clients/models
|
| 29 |
-
# -------------------------
|
| 30 |
-
print("Loading CLIP model (this may take 20-60s the first time)...")
|
| 31 |
MODEL_ID = "sentence-transformers/clip-ViT-B-32-multilingual-v1"
|
| 32 |
clip_model = SentenceTransformer(MODEL_ID)
|
| 33 |
|
| 34 |
-
# Gemini client
|
| 35 |
genai_client = genai.Client(api_key=GEMINI_API_KEY) if GEMINI_API_KEY else None
|
| 36 |
|
| 37 |
-
# Qdrant client
|
| 38 |
if not QDRANT_URL:
|
| 39 |
-
raise RuntimeError("
|
| 40 |
qclient = QdrantClient(url=QDRANT_URL, api_key=QDRANT_API_KEY)
|
| 41 |
|
| 42 |
COLLECTION = "lost_found_items"
|
| 43 |
VECTOR_SIZE = 512
|
| 44 |
-
|
| 45 |
if not qclient.collection_exists(COLLECTION):
|
| 46 |
qclient.create_collection(
|
| 47 |
collection_name=COLLECTION,
|
| 48 |
vectors_config=VectorParams(size=VECTOR_SIZE, distance=Distance.COSINE),
|
| 49 |
)
|
| 50 |
|
| 51 |
-
# -------------------------
|
| 52 |
-
# Helpers
|
| 53 |
-
# -------------------------
|
| 54 |
def embed_text(text: str):
|
| 55 |
return clip_model.encode(text, convert_to_numpy=True)
|
| 56 |
|
| 57 |
def embed_image_pil(pil_img: Image.Image):
|
| 58 |
return clip_model.encode(pil_img, convert_to_numpy=True)
|
| 59 |
|
| 60 |
-
def gen_tags_from_image_file(
|
| 61 |
-
|
| 62 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
return ""
|
| 64 |
-
uploaded_file = genai_client.files.upload(file=file_obj)
|
| 65 |
-
prompt_text = (
|
| 66 |
-
"Give 4 short tags (comma-separated) describing this item in the image. "
|
| 67 |
-
"Tags should be short single words or two-word phrases (e.g. 'black backpack', 'water bottle'). "
|
| 68 |
-
"Respond only with tags, no extra explanation."
|
| 69 |
-
)
|
| 70 |
-
response = genai_client.models.generate_content(
|
| 71 |
-
model="gemini-2.5-flash",
|
| 72 |
-
contents=[prompt_text, uploaded_file],
|
| 73 |
-
)
|
| 74 |
-
return response.text.strip()
|
| 75 |
|
| 76 |
-
# -------------------------
|
| 77 |
-
# App logic: add item
|
| 78 |
-
# -------------------------
|
| 79 |
def add_item(mode: str, uploaded_image, text_description: str):
|
| 80 |
item_id = str(uuid.uuid4())
|
| 81 |
payload = {"mode": mode, "text": text_description}
|
| 82 |
|
| 83 |
-
if uploaded_image
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
img_bytes_io.seek(0)
|
| 88 |
-
|
| 89 |
-
# Embed image
|
| 90 |
vec = embed_image_pil(uploaded_image).tolist()
|
| 91 |
payload["has_image"] = True
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
tags = gen_tags_from_image_file(img_bytes_io)
|
| 96 |
-
except Exception:
|
| 97 |
-
tags = ""
|
| 98 |
-
payload["tags"] = tags
|
| 99 |
-
|
| 100 |
-
# Store image as base64
|
| 101 |
-
img_bytes_io.seek(0)
|
| 102 |
-
payload["image_b64"] = base64.b64encode(img_bytes_io.read()).decode("utf-8")
|
| 103 |
else:
|
| 104 |
vec = embed_text(text_description).tolist()
|
| 105 |
payload["has_image"] = False
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
try:
|
| 109 |
-
resp = genai_client.models.generate_content(
|
| 110 |
-
model="gemini-2.5-flash",
|
| 111 |
-
contents=f"Give 4 short, comma-separated tags for this item described as: {text_description}. Reply only with tags."
|
| 112 |
-
)
|
| 113 |
-
payload["tags"] = resp.text.strip()
|
| 114 |
-
except Exception:
|
| 115 |
-
payload["tags"] = ""
|
| 116 |
-
else:
|
| 117 |
-
payload["tags"] = ""
|
| 118 |
-
|
| 119 |
-
# Upsert into Qdrant
|
| 120 |
point = PointStruct(id=item_id, vector=vec, payload=payload)
|
| 121 |
qclient.upsert(collection_name=COLLECTION, points=[point], wait=True)
|
| 122 |
|
| 123 |
return f"Saved item id: {item_id}\nTags: {payload.get('tags','')}"
|
| 124 |
|
| 125 |
-
# -------------------------
|
| 126 |
-
# App logic: search
|
| 127 |
-
# -------------------------
|
| 128 |
def search_items(query_image, query_text, limit: int = 5):
|
| 129 |
-
if query_image
|
| 130 |
qvec = embed_image_pil(query_image).tolist()
|
| 131 |
elif query_text:
|
| 132 |
qvec = embed_text(query_text).tolist()
|
| 133 |
else:
|
| 134 |
-
return "
|
| 135 |
|
| 136 |
hits = qclient.search(collection_name=COLLECTION, query_vector=qvec, limit=limit)
|
| 137 |
-
|
| 138 |
if not hits:
|
| 139 |
return "No results."
|
| 140 |
|
| 141 |
results = []
|
| 142 |
for h in hits:
|
| 143 |
payload = h.payload or {}
|
| 144 |
-
score = getattr(h, "score",
|
| 145 |
-
img_html = ""
|
| 146 |
-
if payload.get("has_image") and payload.get("image_b64"):
|
| 147 |
-
img_html = f'<img src="data:image/png;base64,{payload["image_b64"]}" width="200">'
|
| 148 |
results.append(
|
| 149 |
-
f"
|
| 150 |
-
f"
|
| 151 |
)
|
| 152 |
|
| 153 |
-
return "
|
| 154 |
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
# -------------------------
|
| 158 |
-
with gr.Blocks(title="Lost & Found — Simple Helper") as demo:
|
| 159 |
-
gr.Markdown("## Lost & Found Helper — Upload items and search by image or text.")
|
| 160 |
with gr.Row():
|
| 161 |
with gr.Column():
|
| 162 |
-
mode = gr.Radio(
|
| 163 |
upload_img = gr.Image(type="pil", label="Item photo (optional)")
|
| 164 |
-
text_desc = gr.Textbox(lines=2, placeholder="Short description", label="Description
|
| 165 |
add_btn = gr.Button("Add item")
|
| 166 |
-
add_out = gr.
|
| 167 |
with gr.Column():
|
| 168 |
query_img = gr.Image(type="pil", label="Search by image (optional)")
|
| 169 |
query_text = gr.Textbox(lines=2, label="Search by text (optional)")
|
| 170 |
search_btn = gr.Button("Search")
|
| 171 |
-
search_out = gr.
|
| 172 |
|
| 173 |
add_btn.click(add_item, inputs=[mode, upload_img, text_desc], outputs=[add_out])
|
| 174 |
search_btn.click(search_items, inputs=[query_img, query_text], outputs=[search_out])
|
|
|
|
| 2 |
import os
|
| 3 |
import uuid
|
| 4 |
import io
|
|
|
|
| 5 |
from PIL import Image
|
| 6 |
import gradio as gr
|
|
|
|
|
|
|
|
|
|
| 7 |
from sentence_transformers import SentenceTransformer
|
|
|
|
|
|
|
| 8 |
from google import genai
|
|
|
|
|
|
|
| 9 |
from qdrant_client import QdrantClient
|
| 10 |
from qdrant_client.http.models import VectorParams, Distance, PointStruct
|
| 11 |
|
|
|
|
|
|
|
|
|
|
| 12 |
GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY")
|
| 13 |
QDRANT_URL = os.environ.get("QDRANT_URL")
|
| 14 |
QDRANT_API_KEY = os.environ.get("QDRANT_API_KEY")
|
| 15 |
|
| 16 |
+
print("Loading CLIP model...")
|
|
|
|
|
|
|
|
|
|
| 17 |
MODEL_ID = "sentence-transformers/clip-ViT-B-32-multilingual-v1"
|
| 18 |
clip_model = SentenceTransformer(MODEL_ID)
|
| 19 |
|
|
|
|
| 20 |
genai_client = genai.Client(api_key=GEMINI_API_KEY) if GEMINI_API_KEY else None
|
| 21 |
|
|
|
|
| 22 |
if not QDRANT_URL:
|
| 23 |
+
raise RuntimeError("Set QDRANT_URL env var")
|
| 24 |
qclient = QdrantClient(url=QDRANT_URL, api_key=QDRANT_API_KEY)
|
| 25 |
|
| 26 |
COLLECTION = "lost_found_items"
|
| 27 |
VECTOR_SIZE = 512
|
|
|
|
| 28 |
if not qclient.collection_exists(COLLECTION):
|
| 29 |
qclient.create_collection(
|
| 30 |
collection_name=COLLECTION,
|
| 31 |
vectors_config=VectorParams(size=VECTOR_SIZE, distance=Distance.COSINE),
|
| 32 |
)
|
| 33 |
|
|
|
|
|
|
|
|
|
|
| 34 |
def embed_text(text: str):
|
| 35 |
return clip_model.encode(text, convert_to_numpy=True)
|
| 36 |
|
| 37 |
def embed_image_pil(pil_img: Image.Image):
|
| 38 |
return clip_model.encode(pil_img, convert_to_numpy=True)
|
| 39 |
|
| 40 |
+
def gen_tags_from_image_file(img_bytes: io.BytesIO) -> str:
|
| 41 |
+
if not genai_client:
|
| 42 |
+
return ""
|
| 43 |
+
try:
|
| 44 |
+
file_obj = genai_client.files.upload(file=img_bytes)
|
| 45 |
+
prompt = ("Give 4 short tags (comma-separated) describing this item in the image. "
|
| 46 |
+
"Respond only with tags.")
|
| 47 |
+
resp = genai_client.models.generate_content(model="gemini-2.5-flash",
|
| 48 |
+
contents=[prompt, file_obj])
|
| 49 |
+
return resp.text.strip()
|
| 50 |
+
except Exception:
|
| 51 |
return ""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
|
|
|
|
|
|
|
|
|
|
| 53 |
def add_item(mode: str, uploaded_image, text_description: str):
|
| 54 |
item_id = str(uuid.uuid4())
|
| 55 |
payload = {"mode": mode, "text": text_description}
|
| 56 |
|
| 57 |
+
if uploaded_image:
|
| 58 |
+
img_bytes = io.BytesIO()
|
| 59 |
+
uploaded_image.save(img_bytes, format="PNG")
|
| 60 |
+
img_bytes.seek(0)
|
|
|
|
|
|
|
|
|
|
| 61 |
vec = embed_image_pil(uploaded_image).tolist()
|
| 62 |
payload["has_image"] = True
|
| 63 |
+
payload["tags"] = gen_tags_from_image_file(img_bytes)
|
| 64 |
+
img_bytes.seek(0)
|
| 65 |
+
payload["image_b64"] = base64.b64encode(img_bytes.read()).decode("utf-8")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
else:
|
| 67 |
vec = embed_text(text_description).tolist()
|
| 68 |
payload["has_image"] = False
|
| 69 |
+
payload["tags"] = ""
|
| 70 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
point = PointStruct(id=item_id, vector=vec, payload=payload)
|
| 72 |
qclient.upsert(collection_name=COLLECTION, points=[point], wait=True)
|
| 73 |
|
| 74 |
return f"Saved item id: {item_id}\nTags: {payload.get('tags','')}"
|
| 75 |
|
|
|
|
|
|
|
|
|
|
| 76 |
def search_items(query_image, query_text, limit: int = 5):
|
| 77 |
+
if query_image:
|
| 78 |
qvec = embed_image_pil(query_image).tolist()
|
| 79 |
elif query_text:
|
| 80 |
qvec = embed_text(query_text).tolist()
|
| 81 |
else:
|
| 82 |
+
return "Provide query image or text."
|
| 83 |
|
| 84 |
hits = qclient.search(collection_name=COLLECTION, query_vector=qvec, limit=limit)
|
|
|
|
| 85 |
if not hits:
|
| 86 |
return "No results."
|
| 87 |
|
| 88 |
results = []
|
| 89 |
for h in hits:
|
| 90 |
payload = h.payload or {}
|
| 91 |
+
score = getattr(h, "score", 0)
|
|
|
|
|
|
|
|
|
|
| 92 |
results.append(
|
| 93 |
+
f"ID:{h.id}\nScore:{float(score):.4f}\nMode:{payload.get('mode','')}\n"
|
| 94 |
+
f"Tags:{payload.get('tags','')}\nText:{payload.get('text','')}\n"
|
| 95 |
)
|
| 96 |
|
| 97 |
+
return "\n\n".join(results)
|
| 98 |
|
| 99 |
+
with gr.Blocks() as demo:
|
| 100 |
+
gr.Markdown("## Lost & Found Helper")
|
|
|
|
|
|
|
|
|
|
| 101 |
with gr.Row():
|
| 102 |
with gr.Column():
|
| 103 |
+
mode = gr.Radio(["lost", "found"], value="lost", label="Add as")
|
| 104 |
upload_img = gr.Image(type="pil", label="Item photo (optional)")
|
| 105 |
+
text_desc = gr.Textbox(lines=2, placeholder="Short description", label="Description")
|
| 106 |
add_btn = gr.Button("Add item")
|
| 107 |
+
add_out = gr.Textbox(interactive=False, label="Result")
|
| 108 |
with gr.Column():
|
| 109 |
query_img = gr.Image(type="pil", label="Search by image (optional)")
|
| 110 |
query_text = gr.Textbox(lines=2, label="Search by text (optional)")
|
| 111 |
search_btn = gr.Button("Search")
|
| 112 |
+
search_out = gr.Textbox(interactive=False, label="Search results")
|
| 113 |
|
| 114 |
add_btn.click(add_item, inputs=[mode, upload_img, text_desc], outputs=[add_out])
|
| 115 |
search_btn.click(search_items, inputs=[query_img, query_text], outputs=[search_out])
|