Spaces:
Paused

jw-tools commited on
Commit
19b362c
·
verified ·
1 Parent(s): 948817a

Refactor v2: stability, hosted hardening, porter+timestamps, dual shards (480x270 video + pub), analytics

Browse files
Dockerfile CHANGED
@@ -12,10 +12,12 @@ ENV PYTHONDONTWRITEBYTECODE=1 \
12
  PYTHONUNBUFFERED=1 \
13
  PIP_NO_CACHE_DIR=1
14
 
 
 
 
 
15
  RUN apt-get update && apt-get install -y --no-install-recommends \
16
  curl \
17
- ffmpeg \
18
- git \
19
  libgl1 \
20
  libglib2.0-0 \
21
  libgomp1 \
@@ -46,7 +48,8 @@ ENV HOME=/home/user \
46
  SEARCH_UI_DATA_ROOT=/data/search-ui \
47
  SEARCH_UI_FRONTEND_DIST=/app/frontend/dist \
48
  SEARCH_UI_CORS_ORIGINS=* \
49
- SEARCH_UI_STRICT_STARTUP=true
 
50
 
51
  EXPOSE 7860
52
 
 
12
  PYTHONUNBUFFERED=1 \
13
  PIP_NO_CACHE_DIR=1
14
 
15
+ # Search-only runtime: ffmpeg (thumbnail/video generation) and git (no
16
+ # git-sourced wheels in requirements-hf) are ingestion-only and dropped to slim
17
+ # the image. libgomp1 is required by torch; libgl1/libglib2.0-0 are kept for
18
+ # the optional DeepFace (cv2) face-image path.
19
  RUN apt-get update && apt-get install -y --no-install-recommends \
20
  curl \
 
 
21
  libgl1 \
22
  libglib2.0-0 \
23
  libgomp1 \
 
48
  SEARCH_UI_DATA_ROOT=/data/search-ui \
49
  SEARCH_UI_FRONTEND_DIST=/app/frontend/dist \
50
  SEARCH_UI_CORS_ORIGINS=* \
51
+ SEARCH_UI_STRICT_STARTUP=true \
52
+ SEARCH_UI_HOSTED_MODE=true
53
 
54
  EXPOSE 7860
55
 
backend/app_config.py CHANGED
@@ -141,6 +141,7 @@ class AppConfig:
141
  startup_check_ffmpeg: bool
142
  startup_check_frontend: bool
143
  strict_startup: bool
 
144
  task_status_file: str
145
  new_content_cache_ttl_seconds: int
146
  online_catalog_cache_ttl_seconds: int
@@ -150,6 +151,7 @@ def load_app_config() -> AppConfig:
150
  backend_dir = get_backend_dir()
151
  json_dir = get_json_dir()
152
  cors_origins, cors_origin_regex = _parse_cors_origins()
 
153
  return AppConfig(
154
  backend_dir=backend_dir,
155
  data_root=get_data_root(),
@@ -166,9 +168,18 @@ def load_app_config() -> AppConfig:
166
  cors_origin_regex=cors_origin_regex,
167
  cors_allow_credentials=_get_cors_allow_credentials(cors_origins),
168
  startup_checks_enabled=_get_bool_env("SEARCH_UI_STARTUP_CHECKS", True),
169
- startup_check_ffmpeg=_get_bool_env("SEARCH_UI_STARTUP_CHECK_FFMPEG", True),
 
 
 
 
170
  startup_check_frontend=_get_bool_env("SEARCH_UI_STARTUP_CHECK_FRONTEND", False),
171
  strict_startup=_get_bool_env("SEARCH_UI_STRICT_STARTUP", True),
 
 
 
 
 
172
  task_status_file=os.path.join(json_dir, "last_updated.json"),
173
  new_content_cache_ttl_seconds=max(
174
  _get_int_env("SEARCH_UI_NEW_CONTENT_CACHE_TTL_SECONDS", 600),
 
141
  startup_check_ffmpeg: bool
142
  startup_check_frontend: bool
143
  strict_startup: bool
144
+ hosted_mode: bool
145
  task_status_file: str
146
  new_content_cache_ttl_seconds: int
147
  online_catalog_cache_ttl_seconds: int
 
151
  backend_dir = get_backend_dir()
152
  json_dir = get_json_dir()
153
  cors_origins, cors_origin_regex = _parse_cors_origins()
154
+ hosted_mode = _get_bool_env("SEARCH_UI_HOSTED_MODE", False)
155
  return AppConfig(
156
  backend_dir=backend_dir,
157
  data_root=get_data_root(),
 
168
  cors_origin_regex=cors_origin_regex,
169
  cors_allow_credentials=_get_cors_allow_credentials(cors_origins),
170
  startup_checks_enabled=_get_bool_env("SEARCH_UI_STARTUP_CHECKS", True),
171
+ # ffmpeg is an ingestion-only tool; the search-only hosted image drops
172
+ # it (S2.8), so don't require it there by default.
173
+ startup_check_ffmpeg=_get_bool_env(
174
+ "SEARCH_UI_STARTUP_CHECK_FFMPEG", not hosted_mode
175
+ ),
176
  startup_check_frontend=_get_bool_env("SEARCH_UI_STARTUP_CHECK_FRONTEND", False),
177
  strict_startup=_get_bool_env("SEARCH_UI_STRICT_STARTUP", True),
178
+ # Hosted (Hugging Face Space) deployments serve search from a prebuilt
179
+ # data bundle; ingestion/admin work happens on the local machine that
180
+ # produces the bundle. When true, main.create_app() does not mount the
181
+ # ingestion/admin routers at all, so those endpoints cannot run there.
182
+ hosted_mode=hosted_mode,
183
  task_status_file=os.path.join(json_dir, "last_updated.json"),
184
  new_content_cache_ttl_seconds=max(
185
  _get_int_env("SEARCH_UI_NEW_CONTENT_CACHE_TTL_SECONDS", 600),
backend/auth.py CHANGED
@@ -52,16 +52,38 @@ def is_auth_enabled() -> bool:
52
  return bool(get_app_password())
53
 
54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
  def _session_token(password: str) -> str:
56
  """Return a deterministic, non-reversible cookie value for ``password``.
57
 
58
  Stable across restarts (so logins survive a reboot) and keyed so the raw
59
  password is never stored in the browser. Its strength is equivalent to the
60
- password, which is acceptable for a single shared LAN secret.
 
61
  """
62
- return hmac.new(
63
- b"searchui-auth-v1", password.encode("utf-8"), hashlib.sha256
64
- ).hexdigest()
65
 
66
 
67
  def expected_token() -> str:
 
52
  return bool(get_app_password())
53
 
54
 
55
+ def is_using_default_password() -> bool:
56
+ """True when no password was configured, so the public default is in use.
57
+
58
+ The default ``"JWSearch"`` is committed in this public repo, so a public
59
+ deployment that doesn't set ``SEARCH_UI_APP_PASSWORD`` is effectively open.
60
+ """
61
+ return os.environ.get("SEARCH_UI_APP_PASSWORD") in (None, _DEFAULT_PASSWORD)
62
+
63
+
64
+ def _auth_secret() -> str:
65
+ """Optional server-side secret mixed into the session token.
66
+
67
+ When set (``SEARCH_UI_AUTH_SECRET``), rotating it invalidates every
68
+ existing cookie without changing the password — a coarse "log everyone
69
+ out" / key-rotation lever the stateless token otherwise can't offer
70
+ (logout only deletes the client cookie, so a captured cookie stayed valid
71
+ until the password changed). When unset, the token is byte-identical to the
72
+ pre-secret scheme, so existing sessions survive a deploy.
73
+ """
74
+ return os.environ.get("SEARCH_UI_AUTH_SECRET", "")
75
+
76
+
77
  def _session_token(password: str) -> str:
78
  """Return a deterministic, non-reversible cookie value for ``password``.
79
 
80
  Stable across restarts (so logins survive a reboot) and keyed so the raw
81
  password is never stored in the browser. Its strength is equivalent to the
82
+ password (plus the optional server secret), which is acceptable for a
83
+ single shared LAN secret.
84
  """
85
+ key = b"searchui-auth-v1" + _auth_secret().encode("utf-8")
86
+ return hmac.new(key, password.encode("utf-8"), hashlib.sha256).hexdigest()
 
87
 
88
 
89
  def expected_token() -> str:
backend/batch_processor.py CHANGED
@@ -21,7 +21,7 @@ import json
21
  import time
22
  import gc
23
  from datetime import datetime
24
- from typing import Dict, List, Any, Optional, Tuple
25
  from dataclasses import dataclass, asdict
26
  from contextlib import contextmanager
27
 
@@ -281,119 +281,6 @@ class MemoryMonitor:
281
  return False
282
 
283
 
284
- class BatchDatabaseWriter:
285
- """
286
- Batch database operations for efficiency.
287
-
288
- Instead of opening a connection per insert, batches multiple
289
- operations into transactions.
290
- """
291
-
292
- def __init__(self, search_images_module, face_search_module):
293
- self.search_images = search_images_module
294
- self.face_search = face_search_module
295
-
296
- # Pending operations
297
- self.pending_categories = []
298
- self.pending_embeddings = []
299
- self.pending_faces = []
300
-
301
- self.batch_size = 50 # Commit every N operations
302
-
303
- def add_categories(self, natural_key: str, frame_number: int, categories: List[Dict]):
304
- """Queue categories for batch insert."""
305
- for cat in categories:
306
- self.pending_categories.append({
307
- 'natural_key': natural_key,
308
- 'frame_number': frame_number,
309
- 'category_name': cat.get('label', ''),
310
- 'score': cat.get('score', 0.0)
311
- })
312
-
313
- if len(self.pending_categories) >= self.batch_size:
314
- self.flush_categories()
315
-
316
- def add_embedding(self, natural_key: str, frame_number: int, embedding):
317
- """Queue embedding for batch insert."""
318
- self.pending_embeddings.append({
319
- 'natural_key': natural_key,
320
- 'frame_number': frame_number,
321
- 'embedding': embedding
322
- })
323
-
324
- if len(self.pending_embeddings) >= self.batch_size:
325
- self.flush_embeddings()
326
-
327
- def flush_categories(self) -> int:
328
- """Flush pending categories to database."""
329
- if not self.pending_categories:
330
- return 0
331
-
332
- image_search = self.search_images.ImageSearch()
333
- conn = image_search._get_db_connection()
334
-
335
- try:
336
- conn.execute("BEGIN")
337
-
338
- for cat in self.pending_categories:
339
- conn.execute("""
340
- INSERT INTO image_categories (natural_key, frame_number, category_name, score)
341
- VALUES (?, ?, ?, ?)
342
- """, (cat['natural_key'], cat['frame_number'], cat['category_name'], cat['score']))
343
-
344
- conn.commit()
345
- count = len(self.pending_categories)
346
- self.pending_categories = []
347
- return count
348
-
349
- except Exception as e:
350
- conn.rollback()
351
- raise e
352
- finally:
353
- conn.close()
354
-
355
- def flush_embeddings(self) -> int:
356
- """Flush pending embeddings to database."""
357
- if not self.pending_embeddings:
358
- return 0
359
-
360
- import numpy as np
361
-
362
- image_search = self.search_images.ImageSearch()
363
- conn = image_search._get_db_connection()
364
-
365
- try:
366
- conn.execute("BEGIN")
367
-
368
- for emb in self.pending_embeddings:
369
- embedding = emb['embedding']
370
- embedding_json = json.dumps(
371
- embedding.tolist() if isinstance(embedding, np.ndarray) else embedding
372
- )
373
-
374
- conn.execute("""
375
- INSERT OR REPLACE INTO image_embeddings (natural_key, frame_number, embedding)
376
- VALUES (?, ?, ?)
377
- """, (emb['natural_key'], emb['frame_number'], embedding_json))
378
-
379
- conn.commit()
380
- count = len(self.pending_embeddings)
381
- self.pending_embeddings = []
382
- return count
383
-
384
- except Exception as e:
385
- conn.rollback()
386
- raise e
387
- finally:
388
- conn.close()
389
-
390
- def flush_all(self) -> Tuple[int, int]:
391
- """Flush all pending operations."""
392
- cat_count = self.flush_categories()
393
- emb_count = self.flush_embeddings()
394
- return cat_count, emb_count
395
-
396
-
397
  class PerformanceTracker:
398
  """Track timing for processing stages."""
399
 
@@ -504,7 +391,7 @@ def analyze_processing_bottlenecks() -> Dict[str, Any]:
504
  "component": "Database Writes",
505
  "issue": "Each category/embedding is a separate INSERT with new connection",
506
  "impact": "High - 3000+ connections per video at scale",
507
- "fix": "Use batch transactions (implemented in BatchDatabaseWriter)"
508
  })
509
 
510
  # Check logging
@@ -524,7 +411,7 @@ def analyze_processing_bottlenecks() -> Dict[str, Any]:
524
  })
525
 
526
  recommendations = [
527
- "Use BatchDatabaseWriter for all category/embedding inserts",
528
  "Replace individual FFmpeg calls with batch image processing",
529
  "Set up per-run logging with StructuredLogger",
530
  "Enable memory monitoring with MemoryMonitor",
 
21
  import time
22
  import gc
23
  from datetime import datetime
24
+ from typing import Dict, List, Any, Optional
25
  from dataclasses import dataclass, asdict
26
  from contextlib import contextmanager
27
 
 
281
  return False
282
 
283
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
284
  class PerformanceTracker:
285
  """Track timing for processing stages."""
286
 
 
391
  "component": "Database Writes",
392
  "issue": "Each category/embedding is a separate INSERT with new connection",
393
  "impact": "High - 3000+ connections per video at scale",
394
+ "fix": "Use batch transactions (one transaction per video, not per insert)"
395
  })
396
 
397
  # Check logging
 
411
  })
412
 
413
  recommendations = [
414
+ "Batch category/embedding inserts into one transaction per video",
415
  "Replace individual FFmpeg calls with batch image processing",
416
  "Set up per-run logging with StructuredLogger",
417
  "Enable memory monitoring with MemoryMonitor",
backend/catalog_routes.py CHANGED
@@ -189,7 +189,9 @@ def create_catalog_router(
189
  sort_by: str = "title",
190
  ):
191
  """Get the local video catalog with exclusion and processing state."""
192
- try:
 
 
193
  all_media = load_all_media(language)
194
  if all_media is None:
195
  return {
@@ -227,6 +229,9 @@ def create_catalog_router(
227
  sort_by=sort_by,
228
  )
229
 
 
 
 
230
  except Exception as exc:
231
  log_message(f"Error getting videos list: {exc}", "ERROR")
232
  raise HTTPException(status_code=500, detail=str(exc))
@@ -328,7 +333,10 @@ def create_catalog_router(
328
  force_refresh: bool = False,
329
  ):
330
  """Fetch online videos from JW.org without saving metadata locally."""
331
- try:
 
 
 
332
  online_media = fetch_online_media(language, force_refresh=force_refresh)
333
  if not online_media:
334
  return {
@@ -373,6 +381,9 @@ def create_catalog_router(
373
  sort_by=sort_by,
374
  )
375
 
 
 
 
376
  except Exception as exc:
377
  log_message(f"Error fetching online videos: {exc}", "ERROR")
378
  raise HTTPException(status_code=500, detail=str(exc))
@@ -385,7 +396,7 @@ def create_catalog_router(
385
  force_refresh: bool = False,
386
  ):
387
  """Get categories and subcategories for the cached online catalog."""
388
- try:
389
  online_media = fetch_online_media(language, force_refresh=force_refresh)
390
  if not online_media:
391
  return {"categories": []}
@@ -403,6 +414,10 @@ def create_catalog_router(
403
  )
404
  }
405
 
 
 
 
 
406
  except Exception as exc:
407
  log_message(f"Error getting online categories: {exc}", "ERROR")
408
  raise HTTPException(status_code=500, detail=str(exc))
 
189
  sort_by: str = "title",
190
  ):
191
  """Get the local video catalog with exclusion and processing state."""
192
+ # collect_video_processing_status walks the videos/ tree and runs
193
+ # several DB scans — run the whole build off the event loop.
194
+ def _build():
195
  all_media = load_all_media(language)
196
  if all_media is None:
197
  return {
 
229
  sort_by=sort_by,
230
  )
231
 
232
+ try:
233
+ return await asyncio.to_thread(_build)
234
+
235
  except Exception as exc:
236
  log_message(f"Error getting videos list: {exc}", "ERROR")
237
  raise HTTPException(status_code=500, detail=str(exc))
 
333
  force_refresh: bool = False,
334
  ):
335
  """Fetch online videos from JW.org without saving metadata locally."""
336
+ # fetch_online_media does a live JW.org crawl (one HTTP GET per category)
337
+ # and collect_video_processing_status walks the videos/ tree — both block
338
+ # for seconds, so run the whole thing off the event loop.
339
+ def _build():
340
  online_media = fetch_online_media(language, force_refresh=force_refresh)
341
  if not online_media:
342
  return {
 
381
  sort_by=sort_by,
382
  )
383
 
384
+ try:
385
+ return await asyncio.to_thread(_build)
386
+
387
  except Exception as exc:
388
  log_message(f"Error fetching online videos: {exc}", "ERROR")
389
  raise HTTPException(status_code=500, detail=str(exc))
 
396
  force_refresh: bool = False,
397
  ):
398
  """Get categories and subcategories for the cached online catalog."""
399
+ def _build():
400
  online_media = fetch_online_media(language, force_refresh=force_refresh)
401
  if not online_media:
402
  return {"categories": []}
 
414
  )
415
  }
416
 
417
+ try:
418
+ # Live JW.org crawl on a cache miss — keep it off the event loop.
419
+ return await asyncio.to_thread(_build)
420
+
421
  except Exception as exc:
422
  log_message(f"Error getting online categories: {exc}", "ERROR")
423
  raise HTTPException(status_code=500, detail=str(exc))
backend/chunk_timestamps.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Compute per-chunk start/end timestamps from VTT cues (Q2.2).
2
+
3
+ Subtitle chunks are stored as plain text with no timing — so jump-to-moment for
4
+ a semantic hit is currently *guessed* per query by parsing the whole VTT and
5
+ word-overlapping the snippet against cues (often fails for chunk-length text,
6
+ and re-parses the VTT on every result). This module computes the timestamp
7
+ ONCE, at index/backfill time, by anchoring each chunk's OPENING words against
8
+ the cue word-stream — high signal vs. the per-query snippet guess.
9
+
10
+ It does NOT re-embed: it only attaches (start, end) to the existing chunks. A
11
+ chunk whose opening words can't be located is left untimed (None) so the caller
12
+ falls back to the existing behaviour — never a wrong timestamp from a bad guess
13
+ masquerading as exact.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import re
19
+ from typing import Optional
20
+
21
+ ANCHOR_WORDS = 8
22
+ _TAG_RE = re.compile(r"<[^>]+>")
23
+
24
+
25
+ def _cue_word_stream(cues: list[dict]) -> tuple[list[str], list[tuple[float, float]]]:
26
+ """Flatten cues into parallel (lowercased word, (start, end)) lists.
27
+
28
+ Inline VTT markup (``<i>``/``<b>``/``<c>``…) is stripped so the word stream
29
+ matches the indexed chunk text — the indexing path builds chunks from the
30
+ HTML-stripped .txt (parse_vtt_file remove_html=True), so leaving tags in
31
+ here would break the anchor match on every cue that carries one (~⅓ of the
32
+ corpus) and silently skip those chunks.
33
+ """
34
+ words: list[str] = []
35
+ times: list[tuple[float, float]] = []
36
+ for cue in cues:
37
+ start = float(cue.get("start", 0.0) or 0.0)
38
+ end = float(cue.get("end", start) or start)
39
+ for word in _TAG_RE.sub("", cue.get("text") or "").split():
40
+ words.append(word.lower())
41
+ times.append((start, end))
42
+ return words, times
43
+
44
+
45
+ def _find_subseq(words: list[str], sub: list[str], lo: int, hi: int) -> Optional[int]:
46
+ """First index i in [lo, hi) with words[i:i+len(sub)] == sub, or None."""
47
+ if not sub:
48
+ return None
49
+ last = min(hi, len(words)) - len(sub)
50
+ i = max(0, lo)
51
+ while i <= last:
52
+ if words[i : i + len(sub)] == sub:
53
+ return i
54
+ i += 1
55
+ return None
56
+
57
+
58
+ def compute_chunk_timestamps(
59
+ cues: list[dict],
60
+ chunk_texts: list[str],
61
+ *,
62
+ chunk_size: int = 220,
63
+ overlap: int = 40,
64
+ ) -> list[Optional[tuple[float, float]]]:
65
+ """Return a (start, end)-or-None per chunk, aligned to the cue stream.
66
+
67
+ Chunks are produced by a deterministic word-window walk (step =
68
+ chunk_size - overlap), so chunk k's opening words are expected near word
69
+ index ``k*step`` — we anchor-match there first (exact when the cue text
70
+ reproduces the indexed text), then fall back to a global search, then give
71
+ up (None) rather than guess.
72
+ """
73
+ words, times = _cue_word_stream(cues)
74
+ n = len(words)
75
+ step = max(1, chunk_size - overlap)
76
+ out: list[Optional[tuple[float, float]]] = []
77
+ for k, text in enumerate(chunk_texts):
78
+ toks = [w.lower() for w in (text or "").split()]
79
+ if not toks or n == 0:
80
+ out.append(None)
81
+ continue
82
+ anchor = toks[:ANCHOR_WORDS]
83
+ expected = k * step
84
+ # Search a window around the expected position first (cheap + avoids
85
+ # latching onto a repeat of the opening words elsewhere), then globally.
86
+ pos = _find_subseq(words, anchor, expected - step, expected + chunk_size + step)
87
+ if pos is None:
88
+ pos = _find_subseq(words, anchor, 0, n)
89
+ if pos is None:
90
+ out.append(None)
91
+ continue
92
+ last_word = min(pos + len(toks) - 1, n - 1)
93
+ out.append((round(times[pos][0], 3), round(times[last_word][1], 3)))
94
+ return out
backend/cli.py CHANGED
@@ -173,6 +173,183 @@ def _cmd_reindex_concepts(args: argparse.Namespace) -> int:
173
  return _emit(result)
174
 
175
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
176
  def build_parser() -> argparse.ArgumentParser:
177
  """Build the CLI parser. Importing/parsing pulls in no ML."""
178
  parser = argparse.ArgumentParser(prog="jws", description=__doc__.split("\n", 1)[0])
@@ -241,6 +418,28 @@ def build_parser() -> argparse.ArgumentParser:
241
  p.add_argument("--batch-size", dest="batch_size", type=int, default=50)
242
  p.set_defaults(func=_cmd_reindex_concepts)
243
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
244
  return parser
245
 
246
 
 
173
  return _emit(result)
174
 
175
 
