Spaces:
Sleeping
Sleeping
Download engine.py from PlateSmart/vehicle-search: direct link, hf CLI and curl.
- Browser
- Download file 20.1 kB
-
https://huggingface.co/spaces/PlateSmart/vehicle-search/resolve/main/engine.py
- Command line
-
hf download hf://spaces/PlateSmart/vehicle-search/engine.py
-
curl -L -o engine.py https://huggingface.co/spaces/PlateSmart/vehicle-search/resolve/main/engine.py
20.1 kB
| 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) | |
| ) | |