hackerloi45 commited on
Commit
47edb75
Β·
1 Parent(s): 27514c1

fixed with UI improved

Browse files
Files changed (1) hide show
  1. app.py +37 -45
app.py CHANGED
@@ -10,22 +10,18 @@ from PIL import Image
10
  # --------------------------
11
  # Qdrant Cloud Connection
12
  # --------------------------
13
- QDRANT_URL = "https://ff4da494-27b1-413c-ba58-d5ea14932fe1.europe-west3-0.gcp.cloud.qdrant.io:6333" # πŸ”‘ Replace with your cluster URL
14
- QDRANT_API_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhY2Nlc3MiOiJtIn0.jjeB1JgnUSlb1hOOKMdRpVvMrUER57-udT-X1AWXT1E" # πŸ”‘ Replace with your API key
15
  COLLECTION_NAME = "lost_and_found"
16
 
17
  # CLIP model (text + image embeddings)
18
  MODEL_NAME = "sentence-transformers/clip-ViT-B-32"
19
  embedder = SentenceTransformer(MODEL_NAME)
20
 
21
- # CLIP ViT-B/32 always gives 512-dimensional embeddings
22
- VECTOR_SIZE = 512
23
 
24
- # Qdrant Client (Cloud)
25
- qclient = QdrantClient(
26
- url=QDRANT_URL,
27
- api_key=QDRANT_API_KEY
28
- )
29
 
30
  # Ensure collection exists
