File size: 20,122 Bytes
b0d5ee7
 
 
8eea021
 
 
 
 
 
 
 
fc46e44
 
 
ba353aa
 
 
b0d5ee7
 
 
 
8eea021
 
 
 
c469a8c
 
8eea021
 
 
 
 
 
 
 
 
 
ba353aa
8eea021
 
 
 
 
 
ba353aa
8eea021
 
 
 
 
 
 
ba353aa
8eea021
ba353aa
 
 
 
 
 
8eea021
ba353aa
 
 
 
 
8eea021
 
ba353aa
8eea021
 
ba353aa
 
8eea021
 
 
 
 
 
 
ba353aa
 
8eea021
 
ba353aa
8eea021
 
ba353aa
 
 
8eea021
 
 
 
 
 
 
ba353aa
8eea021
ba353aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8eea021
 
ba353aa
8eea021
ba353aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc46e44
 
 
 
 
c469a8c
fc46e44
c469a8c
b0d5ee7
c469a8c
 
b0d5ee7
fc46e44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ba353aa
 
 
 
8eea021
 
ba353aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8eea021
 
 
 
 
 
ba353aa
8eea021
ba353aa
8eea021
 
 
 
 
ba353aa
8eea021
ba353aa
 
 
8eea021
 
ba353aa
8eea021
 
 
 
ba353aa
8eea021
 
 
 
ba353aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b0d5ee7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8eea021
 
 
 
 
 
 
ba353aa
8eea021
ba353aa
8eea021
 
ba353aa
8eea021
ba353aa
 
 
 
 
 
 
 
 
 
 
 
8eea021
 
 
 
 
 
ba353aa
8eea021
ba353aa
8eea021
 
 
 
 
ba353aa
8eea021
ba353aa
8eea021
 
ba353aa
8eea021
 
 
 
ba353aa
8eea021
 
 
 
ba353aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b0d5ee7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8eea021
 
 
 
 
 
 
ba353aa
8eea021
ba353aa
b0d5ee7
 
 
 
 
ba353aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b0d5ee7
ba353aa
 
 
 
8eea021
 
 
ba353aa
8eea021
ba353aa
8eea021
ba353aa
 
 
8eea021
ba353aa
 
 
 
 
 
 
 
 
8eea021
 
 
ba353aa
 
8eea021
 
ba353aa
8eea021
 
ba353aa
 
8eea021
 
 
ba353aa
8eea021
ba353aa
8eea021
 
ba353aa
 
8eea021
ba353aa
 
8eea021
 
 
ba353aa
 
8eea021
 
ba353aa
8eea021
 
 
 
c469a8c
 
 
b0d5ee7
 
 
 
 
 
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
import sys
sys.stdout.reconfigure(encoding='utf-8')

import gradio as gr
import open_clip
from pymilvus import MilvusClient
from PIL import Image
import torch
import time
import os
import requests

import json
import psycopg2
import re
from datetime import datetime, timedelta
from io import BytesIO
from dotenv import load_dotenv

# Load environment variables from .env file (for local development)
load_dotenv()

# ============================================
# 0. Zilliz Cloud connection
# ============================================
ZILLIZ_ENDPOINT = os.environ.get("ZILLIZ_ENDPOINT")
ZILLIZ_API_KEY = os.environ.get("ZILLIZ_API_KEY")

client = MilvusClient(uri=ZILLIZ_ENDPOINT, token=ZILLIZ_API_KEY)
print("Connected to Zilliz Cloud")

# ============================================
# 1. Load models
# ============================================
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f"Using device: {device}")

print("Loading SigLIP (768-dim)...")
siglip_model, _, siglip_preprocess = open_clip.create_model_and_transforms(
    "ViT-B-16-SigLIP", pretrained="webli"
)
siglip_tokenizer = open_clip.get_tokenizer("ViT-B-16-SigLIP")
siglip_model = siglip_model.to(device).half().eval()

print("Loading MobileCLIP (512-dim)...")
mobile_model, _, mobile_preprocess = open_clip.create_model_and_transforms(
    "MobileCLIP-S1", pretrained="datacompdr"
)
mobile_tokenizer = open_clip.get_tokenizer("MobileCLIP-S1")
mobile_model = mobile_model.to(device).half().eval()

