phaethon-order commited on
Commit
bd2eab1
·
unverified ·
1 Parent(s): 7744fd3
infrastructure/chunker.py CHANGED
@@ -405,9 +405,9 @@ def chunk_doc(text: str, doc_id: int, max_chars: int = 1200, overlap: int = 150,
405
  # Link prev/next
406
  for i, rec in enumerate(chunk_metadata_records):
407
  if i > 0:
408
- rec['prev_id'] = chunk_metadata_records[i-1]['index']
409
  if i < len(chunk_metadata_records) - 1:
410
- rec['next_id'] = chunk_metadata_records[i+1]['index']
411
 
412
  records = json.dumps(chunk_metadata_records, ensure_ascii=False, indent=0)
413
  path = os.path.join(CHUNKS_DIR, "chunks.jsonl")
 
405
  # Link prev/next
406
  for i, rec in enumerate(chunk_metadata_records):
407
  if i > 0:
408
+ rec['prev_id'] = chunk_metadata_records[i-1]['id']
409
  if i < len(chunk_metadata_records) - 1:
410
+ rec['next_id'] = chunk_metadata_records[i+1]['id']
411
 
412
  records = json.dumps(chunk_metadata_records, ensure_ascii=False, indent=0)
413
  path = os.path.join(CHUNKS_DIR, "chunks.jsonl")
infrastructure/database.py CHANGED
@@ -383,6 +383,18 @@ def session_scope():
383
  # --------------- CRUD ---------------
384
  def add_document(*, sha256, title=None, source_path=None, doc_type=None, jurisdiction=None, industry=None, party_roles=None, governing_law=None, effective_date=None):
385
  existing = _documents_collection.get(where={"sha256": sha256})
 
 
 
 
 
 
 
 
 
 
 
 
386
  if existing['ids'] and existing['metadatas']:
387
  doc_id = int(existing['ids'][0])
388
  metadata = dict(existing['metadatas'][0])
@@ -566,6 +578,12 @@ def get_document_chunk_counts(doc_ids: list[int]) -> dict[int, int]:
566
  counts[int(doc_id)] += 1
567
  return counts
568
 
 
 
 
 
 
 
569
  def get_all_chunks(limit: int = 200, offset: int = 0):
570
  all_ids = _chunks_collection.get(include=[])['ids']
571
  paginated_ids = sorted([int(i) for i in all_ids])[offset : offset + limit]
@@ -601,10 +619,61 @@ def get_embedding_for_chunk(chunk_id: int):
601
  def delete_document(doc_id: int):
602
  chunks_to_delete = _chunks_collection.get(where={"doc_id": doc_id})
603
  if chunks_to_delete['ids']:
604
- _chunks_collection.delete(ids=chunks_to_delete['ids'])
 
 
 
 
 
 
 
 
 
 
 
 
 
605
 
606
  _documents_collection.delete(ids=[str(doc_id)])
607
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
608
  def clear_database():
609
  _client.delete_collection(name="documents")
610
  _client.delete_collection(name="chunks")
@@ -622,7 +691,7 @@ __all__ = [
622
  "add_document", "add_chunk", "upsert_embedding",
623
  "get_document", "get_document_by_sha", "get_chunks_for_doc", "get_chunks_by_ids",
624
  "get_documents", "get_document_chunk_counts", "get_all_chunks", "get_max_chunk_id",
625
- "get_embedding_for_chunk", "delete_document", "clear_database",
626
  "TOK_VER", "SEG_VER", "ping",
627
  "Document", "Chunk", "Embedding",
628
  ]
 
383
  # --------------- CRUD ---------------
384
  def add_document(*, sha256, title=None, source_path=None, doc_type=None, jurisdiction=None, industry=None, party_roles=None, governing_law=None, effective_date=None):
385
  existing = _documents_collection.get(where={"sha256": sha256})
386
+
387
+ if doc_type and isinstance(doc_type, list):
388
+ doc_type = ", ".join(doc_type)
389
+ if jurisdiction and isinstance(jurisdiction, list):
390
+ jurisdiction = ", ".join(jurisdiction)
391
+ if industry and isinstance(industry, list):
392
+ industry = ", ".join(industry)
393
+ if party_roles and isinstance(party_roles, list):
394
+ party_roles = ", ".join(party_roles)
395
+ if governing_law and isinstance(governing_law, list):
396
+ governing_law = ", ".join(governing_law)
397
+
398
  if existing['ids'] and existing['metadatas']:
399
  doc_id = int(existing['ids'][0])
400
  metadata = dict(existing['metadatas'][0])
 
578
  counts[int(doc_id)] += 1
579
  return counts
580
 
581
+ def get_max_document_id():
582
+ all_ids = _documents_collection.get(include=[])['ids']
583
+ if not all_ids:
584
+ return -1
585
+ return max([int(i) for i in all_ids])
586
+
587
  def get_all_chunks(limit: int = 200, offset: int = 0):
588
  all_ids = _chunks_collection.get(include=[])['ids']
589
  paginated_ids = sorted([int(i) for i in all_ids])[offset : offset + limit]
 
619
  def delete_document(doc_id: int):
620
  chunks_to_delete = _chunks_collection.get(where={"doc_id": doc_id})
621
  if chunks_to_delete['ids']:
622
+ chunk_ids = [str(cid) for cid in chunks_to_delete['ids']]
623
+ # Also delete corresponding embeddings from the external embeddings collection
624
+ try:
625
+ from .embeddings import get_chroma_collection # local import to avoid cycles
626
+ vec_coll = get_chroma_collection()
627
+ try:
628
+ vec_coll.delete(ids=chunk_ids)
629
+ except Exception as e: # pragma: no cover - defensive
630
+ _logger.error("Failed to delete embeddings for chunk_ids=%s: %s", chunk_ids[:5], e)
631
+ except Exception as e: # pragma: no cover - env or import issues
632
+ _logger.error("Could not access embeddings collection to delete vectors: %s", e)
633
+
634
+ # Delete chunks (and their stored vectors in the chunks collection)
635
+ _chunks_collection.delete(ids=chunk_ids)
636
 
637
  _documents_collection.delete(ids=[str(doc_id)])
638
 
639
+ def update_document(doc_id: int, updates: Dict[str, Any]) -> Optional[Document]:
640
+ """Update metadata fields for a document.
641
+
642
+ Only known metadata keys are updated. Returns the updated Document or None if not found.
643
+ """
644
+ allowed = {
645
+ "title",
646
+ "doc_type",
647
+ "jurisdiction",
648
+ "governing_law",
649
+ "party_roles",
650
+ "industry",
651
+ "effective_date",
652
+ "source_path",
653
+ }
654
+ try:
655
+ existing = _documents_collection.get(ids=[str(doc_id)])
656
+ if not existing['ids'] or not existing['metadatas']:
657
+ return None
658
+ meta = dict(existing['metadatas'][0])
659
+ # Normalize list values to comma-separated strings
660
+ def _norm(v):
661
+ if isinstance(v, list):
662
+ return ", ".join(str(x) for x in v)
663
+ return v
664
+ for k, v in updates.items():
665
+ if k in allowed:
666
+ if k == "effective_date" and isinstance(v, str):
667
+ # store as ISO string as-is; validation elsewhere
668
+ meta[k] = v
669
+ else:
670
+ meta[k] = _norm(v)
671
+ _documents_collection.update(ids=[str(doc_id)], metadatas=[meta])
672
+ return Document.from_chroma(doc_id, meta)
673
+ except Exception as e: # pragma: no cover - defensive
674
+ _logger.error(f"Failed to update document {doc_id}: {e}")
675
+ return None
676
+
677
  def clear_database():
678
  _client.delete_collection(name="documents")
679
  _client.delete_collection(name="chunks")
 
691
  "add_document", "add_chunk", "upsert_embedding",
692
  "get_document", "get_document_by_sha", "get_chunks_for_doc", "get_chunks_by_ids",
693
  "get_documents", "get_document_chunk_counts", "get_all_chunks", "get_max_chunk_id",
694
+ "get_embedding_for_chunk", "delete_document", "clear_database", "update_document",
695
  "TOK_VER", "SEG_VER", "ping",
696
  "Document", "Chunk", "Embedding",
697
  ]