31
  qclient.recreate_collection(
@@ -38,13 +34,11 @@ qclient.recreate_collection(
38
  # --------------------------
39
 
40
  def image_to_base64(img: Image.Image) -> str:
41
- """Convert PIL image to base64 string"""
42
  buf = io.BytesIO()
43
  img.save(buf, format="PNG")
44
  return base64.b64encode(buf.getvalue()).decode("utf-8")
45
 
46
  def base64_to_image(b64_str: str) -> Image.Image:
47
- """Convert base64 string back to PIL image"""
48
  img_bytes = base64.b64decode(b64_str)
49
  return Image.open(io.BytesIO(img_bytes))
50
 
@@ -55,15 +49,12 @@ def embed_image(img: Image.Image):
55
  return embedder.encode(img).tolist()
56
 
57
  def add_item(image, description, finder_name, finder_phone):
58
- """Add a found item to Qdrant database"""
59
  if image is None or description.strip() == "":
60
- return "❌ Please provide both an image and a description."
61
 
62
- # Encode image
63
  embedding = embed_image(image)
64
  img_b64 = image_to_base64(image)
65
 
66
- # Store metadata including image
67
  metadata = {
68
  "description": description,
69
  "finder_name": finder_name if finder_name.strip() else "NA",
@@ -71,7 +62,6 @@ def add_item(image, description, finder_name, finder_phone):
71
  "image_b64": img_b64
72
  }
73
 
74
- # Insert into Qdrant
75
  qclient.upsert(
76
  collection_name=COLLECTION_NAME,
77
  points=[
@@ -82,20 +72,17 @@ def add_item(image, description, finder_name, finder_phone):
82
  )
83
  ]
84
  )
85
- return "βœ… Item successfully added!"
86
 
87
  def search_items(query_text, query_image):
88
- """Search by text or image"""
89
  if not query_text and query_image is None:
90
- return "❌ Please enter text or upload an image to search.", []
91
 
92
- # Use text or image embedding
93
  if query_image:
94
  query_vector = embed_image(query_image)
95
  else:
96
  query_vector = embed_text(query_text)
97
 
98
- # Search Qdrant
99
  results = qclient.search(
100
  collection_name=COLLECTION_NAME,
101
  query_vector=query_vector,
@@ -103,11 +90,10 @@ def search_items(query_text, query_image):
103
  )
104
 
105
  if not results:
106
- return "❌ No matches found.", []
107
 
108
- # Format results
109
  gallery = []
110
- output_text = "βœ… Found Matches:\n\n"
111
  for r in results:
112
  desc = r.payload.get("description", "No description")
113
  name = r.payload.get("finder_name", "NA")
@@ -124,50 +110,56 @@ def search_items(query_text, query_image):
124
  return output_text, gallery
125
 
126
  def clear_database():
127
- """Clear all stored items in Qdrant"""
128
  qclient.delete_collection(COLLECTION_NAME)
129
  qclient.recreate_collection(
130
  collection_name=COLLECTION_NAME,
131
  vectors_config=VectorParams(size=VECTOR_SIZE, distance=Distance.COSINE),
132
  )
133
- return "πŸ—‘οΈ Database cleared!"
134
 
135
  # --------------------------
136
  # Gradio UI
137
  # --------------------------
138
 
139
- with gr.Blocks() as demo:
140
- gr.Markdown("# πŸ” Lost & Found System")
 
 
 
 
 
141
 
142
- with gr.Tab("βž• Add Found Item"):
143
  with gr.Row():
144
- image_in = gr.Image(type="pil", label="Upload Found Item Image")
145
- desc_in = gr.Textbox(label="Item Description")
146
  with gr.Row():
147
- finder_name = gr.Textbox(label="Finder's Name")
148
- finder_phone = gr.Textbox(label="Finder's Phone Number")
149
- add_btn = gr.Button("Add Item")
150
- add_output = gr.Textbox(label="Status")
151
 
152
- with gr.Tab("πŸ”Ž Search Items"):
153
  with gr.Row():
154
- search_text = gr.Textbox(label="Search by Text")
155
- search_image = gr.Image(type="pil", label="Or Search by Image")
156
- search_btn = gr.Button("Search")
157
  search_output = gr.Markdown(label="Results")
158
- gallery = gr.Gallery(label="Matched Items", show_label=True, elem_id="gallery")
 
 
159
 
160
- with gr.Tab("⚠️ Admin"):
161
- clear_btn = gr.Button("Clear Entire Database")
162
- clear_output = gr.Textbox(label="Status")
163
 
164
- # Button actions
165
  add_btn.click(add_item, inputs=[image_in, desc_in, finder_name, finder_phone], outputs=add_output)
166
  search_btn.click(search_items, inputs=[search_text, search_image], outputs=[search_output, gallery])
167
  clear_btn.click(clear_database, outputs=clear_output)
168
 
169
  # --------------------------
170
- # Launch App
171
  # --------------------------
172
  if __name__ == "__main__":
173
  demo.launch(server_name="0.0.0.0", server_port=7860)
 
10
  # --------------------------
11
  # Qdrant Cloud Connection
12
  # --------------------------
13
+ QDRANT_URL = "https://YOUR-CLUSTER-URL.qdrant.io" # πŸ”‘ Replace with your cluster URL
14
+ QDRANT_API_KEY = "YOUR_API_KEY" # πŸ”‘ Replace with your API key
15
  COLLECTION_NAME = "lost_and_found"
16
 
17
  # CLIP model (text + image embeddings)
18
  MODEL_NAME = "sentence-transformers/clip-ViT-B-32"
19
  embedder = SentenceTransformer(MODEL_NAME)
20
 
21
+ VECTOR_SIZE = 512 # CLIP always outputs 512-dim vectors
 
22
 
23
+ # Qdrant Client
24
+ qclient = QdrantClient(url=QDRANT_URL, api_key=QDRANT_API_KEY)
 
 
 
25
 
26
  # Ensure collection exists
27
  qclient.recreate_collection(
 
34
  # --------------------------
35
 
36
  def image_to_base64(img: Image.Image) -> str:
 
37
  buf = io.BytesIO()
38
  img.save(buf, format="PNG")
39
  return base64.b64encode(buf.getvalue()).decode("utf-8")
40
 
41
  def base64_to_image(b64_str: str) -> Image.Image:
 
42
  img_bytes = base64.b64decode(b64_str)
43
  return Image.open(io.BytesIO(img_bytes))
44
 
 
49
  return embedder.encode(img).tolist()
50
 
51
  def add_item(image, description, finder_name, finder_phone):
 
52
  if image is None or description.strip() == "":
53
+ return "Please provide both an image and a description."
54
 
 
55
  embedding = embed_image(image)
56
  img_b64 = image_to_base64(image)
57
 
 
58
  metadata = {
59
  "description": description,
60
  "finder_name": finder_name if finder_name.strip() else "NA",
 
62
  "image_b64": img_b64
63
  }
64
 
 
65
  qclient.upsert(
66
  collection_name=COLLECTION_NAME,
67
  points=[
 
72
  )
73
  ]
74
  )
75
+ return "Item successfully added."
76
 
77
  def search_items(query_text, query_image):
 
78
  if not query_text and query_image is None:
79
+ return "Enter text or upload an image to search.", []
80
 
 
81
  if query_image:
82
  query_vector = embed_image(query_image)
83
  else:
84
  query_vector = embed_text(query_text)
85
 
 
86
  results = qclient.search(
87
  collection_name=COLLECTION_NAME,
88
  query_vector=query_vector,
 
90
  )
91
 
92
  if not results:
93
+ return "No matches found.", []
94
 
 
95
  gallery = []
96
+ output_text = "### Matches Found:\n\n"
97
  for r in results:
98
  desc = r.payload.get("description", "No description")
99
  name = r.payload.get("finder_name", "NA")
 
110
  return output_text, gallery
111
 
112
  def clear_database():
 
113
  qclient.delete_collection(COLLECTION_NAME)
114
  qclient.recreate_collection(
115
  collection_name=COLLECTION_NAME,
116
  vectors_config=VectorParams(size=VECTOR_SIZE, distance=Distance.COSINE),
117
  )
118
+ return "Database cleared."
119
 
120
  # --------------------------
121
  # Gradio UI
122
  # --------------------------
123
 
124
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
125
+ gr.Markdown(
126
+ """
127
+ # Lost & Found System
128
+ Upload, search, and manage found items with text or image queries.
129
+ """
130
+ )
131
 
132
+ with gr.Tab("Add Item"):
133
  with gr.Row():
134
+ image_in = gr.Image(type="pil", label="Upload Image", height=250)
135
+ desc_in = gr.Textbox(label="Item Description", placeholder="e.g. Silver keychain with tag")
136
  with gr.Row():
137
+ finder_name = gr.Textbox(label="Finder's Name", placeholder="John Doe")
138
+ finder_phone = gr.Textbox(label="Finder's Phone", placeholder="+123456789")
139
+ add_btn = gr.Button("Add Item", variant="primary")
140
+ add_output = gr.Textbox(label="Status", interactive=False)
141
 
142
+ with gr.Tab("Search"):
143
  with gr.Row():
144
+ search_text = gr.Textbox(label="Search by Text", placeholder="Enter keywords...")
145
+ search_image = gr.Image(type="pil", label="Or Search by Image", height=250)
146
+ search_btn = gr.Button("Search", variant="primary")
147
  search_output = gr.Markdown(label="Results")
148
+ gallery = gr.Gallery(label="Matched Items", show_label=True, elem_id="gallery").style(
149
+ grid=[2], height="auto"
150
+ )
151
 
152
+ with gr.Tab("Admin"):
153
+ clear_btn = gr.Button("Clear Database", variant="stop")
154
+ clear_output = gr.Textbox(label="Status", interactive=False)
155
 
156
+ # Actions
157
  add_btn.click(add_item, inputs=[image_in, desc_in, finder_name, finder_phone], outputs=add_output)
158
  search_btn.click(search_items, inputs=[search_text, search_image], outputs=[search_output, gallery])
159
  clear_btn.click(clear_database, outputs=clear_output)
160
 
161
  # --------------------------
162
+ # Launch
163
  # --------------------------
164
  if __name__ == "__main__":
165
  demo.launch(server_name="0.0.0.0", server_port=7860)