176
+ # Keep in sync with search_db._init_db's FTS5 CREATE statements (porter).
177
+ _FTS_REBUILD_SCHEMA = {
178
+ "subtitles_fts": (
179
+ "CREATE VIRTUAL TABLE subtitles_fts USING fts5("
180
+ "natural_key, language, content, tokenize = 'porter unicode61')"
181
+ ),
182
+ "ad_transcriptions_fts": (
183
+ "CREATE VIRTUAL TABLE ad_transcriptions_fts USING fts5("
184
+ "natural_key, language, content, tokenize = 'porter unicode61')"
185
+ ),
186
+ }
187
+
188
+
189
+ def _cmd_backfill_chunk_timestamps(args: argparse.Namespace) -> int:
190
+ """Attach VTT-derived start/end to subtitle_chunks (Q2.2). No re-embed.
191
+
192
+ Anchors each chunk's opening words to the cue stream (anchor-or-skip), so a
193
+ chunk is timed only when it can be located — never a wrong guess. Run after
194
+ the VTTs are present (``ingest subtitles``).
195
+ """
196
+ import os
197
+
198
+ from chunk_timestamps import compute_chunk_timestamps
199
+ from db_utils import connect_vec_db
200
+ from runtime_paths import get_search_db_path, get_subtitles_dir
201
+ from subtitles_process_vtt import parse_vtt
202
+
203
+ lang = args.language
204
+ subroot = get_subtitles_dir()
205
+ conn = connect_vec_db(get_search_db_path())
206
+ videos_timed = chunks_timed = videos_no_vtt = 0
207
+ try:
208
+ cols = {r[1] for r in conn.execute("PRAGMA table_info(subtitle_chunks)")}
209
+ for col in ("start_seconds", "end_seconds"):
210
+ if col not in cols:
211
+ conn.execute(f"ALTER TABLE subtitle_chunks ADD COLUMN {col} REAL")
212
+ conn.commit()
213
+
214
+ keys = [
215
+ r[0] for r in conn.execute(
216
+ "SELECT DISTINCT natural_key FROM subtitle_chunks WHERE language = ?",
217
+ (lang,),
218
+ )
219
+ ]
220
+ for nk in keys:
221
+ vtt_path = os.path.join(subroot, lang, f"{nk}.vtt")
222
+ if not os.path.exists(vtt_path):
223
+ videos_no_vtt += 1
224
+ continue
225
+ try:
226
+ with open(vtt_path, "r", encoding="utf-8") as fh:
227
+ cues = parse_vtt(fh.read())
228
+ except Exception:
229
+ continue
230
+ rows = conn.execute(
231
+ "SELECT chunk_index, chunk_text FROM subtitle_chunks "
232
+ "WHERE natural_key = ? AND language = ? ORDER BY chunk_index",
233
+ (nk, lang),
234
+ ).fetchall()
235
+ timestamps = compute_chunk_timestamps(cues, [r[1] for r in rows])
236
+ timed_here = False
237
+ for (cidx, _text), ts in zip(rows, timestamps):
238
+ if ts is not None:
239
+ conn.execute(
240
+ "UPDATE subtitle_chunks SET start_seconds = ?, end_seconds = ? "
241
+ "WHERE natural_key = ? AND language = ? AND chunk_index = ?",
242
+ (ts[0], ts[1], nk, lang, cidx),
243
+ )
244
+ chunks_timed += 1
245
+ timed_here = True
246
+ if timed_here:
247
+ videos_timed += 1
248
+ conn.commit()
249
+ finally:
250
+ conn.close()
251
+ return _emit({
252
+ "status": "success",
253
+ "command": "backfill chunk-timestamps",
254
+ "language": lang,
255
+ "videos_timed": videos_timed,
256
+ "chunks_timed": chunks_timed,
257
+ "videos_without_vtt": videos_no_vtt,
258
+ })
259
+
260
+
261
+ def _cmd_reindex_fts(args: argparse.Namespace) -> int:
262
+ """Rebuild the keyword FTS tables in place with the CURRENT schema.
263
+
264
+ FTS5 cannot ALTER its tokenizer, so switching to porter stemming needs a
265
+ drop + recreate + repopulate. Content is read back from the existing FTS
266
+ (no re-download, no embeddings touched), so this is fast. ML-free.
267
+ """
268
+ from db_utils import connect_vec_db
269
+ from runtime_paths import get_search_db_path
270
+
271
+ conn = connect_vec_db(get_search_db_path())
272
+ rebuilt = {}
273
+ try:
274
+ for table, create_sql in _FTS_REBUILD_SCHEMA.items():
275
+ try:
276
+ rows = conn.execute(
277
+ f"SELECT natural_key, language, content FROM {table}"
278
+ ).fetchall()
279
+ except Exception:
280
+ continue # table absent in this DB
281
+ conn.execute(f"DROP TABLE {table}")
282
+ conn.execute(create_sql)
283
+ conn.executemany(
284
+ f"INSERT INTO {table}(natural_key, language, content) VALUES (?, ?, ?)",
285
+ rows,
286
+ )
287
+ conn.commit()
288
+ rebuilt[table] = len(rows)
289
+ finally:
290
+ conn.close()
291
+ return _emit({"status": "success", "command": "reindex fts", "rebuilt": rebuilt})
292
+
293
+
294
+ def _cmd_check_integrity(args: argparse.Namespace) -> int:
295
+ """Report cross-table row-count drift in the search DB (ML-free).
296
+
297
+ Surfaces the kind of silent drift the audit found (e.g. embedding rows
298
+ without a matching chunk). Counting vec0 tables needs sqlite-vec loaded but
299
+ no torch, so this stays a lightweight health check.
300
+ """
301
+ from db_utils import connect_vec_db
302
+ from runtime_paths import get_search_db_path
303
+
304
+ conn = connect_vec_db(get_search_db_path())
305
+ issues: list[str] = []
306
+
307
+ def _count(table: str) -> int | None:
308
+ try:
309
+ return int(conn.execute(f"SELECT COUNT(*) FROM {table}").fetchone()[0])
310
+ except Exception:
311
+ return None
312
+
313
+ try:
314
+ chunks = _count("subtitle_chunks")
315
+ chunk_embeddings = _count("subtitle_chunk_embeddings")
316
+ fts_docs = _count("subtitles_fts")
317
+ concepts = _count("video_concepts")
318
+ concept_embeddings = _count("video_concept_embeddings")
319
+ legacy = _count("subtitle_embeddings")
320
+
321
+ if chunks is not None and chunk_embeddings is not None and chunks != chunk_embeddings:
322
+ issues.append(
323
+ f"subtitle_chunks ({chunks}) != subtitle_chunk_embeddings "
324
+ f"({chunk_embeddings}) — {abs(chunks - chunk_embeddings)} orphaned rows"
325
+ )
326
+ if concepts is not None and concept_embeddings is not None and concepts != concept_embeddings:
327
+ issues.append(
328
+ f"video_concepts ({concepts}) != video_concept_embeddings "
329
+ f"({concept_embeddings})"
330
+ )
331
+ if legacy:
332
+ issues.append(
333
+ f"legacy mxbai subtitle_embeddings table still present ({legacy} rows) — "
334
+ "retired; drop via migration 0002 when convenient"
335
+ )
336
+ finally:
337
+ conn.close()
338
+
339
+ return _emit({
340
+ "ok": not issues,
341
+ "counts": {
342
+ "subtitle_chunks": chunks,
343
+ "subtitle_chunk_embeddings": chunk_embeddings,
344
+ "subtitles_fts": fts_docs,
345
+ "video_concepts": concepts,
346
+ "video_concept_embeddings": concept_embeddings,
347
+ "legacy_subtitle_embeddings": legacy,
348
+ },
349
+ "issues": issues,
350
+ })
351
+
352
+
353
  def build_parser() -> argparse.ArgumentParser:
354
  """Build the CLI parser. Importing/parsing pulls in no ML."""
355
  parser = argparse.ArgumentParser(prog="jws", description=__doc__.split("\n", 1)[0])
 
418
  p.add_argument("--batch-size", dest="batch_size", type=int, default=50)
419
  p.set_defaults(func=_cmd_reindex_concepts)
420
 
421
+ p = reindex_sub.add_parser(
422
+ "fts",
423
+ help="Rebuild the keyword FTS tables with the current tokenizer (porter).",
424
+ )
425
+ p.set_defaults(func=_cmd_reindex_fts)
426
+
427
+ # backfill <noun>
428
+ backfill = top.add_parser("backfill", help="Backfill derived columns on existing data.")
429
+ backfill_sub = backfill.add_subparsers(dest="noun", required=True)
430
+ p = backfill_sub.add_parser(
431
+ "chunk-timestamps",
432
+ help="Attach VTT start/end times to subtitle_chunks (Q2.2, no re-embed).",
433
+ )
434
+ p.add_argument("--language", default="E")
435
+ p.set_defaults(func=_cmd_backfill_chunk_timestamps)
436
+
437
+ # check <noun>
438
+ check = top.add_parser("check", help="Health/integrity checks on the indexes.")
439
+ check_sub = check.add_subparsers(dest="noun", required=True)
440
+ p = check_sub.add_parser("integrity", help="Report cross-table row-count drift.")
441
+ p.set_defaults(func=_cmd_check_integrity)
442
+
443
  return parser
444
 
445
 
backend/conftest.py ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Pytest configuration applied when tests are collected with rootdir=backend/.
2
+
3
+ CLAUDE.md tells developers to `cd backend` and run the suite there, in which
4
+ case pytest's rootdir is backend/ and the repo-root conftest.py is NOT loaded.
5
+ This mirrors the one setting that must hold for deterministic tests: the
6
+ process-wide smart-search result cache is disabled, so a query reused across
7
+ tests with different mocked services never returns a stale cached response.
8
+ ``setdefault`` so an explicit env still wins, and so running from the repo
9
+ root (where the root conftest already set it) is a harmless no-op.
10
+ """
11
+
12
+ import os
13
+
14
+ os.environ.setdefault("SEARCH_UI_RESULT_CACHE_TTL", "0")
backend/content_status.py CHANGED
@@ -9,7 +9,7 @@ import json
9
  import os
10
  from typing import Any, Callable
11
 
12
- from db_utils import sqlite3
13
  from face_search import get_face_search_instance
14
  from media_visibility import filter_visible_media
15
  from runtime_paths import get_image_db_path, get_search_db_path
@@ -226,7 +226,7 @@ def _max_timestamp(db_path: str, query: str) -> str | None:
226
  if not os.path.exists(db_path):
227
  return None
228
  try:
229
- conn = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True)
230
  except sqlite3.OperationalError:
231
  return None
232
  try:
@@ -269,7 +269,9 @@ def get_data_freshness() -> dict[str, str | None]:
269
 
270
  def _get_fast_image_status_counts(db_path: str) -> dict[str, int]:
271
  """Return status counts without touching the large vec0 embedding table."""
272
- conn = sqlite3.connect(db_path)
 
 
273
  try:
274
  total_categories = conn.execute("SELECT COUNT(*) FROM image_categories").fetchone()[0]
275
  unique_videos = conn.execute("SELECT COUNT(*) FROM processed_videos").fetchone()[0]
 
9
  import os
10
  from typing import Any, Callable
11
 
12
+ from db_utils import connect_sqlite, sqlite3
13
  from face_search import get_face_search_instance
14
  from media_visibility import filter_visible_media
15
  from runtime_paths import get_image_db_path, get_search_db_path
 
226
  if not os.path.exists(db_path):
227
  return None
228
  try:
229
+ conn = connect_sqlite(f"file:{db_path}?mode=ro", uri=True, foreign_keys=False)
230
  except sqlite3.OperationalError:
231
  return None
232
  try:
 
269
 
270
  def _get_fast_image_status_counts(db_path: str) -> dict[str, int]:
271
  """Return status counts without touching the large vec0 embedding table."""
272
+ # Reads the image DB while ingestion may be writing it; busy_timeout
273
+ # (via connect_sqlite) lets the read wait for the lock instead of failing.
274
+ conn = connect_sqlite(db_path, foreign_keys=False)
275
  try:
276
  total_categories = conn.execute("SELECT COUNT(*) FROM image_categories").fetchone()[0]
277
  unique_videos = conn.execute("SELECT COUNT(*) FROM processed_videos").fetchone()[0]
backend/db_utils.py CHANGED
@@ -109,11 +109,16 @@ IMAGE_DB_PRAGMAS: Final[tuple[str, ...]] = (
109
  )
110
 
111
 
 
 
 
112
  def connect_sqlite(
113
  db_path: str,
114
  *,
115
  foreign_keys: bool = True,
116
  load_vec: bool = False,
 
 
117
  pragmas: Iterable[str] = (),
118
  ) -> sqlite3.Connection:
119
  """