# ============================================
# 2. Placeholder image for when no path is available
# ============================================
placeholder_img = Image.new('RGBA', (1, 1), (0, 0, 0, 0))
placeholder_buf = BytesIO()
placeholder_img.save(placeholder_buf, format='PNG')
PLACEHOLDER_PATH = "placeholder.png"
with open(PLACEHOLDER_PATH, 'wb') as f:
    f.write(placeholder_buf.getvalue())

# ============================================
# 3. Embedding helpers
# ============================================
def get_text_embedding(query, dim):
    if dim == 768:
        model = siglip_model
        tokenizer = siglip_tokenizer
    elif dim == 512:
        model = mobile_model
        tokenizer = mobile_tokenizer
    else:
        raise ValueError(f"Unsupported dimension: {dim}")

    tokens = tokenizer([query]).to(device)
    with torch.no_grad():
        features = model.encode_text(tokens)
        features = features / features.norm(p=2, dim=-1, keepdim=True)
    return features.cpu().numpy()[0].tolist()

def get_image_embedding(img, dim):
    if dim == 768:
        model = siglip_model
        preprocess = siglip_preprocess
    elif dim == 512:
        model = mobile_model
        preprocess = mobile_preprocess
    else:
        raise ValueError(f"Unsupported dimension: {dim}")

    img_tensor = preprocess(img).unsqueeze(0).to(device).half()
    with torch.no_grad():
        features = model.encode_image(img_tensor)
        features = features / features.norm(p=2, dim=-1, keepdim=True)
    return features.cpu().numpy()[0].tolist()

# ============================================
# 4. Get all collections – detect actual image path field
# ============================================
POSSIBLE_PATH_FIELDS = ["path", "filename", "source", "uri", "image_path", "img_path"]

def get_all_collections():
    all_collections = client.list_collections()
    usable = {}
    for col_name in all_collections:
        try:
            schema = client.describe_collection(col_name)
            dim = None
            vector_field = None
            path_field = None

            for field in schema['fields']:
                if field['name'] == 'vector' or field.get('type') == 'VECTOR':
                    vector_field = field['name']
                    dim = field['params']['dim']
                elif field['name'] in POSSIBLE_PATH_FIELDS:
                    path_field = field['name']

            if dim is None:
                print(f"⏭️ Skipping collection '{col_name}' – no vector field found")
                continue

            parts = client.list_partitions(col_name)
            parts = [p for p in parts if p not in ('_default', '_meta')]
            parts.sort()

            usable[col_name] = {
                'dim': dim,
                'vector_field': vector_field,
                'partitions': parts,
                'path_field': path_field
            }
            if path_field:
                print(f"βœ… Collection '{col_name}' ready (dim={dim}, path field='{path_field}')")
            else:
                print(f"⚠️ Collection '{col_name}' ready (dim={dim}, NO image path field – using placeholder)")
        except Exception as e:
            print(f"⚠️ Error processing collection {col_name}: {e}")
            continue
    return usable

# ============================================
# 5. Date offset per collection (stored date behind by these days)
# ============================================
COLLECTION_DATE_OFFSET = {
    "febsiglip_fix": 1,
    "febmobileclip_fix": 1,
    "vehicle_search_siglip": 2,
    "mobileclip_vectors": 2,
    "alpr_camera_partitions": 2,
    "alpr_vehicle_type_partitions": 2,
}

def parse_date_from_query(query, offset_days=0):
    query_lower = query.lower()
    months = {
        'jan': 1, 'feb': 2, 'mar': 3, 'apr': 4, 'may': 5, 'jun': 6,
        'jul': 7, 'aug': 8, 'sep': 9, 'oct': 10, 'nov': 11, 'dec': 12
    }
    date_str = None
    year = 2026

    for month_word, month_num in months.items():
        if month_word in query_lower:
            pattern = rf'{month_word}[a-z]*\s+(\d{{1,2}})(?:st|nd|rd|th)?'
            match = re.search(pattern, query_lower)
            if match:
                day = int(match.group(1))
                date_str = f"{year:04d}_{month_num:02d}_{day:02d}"
                break
            pattern = rf'(\d{{1,2}})(?:st|nd|rd|th)?\s+{month_word}[a-z]*'
            match = re.search(pattern, query_lower)
            if match:
                day = int(match.group(1))
                date_str = f"{year:04d}_{month_num:02d}_{day:02d}"
                break

    if not date_str:
        match = re.search(r'(\d{1,2})[-/](\d{1,2})', query)
        if match:
            month, day = int(match.group(1)), int(match.group(2))
            date_str = f"{year:04d}_{month:02d}_{day:02d}"
        else:
            match = re.search(r'(\d{4})[-/](\d{1,2})[-/](\d{1,2})', query)
            if match:
                year, month, day = int(match.group(1)), int(match.group(2)), int(match.group(3))
                date_str = f"{year:04d}_{month:02d}_{day:02d}"

    if date_str:
        dt = datetime.strptime(date_str.replace('_', '-'), '%Y-%m-%d')
        dt_adjusted = dt - timedelta(days=offset_days)
        return dt_adjusted.strftime('%Y_%m_%d')
    return None

