StillWorking commited on
Commit
35e2e54
Β·
verified Β·
1 Parent(s): 87d6e18

Upload backend/api/routes/search.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. backend/api/routes/search.py +165 -0
backend/api/routes/search.py ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ api/routes/search.py β€” Sentinel-AI
3
+ ========================================
4
+ POST /api/v1/semantic-search
5
+
6
+ Allows operators to search the FAISS metadata database using natural
7
+ language (e.g. "young male with wavy hair and eyeglasses").
8
+
9
+ Pipeline:
10
+ 1. cascadeflow + Gemini extracts CelebA attribute names from the query
11
+ 2. Negative constraints (e.g. "woman" β†’ exclude Male) are derived
12
+ deterministically, because CelebA has no positive Female/Old label
13
+ 3. FAISS metadata is filtered for entries matching ALL extracted attributes
14
+ and NONE of the excluded attributes
15
+
16
+ No vector comparison is performed here β€” this is pure metadata filtering.
17
+ The filter is backed by a cached NumPy boolean attribute matrix (milliseconds
18
+ on 202k rows) and runs in a worker thread so it never blocks the event loop.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import asyncio
24
+ import os
25
+ import re
26
+ from typing import Any
27
+
28
+ from fastapi import APIRouter, HTTPException
29
+ from fastapi.responses import FileResponse
30
+
31
+ from api.schemas import (
32
+ CascadeflowMetrics,
33
+ SemanticSearchMatch,
34
+ SemanticSearchRequest,
35
+ SemanticSearchResponse,
36
+ )
37
+ from core.faiss_store import get_faiss_order, search_by_attributes
38
+ from core.gemini_agent import extract_attributes_from_query
39
+ from core.paths import resolve_path
40
+
41
+ router = APIRouter()
42
+
43
+ # Image directory from environment, anchored to the backend package.
44
+ IMAGES_DIR = resolve_path(
45
+ os.getenv("CELEBA_IMAGES_DIR"),
46
+ "../Data/img_align_celeba",
47
+ )
48
+
49
+ # Celebrity images are always zero-padded 6-digit JPEG filenames.
50
+ _IMAGE_ID_RE = re.compile(r"^\d{6}\.jpg$")
51
+
52
+
53
+ # ─────────────────────────────────────────────────────────────────────────────
54
+ @router.post(
55
+ "/semantic-search",
56
+ response_model=SemanticSearchResponse,
57
+ summary="Search the face database with a natural-language description",
58
+ )
59
+ async def semantic_search(body: SemanticSearchRequest) -> SemanticSearchResponse:
60
+ """
61
+ Search the face database using plain English.
62
+
63
+ - **query**: natural-language description, e.g. *"older male with grey hair and a goatee"*
64
+ - **top_k**: maximum number of matching image IDs to return (default 10)
65
+ """
66
+ # ── 1. Gemini: extract structured CelebA attributes from query ────────────
67
+ agent_result: dict[str, Any] = await extract_attributes_from_query(query=body.query)
68
+
69
+ extracted_attrs: list[str] = agent_result.get("attributes", [])
70
+ excluded_attrs: list[str] = agent_result.get("excluded_attributes", [])
71
+ cf_metrics_raw = agent_result.get("cascadeflow_metrics", {})
72
+
73
+ cf_metrics = CascadeflowMetrics(
74
+ latency_ms=cf_metrics_raw.get("latency_ms", 0.0),
75
+ cost_usd=cf_metrics_raw.get("cost_usd", 0.0),
76
+ )
77
+
78
+ # A query can consist solely of a negative constraint ("a woman" β†’
79
+ # exclude Male), so both lists must be empty before giving up.
80
+ if not extracted_attrs and not excluded_attrs:
81
+ return SemanticSearchResponse(
82
+ status="no_attributes_extracted",
83
+ query=body.query,
84
+ extracted_attrs=[],
85
+ excluded_attrs=[],
86
+ matches=[],
87
+ cascadeflow_metrics=cf_metrics,
88
+ )
89
+
90
+ # ── 2. FAISS metadata filter (offloaded: NumPy still does real work) ─────
91
+ raw_matches = await asyncio.to_thread(
92
+ search_by_attributes,
93
+ required_attrs=extracted_attrs,
94
+ top_k=body.top_k,
95
+ excluded_attrs=excluded_attrs,
96
+ )
97
+
98
+ matches = [
99
+ SemanticSearchMatch(
100
+ image_id=m["image_id"],
101
+ attributes=m["attributes"],
102
+ faiss_id=m["faiss_id"],
103
+ )
104
+ for m in raw_matches
105
+ ]
106
+
107
+ return SemanticSearchResponse(
108
+ status="success" if matches else "no_matches_found",
109
+ query=body.query,
110
+ extracted_attrs=extracted_attrs,
111
+ excluded_attrs=excluded_attrs,
112
+ matches=matches,
113
+ cascadeflow_metrics=cf_metrics,
114
+ )
115
+
116
+
117
+ # ─────────────────────────────────────────────────────────────────────────────
118
+ @router.get(
119
+ "/images/{image_id}",
120
+ response_class=FileResponse,
121
+ summary="Serve a CelebA image by filename or FAISS ID",
122
+ )
123
+ async def serve_image(image_id: str) -> FileResponse:
124
+ """
125
+ Serve a CelebA face image.
126
+
127
+ - **image_id**: filename (e.g. "000001.jpg") or FAISS ID (e.g. "0")
128
+
129
+ Only files inside ``CELEBA_IMAGES_DIR`` are served; anything that could
130
+ escape that directory (``../``, backslashes, alternate data streams) is
131
+ rejected with 400 before touching the filesystem.
132
+ """
133
+ if image_id.isdigit():
134
+ # Map the FAISS insertion id to its filename. Fall back to the
135
+ # dataset's 1-based naming when the index artifact predates
136
+ # faiss_order.json.
137
+ try:
138
+ order = get_faiss_order()
139
+ faiss_id = int(image_id)
140
+ filename = order[faiss_id] if 0 <= faiss_id < len(order) else ""
141
+ except Exception:
142
+ filename = ""
143
+ if not filename:
144
+ filename = f"{int(image_id) + 1:06d}.jpg"
145
+ else:
146
+ filename = image_id
147
+
148
+ if not _IMAGE_ID_RE.match(filename):
149
+ raise HTTPException(status_code=400, detail="Invalid image identifier.")
150
+
151
+ images_root = IMAGES_DIR.resolve()
152
+ image_path = (images_root / filename).resolve()
153
+
154
+ # Defense in depth: the regex already forbids separators and dots.
155
+ if not image_path.is_relative_to(images_root):
156
+ raise HTTPException(status_code=400, detail="Invalid image identifier.")
157
+
158
+ if not image_path.is_file():
159
+ raise HTTPException(status_code=404, detail="Image not found.")
160
+
161
+ return FileResponse(
162
+ path=str(image_path),
163
+ media_type="image/jpeg",
164
+ headers={"Cache-Control": "public, max-age=86400"},
165
+ )