@@ -123,6 +128,11 @@ def connect_sqlite(
123
  db_path: Path to the database file.
124
  foreign_keys: Enable foreign-key enforcement for this connection.
125
  load_vec: Load the sqlite-vec extension.
 
 
 
 
 
126
  pragmas: Additional PRAGMA statements in `name=value` form.
127
  """
128
  connection_target = db_path
@@ -131,11 +141,14 @@ def connect_sqlite(
131
  os.makedirs(os.path.dirname(absolute_path), exist_ok=True)
132
  connection_target = absolute_path
133
 
134
- conn = sqlite3.connect(connection_target)
135
 
136
  if foreign_keys:
137
  conn.execute("PRAGMA foreign_keys=ON")
138
 
 
 
 
139
  if load_vec:
140
  if not hasattr(conn, "enable_load_extension"):
141
  raise RuntimeError(
 
109
  )
110
 
111
 
112
+ DEFAULT_BUSY_TIMEOUT_MS: Final[int] = 30000
113
+
114
+
115
  def connect_sqlite(
116
  db_path: str,
117
  *,
118
  foreign_keys: bool = True,
119
  load_vec: bool = False,
120
+ busy_timeout_ms: int = DEFAULT_BUSY_TIMEOUT_MS,
121
+ uri: bool = False,
122
  pragmas: Iterable[str] = (),
123
  ) -> sqlite3.Connection:
124
  """
 
128
  db_path: Path to the database file.
129
  foreign_keys: Enable foreign-key enforcement for this connection.
130
  load_vec: Load the sqlite-vec extension.
131
+ busy_timeout_ms: SQLite busy-handler timeout. Defaults to 30 s so a
132
+ reader hitting the DB mid-write waits for the lock instead of
133
+ raising ``database is locked`` immediately (the default is 0).
134
+ Pass ``0`` to disable. WAL DBs pass this again via IMAGE_DB_PRAGMAS;
135
+ re-applying the same value is harmless.
136
  pragmas: Additional PRAGMA statements in `name=value` form.
137
  """
138
  connection_target = db_path
 
141
  os.makedirs(os.path.dirname(absolute_path), exist_ok=True)
142
  connection_target = absolute_path
143
 
144
+ conn = sqlite3.connect(connection_target, uri=uri)
145
 
146
  if foreign_keys:
147
  conn.execute("PRAGMA foreign_keys=ON")
148
 
149
+ if busy_timeout_ms:
150
+ conn.execute(f"PRAGMA busy_timeout={int(busy_timeout_ms)}")
151
+
152
  if load_vec:
153
  if not hasattr(conn, "enable_load_extension"):
154
  raise RuntimeError(
backend/face_routes.py CHANGED
@@ -2,6 +2,7 @@
2
  Person and face-recognition API routes extracted from the FastAPI entrypoint.
3
  """
4
 
 
5
  import os
6
  import tempfile
7
  from typing import Any
@@ -211,29 +212,35 @@ def create_face_router(
211
  temp_path = None
212
  try:
213
  temp_path = _save_upload_to_temp(file)
214
- face_search = get_face_search_service()
215
- image_search = get_image_search_service()
216
- matches = face_search.search_by_image(temp_path, limit)
217
 
218
- if not matches:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
219
  return {
220
  "results": [],
221
  "count": 0,
222
  "message": "No faces found in uploaded image or no matches in database",
223
  }
224
-
225
- media_info = load_all_media(language)
226
- results = [
227
- _build_face_match_result(
228
- natural_key,
229
- frame_number,
230
- face_index,
231
- similarity,
232
- media_info,
233
- image_search,
234
- )
235
- for natural_key, frame_number, face_index, similarity in matches
236
- ]
237
  return {"results": results, "count": len(results), "method": "face-upload"}
238
 
239
  except Exception as exc:
 
2
  Person and face-recognition API routes extracted from the FastAPI entrypoint.
3
  """
4
 
5
+ import asyncio
6
  import os
7
  import tempfile
8
  from typing import Any
 
212
  temp_path = None
213
  try:
214
  temp_path = _save_upload_to_temp(file)
 
 
 
215
 
216
+ # DeepFace/ArcFace detection+embedding is seconds of CPU; the
217
+ # per-match enrichment hits the DB. Run the whole thing off-loop.
218
+ def _run():
219
+ face_search = get_face_search_service()
220
+ image_search = get_image_search_service()
221
+ matches = face_search.search_by_image(temp_path, limit)
222
+ if not matches:
223
+ return None
224
+ media_info = load_all_media(language)
225
+ return [
226
+ _build_face_match_result(
227
+ natural_key,
228
+ frame_number,
229
+ face_index,
230
+ similarity,
231
+ media_info,
232
+ image_search,
233
+ )
234
+ for natural_key, frame_number, face_index, similarity in matches
235
+ ]
236
+
237
+ results = await asyncio.to_thread(_run)
238
+ if results is None:
239
  return {
240
  "results": [],
241
  "count": 0,
242
  "message": "No faces found in uploaded image or no matches in database",
243
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
244
  return {"results": results, "count": len(results), "method": "face-upload"}
245
 
246
  except Exception as exc:
backend/lower_third_person_bootstrap.py CHANGED
@@ -280,7 +280,9 @@ def _load_lower_third_rows(
280
  limit: int,
281
  ) -> list[tuple[str, int, str, float, str | None]]:
282
  placeholders = ",".join("?" for _ in LOWER_THIRD_PERSON_LABELS)
283
- conn = sqlite3.connect(image_db_path)
 
 
284
  try:
285
  has_resolution_label = _table_has_column(conn, "processed_videos", "resolution_label")
286
  resolution_select = "MAX(processed_videos.resolution_label)" if has_resolution_label else "NULL"
 
280
  limit: int,
281
  ) -> list[tuple[str, int, str, float, str | None]]:
282
  placeholders = ",".join("?" for _ in LOWER_THIRD_PERSON_LABELS)
283
+ from db_utils import connect_sqlite
284
+
285
+ conn = connect_sqlite(image_db_path, foreign_keys=False)
286
  try:
287
  has_resolution_label = _table_has_column(conn, "processed_videos", "resolution_label")
288
  resolution_select = "MAX(processed_videos.resolution_label)" if has_resolution_label else "NULL"
backend/main.py CHANGED
@@ -16,6 +16,7 @@ try:
16
  except ImportError:
17
  pass
18
 
 
19
  from contextlib import asynccontextmanager
20
 
21
  from fastapi import FastAPI, HTTPException, Request
@@ -48,6 +49,64 @@ from workflow_routes import (
48
  )
49
 
50
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
  def _warm_on_startup_enabled() -> bool:
52
  """Whether to warm search models at startup (default on)."""
53
  return os.environ.get("SEARCH_UI_WARM_ON_STARTUP", "true").strip().lower() not in (
@@ -110,14 +169,27 @@ def create_app() -> FastAPI:
110
  async def lifespan(app: FastAPI):
111
  app.state.runtime = runtime
112
  app.state.startup_report = startup_report
113
- # "Search ready" is a stronger signal than "data bundle extracted".
114
- # /api/health only flips to ok:true once this is set, so the front-end
115
- # warm-up gate keeps the user out until the first search will be fast.
116
- # Each worker process runs this lifespan, so each warms its OWN model
117
- # copies — there's no shared warm state to race on across workers.
118
  app.state.search_ready = False
119
  _start_search_warmup(app, runtime)
120
- yield
 
 
 
 
 
 
 
 
 
 
 
 
 
 
121
 
122
  app = FastAPI(lifespan=lifespan)
123
 
@@ -126,6 +198,24 @@ def create_app() -> FastAPI:
126
  import search_feature_flags
127
  search_feature_flags.apply_persisted_flags()
128
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
129
  # Single shared-password gate. Added BEFORE the CORS middleware below so
130
  # CORS ends up outermost — a 401 from the gate still gets CORS headers, so
131
  # the browser can read it in cross-origin dev.
@@ -152,8 +242,30 @@ def create_app() -> FastAPI:
152
  allow_headers=["*"],
153
  )
154
 
155
- app.mount("/videos", StaticFiles(directory=runtime.config.videos_dir), name="videos")
156
- app.mount("/publications", StaticFiles(directory=runtime.config.publications_dir), name="publications")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
157
 
158
  app.include_router(
159
  create_face_router(
@@ -170,9 +282,22 @@ def create_app() -> FastAPI:
170
  )
171
  from auth import create_auth_router
172
 
 
 
 
 
 
 
 
 
 
 
 
 
173
  app.include_router(create_auth_router())
174
  app.include_router(create_settings_router())
175
- app.include_router(create_audio_description_router())
 
176
  app.include_router(
177
  create_catalog_router(
178
  backend_dir=runtime.config.backend_dir,
@@ -203,31 +328,33 @@ def create_app() -> FastAPI:
203
  get_image_search_service=runtime.services.get_image_search,
204
  )
205
  )
206
- app.include_router(
207
- create_sync_router(
208
- backend_dir=runtime.config.backend_dir,
209
- subtitles_root=runtime.config.subtitles_dir,
210
- videos_dir=runtime.config.videos_dir,
211
- get_image_search_service=runtime.services.get_image_search,
212
- )
213
- )
214
- app.include_router(create_publication_router(runtime.task_manager))
215
- app.include_router(create_web_image_router(runtime.task_manager))
216
- app.include_router(
217
- create_processing_router(
218
- ProcessingRuntime(
219
  backend_dir=runtime.config.backend_dir,
220
- json_root=runtime.config.json_dir,
221
  subtitles_root=runtime.config.subtitles_dir,
222
  videos_dir=runtime.config.videos_dir,
223
- checkpoints_dir=runtime.config.checkpoints_dir,
224
- logs_dir=runtime.config.logs_dir,
225
- task_manager=runtime.task_manager,
226
- search_service=runtime.services.search,
227
- image_search_service=runtime.services.image_search,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
228
  )
229
  )
230
- )
231
  app.include_router(
232
  create_status_router(
233
  runtime.task_manager,
@@ -239,20 +366,21 @@ def create_app() -> FastAPI:
239
  new_content_cache_ttl_seconds=runtime.config.new_content_cache_ttl_seconds,
240
  )
241
  )
242
- app.include_router(
243
- create_workflow_router(
244
- runtime.task_manager,
245
- supported_languages=runtime.supported_languages,
246
- primary_face_language=runtime.primary_face_language,
247
- backend_dir=runtime.config.backend_dir,
248
- json_root=runtime.config.json_dir,
249
- subtitles_root=runtime.config.subtitles_dir,
250
- videos_dir=runtime.config.videos_dir,
251
- search_service=runtime.services.search,
252
- image_search_service=runtime.services.image_search,
253
- face_search_service=runtime.services.face_search,
 
 
254
  )
255
- )
256
 
257
  frontend_dist = runtime.config.frontend_dist
258
 
@@ -283,12 +411,21 @@ def create_app() -> FastAPI:
283
  return {"ok": ready}
284
  payload["search_ready"] = search_ready
285
  payload["data_root"] = runtime.config.data_root
 
286
  return payload
287
 
288
  if frontend_dist:
289
  assets_dir = os.path.join(frontend_dist, "assets")
290
  if os.path.isdir(assets_dir):
291
- app.mount("/assets", StaticFiles(directory=assets_dir), name="frontend-assets")
 
 
 
 
 
 
 
 
292
 
293
  spa_index = os.path.join(frontend_dist, "index.html")
294
 
 
16
  except ImportError:
17
  pass
18
 
19
+ import asyncio
20
  from contextlib import asynccontextmanager
21
 
22
  from fastapi import FastAPI, HTTPException, Request
 
49
  )
50
 
51
 
52
+ class CacheControlStaticFiles(StaticFiles):
53
+ """StaticFiles with a Cache-Control header on served files.
54
+
55
+ Starlette's StaticFiles only sends ETag/Last-Modified, so every thumbnail
56
+ in a result grid re-validates through the proxy on every visit (a round
57
+ trip per image on the hosted Space). Thumbnails and hashed assets change
58
+ only when the data bundle / frontend build changes, so real caching is
59
+ safe.
60
+ """
61
+
62
+ def __init__(self, *args, cache_control: str, shard_reader=None, **kwargs):
63
+ super().__init__(*args, **kwargs)
64
+ self.cache_control = cache_control
65
+ # Optional blob-shard fallback (hosted mode): see thumbnail_shards.py.
66
+ self.shard_reader = shard_reader
67
+
68
+ async def _shard_response(self, path: str):
69
+ """Serve ``path`` from the blob shard, or None if absent."""
70
+ if self.shard_reader is None:
71
+ return None
72
+ import anyio
73
+ from starlette.responses import Response
74
+
75
+ from thumbnail_shards import guess_content_type
76
+
77
+ data = await anyio.to_thread.run_sync(self.shard_reader.get, path)
78
+ if data is None:
79
+ return None
80
+ return Response(
81
+ content=data,
82
+ media_type=guess_content_type(path),
83
+ headers={"Cache-Control": self.cache_control},
84
+ )
85
+
86
+ async def get_response(self, path: str, scope):
87
+ # Loose file present → serve it (local mode unchanged). A missing file
88
+ # makes StaticFiles raise/return 404; only then do we fall back to the
89
+ # thumbnail shard (hosted mode, where loose thumbnails aren't shipped),
90
+ # so the two modes stay isolated.
91
+ try:
92
+ response = await super().get_response(path, scope)
93
+ except Exception as exc: # noqa: BLE001
94
+ # StaticFiles raises starlette.exceptions.HTTPException (NOT fastapi's)
95
+ # for a missing file — match on status_code so both are handled.
96
+ if getattr(exc, "status_code", None) == 404:
97
+ shard = await self._shard_response(path)
98
+ if shard is not None:
99
+ return shard
100
+ raise
101
+ if response.status_code == 404:
102
+ shard = await self._shard_response(path)
103
+ if shard is not None:
104
+ return shard
105
+ if response.status_code in (200, 304):
106
+ response.headers["Cache-Control"] = self.cache_control
107
+ return response
108
+
109
+
110
  def _warm_on_startup_enabled() -> bool:
111
  """Whether to warm search models at startup (default on)."""
112
  return os.environ.get("SEARCH_UI_WARM_ON_STARTUP", "true").strip().lower() not in (
 
169
  async def lifespan(app: FastAPI):
170
  app.state.runtime = runtime
171
  app.state.startup_report = startup_report
172
+ # Warm models at startup and gate /api/health on search_ready so the
173
+ # front-end warm-up screen holds users until the first search is fast
174
+ # (main's #92 mechanism; each worker warms its own model copies). This
175
+ # replaces the earlier S2.6 lifespan warmup.
 
176
  app.state.search_ready = False
177
  _start_search_warmup(app, runtime)
178
+ try:
179
+ yield
180
+ finally:
181
+ # Graceful shutdown: cancel an in-flight background task so SIGTERM
182
+ # doesn't strand a coroutine or leave the container waiting on a
183
+ # detached task. (Hosted mode has no task routes, so this is a
184
+ # no-op there; it matters for the local full app.)
185
+ background_task = getattr(runtime.task_manager, "background_task", None)
186
+ if background_task is not None and not background_task.done():
187
+ log_message("Shutdown: cancelling in-flight background task")
188
+ background_task.cancel()
189
+ try:
190
+ await background_task
191
+ except (asyncio.CancelledError, Exception): # noqa: BLE001
192
+ pass
193
 
194
  app = FastAPI(lifespan=lifespan)
195
 
 
198
  import search_feature_flags
199
  search_feature_flags.apply_persisted_flags()
200
 
201
+ # Compress responses (innermost middleware). Search JSON at the default
202
+ # limit=200 runs to hundreds of KB and was shipping uncompressed.
203
+ # Requires starlette >= 0.46 (pinned in requirements), where
204
+ # GZipMiddleware skips text/event-stream so SSE task streams keep
205
+ # flowing unbuffered. On an older starlette (e.g. a venv installed
206
+ # before the pin), compressing SSE would buffer live task progress —
207
+ # so compression stays off and the operator is told how to fix it.
208
+ import starlette.middleware.gzip as _gzip_module
209
+
210
+ if hasattr(_gzip_module, "DEFAULT_EXCLUDED_CONTENT_TYPES"):
211
+ app.add_middleware(_gzip_module.GZipMiddleware, minimum_size=1024)
212
+ else:
213
+ log_message(
214
+ "Response compression DISABLED: starlette < 0.46 would gzip SSE "
215
+ "task streams. Run: pip install 'starlette>=0.46,<0.47'",
216
+ "WARNING",
217
+ )
218
+
219
  # Single shared-password gate. Added BEFORE the CORS middleware below so
220
  # CORS ends up outermost — a 401 from the gate still gets CORS headers, so
221
  # the browser can read it in cross-origin dev.
 
242
  allow_headers=["*"],
243
  )
244
 
245
+ # Optional thumbnail blob shards (hosted cold-start fix). Absent locally,
246
+ # so the loose-file path is used and behavior is unchanged.
247
+ from thumbnail_shards import open_shard_readers
248
+
249
+ shard_readers = open_shard_readers()
250
+
251
+ app.mount(
252
+ "/videos",
253
+ CacheControlStaticFiles(
254
+ directory=runtime.config.videos_dir,
255
+ cache_control="public, max-age=86400",
256
+ shard_reader=shard_readers.get("videos"),
257
+ ),
258
+ name="videos",
259
+ )
260
+ app.mount(
261
+ "/publications",
262
+ CacheControlStaticFiles(
263
+ directory=runtime.config.publications_dir,
264
+ cache_control="public, max-age=86400",
265
+ shard_reader=shard_readers.get("publications"),
266
+ ),
267
+ name="publications",
268
+ )
269
 
270
  app.include_router(
271
  create_face_router(
 
282
  )
283
  from auth import create_auth_router
284
 
285
+ # Hosted (HF Space) deployments are search-only: the data bundle is built
286
+ # by the local app, so ingestion/admin endpoints are not mounted at all.
287
+ # The web frontend already hides the Sync/People admin pages; this makes
288
+ # the server match (the endpoints 404 instead of running hour-long
289
+ # downloads/ML inside the serving container).
290
+ hosted_mode = runtime.config.hosted_mode
291
+ if hosted_mode:
292
+ log_message(
293
+ "Hosted mode: ingestion/admin routers disabled "
294
+ "(sync, workflow, processing, audio-description, web-image-crawl)."
295
+ )
296
+
297
  app.include_router(create_auth_router())
298
  app.include_router(create_settings_router())
299
+ if not hosted_mode:
300
+ app.include_router(create_audio_description_router())
301
  app.include_router(
302
  create_catalog_router(
303
  backend_dir=runtime.config.backend_dir,
 
328
  get_image_search_service=runtime.services.get_image_search,
329
  )
330
  )
331
+ if not hosted_mode:
332
+ app.include_router(
333
+ create_sync_router(
 
 
 
 
 
 
 
 
 
 
334
  backend_dir=runtime.config.backend_dir,
 
335
  subtitles_root=runtime.config.subtitles_dir,
336
  videos_dir=runtime.config.videos_dir,
337
+ get_image_search_service=runtime.services.get_image_search,
338
+ )
339
+ )
340
+ app.include_router(create_publication_router(runtime.task_manager))
341
+ if not hosted_mode:
342
+ app.include_router(create_web_image_router(runtime.task_manager))
343
+ app.include_router(
344
+ create_processing_router(
345
+ ProcessingRuntime(
346
+ backend_dir=runtime.config.backend_dir,
347
+ json_root=runtime.config.json_dir,
348
+ subtitles_root=runtime.config.subtitles_dir,
349
+ videos_dir=runtime.config.videos_dir,
350
+ checkpoints_dir=runtime.config.checkpoints_dir,
351
+ logs_dir=runtime.config.logs_dir,
352
+ task_manager=runtime.task_manager,
353
+ search_service=runtime.services.search,
354
+ image_search_service=runtime.services.image_search,
355
+ )
356
  )
357
  )
 
358
  app.include_router(
359
  create_status_router(
360
  runtime.task_manager,
 
366
  new_content_cache_ttl_seconds=runtime.config.new_content_cache_ttl_seconds,
367
  )
368
  )
369
+ if not hosted_mode:
370
+ app.include_router(
371
+ create_workflow_router(
372
+ runtime.task_manager,
373
+ supported_languages=runtime.supported_languages,
374
+ primary_face_language=runtime.primary_face_language,
375
+ backend_dir=runtime.config.backend_dir,
376
+ json_root=runtime.config.json_dir,
377
+ subtitles_root=runtime.config.subtitles_dir,
378
+ videos_dir=runtime.config.videos_dir,
379
+ search_service=runtime.services.search,
380
+ image_search_service=runtime.services.image_search,
381
+ face_search_service=runtime.services.face_search,
382
+ )
383
  )
 
384
 
385
  frontend_dist = runtime.config.frontend_dist
386
 
 
411
  return {"ok": ready}
412
  payload["search_ready"] = search_ready
413
  payload["data_root"] = runtime.config.data_root
414
+ payload["hosted_mode"] = runtime.config.hosted_mode
415
  return payload
416
 
417
  if frontend_dist:
418
  assets_dir = os.path.join(frontend_dist, "assets")
419
  if os.path.isdir(assets_dir):
420
+ # Vite emits content-hashed filenames, so these are immutable.
421
+ app.mount(
422
+ "/assets",
423
+ CacheControlStaticFiles(
424
+ directory=assets_dir,
425
+ cache_control="public, max-age=31536000, immutable",
426
+ ),
427
+ name="frontend-assets",
428
+ )
429
 
430
  spa_index = os.path.join(frontend_dist, "index.html")
431
 
backend/media_metadata.py CHANGED
@@ -75,8 +75,15 @@ def get_all_media(
75
  )
76
  return all_media
77
 
78
- except Exception as exc:
79
- log_message(f"Error loading media metadata: {exc}")
 
 
 
 
 
 
 
80
  return None
81
 
82
 
 
75
  )
76
  return all_media
77
 
78
+ except (OSError, json.JSONDecodeError) as exc:
79
+ # A corrupt or unreadable all_media_items.json degrades every search
80
+ # result to mediaItem=null — surface it loudly rather than silently
81
+ # returning None for an unrelated programming error (No Silent
82
+ # Degradation: only the expected file-level failures are tolerated).
83
+ log_message(
84
+ f"Failed to load media metadata for {language} from {all_media_path}: {exc}",
85
+ "ERROR",
86
+ )
87
  return None
88
 
89
 
backend/processing_stats.py CHANGED
@@ -7,7 +7,7 @@ import time
7
  from dataclasses import dataclass
8
  from typing import Any
9
 
10
- from db_utils import sqlite3
11
  from face_search import ARCFACE_MODEL_VERSION
12
  from search_images import CLASSIFICATION_THRESHOLD, SIGLIP_MODEL_VERSION, get_labels_version
13
 
@@ -97,7 +97,9 @@ def build_processing_stats(
97
 
98
  def get_fast_image_processing_counts(db_path: str) -> dict[str, int]:
99
  """Return image counts from regular tables only."""
100
- conn = sqlite3.connect(db_path)
 
 
101
  try:
102
  total_categories = conn.execute("SELECT COUNT(*) FROM image_categories").fetchone()[0]
103
  video_row = conn.execute(
 
7
  from dataclasses import dataclass
8
  from typing import Any
9
 
10
+ from db_utils import connect_sqlite, sqlite3
11
  from face_search import ARCFACE_MODEL_VERSION
12
  from search_images import CLASSIFICATION_THRESHOLD, SIGLIP_MODEL_VERSION, get_labels_version
13
 
 
97
 
98
  def get_fast_image_processing_counts(db_path: str) -> dict[str, int]:
99
  """Return image counts from regular tables only."""
100
+ # Reads while ingestion may write; busy_timeout (via connect_sqlite)
101
+ # avoids an immediate "database is locked".
102
+ conn = connect_sqlite(db_path, foreign_keys=False)
103
  try:
104
  total_categories = conn.execute("SELECT COUNT(*) FROM image_categories").fetchone()[0]
105
  video_row = conn.execute(
backend/publications_processor.py CHANGED
@@ -181,7 +181,9 @@ def _query_image_metadata(db_path: str) -> List[Dict]:
181
  results = []
182
  conn = None
183
  try:
184
- conn = sqlite3.connect(db_path)
 
 
185
  cursor = conn.cursor()
186
 
187
  # Check which tables exist
 
181
  results = []
182
  conn = None
183
  try:
184
+ from db_utils import connect_sqlite
185
+
186
+ conn = connect_sqlite(db_path, foreign_keys=False)
187
  cursor = conn.cursor()
188
 
189
  # Check which tables exist
backend/requirements-hf.txt CHANGED
@@ -3,6 +3,9 @@
3
  # prebuilt databases and compact thumbnails.
4
 
5
  fastapi==0.115.12
 
 
 
6
  uvicorn[standard]==0.34.0
7
  python-multipart
8
 
 
3
  # prebuilt databases and compact thumbnails.
4
 
5
  fastapi==0.115.12
6
+ # GZipMiddleware skips text/event-stream (SSE) only from starlette 0.46 —
7
+ # older versions would buffer/compress live task streams.
8
+ starlette>=0.46,<0.47
9
  uvicorn[standard]==0.34.0
10
  python-multipart
11
 
backend/requirements.txt CHANGED
@@ -6,6 +6,9 @@
6
 
7
  # Core web framework
8
  fastapi==0.115.12
 
 
 
9
  uvicorn[standard]==0.34.0
10
  python-multipart
11
 
 
6
 
7
  # Core web framework
8
  fastapi==0.115.12
9
+ # GZipMiddleware skips text/event-stream (SSE) only from starlette 0.46 —
10
+ # older versions would buffer/compress live task streams.
11
+ starlette>=0.46,<0.47
12
  uvicorn[standard]==0.34.0
13
  python-multipart
14
 
backend/result_cache.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tiny TTL + LRU cache for full search responses.
2
+
3
+ The served index only changes when a new data bundle is deployed, so identical
4
+ repeat searches (editors refining a query, shared links) can return a cached
5
+ response instead of re-encoding and re-merging. This sits *above* the
6
+ query-embedding cache: it skips the whole pipeline, not just the encode.
7
+
8
+ Bounded by size and TTL, thread-safe, and a no-op when the TTL is 0 (set
9
+ ``SEARCH_UI_RESULT_CACHE_TTL`` to disable). Runtime feature-flag toggles
10
+ (e.g. smart_scene_fusion via the Settings UI) take effect within one TTL.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import os
16
+ import threading
17
+ import time
18
+ from collections import OrderedDict
19
+ from typing import Any, Hashable, Optional
20
+
21
+ DEFAULT_TTL_SECONDS = 300
22
+ DEFAULT_MAX_ENTRIES = 256
23
+
24
+
25
+ def _ttl_seconds() -> int:
26
+ raw = os.environ.get("SEARCH_UI_RESULT_CACHE_TTL", "").strip()
27
+ if not raw:
28
+ return DEFAULT_TTL_SECONDS
29
+ try:
30
+ return max(0, int(raw))
31
+ except ValueError:
32
+ return DEFAULT_TTL_SECONDS
33
+
34
+
35
+ class ResultCache:
36
+ """Thread-safe TTL+LRU cache. ``now`` is injectable for tests."""
37
+
38
+ def __init__(self, *, max_entries: int = DEFAULT_MAX_ENTRIES, now=time.monotonic):
39
+ self._max_entries = max_entries
40
+ self._now = now
41
+ self._lock = threading.Lock()
42
+ self._store: "OrderedDict[Hashable, tuple[float, Any]]" = OrderedDict()
43
+
44
+ @property
45
+ def enabled(self) -> bool:
46
+ return _ttl_seconds() > 0
47
+
48
+ def get(self, key: Hashable) -> Optional[Any]:
49
+ ttl = _ttl_seconds()
50
+ if ttl <= 0:
51
+ return None
52
+ with self._lock:
53
+ entry = self._store.get(key)
54
+ if entry is None:
55
+ return None
56
+ expires_at, value = entry
57
+ if expires_at <= self._now():
58
+ del self._store[key]
59
+ return None
60
+ self._store.move_to_end(key)
61
+ return value
62
+
63
+ def put(self, key: Hashable, value: Any) -> None:
64
+ ttl = _ttl_seconds()
65
+ if ttl <= 0:
66
+ return
67
+ with self._lock:
68
+ self._store[key] = (self._now() + ttl, value)
69
+ self._store.move_to_end(key)
70
+ while len(self._store) > self._max_entries:
71
+ self._store.popitem(last=False)
72
+
73
+ def clear(self) -> None:
74
+ with self._lock:
75
+ self._store.clear()
76
+
77
+
78
+ # Process-wide cache for the smart-search GET response.
79
+ smart_search_cache = ResultCache()
backend/rule_based_router.py CHANGED
@@ -19,6 +19,17 @@ from enum import Enum
19
  from utils import log_message
20
 
21
 
 
 
 
 
 
 
 
 
 
 
 
22
  class SearchMethod(Enum):
23
  """Available search methods."""
24
  HYBRID = "hybrid"
@@ -285,7 +296,12 @@ class RuleBasedRouter:
285
  return None
286
 
287
  def _check_visual_keywords(self, query: str, query_lower: str) -> Optional[SearchPlan]:
288
- """Route to image search only when an explicit visual phrase is present."""
 
 
 
 
 
289
  category_match = next(
290
  (phrase for phrase in self.CATEGORY_VISUAL_PHRASES if phrase in query_lower),
291
  None,
@@ -293,7 +309,7 @@ class RuleBasedRouter:
293
  if category_match:
294
  return SearchPlan(
295
  primary_method=SearchMethod.IMAGE_CATEGORY,
296
- secondary_methods=[],
297
  extracted_query=query,
298
  intent=QueryIntent.VISUAL_SEARCH,
299
  confidence=0.85,
@@ -307,7 +323,7 @@ class RuleBasedRouter:
307
  if content_match:
308
  return SearchPlan(
309
  primary_method=SearchMethod.IMAGE_CONTENT,
310
- secondary_methods=[],
311
  extracted_query=query,
312
  intent=QueryIntent.VISUAL_SEARCH,
313
  confidence=0.8,
@@ -318,7 +334,7 @@ class RuleBasedRouter:
318
  def _check_person_keywords(self, query: str, query_lower: str) -> Optional[SearchPlan]:
319
  """Check if query is about finding a person."""
320
  for keyword in self.PERSON_KEYWORDS:
321
- if keyword in query_lower:
322
  return SearchPlan(
323
  primary_method=SearchMethod.FACE,
324
  secondary_methods=[SearchMethod.HYBRID],
@@ -332,7 +348,7 @@ class RuleBasedRouter:
332
  def _check_title_keywords(self, query: str, query_lower: str) -> Optional[SearchPlan]:
333
  """Check if query is searching for a specific title."""
334
  for keyword in self.TITLE_KEYWORDS:
335
- if keyword in query_lower:
336
  # Extract the actual title being searched for
337
  cleaned = query
338
  for kw in ["video called", "video named", "titled", "title"]:
 
19
  from utils import log_message
20
 
21
 
22
+ def _contains_phrase(text: str, phrase: str) -> bool:
23
+ """True if ``phrase`` appears in ``text`` on word boundaries.
24
+
25
+ Substring matching mis-fired badly: "brother" matched *brotherly*, "part"
26
+ matched *impartial*, "show" matched *shows*. Word boundaries keep the
27
+ keyword from latching onto a longer word while still matching multi-word
28
+ phrases ("who is", "morning worship").
29
+ """
30
+ return re.search(rf"\b{re.escape(phrase)}\b", text) is not None
31
+
32
+
33
  class SearchMethod(Enum):
34
  """Available search methods."""
35
  HYBRID = "hybrid"
 
296
  return None
297
 
298
  def _check_visual_keywords(self, query: str, query_lower: str) -> Optional[SearchPlan]:
299
+ """Route to image search only when an explicit visual phrase is present.
300
+
301
+ Visual phrases keep HYBRID as a secondary method so the text leg is
302
+ never dropped — e.g. "what does a kingdom hall look like" should still
303
+ return subtitle matches, not zero text results.
304
+ """
305
  category_match = next(
306
  (phrase for phrase in self.CATEGORY_VISUAL_PHRASES if phrase in query_lower),
307
  None,
 
309
  if category_match:
310
  return SearchPlan(
311
  primary_method=SearchMethod.IMAGE_CATEGORY,
312
+ secondary_methods=[SearchMethod.HYBRID],
313
  extracted_query=query,
314
  intent=QueryIntent.VISUAL_SEARCH,
315
  confidence=0.85,
 
323
  if content_match:
324
  return SearchPlan(
325
  primary_method=SearchMethod.IMAGE_CONTENT,
326
+ secondary_methods=[SearchMethod.HYBRID],
327
  extracted_query=query,
328
  intent=QueryIntent.VISUAL_SEARCH,
329
  confidence=0.8,
 
334
  def _check_person_keywords(self, query: str, query_lower: str) -> Optional[SearchPlan]:
335
  """Check if query is about finding a person."""
336
  for keyword in self.PERSON_KEYWORDS:
337
+ if _contains_phrase(query_lower, keyword):
338
  return SearchPlan(
339
  primary_method=SearchMethod.FACE,
340
  secondary_methods=[SearchMethod.HYBRID],
 
348
  def _check_title_keywords(self, query: str, query_lower: str) -> Optional[SearchPlan]:
349
  """Check if query is searching for a specific title."""
350
  for keyword in self.TITLE_KEYWORDS:
351
+ if _contains_phrase(query_lower, keyword):
352
  # Extract the actual title being searched for
353
  cleaned = query
354
  for kw in ["video called", "video named", "titled", "title"]:
backend/runtime_paths.py CHANGED
@@ -98,6 +98,16 @@ def get_publications_db_path() -> str:
98
  )
99
 
100
 
 
 
 
 
 
 
 
 
 
 
101
  def get_data_root() -> str:
102
  configured = os.environ.get("SEARCH_UI_DATA_ROOT")
103
  if configured:
 
98
  )
99
 
100
 
101
+ def get_search_log_db_path() -> str:
102
+ """Path to the user-search analytics log DB (separate so its writes never
103
+ contend with the large read databases)."""
104
+ return _resolve_runtime_file(
105
+ "SEARCH_UI_SEARCH_LOG_DB_PATH",
106
+ get_db_dir(),
107
+ "search_log.db",
108
+ )
109
+
110
+
111
  def get_data_root() -> str:
112
  configured = os.environ.get("SEARCH_UI_DATA_ROOT")
113
  if configured:
backend/schema_version.py CHANGED
@@ -111,7 +111,9 @@ def ensure_alembic_version(db_path: str | None = None) -> str:
111
  """
112
  path = db_path or get_primary_db_path()
113
 
114
- conn = sqlite3.connect(path)
 
 
115
  try:
116
  if _table_exists(conn, "alembic_version"):
117
  return "managed"
 
111
  """
112
  path = db_path or get_primary_db_path()
113
 
114
+ from db_utils import connect_sqlite
115
+
116
+ conn = connect_sqlite(path, foreign_keys=False)
117
  try:
118
  if _table_exists(conn, "alembic_version"):
119
  return "managed"
backend/search.py CHANGED
@@ -13,7 +13,9 @@ import argparse
13
  import hashlib
14
  import json
15
  import logging
 
16
  import threading
 
17
  from typing import TYPE_CHECKING, Dict, List, Optional, Set, Tuple
18
 
19
  if TYPE_CHECKING:
@@ -45,6 +47,12 @@ CURRENT_SEARCH_EMBEDDING_TYPE = "float"
45
  SUBTITLE_CHUNK_SIZE_WORDS = 220
46
  SUBTITLE_CHUNK_OVERLAP_WORDS = 40
47
  SUBTITLE_CHUNK_MIN_WORDS = 60
 
 
 
 
 
 
48
 
49
 
50
  class SubtitleSearch:
@@ -68,6 +76,8 @@ class SubtitleSearch:
68
  self._model_lock = threading.Lock()
69
  self._vocabulary_cache: Dict[str, Set[str]] = {}
70
  self._vocabulary_cache_size: Dict[str, int] = {}
 
 
71
 
72
  def get_embedding_model(self) -> SentenceTransformer:
73
  """Get the embedding model."""
@@ -144,13 +154,40 @@ class SubtitleSearch:
144
  return chunks
145
 
146
  def _encode_query_embedding(self, query: str):
147
- """Encode a search query using the current retrieval recipe."""
 
 
 
 
 
 
 
 
 
 
148
  model = self.get_embedding_model()
149
  prompts = getattr(model, "prompts", None) or {}
150
  kwargs: Dict[str, object] = {"normalize_embeddings": True}
151
- if "query" in prompts:
 
 
 
 
 
 
 
152
  kwargs["prompt_name"] = "query"
153
- return model.encode(query, **kwargs)
 
 
 
 
 
 
 
 
 
 
154
 
155
  def _init_db(self) -> None:
156
  return search_db_module._init_db(self)
@@ -282,6 +319,7 @@ class SubtitleSearch:
282
  fuzzy: bool = False,
283
  fuzzy_threshold: int = 80,
284
  include_ad: bool = True,
 
285
  ) -> List[Tuple[str, float, str]]:
286
  return search_keyword_module.search_keyword(
287
  self,
@@ -291,6 +329,7 @@ class SubtitleSearch:
291
  fuzzy=fuzzy,
292
  fuzzy_threshold=fuzzy_threshold,
293
  include_ad=include_ad,
 
294
  )
295
 
296
  def search_semantic(
 
13
  import hashlib
14
  import json
15
  import logging
16
+ import os
17
  import threading
18
+ from collections import OrderedDict
19
  from typing import TYPE_CHECKING, Dict, List, Optional, Set, Tuple
20
 
21
  if TYPE_CHECKING:
 
47
  SUBTITLE_CHUNK_SIZE_WORDS = 220
48
  SUBTITLE_CHUNK_OVERLAP_WORDS = 40
49
  SUBTITLE_CHUNK_MIN_WORDS = 60
50
+ # A query embedding on CPU costs ~1-3 s; one hybrid search encodes the same
51
+ # query for both the chunk and concept streams, and a smart-search request can
52
+ # encode the same text up to ~5 times across its parallel methods. The cache
53
+ # turns those repeats into lookups. Keyed by raw query text — the model and
54
+ # recipe are fixed per process.
55
+ QUERY_EMBEDDING_CACHE_SIZE = 256
56
 
57
 
58
  class SubtitleSearch:
 
76
  self._model_lock = threading.Lock()
77
  self._vocabulary_cache: Dict[str, Set[str]] = {}
78
  self._vocabulary_cache_size: Dict[str, int] = {}
79
+ self._query_embedding_cache: "OrderedDict[str, object]" = OrderedDict()
80
+ self._query_embedding_cache_lock = threading.Lock()
81
 
82
  def get_embedding_model(self) -> SentenceTransformer:
83
  """Get the embedding model."""
 
154
  return chunks
155
 
156
  def _encode_query_embedding(self, query: str):
157
+ """Encode a search query using the current retrieval recipe (cached).
158
+
159
+ Cached vectors are returned as-is — callers only read them
160
+ (``.tolist()``), never mutate.
161
+ """
162
+ with self._query_embedding_cache_lock:
163
+ cached = self._query_embedding_cache.get(query)
164
+ if cached is not None:
165
+ self._query_embedding_cache.move_to_end(query)
166
+ return cached
167
+
168
  model = self.get_embedding_model()
169
  prompts = getattr(model, "prompts", None) or {}
170
  kwargs: Dict[str, object] = {"normalize_embeddings": True}
171
+ # Q1.6: an optional domain-framed instruction (query-side only, no
172
+ # reindex). When SEARCH_UI_QUERY_INSTRUCTION is set it overrides the
173
+ # model's generic web-search "query" prompt; unset = unchanged behavior.
174
+ # Validate on the eval set before enabling in production.
175
+ custom_instruction = os.environ.get("SEARCH_UI_QUERY_INSTRUCTION", "").strip()
176
+ if custom_instruction:
177
+ kwargs["prompt"] = custom_instruction
178
+ elif "query" in prompts:
179
  kwargs["prompt_name"] = "query"
180
+ # Encode outside the lock: a concurrent miss on the same query costs
181
+ # one duplicate encode, while holding the lock would serialize every
182
+ # distinct query behind a 1-3 s CPU forward pass.
183
+ embedding = model.encode(query, **kwargs)
184
+
185
+ with self._query_embedding_cache_lock:
186
+ self._query_embedding_cache[query] = embedding
187
+ self._query_embedding_cache.move_to_end(query)
188
+ while len(self._query_embedding_cache) > QUERY_EMBEDDING_CACHE_SIZE:
189
+ self._query_embedding_cache.popitem(last=False)
190
+ return embedding
191
 
192
  def _init_db(self) -> None:
193
  return search_db_module._init_db(self)
 
319
  fuzzy: bool = False,
320
  fuzzy_threshold: int = 80,
321
  include_ad: bool = True,
322
+ extra_terms: List[str] | None = None,
323
  ) -> List[Tuple[str, float, str]]:
324
  return search_keyword_module.search_keyword(
325
  self,
 
329
  fuzzy=fuzzy,
330
  fuzzy_threshold=fuzzy_threshold,
331
  include_ad=include_ad,
332
+ extra_terms=extra_terms,
333
  )
334
 
335
  def search_semantic(
backend/search_db.py CHANGED
@@ -26,13 +26,19 @@ def _init_db(search: "SubtitleSearch") -> None:
26
  """Initialize the SQLite database with FTS5 and vector tables."""
27
  conn = connect_vec_db(search.db_path, pragmas=IMAGE_DB_PRAGMAS)
28
 
29
- # Create FTS5 virtual table for keyword search
 
 
 
 
 
30
  conn.execute("""
31
  CREATE VIRTUAL TABLE IF NOT EXISTS subtitles_fts
32
  USING fts5(
33
  natural_key,
34
  language,
35
- content
 
36
  )
37
  """)
38
 
@@ -44,6 +50,8 @@ def _init_db(search: "SubtitleSearch") -> None:
44
  language TEXT NOT NULL,
45
  chunk_index INTEGER NOT NULL,
46
  chunk_text TEXT NOT NULL,
 
 
47
  UNIQUE(natural_key, language, chunk_index)
48
  )
49
  """
@@ -207,7 +215,8 @@ def _init_db(search: "SubtitleSearch") -> None:
207
  USING fts5(
208
  natural_key,
209
  language,
210
- content
 
211
  )
212
  """)
213
 
 
26
  """Initialize the SQLite database with FTS5 and vector tables."""
27
  conn = connect_vec_db(search.db_path, pragmas=IMAGE_DB_PRAGMAS)
28
 
29
+ # Create FTS5 virtual table for keyword search.
30
+ # porter (over unicode61: case-fold + strip diacritics) stems both indexed
31
+ # and query terms, so "preach" matches "preaching"/"preached" — a recall
32
+ # win for the English corpus. (Porter is English-only; a future multilingual
33
+ # index would pick the tokenizer per language. Changing the tokenizer needs
34
+ # an FTS rebuild — see `cli.py reindex fts`.)
35
  conn.execute("""
36
  CREATE VIRTUAL TABLE IF NOT EXISTS subtitles_fts
37
  USING fts5(
38
  natural_key,
39
  language,
40
+ content,
41
+ tokenize = 'porter unicode61'
42
  )
43
  """)
44
 
 
50
  language TEXT NOT NULL,
51
  chunk_index INTEGER NOT NULL,
52
  chunk_text TEXT NOT NULL,
53
+ start_seconds REAL,
54
+ end_seconds REAL,
55
  UNIQUE(natural_key, language, chunk_index)
56
  )
57
  """
 
215
  USING fts5(
216
  natural_key,
217
  language,
218
+ content,
219
+ tokenize = 'porter unicode61'
220
  )
221
  """)
222
 
backend/search_keyword.py CHANGED
@@ -100,7 +100,11 @@ def get_vocabulary(search: "SubtitleSearch", language: str) -> Set[str]:
100
  )
101
 
102
  vocabulary: Set[str] = set()
103
- word_pattern = re.compile(r"\b[a-zA-Z]{3,}\b")
 
 
 
 
104
  for (content,) in cursor.fetchall():
105
  words = word_pattern.findall(content.lower())
106
  vocabulary.update(words)
@@ -191,11 +195,17 @@ def search_keyword(
191
  fuzzy: bool = False,
192
  fuzzy_threshold: int = 80,
193
  include_ad: bool = True,
 
194
  ) -> List[Tuple[str, float, str]]:
195
  """SQLite FTS5 full-text search with optional fuzzy matching.
196
 
197
  Searches the subtitles index and (optionally) the AD-transcription
198
  index, combining results. Returns ``[(natural_key, score, snippet)]``.
 
 
 
 
 
199
  """
200
  conn = search._get_db_connection()
201
  fetch_limit = max(limit * 5, limit + 20)
@@ -288,6 +298,15 @@ def search_keyword(
288
  lexicon_results = collect_results(lexicon_query)
289
  if lexicon_results:
290
  results = merge_secondary_results(results, lexicon_results)
 
 
 
 
 
 
 
 
 
291
  if fuzzy and len(results) < limit:
292
  fuzzy_query = expand_query_with_fuzzy(search, query, language, fuzzy_threshold)
293
  if fuzzy_query != query.lower().strip():
 
100
  )
101
 
102
  vocabulary: Set[str] = set()
103
+ # Unicode letters (3+), excluding digits/underscore. [^\W\d_] matches the
104
+ # same set as [a-zA-Z] for English but also accented/non-Latin letters, so
105
+ # the fuzzy spell-correction vocabulary works for non-Latin languages too
106
+ # (the old ASCII-only [a-zA-Z] left them with an empty vocabulary).
107
+ word_pattern = re.compile(r"[^\W\d_]{3,}", re.UNICODE)
108
  for (content,) in cursor.fetchall():
109
  words = word_pattern.findall(content.lower())
110
  vocabulary.update(words)
 
195
  fuzzy: bool = False,
196
  fuzzy_threshold: int = 80,
197
  include_ad: bool = True,
198
+ extra_terms: List[str] | None = None,
199
  ) -> List[Tuple[str, float, str]]:
200
  """SQLite FTS5 full-text search with optional fuzzy matching.
201
 
202
  Searches the subtitles index and (optionally) the AD-transcription
203
  index, combining results. Returns ``[(natural_key, score, snippet)]``.
204
+
205
+ ``extra_terms`` (Q1.7): additional recall terms (e.g. the LLM router's
206
+ ``expanded_terms``) OR-ed into the search at the same 0.85 discount as
207
+ synonym/lexicon expansion — they can broaden recall but never out-rank an
208
+ exact match.
209
  """
210
  conn = search._get_db_connection()
211
  fetch_limit = max(limit * 5, limit + 20)
 
298
  lexicon_results = collect_results(lexicon_query)
299
  if lexicon_results:
300
  results = merge_secondary_results(results, lexicon_results)
301
+ # Caller-supplied recall terms (LLM router expanded_terms): each term is
302
+ # searched independently (OR semantics) and folded in at the discount.
303
+ for term in (extra_terms or []):
304
+ term = (term or "").strip()
305
+ if not term:
306
+ continue
307
+ term_results = collect_results(term)
308
+ if term_results:
309
+ results = merge_secondary_results(results, term_results)
310
  if fuzzy and len(results) < limit:
311
  fuzzy_query = expand_query_with_fuzzy(search, query, language, fuzzy_threshold)
312
  if fuzzy_query != query.lower().strip():
backend/search_logger.py ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Lightweight analytics log of the searches users actually run.
2
+
3
+ Purpose (Glenn's ask): capture every query so we can see what people search
4
+ for, find queries we serve poorly (zero / few results), and spot trends to
5
+ improve on. This is product analytics, not request logging — there is no
6
+ per-user identity (the app is one shared password) and no IP/PII is stored;
7
+ the query text itself is the signal we want.
8
+
9
+ Storage: a dedicated WAL SQLite DB (``search_log.db``) so its writes never
10
+ contend with the large read databases. Logging is best-effort — a logging
11
+ failure must never break a search (every write is wrapped and swallowed with a
12
+ warning).
13
+
14
+ Enabled by default; ``SEARCH_UI_SEARCH_LOG=0`` turns it off.
15
+
16
+ Hosted (Hugging Face) durability caveat: the Space's disk is ephemeral, so the
17
+ log accumulates only between restarts (the keep-warm heartbeat means that is
18
+ usually weeks). For durable history, pull it periodically via the
19
+ ``/api/search-log/export`` NDJSON endpoint (e.g. from the keep-warm workflow)
20
+ or copy ``search_log.db`` out before a redeploy.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import os
26
+ import threading
27
+ from typing import Any
28
+
29
+ from db_utils import IMAGE_DB_PRAGMAS, connect_sqlite
30
+ from runtime_paths import get_search_log_db_path
31
+ from utils import log_message
32
+
33
+ SEARCH_LOG_ENV = "SEARCH_UI_SEARCH_LOG"
34
+ _TRUTHY = {"1", "true", "yes", "on"}
35
+ _FALSY = {"0", "false", "no", "off"}
36
+
37
+ # Guards lazy one-time schema creation per process.
38
+ _init_lock = threading.Lock()
39
+ _initialized = False
40
+
41
+
42
+ def is_enabled() -> bool:
43
+ """Search logging is on unless explicitly disabled via the env var."""
44
+ raw = os.environ.get(SEARCH_LOG_ENV, "").strip().lower()
45
+ if raw in _FALSY:
46
+ return False
47
+ return True # default on (also covers blank / truthy)
48
+
49
+
50
+ def _connect():
51
+ return connect_sqlite(get_search_log_db_path(), pragmas=IMAGE_DB_PRAGMAS)
52
+
53
+
54
+ def _ensure_schema(conn) -> None:
55
+ conn.execute(
56
+ """
57
+ CREATE TABLE IF NOT EXISTS search_log (
58
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
59
+ ts TEXT NOT NULL DEFAULT (datetime('now')),
60
+ query TEXT NOT NULL,
61
+ language TEXT NOT NULL,
62
+ method TEXT NOT NULL,
63
+ result_count INTEGER NOT NULL,
64
+ zero_results INTEGER NOT NULL,
65
+ router_used TEXT,
66
+ cached INTEGER NOT NULL DEFAULT 0,
67
+ total_time_ms REAL,
68
+ source TEXT
69
+ )
70
+ """
71
+ )
72
+ # Indexes that serve the analytics queries below.
73
+ conn.execute("CREATE INDEX IF NOT EXISTS idx_search_log_ts ON search_log(ts)")
74
+ conn.execute(
75
+ "CREATE INDEX IF NOT EXISTS idx_search_log_zero ON search_log(zero_results, query)"
76
+ )
77
+ conn.commit()
78
+
79
+
80
+ def _init_once(conn) -> None:
81
+ global _initialized
82
+ if _initialized:
83
+ return
84
+ with _init_lock:
85
+ if not _initialized:
86
+ _ensure_schema(conn)
87
+ _initialized = True
88
+
89
+
90
+ def log_search(
91
+ *,
92
+ query: str,
93
+ language: str,
94
+ method: str,
95
+ result_count: int,
96
+ router_used: str | None = None,
97
+ cached: bool = False,
98
+ total_time_ms: float | None = None,
99
+ source: str = "search",
100
+ ) -> None:
101
+ """Record one search. Best-effort: never raises into the request path."""
102
+ if not is_enabled():
103
+ return
104
+ normalized = (query or "").strip()
105
+ if not normalized:
106
+ return # don't log empty-query "searches"
107
+ try:
108
+ conn = _connect()
109
+ try:
110
+ _init_once(conn)
111
+ conn.execute(
112
+ """
113
+ INSERT INTO search_log
114
+ (query, language, method, result_count, zero_results,
115
+ router_used, cached, total_time_ms, source)
116
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
117
+ """,
118
+ (
119
+ normalized,
120
+ language,
121
+ method,
122
+ int(result_count),
123
+ 1 if int(result_count) == 0 else 0,
124
+ router_used,
125
+ 1 if cached else 0,
126
+ total_time_ms,
127
+ source,
128
+ ),
129
+ )
130
+ conn.commit()
131
+ finally:
132
+ conn.close()
133
+ except Exception as exc: # noqa: BLE001 - logging must never break search
134
+ log_message(f"search_logger.log_search failed: {exc}", "WARNING")
135
+
136
+
137
+ def get_stats(*, limit: int = 50, days: int | None = 30) -> dict[str, Any]:
138
+ """Aggregate the log for the admin readout: volume, top queries, and — most
139
+ useful for improvement — the queries that returned zero results."""
140
+ if not is_enabled():
141
+ return {"enabled": False}
142
+ try:
143
+ conn = _connect()
144
+ except Exception as exc: # noqa: BLE001
145
+ return {"enabled": True, "error": str(exc)}
146
+ try:
147
+ _init_once(conn)
148
+ window = ""
149
+ params_tail: tuple = ()
150
+ if days is not None and days > 0:
151
+ window = "WHERE ts >= datetime('now', ?)"
152
+ params_tail = (f"-{int(days)} days",)
153
+
154
+ total = conn.execute(
155
+ f"SELECT COUNT(*) FROM search_log {window}", params_tail
156
+ ).fetchone()[0]
157
+ distinct = conn.execute(
158
+ f"SELECT COUNT(DISTINCT lower(query)) FROM search_log {window}", params_tail
159
+ ).fetchone()[0]
160
+ zero_total = conn.execute(
161
+ f"SELECT COUNT(*) FROM search_log {window}{' AND' if window else 'WHERE'} zero_results = 1",
162
+ params_tail,
163
+ ).fetchone()[0]
164
+
165
+ top = conn.execute(
166
+ f"""
167
+ SELECT lower(query) AS q, COUNT(*) AS n,
168
+ AVG(result_count) AS avg_results
169
+ FROM search_log {window}
170
+ GROUP BY lower(query)
171
+ ORDER BY n DESC, q ASC
172
+ LIMIT ?
173
+ """,
174
+ (*params_tail, limit),
175
+ ).fetchall()
176
+
177
+ zero = conn.execute(
178
+ f"""
179
+ SELECT lower(query) AS q, COUNT(*) AS n
180
+ FROM search_log
181
+ {window}{' AND' if window else 'WHERE'} zero_results = 1
182
+ GROUP BY lower(query)
183
+ ORDER BY n DESC, q ASC
184
+ LIMIT ?
185
+ """,
186
+ (*params_tail, limit),
187
+ ).fetchall()
188
+
189
+ return {
190
+ "enabled": True,
191
+ "window_days": days,
192
+ "total_searches": int(total),
193
+ "distinct_queries": int(distinct),
194
+ "zero_result_searches": int(zero_total),
195
+ "top_queries": [
196
+ {"query": q, "count": int(n), "avg_results": round(a or 0, 1)}
197
+ for q, n, a in top
198
+ ],
199
+ "zero_result_queries": [
200
+ {"query": q, "count": int(n)} for q, n in zero
201
+ ],
202
+ }
203
+ finally:
204
+ conn.close()
205
+
206
+
207
+ def iter_rows(limit: int = 10000):
208
+ """Yield recent log rows as dicts, newest first (for NDJSON export)."""
209
+ conn = _connect()
210
+ try:
211
+ _init_once(conn)
212
+ cursor = conn.execute(
213
+ """
214
+ SELECT ts, query, language, method, result_count, zero_results,
215
+ router_used, cached, total_time_ms, source
216
+ FROM search_log ORDER BY id DESC LIMIT ?
217
+ """,
218
+ (int(limit),),
219
+ )
220
+ cols = [c[0] for c in cursor.description]
221
+ for row in cursor:
222
+ yield dict(zip(cols, row))
223
+ finally:
224
+ conn.close()
backend/search_method_runner.py CHANGED
@@ -98,6 +98,7 @@ def run_search_method(
98
  model: str = "siglip2",
99
  fuzzy: bool = True,
100
  fuzzy_threshold: int = 80,
 
101
  ) -> dict[str, Any]:
102
  """Run one backend search method and return enriched raw results."""
103
  if not q or not q.strip():
@@ -138,7 +139,10 @@ def run_search_method(
138
 
139
  search = get_search_service()
140
  if method == "keyword":
141
- results = search.search_keyword(q, language, limit, fuzzy=fuzzy, fuzzy_threshold=fuzzy_threshold)
 
 
 
142
  elif method == "semantic":
143
  results = search.search_semantic(q, language, limit)
144
  else:
 
98
  model: str = "siglip2",
99
  fuzzy: bool = True,
100
  fuzzy_threshold: int = 80,
101
+ extra_terms: list[str] | None = None,
102
  ) -> dict[str, Any]:
103
  """Run one backend search method and return enriched raw results."""
104
  if not q or not q.strip():
 
139
 
140
  search = get_search_service()
141
  if method == "keyword":
142
+ results = search.search_keyword(
143
+ q, language, limit, fuzzy=fuzzy, fuzzy_threshold=fuzzy_threshold,
144
+ extra_terms=extra_terms,
145
+ )
146
  elif method == "semantic":
147
  results = search.search_semantic(q, language, limit)
148
  else:
backend/search_route_results.py CHANGED
@@ -4,7 +4,7 @@ from __future__ import annotations
4
 
5
  import os
6
  import re
7
- from datetime import datetime
8
  from typing import Any
9
 
10
  from asset_urls import video_thumbnail_url
@@ -18,6 +18,72 @@ from utils import log_message
18
  AUDIO_DESCRIPTION_SUFFIX_RE = re.compile(r"\s*\(with audio descriptions\)\s*$", re.IGNORECASE)
19
 
20
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  def find_timestamp_for_snippet(
22
  subtitles_root: str,
23
  natural_key: str,
@@ -28,6 +94,13 @@ def find_timestamp_for_snippet(
28
  if not snippet:
29
  return None
30
 
 
 
 
 
 
 
 
31
  clean_snippet = re.sub(r"<[^>]+>", "", snippet)
32
  clean_snippet = clean_snippet.replace("...", "").strip()
33
  if len(clean_snippet) < 10:
@@ -222,6 +295,8 @@ def apply_result_filters(
222
  if published:
223
  try:
224
  pub_dt = datetime.fromisoformat(published.replace("Z", "+00:00"))
 
 
225
  if date_from_dt and pub_dt < date_from_dt:
226
  return False
227
  if date_to_dt and pub_dt > date_to_dt:
@@ -482,9 +557,15 @@ def _parse_filter_date(value: str | None) -> datetime | None:
482
  if not value:
483
  return None
484
  try:
485
- return datetime.fromisoformat(value)
486
  except ValueError:
487
  return None
 
 
 
 
 
 
488
 
489
 
490
  def _coerce_float(value: Any) -> float | None:
 
4
 
5
  import os
6
  import re
7
+ from datetime import datetime, timezone
8
  from typing import Any
9
 
10
  from asset_urls import video_thumbnail_url
 
18
  AUDIO_DESCRIPTION_SUFFIX_RE = re.compile(r"\s*\(with audio descriptions\)\s*$", re.IGNORECASE)
19
 
20
 
21
+ # Cache (per search-DB path) of whether subtitle_chunks carries the Q2.2
22
+ # timestamp columns, so an un-backfilled DB doesn't raise per result.
23
+ _CHUNK_TS_COLUMNS: dict[str, bool] = {}
24
+
25
+
26
+ def _chunk_ts_columns_present(db_path: str) -> bool:
27
+ cached = _CHUNK_TS_COLUMNS.get(db_path)
28
+ if cached is not None:
29
+ return cached
30
+ present = False
31
+ try:
32
+ from db_utils import connect_sqlite
33
+
34
+ conn = connect_sqlite(db_path, foreign_keys=False)
35
+ try:
36
+ cols = {row[1] for row in conn.execute("PRAGMA table_info(subtitle_chunks)")}
37
+ present = "start_seconds" in cols and "end_seconds" in cols
38
+ finally:
39
+ conn.close()
40
+ except Exception: # noqa: BLE001 - absence/unreadable → treat as not present
41
+ present = False
42
+ _CHUNK_TS_COLUMNS[db_path] = present
43
+ return present
44
+
45
+
46
+ def lookup_stored_chunk_timestamp(
47
+ natural_key: str, snippet: str, language: str
48
+ ) -> dict[str, Any] | None:
49
+ """Return the chunk's stored (start, end) for a semantic snippet, or None.
50
+
51
+ Q2.2: semantic snippets are a chunk_text prefix, so a stored timestamp can
52
+ be looked up by prefix instead of re-parsing the VTT and guessing by word
53
+ overlap. Returns None on keyword/FTS snippets (which won't prefix-match a
54
+ chunk) so the VTT fallback still handles those.
55
+ """
56
+ clean = re.sub(r"<[^>]+>", "", snippet or "").replace("...", "").strip()
57
+ if len(clean) < 10:
58
+ return None
59
+ from runtime_paths import get_search_db_path
60
+
61
+ db_path = get_search_db_path()
62
+ if not _chunk_ts_columns_present(db_path):
63
+ return None
64
+ try:
65
+ from db_utils import connect_sqlite
66
+
67
+ # Escape LIKE wildcards in the snippet prefix so a literal %/_ in
68
+ # subtitle text can't act as a wildcard (worst case a sibling chunk).
69
+ prefix = clean[:60].replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
70
+ conn = connect_sqlite(db_path, foreign_keys=False)
71
+ try:
72
+ row = conn.execute(
73
+ "SELECT start_seconds, end_seconds FROM subtitle_chunks "
74
+ "WHERE natural_key = ? AND language = ? AND start_seconds IS NOT NULL "
75
+ "AND chunk_text LIKE ? ESCAPE '\\' LIMIT 1",
76
+ (natural_key, language, prefix + "%"),
77
+ ).fetchone()
78
+ finally:
79
+ conn.close()
80
+ except Exception: # noqa: BLE001 - never break enrichment over a lookup
81
+ return None
82
+ if row and row[0] is not None:
83
+ return {"start": row[0], "end": row[1]}
84
+ return None
85
+
86
+
87
  def find_timestamp_for_snippet(
88
  subtitles_root: str,
89
  natural_key: str,
 
94
  if not snippet:
95
  return None
96
 
97
+ # Q2.2: prefer the timestamp stored on the matching chunk (exact, no VTT
98
+ # parse). Falls through to the VTT word-overlap guess for keyword/FTS
99
+ # snippets or DBs that haven't been backfilled.
100
+ stored = lookup_stored_chunk_timestamp(natural_key, snippet, language)
101
+ if stored is not None:
102
+ return stored
103
+
104
  clean_snippet = re.sub(r"<[^>]+>", "", snippet)
105
  clean_snippet = clean_snippet.replace("...", "").strip()
106
  if len(clean_snippet) < 10:
 
295
  if published:
296
  try:
297
  pub_dt = datetime.fromisoformat(published.replace("Z", "+00:00"))
298
+ if pub_dt.tzinfo is None:
299
+ pub_dt = pub_dt.replace(tzinfo=timezone.utc)
300
  if date_from_dt and pub_dt < date_from_dt:
301
  return False
302
  if date_to_dt and pub_dt > date_to_dt:
 
557
  if not value:
558
  return None
559
  try:
560
+ parsed = datetime.fromisoformat(value)
561
  except ValueError:
562
  return None
563
+ # Media firstPublished dates are timezone-aware ("...Z"); a bare filter
564
+ # date like "2024-01-01" parses naive, and comparing the two raises
565
+ # TypeError. Treat naive filter dates as UTC so the comparison is legal.
566
+ if parsed.tzinfo is None:
567
+ parsed = parsed.replace(tzinfo=timezone.utc)
568
+ return parsed
569
 
570
 
571
  def _coerce_float(value: Any) -> float | None:
backend/search_routes.py CHANGED
@@ -28,6 +28,8 @@ from search_route_results import (
28
  finalize_results,
29
  )
30
  from search_warmup import get_search_warmup_status, reserve_search_warmup, run_search_warmup
 
 
31
  import smart_scene_fusion
32
  from utils import log_message
33
  from process_video import get_local_video_info
@@ -35,6 +37,67 @@ from subtitles_process_vtt import parse_vtt
35
  from validation import normalize_language_code, resolve_under, validate_natural_key
36
 
37
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  def _get_default_search_service():
39
  return get_search_instance()
40
 
@@ -112,10 +175,29 @@ def create_search_router(
112
  routing if OPENROUTER_API_KEY is not set."""
113
  start_time = time.time()
114
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
115
  try:
116
  # ── 1. Query intelligence (LLM if key set, rule-based otherwise) ──
117
  # Uses the injected router (LLM by default; a mock in tests).
118
- plan = get_query_router().plan_search(q, "text")
 
 
 
119
  routed_query = plan.extracted_query or q
120
  expanded_query = getattr(plan, "expanded_query", routed_query)
121
  expanded_terms = getattr(plan, "expanded_terms", [])
@@ -211,12 +293,74 @@ def create_search_router(
211
  if key not in result_by_key:
212
  result_by_key[key] = {**result, "source_method": method.value}
213
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
214
  rrf_scores: dict[str, float] = dict(text_rrf)
215
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
216
  # ── 4b. Optional scene/video (VLM) stream — fused by RANK only ────
217
  # scene_search uses bge-m3, a DIFFERENT vector space from the Qwen
218
  # text methods, so its scores are NOT comparable — it joins the merge
219
- # purely by RRF rank. Off by default (smart_scene_fusion flag); an
220
  # optional stream must never break core search, hence the broad guard.
221
  #
222
  # Gated by INTENT, and the granularity follows the wording:
@@ -236,18 +380,25 @@ def create_search_router(
236
  scene_weight = smart_scene_fusion.weight_for(visual_intent)
237
  try:
238
  import scene_search # lazy: pulls in the bge-m3 embedder
 
 
239
  if visual_intent == "clip":
240
  # Clip intent = the editor wants visual FOOTAGE. Drop
241
  # talking-head windows (a presenter speaking to camera):
242
  # a description that merely mentions the topic would
243
  # otherwise surface a talking head, which is exactly the
244
- # "don't match words spoken in a talk" failure.
245
- scene_hits = scene_search.search_scenes(
 
 
 
246
  routed_query, language, limit,
247
  exclude_shot_types={"talking-head"},
248
- ).results
249
  else:
250
- scene_hits = scene_search.search_videos(routed_query, language, limit).results
 
 
251
  except Exception as exc: # noqa: BLE001 - optional stream, fail soft
252
  log_message(f"Smart-search scene stream failed: {exc}")
253
  scene_hits = []
@@ -393,7 +544,8 @@ def create_search_router(
393
  # No colon in the matched text means no explicit verse was
394
  # given ("Matthew 24") -> search the whole chapter.
395
  verse = ref.verse_start if ":" in ref.original_text else None
396
- rows = get_search_service().search_scripture(
 
397
  book=ref.book,
398
  chapter=ref.chapter,
399
  verse=verse,
@@ -447,6 +599,22 @@ def create_search_router(
447
  "expanded_terms": expanded_terms,
448
  "explanation": getattr(plan, "explanation", ""),
449
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
450
  pre_filter_count = len(response["results"])
451
  filtered_results, filters_applied = apply_result_filters(
452
  results=response["results"],
@@ -464,6 +632,13 @@ def create_search_router(
464
  response["filters"] = filters_applied if filters_applied else None
465
  response["total_before_filters"] = pre_filter_count if filters_applied else None
466
  response["total_time_ms"] = round((time.time() - start_time) * 1000, 1)
 
 
 
 
 
 
 
467
  return response
468
 
469
  except Exception as exc:
@@ -488,35 +663,40 @@ def create_search_router(
488
  tmp.write(await file.read())
489
  temp_path = tmp.name
490
 
491
- image_search = get_image_search_service()
492
- embedding = generate_image_embedding(temp_path)
493
- # search_by_image_embedding returns (natural_key, frame_number,
494
- # distance), where distance is a Hamming distance over the
495
- # bit[1152] image_embeddings vector. Convert to a [0,1]
496
- # similarity so higher = better (matches search_by_embedding).
497
- results = image_search.search_by_image_embedding(embedding, limit)
498
- ranked_frames = [
499
- (
500
- natural_key,
501
- frame_number,
502
- 1.0 - (distance / 1152.0),
503
- image_search.get_frame_categories(natural_key, frame_number),
504
- [],
 
 
 
 
 
 
 
 
 
 
 
 
505
  )
506
- for natural_key, frame_number, distance in results
507
- ]
508
- enriched_results = build_image_results(
509
- image_search=image_search,
510
- lookup_media_item=lookup_media_item,
511
- decorate_result=decorate_result,
512
- language=language,
513
- ranked_frames=ranked_frames,
514
- )
515
- finalized_results = finalize_results(
516
- results=enriched_results,
517
- language=language,
518
- load_all_media=load_all_media,
519
- )
520
  return {
521
  "query": q or "[image search]",
522
  "language": language,
@@ -528,21 +708,26 @@ def create_search_router(
528
  "total_time_ms": round((time.time() - start_time) * 1000, 1),
529
  }
530
 
531
- response = build_smart_text_results(
532
- subtitles_root=subtitles_root,
533
- search_service=get_search_service(),
534
- lookup_media_item=lookup_media_item,
535
- decorate_result=decorate_result,
536
- q=q,
537
- language=language,
538
- limit=limit,
539
- )
540
- response["results"] = finalize_results(
541
- results=response["results"],
542
- language=language,
543
- load_all_media=load_all_media,
544
- )
545
- response["count"] = len(response["results"])
 
 
 
 
 
546
  response["total_time_ms"] = round((time.time() - start_time) * 1000, 1)
547
  return response
548
 
@@ -611,12 +796,38 @@ def create_search_router(
611
  response["fuzzy_threshold"] = fuzzy_threshold if fuzzy else None
612
  response["filters"] = filters_applied if filters_applied else None
613
  response["total_before_filters"] = pre_filter_count if filters_applied else None
 
 
 
 
 
614
  return response
615
 
616
  except Exception as exc:
617
  log_message(f"Error searching: {exc}")
618
  raise HTTPException(status_code=500, detail=str(exc))
619
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
620
  @router.get("/api/categories")
621
  async def get_categories_endpoint(language: str = "E"):
622
  """Get all unique categories and subcategories from media items."""
@@ -970,32 +1181,37 @@ def create_content_router(
970
  temp_path = tmp.name
971
 
972
  log_message(f"Generating embedding for uploaded image: {file.filename}")
973
- embedding = generate_image_embedding(temp_path)
974
 
975
- image_search = get_image_search_service()
976
- media_info = load_all_media(language)
977
- results = []
978
-
979
- for natural_key, frame_number, distance in image_search.search_by_image_embedding(
980
- embedding,
981
- limit,
982
- ):
983
- # distance is a Hamming distance over the bit[1152]
984
- # image_embeddings vector → [0,1] similarity (matches
985
- # search_by_embedding); /2.0 was wrong and produced scores
986
- # that went sharply negative.
987
- similarity = 1.0 - (distance / 1152.0)
988
- results.append(
989
- {
990
- "natural_key": natural_key,
991
- "frame_number": frame_number,
992
- "score": similarity,
993
- "thumbnail": video_thumbnail_url(natural_key, frame_number),
994
- "mediaItem": media_info.get(natural_key) if media_info else None,
995
- "local_info": get_local_video_info(natural_key),
996
- }
997
- )
 
 
 
 
 
998
 
 
999
  return {
1000
  "results": results,
1001
  "count": len(results),
@@ -1218,7 +1434,9 @@ def create_analysis_router() -> APIRouter:
1218
  from nlp_search import process_natural_language_query
1219
  from scripture_parser import parse_scripture_references
1220
 
1221
- try:
 
 
1222
  processed = process_natural_language_query(q)
1223
  search = get_search_instance()
1224
 
@@ -1296,6 +1514,9 @@ def create_analysis_router() -> APIRouter:
1296
  "count": len(results),
1297
  }
1298
 
 
 
 
1299
  except Exception as exc:
1300
  log_message(f"Error in natural language search: {exc}")
1301
  raise HTTPException(status_code=500, detail=str(exc))
@@ -1319,7 +1540,8 @@ def create_analysis_router() -> APIRouter:
1319
  language,
1320
  detail=f"No subtitle content found for {natural_key}",
1321
  )
1322
- analysis = analyze_content(text)
 
1323
  all_media = get_all_media(language)
1324
  media_item = all_media.get(natural_key) if all_media else None
1325
 
@@ -1347,7 +1569,7 @@ def create_analysis_router() -> APIRouter:
1347
  detail="Text must be at least 10 characters",
1348
  )
1349
 
1350
- return {"analysis": analyze_content(text)}
1351
 
1352
  except HTTPException:
1353
  raise
@@ -1362,7 +1584,7 @@ def create_analysis_router() -> APIRouter:
1362
 
1363
  try:
1364
  text = _get_video_text_or_404(natural_key, language)
1365
- topics = classify_topics(text, top_k=5)
1366
  return {
1367
  "natural_key": natural_key,
1368
  "topics": [{"topic": topic, "confidence": round(confidence, 3)} for topic, confidence in topics],
@@ -1381,7 +1603,11 @@ def create_analysis_router() -> APIRouter:
1381
 
1382
  try:
1383
  text = _get_video_text_or_404(natural_key, language)
1384
- summary = generate_extractive_summary(text, num_sentences=sentences)
 
 
 
 
1385
  all_media = get_all_media(language)
1386
  media_item = all_media.get(natural_key) if all_media else None
1387
 
 
28
  finalize_results,
29
  )
30
  from search_warmup import get_search_warmup_status, reserve_search_warmup, run_search_warmup
31
+ from result_cache import smart_search_cache
32
+ import search_logger
33
  import smart_scene_fusion
34
  from utils import log_message
35
  from process_video import get_local_video_info
 
37
  from validation import normalize_language_code, resolve_under, validate_natural_key
38
 
39
 
40
+ # Title voter for the smart-search merge. Users are usually searching for what
41
+ # is SAID in a video, not its title — a loose title match is actively
42
+ # misleading. So the title stream only votes on near-certain matches (the whole
43
+ # multi-word query inside a title, an exact title, or a near-exact fuzzy hit),
44
+ # is capped, and votes at reduced weight: a video matching content AND title
45
+ # gets a modest boost; a title-only match enters below an equally-ranked
46
+ # content match instead of displacing it.
47
+ SMART_TITLE_WEIGHT_ENV = "SEARCH_UI_SMART_TITLE_WEIGHT"
48
+ SMART_TITLE_DEFAULT_WEIGHT = 0.7
49
+ SMART_TITLE_MIN_QUERY_CHARS = 4
50
+ SMART_TITLE_FUZZY_THRESHOLD = 90
51
+ SMART_TITLE_MAX_VOTES = 8
52
+
53
+
54
+ def _smart_title_weight() -> float:
55
+ raw = os.getenv(SMART_TITLE_WEIGHT_ENV, "").strip()
56
+ if not raw:
57
+ return SMART_TITLE_DEFAULT_WEIGHT
58
+ try:
59
+ return max(0.0, float(raw))
60
+ except ValueError:
61
+ return SMART_TITLE_DEFAULT_WEIGHT
62
+
63
+
64
+ def _strong_title_matches(all_media: dict, query: str) -> list:
65
+ """Title hits confident enough to vote in the smart-search merge.
66
+
67
+ Returns at most SMART_TITLE_MAX_VOTES ``(natural_key, score, media_item)``
68
+ tuples, best first. Single-word queries only match a title verbatim
69
+ ("hope" must not boost every title containing the word); multi-word
70
+ queries match as a substring or near-exact fuzzy hit.
71
+ """
72
+ text = (query or "").strip().lower()
73
+ if len(text) < SMART_TITLE_MIN_QUERY_CHARS:
74
+ return []
75
+ multi_word = len(text.split()) >= 2
76
+
77
+ from rapidfuzz import fuzz
78
+
79
+ matches = []
80
+ for natural_key, media_item in all_media.items():
81
+ title = (media_item.get("title") or "").strip().lower()
82
+ if not title:
83
+ continue
84
+ if title == text:
85
+ score = 1.0
86
+ elif multi_word and text in title:
87
+ score = 0.95
88
+ elif multi_word:
89
+ ratio = fuzz.partial_ratio(text, title)
90
+ if ratio < SMART_TITLE_FUZZY_THRESHOLD:
91
+ continue
92
+ score = (ratio / 100) * 0.9
93
+ else:
94
+ continue
95
+ matches.append((natural_key, score, media_item))
96
+
97
+ matches.sort(key=lambda match: (-match[1], (match[2].get("title") or "")))
98
+ return matches[:SMART_TITLE_MAX_VOTES]
99
+
100
+
101
  def _get_default_search_service():
102
  return get_search_instance()
103
 
 
175
  routing if OPENROUTER_API_KEY is not set."""
176
  start_time = time.time()
177
 
178
+ # The served index is static between bundle deploys, so an identical
179
+ # repeat search can skip the whole pipeline (encode + merge + filter).
180
+ cache_key = (
181
+ q, language, limit, date_from, date_to, duration_min, duration_max,
182
+ include_series, exclude_series, exclude_text_only_visual,
183
+ )
184
+ cached = smart_search_cache.get(cache_key)
185
+ if cached is not None:
186
+ search_logger.log_search(
187
+ query=q, language=language, method="smart",
188
+ result_count=cached.get("count", 0),
189
+ router_used=cached.get("router_used"), cached=True,
190
+ total_time_ms=cached.get("total_time_ms"), source="smart-search",
191
+ )
192
+ return {**cached, "cached": True}
193
+
194
  try:
195
  # ── 1. Query intelligence (LLM if key set, rule-based otherwise) ──
196
  # Uses the injected router (LLM by default; a mock in tests).
197
+ # The LLM path is a blocking HTTP call (up to 15 s), so offload it
198
+ # to a worker thread — otherwise it stalls the whole event loop and
199
+ # every other request queues behind one uncached query.
200
+ plan = await asyncio.to_thread(get_query_router().plan_search, q, "text")
201
  routed_query = plan.extracted_query or q
202
  expanded_query = getattr(plan, "expanded_query", routed_query)
203
  expanded_terms = getattr(plan, "expanded_terms", [])
 
293
  if key not in result_by_key:
294
  result_by_key[key] = {**result, "source_method": method.value}
295
 
296
+ # ── 4·Q1.7. Expanded-terms keyword recall voter ──────────────────
297
+ # The LLM router emits expanded_terms (extra recall words) that were
298
+ # generated and returned but never queried. OR them into one extra
299
+ # keyword pass (discounted inside search_keyword) and fold it in as
300
+ # part of the single text voter (max), so it can broaden recall
301
+ # without out-voting the primary signal. Only fires when the LLM
302
+ # router produced terms; the rule-based router (the Space default)
303
+ # produces none, so this is inert there.
304
+ if expanded_terms:
305
+ try:
306
+ kw_resp = await asyncio.to_thread(
307
+ run_search_method,
308
+ subtitles_root=subtitles_root,
309
+ get_search_service=get_search_service,
310
+ get_image_search_service=get_image_search_service,
311
+ get_face_search_service=get_face_search_service,
312
+ lookup_media_item=lookup_media_item,
313
+ decorate_result=decorate_result,
314
+ q=routed_query,
315
+ language=language,
316
+ method="keyword",
317
+ limit=limit,
318
+ extra_terms=expanded_terms,
319
+ )
320
+ kw_results = kw_resp.get("results", [])
321
+ if kw_results:
322
+ methods_executed.append("keyword_expanded_terms")
323
+ for rank, result in enumerate(kw_results):
324
+ key = result.get("natural_key", "") or str(rank)
325
+ text_rrf[key] = max(text_rrf.get(key, 0.0), 1.0 / (K + rank + 1))
326
+ if key not in result_by_key:
327
+ result_by_key[key] = {**result, "source_method": "keyword"}
328
+ except Exception as exc: # noqa: BLE001 - optional voter, fail soft
329
+ log_message(f"Smart-search expanded-terms voter failed: {exc}")
330
+
331
  rrf_scores: dict[str, float] = dict(text_rrf)
332
 
333
+ # ── 4a. Title voter — strong matches only, reduced weight ────────
334
+ # Titles are usually not what the user means (they search what is
335
+ # SAID in the video), so only near-verbatim title matches vote —
336
+ # see _strong_title_matches. Title evidence was previously invisible
337
+ # to smart-search entirely ('title' is not in SMART_EXECUTABLE).
338
+ try:
339
+ title_hits = await asyncio.to_thread(
340
+ _strong_title_matches, load_all_media(language) or {}, routed_query
341
+ )
342
+ except Exception as exc: # noqa: BLE001 - optional voter, fail soft
343
+ log_message(f"Smart-search title voter failed: {exc}")
344
+ title_hits = []
345
+ if title_hits:
346
+ methods_executed.append("title")
347
+ title_weight = _smart_title_weight()
348
+ for rank, (nk, score, media_item) in enumerate(title_hits):
349
+ rrf_scores[nk] = rrf_scores.get(nk, 0.0) + title_weight / (K + rank + 1)
350
+ if nk not in result_by_key:
351
+ result_by_key[nk] = decorate_result({
352
+ "natural_key": nk,
353
+ "score": score,
354
+ "snippet": "",
355
+ "timestamp": None,
356
+ "mediaItem": media_item,
357
+ "source_method": "title",
358
+ })
359
+
360
  # ── 4b. Optional scene/video (VLM) stream — fused by RANK only ────
361
  # scene_search uses bge-m3, a DIFFERENT vector space from the Qwen
362
  # text methods, so its scores are NOT comparable — it joins the merge
363
+ # purely by RRF rank. On by default (smart_scene_fusion flag); an
364
  # optional stream must never break core search, hence the broad guard.
365
  #
366
  # Gated by INTENT, and the granularity follows the wording:
 
380
  scene_weight = smart_scene_fusion.weight_for(visual_intent)
381
  try:
382
  import scene_search # lazy: pulls in the bge-m3 embedder
383
+ # bge-m3 inference + full-matrix cosine is seconds of CPU —
384
+ # offload so the scene stream never blocks the event loop.
385
  if visual_intent == "clip":
386
  # Clip intent = the editor wants visual FOOTAGE. Drop
387
  # talking-head windows (a presenter speaking to camera):
388
  # a description that merely mentions the topic would
389
  # otherwise surface a talking head, which is exactly the
390
+ # "don't match words spoken in a talk" failure. Offloaded
391
+ # to a thread (bge-m3 inference + full-matrix cosine is
392
+ # seconds of CPU) so it never blocks the event loop.
393
+ scene_hits = (await asyncio.to_thread(
394
+ scene_search.search_scenes,
395
  routed_query, language, limit,
396
  exclude_shot_types={"talking-head"},
397
+ )).results
398
  else:
399
+ scene_hits = (await asyncio.to_thread(
400
+ scene_search.search_videos, routed_query, language, limit
401
+ )).results
402
  except Exception as exc: # noqa: BLE001 - optional stream, fail soft
403
  log_message(f"Smart-search scene stream failed: {exc}")
404
  scene_hits = []
 
544
  # No colon in the matched text means no explicit verse was
545
  # given ("Matthew 24") -> search the whole chapter.
546
  verse = ref.verse_start if ":" in ref.original_text else None
547
+ rows = await asyncio.to_thread(
548
+ get_search_service().search_scripture,
549
  book=ref.book,
550
  chapter=ref.chapter,
551
  verse=verse,
 
599
  "expanded_terms": expanded_terms,
600
  "explanation": getattr(plan, "explanation", ""),
601
  }
602
+
603
+ # The router extracts time/duration intent from the query itself
604
+ # ("recent videos about…", "talks from 2023") into plan.filters and
605
+ # strips those words from the routed text — so unless the extracted
606
+ # filters are applied here, the user's time constraint is silently
607
+ # deleted. Explicit query params always win over plan-derived ones.
608
+ plan_filters = getattr(plan, "filters", None) or {}
609
+ if date_from is None:
610
+ date_from = plan_filters.get("date_from") or None
611
+ if date_to is None:
612
+ date_to = plan_filters.get("date_to") or None
613
+ if duration_max is None:
614
+ plan_duration_max = plan_filters.get("duration_max_seconds")
615
+ if isinstance(plan_duration_max, (int, float)) and plan_duration_max > 0:
616
+ duration_max = int(plan_duration_max)
617
+
618
  pre_filter_count = len(response["results"])
619
  filtered_results, filters_applied = apply_result_filters(
620
  results=response["results"],
 
632
  response["filters"] = filters_applied if filters_applied else None
633
  response["total_before_filters"] = pre_filter_count if filters_applied else None
634
  response["total_time_ms"] = round((time.time() - start_time) * 1000, 1)
635
+ smart_search_cache.put(cache_key, response)
636
+ search_logger.log_search(
637
+ query=q, language=language, method="smart",
638
+ result_count=response.get("count", 0),
639
+ router_used=response.get("router_used"), cached=False,
640
+ total_time_ms=response.get("total_time_ms"), source="smart-search",
641
+ )
642
  return response
643
 
644
  except Exception as exc:
 
663
  tmp.write(await file.read())
664
  temp_path = tmp.name
665
 
666
+ # SigLIP image encoding + Hamming KNN + enrichment is seconds of
667
+ # CPU — run the whole block off the event loop.
668
+ def _image_branch():
669
+ image_search = get_image_search_service()
670
+ embedding = generate_image_embedding(temp_path)
671
+ # search_by_image_embedding returns (natural_key, frame_number,
672
+ # distance), where distance is a Hamming distance over the
673
+ # bit[1152] image_embeddings vector. Convert to a [0,1]
674
+ # similarity so higher = better (matches search_by_embedding).
675
+ results = image_search.search_by_image_embedding(embedding, limit)
676
+ ranked_frames = [
677
+ (
678
+ natural_key,
679
+ frame_number,
680
+ 1.0 - (distance / 1152.0),
681
+ image_search.get_frame_categories(natural_key, frame_number),
682
+ [],
683
+ )
684
+ for natural_key, frame_number, distance in results
685
+ ]
686
+ enriched_results = build_image_results(
687
+ image_search=image_search,
688
+ lookup_media_item=lookup_media_item,
689
+ decorate_result=decorate_result,
690
+ language=language,
691
+ ranked_frames=ranked_frames,
692
  )
693
+ return finalize_results(
694
+ results=enriched_results,
695
+ language=language,
696
+ load_all_media=load_all_media,
697
+ )
698
+
699
+ finalized_results = await asyncio.to_thread(_image_branch)
 
 
 
 
 
 
 
700
  return {
701
  "query": q or "[image search]",
702
  "language": language,
 
708
  "total_time_ms": round((time.time() - start_time) * 1000, 1),
709
  }
710
 
711
+ # Text fallback also encodes the query (embedding inference) — offload.
712
+ def _text_branch():
713
+ resp = build_smart_text_results(
714
+ subtitles_root=subtitles_root,
715
+ search_service=get_search_service(),
716
+ lookup_media_item=lookup_media_item,
717
+ decorate_result=decorate_result,
718
+ q=q,
719
+ language=language,
720
+ limit=limit,
721
+ )
722
+ resp["results"] = finalize_results(
723
+ results=resp["results"],
724
+ language=language,
725
+ load_all_media=load_all_media,
726
+ )
727
+ resp["count"] = len(resp["results"])
728
+ return resp
729
+
730
+ response = await asyncio.to_thread(_text_branch)
731
  response["total_time_ms"] = round((time.time() - start_time) * 1000, 1)
732
  return response
733
 
 
796
  response["fuzzy_threshold"] = fuzzy_threshold if fuzzy else None
797
  response["filters"] = filters_applied if filters_applied else None
798
  response["total_before_filters"] = pre_filter_count if filters_applied else None
799
+ search_logger.log_search(
800
+ query=q, language=language, method=method,
801
+ result_count=response.get("count", len(filtered_results)),
802
+ cached=False, source="search",
803
+ )
804
  return response
805
 
806
  except Exception as exc:
807
  log_message(f"Error searching: {exc}")
808
  raise HTTPException(status_code=500, detail=str(exc))
809
 
810
+ @router.get("/api/search-log/stats")
811
+ async def search_log_stats(days: int = 30, limit: int = 50):
812
+ """Analytics over the searches users have run: volume, top queries, and
813
+ — most useful for improvement — the queries that returned zero results.
814
+ Auth-gated (admin) like every /api route. Mounted in hosted mode too,
815
+ since that's where real user queries land."""
816
+ limit = max(1, min(limit, 500))
817
+ return await asyncio.to_thread(search_logger.get_stats, limit=limit, days=days)
818
+
819
+ @router.get("/api/search-log/export")
820
+ async def search_log_export(limit: int = 10000):
821
+ """Download recent search-log rows as NDJSON (one JSON object per line)
822
+ for durable off-Space archival/analysis."""
823
+ import json as _json
824
+ from fastapi.responses import PlainTextResponse
825
+
826
+ limit = max(1, min(limit, 100000))
827
+ rows = await asyncio.to_thread(lambda: list(search_logger.iter_rows(limit)))
828
+ body = "\n".join(_json.dumps(r, ensure_ascii=False) for r in rows)
829
+ return PlainTextResponse(body, media_type="application/x-ndjson")
830
+
831
  @router.get("/api/categories")
832
  async def get_categories_endpoint(language: str = "E"):
833
  """Get all unique categories and subcategories from media items."""
 
1181
  temp_path = tmp.name
1182
 
1183
  log_message(f"Generating embedding for uploaded image: {file.filename}")
 
1184
 
1185
+ # SigLIP encode + Hamming KNN + per-result local-info lookups are
1186
+ # seconds of CPU — run off the event loop. Thumbnail URLs go through
1187
+ # video_thumbnail_url (CDN-aware) per main's thumbnail work.
1188
+ def _image_search():
1189
+ embedding = generate_image_embedding(temp_path)
1190
+ image_search = get_image_search_service()
1191
+ media_info = load_all_media(language)
1192
+ out = []
1193
+ for natural_key, frame_number, distance in image_search.search_by_image_embedding(
1194
+ embedding,
1195
+ limit,
1196
+ ):
1197
+ # distance is a Hamming distance over the bit[1152]
1198
+ # image_embeddings vector → [0,1] similarity (matches
1199
+ # search_by_embedding); /2.0 was wrong and produced scores
1200
+ # that went sharply negative.
1201
+ similarity = 1.0 - (distance / 1152.0)
1202
+ out.append(
1203
+ {
1204
+ "natural_key": natural_key,
1205
+ "frame_number": frame_number,
1206
+ "score": similarity,
1207
+ "thumbnail": video_thumbnail_url(natural_key, frame_number),
1208
+ "mediaItem": media_info.get(natural_key) if media_info else None,
1209
+ "local_info": get_local_video_info(natural_key),
1210
+ }
1211
+ )
1212
+ return out
1213
 
1214
+ results = await asyncio.to_thread(_image_search)
1215
  return {
1216
  "results": results,
1217
  "count": len(results),
 
1434
  from nlp_search import process_natural_language_query
1435
  from scripture_parser import parse_scripture_references
1436
 
1437
+ # The whole body encodes the query (hybrid/semantic embedding) — run it
1438
+ # off the event loop so a concurrent search isn't blocked.
1439
+ def _run():
1440
  processed = process_natural_language_query(q)
1441
  search = get_search_instance()
1442
 
 
1514
  "count": len(results),
1515
  }
1516
 
1517
+ try:
1518
+ return await asyncio.to_thread(_run)
1519
+
1520
  except Exception as exc:
1521
  log_message(f"Error in natural language search: {exc}")
1522
  raise HTTPException(status_code=500, detail=str(exc))
 
1540
  language,
1541
  detail=f"No subtitle content found for {natural_key}",
1542
  )
1543
+ # analyze_content runs embedding inference — keep it off the loop.
1544
+ analysis = await asyncio.to_thread(analyze_content, text)
1545
  all_media = get_all_media(language)
1546
  media_item = all_media.get(natural_key) if all_media else None
1547
 
 
1569
  detail="Text must be at least 10 characters",
1570
  )
1571
 
1572
+ return {"analysis": await asyncio.to_thread(analyze_content, text)}
1573
 
1574
  except HTTPException:
1575
  raise
 
1584
 
1585
  try:
1586
  text = _get_video_text_or_404(natural_key, language)
1587
+ topics = await asyncio.to_thread(classify_topics, text, top_k=5)
1588
  return {
1589
  "natural_key": natural_key,
1590
  "topics": [{"topic": topic, "confidence": round(confidence, 3)} for topic, confidence in topics],
 
1603
 
1604
  try:
1605
  text = _get_video_text_or_404(natural_key, language)
1606
+ # Extractive summary embeds every sentence — minutes on a long
1607
+ # video; never on the event loop.
1608
+ summary = await asyncio.to_thread(
1609
+ generate_extractive_summary, text, num_sentences=sentences
1610
+ )
1611
  all_media = get_all_media(language)
1612
  media_item = all_media.get(natural_key) if all_media else None
1613
 
backend/search_semantic.py CHANGED
@@ -119,6 +119,41 @@ def _lookup_missing_snippets(
119
  return snippets
120
 
121
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
122
  def search_semantic(
123
  search: "SubtitleSearch",
124
  query: str,
@@ -200,6 +235,14 @@ def search_semantic(
200
  )
201
 
202
  for natural_key, distance in ad_cursor.fetchall():
 
 
 
 
 
 
 
 
203
  similarity = 1.0 - (distance / 1024.0)
204
  existing = results_dict.get(natural_key)
205
  if existing is not None and similarity <= existing[0]:
@@ -358,6 +401,48 @@ def search_hybrid(
358
  for natural_key, (score, snippet) in sorted_results[:pool_size]
359
  ]
360
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
361
  results = search._filter_excluded_media(results, language)
362
- results = search_rerank.rerank(query, results, lambda row: row[2])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
363
  return results[:limit]
 
119
  return snippets
120
 
121
 
122
+ def _lookup_concept_summaries(
123
+ conn: "sqlite3.Connection",
124
+ natural_keys: List[str],
125
+ language: str,
126
+ ) -> Dict[str, str]:
127
+ """Map snippet-less hybrid hits to their video-concept summary for display.
128
+
129
+ A hit that reached the hybrid pool only through the video-concept stream
130
+ has no chunk/FTS snippet — but the concept index's own summary says exactly
131
+ why the video matched ("what this video is about"). Without a snippet these
132
+ hits are dropped by the route layer's has_meaningful_snippet filter, so the
133
+ concept stream could re-rank existing results but never ADD one. Filling
134
+ the snippet from the summary restores that recall contribution.
135
+ """
136
+ if not natural_keys:
137
+ return {}
138
+ placeholders = ",".join("?" for _ in natural_keys)
139
+ try:
140
+ rows = conn.execute(
141
+ f"""
142
+ SELECT natural_key, summary FROM video_concepts
143
+ WHERE language = ? AND natural_key IN ({placeholders})
144
+ """,
145
+ (language, *natural_keys),
146
+ ).fetchall()
147
+ except sqlite3.Error:
148
+ # Concept tables absent on older schemas — hits stay snippet-less.
149
+ return {}
150
+ return {
151
+ natural_key: summary.strip()[:_SNIPPET_FALLBACK_CHARS]
152
+ for natural_key, summary in rows
153
+ if summary and summary.strip()
154
+ }
155
+
156
+
157
  def search_semantic(
158
  search: "SubtitleSearch",
159
  query: str,
 
235
  )
236
 
237
  for natural_key, distance in ad_cursor.fetchall():
238
+ # CAVEAT (latent — the AD index is empty in production): this
239
+ # binary-Hamming similarity (1 - d/1024, range [0,1]) is on a
240
+ # DIFFERENT scale from the chunk stream's L2-derived
241
+ # `1 - d/2`, yet they're compared in one max() below. Both land
242
+ # in [0,1] as a "fraction similar", so it ranks sanely, but
243
+ # before the AD index is ever populated the two scales must be
244
+ # validated against each other on a labeled set (do NOT change
245
+ # the chunk formula — it is golden-test-locked).
246
  similarity = 1.0 - (distance / 1024.0)
247
  existing = results_dict.get(natural_key)
248
  if existing is not None and similarity <= existing[0]:
 
401
  for natural_key, (score, snippet) in sorted_results[:pool_size]
402
  ]
403
 
404
+ # Concept-only hits arrive snippet-less and would be dropped downstream by
405
+ # has_meaningful_snippet — fill them from the video's concept summary so
406
+ # the concept stream contributes recall, not just re-ranking. RRF scores are
407
+ # untouched; the only ranking effect is when the (default-OFF) cross-encoder
408
+ # reranker is enabled, since it scores the snippet text — intended there.
409
+ blank_keys = [nk for nk, _score, snippet in results if not snippet]
410
+ if blank_keys:
411
+ fill_conn = search._get_db_connection()
412
+ try:
413
+ summary_fills = _lookup_concept_summaries(fill_conn, blank_keys, language)
414
+ finally:
415
+ fill_conn.close()
416
+ if summary_fills:
417
+ results = [
418
+ (nk, score, snippet or summary_fills.get(nk, ""))
419
+ for nk, score, snippet in results
420
+ ]
421
+
422
  results = search._filter_excluded_media(results, language)
423
+
424
+ # Q2.4: when the (default-OFF) cross-encoder reranker is on, score it on
425
+ # RICHER text — the video's concept summary ("what this video is about")
426
+ # prepended to the matched snippet — rather than the bare snippet alone.
427
+ # The 2026-06-04 investigation rejected the snippet-only reranker precisely
428
+ # because it saw only a short fragment; this is the open variant the report
429
+ # itself proposed. Summaries are fetched only when reranking is enabled, so
430
+ # the default path is unchanged. (Title is deliberately NOT added — Glenn:
431
+ # titles are often misleading; the RRF title voter handles them.)
432
+ rerank_summaries: Dict[str, str] = {}
433
+ if search_rerank.is_enabled():
434
+ rconn = search._get_db_connection()
435
+ try:
436
+ rerank_summaries = _lookup_concept_summaries(
437
+ rconn, [r[0] for r in results], language
438
+ )
439
+ finally:
440
+ rconn.close()
441
+
442
+ def _rerank_text(row: Tuple[str, float, str]) -> str:
443
+ summary = rerank_summaries.get(row[0])
444
+ snippet = row[2] or ""
445
+ return f"{summary} {snippet}".strip() if summary else snippet
446
+
447
+ results = search_rerank.rerank(query, results, _rerank_text)
448
  return results[:limit]
backend/smart_scene_fusion.py CHANGED
@@ -16,8 +16,11 @@ Two granularities, chosen by the query's wording (``classify_visual_intent``):
16
  * None -> an ordinary text query; the scene stream stays out entirely, so
17
  normal searches are never perturbed.
18
 
19
- Off by default (like the reranker and SigLIP2 visual fusion). Precedence in
20
- ``is_enabled``: a UI/runtime override wins; otherwise the env var decides. This
 
 
 
21
  mirrors ``scene_visual_fusion`` / ``search_rerank`` so it plugs into
22
  ``search_feature_flags`` and the existing settings UI.
23
  """
@@ -143,10 +146,17 @@ def set_enabled(value: bool | None) -> None:
143
 
144
 
145
  def is_enabled() -> bool:
146
- """True when scene fusion is on — runtime override wins, else the env var."""
 
 
 
 
147
  if _runtime_enabled is not None:
148
  return _runtime_enabled
149
- return os.getenv(SMART_SCENE_FUSION_ENV, "").strip().lower() in _TRUTHY
 
 
 
150
 
151
 
152
  def classify_visual_intent(query: str) -> Optional[str]:
 
16
  * None -> an ordinary text query; the scene stream stays out entirely, so
17
  normal searches are never perturbed.
18
 
19
+ ON by default since 2026-06-12 (QC'd 2026-06-04: clip results strong on
20
+ concrete visual subjects, ordinary text queries unchanged by construction —
21
+ the intent gate keeps the scene stream out of non-visual queries entirely).
22
+ Precedence in ``is_enabled``: a UI/runtime override wins; otherwise the env
23
+ var decides (set ``SEARCH_UI_SMART_SCENE_FUSION=0`` to turn it off). This
24
  mirrors ``scene_visual_fusion`` / ``search_rerank`` so it plugs into
25
  ``search_feature_flags`` and the existing settings UI.
26
  """
 
146
 
147
 
148
  def is_enabled() -> bool:
149
+ """True when scene fusion is on — runtime override wins, else the env var.
150
+
151
+ Defaults ON when the env var is unset; the per-query intent gate
152
+ (``classify_visual_intent``) still keeps ordinary text searches untouched.
153
+ """
154
  if _runtime_enabled is not None:
155
  return _runtime_enabled
156
+ raw = os.getenv(SMART_SCENE_FUSION_ENV, "").strip().lower()
157
+ if not raw:
158
+ return True
159
+ return raw in _TRUTHY
160
 
161
 
162
  def classify_visual_intent(query: str) -> Optional[str]:
backend/startup_checks.py CHANGED
@@ -61,6 +61,44 @@ def _check_sqlite_vec(data_root: str) -> str | None:
61
  return None
62
 
63
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
  # Env vars that signal the app boots off a remote/streamed data bundle (hosted),
65
  # as opposed to a local checkout with on-disk media (desktop/dev).
66
  _HOSTED_BUNDLE_ENV_VARS = (
@@ -85,14 +123,14 @@ def _directory_has_entries(path: str) -> bool:
85
 
86
 
87
  def _check_videos_cdn_consistency(config: Any) -> str | None:
88
- """Fail loud when a hosted slim bundle has no CDN base for thumbnails.
89
 
90
  A hosted deploy that streams a *slim* bundle has no ``videos/`` on disk, so
91
- every result thumbnail must be served from the CDN. If
92
- ``SEARCH_UI_VIDEOS_ASSET_BASE_URL`` is unset in that situation, every tile
93
- 404s — the exact "shipped heavy / forgot the CDN" mistake. Surface it as a
94
- startup error so the misconfiguration can't deploy looking healthy, instead
95
- of silently serving broken images.
96
  """
97
  hosted = any(os.getenv(name, "").strip() for name in _HOSTED_BUNDLE_ENV_VARS)
98
  if not hosted:
@@ -100,14 +138,19 @@ def _check_videos_cdn_consistency(config: Any) -> str | None:
100
 
101
  from asset_urls import is_videos_cdn_enabled
102
 
103
- if _directory_has_entries(config.videos_dir) or is_videos_cdn_enabled():
 
 
 
 
104
  return None
105
 
106
  return (
107
  "Hosted data bundle is configured with no local videos/ on disk and "
108
- "SEARCH_UI_VIDEOS_ASSET_BASE_URL is unset — result thumbnails would 404. "
109
- "Set SEARCH_UI_VIDEOS_ASSET_BASE_URL to the dataset CDN videos base "
110
- "(e.g. https://huggingface.co/datasets/<org>/<repo>/resolve/main/videos)."
 
111
  )
112
 
113
 
@@ -115,6 +158,8 @@ def _append_base_checks(report: StartupReport, config: Any) -> None:
115
  if not getattr(config, "startup_checks_enabled", True):
116
  return
117
 
 
 
118
  for directory in (
119
  config.data_root,
120
  getattr(config, "db_dir", config.data_root),
@@ -140,6 +185,24 @@ def _append_base_checks(report: StartupReport, config: Any) -> None:
140
  if getattr(config, "startup_check_frontend", False) and config.frontend_dist is None:
141
  report.warnings.append("Frontend dist bundle not found; API-only mode is active.")
142
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
143
  cdn_error = _check_videos_cdn_consistency(config)
144
  if cdn_error:
145
  report.errors.append(cdn_error)
@@ -164,6 +227,25 @@ def run_preflight_checks(config: Any) -> StartupReport:
164
  return _finalize_report(report, strict_startup=getattr(config, "strict_startup", True))
165
 
166
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
167
  def append_runtime_warnings(report: StartupReport, runtime: AppRuntime) -> StartupReport:
168
  """Add runtime-dependent warnings after services have been constructed."""
169
  if runtime.services.speaker_recognition is None:
@@ -173,6 +255,22 @@ def append_runtime_warnings(report: StartupReport, runtime: AppRuntime) -> Start
173
  if warning not in report.warnings:
174
  report.warnings.append(warning)
175
  log_message(f"[startup] WARNING: {warning}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
176
  return report
177
 
178
 
 
61
  return None
62
 
63
 
64
+ # The five data DBs that the merge tool consolidates into one. Each is located
65
+ # by its own env var; a plain restart sets NONE (→ 5-DB mode) and the launcher
66
+ # sets ALL (→ merged mode). Setting only SOME runs a half-merged process whose
67
+ # writes/reads split across files — the documented silent-drift hazard.
68
+ _MERGEABLE_DB_ENV_VARS = (
69
+ "SEARCH_UI_SEARCH_DB_PATH",
70
+ "SEARCH_UI_IMAGE_DB_PATH",
71
+ "SEARCH_UI_FACE_DB_PATH",
72
+ "SEARCH_UI_SPEAKER_DB_PATH",
73
+ "SEARCH_UI_PUBLICATIONS_DB_PATH",
74
+ )
75
+
76
+
77
+ def _check_db_path_consistency(report: StartupReport) -> None:
78
+ """Warn loudly on a partial (half-merged) DB-path configuration."""
79
+ set_vars = [name for name in _MERGEABLE_DB_ENV_VARS if os.environ.get(name)]
80
+ n = len(set_vars)
81
+ if n == 0:
82
+ log_message("[startup] DB mode: 5 separate source databases (default).")
83
+ return
84
+ if n == len(_MERGEABLE_DB_ENV_VARS):
85
+ unique = {os.path.abspath(os.environ[name]) for name in _MERGEABLE_DB_ENV_VARS}
86
+ if len(unique) == 1:
87
+ log_message(f"[startup] DB mode: single merged database ({next(iter(unique))}).")
88
+ else:
89
+ log_message(f"[startup] DB mode: {len(unique)} explicitly-configured databases.")
90
+ return
91
+ missing = [name for name in _MERGEABLE_DB_ENV_VARS if name not in set_vars]
92
+ report.warnings.append(
93
+ "Partial database configuration: "
94
+ f"{n}/{len(_MERGEABLE_DB_ENV_VARS)} DB-path env vars are set "
95
+ f"({', '.join(set_vars)}); unset: {', '.join(missing)}. The process is "
96
+ "half-merged — some reads/writes hit the merged DB and others the "
97
+ "separate source DBs, which silently loses data. Set all of them (use "
98
+ "scripts/run-backend-merged.sh) or none."
99
+ )
100
+
101
+
102
  # Env vars that signal the app boots off a remote/streamed data bundle (hosted),
103
  # as opposed to a local checkout with on-disk media (desktop/dev).
104
  _HOSTED_BUNDLE_ENV_VARS = (
 
123
 
124
 
125
  def _check_videos_cdn_consistency(config: Any) -> str | None:
126
+ """Fail loud when a hosted slim bundle has no way to serve thumbnails.
127
 
128
  A hosted deploy that streams a *slim* bundle has no ``videos/`` on disk, so
129
+ result thumbnails must come from either the CDN
130
+ (``SEARCH_UI_VIDEOS_ASSET_BASE_URL``) or the local blob shards
131
+ (``SEARCH_UI_THUMBNAIL_SHARD_DIR``, see thumbnail_shards.py). If neither is
132
+ configured, every tile 404s — the "shipped heavy / forgot the thumbnails"
133
+ mistake. Surface it as a startup error so it can't deploy looking healthy.
134
  """
135
  hosted = any(os.getenv(name, "").strip() for name in _HOSTED_BUNDLE_ENV_VARS)
136
  if not hosted:
 
138
 
139
  from asset_urls import is_videos_cdn_enabled
140
 
141
+ if (
142
+ _directory_has_entries(config.videos_dir)
143
+ or is_videos_cdn_enabled()
144
+ or os.getenv("SEARCH_UI_THUMBNAIL_SHARD_DIR", "").strip()
145
+ ):
146
  return None
147
 
148
  return (
149
  "Hosted data bundle is configured with no local videos/ on disk and "
150
+ "neither SEARCH_UI_VIDEOS_ASSET_BASE_URL nor SEARCH_UI_THUMBNAIL_SHARD_DIR "
151
+ "is set — result thumbnails would 404. Set the CDN videos base "
152
+ "(https://huggingface.co/datasets/<org>/<repo>/resolve/main/videos) or "
153
+ "the thumbnail-shard dir."
154
  )
155
 
156
 
 
158
  if not getattr(config, "startup_checks_enabled", True):
159
  return
160
 
161
+ _check_db_path_consistency(report)
162
+
163
  for directory in (
164
  config.data_root,
165
  getattr(config, "db_dir", config.data_root),
 
185
  if getattr(config, "startup_check_frontend", False) and config.frontend_dist is None:
186
  report.warnings.append("Frontend dist bundle not found; API-only mode is active.")
187
 
188
+ # A hosted (public) deployment must not run on the repo's default password,
189
+ # which is committed in this public repo and would leave the Space open.
190
+ if getattr(config, "hosted_mode", False):
191
+ from auth import is_auth_enabled, is_using_default_password
192
+
193
+ if not is_auth_enabled():
194
+ report.errors.append(
195
+ "Hosted mode is enabled but the password gate is DISABLED "
196
+ "(SEARCH_UI_APP_PASSWORD is empty), so the Space would be open "
197
+ "to anyone. Set SEARCH_UI_APP_PASSWORD to a non-empty secret."
198
+ )
199
+ elif is_using_default_password():
200
+ report.errors.append(
201
+ "Hosted mode is enabled but no SEARCH_UI_APP_PASSWORD is set, so "
202
+ "the public default password is in use — the Space would be open "
203
+ "to anyone. Set SEARCH_UI_APP_PASSWORD as a Space secret."
204
+ )
205
+
206
  cdn_error = _check_videos_cdn_consistency(config)
207
  if cdn_error:
208
  report.errors.append(cdn_error)
 
227
  return _finalize_report(report, strict_startup=getattr(config, "strict_startup", True))
228
 
229
 
230
+ def _count_indexed_subtitles(search_service: Any) -> int | None:
231
+ """Best-effort row count of the subtitle text index, or None if unknown."""
232
+ try:
233
+ conn = search_service._get_db_connection()
234
+ except Exception: # noqa: BLE001 - service/DB not ready; treat as unknown
235
+ return None
236
+ try:
237
+ for table in ("subtitle_embedding_status", "subtitles_fts"):
238
+ try:
239
+ row = conn.execute(f"SELECT COUNT(*) FROM {table}").fetchone()
240
+ if row is not None:
241
+ return int(row[0])
242
+ except Exception: # noqa: BLE001 - table absent in this layout
243
+ continue
244
+ return None
245
+ finally:
246
+ conn.close()
247
+
248
+
249
  def append_runtime_warnings(report: StartupReport, runtime: AppRuntime) -> StartupReport:
250
  """Add runtime-dependent warnings after services have been constructed."""
251
  if runtime.services.speaker_recognition is None:
 
255
  if warning not in report.warnings:
256
  report.warnings.append(warning)
257
  log_message(f"[startup] WARNING: {warning}")
258
+
259
+ # Fail loud, not silent: a hosted Space whose data bundle failed to
260
+ # download/extract boots green but every search returns nothing. Surface an
261
+ # empty index as a visible warning (in logs and /api/health) rather than
262
+ # letting it look like "no results for your query".
263
+ if getattr(runtime.config, "hosted_mode", False):
264
+ indexed = _count_indexed_subtitles(runtime.services.search)
265
+ if indexed == 0:
266
+ warning = (
267
+ "Search index is EMPTY (0 indexed subtitles). The data bundle "
268
+ "likely failed to download/extract — every search will return "
269
+ "nothing. Check the data-bundle env vars and the cold-start logs."
270
+ )
271
+ if warning not in report.warnings:
272
+ report.warnings.append(warning)
273
+ log_message(f"[startup] WARNING: {warning}")
274
  return report
275
 
276
 
backend/task_manager.py CHANGED
@@ -24,9 +24,44 @@ class TaskManager:
24
  self.subscribers = []
25
  self.completion_time = None
26
  self.background_task = None
 
 
 
 
 
 
27
  self.last_updated_file = last_updated_file
28
  self._load_last_updated()
29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
  def _load_last_updated(self):
31
  """Load last updated timestamps from file."""
32
  self.last_updated = {}
@@ -78,11 +113,7 @@ class TaskManager:
78
  """Update progress and broadcast to all subscribers."""
79
  if self.current_task:
80
  self.current_task["progress"] = progress
81
- for queue in self.subscribers:
82
- try:
83
- queue.put_nowait(progress)
84
- except asyncio.QueueFull:
85
- log_message(f"Progress queue full for {self.current_task['id']}", "DEBUG")
86
 
87
  def complete_task(self, result: dict[str, Any] | None = None):
88
  """Mark task as complete."""
@@ -102,12 +133,7 @@ class TaskManager:
102
  languages_to_mark = processed_languages
103
  for language in languages_to_mark:
104
  self.set_language_updated(language)
105
- completion_msg = {"type": "complete", "results": result}
106
- for queue in self.subscribers:
107
- try:
108
- queue.put_nowait(completion_msg)
109
- except asyncio.QueueFull:
110
- log_message(f"Completion queue full for {self.current_task['id']}", "DEBUG")
111
  log_message(f"Task {self.current_task['id']} completed")
112
 
113
  def fail_task(self, error: str):
@@ -117,12 +143,7 @@ class TaskManager:
117
  self.current_task["result"] = {"error": error}
118
  self.current_task["cancel_requested"] = False
119
  self.completion_time = datetime.now()
120
- error_msg = {"type": "error", "message": error}
121
- for queue in self.subscribers:
122
- try:
123
- queue.put_nowait(error_msg)
124
- except asyncio.QueueFull:
125
- log_message(f"Error queue full for {self.current_task['id']}", "DEBUG")
126
  log_message(f"Task {self.current_task['id']} failed: {error}")
127
 
128
  def cancel_task(self):
@@ -146,18 +167,14 @@ class TaskManager:
146
  self.current_task["result"]["stopped"] = True
147
  self.current_task["cancel_requested"] = False
148
  self.completion_time = datetime.now()
149
- stop_msg = {"type": "stopped", "results": self.current_task["result"]}
150
- for queue in self.subscribers:
151
- try:
152
- queue.put_nowait(stop_msg)
153
- except asyncio.QueueFull:
154
- log_message(f"Stop queue full for {self.current_task['id']}", "DEBUG")
155
  log_message(
156
  f"Task {self.current_task['id']} stopped gracefully with partial results: {results}"
157
  )
158
 
159
  def subscribe(self) -> asyncio.Queue:
160
  """Subscribe to progress updates. Returns a queue."""
 
161
  queue = asyncio.Queue(maxsize=100)
162
  self.subscribers.append(queue)
163
  return queue
@@ -194,6 +211,7 @@ class TaskManager:
194
  def run_in_background(self, coro):
195
  """Run a coroutine as a background task."""
196
  log_message("[TaskManager] Creating background task...")
 
197
  self.background_task = asyncio.create_task(coro)
198
 
199
  def task_done_callback(task):
 
24
  self.subscribers = []
25
  self.completion_time = None
26
  self.background_task = None
27
+ # Event loop that owns the subscriber queues. Progress callbacks fire
28
+ # from run_in_executor worker threads (publication/web-image ingest),
29
+ # and asyncio.Queue is NOT thread-safe — so every broadcast is marshalled
30
+ # back onto this loop via call_soon_threadsafe. Captured when the loop is
31
+ # known (subscribe / run_in_background, both called on the loop).
32
+ self._loop: asyncio.AbstractEventLoop | None = None
33
  self.last_updated_file = last_updated_file
34
  self._load_last_updated()
35
 
36
+ def _capture_loop(self) -> None:
37
+ """Record the running event loop (call only from the loop thread)."""
38
+ try:
39
+ self._loop = asyncio.get_running_loop()
40
+ except RuntimeError:
41
+ # No running loop (e.g. synchronous unit test) — best-effort.
42
+ self._loop = None
43
+
44
+ def _safe_put(self, queue: "asyncio.Queue", message: Any) -> None:
45
+ try:
46
+ queue.put_nowait(message)
47
+ except asyncio.QueueFull:
48
+ task_id = self.current_task["id"] if self.current_task else "?"
49
+ log_message(f"Progress queue full for {task_id}", "DEBUG")
50
+
51
+ def _broadcast(self, message: Any) -> None:
52
+ """Deliver a message to every subscriber, thread-safely.
53
+
54
+ Safe to call from any thread: when a loop is captured and running the
55
+ put is scheduled on it (asyncio.Queue is not thread-safe); otherwise it
56
+ falls back to a direct put on the current thread.
57
+ """
58
+ loop = self._loop
59
+ for queue in list(self.subscribers):
60
+ if loop is not None and loop.is_running():
61
+ loop.call_soon_threadsafe(self._safe_put, queue, message)
62
+ else:
63
+ self._safe_put(queue, message)
64
+
65
  def _load_last_updated(self):
66
  """Load last updated timestamps from file."""
67
  self.last_updated = {}
 
113
  """Update progress and broadcast to all subscribers."""
114
  if self.current_task:
115
  self.current_task["progress"] = progress
116
+ self._broadcast(progress)
 
 
 
 
117
 
118
  def complete_task(self, result: dict[str, Any] | None = None):
119
  """Mark task as complete."""
 
133
  languages_to_mark = processed_languages
134
  for language in languages_to_mark:
135
  self.set_language_updated(language)
136
+ self._broadcast({"type": "complete", "results": result})
 
 
 
 
 
137
  log_message(f"Task {self.current_task['id']} completed")
138
 
139
  def fail_task(self, error: str):
 
143
  self.current_task["result"] = {"error": error}
144
  self.current_task["cancel_requested"] = False
145
  self.completion_time = datetime.now()
146
+ self._broadcast({"type": "error", "message": error})
 
 
 
 
 
147
  log_message(f"Task {self.current_task['id']} failed: {error}")
148
 
149
  def cancel_task(self):
 
167
  self.current_task["result"]["stopped"] = True
168
  self.current_task["cancel_requested"] = False
169
  self.completion_time = datetime.now()
170
+ self._broadcast({"type": "stopped", "results": self.current_task["result"]})
 
 
 
 
 
171
  log_message(
172
  f"Task {self.current_task['id']} stopped gracefully with partial results: {results}"
173
  )
174
 
175
  def subscribe(self) -> asyncio.Queue:
176
  """Subscribe to progress updates. Returns a queue."""
177
+ self._capture_loop()
178
  queue = asyncio.Queue(maxsize=100)
179
  self.subscribers.append(queue)
180
  return queue
 
211
  def run_in_background(self, coro):
212
  """Run a coroutine as a background task."""
213
  log_message("[TaskManager] Creating background task...")
214
+ self._capture_loop()
215
  self.background_task = asyncio.create_task(coro)
216
 
217
  def task_done_callback(task):
backend/thumbnail_shards.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Serve thumbnails from a few large SQLite blob shards instead of millions of
2
+ loose files.
3
+
4
+ Why: the hosted Space's cold start is dominated by *writing ~2.5M tiny
5
+ thumbnail files* to ephemeral disk (per-file filesystem overhead), not by
6
+ download bandwidth — the same file-count problem that stalled the bucket-mount
7
+ test. Packing the thumbnails into a handful of SQLite blob files (path -> bytes)
8
+ turns extraction into a few big sequential writes, cutting cold start from
9
+ ~45 min to minutes.
10
+
11
+ This module is the READ side: a ``ShardReader`` looks a thumbnail up by its
12
+ path relative to the mount root. ``ShardStaticFiles`` wires it into the
13
+ existing ``/videos`` and ``/publications`` mounts as a FALLBACK — a loose file
14
+ on disk still wins, so local (full-data) mode is byte-for-byte unchanged; the
15
+ shard is consulted only when the loose file is absent (the hosted case).
16
+
17
+ Build the shards with ``scripts/build_thumbnail_shards.py``. Wire them in by
18
+ setting ``SEARCH_UI_THUMBNAIL_SHARD_DIR`` to a directory holding ``videos.db``
19
+ and/or ``publications.db``.
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import mimetypes
25
+ import os
26
+ import threading
27
+ from typing import Optional
28
+
29
+ from db_utils import connect_sqlite
30
+ from utils import log_message
31
+
32
+ SHARD_DIR_ENV = "SEARCH_UI_THUMBNAIL_SHARD_DIR"
33
+ # Schema shared by the builder and reader.
34
+ SHARD_TABLE = "thumbnails"
35
+ SHARD_SCHEMA = (
36
+ f"CREATE TABLE IF NOT EXISTS {SHARD_TABLE} "
37
+ "(path TEXT PRIMARY KEY, bytes BLOB NOT NULL)"
38
+ )
39
+
40
+
41
+ class ShardReader:
42
+ """Read-only lookup of thumbnail bytes by relative path from a blob shard.
43
+
44
+ SQLite connections are not shareable across threads, and StaticFiles serves
45
+ from a threadpool, so connections are cached per-thread.
46
+ """
47
+
48
+ def __init__(self, db_path: str):
49
+ self.db_path = db_path
50
+ self._local = threading.local()
51
+
52
+ def _conn(self):
53
+ conn = getattr(self._local, "conn", None)
54
+ if conn is None:
55
+ # Read-only URI: never create or write the shard from the serve path.
56
+ conn = connect_sqlite(
57
+ f"file:{os.path.abspath(self.db_path)}?mode=ro",
58
+ uri=True,
59
+ foreign_keys=False,
60
+ )
61
+ self._local.conn = conn
62
+ return conn
63
+
64
+ def get(self, rel_path: str) -> Optional[bytes]:
65
+ """Return the stored bytes for ``rel_path`` (normalized), or None."""
66
+ key = rel_path.lstrip("/")
67
+ try:
68
+ row = self._conn().execute(
69
+ f"SELECT bytes FROM {SHARD_TABLE} WHERE path = ?", (key,)
70
+ ).fetchone()
71
+ except Exception as exc: # noqa: BLE001 - a bad shard must not 500 serving
72
+ log_message(f"Thumbnail shard read failed for {key!r}: {exc}", "WARNING")
73
+ return None
74
+ return bytes(row[0]) if row else None
75
+
76
+
77
+ def open_shard_readers(shard_dir: str | None = None) -> dict[str, ShardReader]:
78
+ """Return ``{mount_name: ShardReader}`` for shard DBs found in the dir.
79
+
80
+ Looks for ``videos.db`` and ``publications.db`` (matching the mount names).
81
+ Returns an empty dict when the dir is unset/absent — i.e. local mode keeps
82
+ serving loose files with no shard involvement.
83
+ """
84
+ shard_dir = shard_dir or os.environ.get(SHARD_DIR_ENV)
85
+ if not shard_dir or not os.path.isdir(shard_dir):
86
+ return {}
87
+ readers: dict[str, ShardReader] = {}
88
+ for mount in ("videos", "publications"):
89
+ candidate = os.path.join(shard_dir, f"{mount}.db")
90
+ if os.path.isfile(candidate):
91
+ readers[mount] = ShardReader(candidate)
92
+ log_message(f"Thumbnail shard enabled for /{mount}: {candidate}")
93
+ return readers
94
+
95
+
96
+ def guess_content_type(path: str) -> str:
97
+ ctype, _ = mimetypes.guess_type(path)
98
+ return ctype or "application/octet-stream"
backend/validation.py CHANGED
@@ -43,21 +43,32 @@ def validate_natural_key(natural_key: str) -> str:
43
  def sanitize_fts_query(query: str) -> str:
44
  """Convert free-text user input into a safe FTS5 MATCH expression.
45
 
46
- Extracts word-character tokens from ``query`` (dropping quotes,
47
- punctuation, and FTS5 operator chars like ``*`` / ``(`` / ``"``)
48
- and wraps each token in double quotes so FTS5 treats them as
49
- literal phrases. The resulting expression matches all tokens
50
- via the FTS5 implicit-AND.
 
 
51
 
52
  Returns an empty string for queries that contain no usable tokens,
53
  so callers can short-circuit before issuing the MATCH.
54
  """
55
  if not query:
56
  return ""
57
- tokens = re.findall(r"\w+", query, flags=re.UNICODE)
58
- if not tokens:
59
- return ""
60
- return " ".join(f'"{token}"' for token in tokens)
 
 
 
 
 
 
 
 
 
61
 
62
 
63
  def resolve_under(root: str, *parts: str) -> str:
 
43
  def sanitize_fts_query(query: str) -> str:
44
  """Convert free-text user input into a safe FTS5 MATCH expression.
45
 
46
+ A balanced double-quoted span in the user's input is preserved as an FTS5
47
+ PHRASE (its words must appear adjacently, in order) — so ``"new world
48
+ translation"`` searches for the phrase, not three AND-ed words scattered
49
+ across the document. Unquoted text keeps the previous behaviour: each
50
+ word-token is quoted individually and AND-ed together. Either way every
51
+ token is double-quoted so FTS5 treats it as a literal, never an operator
52
+ (``*`` / ``(`` / ``OR`` / ``NEAR`` are inert).
53
 
54
  Returns an empty string for queries that contain no usable tokens,
55
  so callers can short-circuit before issuing the MATCH.
56
  """
57
  if not query:
58
  return ""
59
+
60
+ parts: list[str] = []
61
+ # Balanced double-quoted spans become FTS5 phrase queries.
62
+ for match in re.finditer(r'"([^"]+)"', query):
63
+ phrase_tokens = re.findall(r"\w+", match.group(1), flags=re.UNICODE)
64
+ if phrase_tokens:
65
+ parts.append('"' + " ".join(phrase_tokens) + '"')
66
+ # Everything outside the quoted spans → individual AND-ed literal tokens.
67
+ remainder = re.sub(r'"[^"]+"', " ", query)
68
+ for token in re.findall(r"\w+", remainder, flags=re.UNICODE):
69
+ parts.append(f'"{token}"')
70
+
71
+ return " ".join(parts)
72
 
73
 
74
  def resolve_under(root: str, *parts: str) -> str:
deploy/huggingface/DEPLOY_REFACTOR.md ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Deploying the Refactor (v2) to the Hugging Face Space
2
+
3
+ Ordered checklist for pushing branch `claude/refactor-v2-round1` to the Space.
4
+ Run on the **data machine** (where the real DBs + thumbnails + VTTs live).
5
+
6
+ ## ⚠️ Two things that WILL bite if skipped
7
+
8
+ 1. **Set a non-default `SEARCH_UI_APP_PASSWORD` Space secret.** Hosted mode now
9
+ **refuses to boot** on the repo's default password `"JWSearch"` (security
10
+ hardening S1.7 — the default is public in the repo). Pick a real password
11
+ and set it as a Space secret, or the container will fail startup.
12
+ 2. **Rotate the secrets that were shared in chat** (HF token, OpenRouter key)
13
+ after deploying — they are exposed in the session transcript. Set the fresh
14
+ OpenRouter key (if used) as the `OPENROUTER_API_KEY` Space secret.
15
+
16
+ ## 1. Build the thumbnail shards (cold-start fix, S2.1)
17
+
18
+ ```bash
19
+ python scripts/build_thumbnail_shards.py --root backend/videos \
20
+ --output dist-shards/videos.db \
21
+ --include "*/thumbnails/*.jpg" --include "*/thumbnails-small/*.jpg"
22
+ python scripts/build_thumbnail_shards.py --root backend/publications \
23
+ --output dist-shards/publications.db
24
+ ```
25
+
26
+ ## 1b. Rebuild the keyword index with porter stemming (Q2.1)
27
+
28
+ The shipped `database.db` was built before porter stemming. Rebuild its FTS
29
+ in place (fast — reads content back, no re-embedding) so "preach" matches
30
+ "preaching" etc.:
31
+
32
+ ```bash
33
+ SEARCH_UI_SEARCH_DB_PATH=<bundle>/database.db python backend/cli.py reindex fts
34
+ ```
35
+
36
+ Validated on the real corpus: topical precision@10 0.214 → 0.286 (+34%), no
37
+ meaningful regression. (A fresh DB already gets porter; this is only for the
38
+ existing bundle DB.)
39
+
40
+ ## 1c. Backfill chunk timestamps (Q2.2 — exact jump-to-moment)
41
+
42
+ With the VTTs present in the bundle's `subtitles/<lang>/`, attach start/end
43
+ times to the subtitle chunks (no re-embed; locatable chunks only):
44
+
45
+ ```bash
46
+ SEARCH_UI_SEARCH_DB_PATH=<bundle>/database.db \
47
+ SEARCH_UI_DATA_ROOT=<bundle> python backend/cli.py backfill chunk-timestamps --language E
48
+ ```
49
+
50
+ On the real corpus this timed ~2,114 videos / ~14,645 chunks. Semantic hits
51
+ then seek to the exact stored moment instead of re-parsing the VTT per result.
52
+
53
+ ## 2. Build the slim bundle (DBs + json + subtitles + shards, NOT loose thumbs)
54
+
55
+ Reuse the existing split-parts bundle flow but include `dist-shards/` and
56
+ exclude the loose `videos/*/thumbnails*` and `publications/image_*` trees.
57
+ Re-split into ~1 GB parts, upload to the `jw-tools/jw-search-data` dataset,
58
+ refresh `parts/manifest.json`.
59
+
60
+ ## 3. Space environment variables / secrets
61
+
62
+ | Var | Value | Why |
63
+ |---|---|---|
64
+ | `SEARCH_UI_HOSTED_MODE` | `true` | already in the Dockerfile; ingestion routers off |
65
+ | `SEARCH_UI_APP_PASSWORD` | **(a real, non-default secret)** | **required — boot fails on "JWSearch"** |
66
+ | `SEARCH_UI_THUMBNAIL_SHARD_DIR` | dir holding `videos.db`/`publications.db` | serve thumbnails from shards |
67
+ | `SEARCH_UI_DATA_BUNDLE_PARTS_MANIFEST_URL` | slim bundle manifest | data source |
68
+ | `SEARCH_UI_FORCE_DATA_BUNDLE` | `1` for the cutover, then remove | re-extract the new bundle |
69
+ | `OPENROUTER_API_KEY` | (optional, fresh key) | enables the LLM router + Q1.7 expanded-terms; unset = rule-based |
70
+ | `SEARCH_UI_SEARCH_LOG` | unset (on) or `0` | search analytics logger |
71
+ | `SEARCH_UI_AUTH_SECRET` | (optional) | rotate to invalidate all sessions |
72
+
73
+ ## 4. Verify after restart
74
+
75
+ ```bash
76
+ curl -s https://jw-tools-jw-search.hf.space/api/health # {"ok":true}
77
+ # then, logged in (password), confirm:
78
+ # /api/search?q=hope&method=keyword&limit=1 -> real result
79
+ # /api/smart-search?q=Governing%20Body%20Update -> GB-Update video ranked #1 (title voter)
80
+ # ingestion routes are gone: /api/sync-all -> 404
81
+ # /api/search-log/stats -> analytics populating as users search
82
+ ```
83
+
84
+ Cold start should drop from ~45 min to a few minutes (shards). The search
85
+ logger captures every query; pull `/api/search-log/export` periodically (the
86
+ Space disk is ephemeral) to keep durable history.
87
+
88
+ ## What's NOT in this deploy (separate, data-machine work)
89
+
90
+ - **Q2 reindex** (FTS title column + porter stemming, stored chunk timestamps,
91
+ two-stage visual) — a schema change + full reindex, gated on a before/after
92
+ eval. Bundle it into a *future* redeploy once validated on the data machine.
deploy/huggingface/README.md CHANGED
@@ -6,6 +6,25 @@ search-focused; video processing, OCR, Whisper transcription, and new face
6
  embedding generation should still run in the local processing workflow
7
  that produces the data bundle.
8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  ## Data Shape
10
 
11
  Use the existing compact data bundle workflow:
@@ -91,6 +110,28 @@ On Hugging Face, the entrypoint starts a tiny placeholder web server before
91
  extracting data so the Space becomes healthy while the first cold-start
92
  download runs. Set `SEARCH_UI_STARTUP_PLACEHOLDER=0` to disable that behavior.
93
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94
  ## Updating Data
95
 
96
  When replacing the data bundle, either clear the Space storage or set:
 
6
  embedding generation should still run in the local processing workflow
7
  that produces the data bundle.
8
 
9
+ ## Deploy styles: local (full app) vs hosted (search-only)
10
+
11
+ These are two deliberately different deployments of the same codebase:
12
+
13
+ | | Local (the processing machine) | Hosted (this Space) |
14
+ |---|---|---|
15
+ | Purpose | Produce the data: sync new videos, process, index | Serve search to users |
16
+ | Data | Live DBs, source videos, subtitles | Prebuilt bundle, re-extracted on cold start |
17
+ | Sync & People pages | Used here | Hidden (web build never shows them) |
18
+ | Ingest/admin API (sync-all, download/process video, AD transcription, web-image crawl) | Mounted | **Not mounted** — `SEARCH_UI_HOSTED_MODE=true` (set in the Dockerfile) |
19
+
20
+ The workflow is: sync/index on the local machine → rebuild the data bundle →
21
+ upload it to the dataset repo → restart the Space.
22
+
23
+ History note: before 2026-06-12 only the *UI* hid the admin features on the
24
+ Space — the API endpoints were still mounted and callable. `SEARCH_UI_HOSTED_MODE`
25
+ now enforces search-only serving at the server, so a long download/ML job can
26
+ never run inside (and freeze) the serving container.
27
+
28
  ## Data Shape
29
 
30
  Use the existing compact data bundle workflow:
 
110
  extracting data so the Space becomes healthy while the first cold-start
111
  download runs. Set `SEARCH_UI_STARTUP_PLACEHOLDER=0` to disable that behavior.
112
 
113
+ ## Thumbnail shards (fast cold start)
114
+
115
+ The cold start is dominated by writing ~2.5M tiny thumbnail files, not by
116
+ download size. Pack them into a few large SQLite blob shards so extraction is a
117
+ handful of big sequential writes instead.
118
+
119
+ On the data-producing machine:
120
+
121
+ ```bash
122
+ python scripts/build_thumbnail_shards.py --root backend/videos \
123
+ --output dist-shards/videos.db \
124
+ --include "*/thumbnails/*.jpg" --include "*/thumbnails-small/*.jpg"
125
+ python scripts/build_thumbnail_shards.py --root backend/publications \
126
+ --output dist-shards/publications.db
127
+ ```
128
+
129
+ Ship `videos.db` / `publications.db` in the bundle (instead of the loose
130
+ thumbnails) and set `SEARCH_UI_THUMBNAIL_SHARD_DIR` to the directory holding
131
+ them. The backend serves `/videos/...` and `/publications/...` from the shards
132
+ when the loose file is absent; with no shard dir set it serves loose files as
133
+ before (local mode unchanged). See `backend/thumbnail_shards.py`.
134
+
135
  ## Updating Data
136
 
137
  When replacing the data bundle, either clear the Space storage or set:
deploy/huggingface/SLIM_BUNDLE_PLAN.md CHANGED
@@ -28,7 +28,29 @@ extracted and models loaded → **no cold start for users**, $0. This is the
28
  immediate mitigation. (Caveat: a rare HF-initiated restart still triggers one
29
  cold start; Part B makes that fast.)
30
 
31
- ### Part B — Slim the runtime bundle to DB-only; serve media from the dataset CDN
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
 
33
  The Space only needs the **databases** (+ models) to start serving search. The
34
  image/thumbnail files only need to be *reachable* when a user views a result —
 
28
  immediate mitigation. (Caveat: a rare HF-initiated restart still triggers one
29
  cold start; Part B makes that fast.)
30
 
31
+ > **2026-06-12 status update — Part B as written is BLOCKED.** Publishing the
32
+ > media as *individual files* to the dataset repo hit Hugging Face's
33
+ > file-count/upload limits (the same class of problem as the 2026-05-28
34
+ > bucket-mount test, which stalled at ~140k of ~2.5M files). HF repos are not
35
+ > built for hundreds of thousands of tiny files, whether mounted or uploaded.
36
+ >
37
+ > **Revised direction: pack the thumbnails into a few large shard files**
38
+ > instead of publishing them individually:
39
+ > - Pack `thumbnails-preview`/publication previews into SQLite blob shards
40
+ > (e.g. 2–8 `thumbs-NNN.db` files keyed by path) or indexed tar shards.
41
+ > - Serve them from the backend via a small read-only lookup route (the
42
+ > frontend keeps its existing `/videos/...`/`/publications/...` URLs; the
43
+ > route falls back to the filesystem when a shard is absent, so local mode
44
+ > is unchanged).
45
+ > - The runtime bundle then becomes DBs + json + subtitles + a handful of
46
+ > shard files — a few big sequential downloads/writes instead of ~2.5M tiny
47
+ > file writes. That file-write storm, not download bandwidth, dominates the
48
+ > measured 43–46 min cold start, so the cold-start win is roughly the same
49
+ > as the original CDN plan without fighting HF's file limits.
50
+ > - The `SEARCH_UI_PUBLICATIONS_ASSET_BASE_URL` CDN hook stays merged and
51
+ > dormant — still useful if a true CDN host appears later.
52
+
53
+ ### Part B (original write-up, kept for reference) — Slim the runtime bundle to DB-only; serve media from the dataset CDN
54
 
55
  The Space only needs the **databases** (+ models) to start serving search. The
56
  image/thumbnail files only need to be *reachable* when a user views a result —
frontend/src/DownloadPage.jsx CHANGED
@@ -346,10 +346,23 @@ function DownloadPage() {
346
  // Ref to track polling interval for cleanup on unmount
347
  const pubPollRef = useRef(null)
348
 
349
- // Cleanup polling on unmount
 
 
350
  useEffect(() => {
351
  return () => {
352
  if (pubPollRef.current) clearInterval(pubPollRef.current)
 
 
 
 
 
 
 
 
 
 
 
353
  }
354
  }, [])
355
 
 
346
  // Ref to track polling interval for cleanup on unmount
347
  const pubPollRef = useRef(null)
348
 
349
+ // Cleanup polling AND any open SSE streams on unmount. Navigating away
350
+ // mid-task otherwise leaks hours-long EventSource connections that keep
351
+ // parsing messages into a dead closure (and StrictMode double-mounts them).
352
  useEffect(() => {
353
  return () => {
354
  if (pubPollRef.current) clearInterval(pubPollRef.current)
355
+ for (const ref of [
356
+ batchEventSourceRef,
357
+ updateEventSourceRef,
358
+ reprocessEventSourceRef,
359
+ nuclearEventSourceRef,
360
+ ]) {
361
+ if (ref.current) {
362
+ try { ref.current.close() } catch { /* already closed */ }
363
+ ref.current = null
364
+ }
365
+ }
366
  }
367
  }, [])
368
 
frontend/src/SearchPage.jsx CHANGED
@@ -73,6 +73,10 @@ function SearchPage({
73
  const [showSubtitlesModal, setShowSubtitlesModal] = useState(false);
74
  const AVAILABLE_LANGUAGES = languages;
75
  const videoRef = useRef(null);
 
 
 
 
76
 
77
  const {
78
  persons,
@@ -207,6 +211,8 @@ function SearchPage({
207
  return;
208
  }
209
 
 
 
210
  setLoading(true);
211
  setError(null);
212
  setNotice(null);
@@ -221,7 +227,9 @@ function SearchPage({
221
  searchMethod,
222
  });
223
  const response = await fetchWithRetry(endpoint);
 
224
  const data = await readJson(response);
 
225
  // The index may be absent/empty until the build machine finishes.
226
  // That's informational, not an error.
227
  if (data.available === false) {
@@ -231,6 +239,7 @@ function SearchPage({
231
  }
232
  setSearchResults(data.results || []);
233
  } catch (err) {
 
234
  logApiFailure('narrative-search', err, { query: searchQuery, method: searchMethod });
235
  // 401 → AuthGate is showing login; stay silent. A real cold start →
236
  // ReadyGate shows the full warm-up screen. A one-off transient blip
@@ -241,7 +250,7 @@ function SearchPage({
241
  ? TRANSIENT_RETRY_MESSAGE
242
  : 'Search failed — the search service didn’t respond. Please try again in a moment.');
243
  } finally {
244
- setLoading(false);
245
  }
246
  };
247
 
@@ -276,6 +285,8 @@ function SearchPage({
276
  return;
277
  }
278
 
 
 
279
  setLoading(true);
280
  setError(null);
281
  setNotice(null);
@@ -313,9 +324,25 @@ function SearchPage({
313
  promises.push(buildPublicationImageFetch(searchQuery));
314
  }
315
 
316
- const results = await Promise.all(promises);
317
- for (const result of results) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
318
  if (result.type === 'video') {
 
319
  setSearchResults(result.data.results || []);
320
  } else if (result.type === 'pubimage') {
321
  setPublicationImageResults(result.data.results || []);
@@ -327,7 +354,12 @@ function SearchPage({
327
  });
328
  }
329
  }
 
 
 
 
330
  } catch (err) {
 
331
  logApiFailure('search', err, { query: searchQuery, method: searchMethod, contentFilter: contentType });
332
  // 401 → AuthGate is showing login; stay silent. A real cold start →
333
  // ReadyGate shows the full warm-up screen. A one-off transient blip
@@ -338,7 +370,7 @@ function SearchPage({
338
  ? TRANSIENT_RETRY_MESSAGE
339
  : "Search failed — the search service didn’t respond. Please try again in a moment.");
340
  } finally {
341
- setLoading(false);
342
  }
343
  };
344
 
 
73
  const [showSubtitlesModal, setShowSubtitlesModal] = useState(false);
74
  const AVAILABLE_LANGUAGES = languages;
75
  const videoRef = useRef(null);
76
+ // Monotonic search id: a slow request (e.g. an LLM-routed smart search)
77
+ // must not overwrite the results of a newer one. Each submission bumps it;
78
+ // a completion only applies its setters when its id is still current.
79
+ const searchRequestIdRef = useRef(0);
80
 
81
  const {
82
  persons,
 
211
  return;
212
  }
213
 
214
+ const requestId = ++searchRequestIdRef.current;
215
+ const isStale = () => searchRequestIdRef.current !== requestId;
216
  setLoading(true);
217
  setError(null);
218
  setNotice(null);
 
227
  searchMethod,
228
  });
229
  const response = await fetchWithRetry(endpoint);
230
+ if (isStale()) return;
231
  const data = await readJson(response);
232
+ if (isStale()) return;
233
  // The index may be absent/empty until the build machine finishes.
234
  // That's informational, not an error.
235
  if (data.available === false) {
 
239
  }
240
  setSearchResults(data.results || []);
241
  } catch (err) {
242
+ if (isStale()) return;
243
  logApiFailure('narrative-search', err, { query: searchQuery, method: searchMethod });
244
  // 401 → AuthGate is showing login; stay silent. A real cold start →
245
  // ReadyGate shows the full warm-up screen. A one-off transient blip
 
250
  ? TRANSIENT_RETRY_MESSAGE
251
  : 'Search failed — the search service didn’t respond. Please try again in a moment.');
252
  } finally {
253
+ if (!isStale()) setLoading(false);
254
  }
255
  };
256
 
 
285
  return;
286
  }
287
 
288
+ const requestId = ++searchRequestIdRef.current;
289
+ const isStale = () => searchRequestIdRef.current !== requestId;
290
  setLoading(true);
291
  setError(null);
292
  setNotice(null);
 
324
  promises.push(buildPublicationImageFetch(searchQuery));
325
  }
326
 
327
+ // allSettled, not all: a failing publication-image leg must not
328
+ // discard successful video results (and vice-versa). Each section
329
+ // surfaces its own error instead of one blanket failure.
330
+ const outcomes = await Promise.allSettled(promises);
331
+ if (isStale()) return;
332
+
333
+ let videoFailed = false;
334
+ let anyVideoHandled = false;
335
+ for (const outcome of outcomes) {
336
+ if (outcome.status !== 'fulfilled') {
337
+ console.error('Search leg failed:', outcome.reason);
338
+ // Only a video-leg failure is a hard error; a publication-
339
+ // image failure is reported but never blanks the page.
340
+ if (searchVideos && !anyVideoHandled) videoFailed = true;
341
+ continue;
342
+ }
343
+ const result = outcome.value;
344
  if (result.type === 'video') {
345
+ anyVideoHandled = true;
346
  setSearchResults(result.data.results || []);
347
  } else if (result.type === 'pubimage') {
348
  setPublicationImageResults(result.data.results || []);
 
354
  });
355
  }
356
  }
357
+
358
+ if (videoFailed && !anyVideoHandled) {
359
+ setError("Failed to search. Make sure the backend is running and subtitles are indexed!");
360
+ }
361
  } catch (err) {
362
+ if (isStale()) return;
363
  logApiFailure('search', err, { query: searchQuery, method: searchMethod, contentFilter: contentType });
364
  // 401 → AuthGate is showing login; stay silent. A real cold start →
365
  // ReadyGate shows the full warm-up screen. A one-off transient blip
 
370
  ? TRANSIENT_RETRY_MESSAGE
371
  : "Search failed — the search service didn’t respond. Please try again in a moment.");
372
  } finally {
373
+ if (!isStale()) setLoading(false);
374
  }
375
  };
376
 
frontend/src/api/auth.js CHANGED
@@ -5,15 +5,35 @@ export function getAuthStatus() {
5
  return apiJson('/api/auth-status')
6
  }
7
 
 
 
 
 
 
 
 
 
 
 
8
  // Submit the shared password; the backend sets the session cookie on success.
9
  export async function login(password) {
10
- const response = await apiFetch('/api/login', {
11
- method: 'POST',
12
- headers: { 'Content-Type': 'application/json' },
13
- body: JSON.stringify({ password }),
14
- })
 
 
 
 
 
 
 
 
 
15
  if (!response.ok) {
16
- throw new Error('Incorrect password')
 
17
  }
18
  return response.json()
19
  }
 
5
  return apiJson('/api/auth-status')
6
  }
7
 
8
+ // Error thrown by login(); `kind` lets the UI tell "wrong password" apart from
9
+ // "backend unreachable" so it doesn't blame the user for a server outage.
10
+ export class LoginError extends Error {
11
+ constructor(kind, message) {
12
+ super(message)
13
+ this.name = 'LoginError'
14
+ this.kind = kind // 'invalid' | 'unavailable'
15
+ }
16
+ }
17
+
18
  // Submit the shared password; the backend sets the session cookie on success.
19
  export async function login(password) {
20
+ let response
21
+ try {
22
+ response = await apiFetch('/api/login', {
23
+ method: 'POST',
24
+ headers: { 'Content-Type': 'application/json' },
25
+ body: JSON.stringify({ password }),
26
+ })
27
+ } catch {
28
+ // Network failure / connection refused — the backend is unreachable.
29
+ throw new LoginError('unavailable', 'Cannot reach the server.')
30
+ }
31
+ if (response.status === 401) {
32
+ throw new LoginError('invalid', 'Incorrect password')
33
+ }
34
  if (!response.ok) {
35
+ // 5xx or other server error — not the user's password.
36
+ throw new LoginError('unavailable', `Server error (${response.status}).`)
37
  }
38
  return response.json()
39
  }
frontend/src/components/AuthGate.jsx CHANGED
@@ -22,9 +22,14 @@ function LoginScreen({ onSuccess }) {
22
  try {
23
  await login(password)
24
  onSuccess()
25
- } catch {
26
- setError('That password is not correct. Please try again.')
27
- setPassword('')
 
 
 
 
 
28
  } finally {
29
  setSubmitting(false)
30
  }
 
22
  try {
23
  await login(password)
24
  onSuccess()
25
+ } catch (err) {
26
+ if (err && err.kind === 'unavailable') {
27
+ // Backend down / errored — don't blame the user's password.
28
+ setError('Cannot reach the server. It may still be starting up — try again in a moment.')
29
+ } else {
30
+ setError('That password is not correct. Please try again.')
31
+ setPassword('')
32
+ }
33
  } finally {
34
  setSubmitting(false)
35
  }
frontend/src/hooks/useUnknownFaces.js CHANGED
@@ -39,6 +39,10 @@ function useUnknownFaces({
39
  const appearancesGridRef = useRef(null)
40
  const toastIdRef = useRef(0)
41
  const deletionTimeoutRef = useRef({})
 
 
 
 
42
  const unknownFacesRef = useRef([])
43
  const selectedUnknownRef = useRef(null)
44
 
@@ -197,6 +201,7 @@ function useUnknownFaces({
197
 
198
  const queueDeleteFaces = (faces, originalCluster) => {
199
  const deletionId = Date.now()
 
200
  setPendingDeletions(prev => [...prev, { id: deletionId, faces, originalCluster }])
201
 
202
  const handleUndo = () => {
@@ -204,6 +209,7 @@ function useUnknownFaces({
204
  clearTimeout(deletionTimeoutRef.current[deletionId])
205
  delete deletionTimeoutRef.current[deletionId]
206
  }
 
207
  setPendingDeletions(prev => prev.filter(deletion => deletion.id !== deletionId))
208
  restoreFacesToState(faces, originalCluster)
209
  addToast('Deletion undone')
@@ -232,6 +238,7 @@ function useUnknownFaces({
232
  }
233
  setPendingDeletions(prev => prev.filter(deletion => deletion.id !== deletionId))
234
  delete deletionTimeoutRef.current[deletionId]
 
235
  }, DELETE_UNDO_MS)
236
  }
237
 
@@ -498,11 +505,24 @@ function useUnknownFaces({
498
 
499
  useEffect(() => {
500
  const pendingDeletionTimeouts = deletionTimeoutRef.current
 
501
  return () => {
502
- Object.values(pendingDeletionTimeouts).forEach(timeout => {
 
 
 
503
  clearTimeout(timeout)
 
 
 
 
 
 
504
  })
505
  }
 
 
 
506
  }, [])
507
 
508
  return {
 
39
  const appearancesGridRef = useRef(null)
40
  const toastIdRef = useRef(0)
41
  const deletionTimeoutRef = useRef({})
42
+ // deletionId -> faces, so a still-pending delete can be FLUSHED (sent) on
43
+ // unmount rather than cancelled — otherwise the user saw "deleted" but the
44
+ // DELETE never fired and the faces reappear on the next visit.
45
+ const pendingDeleteFacesRef = useRef({})
46
  const unknownFacesRef = useRef([])
47
  const selectedUnknownRef = useRef(null)
48
 
 
201
 
202
  const queueDeleteFaces = (faces, originalCluster) => {
203
  const deletionId = Date.now()
204
+ pendingDeleteFacesRef.current[deletionId] = faces
205
  setPendingDeletions(prev => [...prev, { id: deletionId, faces, originalCluster }])
206
 
207
  const handleUndo = () => {
 
209
  clearTimeout(deletionTimeoutRef.current[deletionId])
210
  delete deletionTimeoutRef.current[deletionId]
211
  }
212
+ delete pendingDeleteFacesRef.current[deletionId]
213
  setPendingDeletions(prev => prev.filter(deletion => deletion.id !== deletionId))
214
  restoreFacesToState(faces, originalCluster)
215
  addToast('Deletion undone')
 
238
  }
239
  setPendingDeletions(prev => prev.filter(deletion => deletion.id !== deletionId))
240
  delete deletionTimeoutRef.current[deletionId]
241
+ delete pendingDeleteFacesRef.current[deletionId]
242
  }, DELETE_UNDO_MS)
243
  }
244
 
 
505
 
506
  useEffect(() => {
507
  const pendingDeletionTimeouts = deletionTimeoutRef.current
508
+ const pendingFaces = pendingDeleteFacesRef.current
509
  return () => {
510
+ // FLUSH, don't cancel: the user already saw "deleted", so send any
511
+ // still-pending DELETE now instead of dropping it. (SPA page swap
512
+ // is a component unmount, not a page unload, so the fetch completes.)
513
+ Object.entries(pendingDeletionTimeouts).forEach(([deletionId, timeout]) => {
514
  clearTimeout(timeout)
515
+ const faces = pendingFaces[deletionId]
516
+ if (faces) {
517
+ try {
518
+ requestDeleteFaces(faces).catch(() => { /* best-effort flush */ })
519
+ } catch { /* best-effort flush */ }
520
+ }
521
  })
522
  }
523
+ // requestDeleteFaces is stable for the component's lifetime; flushing
524
+ // on unmount intentionally runs once.
525
+ // eslint-disable-next-line react-hooks/exhaustive-deps
526
  }, [])
527
 
528
  return {