def fetch_urls_from_db(data):
    timestamps_to_fetch = [hit.get('timestamp') for hit in data if hit.get('timestamp')]
    url_map = {}
    if timestamps_to_fetch:
        try:
            db_password = os.environ.get("DB_PASSWORD")
            conn = psycopg2.connect(
                host=os.environ.get("DB_HOST"),
                port=int(os.environ.get("DB_PORT", 5432)),
                database=os.environ.get("DB_NAME"),
                user=os.environ.get("DB_USER"),
                password=db_password,
                sslmode='require'
            )
            cursor = conn.cursor()
            cursor.execute('SELECT timestamp, metadata FROM alpr_data.alpr_event WHERE timestamp IN %s', (tuple(timestamps_to_fetch),))
            for row in cursor.fetchall():
                ts = row[0]
                try:
                    meta = json.loads(row[1]) if isinstance(row[1], str) else row[1]
                    image_id = meta.get('image', {}).get('id')
                    camera_id = meta.get('source', {}).get('id')
                    if image_id and camera_id and ts:
                        epoch_day = (int(ts) // 86400000) * 86400000
                        url = f"https://s3.us-east-1.wasabisys.com/adept-data-archive-742i3ur2uryo2j3n847234tu2/alpr/img-{epoch_day}/{camera_id}/{image_id}.jpeg"
                        url_map[ts] = url
                except Exception:
                    pass
            cursor.close()
            conn.close()
        except Exception as e:
            print("DB error:", e)
    return url_map

# ============================================
# 6. Text search – uses detected path field, hides path/id from label
# ============================================
def search_vcu(collection_name, partition_name, query, limit=20):
    if not query.strip():
        return [], "⚠️ Please enter a query", 0

    col_info = collections_data.get(collection_name)
    if not col_info:
        return [], f"❌ Collection '{collection_name}' not found", 0

    dim = col_info['dim']
    vector_field = col_info['vector_field']
    path_field = col_info.get('path_field')

    q_emb = get_text_embedding(query, dim)

    offset_days = COLLECTION_DATE_OFFSET.get(collection_name, 0)
    date_str = parse_date_from_query(query, offset_days)
    filter_str = None
    if date_str:
        filter_str = f'date == "{date_str}"'
        print(f"πŸ” Date filter: {date_str} (offset {offset_days} days)")

    url = f"{ZILLIZ_ENDPOINT}/v2/vectordb/entities/search"
    headers = {
        "Authorization": f"Bearer {ZILLIZ_API_KEY}",
        "Content-Type": "application/json"
    }
    payload = {
        "collectionName": collection_name,
        "data": [q_emb],
        "annsField": vector_field,
        "limit": limit,
        "searchParams": {
            "metricType": "COSINE",
            "params": {"nprobe": 10}
        },
        "outputFields": ["*"]
    }

    if filter_str:
        payload["filter"] = filter_str
    if partition_name and partition_name != "All":
        payload["partitionNames"] = [partition_name]

    start = time.time()
    try:
        response = requests.post(url, headers=headers, json=payload, timeout=30)
        latency_ms = (time.time() - start) * 1000

        if response.status_code == 200:
            result = response.json()
            vcu_used = result.get('cost', 0)
            data = result.get('data', [])
            gallery = []
            for hit in data:
                # Build label excluding path, id, vector, distance (we already show distance first)
                parts = [f"Distance: {hit.get('distance', 0):.3f}"]
                for key, value in hit.items():
                    if key in ('distance', 'vector', 'path', 'id') or value is None:
                        continue
                    # Date correction if needed
                    if key == 'date' and offset_days and isinstance(value, str):
                        try:
                            dt = datetime.strptime(value, '%Y_%m_%d')
                            corrected_dt = dt + timedelta(days=offset_days)
                            value = corrected_dt.strftime('%Y_%m_%d')
                        except:
                            pass
                    parts.append(f"{key.capitalize()}: {value}")
                label = " | ".join(parts)

                # Image URL handling: prefer S3 URL from DB, fallback to local path or placeholder
                ts = hit.get('timestamp')
                gallery.append((hit, label))  # temporarily store hit for batch processing

            # Batch fetch S3 URLs from DB for all hits
            url_map = fetch_urls_from_db(data)
            final_gallery = []
            for (hit, label) in gallery:
                ts = hit.get('timestamp')
                img_src = url_map.get(ts) if ts else None
                if not img_src:
                    if path_field:
                        local_path = hit.get(path_field, '')
                        img_src = local_path if local_path and os.path.exists(local_path) else PLACEHOLDER_PATH
                    else:
                        img_src = PLACEHOLDER_PATH
                final_gallery.append((img_src, label))
            gallery = final_gallery

            status = f"βœ… {len(final_gallery)} results | Latency: {latency_ms:.1f} ms | vCU: {vcu_used:.2f} | Filter: {filter_str if filter_str else 'None'}"
            return gallery, status, vcu_used
        else:
            return [], f"❌ API Error: {response.status_code} - {response.text}", 0
    except Exception as e:
        return [], f"❌ Error: {e}", 0

# ============================================
# 7. Image search – same logic
# ============================================
def search_image_vcu(collection_name, partition_name, query_image, limit=20):
    if query_image is None:
        return [], "⚠️ Please upload an image", 0

    img = Image.open(query_image).convert('RGB')

    col_info = collections_data.get(collection_name)
    if not col_info:
        return [], f"❌ Collection '{collection_name}' not found", 0

    dim = col_info['dim']
    vector_field = col_info['vector_field']
    path_field = col_info.get('path_field')

    q_emb = get_image_embedding(img, dim)
    offset_days = COLLECTION_DATE_OFFSET.get(collection_name, 0)

    url = f"{ZILLIZ_ENDPOINT}/v2/vectordb/entities/search"
    headers = {
        "Authorization": f"Bearer {ZILLIZ_API_KEY}",
        "Content-Type": "application/json"
    }
    payload = {
        "collectionName": collection_name,
        "data": [q_emb],
        "annsField": vector_field,
        "limit": limit,
        "searchParams": {
            "metricType": "COSINE",
            "params": {"nprobe": 10}
        },
        "outputFields": ["*"]
    }

    if partition_name and partition_name != "All":
        payload["partitionNames"] = [partition_name]

    start = time.time()
    try:
        response = requests.post(url, headers=headers, json=payload, timeout=30)
        latency_ms = (time.time() - start) * 1000

        if response.status_code == 200:
            result = response.json()
            vcu_used = result.get('cost', 0)
            data = result.get('data', [])
            gallery = []
            for hit in data:
                parts = [f"Distance: {hit.get('distance', 0):.3f}"]
                for key, value in hit.items():
                    if key in ('distance', 'vector', 'path', 'id') or value is None:
                        continue
                    if key == 'date' and offset_days and isinstance(value, str):
                        try:
                            dt = datetime.strptime(value, '%Y_%m_%d')
                            corrected_dt = dt + timedelta(days=offset_days)
                            value = corrected_dt.strftime('%Y_%m_%d')
                        except:
                            pass
                    parts.append(f"{key.capitalize()}: {value}")
                label = " | ".join(parts)

                gallery.append((hit, label))  # temporarily store hit for batch processing

            # Batch fetch S3 URLs from DB for all hits
            url_map = fetch_urls_from_db(data)
            final_gallery = []
            for (hit, label) in gallery:
                ts = hit.get('timestamp')
                img_src = url_map.get(ts) if ts else None
                if not img_src:
                    if path_field:
                        local_path = hit.get(path_field, '')
                        img_src = local_path if local_path and os.path.exists(local_path) else PLACEHOLDER_PATH
                    else:
                        img_src = PLACEHOLDER_PATH
                final_gallery.append((img_src, label))
            gallery = final_gallery

            status = f"βœ… {len(final_gallery)} results | Latency: {latency_ms:.1f} ms | vCU: {vcu_used:.2f}"
            return gallery, status, vcu_used
        else:
            return [], f"❌ API Error: {response.status_code} - {response.text}", 0
    except Exception as e:
        return [], f"❌ Error: {e}", 0

# ============================================
# 8. Load collections into memory & build UI
# ============================================
collections_data = get_all_collections()

# Filter to only show specific collections
ALLOWED_COLLECTIONS = ["febmobileclip_fix", "febsiglip_fix"]
collections_data = {k: v for k, v in collections_data.items() if k in ALLOWED_COLLECTIONS}

collection_names = sorted(collections_data.keys())

if not collection_names:
    print("⚠️ No collections found. Check your Zilliz Cloud connection.")
    gr.Warning("No collections found.")
else:
    print("Loading all collections into memory...")
    for col_name in collection_names:
        try:
            client.load_collection(col_name)
            print(f"βœ… Loaded: {col_name}")
        except Exception as e:
            print(f"⚠️ Could not load {col_name}: {e}")
    print("All collections ready.")

with gr.Blocks(title="Vehicle Search - Zilliz Cloud") as demo:
    gr.Markdown("# πŸ” Multimodal Vehicle Search – Zilliz Cloud")
    gr.Markdown("All collections are shown. If an image path exists, real images are displayed. File paths and internal IDs are hidden from captions. Date filters are auto‑applied with offset correction.")

    # ----- Text Search -----
    with gr.Tab("Text Search"):
        with gr.Row():
            collection_selector = gr.Dropdown(
                choices=collection_names,
                label="Collection",
                value=collection_names[0] if collection_names else None
            )
            query_txt = gr.Textbox(label="Search Query", scale=3, placeholder="e.g., motorcycle on feb 13th")
            limit_txt = gr.Slider(5, 200, value=20, step=1, label="Results")

        partition_selector = gr.Dropdown(choices=["All"], label="Partition", value="All")

        def update_partitions(col_name):
            if col_name in collections_data:
                parts = collections_data[col_name]['partitions']
                return gr.update(choices=["All"] + parts, value="All")
            return gr.update(choices=["All"], value="All")

        collection_selector.change(update_partitions, inputs=collection_selector, outputs=partition_selector)

        btn_search = gr.Button("πŸ” Search", variant="primary")
        gallery_txt = gr.Gallery(label="Results", columns=4, height=500)
        status_txt = gr.Textbox(label="Status", interactive=False)
        vcu_display = gr.Textbox(label="vCU Used", interactive=False)

        btn_search.click(
            search_vcu,
            [collection_selector, partition_selector, query_txt, limit_txt],
            [gallery_txt, status_txt, vcu_display]
        )

    # ----- Image Search -----
    with gr.Tab("Image Search"):
        with gr.Row():
            collection_selector_img = gr.Dropdown(
                choices=collection_names,
                label="Collection",
                value=collection_names[0] if collection_names else None
            )
            query_img = gr.Image(type="filepath", label="Upload Image")
            limit_img = gr.Slider(5, 200, value=20, step=1, label="Results")

        partition_selector_img = gr.Dropdown(choices=["All"], label="Partition", value="All")
        collection_selector_img.change(update_partitions, inputs=collection_selector_img, outputs=partition_selector_img)

        btn_search_img = gr.Button("πŸ” Search Similar", variant="primary")
        gallery_img = gr.Gallery(label="Similar Images", columns=4, height=500)
        status_img = gr.Textbox(label="Status", interactive=False)
        vcu_display_img = gr.Textbox(label="vCU Used", interactive=False)

        btn_search_img.click(
            search_image_vcu,
            [collection_selector_img, partition_selector_img, query_img, limit_img],
            [gallery_img, status_img, vcu_display_img]
        )

if __name__ == "__main__":
    # Fetch credentials from environment variables for security
    USERNAME = os.environ.get("GRADIO_USERNAME")
    PASSWORD = os.environ.get("GRADIO_PASSWORD")
    
    demo.launch(
        share=True, 
        allowed_paths=["D:\\"],
        auth=(USERNAME, PASSWORD)
    )