phaethon-order commited on
Commit
eee15b3
·
1 Parent(s): 7abc2dc

Enhance error handling in chunk_doc function and improve find_nearest_neighbors function with optional filtering; update HTML styling for better readability and responsiveness in chunks and database viewer.

Browse files
infrastructure/chunker.py CHANGED
@@ -420,6 +420,8 @@ def chunk_doc(text: str, doc_id: int, max_chars: int = 1200, overlap: int = 150,
420
  with open(path, "w", encoding="utf-8") as f:
421
  f.write(records)
422
  logger.info(f"Created new chunks file with {len(chunk_metadata_records)} records as it did not exist")
 
 
423
 
424
  chunk_texts = [spec[0] for spec in chunk_specs]
425
  # Generate embeddings and upsert to ChromaDB
 
420
  with open(path, "w", encoding="utf-8") as f:
421
  f.write(records)
422
  logger.info(f"Created new chunks file with {len(chunk_metadata_records)} records as it did not exist")
423
+ except Exception as e:
424
+ logger.error(f"Failed to write chunk records to {path}: {e}")
425
 
426
  chunk_texts = [spec[0] for spec in chunk_specs]
427
  # Generate embeddings and upsert to ChromaDB
infrastructure/vector_search.py CHANGED
@@ -1,5 +1,6 @@
1
- from typing import List, Tuple
2
  import json
 
3
 
4
  from infrastructure.embeddings import get_chroma_collection
5
  from infrastructure.logger import get_logger
@@ -9,41 +10,68 @@ logger = get_logger()
9
  def find_nearest_neighbors(
10
  query: str,
11
  num_neighbors: int,
12
- ) -> List[Tuple[str, float]]:
 
 
13
  """
14
- Finds the nearest neighbors for a given query using ChromaDB.
15
 
16
  Args:
17
  query: The query string.
18
  num_neighbors: The number of nearest neighbors to retrieve.
 
 
19
 
20
  Returns:
21
- A list of tuples, where each tuple contains the ID of a neighbor and its distance.
 
22
  """
23
- logger.info(f"Finding {num_neighbors} nearest neighbors for query: '{query}'")
24
 
25
  collection = get_chroma_collection()
26
 
27
  try:
28
  results = collection.query(
29
  query_texts=[query],
30
- n_results=num_neighbors
 
 
 
31
  )
32
 
33
- if (
34
- not results
35
- or not results.get("ids")
36
- or not results["ids"][0]
37
- or not results.get("distances")
38
- or not results["distances"]
39
- ):
40
- logger.error("No neighbors found or results format is invalid.")
41
  return []
42
 
43
  ids = results["ids"][0]
44
- distances = results["distances"][0]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
 
46
- neighbors = list(zip(ids, distances))
47
  logger.info(f"Found {len(neighbors)} neighbors.")
48
  return neighbors
49
 
 
1
+ from typing import List, Dict, Any, Optional
2
  import json
3
+ from chromadb.types import Where, WhereDocument
4
 
5
  from infrastructure.embeddings import get_chroma_collection
6
  from infrastructure.logger import get_logger
 
10
  def find_nearest_neighbors(
11
  query: str,
12
  num_neighbors: int,
13
+ where: Optional[Where] = None,
14
+ where_document: Optional[WhereDocument] = None,
15
+ ) -> List[Dict[str, Any]]:
16
  """
17
+ Finds the nearest neighbors for a given query using ChromaDB, with optional filtering.
18
 
19
  Args:
20
  query: The query string.
21
  num_neighbors: The number of nearest neighbors to retrieve.
22
+ where: An optional dictionary for metadata-based filtering.
23
+ where_document: An optional dictionary for document-based filtering.
24
 
25
  Returns:
26
+ A list of dictionaries, where each dictionary contains the 'id',
27
+ 'distance', 'document', and 'metadata' of a neighbor.
28
  """
29
+ logger.info(f"Finding {num_neighbors} nearest neighbors for query: '{query}' with filters: where={where}, where_document={where_document}")
30
 
31
  collection = get_chroma_collection()
32
 
33
  try:
34
  results = collection.query(
35
  query_texts=[query],
36
+ n_results=num_neighbors,
37
+ where=where,
38
+ where_document=where_document,
39
+ include=["metadatas", "documents", "distances"]
40
  )
41
 
42
+ if not results or not results.get("ids") or not results["ids"][0]:
43
+ logger.warning("No neighbors found or results format is invalid.")
 
 
 
 
 
 
44
  return []
45
 
46
  ids = results["ids"][0]
47
+ distances_list = results.get("distances")
48
+ documents_list = results.get("documents")
49
+ metadatas_list = results.get("metadatas")
50
+
51
+ distances = distances_list[0] if distances_list is not None else []
52
+ documents = documents_list[0] if documents_list is not None else []
53
+ metadatas = metadatas_list[0] if metadatas_list is not None else []
54
+
55
+ neighbors = []
56
+ for i, doc_id in enumerate(ids):
57
+ metadata = metadatas[i] if metadatas and i < len(metadatas) else {}
58
+
59
+ # Create a mutable copy of metadata to allow modification
60
+ if metadata:
61
+ mutable_metadata = dict(metadata)
62
+ if 'restricts' in mutable_metadata and isinstance(mutable_metadata['restricts'], str):
63
+ mutable_metadata['restricts'] = json.loads(mutable_metadata['restricts'])
64
+ if 'numeric_restricts' in mutable_metadata and isinstance(mutable_metadata['numeric_restricts'], str):
65
+ mutable_metadata['numeric_restricts'] = json.loads(mutable_metadata['numeric_restricts'])
66
+ metadata = mutable_metadata
67
+
68
+ neighbors.append({
69
+ "id": doc_id,
70
+ "distance": distances[i] if distances and i < len(distances) else float('inf'),
71
+ "document": documents[i] if documents and i < len(documents) else "",
72
+ "metadata": metadata,
73
+ })
74
 
 
75
  logger.info(f"Found {len(neighbors)} neighbors.")
76
  return neighbors
77
 
static/chunks.html CHANGED
@@ -44,12 +44,29 @@
44
  .kv{background:#222;border:2px solid #555;border-radius:12px;padding:10px 12px;display:flex;flex-direction:column;gap:4px}
45
  .kv span.k{font-size:.6rem;text-transform:uppercase;letter-spacing:1px;color:#999}
46
  .kv span.v{font-size:.8rem;word-break:break-word}
47
- .table-wrapper{background:#222;border:2px solid #555;border-radius:16px;padding:14px 18px;max-height:60vh;overflow:auto}
48
- table.data-table{width:100%;border-collapse:collapse;font-size:.65rem}
49
  table.data-table th,table.data-table td{padding:6px 8px;text-align:left;border:1px solid #444;vertical-align:top;white-space:normal;word-break:break-word;overflow-wrap:anywhere}
50
  table.data-table th{position:sticky;top:0;background:#2d3f4d;z-index:2;font-weight:600;letter-spacing:.5px}
51
  table.data-table tbody tr:nth-child(even){background:#1e2a33}
52
  .truncate{max-width:unset;white-space:normal;word-break:break-word;overflow-wrap:anywhere}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
  .toolbar{display:flex;flex-wrap:wrap;gap:10px}
54
  .toolbar input{background:#222;border:2px solid #555;border-radius:10px;padding:8px 10px;color:#fff;font-size:.75rem;min-width:220px}
55
  .toolbar input:focus{outline:none;border-color:#7ec8ff;box-shadow:0 0 0 3px rgba(126,200,255,.15)}
 
44
  .kv{background:#222;border:2px solid #555;border-radius:12px;padding:10px 12px;display:flex;flex-direction:column;gap:4px}
45
  .kv span.k{font-size:.6rem;text-transform:uppercase;letter-spacing:1px;color:#999}
46
  .kv span.v{font-size:.8rem;word-break:break-word}
47
+ .table-wrapper{background:#222;border:2px solid #555;border-radius:16px;padding:14px 18px;max-height:60vh;overflow:auto;overflow-x:auto}
48
+ table.data-table{width:auto;min-width:1900px;border-collapse:collapse;font-size:.65rem;table-layout:fixed}
49
  table.data-table th,table.data-table td{padding:6px 8px;text-align:left;border:1px solid #444;vertical-align:top;white-space:normal;word-break:break-word;overflow-wrap:anywhere}
50
  table.data-table th{position:sticky;top:0;background:#2d3f4d;z-index:2;font-weight:600;letter-spacing:.5px}
51
  table.data-table tbody tr:nth-child(even){background:#1e2a33}
52
  .truncate{max-width:unset;white-space:normal;word-break:break-word;overflow-wrap:anywhere}
53
+ /* Wider, fixed column widths for better readability and horizontal scrolling */
54
+ table.data-table th:nth-child(1),
55
+ table.data-table td:nth-child(1){width:90px}
56
+ table.data-table th:nth-child(2),
57
+ table.data-table td:nth-child(2){width:90px}
58
+ table.data-table th:nth-child(3),
59
+ table.data-table td:nth-child(3){width:900px} /* text */
60
+ table.data-table th:nth-child(4),
61
+ table.data-table td:nth-child(4){width:120px}
62
+ table.data-table th:nth-child(5),
63
+ table.data-table td:nth-child(5){width:320px}
64
+ table.data-table th:nth-child(6),
65
+ table.data-table td:nth-child(6){width:180px}
66
+ table.data-table th:nth-child(7),
67
+ table.data-table td:nth-child(7){width:240px}
68
+ table.data-table th:nth-child(8),
69
+ table.data-table td:nth-child(8){width:140px}
70
  .toolbar{display:flex;flex-wrap:wrap;gap:10px}
71
  .toolbar input{background:#222;border:2px solid #555;border-radius:10px;padding:8px 10px;color:#fff;font-size:.75rem;min-width:220px}
72
  .toolbar input:focus{outline:none;border-color:#7ec8ff;box-shadow:0 0 0 3px rgba(126,200,255,.15)}
static/dbviewer.html CHANGED
@@ -40,10 +40,10 @@
40
  .view-toggles button.active:hover { background:#6bb8ff; }
41
  .table-wrapper { background:#222; border:2px solid #555; border-radius:16px; padding:14px 18px; max-height:60vh; overflow:auto; }
42
  table.data-table { width:100%; border-collapse:collapse; font-size:.7rem; }
43
- table.data-table th, table.data-table td { padding:8px 10px; text-align:left; border:1px solid #444; vertical-align:top; }
44
  table.data-table th { position:sticky; top:0; background:#2d3f4d; z-index:2; font-weight:600; letter-spacing:.5px; }
45
  table.data-table tbody tr:nth-child(even){ background:#1e2a33; }
46
- .truncate { max-width:150px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; cursor:pointer; }
47
  .truncate:hover { background:#203240; }
48
  .empty { text-align:center; font-style:italic; color:#ccc; padding:40px; }
49
  .error { color:#ff7b7b; font-weight:600; }
 
40
  .view-toggles button.active:hover { background:#6bb8ff; }
41
  .table-wrapper { background:#222; border:2px solid #555; border-radius:16px; padding:14px 18px; max-height:60vh; overflow:auto; }
42
  table.data-table { width:100%; border-collapse:collapse; font-size:.7rem; }
43
+ table.data-table th, table.data-table td { padding:8px 10px; text-align:left; border:1px solid #444; vertical-align:top; white-space:normal; word-break:break-word; overflow-wrap:anywhere; }
44
  table.data-table th { position:sticky; top:0; background:#2d3f4d; z-index:2; font-weight:600; letter-spacing:.5px; }
45
  table.data-table tbody tr:nth-child(even){ background:#1e2a33; }
46
+ .truncate { white-space:normal; word-break:break-word; overflow-wrap:anywhere; cursor:pointer; }
47
  .truncate:hover { background:#203240; }
48
  .empty { text-align:center; font-style:italic; color:#ccc; padding:40px; }
49
  .error { color:#ff7b7b; font-weight:600; }