infrastructure/document_processor.py CHANGED
@@ -46,11 +46,9 @@ def get_manifest_info(text: str) -> Dict[str, Optional[str]]:
46
  client = OpenAI(api_key=API_KEY)
47
  prompt = (
48
  f"""
49
- Examine the attached technology transactions document and then identify respective values for each of the following keys: source_url (url of the document), license, type of technology transactions document (doc_type, use only one or two words, use abbreviations where appropriate), the role(s) of the party or parties (use only the roles, e.g., licensor, licensee; do not include the names of the parties), the jurisdiction, the governing law, the industry (use only one or two words), and the effective date of the agreement. Consider the substantive meaning of words (e.g., "Page 1 of 12" is not likely to be the license), placement in the document, surrounding text, applicable section, and any other factors that might inform your decision. Use standard legal abbreviations for the jurisdiction and governing law (e.g., US-CA for California state law, US-FED for US federal law, etc.). Format the date in a string "YYYY-MM-DD".
50
  Return a response in following JSON format only:
51
  {{
52
- "source_url": source_url,
53
- "license": license,
54
  "party_roles": party_roles,
55
  "governing_law": governing_law,
56
  "industry": industry,
@@ -68,7 +66,7 @@ def get_manifest_info(text: str) -> Dict[str, Optional[str]]:
68
  response = client.chat.completions.create(
69
  model=ai_model,
70
  messages=[
71
- {"role": "system", "content": "Extract the document's source_url, license, the role of the party or parties, the governing law, the industry, and the version or effective date based from the following text.\n"},
72
  {"role": "user", "content": prompt},
73
  ]
74
  )
@@ -78,8 +76,6 @@ def get_manifest_info(text: str) -> Dict[str, Optional[str]]:
78
  candidate = (response or [])
79
  logger.info(f"AI manifest response: {candidate}")
80
  expected_keys = [
81
- "source_url",
82
- "license",
83
  "party_roles",
84
  "governing_law",
85
  "industry",
@@ -237,12 +233,12 @@ def sha256_text(text: str) -> str:
237
  """Compute the SHA-256 hash of a text string."""
238
  return sha256_bytes(text.encode('utf-8'))
239
 
240
- def upsert_manifest_record(text: str, size: str, doc_id: str, sha256: str, source_path: str, clean_path: str, content_type: str, title: str, jurisdiction: str, doc_type: str) -> Dict[str, Optional[Any]]:
241
  """Upsert a manifest record in the database."""
242
 
243
  manifest = get_manifest_info(text)
244
  manifest_record = {
245
- "doc_id": doc_id,
246
  "title": title,
247
  "sha256": sha256,
248
  "source_path": source_path,
 
46
  client = OpenAI(api_key=API_KEY)
47
  prompt = (
48
  f"""
49
+ Examine the attached technology transactions document and then identify respective values for each of the following keys: the role(s) of the party or parties (use only the roles, e.g., licensor, licensee; do not include the names of the parties), the governing law (use standard legal abbreviations, e.g., US-CA, US-FED, IL, etc.), the industry (use only one or two words), and the effective date of the agreement. Consider the substantive meaning of words (e.g., "Page 1 of 12" is not likely to be the governing law), placement in the document, surrounding text, applicable section, and any other factors that might inform your decision. Format the date in a string "YYYY-MM-DD".
50
  Return a response in following JSON format only:
51
  {{
 
 
52
  "party_roles": party_roles,
53
  "governing_law": governing_law,
54
  "industry": industry,
 
66
  response = client.chat.completions.create(
67
  model=ai_model,
68
  messages=[
69
+ {"role": "system", "content": "Extract the document's the role of the party or parties, the governing law, the industry, and the version or effective date based from the following text.\n"},
70
  {"role": "user", "content": prompt},
71
  ]
72
  )
 
76
  candidate = (response or [])
77
  logger.info(f"AI manifest response: {candidate}")
78
  expected_keys = [
 
 
79
  "party_roles",
80
  "governing_law",
81
  "industry",
 
233
  """Compute the SHA-256 hash of a text string."""
234
  return sha256_bytes(text.encode('utf-8'))
235
 
236
+ def upsert_manifest_record(text: str, size: str, doc_id: int, sha256: str, source_path: str, clean_path: str, content_type: str | None, title: str | None, jurisdiction: str | None, doc_type: str | None) -> Dict[str, Optional[Any]]:
237
  """Upsert a manifest record in the database."""
238
 
239
  manifest = get_manifest_info(text)
240
  manifest_record = {
241
+ "doc_id": str(doc_id),
242
  "title": title,
243
  "sha256": sha256,
244
  "source_path": source_path,
routes/api.py CHANGED
@@ -1,8 +1,9 @@
1
  # api.py
2
  import os
3
- from flask import Blueprint, request, jsonify
4
  from werkzeug.utils import secure_filename
5
  from infrastructure.logger import get_logger
 
6
 
7
  from infrastructure.database import (
8
  init_db,
@@ -13,15 +14,19 @@ from infrastructure.database import (
13
  get_document_chunk_counts,
14
  get_all_chunks,
15
  full_reset_chroma,
 
 
 
 
16
  )
17
  from infrastructure.document_processor import (
18
  extract_text,
19
  extract_title_type_jurisdiction,
20
  sha256_text,
 
21
  )
22
  from infrastructure.chunker import chunk_doc
23
  from infrastructure.vector_search import find_nearest_neighbors
24
- from infrastructure.database import get_chunks_by_ids
25
 
26
  api_bp = Blueprint("api", __name__, url_prefix="/api")
27
  logger = get_logger()
@@ -29,6 +34,8 @@ logger = get_logger()
29
  ALLOWED_EXTENSIONS = {"pdf", "docx", "txt"}
30
  UPLOAD_FOLDER = os.getenv("UPLOAD_FOLDER", "/data/corpus_raw")
31
  CLEAN_FOLDER = os.getenv("CLEAN_FOLDER", "/data/corpus_clean")
 
 
32
 
33
  def allowed_file(filename: str) -> bool:
34
  return "." in filename and filename.rsplit(".", 1)[1].lower() in ALLOWED_EXTENSIONS
@@ -58,8 +65,26 @@ def add_doc():
58
 
59
  if not doc:
60
  filename = secure_filename(file.filename)
61
- raw_path = os.path.join(UPLOAD_FOLDER, filename)
62
- txt_filename = filename.rsplit('.', 1)[0] + '.txt'
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
  clean_path = os.path.join(CLEAN_FOLDER, txt_filename)
64
 
65
  file.stream.seek(0)
@@ -70,16 +95,30 @@ def add_doc():
70
  f.write(clean_text)
71
  logger.info("Saved clean text to %s", clean_path)
72
 
73
- doc_info = extract_title_type_jurisdiction(clean_text)
74
- title = doc_info.get("title") or file.filename.split('.')[0]
75
- if not doc_type and "doc_type" in doc_info:
76
- doc_type = doc_info.get("doc_type")
77
- if not jurisdiction and "jurisdiction" in doc_info:
78
- jurisdiction = doc_info.get("jurisdiction")
79
-
80
- doc = add_document(sha256=content_sha, title=title, source_path=raw_path, doc_type=doc_type, jurisdiction=jurisdiction)
 
 
 
 
 
 
 
 
 
 
 
81
  doc_id_val = getattr(doc, "doc_id", 0)
82
 
 
 
 
83
  else:
84
  doc_id_val = getattr(doc, "doc_id", 0)
85
  title = getattr(doc, "title", None)
@@ -290,3 +329,155 @@ def reset_system():
290
  "dirs_deleted": len([p for p in erased_paths if p.endswith('/')]),
291
  "chroma_reset": chroma_ok,
292
  }), 200
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  # api.py
2
  import os
3
+ from flask import Blueprint, request, jsonify, send_from_directory
4
  from werkzeug.utils import secure_filename
5
  from infrastructure.logger import get_logger
6
+ from random import randint
7
 
8
  from infrastructure.database import (
9
  init_db,
 
14
  get_document_chunk_counts,
15
  get_all_chunks,
16
  full_reset_chroma,
17
+ get_max_document_id,
18
+ get_chunks_by_ids,
19
+ update_document,
20
+ delete_document,
21
  )
22
  from infrastructure.document_processor import (
23
  extract_text,
24
  extract_title_type_jurisdiction,
25
  sha256_text,
26
+ upsert_manifest_record
27
  )
28
  from infrastructure.chunker import chunk_doc
29
  from infrastructure.vector_search import find_nearest_neighbors
 
30
 
31
  api_bp = Blueprint("api", __name__, url_prefix="/api")
32
  logger = get_logger()
 
34
  ALLOWED_EXTENSIONS = {"pdf", "docx", "txt"}
35
  UPLOAD_FOLDER = os.getenv("UPLOAD_FOLDER", "/data/corpus_raw")
36
  CLEAN_FOLDER = os.getenv("CLEAN_FOLDER", "/data/corpus_clean")
37
+ MANIFEST_DIR = os.getenv("MANIFEST_DIR", "/data/manifest")
38
+ RAW_PREFIX = "/data/corpus_raw"
39
 
40
  def allowed_file(filename: str) -> bool:
41
  return "." in filename and filename.rsplit(".", 1)[1].lower() in ALLOWED_EXTENSIONS
 
65
 
66
  if not doc:
67
  filename = secure_filename(file.filename)
68
+
69
+ doc_info = extract_title_type_jurisdiction(clean_text)
70
+ title = doc_info.get("title") or file.filename.split('.')[0]
71
+ if not doc_type and "doc_type" in doc_info:
72
+ doc_type = doc_info.get("doc_type")
73
+ if not jurisdiction and "jurisdiction" in doc_info:
74
+ jurisdiction = doc_info.get("jurisdiction")
75
+
76
+ max_doc_id = get_max_document_id()
77
+
78
+ current_doc_id = max_doc_id + 1 if max_doc_id is not None else 0
79
+ file_format = file.mimetype
80
+ file.stream.seek(0, 2)
81
+ file_size = file.tell()
82
+ file.stream.seek(0)
83
+
84
+ raw_filename = f"{str(current_doc_id)}" + "." + filename.rsplit('.', 1)[1].lower()
85
+
86
+ raw_path = os.path.join(UPLOAD_FOLDER, raw_filename)
87
+ txt_filename = f"{str(current_doc_id)}" + '.txt'
88
  clean_path = os.path.join(CLEAN_FOLDER, txt_filename)
89
 
90
  file.stream.seek(0)
 
95
  f.write(clean_text)
96
  logger.info("Saved clean text to %s", clean_path)
97
 
98
+ manifest_record = upsert_manifest_record(
99
+ sha256=content_sha,
100
+ title=title,
101
+ source_path=raw_path,
102
+ clean_path=clean_path,
103
+ doc_type=doc_type or "",
104
+ jurisdiction=jurisdiction or "",
105
+ doc_id=current_doc_id or randint(100, 999),
106
+ text=clean_text,
107
+ size=str(file_size),
108
+ content_type=file_format,
109
+ )
110
+
111
+ industry = manifest_record.get("industry") or None
112
+ party_roles = manifest_record.get("party_roles") or None
113
+ governing_law = manifest_record.get("governing_law") or None
114
+ effective_date = manifest_record.get("effective_date") or None
115
+
116
+ doc = add_document(sha256=content_sha, title=title, source_path=raw_path, doc_type=doc_type, jurisdiction=jurisdiction, industry=industry, party_roles=party_roles, governing_law=governing_law, effective_date=effective_date)
117
  doc_id_val = getattr(doc, "doc_id", 0)
118
 
119
+ logger.error("INFO: Added document id=%s, sha256=%s, title=%s, doc_type=%s, jurisdiction=%s", doc_id_val, content_sha, title, doc_type, jurisdiction)
120
+ logger.error(f"INFO: DB doc_id: {doc_id_val}; Manifest doc_id: {current_doc_id} ")
121
+
122
  else:
123
  doc_id_val = getattr(doc, "doc_id", 0)
124
  title = getattr(doc, "title", None)
 
329
  "dirs_deleted": len([p for p in erased_paths if p.endswith('/')]),
330
  "chroma_reset": chroma_ok,
331
  }), 200
332
+
333
+
334
+ # -------- Manifest JSONL helpers and endpoints --------
335
+ def _manifest_path() -> str:
336
+ os.makedirs(MANIFEST_DIR, exist_ok=True)
337
+ return os.path.join(MANIFEST_DIR, "manifest.jsonl")
338
+
339
+ def _read_manifest() -> list[dict]:
340
+ path = _manifest_path()
341
+ rows: list[dict] = []
342
+ if not os.path.exists(path):
343
+ return rows
344
+ try:
345
+ with open(path, "r", encoding="utf-8") as f:
346
+ for line in f:
347
+ line = line.strip()
348
+ if not line:
349
+ continue
350
+ try:
351
+ rows.append(__import__("json").loads(line))
352
+ except Exception:
353
+ continue
354
+ except Exception as e:
355
+ logger.error("Failed reading manifest: %s", e)
356
+ return rows
357
+
358
+ def _write_manifest(rows: list[dict]) -> bool:
359
+ path = _manifest_path()
360
+ tmp_path = path + ".tmp"
361
+ try:
362
+ with open(tmp_path, "w", encoding="utf-8") as f:
363
+ for r in rows:
364
+ f.write(__import__("json").dumps(r) + "\n")
365
+ os.replace(tmp_path, path)
366
+ return True
367
+ except Exception as e:
368
+ logger.error("Failed writing manifest: %s", e)
369
+ try:
370
+ if os.path.exists(tmp_path):
371
+ os.remove(tmp_path)
372
+ except Exception:
373
+ pass
374
+ return False
375
+
376
+
377
+ @api_bp.route("/manifest", methods=["GET"])
378
+ def manifest_get():
379
+ rows = _read_manifest()
380
+ # minimal projection for UI: include keys asked by user, but pass through extra fields too
381
+ return jsonify(rows), 200
382
+
383
+
384
+ @api_bp.route("/manifest", methods=["PATCH"])
385
+ def manifest_patch():
386
+ payload = request.get_json(force=True) or {}
387
+ doc_id = payload.get("doc_id")
388
+ updates = payload.get("updates") or {}
389
+ if doc_id is None:
390
+ return jsonify({"error": "doc_id required"}), 400
391
+ try:
392
+ did = int(doc_id)
393
+ except Exception:
394
+ return jsonify({"error": "invalid doc_id"}), 400
395
+
396
+ # Fields not editable: doc_id, source_path
397
+ updates.pop("doc_id", None)
398
+ updates.pop("source_path", None)
399
+
400
+ rows = _read_manifest()
401
+ found = False
402
+ for r in rows:
403
+ try:
404
+ rid = int(str(r.get("doc_id")))
405
+ except Exception:
406
+ continue
407
+ if rid == did:
408
+ for k, v in updates.items():
409
+ r[k] = v
410
+ found = True
411
+ break
412
+ if not found:
413
+ return jsonify({"error": "doc not found"}), 404
414
+
415
+ if not _write_manifest(rows):
416
+ return jsonify({"error": "failed to persist manifest"}), 500
417
+
418
+ # Update DB metadata too
419
+ db_doc = update_document(did, updates)
420
+ if db_doc is None:
421
+ # Not fatal for manifest, but report
422
+ logger.error("update_document failed for doc_id=%s", did)
423
+
424
+ return jsonify({"ok": True}), 200
425
+
426
+
427
+ @api_bp.route("/manifest", methods=["DELETE"])
428
+ def manifest_delete():
429
+ payload = request.get_json(force=True) or {}
430
+ doc_id = payload.get("doc_id")
431
+ if doc_id is None:
432
+ return jsonify({"error": "doc_id required"}), 400
433
+ try:
434
+ did = int(doc_id)
435
+ except Exception:
436
+ return jsonify({"error": "invalid doc_id"}), 400
437
+
438
+ rows = _read_manifest()
439
+ new_rows: list[dict] = []
440
+ record: dict | None = None
441
+ for r in rows:
442
+ try:
443
+ rid = int(str(r.get("doc_id")))
444
+ except Exception:
445
+ new_rows.append(r)
446
+ continue
447
+ if rid == did:
448
+ record = r
449
+ continue
450
+ new_rows.append(r)
451
+
452
+ if record is None:
453
+ return jsonify({"error": "doc not found"}), 404
454
+
455
+ # Persist manifest removal
456
+ if not _write_manifest(new_rows):
457
+ return jsonify({"error": "failed to persist manifest"}), 500
458
+
459
+ # Delete from DB
460
+ try:
461
+ delete_document(did)
462
+ except Exception as e:
463
+ logger.error("Failed deleting document %s from DB: %s", did, e)
464
+
465
+ # Delete files from corpus_raw and corpus_clean
466
+ for key in ("source_path", "clean_path"):
467
+ p = record.get(key)
468
+ if p and isinstance(p, str):
469
+ try:
470
+ if os.path.exists(p):
471
+ os.remove(p)
472
+ except Exception as e:
473
+ logger.error("Failed removing %s: %s", p, e)
474
+
475
+ return jsonify({"ok": True}), 200
476
+
477
+
478
+ @api_bp.route("/raw/<path:subpath>", methods=["GET"])
479
+ def serve_raw(subpath: str):
480
+ # Serve files from /data/corpus_raw for clicking source_path links in UI
481
+ # To use, ensure source_path links are constructed as /api/raw/<relative to RAW_PREFIX>
482
+ abs_path = os.path.join(RAW_PREFIX, "")
483
+ return send_from_directory(abs_path, subpath, as_attachment=False)
static/manifest.html CHANGED
@@ -79,7 +79,7 @@
79
  <div class="shell">
80
  <div class="panel">
81
  <h1>Global Manifest</h1>
82
- <p class="sub">Viewing combined <code>manifest/manifest.jsonl</code> from bucket <code>tech-trans-rag-bucket</code>. Columns represent extracted / enriched metadata for all documents. Client-side filter works across all loaded rows.</p>
83
  <form id="filterForm" class="query" autocomplete="off" style="margin-bottom:10px;">
84
  <div>
85
  <label for="filter">Text Filter</label>
@@ -117,11 +117,12 @@
117
  const clearBtn = document.getElementById('clearBtn');
118
  const manifestTableWrapper = document.getElementById('manifestTableWrapper');
119
  const rowCountEl = document.getElementById('rowCount');
120
- let manifestRows = [];
121
  const PAGE_SIZE = 25;
122
  let currentPage = 1;
123
  let sortCol = 'doc_id';
124
  let sortDir = 'asc'; // 'asc' | 'desc'
 
125
 
126
  // Pagination elements
127
  const paginationEl = document.getElementById('pagination');
@@ -220,25 +221,41 @@
220
  const rows = sortRows(filteredRows());
221
  rowCountEl.textContent = rows.length;
222
  if(!rows.length){ manifestTableWrapper.innerHTML = '<div class="empty">No entries match.</div>'; paginationEl.style.display='none'; return; }
223
- const cols = ["doc_id","title","doc_type","jurisdiction","governing_law","party_roles","industry","effective_date","source_path"];
224
  const pageRows = paginate(rows);
225
  let html = '<table class="data-table"><thead><tr>' + buildHeader(cols) + '</tr></thead><tbody>';
226
  html += pageRows.map(r => {
227
  const rid = esc(r.doc_id);
228
  let tds = cols.map(c => {
 
 
 
229
  let val = r[c];
230
  if(val == null) val = '';
231
  let full = String(val);
232
  let display = full;
233
  if(display.length > 160) display = display.slice(0,160)+'…';
234
- const nonEditable = (c === 'doc_id' || c === 'source_path');
235
  const cls = [display!==full?'truncate':'', nonEditable?'':'editable'].filter(Boolean).join(' ');
236
- const content = (c === 'source_path' && val)
237
- ? `<a href="${esc(val)}" target="_blank" rel="noopener noreferrer">${esc(display)}</a>`
238
- : esc(display);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
239
  return `<td data-col="${esc(c)}" data-doc="${rid}" class="${cls}" title="${esc(full)}">${content}</td>`;
240
  }).join('');
241
- // Actions placeholder cell appended
242
  return `<tr data-doc="${rid}">${tds}</tr>`;
243
  }).join('');
244
  html += '</tbody></table>';
@@ -277,83 +294,47 @@
277
  lastPageBtn.addEventListener('click', () => { const rows = filteredRows(); currentPage = Math.max(1, Math.ceil(rows.length / PAGE_SIZE)); renderTable(); });
278
 
279
  function attachEditing(){
 
280
  manifestTableWrapper.querySelectorAll('td.editable').forEach(td => {
281
- td.addEventListener('click', () => beginEdit(td));
 
 
 
 
 
 
 
 
 
 
 
 
 
282
  });
283
  }
284
 
285
- function beginEdit(td){
286
  const tr = td.closest('tr');
287
- if(tr.classList.contains('editing')) return; // one edit at a time per row
288
- tr.classList.add('editing');
289
  const docId = tr.getAttribute('data-doc');
290
- const originalValues = {};
291
- tr.querySelectorAll('td').forEach(cell => {
292
- const col = cell.getAttribute('data-col');
293
- if(!col) return;
294
- originalValues[col] = cell.getAttribute('title') || cell.textContent || '';
295
- });
296
- tr.dataset.original = JSON.stringify(originalValues);
297
-
298
- // Make each editable cell an input
299
- tr.querySelectorAll('td.editable').forEach(cell => {
300
- const col = cell.getAttribute('data-col');
301
- const val = originalValues[col];
302
- cell.innerHTML = `<input type="text" style="width:100%;background:#16232d;border:1px solid #4a6578;color:#fff;font-size:.65rem;padding:4px 6px;border-radius:4px;" value="${esc(val)}" />`;
303
- });
304
-
305
- // Append action buttons row-end: we'll add a new td spanning? Simpler: insert after last cell.
306
- const colsCount = tr.querySelectorAll('td').length;
307
- const actionsTd = document.createElement('td');
308
- actionsTd.innerHTML = `<div class="row-actions"><button class="confirm">Save</button><button class="cancel">Cancel</button></div>`;
309
- tr.appendChild(actionsTd);
310
-
311
- actionsTd.querySelector('.confirm').addEventListener('click', () => confirmEdit(tr, docId));
312
- actionsTd.querySelector('.cancel').addEventListener('click', () => cancelEdit(tr));
313
  }
314
 
315
- function cancelEdit(tr){
316
- const orig = tr.dataset.original ? JSON.parse(tr.dataset.original) : {};
317
- tr.innerHTML = '';
318
- const cols = ["doc_id","title","doc_type","jurisdiction","governing_law","party_roles","industry","effective_date","source_path"];
319
- cols.forEach(c => {
320
- const val = orig[c] ?? '';
321
- const nonEditable = (c === 'doc_id' || c === 'source_path');
322
- const display = val.length>160?val.slice(0,160)+'…':val;
323
- const cls = [display!==val?'truncate':'', nonEditable?'':'editable'].filter(Boolean).join(' ');
324
- const td = document.createElement('td');
325
- td.setAttribute('data-col', c);
326
- td.setAttribute('title', val);
327
- td.className = cls;
328
- if (c === 'source_path' && val) {
329
- td.innerHTML = `<a href="${esc(val)}" target="_blank" rel="noopener noreferrer">${esc(display)}</a>`;
330
- } else {
331
- td.textContent = display;
332
- }
333
- tr.appendChild(td);
334
- });
335
- tr.classList.remove('editing');
336
- attachEditing();
337
  }
338
 
339
- function confirmEdit(tr, docId){
340
- const orig = tr.dataset.original ? JSON.parse(tr.dataset.original) : {};
341
- const updates = {};
342
- tr.querySelectorAll('td').forEach(cell => {
343
- const col = cell.getAttribute('data-col');
344
- if(!col || col==='doc_id' || col==='source_path') return;
345
- const input = cell.querySelector('input');
346
- if(!input) return;
347
- const newVal = input.value.trim();
348
- if(orig[col] !== newVal){
349
- updates[col] = newVal;
350
- }
351
- });
352
- if(Object.keys(updates).length === 0){
353
- cancelEdit(tr);
354
- return;
355
- }
356
- // Persist
357
  setStatus('Saving…');
358
  fetch('/api/manifest', {
359
  method: 'PATCH',
@@ -361,30 +342,30 @@
361
  body: JSON.stringify({ doc_id: docId, updates })
362
  }).then(r => r.json().then(j => ({ ok: r.ok, data: j })))
363
  .then(res => {
364
- if(!res.ok){
365
- setStatus(res.data.error || 'Save failed', true);
366
- return;
367
- }
368
- // Update manifestRows entry
369
  const rec = manifestRows.find(r => String(r.doc_id) === String(docId));
370
- if(rec){ Object.entries(updates).forEach(([k,v]) => rec[k] = v); }
371
  setStatus('Saved.');
372
- cancelEdit(tr); // rebuild row from updated values
373
- // Re-apply updates for row display
374
- const rebuilt = manifestRows.find(r => String(r.doc_id) === String(docId));
375
- if(rebuilt){
376
- tr.querySelectorAll('td').forEach(td => {
377
- const col = td.getAttribute('data-col');
378
- if(!col) return;
379
- const val = rebuilt[col] ?? '';
380
- td.title = val;
381
- td.textContent = val.length>160?val.slice(0,160)+'…':val;
382
- });
383
- }
 
 
 
 
 
 
384
  })
385
- .catch(err => {
386
- setStatus('Save error: '+ err.message, true);
387
- });
388
  }
389
 
390
  // Initial load
 
79
  <div class="shell">
80
  <div class="panel">
81
  <h1>Global Manifest</h1>
82
+ <p class="sub">Viewing stored documents manifest, available at <code>/data/manifest/manifest.jsonl</code>. Columns represent extracted / enriched metadata for all documents.</p>
83
  <form id="filterForm" class="query" autocomplete="off" style="margin-bottom:10px;">
84
  <div>
85
  <label for="filter">Text Filter</label>
 
117
  const clearBtn = document.getElementById('clearBtn');
118
  const manifestTableWrapper = document.getElementById('manifestTableWrapper');
119
  const rowCountEl = document.getElementById('rowCount');
120
+ let manifestRows = [];
121
  const PAGE_SIZE = 25;
122
  let currentPage = 1;
123
  let sortCol = 'doc_id';
124
  let sortDir = 'asc'; // 'asc' | 'desc'
125
+ let editing = { rowDocId: null, col: null };
126
 
127
  // Pagination elements
128
  const paginationEl = document.getElementById('pagination');
 
221
  const rows = sortRows(filteredRows());
222
  rowCountEl.textContent = rows.length;
223
  if(!rows.length){ manifestTableWrapper.innerHTML = '<div class="empty">No entries match.</div>'; paginationEl.style.display='none'; return; }
224
+ const cols = ["doc_id","source_path","title","doc_type","jurisdiction","governing_law","party_roles","industry","effective_date","actions"];
225
  const pageRows = paginate(rows);
226
  let html = '<table class="data-table"><thead><tr>' + buildHeader(cols) + '</tr></thead><tbody>';
227
  html += pageRows.map(r => {
228
  const rid = esc(r.doc_id);
229
  let tds = cols.map(c => {
230
+ if (c === 'actions') {
231
+ return `<td data-col="actions" data-doc="${rid}"><div class="row-actions"><button class="delete" data-doc="${rid}">Delete</button>${editing.rowDocId===String(r.doc_id)?`<button class="confirm">Save</button><button class="cancel">Cancel</button>`:''}</div></td>`;
232
+ }
233
  let val = r[c];
234
  if(val == null) val = '';
235
  let full = String(val);
236
  let display = full;
237
  if(display.length > 160) display = display.slice(0,160)+'…';
238
+ const nonEditable = (c === 'doc_id' || c === 'source_path' || c === 'actions');
239
  const cls = [display!==full?'truncate':'', nonEditable?'':'editable'].filter(Boolean).join(' ');
240
+ let content = esc(display);
241
+ if (c === 'source_path' && val) {
242
+ const rawPrefix = '/data/corpus_raw/';
243
+ let rel = '';
244
+ if (full.startsWith(rawPrefix)) rel = full.substring(rawPrefix.length);
245
+ else {
246
+ try {
247
+ const parts = full.split('/');
248
+ rel = parts.slice(parts.indexOf('corpus_raw')+1).join('/');
249
+ } catch { rel = full.split('/').pop(); }
250
+ }
251
+ const href = '/api/raw/' + encodeURI(rel);
252
+ content = `<a href="${href}" target="_blank" rel="noopener noreferrer">${esc(display)}</a>`;
253
+ }
254
+ if (editing.rowDocId===String(r.doc_id) && editing.col===c) {
255
+ content = `<input type="text" style="width:100%;background:#16232d;border:1px solid #4a6578;color:#fff;font-size:.65rem;padding:4px 6px;border-radius:4px;" value="${esc(full)}" />`;
256
+ }
257
  return `<td data-col="${esc(c)}" data-doc="${rid}" class="${cls}" title="${esc(full)}">${content}</td>`;
258
  }).join('');
 
259
  return `<tr data-doc="${rid}">${tds}</tr>`;
260
  }).join('');
261
  html += '</tbody></table>';
 
294
  lastPageBtn.addEventListener('click', () => { const rows = filteredRows(); currentPage = Math.max(1, Math.ceil(rows.length / PAGE_SIZE)); renderTable(); });
295
 
296
  function attachEditing(){
297
+ // cell editing
298
  manifestTableWrapper.querySelectorAll('td.editable').forEach(td => {
299
+ td.addEventListener('click', () => beginCellEdit(td));
300
+ });
301
+ // delete handlers
302
+ manifestTableWrapper.querySelectorAll('button.delete').forEach(btn => {
303
+ btn.addEventListener('click', () => doDelete(btn.getAttribute('data-doc')));
304
+ });
305
+ // save/cancel handlers if visible
306
+ manifestTableWrapper.querySelectorAll('tr').forEach(tr => {
307
+ const rid = tr.getAttribute('data-doc');
308
+ if (!rid) return;
309
+ const confirmBtn = tr.querySelector('button.confirm');
310
+ const cancelBtn = tr.querySelector('button.cancel');
311
+ if (confirmBtn) confirmBtn.addEventListener('click', () => confirmCellEdit(rid));
312
+ if (cancelBtn) cancelBtn.addEventListener('click', cancelCellEdit);
313
  });
314
  }
315
 
316
+ function beginCellEdit(td){
317
  const tr = td.closest('tr');
 
 
318
  const docId = tr.getAttribute('data-doc');
319
+ const col = td.getAttribute('data-col');
320
+ if (!col || col==='doc_id' || col==='source_path' || col==='actions') return;
321
+ // Only one at a time
322
+ editing = { rowDocId: String(docId), col };
323
+ renderTable();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
324
  }
325
 
326
+ function cancelCellEdit(){
327
+ editing = { rowDocId: null, col: null };
328
+ renderTable();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
329
  }
330
 
331
+ function confirmCellEdit(docId){
332
+ const row = manifestTableWrapper.querySelector(`tr[data-doc="${CSS.escape(docId)}"]`);
333
+ if (!row) return;
334
+ const cell = row.querySelector(`td[data-col="${CSS.escape(editing.col)}"] input`);
335
+ if (!cell) { cancelCellEdit(); return; }
336
+ const newVal = cell.value.trim();
337
+ const updates = { [editing.col]: newVal };
 
 
 
 
 
 
 
 
 
 
 
338
  setStatus('Saving…');
339
  fetch('/api/manifest', {
340
  method: 'PATCH',
 
342
  body: JSON.stringify({ doc_id: docId, updates })
343
  }).then(r => r.json().then(j => ({ ok: r.ok, data: j })))
344
  .then(res => {
345
+ if(!res.ok){ setStatus(res.data.error || 'Save failed', true); return; }
 
 
 
 
346
  const rec = manifestRows.find(r => String(r.doc_id) === String(docId));
347
+ if(rec){ rec[editing.col] = newVal; }
348
  setStatus('Saved.');
349
+ cancelCellEdit();
350
+ })
351
+ .catch(err => setStatus('Save error: '+ err.message, true));
352
+ }
353
+
354
+ function doDelete(docId){
355
+ if (!confirm('Delete document '+docId+'? This cannot be undone.')) return;
356
+ setStatus('Deleting…');
357
+ fetch('/api/manifest', {
358
+ method: 'DELETE',
359
+ headers: { 'Content-Type': 'application/json' },
360
+ body: JSON.stringify({ doc_id: docId })
361
+ }).then(r => r.json().then(j => ({ ok: r.ok, data: j })))
362
+ .then(res => {
363
+ if(!res.ok){ setStatus(res.data.error || 'Delete failed', true); return; }
364
+ manifestRows = manifestRows.filter(r => String(r.doc_id) !== String(docId));
365
+ setStatus('Deleted.');
366
+ renderTable();
367
  })
368
+ .catch(err => setStatus('Delete error: ' + err.message, true));
 
 
369
  }
370
 
371
  // Initial load