phaethon-order commited on
Commit
fc3bf2a
·
unverified ·
1 Parent(s): 6f0b158

Add manifest viewer and document upload pages

Browse files

- Implemented a new manifest viewer in `manifest.html` to display and filter document metadata.
- Added pagination, sorting, and editing capabilities for manifest entries.
- Created an upload interface in `upload.html` for technology transactions documents with drag-and-drop support.
- Included file validation, progress tracking, and user feedback for uploads.

.DS_Store ADDED
Binary file (6.15 kB). View file
 
Dockerfile ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Use a slim Python image (matches local development Python 3.13 artifacts)
2
+ FROM python:3.13-slim AS builder
3
+
4
+ # Metadata
5
+ LABEL maintainer="techtrans <no-reply@example.com>"
6
+
7
+ # Environment - Optimized for Cloud Run and Cloud Logging
8
+ ENV PYTHONDONTWRITEBYTECODE=1 \
9
+ PYTHONUNBUFFERED=1 \
10
+ PIP_DISABLE_PIP_VERSION_CHECK=1 \
11
+ PORT=8080 \
12
+ LOG_TO_CLOUD=true \
13
+ GOOGLE_CLOUD_PROJECT="tech-trans-rag" \
14
+ PYTHONPATH=/app
15
+
16
+ WORKDIR /app
17
+
18
+ # Install system dependencies required by some Python packages (Tesseract for OCR, libs for images/PDFs)
19
+ RUN apt-get update \
20
+ && apt-get install -y --no-install-recommends \
21
+ build-essential \
22
+ tesseract-ocr \
23
+ poppler-utils \
24
+ libgl1 \
25
+ wget \
26
+ ca-certificates \
27
+ git \
28
+ && rm -rf /var/lib/apt/lists/*
29
+
30
+ # Copy requirements first to leverage Docker cache
31
+ COPY requirements.txt .
32
+
33
+ # Install Python dependencies (include gunicorn for production)
34
+ RUN pip wheel --no-cache-dir --wheel-dir /wheels -r requirements.txt
35
+
36
+ FROM python:3.13-slim
37
+
38
+ ENV PYTHONDONTWRITEBYTECODE=1 \
39
+ PYTHONUNBUFFERED=1 \
40
+ PIP_DISABLE_PIP_VERSION_CHECK=1 \
41
+ PORT=8080 \
42
+ LOG_TO_CLOUD=true \
43
+ GOOGLE_CLOUD_PROJECT="tech-trans-rag"
44
+
45
+ WORKDIR /app
46
+
47
+ RUN apt-get update \
48
+ && apt-get install -y --no-install-recommends \
49
+ tesseract-ocr \
50
+ poppler-utils \
51
+ libgl1 \
52
+ wget \
53
+ ca-certificates \
54
+ git \
55
+ && rm -rf /var/lib/apt/lists/*
56
+
57
+ COPY --from=builder /wheels /wheels
58
+ RUN pip install --no-cache /wheels/*
59
+
60
+ COPY . .
61
+
62
+ CMD ["bash", "-lc", "exec gunicorn 'app:create_app()' --bind 0.0.0.0:${PORT} --workers ${WEB_CONCURRENCY:-2} --threads ${GUNICORN_THREADS:-8} --timeout ${GUNICORN_TIMEOUT:-1200} --access-logfile - --error-logfile -"]
LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Alex S. Osterlind
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
app.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask
2
+ from flask_cors import CORS
3
+ from infrastructure.logger import setup_logger
4
+ from routes.web import web_bp
5
+ from routes.api import api_bp
6
+ import infrastructure.database as db
7
+
8
+
9
+ setup_logger()
10
+
11
+ def create_app():
12
+ app = Flask(__name__, template_folder='static')
13
+ CORS(app)
14
+ app.config.from_object('config.Config')
15
+
16
+ app.register_blueprint(web_bp)
17
+ app.register_blueprint(api_bp)
18
+
19
+ with app.app_context():
20
+ db.init_db()
21
+
22
+ return app
23
+
24
+ if __name__ == "__main__":
25
+ app = create_app()
26
+ app.run(host="0.0.0.0", port=8080)
config.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dotenv import load_dotenv
2
+ import os
3
+ from flask import current_app, has_app_context
4
+
5
+ load_dotenv()
6
+
7
+ class Config:
8
+ SECRET_KEY = os.getenv("SECRET_KEY")
9
+ EMBEDDING_MODEL = os.getenv("EMBEDDING_MODEL")
10
+ CHAT_MODEL = os.getenv("CHAT_MODEL")
11
+ OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
12
+ CLAUDE_KEY = os.getenv("CLAUDE_KEY")
13
+ OPENAI_BASE_URL = os.getenv("OPENAI_BASE_URL")
14
+ MAX_CONTEXT_LENGTH = os.getenv("MAX_CONTEXT_LENGTH")
15
+ TOP_K_RESULTS = os.getenv("TOP_K_RESULTS")
16
+ MAX_QUERY_LENGTH = os.getenv("MAX_QUERY_LENGTH")
17
+ REQUEST_TIMEOUT = os.getenv("REQUEST_TIMEOUT")
18
+ UPLOAD_FOLDER = os.getenv("UPLOAD_FOLDER", "gs://tx-rag-corpus/corpus_raw")
19
+ CLEAN_FOLDER = os.getenv("CLEAN_FOLDER", "gs://tx-rag-corpus/corpus_clean")
20
+ METADATA_FOLDER = os.getenv("METADATA_FOLDER", "gs://tx-rag-corpus/manifest")
21
+ CHUNKS_FOLDER = os.getenv("CHUNKS_FOLDER", "gs://tx-rag-corpus/chunks")
22
+ DB_PATH = os.getenv("DB_PATH", "gs://tx-rag-corpus/app.db")
23
+ DB_NAME = os.getenv("DB_NAME", "appdb")
24
+ DB_USER = os.getenv("DB_USER", "appuser")
25
+ DB_PASSWORD = os.getenv("DB_PASSWORD", "appuser")
26
+ DB_HOST = os.getenv("DB_HOST", "10.25.1.3")
27
+ DB_PORT = os.getenv("DB_PORT", "5432")
28
+ CLOUD_SQL_CONNECTION_NAME = os.getenv("CLOUD_SQL_CONNECTION_NAME", "tech-trans-rag:us-west2:tx-rag-pg")
29
+ DB_IAM_AUTH=os.getenv("DB_IAM_AUTH", "False").lower() in ("true", "1", "t")
30
+ DB_USE_CONNECTOR=os.getenv("DB_USE_CONNECTOR", "False").lower() in ("true", "1", "t")
31
+ VERTEX_PROJECT_ID = os.getenv("VERTEX_PROJECT_ID", "tech-trans-rag")
32
+ VERTEX_LOCATION = os.getenv("VERTEX_LOCATION", "us-west2")
33
+ VERTEX_INDEX_ENDPOINT_ID = os.getenv("VERTEX_INDEX_ENDPOINT_ID", "6972425444192681984")
34
+ VERTEX_INDEX_ID = os.getenv("VERTEX_INDEX_ID", "9085431706080509952")
35
+ VERTEX_DEPLOYED_INDEX_ID = os.getenv("VERTEX_DEPLOYED_INDEX_ID", "chunks_deployed")
36
+
37
+ def cfg(key, default=None, cast=lambda x: x):
38
+ val = current_app.config.get(key) if has_app_context() else None
39
+ if val is None:
40
+ val = os.getenv(key, default)
41
+ return cast(val) if val is not None else val
infrastructure/chunker.py ADDED
@@ -0,0 +1,405 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Utilities for segmenting plain-text documents into database chunks.
2
+
3
+ Currently provides a single public helper `chunk_doc` that:
4
+
5
+ 1. Reads a cleaned `.txt` file (already extracted & normalized elsewhere).
6
+ 2. Splits it into pages (form-feed ``\f`` boundaries) and paragraphs.
7
+ 3. Aggregates paragraphs into size‑bounded chunks with optional character overlap.
8
+ 4. Persists each chunk using `infrastructure.database.persist_chunk`.
9
+
10
+ Design notes:
11
+ * Chunk sizing is character based (not tokens) to avoid extra deps.
12
+ * Overlap helps preserve context across boundaries (default 150 chars).
13
+ * Each chunk records page_start / page_end (1-based indices of the spanned pages).
14
+ * A very small heuristic attempts to derive a section label from the first
15
+ non-empty line that looks like a heading (ALL CAPS or Title Case and short).
16
+ * Idempotency: `persist_chunk` REPLACE logic + hash-derived chunk_id prevents
17
+ uncontrolled duplication if the same text is reprocessed.
18
+
19
+ Future improvements (not required now):
20
+ * Token-based sizing using a tokenizer (e.g., tiktoken) when available.
21
+ * Heading detection via regex / numbering patterns (e.g., 1., 1.1, Section 2).
22
+ * Optional semantic boundary preservation (sentence splitter).
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ from typing import List, Tuple, Optional, Dict, Any, Iterable
28
+ import os
29
+ import re
30
+ import json
31
+ from openai import OpenAI
32
+ from .logger import get_logger
33
+ from .embeddings import get_chroma_collection
34
+ from .database import add_chunk, get_max_chunk_id
35
+
36
+
37
+ try: # Avoid hard import failure if heavy deps (openai, fitz) not installed during chunk-only operations
38
+ from .document_processor import normalize # type: ignore
39
+ except Exception: # pragma: no cover - fallback path
40
+ def normalize(s: str) -> str: # minimal fallback
41
+ s = s.replace("\r\n", "\n").replace("\r", "\n")
42
+ s = re.sub(r"\n{3,}", "\n\n", s)
43
+ return s
44
+
45
+ logger = get_logger()
46
+
47
+ API_KEY = os.getenv("OPENAI_API_KEY", "")
48
+
49
+ API_KEY = os.getenv("OPENAI_API_KEY")
50
+ PROJECT_ID = os.getenv("VERTEX_PROJECT_ID", "tech-trans-rag")
51
+ GCS_BUCKET = os.getenv("GCS_BUCKET", "tech-trans-rag-bucket")
52
+ MANIFEST_DOC = os.getenv("MANIFEST_DOC", "manifest/manifest.jsonl")
53
+ CHUNKS_DOC = os.getenv("CHUNKS_DOC", "chunks/chunks.jsonl")
54
+
55
+
56
+ def _split_pages(text: str) -> List[str]:
57
+ """Split text into pages on form-feed markers inserted during PDF extraction.
58
+
59
+ If no form feed exists, the entire text is a single page.
60
+ """
61
+ if "\f" not in text:
62
+ return [text]
63
+ # Allow light whitespace around form-feed separator pattern used in extraction
64
+ parts = re.split(r"\n*\f\n*", text)
65
+ return [p.strip() for p in parts if p.strip()]
66
+
67
+
68
+ def _paragraphs(page_text: str) -> List[str]:
69
+ """Return logical paragraphs (double-newline or blank-line separated)."""
70
+ paras = re.split(r"\n{2,}", page_text)
71
+ return [p.strip() for p in paras if p.strip()]
72
+
73
+
74
+ def _chunk_paragraphs(paragraphs: List[Tuple[int, str]], max_chars: int, overlap: int) -> List[Tuple[str, int, int]]:
75
+ """Aggregate (page_index, paragraph_text) into sized chunks.
76
+
77
+ Returns list of (chunk_text, page_start, page_end).
78
+ Overlap is applied on character basis between consecutive chunks.
79
+ """
80
+ chunks: List[Tuple[str, int, int]] = []
81
+ buf: List[str] = []
82
+ buf_pages: List[int] = []
83
+ current_len = 0
84
+ last_tail = ""
85
+
86
+ for page_idx, para in paragraphs:
87
+ para_len = len(para)
88
+ if current_len and current_len + para_len + 2 > max_chars:
89
+ # Flush current buffer
90
+ chunk_text = "\n\n".join(buf).strip()
91
+ if chunk_text:
92
+ chunks.append((chunk_text, min(buf_pages), max(buf_pages)))
93
+ # Prepare overlap tail
94
+ last_tail = chunk_text[-overlap:] if overlap > 0 else ""
95
+ buf, buf_pages = [], []
96
+ current_len = 0
97
+ # Add overlap to new buffer if starting fresh and have tail
98
+ if not buf and last_tail:
99
+ buf.append(last_tail)
100
+ buf_pages.append(page_idx) # associate with current page for simplicity
101
+ current_len = len(last_tail)
102
+ buf.append(para)
103
+ buf_pages.append(page_idx)
104
+ current_len += para_len + 2 # account for join newlines
105
+
106
+ # Final flush
107
+ if buf:
108
+ chunk_text = "\n\n".join(buf).strip()
109
+ if chunk_text:
110
+ chunks.append((chunk_text, min(buf_pages), max(buf_pages)))
111
+ return chunks
112
+
113
+
114
+ try: # Optional tokenizer (tiktoken) for accurate token counts
115
+ import tiktoken # type: ignore
116
+ _TT_ENC = tiktoken.get_encoding("cl100k_base")
117
+ def _encode_tokens(text: str) -> List[int]:
118
+ return _TT_ENC.encode(text) # type: ignore[union-attr]
119
+ def _decode_tokens(tokens: List[int]) -> str:
120
+ return _TT_ENC.decode(tokens) # type: ignore[union-attr]
121
+ TOKENIZER_NAME = "cl100k_base"
122
+ except Exception: # pragma: no cover
123
+ _TT_ENC = None # type: ignore
124
+ _FALLBACK_VOCAB: Dict[str, int] = {}
125
+ _FALLBACK_ID2WORD: Dict[int, str] = {}
126
+ def _encode_tokens(text: str) -> List[int]: # fallback naive whitespace word -> int mapping
127
+ tokens: List[int] = []
128
+ for w in re.findall(r"\S+", text):
129
+ if w not in _FALLBACK_VOCAB:
130
+ idx = len(_FALLBACK_VOCAB) + 1
131
+ _FALLBACK_VOCAB[w] = idx
132
+ _FALLBACK_ID2WORD[idx] = w
133
+ tokens.append(_FALLBACK_VOCAB[w])
134
+ return tokens
135
+ def _decode_tokens(tokens: List[int]) -> str:
136
+ return " ".join(_FALLBACK_ID2WORD.get(t, "") for t in tokens).strip()
137
+ TOKENIZER_NAME = "fallback_simple_vocab"
138
+
139
+
140
+ def _split_large_paragraph_tokens(tokens: List[int], max_tokens: int) -> Iterable[List[int]]:
141
+ for i in range(0, len(tokens), max_tokens):
142
+ yield tokens[i:i+max_tokens]
143
+
144
+
145
+ def _chunk_paragraphs_tokens(paragraphs: List[Tuple[int, str]], max_tokens: int, overlap_tokens: int) -> List[Tuple[str, int, int]]:
146
+ """Token-based chunk aggregation.
147
+
148
+ paragraphs: list of (page_index, text)
149
+ Returns list of (chunk_text, page_start, page_end)
150
+ """
151
+ # Pre-tokenize paragraphs (cache by object id / value) to avoid repeats
152
+ tokenized: List[Tuple[int, List[int], str]] = [] # (page_idx, token_ids, original_text)
153
+ for page_idx, para in paragraphs:
154
+ toks = _encode_tokens(para)
155
+ # If single para exceeds max_tokens, split hard
156
+ if len(toks) > max_tokens:
157
+ for slice_tokens in _split_large_paragraph_tokens(toks, max_tokens):
158
+ tokenized.append((page_idx, list(slice_tokens), _decode_tokens(list(slice_tokens))))
159
+ else:
160
+ tokenized.append((page_idx, toks, para))
161
+
162
+ chunks: List[Tuple[str, int, int]] = []
163
+ buf_tokens: List[int] = []
164
+ buf_pages: List[int] = []
165
+ tail_tokens: List[int] = []
166
+
167
+ for page_idx, toks, original in tokenized:
168
+ needed = len(toks)
169
+ if buf_tokens and (len(buf_tokens) + needed) > max_tokens:
170
+ # Flush current
171
+ chunk_text = _decode_tokens(buf_tokens).strip()
172
+ if chunk_text:
173
+ chunks.append((chunk_text, min(buf_pages), max(buf_pages)))
174
+ tail_tokens = buf_tokens[-overlap_tokens:] if overlap_tokens > 0 else []
175
+ buf_tokens, buf_pages = [], []
176
+ if not buf_tokens and tail_tokens:
177
+ buf_tokens.extend(tail_tokens)
178
+ buf_pages.append(page_idx)
179
+ buf_tokens.extend(toks)
180
+ buf_pages.append(page_idx)
181
+
182
+ if buf_tokens:
183
+ chunk_text = _decode_tokens(buf_tokens).strip()
184
+ if chunk_text:
185
+ chunks.append((chunk_text, min(buf_pages), max(buf_pages)))
186
+ return chunks
187
+
188
+ def get_chunk_info(text: str, chunk_text: str) -> Dict[str, Optional[str]]:
189
+
190
+ try:
191
+ client = OpenAI(api_key=API_KEY)
192
+ prompt = (
193
+ f"""
194
+ Examine the attached technology transactions document and the chunk taken from the document then identify respective values for each of the following keys: section_number (section(s), including subsection(s) and/or paragraph(s), applicable to the chunk), section_title (title, header, subheader, etc. applicable to this chunk), clause_type (the type(s) of clause(s) captured in this chunk), path (the section, including subsection(s) or paragraph(s) to the section_number for this chunk -- e.g., if section_number is 9.2(b) for the chunk, the path would be 9 → 9.2 → 9.2(b)), numbers_present (if this chunk includes a section_number in the chunk_text), and definition_terms (a list of all defined terms in this chunk). Consider the substantive meaning of words (e.g., "Page 1 of 12" is not likely to be the clause_type), placement in the document, surrounding text, applicable section, and any other factors that might inform your decision.
195
+ Return a response in following JSON format only:
196
+ {{
197
+ "section_number": section_number,
198
+ "section_title": section_title,
199
+ "clause_type": clause_type,
200
+ "path": path,
201
+ "numbers_present": numbers_present,
202
+ "definition_terms": [definition_terms]
203
+ }}.
204
+ Do not return anything else outside of the JSON object. If you cannot identify a distinct value corresponding to one of the keys, respond with null for that key.
205
+ --- DOCUMENT TEXT START ---\n
206
+ {text}\n
207
+ --- DOCUMENT TEXT END ---\n\n
208
+ --- CHUNK TEXT START ---\n
209
+ {chunk_text}\n
210
+ --- CHUNK TEXT END ---
211
+ """
212
+ )
213
+
214
+ ai_model = "gpt-5-mini"
215
+
216
+ response = client.chat.completions.create(
217
+ model=ai_model,
218
+ messages=[
219
+ {"role": "system", "content": "Identify values for the following keys: section_number, section_title, clause_type, path, numbers_present, and definition_terms based on the following text.\n"},
220
+ {"role": "user", "content": prompt},
221
+ ]
222
+ )
223
+
224
+ response = response.choices[0].message.content if response.choices else []
225
+ logger.info(f"AI chunk raw response: {response}")
226
+ candidate = (response or [])
227
+ logger.info(f"AI chunk response: {candidate}")
228
+ expected_keys = [
229
+ "section_number",
230
+ "section_title",
231
+ "clause_type",
232
+ "path",
233
+ "numbers_present",
234
+ "definition_terms",
235
+ ]
236
+
237
+ data = {}
238
+ if isinstance(candidate, dict):
239
+ data = candidate
240
+ elif isinstance(candidate, str):
241
+ try:
242
+ data = json.loads(candidate)
243
+ except Exception:
244
+ logger.warning("AI manifest response not valid JSON; returning defaults")
245
+ data = {}
246
+ else:
247
+ logger.warning("AI manifest response unexpected type %s", type(candidate))
248
+
249
+ # Build normalized manifest dict
250
+ manifest = {k: (data.get(k) if isinstance(data, dict) else None) for k in expected_keys}
251
+
252
+ # Coerce obvious placeholder / unknown strings to None
253
+ for k, v in manifest.items():
254
+ if isinstance(v, str) and v.strip().lower() in {"unknown", "null", "n/a", "none", ""}:
255
+ manifest[k] = None
256
+
257
+ return manifest
258
+
259
+ except Exception as e:
260
+ logger.error(f"Error extracting values from text: {e}")
261
+ return {}
262
+
263
+ def chunk_doc(text: str, doc_id: str, max_chars: int = 1200, overlap: int = 150, *, max_tokens: Optional[int] = None, token_overlap: Optional[int] = None) -> List[int]:
264
+ """Chunk a cleaned text file, persist chunks, metadata, embeddings, and index.
265
+
266
+ Returns list of chunk IDs.
267
+ """
268
+ # Validate modes
269
+ use_tokens = max_tokens is not None
270
+ if use_tokens:
271
+ if max_tokens is None or max_tokens <= 0:
272
+ raise ValueError("max_tokens must be positive when provided")
273
+ if token_overlap is None:
274
+ # default 12% of max_tokens capped at 200
275
+ token_overlap = min(max(0, int(max_tokens * 0.12)), 200)
276
+ if token_overlap < 0:
277
+ raise ValueError("token_overlap cannot be negative")
278
+ if token_overlap >= max_tokens:
279
+ logger.warning("token_overlap (%d) >= max_tokens (%d); reducing", token_overlap, max_tokens)
280
+ token_overlap = max(0, max_tokens // 5)
281
+ else:
282
+ if max_chars <= 0:
283
+ raise ValueError("max_chars must be positive")
284
+ if overlap < 0:
285
+ raise ValueError("overlap cannot be negative")
286
+ if overlap >= max_chars:
287
+ logger.warning("overlap (%d) >= max_chars (%d); reducing overlap", overlap, max_chars)
288
+ overlap = max(0, max_chars // 4) # soften
289
+
290
+
291
+ pages = _split_pages(text)
292
+ logger.info("Chunking doc_id=%s pages=%d (max_chars=%d overlap=%d)", doc_id, len(pages), max_chars, overlap)
293
+ doc_iden = doc_id # avoid shadowing
294
+ # Flatten paragraphs with page indices
295
+ para_with_pages: List[Tuple[int, str]] = []
296
+ for p_idx, page_text in enumerate(pages, start=1):
297
+ for para in _paragraphs(page_text):
298
+ para_with_pages.append((p_idx, para))
299
+
300
+ if not para_with_pages:
301
+ logger.warning("No paragraphs detected; using raw text as single chunk for %s", doc_id)
302
+ para_with_pages = [(1, text)]
303
+
304
+ if use_tokens:
305
+ chunk_specs = _chunk_paragraphs_tokens(para_with_pages, max_tokens=max_tokens, overlap_tokens=token_overlap or 0) # type: ignore[arg-type]
306
+ logger.info("Token chunking mode tokenizer=%s max_tokens=%s overlap_tokens=%s", TOKENIZER_NAME, max_tokens, token_overlap)
307
+ else:
308
+ chunk_specs = _chunk_paragraphs(para_with_pages, max_chars=max_chars, overlap=overlap)
309
+
310
+ chunk_ids: List[int] = []
311
+
312
+ chunk_metadata_records: List[Dict[str, Any]] = []
313
+
314
+ max_id = get_max_chunk_id()
315
+ start_chunk_id = max_id + 1
316
+
317
+ for idx, (chunk_text, page_s, page_e) in enumerate(chunk_specs):
318
+
319
+ chunk_data = get_chunk_info(text, chunk_text)
320
+ sec_number = chunk_data.get("section_number")
321
+ section_title = chunk_data.get("section_title")
322
+ clause_type = chunk_data.get("clause_type")
323
+ path = chunk_data.get("path")
324
+ numbers_present = chunk_data.get("numbers_present")
325
+ definition_terms = chunk_data.get("definition_terms")
326
+
327
+ chunk_id = start_chunk_id + idx
328
+
329
+ new_chunk = add_chunk(
330
+ doc_id=int(doc_iden),
331
+ chunk_id=chunk_id,
332
+ chunk_index=idx,
333
+ text=chunk_text,
334
+ page_start=page_s,
335
+ page_end=page_e,
336
+ section_number=sec_number,
337
+ section_title=section_title,
338
+ clause_type=clause_type,
339
+ )
340
+ logger.info("Persisted chunk %s (pages %d-%d) for doc_id=%s", chunk_id, page_s, page_e, doc_id)
341
+
342
+ chunk_ids.append(chunk_id)
343
+ logger.info(f"Chunk {chunk_id} info: {new_chunk}")
344
+
345
+ chunk_metadata_records.append({
346
+ 'id': chunk_id,
347
+ 'index': idx,
348
+ 'doc_id': doc_id,
349
+ 'section_number': sec_number,
350
+ 'section_title': section_title,
351
+ 'clause_type': clause_type,
352
+ 'path': path,
353
+ 'numbers_present': numbers_present,
354
+ 'definition_terms': definition_terms,
355
+ 'text': chunk_text,
356
+ 'metadata': None,
357
+ 'prev_id': None, # fill later
358
+ 'next_id': None, # fill later
359
+ })
360
+ logger.info("Chunk metadata record: %s", chunk_metadata_records[-1])
361
+
362
+ # Link prev/next
363
+ for i, rec in enumerate(chunk_metadata_records):
364
+ if i > 0:
365
+ rec['prev_id'] = chunk_metadata_records[i-1]['index']
366
+ if i < len(chunk_metadata_records) - 1:
367
+ rec['next_id'] = chunk_metadata_records[i+1]['index']
368
+
369
+ # Write / upsert JSONL file
370
+ os.makedirs(os.path.dirname(CHUNKS_DOC), exist_ok=True)
371
+ records = json.dumps(chunk_metadata_records, ensure_ascii=False, indent=0)
372
+
373
+ try:
374
+ with open(CHUNKS_DOC, "r+", encoding="utf-8") as f:
375
+ existing = f.read()
376
+ f.seek(0)
377
+ updated = existing + "\n" + records if existing else records
378
+ f.write(updated)
379
+ logger.info(f"Appended {len(chunk_metadata_records)} chunk records to existing chunks file {CHUNKS_DOC}")
380
+ except FileNotFoundError:
381
+ with open(CHUNKS_DOC, "w", encoding="utf-8") as f:
382
+ f.write(records)
383
+ logger.info(f"Created new chunks file with {len(chunk_metadata_records)} records as it did not exist")
384
+
385
+ chunk_texts = [spec[0] for spec in chunk_specs]
386
+ # Generate embeddings and upsert to ChromaDB
387
+ try:
388
+ collection = get_chroma_collection()
389
+ collection.add(
390
+ ids=[str(cid) for cid in chunk_ids],
391
+ documents=chunk_texts,
392
+ metadatas=[{k: v for k, v in rec.items() if k not in ['id', 'text', 'prev_id', 'next_id']} for rec in chunk_metadata_records]
393
+ )
394
+ logger.info('Upserted %d embeddings to ChromaDB for doc_id=%s', len(chunk_ids), doc_id)
395
+
396
+ except Exception as e: # pragma: no cover
397
+ logger.error('Embedding/indexing step failed for %s: %s', doc_id, e)
398
+
399
+
400
+ logger.info("Persisted %d chunks for doc_id=%s", len(chunk_ids), doc_id)
401
+ return chunk_ids
402
+
403
+
404
+ __all__ = ["chunk_doc"]
405
+
infrastructure/database.py ADDED
@@ -0,0 +1,349 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ChromaDB database layer.
3
+ """
4
+ import os
5
+ import contextlib
6
+ from datetime import datetime, timezone
7
+ from dataclasses import dataclass, field, fields
8
+ from typing import List, Optional, Dict, Any
9
+ import numpy as np
10
+
11
+ import chromadb
12
+ from chromadb.utils import embedding_functions
13
+
14
+ try:
15
+ from infrastructure.logger import get_logger # reuse central logger if available
16
+ _logger = get_logger()
17
+ except Exception: # pragma: no cover - fallback minimal logger
18
+ import logging as _logging
19
+ _logging.basicConfig(level=_logging.INFO)
20
+ _logger = _logging.getLogger("db")
21
+
22
+ # ---------------------------------------------------------------------------
23
+ # Versioning for corpus mechanics
24
+ # ---------------------------------------------------------------------------
25
+ TOK_VER = int(os.getenv("TOK_VER", "1"))
26
+ SEG_VER = int(os.getenv("SEG_VER", "1"))
27
+
28
+ # ---------------------------------------------------------------------------
29
+ # ChromaDB client setup
30
+ # ---------------------------------------------------------------------------
31
+ CHROMA_PATH = os.getenv("CHROMA_PATH", "chroma_db")
32
+ _client = chromadb.PersistentClient(path=CHROMA_PATH)
33
+
34
+ # Using a default embedding function for the collections, though we'll be providing our own embeddings.
35
+ # This is required by ChromaDB.
36
+ # The type hint for embedding_function is complex, and mypy has issues with it.
37
+ # Using type: ignore to suppress the error.
38
+ default_ef = embedding_functions.DefaultEmbeddingFunction()
39
+
40
+ _documents_collection = _client.get_or_create_collection(
41
+ name="documents",
42
+ embedding_function=default_ef # type: ignore
43
+ )
44
+ _chunks_collection = _client.get_or_create_collection(
45
+ name="chunks",
46
+ embedding_function=default_ef # type: ignore
47
+ )
48
+
49
+ # ---------------------------------------------------------------------------
50
+ # Data classes (replacing ORM)
51
+ # ---------------------------------------------------------------------------
52
+ @dataclass
53
+ class Document:
54
+ doc_id: int
55
+ sha256: str
56
+ title: Optional[str] = None
57
+ source_path: Optional[str] = None
58
+ created_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
59
+ doc_type: Optional[str] = None
60
+ jurisdiction: Optional[str] = None
61
+ governing_law: Optional[str] = None
62
+ party_roles: Optional[str] = None
63
+ industry: Optional[str] = None
64
+ effective_date: Optional[datetime] = None
65
+ chunks: List['Chunk'] = field(default_factory=list)
66
+
67
+ @classmethod
68
+ def from_chroma(cls, doc_id: int, metadata: Dict[str, Any]):
69
+ if metadata.get('effective_date') and isinstance(metadata['effective_date'], str):
70
+ metadata['effective_date'] = datetime.fromisoformat(metadata['effective_date'])
71
+ if metadata.get('created_at') and isinstance(metadata['created_at'], str):
72
+ metadata['created_at'] = datetime.fromisoformat(metadata['created_at'])
73
+
74
+ # Filter metadata to only include fields expected by the dataclass
75
+ known_fields = {f.name for f in fields(cls) if f.init}
76
+ filtered_metadata = {k: v for k, v in metadata.items() if k in known_fields}
77
+
78
+ return cls(doc_id=doc_id, **filtered_metadata)
79
+
80
+ @dataclass
81
+ class Chunk:
82
+ chunk_id: int
83
+ doc_id: int
84
+ chunk_index: int
85
+ text: str
86
+ token_count: Optional[int] = None
87
+ page_start: Optional[int] = None
88
+ page_end: Optional[int] = None
89
+ section_number: Optional[str] = None
90
+ section_title: Optional[str] = None
91
+ clause_type: Optional[str] = None
92
+ tok_ver: int = TOK_VER
93
+ seg_ver: int = SEG_VER
94
+ document: Optional[Document] = None
95
+ embedding: Optional['Embedding'] = None
96
+
97
+ @classmethod
98
+ def from_chroma(cls, chunk_id: int, metadata: Dict[str, Any], document_text: str):
99
+ metadata['text'] = document_text
100
+ known_fields = {f.name for f in fields(cls) if f.init}
101
+ filtered_metadata = {k: v for k, v in metadata.items() if k in known_fields}
102
+ return cls(chunk_id=chunk_id, **filtered_metadata)
103
+
104
+ @dataclass
105
+ class Embedding:
106
+ id: int
107
+ chunk_id: int
108
+ model: str
109
+ dim: int
110
+ vector: list[float]
111
+ chunk: Optional[Chunk] = None
112
+
113
+ # ---------------------------------------------------------------------------
114
+ # Public API
115
+ # ---------------------------------------------------------------------------
116
+ def init_db():
117
+ """Initializes ChromaDB collections."""
118
+ global _documents_collection, _chunks_collection
119
+ _documents_collection = _client.get_or_create_collection(name="documents", embedding_function=default_ef) # type: ignore
120
+ _chunks_collection = _client.get_or_create_collection(name="chunks", embedding_function=default_ef) # type: ignore
121
+ _logger.info("ChromaDB collections ensured.")
122
+
123
+ def get_session():
124
+ return None
125
+
126
+ def get_db():
127
+ return None
128
+
129
+ @contextlib.contextmanager
130
+ def session_scope():
131
+ """Provide a transactional scope (no-op for ChromaDB)."""
132
+ yield None
133
+
134
+ # --------------- CRUD ---------------
135
+ 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):
136
+ existing = _documents_collection.get(where={"sha256": sha256})
137
+ if existing['ids'] and existing['metadatas']:
138
+ doc_id = int(existing['ids'][0])
139
+ metadata = dict(existing['metadatas'][0])
140
+ _logger.info("Document with sha256 %s already exists (doc_id=%s); checking for metadata enrichment", sha256, doc_id)
141
+
142
+ updated = False
143
+ if doc_type and not metadata.get("doc_type"):
144
+ metadata["doc_type"] = doc_type
145
+ updated = True
146
+ if jurisdiction and not metadata.get("jurisdiction"):
147
+ metadata["jurisdiction"] = jurisdiction
148
+ updated = True
149
+ if industry and not metadata.get("industry"):
150
+ metadata["industry"] = industry
151
+ updated = True
152
+ if party_roles and not metadata.get("party_roles"):
153
+ metadata["party_roles"] = party_roles
154
+ updated = True
155
+ if governing_law and not metadata.get("governing_law"):
156
+ metadata["governing_law"] = governing_law
157
+ updated = True
158
+ if effective_date and not metadata.get("effective_date"):
159
+ metadata["effective_date"] = effective_date.isoformat()
160
+ updated = True
161
+
162
+ if updated:
163
+ _documents_collection.update(ids=[str(doc_id)], metadatas=[metadata])
164
+ _logger.info("Document metadata enriched for doc_id=%s", doc_id)
165
+
166
+ return Document.from_chroma(doc_id, metadata)
167
+
168
+ all_docs = _documents_collection.get(include=[])
169
+ max_id = 0
170
+ if all_docs['ids']:
171
+ max_id = max([int(i) for i in all_docs['ids']])
172
+ new_doc_id = max_id + 1
173
+
174
+ metadata = {
175
+ "sha256": sha256, "title": title, "source_path": source_path, "doc_type": doc_type,
176
+ "jurisdiction": jurisdiction, "industry": industry, "party_roles": party_roles,
177
+ "governing_law": governing_law, "created_at": datetime.now(timezone.utc).isoformat(),
178
+ "effective_date": effective_date.isoformat() if effective_date else None,
179
+ }
180
+ metadata = {k: v for k, v in metadata.items() if v is not None}
181
+
182
+ _documents_collection.add(ids=[str(new_doc_id)], metadatas=[metadata], documents=[title or ''])
183
+ return Document(doc_id=new_doc_id, **metadata)
184
+
185
+ def add_chunk(doc_id: int, chunk_id: int, text: str, chunk_index: int, token_count: int | None = None,
186
+ page_start: int | None = None, page_end: int | None = None, section_number: str | None = None,
187
+ section_title: str | None = None, clause_type: str | None = None, tok_ver: int = TOK_VER, seg_ver: int = SEG_VER):
188
+
189
+ metadata: Dict[str, Any] = {
190
+ "doc_id": doc_id, "chunk_index": chunk_index, "token_count": token_count,
191
+ "page_start": page_start, "page_end": page_end, "section_number": section_number,
192
+ "section_title": section_title, "clause_type": clause_type, "tok_ver": tok_ver, "seg_ver": seg_ver,
193
+ }
194
+ metadata = {k: v for k, v in metadata.items() if v is not None}
195
+
196
+ _chunks_collection.add(ids=[str(chunk_id)], documents=[text], metadatas=[metadata])
197
+ _logger.info("DB added chunk %s for doc_id=%s", chunk_id, doc_id)
198
+
199
+ return Chunk(chunk_id=chunk_id, doc_id=doc_id, text=text, chunk_index=chunk_index, **metadata)
200
+
201
+ def upsert_embedding(chunk_id: int, model: str, dim: int, vector_bytes: bytes):
202
+ vector = np.frombuffer(vector_bytes, dtype=np.float32).tolist()
203
+
204
+ existing_chunk = _chunks_collection.get(ids=[str(chunk_id)], include=["metadatas"])
205
+ if not existing_chunk['ids'] or not existing_chunk['metadatas']:
206
+ _logger.error(f"Cannot upsert embedding for non-existent chunk_id {chunk_id}")
207
+ return None
208
+
209
+ metadata = dict(existing_chunk['metadatas'][0])
210
+ metadata['embedding_model'] = model
211
+ metadata['embedding_dim'] = dim
212
+
213
+ _chunks_collection.update(ids=[str(chunk_id)], embeddings=[vector], metadatas=[metadata])
214
+
215
+ return Embedding(id=chunk_id, chunk_id=chunk_id, model=model, dim=dim, vector=vector)
216
+
217
+ def get_document(doc_id: int):
218
+ doc_data = _documents_collection.get(ids=[str(doc_id)])
219
+ if not doc_data['ids'] or not doc_data['metadatas']:
220
+ return None
221
+ return Document.from_chroma(doc_id, dict(doc_data['metadatas'][0]))
222
+
223
+ def get_document_by_sha(sha256: str):
224
+ doc_data = _documents_collection.get(where={"sha256": sha256})
225
+ if not doc_data['ids'] or not doc_data['metadatas']:
226
+ return None
227
+ doc_id = int(doc_data['ids'][0])
228
+ return Document.from_chroma(doc_id, dict(doc_data['metadatas'][0]))
229
+
230
+ def get_chunks_for_doc(doc_id: int):
231
+ chunk_data = _chunks_collection.get(where={"doc_id": doc_id})
232
+ if not chunk_data['ids'] or not chunk_data['metadatas'] or not chunk_data['documents']:
233
+ return []
234
+
235
+ chunks = [Chunk.from_chroma(int(cid), dict(meta), text) for cid, meta, text in zip(chunk_data['ids'], chunk_data['metadatas'], chunk_data['documents'])]
236
+ chunks.sort(key=lambda c: c.chunk_index)
237
+ return chunks
238
+
239
+ def get_chunks_by_ids(chunk_ids: list[int]):
240
+ if not chunk_ids:
241
+ return []
242
+ str_chunk_ids = [str(cid) for cid in chunk_ids]
243
+ chunk_data = _chunks_collection.get(ids=str_chunk_ids, include=["metadatas", "documents"])
244
+
245
+ chunks = []
246
+ doc_ids_to_fetch = set()
247
+
248
+ if chunk_data['ids'] and chunk_data['metadatas'] and chunk_data['documents']:
249
+ for i, chunk_id_str in enumerate(chunk_data['ids']):
250
+ metadata = chunk_data['metadatas'][i]
251
+ text = chunk_data['documents'][i]
252
+ chunk = Chunk.from_chroma(int(chunk_id_str), dict(metadata), text)
253
+ chunks.append(chunk)
254
+ if 'doc_id' in metadata:
255
+ doc_ids_to_fetch.add(metadata['doc_id'])
256
+
257
+ if doc_ids_to_fetch:
258
+ str_doc_ids = [str(did) for did in doc_ids_to_fetch]
259
+ docs_data = _documents_collection.get(ids=str_doc_ids)
260
+ if docs_data['ids'] and docs_data['metadatas']:
261
+ docs_map = {int(doc_id): Document.from_chroma(int(doc_id), dict(meta)) for doc_id, meta in zip(docs_data['ids'], docs_data['metadatas'])}
262
+
263
+ for chunk in chunks:
264
+ if chunk.doc_id in docs_map:
265
+ chunk.document = docs_map[chunk.doc_id]
266
+
267
+ return chunks
268
+
269
+ def get_documents(limit: int = 100, offset: int = 0):
270
+ all_docs_data = _documents_collection.get()
271
+ if not all_docs_data['ids'] or not all_docs_data['metadatas']:
272
+ return []
273
+ docs = [Document.from_chroma(int(id), dict(meta)) for id, meta in zip(all_docs_data['ids'], all_docs_data['metadatas'])]
274
+ docs.sort(key=lambda d: d.created_at, reverse=True)
275
+ return docs[offset : offset + limit]
276
+
277
+ def get_document_chunk_counts(doc_ids: list[int]) -> dict[int, int]:
278
+ if not doc_ids:
279
+ return {}
280
+
281
+ chunk_data = _chunks_collection.get(where={"doc_id": {"$in": doc_ids}}, include=['metadatas']) # type: ignore
282
+ counts = {doc_id: 0 for doc_id in doc_ids}
283
+ if chunk_data['metadatas']:
284
+ for meta in chunk_data['metadatas']:
285
+ doc_id = meta.get('doc_id')
286
+ if doc_id in counts:
287
+ counts[int(doc_id)] += 1
288
+ return counts
289
+
290
+ def get_all_chunks(limit: int = 200, offset: int = 0):
291
+ all_ids = _chunks_collection.get(include=[])['ids']
292
+ paginated_ids = sorted([int(i) for i in all_ids])[offset : offset + limit]
293
+
294
+ if not paginated_ids:
295
+ return []
296
+
297
+ chunks = get_chunks_by_ids(paginated_ids)
298
+ chunks.sort(key=lambda c: c.chunk_id)
299
+ return chunks
300
+
301
+ def get_max_chunk_id():
302
+ all_ids = _chunks_collection.get(include=[])['ids']
303
+ if not all_ids:
304
+ return -1
305
+ return max([int(i) for i in all_ids])
306
+
307
+ def get_embedding_for_chunk(chunk_id: int):
308
+ chunk_data = _chunks_collection.get(ids=[str(chunk_id)], include=["embeddings", "metadatas"])
309
+ if not chunk_data['ids'] or not chunk_data['embeddings'] or not chunk_data['embeddings'][0] or not chunk_data['metadatas']:
310
+ return None
311
+
312
+ vector = chunk_data['embeddings'][0]
313
+ meta = chunk_data['metadatas'][0]
314
+ model = str(meta.get('embedding_model', 'unknown'))
315
+ dim_val = meta.get('embedding_dim')
316
+ dim = int(dim_val) if dim_val is not None else (len(vector) if vector else 0)
317
+
318
+ float_vector = [float(v) for v in vector] if vector else []
319
+
320
+ return Embedding(id=chunk_id, chunk_id=chunk_id, model=model, dim=dim, vector=float_vector)
321
+
322
+ def delete_document(doc_id: int):
323
+ chunks_to_delete = _chunks_collection.get(where={"doc_id": doc_id})
324
+ if chunks_to_delete['ids']:
325
+ _chunks_collection.delete(ids=chunks_to_delete['ids'])
326
+
327
+ _documents_collection.delete(ids=[str(doc_id)])
328
+
329
+ def clear_database():
330
+ _client.delete_collection(name="documents")
331
+ _client.delete_collection(name="chunks")
332
+ init_db()
333
+
334
+ def ping():
335
+ try:
336
+ _client.heartbeat()
337
+ except Exception as e:
338
+ _logger.error(f"ChromaDB ping failed: {e}")
339
+ raise
340
+
341
+ __all__ = [
342
+ "init_db", "get_session", "get_db", "session_scope",
343
+ "add_document", "add_chunk", "upsert_embedding",
344
+ "get_document", "get_document_by_sha", "get_chunks_for_doc", "get_chunks_by_ids",
345
+ "get_documents", "get_document_chunk_counts", "get_all_chunks", "get_max_chunk_id",
346
+ "get_embedding_for_chunk", "delete_document", "clear_database",
347
+ "TOK_VER", "SEG_VER", "ping",
348
+ "Document", "Chunk", "Embedding",
349
+ ]
infrastructure/document_processor.py ADDED
@@ -0,0 +1,283 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from openai import OpenAI
2
+ import fitz
3
+ from .logger import get_logger
4
+ import os
5
+ import io
6
+ import re
7
+ from PIL import Image
8
+ import pytesseract
9
+ import hashlib
10
+ import docx
11
+ from google.cloud import storage
12
+ from google.api_core.exceptions import NotFound
13
+ from typing import Optional, Dict, Any
14
+ import json
15
+ from werkzeug.datastructures import FileStorage
16
+ from datetime import datetime, timezone
17
+
18
+ logger = get_logger()
19
+
20
+ API_KEY = os.getenv("OPENAI_API_KEY")
21
+ PROJECT_ID = os.getenv("VERTEX_PROJECT_ID", "tech-trans-rag")
22
+ GCS_BUCKET = os.getenv("GCS_BUCKET", "tech-trans-rag-bucket")
23
+ MANIFEST_DOC = os.getenv("MANIFEST_DOC", "manifest/manifest.jsonl")
24
+ CHUNKS_DOC = os.getenv("CHUNKS_DOC", "chunks/chunks.jsonl")
25
+
26
+ def ocr_page(page: fitz.Page, zoom: float = 2.0) -> str:
27
+ mat = fitz.Matrix(zoom, zoom)
28
+
29
+ pix = page.get_pixmap(matrix=mat, alpha=False) # type: ignore
30
+ img = Image.open(io.BytesIO(pix.tobytes("png")))
31
+ return pytesseract.image_to_string(img)
32
+
33
+ def blocks_text(tp: fitz.TextPage) -> str:
34
+ blocks = tp.extractBLOCKS()
35
+ blocks.sort(key=lambda b: (round(b[1], 2), round(b[0], 2)))
36
+ parts = [(b[4] or "").strip() for b in blocks if (b[4] or "").strip()]
37
+ return "\n\n".join(parts)
38
+
39
+ def normalize(s: str) -> str:
40
+ s = s.replace("\r\n", "\n").replace("\r", "\n")
41
+ s = re.sub(r"[“”]", '"', s)
42
+ s = re.sub(r"[‘’]", "'", s)
43
+ s = re.sub(r"(\w)-\n(\w)", r"\1\2", s) # de-hyphenate soft wraps
44
+ s = re.sub(r"\n{3,}", "\n\n", s) # collapse excess breaks
45
+ return s
46
+
47
+ def get_manifest_info(text: str) -> Dict[str, Optional[str]]:
48
+
49
+ try:
50
+ client = OpenAI(api_key=API_KEY)
51
+ prompt = (
52
+ f"""
53
+ 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".
54
+ Return a response in following JSON format only:
55
+ {{
56
+ "source_url": source_url,
57
+ "license": license,
58
+ "party_roles": party_roles,
59
+ "governing_law": governing_law,
60
+ "industry": industry,
61
+ "effective_date": effective_date
62
+ }}.
63
+ Do not return anything else outside of the JSON object. If you cannot identify a distinct value corresponding to one of the keys, respond with null for that key.
64
+ --- PAGE TEXT START ---\n
65
+ {text}\n
66
+ --- PAGE TEXT END ---
67
+ """
68
+ )
69
+
70
+ ai_model = "gpt-5-mini"
71
+
72
+ response = client.chat.completions.create(
73
+ model=ai_model,
74
+ messages=[
75
+ {"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"},
76
+ {"role": "user", "content": prompt},
77
+ ]
78
+ )
79
+
80
+ response = response.choices[0].message.content if response.choices else []
81
+ logger.info(f"AI manifest raw response: {response}")
82
+ candidate = (response or [])
83
+ logger.info(f"AI manifest response: {candidate}")
84
+ expected_keys = [
85
+ "source_url",
86
+ "license",
87
+ "party_roles",
88
+ "governing_law",
89
+ "industry",
90
+ "effective_date",
91
+ ]
92
+
93
+ data = {}
94
+ if isinstance(candidate, dict):
95
+ data = candidate
96
+ elif isinstance(candidate, str):
97
+ try:
98
+ data = json.loads(candidate)
99
+ except Exception:
100
+ logger.warning("AI manifest response not valid JSON; returning defaults")
101
+ data = {}
102
+ else:
103
+ logger.warning("AI manifest response unexpected type %s", type(candidate))
104
+
105
+ # Build normalized manifest dict
106
+ manifest = {k: (data.get(k) if isinstance(data, dict) else None) for k in expected_keys}
107
+
108
+ # Coerce obvious placeholder / unknown strings to None
109
+ for k, v in manifest.items():
110
+ if isinstance(v, str) and v.strip().lower() in {"unknown", "null", "n/a", "none", ""}:
111
+ manifest[k] = None
112
+
113
+ return manifest
114
+
115
+ except Exception as e:
116
+ logger.error(f"Error extracting title from text: {e}")
117
+ return {}
118
+
119
+
120
+ def extract_pdf_text(file: FileStorage):
121
+ file.stream.seek(0)
122
+ text_parts = []
123
+ logger.info("Extracting text from PDF")
124
+ with fitz.open(stream=file.stream.read(), filetype="pdf") as doc:
125
+ for page in doc:
126
+ text = page.get_text("text")
127
+ if text.strip():
128
+ text_parts.append(text)
129
+ else:
130
+ pix = page.get_pixmap()
131
+ img = Image.frombytes(mode="RGB", size=(pix.width, pix.height), data=pix.samples)
132
+ ocr_text = pytesseract.image_to_string(img)
133
+ text_parts.append(ocr_text)
134
+ text_parts.append("\n\n\f\n\n") # Page break
135
+ raw = "\n\n\f\n\n".join(text_parts).strip()
136
+ return normalize(raw)
137
+
138
+ def extract_docx_text(file: FileStorage):
139
+ file.stream.seek(0)
140
+ logger.info("Extracting text from DOCX")
141
+ doc = docx.Document(file.stream)
142
+ text = [p.text for p in doc.paragraphs]
143
+ raw = "\n".join(text)
144
+ return normalize(raw)
145
+
146
+ def extract_text(file: FileStorage) -> str:
147
+ filename = file.filename or ""
148
+ file.stream.seek(0)
149
+ _, ext = os.path.splitext(filename.lower())
150
+
151
+ if ext == ".txt":
152
+ return normalize(file.stream.read().decode('utf-8'))
153
+ if ext == ".pdf":
154
+ return extract_pdf_text(file)
155
+ elif ext == ".docx":
156
+ return extract_docx_text(file)
157
+ else:
158
+ raise ValueError("Unsupported file format")
159
+
160
+ def extract_title_type_jurisdiction(text: str) -> Dict[str, Optional[str]]:
161
+ try:
162
+ client = OpenAI(api_key=API_KEY)
163
+ prompt = (
164
+ f"""
165
+ Examine the attached legal document, which is a technology transactions document, and then identify the title, type of technology transactions document (e.g., IP agreement, NDA, license, MSA, etc.), and jurisdiction. Use an accepted legal abbreviation for the jurisdiction (e.g., US-CA, US-FED, FRG, etc.). If you are unable to identify the jurisdiction, use the governing law, if available. Consider the substantive meaning of words (e.g., "Page 1 of 12" is not likely to be the title), placement in the document, case of the letters, length, punctuation, justification, and any other factors that might inform your decision. If you cannot confidently identify a distinct value for any field, respond with null. Return only a JSON object, with no other characters outside the JSON object. The JSON object should have the following keys: title, doc_type, jurisdiction. For example:
166
+ {{"title": title, "doc_type": doc_type, "jurisdiction": jurisdiction}}.
167
+ --- PAGE TEXT START ---\n
168
+ {text}\n
169
+ --- PAGE TEXT END ---
170
+ """
171
+ )
172
+
173
+ ai_model = "gpt-5-nano"
174
+
175
+ response = client.chat.completions.create(
176
+ model=ai_model,
177
+ messages=[
178
+ {"role": "system", "content": "Extract the document's title, doc_type, and jurisdiction based on the following text.\n"},
179
+ {"role": "user", "content": prompt},
180
+ ]
181
+ )
182
+
183
+ response_text = response.choices[0].message.content if response.choices else ""
184
+ candidate = (response_text or "").strip()
185
+
186
+ # Expected keys
187
+ keys = ["title", "doc_type", "jurisdiction"]
188
+ result: Dict[str, Optional[str]] = {k: None for k in keys}
189
+
190
+ if not candidate:
191
+ return result
192
+
193
+ parsed: Dict[str, Optional[str]] = {}
194
+
195
+ # Try direct JSON parse first
196
+ try:
197
+ parsed = json.loads(candidate)
198
+ except Exception:
199
+ # Attempt to salvage JSON substring if model added stray text
200
+ try:
201
+ import re as _re
202
+ match = _re.search(r"\{.*\}", candidate, _re.DOTALL)
203
+ if match:
204
+ parsed = json.loads(match.group(0))
205
+ else:
206
+ logger.warning("AI title/doc_type/jurisdiction response not valid JSON: %s", candidate[:200])
207
+ except Exception:
208
+ logger.warning("Failed to parse AI JSON for title/doc_type/jurisdiction")
209
+
210
+ if isinstance(parsed, dict):
211
+ for k in keys:
212
+ v = parsed.get(k)
213
+ if isinstance(v, str):
214
+ vs = v.strip()
215
+ if vs.lower() in {"", "null", "none", "unknown", "n/a"}:
216
+ result[k] = None
217
+ else:
218
+ result[k] = vs
219
+ elif v is None:
220
+ result[k] = None
221
+ else:
222
+ # Unexpected type -> stringify conservatively
223
+ try:
224
+ result[k] = str(v)
225
+ except Exception:
226
+ result[k] = None
227
+
228
+ return result
229
+ except Exception as e:
230
+ logger.error(f"Error extracting title from text: {e}")
231
+ return {"title": None, "doc_type": None, "jurisdiction": None}
232
+
233
+ def sha256_file(file: FileStorage) -> str:
234
+ file.stream.seek(0)
235
+ return sha256_bytes(file.stream.read())
236
+
237
+ def sha256_bytes(bytes: bytes) -> str:
238
+ return hashlib.sha256(bytes).hexdigest()
239
+
240
+ def sha256_text(text: str) -> str:
241
+ """Compute the SHA-256 hash of a text string."""
242
+ return sha256_bytes(text.encode('utf-8'))
243
+
244
+ 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]]:
245
+ """Upsert a manifest record in the database."""
246
+
247
+ manifest = get_manifest_info(text)
248
+ manifest_record = {
249
+ "doc_id": doc_id,
250
+ "title": title,
251
+ "sha256": sha256,
252
+ "source_path": source_path,
253
+ "clean_path": clean_path,
254
+ "bytes": size,
255
+ "content_type": content_type,
256
+ "license": manifest.get("license"),
257
+ "doc_type": doc_type,
258
+ "party_roles": manifest.get("party_roles"),
259
+ "jurisdiction": jurisdiction,
260
+ "governing_law": manifest.get("governing_law"),
261
+ "industry": manifest.get("industry"),
262
+ "effective_date": manifest.get("effective_date"),
263
+ "created_at": datetime.now(timezone.utc).isoformat(),
264
+ }
265
+
266
+ client = storage.Client(project=PROJECT_ID)
267
+ bucket = client.bucket(GCS_BUCKET)
268
+ blob = bucket.blob(MANIFEST_DOC)
269
+
270
+ line = json.dumps(manifest_record) + "\n"
271
+
272
+ try:
273
+ blob.reload()
274
+ current_gen = blob.generation
275
+ existing = blob.download_as_text(encoding="utf-8")
276
+ updated = existing + line
277
+ blob.upload_from_string(updated, content_type="application/jsonl", if_generation_match=current_gen)
278
+ logger.info(f"Appended manifest record to existing manifest with generation {current_gen}")
279
+ except NotFound:
280
+ blob.upload_from_string(line, content_type="application/jsonl", if_generation_match=0)
281
+ logger.info(f"Created new manifest record as manifest did not exist: {manifest_record}")
282
+
283
+ return manifest_record
infrastructure/embeddings.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Embedding utilities.
2
+
3
+ Generates embeddings for chunk records lacking a stored vector and writes
4
+ results to the SQLite `embeddings` table. Also upserts into a Vertex AI
5
+ Matching Engine index.
6
+
7
+ Primary entrypoint:
8
+ generate_and_store_embeddings(doc_id: str | None = None,
9
+ model: str | None = None,
10
+ batch_size: int = 64) -> int
11
+
12
+ Requirements / Assumptions:
13
+ * Uses OpenAI Embeddings API (model default: text-embedding-3-large).
14
+ * Stores vectors as little-endian float32 binary blobs (dimension recorded).
15
+ * Uses Vertex AI Matching Engine for vector indexing. Requires environment
16
+ variables for project, region, and index endpoint.
17
+ * Current DB schema has `chunk_id` as PRIMARY KEY in embeddings table, so only
18
+ one embedding per chunk is effectively stored despite a `model` column.
19
+
20
+ Graceful degradation:
21
+ * If openai or google-cloud-aiplatform packages are missing or API calls fail,
22
+ logs an error and aborts/skips steps.
23
+ * Batches requests; naive exponential backoff on rate / transient errors.
24
+
25
+ Future improvements:
26
+ * Streaming ingestion & async concurrency.
27
+ * Token counting for dynamic batch sizing.
28
+ """
29
+ from __future__ import annotations
30
+
31
+ import os
32
+ from typing import List, Optional
33
+ from openai import OpenAI
34
+ import chromadb
35
+ from chromadb.utils import embedding_functions
36
+ import time
37
+
38
+ from .logger import get_logger
39
+
40
+ logger = get_logger()
41
+
42
+ DEFAULT_MODEL = os.getenv("EMBEDDING_MODEL", "text-embedding-3-large")
43
+ CHROMA_DATA_PATH = "chroma_data"
44
+ CHROMA_COLLECTION = "techtrans_rag"
45
+
46
+
47
+ def get_chroma_collection():
48
+ """Return a ChromaDB collection instance."""
49
+ # Get the API key from environment variables
50
+ api_key = os.getenv("OPENAI_API_KEY")
51
+ if not api_key:
52
+ raise ValueError("OPENAI_API_KEY environment variable not set.")
53
+
54
+ # Initialize the embedding function with the API key
55
+ openai_ef = embedding_functions.OpenAIEmbeddingFunction(
56
+ api_key=api_key,
57
+ model_name=DEFAULT_MODEL
58
+ )
59
+
60
+ client = chromadb.PersistentClient(path=CHROMA_DATA_PATH)
61
+
62
+ # Pass the embedding function to the get_or_create_collection method
63
+ collection = client.get_or_create_collection(name=CHROMA_COLLECTION)
64
+
65
+ return collection
66
+
67
+
68
+ def _ensure_openai_client() -> Optional[OpenAI]:
69
+ """Ensure OpenAI client is available and configured."""
70
+ if OpenAI is None:
71
+ logger.error("openai package not installed; cannot generate embeddings")
72
+ return None
73
+ api_key = os.getenv("OPENAI_API_KEY")
74
+ if not api_key:
75
+ logger.error("OPENAI_API_KEY not set; cannot generate embeddings")
76
+ return None
77
+ try:
78
+ return OpenAI(api_key=api_key)
79
+ except Exception as e: # pragma: no cover
80
+ logger.error("Failed to init OpenAI client: %s", e)
81
+ return None
82
+
83
+
84
+ def generate_embeddings(
85
+ texts: List[str],
86
+ model: str | None = None,
87
+ max_retries: int = 5,
88
+ ) -> List[List[float]]:
89
+ """Generate embeddings for a list of texts."""
90
+ model = model or DEFAULT_MODEL
91
+ client = _ensure_openai_client()
92
+ if not client:
93
+ return []
94
+
95
+ attempt = 0
96
+ while True:
97
+ try:
98
+ resp = client.embeddings.create(model=model, input=texts)
99
+ vectors = [d.embedding for d in resp.data]
100
+ if len(vectors) != len(texts):
101
+ raise RuntimeError("Mismatch between returned embeddings and input size")
102
+ return vectors
103
+ except Exception as e:
104
+ attempt += 1
105
+ if attempt > max_retries:
106
+ logger.error(
107
+ "Failed embedding batch after %d attempts: %s", attempt - 1, e
108
+ )
109
+ return []
110
+ sleep_for = min(2**attempt, 30)
111
+ logger.warning(
112
+ "Embedding batch error (%s). Retry %d/%d in %.1fs",
113
+ e,
114
+ attempt,
115
+ max_retries,
116
+ sleep_for,
117
+ )
118
+ time.sleep(sleep_for)
119
+
120
+
121
+ def generate_embedding(
122
+ text: str,
123
+ model: str | None = None,
124
+ max_retries: int = 5,
125
+ ) -> List[float]:
126
+ """Generate an embedding for a single text."""
127
+ embeddings = generate_embeddings([text], model=model, max_retries=max_retries)
128
+ return embeddings[0] if embeddings else []
129
+
130
+
131
+ __all__ = [
132
+ "generate_embeddings",
133
+ "generate_embedding",
134
+ "get_chroma_collection",
135
+ ]
infrastructure/logger.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import sys
3
+ import os
4
+
5
+ _loggers = {}
6
+
7
+ def setup_logger(name="techtrans", level=logging.INFO, toFile=True, fileName="techtrans.log"):
8
+ """
9
+ Establish an instance of a logger to be used for logging in current context of app
10
+
11
+ Args
12
+ name: name of the logger
13
+ level: level of logging info
14
+ toFile: whether to log to file (ignored in cloud environments)
15
+ fileName: log file name (ignored in cloud environments)
16
+ """
17
+ if name in _loggers:
18
+ return _loggers[name]
19
+
20
+ # Check if running in cloud environment
21
+ is_cloud = os.getenv('LOG_TO_CLOUD', 'false').lower() == 'true'
22
+
23
+ if is_cloud:
24
+ # Use Google Cloud Logging in cloud environment
25
+ try:
26
+ import google.cloud.logging
27
+ client = google.cloud.logging.Client()
28
+ client.setup_logging()
29
+ logger = logging.getLogger(name)
30
+ except ImportError:
31
+ # Fallback to standard logging if google-cloud-logging not available
32
+ logger = logging.getLogger(name)
33
+ handler = logging.StreamHandler(sys.stdout)
34
+ formatter = logging.Formatter('{"severity": "%(levelname)s", "message": "%(message)s", "timestamp": "%(asctime)s", "logger": "%(name)s"}')
35
+ handler.setFormatter(formatter)
36
+ logger.addHandler(handler)
37
+ else:
38
+ # Local development logging
39
+ logger = logging.getLogger(name)
40
+ formatter = logging.Formatter("[%(asctime)s] - %(name)s %(levelname)s %(message)s")
41
+
42
+ if toFile:
43
+ fileHandler = logging.FileHandler(fileName)
44
+ fileHandler.setFormatter(formatter)
45
+ logger.addHandler(fileHandler)
46
+
47
+ streamHandler = logging.StreamHandler(sys.stderr)
48
+ streamHandler.setFormatter(formatter)
49
+ logger.addHandler(streamHandler)
50
+
51
+ numeric_level = getattr(logging, str(level).upper(), logging.INFO)
52
+ logger.setLevel(numeric_level)
53
+
54
+ _loggers[name] = logger
55
+ return logger
56
+
57
+ def get_logger(name="techtrans"):
58
+ return logging.getLogger(name)
infrastructure/vector_search.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
6
+
7
+ logger = get_logger()
8
+
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.warning("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
+
50
+ except Exception as e:
51
+ logger.error(f"ChromaDB neighbor search failed: {e}")
52
+ return []
53
+
54
+
55
+ def upsert_datapoints(datapoints: list[dict]):
56
+ """Upserts datapoints to the ChromaDB collection."""
57
+ if not datapoints:
58
+ logger.info("No datapoints to upsert.")
59
+ return
60
+
61
+ collection = get_chroma_collection()
62
+
63
+ ids = [str(dp['datapoint_id']) for dp in datapoints]
64
+ embeddings = [dp['embedding'] for dp in datapoints]
65
+
66
+ # ChromaDB metadatas must be Dict[str, str | int | float | bool]
67
+ # Our 'restricts' are lists of dicts, which are not supported.
68
+ # We will serialize them to JSON strings.
69
+ metadatas = []
70
+ for dp in datapoints:
71
+ metadata = {}
72
+ if 'restricts' in dp:
73
+ # Assuming 'restricts' is a list of dictionaries
74
+ metadata['restricts'] = json.dumps(dp['restricts'])
75
+ if 'numeric_restricts' in dp:
76
+ metadata['numeric_restricts'] = json.dumps(dp['numeric_restricts'])
77
+ metadatas.append(metadata)
78
+
79
+ try:
80
+ logger.info(f"Upserting {len(datapoints)} datapoints to ChromaDB collection.")
81
+ collection.upsert(
82
+ ids=ids,
83
+ embeddings=embeddings,
84
+ metadatas=metadatas
85
+ )
86
+ logger.info(f"Successfully upserted {len(datapoints)} datapoints.")
87
+ except Exception as e:
88
+ logger.error(f"Failed to upsert to ChromaDB: {e}")
89
+ raise Exception("Failed to upsert to ChromaDB")
routes/api.py ADDED
@@ -0,0 +1,246 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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,
9
+ add_document,
10
+ get_document_by_sha,
11
+ get_chunks_for_doc,
12
+ get_documents,
13
+ get_document_chunk_counts,
14
+ get_all_chunks,
15
+ )
16
+ from infrastructure.document_processor import (
17
+ extract_text,
18
+ extract_title_type_jurisdiction,
19
+ sha256_text,
20
+ )
21
+ from infrastructure.chunker import chunk_doc
22
+ from infrastructure.vector_search import find_nearest_neighbors
23
+ from infrastructure.database import get_chunks_by_ids
24
+
25
+ api_bp = Blueprint("api", __name__, url_prefix="/api")
26
+ logger = get_logger()
27
+
28
+ ALLOWED_EXTENSIONS = {"pdf", "docx", "txt"}
29
+ UPLOAD_FOLDER = os.getenv("UPLOAD_FOLDER", "corpus_raw/")
30
+ CLEAN_FOLDER = os.getenv("CLEAN_FOLDER", "corpus_clean/")
31
+ os.makedirs(UPLOAD_FOLDER, exist_ok=True)
32
+ os.makedirs(CLEAN_FOLDER, exist_ok=True)
33
+
34
+ def allowed_file(filename: str) -> bool:
35
+ return "." in filename and filename.rsplit(".", 1)[1].lower() in ALLOWED_EXTENSIONS
36
+
37
+ @api_bp.route("/upload", methods=["POST"])
38
+ def add_doc():
39
+ """Upload one document, extract text, persist metadata, and schedule chunking."""
40
+ if "file" not in request.files:
41
+ return jsonify({"error": "No file part"}), 400
42
+ file = request.files["file"]
43
+ if not file or not file.filename:
44
+ return jsonify({"error": "No selected file"}), 400
45
+ if not allowed_file(file.filename):
46
+ return jsonify({"error": "Unsupported file type"}), 400
47
+
48
+ doc_type = request.form.get("doc_type") or None
49
+ jurisdiction = request.form.get("jurisdiction") or None
50
+
51
+ logger.info("Received upload: filename=%s, doc_type=%s, jurisdiction=%s",
52
+ file.filename, doc_type, jurisdiction)
53
+
54
+ clean_text = extract_text(file=file)
55
+ content_sha = sha256_text(clean_text)
56
+
57
+ doc = get_document_by_sha(content_sha)
58
+ title = None
59
+ doc_id_val = None
60
+
61
+ if not doc:
62
+ filename = secure_filename(file.filename)
63
+ raw_path = os.path.join(UPLOAD_FOLDER, filename)
64
+ txt_filename = filename.rsplit('.', 1)[0] + '.txt'
65
+ clean_path = os.path.join(CLEAN_FOLDER, txt_filename)
66
+
67
+ file.stream.seek(0)
68
+ file.save(raw_path)
69
+ logger.info("Saved raw file to %s", raw_path)
70
+
71
+ with open(clean_path, "w", encoding="utf-8") as f:
72
+ f.write(clean_text)
73
+ logger.info("Saved clean text to %s", clean_path)
74
+
75
+ doc_info = extract_title_type_jurisdiction(clean_text)
76
+ title = doc_info.get("title") or file.filename.split('.')[0]
77
+ if not doc_type and "doc_type" in doc_info:
78
+ doc_type = doc_info.get("doc_type")
79
+ if not jurisdiction and "jurisdiction" in doc_info:
80
+ jurisdiction = doc_info.get("jurisdiction")
81
+
82
+ doc = add_document(sha256=content_sha, title=title, source_path=raw_path, doc_type=doc_type, jurisdiction=jurisdiction)
83
+ doc_id_val = getattr(doc, "doc_id", None)
84
+
85
+ else:
86
+ doc_id_val = getattr(doc, "doc_id", None)
87
+ title = getattr(doc, "title", None)
88
+ try:
89
+ doc = add_document(sha256=content_sha, doc_type=doc_type, jurisdiction=jurisdiction)
90
+ except Exception:
91
+ pass
92
+
93
+ try:
94
+ chunks = chunk_doc(text=clean_text, doc_id=str(doc_id_val))
95
+ logger.info("Chunked document into %d chunks", len(chunks))
96
+ except Exception as e:
97
+ logger.exception("Chunking failed: %s", e)
98
+ pass
99
+
100
+ return jsonify({
101
+ "message": "ok",
102
+ "doc_id": doc_id_val,
103
+ "sha256": content_sha,
104
+ "title": title,
105
+ "doc_type": getattr(doc, "doc_type", None),
106
+ "jurisdiction": getattr(doc, "jurisdiction", None)
107
+ }), 200
108
+
109
+
110
+ @api_bp.route("/chunks", methods=["GET"])
111
+ def get_chunks():
112
+ """List chunks for a document: /chunks?doc_id=123"""
113
+ try:
114
+ doc_id = int(request.args.get("doc_id", "0"))
115
+ except ValueError:
116
+ return jsonify({"error": "invalid doc_id"}), 400
117
+ if not doc_id:
118
+ return jsonify({"error": "doc_id required"}), 400
119
+
120
+ chunks = get_chunks_for_doc(doc_id)
121
+ out = [{
122
+ "chunk_id": c.chunk_id,
123
+ "doc_id": c.doc_id,
124
+ "chunk_index": c.chunk_index,
125
+ "token_count": c.token_count,
126
+ "tok_ver": c.tok_ver,
127
+ "seg_ver": c.seg_ver,
128
+ "text": str(getattr(c, "text", "") or ""),
129
+ } for c in chunks]
130
+ return jsonify({"doc_id": doc_id, "count": len(out), "chunks": out}), 200
131
+
132
+ @api_bp.route("/documents", methods=["GET"])
133
+ def list_documents():
134
+ """List documents with pagination and basic counts.
135
+
136
+ Query params:
137
+ limit (default 100, max 500)
138
+ offset (default 0)
139
+ """
140
+ try:
141
+ limit = int(request.args.get("limit", 100))
142
+ offset = int(request.args.get("offset", 0))
143
+ except ValueError:
144
+ return jsonify({"error": "invalid pagination"}), 400
145
+ limit = max(1, min(limit, 500))
146
+ offset = max(0, offset)
147
+ docs = get_documents(limit=limit, offset=offset)
148
+ ids = [int(getattr(d, 'doc_id')) for d in docs]
149
+ counts = get_document_chunk_counts(ids)
150
+ out = []
151
+ for d in docs:
152
+ out.append({
153
+ "doc_id": int(getattr(d, 'doc_id')),
154
+ "title": d.title,
155
+ "sha256": d.sha256,
156
+ "doc_type": getattr(d, "doc_type", None),
157
+ "jurisdiction": getattr(d, "jurisdiction", None),
158
+ "created_at": d.created_at.isoformat() if getattr(d, 'created_at', None) else None,
159
+ "chunk_count": counts.get(int(getattr(d, 'doc_id')), 0),
160
+ })
161
+ return jsonify({"documents": out, "count": len(out), "limit": limit, "offset": offset}), 200
162
+
163
+
164
+ @api_bp.route("/chunks/all", methods=["GET"])
165
+ def list_all_chunks():
166
+ """List global chunks slice (paginated). Query params: limit (<=500), offset."""
167
+ try:
168
+ limit = int(request.args.get("limit", 200))
169
+ offset = int(request.args.get("offset", 0))
170
+ except ValueError:
171
+ return jsonify({"error": "invalid pagination"}), 400
172
+ limit = max(1, min(limit, 500))
173
+ offset = max(0, offset)
174
+ rows = get_all_chunks(limit=limit, offset=offset)
175
+ out = []
176
+ for c in rows:
177
+ doc = getattr(c, 'document', None)
178
+ out.append({
179
+ "chunk_id": c.chunk_id,
180
+ "doc_id": c.doc_id,
181
+ "chunk_index": c.chunk_index,
182
+ "token_count": c.token_count,
183
+ "tok_ver": c.tok_ver,
184
+ "seg_ver": c.seg_ver,
185
+ "text": str(getattr(c, 'text', '') or ''),
186
+ "doc_type": getattr(doc, 'doc_type', None) if doc else None,
187
+ "jurisdiction": getattr(doc, 'jurisdiction', None) if doc else None,
188
+ "title": getattr(doc, 'title', None) if doc else None,
189
+ })
190
+ return jsonify({"chunks": out, "count": len(out), "limit": limit, "offset": offset}), 200
191
+
192
+ @api_bp.route("/query", methods=["POST"])
193
+ def query():
194
+ """Vector search against chunk embeddings using ChromaDB."""
195
+ payload = request.get_json(force=True) or {}
196
+ question = payload.get("query")
197
+ top_k = int(payload.get("top_k", 5))
198
+ if not question:
199
+ return jsonify({"error": "query required"}), 400
200
+
201
+ try:
202
+ neighbors = find_nearest_neighbors(query=question, num_neighbors=top_k)
203
+
204
+ if not neighbors:
205
+ return jsonify({"results": [], "message": "No results found."}), 200
206
+
207
+ chunk_ids = [int(nid) for nid, dist in neighbors]
208
+ chunks = get_chunks_by_ids(chunk_ids)
209
+
210
+ # Create a dictionary for quick lookup
211
+ chunk_map = {chunk.chunk_id: chunk for chunk in chunks}
212
+
213
+ results = []
214
+ for neighbor_id, distance in neighbors:
215
+ chunk = chunk_map.get(int(neighbor_id))
216
+ if chunk:
217
+ doc_info = {}
218
+ if chunk.document:
219
+ doc_info = {
220
+ "title": chunk.document.title,
221
+ "doc_type": chunk.document.doc_type,
222
+ "jurisdiction": chunk.document.jurisdiction,
223
+ }
224
+ results.append({
225
+ "chunk_id": chunk.chunk_id,
226
+ "doc_id": chunk.doc_id,
227
+ "text": chunk.text,
228
+ "distance": distance,
229
+ "document": doc_info
230
+ })
231
+
232
+ return jsonify({"results": results}), 200
233
+ except Exception as e:
234
+ logger.exception("Query failed: %s", e)
235
+ return jsonify({"error": "Failed to execute query"}), 500
236
+
237
+
238
+ # Health
239
+ @api_bp.route("/healthz", methods=["GET"])
240
+ def healthz():
241
+ try:
242
+ init_db() # idempotent
243
+ return jsonify({"ok": True}), 200
244
+ except Exception as e:
245
+ logger.error("Health check failed: %s", e)
246
+ return jsonify({"status": "error", "reason": str(e)}), 500
routes/web.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Blueprint, render_template
2
+
3
+ web_bp = Blueprint('web', __name__)
4
+
5
+ @web_bp.route('/')
6
+ def index():
7
+ return render_template('index.html')
8
+
9
+ @web_bp.route('/upload')
10
+ def upload():
11
+ return render_template('upload.html')
12
+
13
+ @web_bp.route('/manifest-status')
14
+ def manifest_status():
15
+ return render_template('manifest.html')
16
+
17
+ @web_bp.route('/chunk-status')
18
+ def chunk_status():
19
+ return render_template('chunks.html')
20
+
21
+ @web_bp.route('/db-status')
22
+ def db_status():
23
+ return render_template('dbtables.html')
static/chunks.html ADDED
@@ -0,0 +1,301 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <meta name="viewport" content="width=device-width,initial-scale=1.0" />
6
+ <title>Chunks Viewer</title>
7
+ <style>
8
+ *{margin:0;padding:0;box-sizing:border-box}
9
+ body{font-family:-apple-system,BlinkMacSystemFont,'SF Pro Rounded','SF Pro Display',Roboto,Oxygen,Ubuntu,Cantarell,sans-serif;background:#001122;color:#fff;min-height:100vh;padding:28px;display:flex;flex-direction:column;align-items:center;gap:28px}
10
+ .shell{width:100%;max-width:1400px;display:flex;flex-direction:column;gap:26px}
11
+ .panel{background:#333;border-radius:20px;padding:26px 32px;box-shadow:0 18px 50px rgba(0,0,0,.5);display:flex;flex-direction:column;gap:20px}
12
+ h1{font-size:2.1rem;font-weight:500;text-shadow:0 4px 8px rgba(0,0,0,.5);margin:0}
13
+ p.sub{font-size:.8rem;color:#ccc;font-style:italic;line-height:1.5;margin:0}
14
+ a{color:#87CEFA;text-decoration:none}a:hover{text-decoration:underline}
15
+ form.query{display:flex;flex-wrap:wrap;gap:14px;align-items:flex-end}
16
+ form.query>div{display:flex;flex-direction:column;gap:6px}
17
+ label{font-size:.7rem;text-transform:uppercase;letter-spacing:1px;color:#ccc}
18
+ input[type=number],input[type=text]{background:#222;border:2px solid #555;border-radius:10px;padding:10px 14px;color:#fff;font-family:inherit;min-width:140px}
19
+ input:focus{outline:none;border-color:#7ec8ff;box-shadow:0 0 0 3px rgba(126,200,255,.15)}
20
+ button{background:#7ec8ff;color:#001122;border:none;padding:10px 18px;border-radius:10px;font-weight:600;cursor:pointer;font-size:.85rem;letter-spacing:1px;transition:.25s;box-shadow:0 8px 18px rgba(126,200,255,.25)}
21
+ button:hover{background:#6bb8ff;transform:translateY(-2px)}
22
+ button:active{transform:translateY(0)}
23
+ button.secondary{background:rgba(255,102,102,.45);color:#fff;box-shadow:none}
24
+ button.secondary:hover{background:rgba(255,102,102,.6)}
25
+ .status{font-size:.75rem;color:#ccc;min-height:18px}
26
+ .results{display:flex;flex-direction:column;gap:22px}
27
+ .view-toggles{display:flex;gap:10px;flex-wrap:wrap}
28
+ .view-toggles button{background:#2d3f4d;color:#cfe9ff;box-shadow:none;padding:8px 14px;font-size:.65rem}
29
+ .view-toggles button.active{background:#7ec8ff;color:#001122}
30
+ .summary{display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:14px}
31
+ .kv{background:#222;border:2px solid #555;border-radius:12px;padding:10px 12px;display:flex;flex-direction:column;gap:4px}
32
+ .kv span.k{font-size:.6rem;text-transform:uppercase;letter-spacing:1px;color:#999}
33
+ .kv span.v{font-size:.8rem;word-break:break-word}
34
+ .chunks{display:flex;flex-direction:column;gap:14px;max-height:60vh;overflow:auto}
35
+ .table-wrapper{background:#222;border:2px solid #555;border-radius:16px;padding:14px 18px;max-height:60vh;overflow:auto}
36
+ table.data-table{width:100%;border-collapse:collapse;font-size:.65rem}
37
+ table.data-table th,table.data-table td{padding:6px 8px;text-align:left;border:1px solid #444;vertical-align:top}
38
+ table.data-table th{position:sticky;top:0;background:#2d3f4d;z-index:2;font-weight:600;letter-spacing:.5px}
39
+ table.data-table tbody tr:nth-child(even){background:#1e2a33}
40
+ .truncate{max-width:420px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
41
+ .chunk{background:#1b2733;border:1px solid #3d4c55;border-radius:14px;padding:16px 18px;display:flex;flex-direction:column;gap:10px;position:relative}
42
+ .chunk h3{margin:0;font-size:.85rem;font-weight:600}
43
+ .meta-row{display:flex;flex-wrap:wrap;gap:6px;font-size:.55rem;letter-spacing:.5px}
44
+ .tag{background:#2d3f4d;color:#cfe9ff;font-size:.55rem;padding:4px 8px;border-radius:100px;text-transform:uppercase}
45
+ .text{font-family:Consolas,Monaco,monospace;font-size:.7rem;line-height:1.35;white-space:pre-wrap;word-break:break-word;max-height:220px;overflow:hidden;position:relative}
46
+ .text.expanded{max-height:none}
47
+ .expand-btn{position:absolute;bottom:0;right:0;background:linear-gradient(90deg,rgba(0,0,0,0),#1b2733 60%);padding:4px 8px;font-size:.55rem;border:none;color:#87CEFA;cursor:pointer}
48
+ .expand-btn:hover{text-decoration:underline}
49
+ .toolbar{display:flex;flex-wrap:wrap;gap:10px}
50
+ .toolbar input{background:#222;border:2px solid #555;border-radius:10px;padding:8px 10px;color:#fff;font-size:.75rem;min-width:220px}
51
+ .toolbar input:focus{outline:none;border-color:#7ec8ff;box-shadow:0 0 0 3px rgba(126,200,255,.15)}
52
+ .pagination{display:flex;align-items:center;gap:12px;font-size:.7rem;flex-wrap:wrap}
53
+ .pagination button{padding:6px 12px;font-size:.65rem}
54
+ .empty{text-align:center;font-style:italic;color:#ccc}
55
+ .spinner{width:18px;height:18px;border:3px solid rgba(255,255,255,.2);border-top-color:#7ec8ff;border-radius:50%;animation:spin 1s linear infinite}
56
+ @keyframes spin{to{transform:rotate(360deg)}}
57
+ @media (max-width:900px){.panel{padding:22px 20px}h1{font-size:1.7rem}}
58
+ </style>
59
+ </head>
60
+ <body>
61
+ <div class="shell">
62
+ <div class="panel">
63
+ <h1>Chunks Explorer</h1>
64
+ <p class="sub">Default view lists a paginated slice of all chunks (<code>/api/chunks/all</code>). Enter or select a document ID to view only that document's chunks via <code>/api/chunks?doc_id=&lt;id&gt;</code>.</p>
65
+ <form id="queryForm" class="query" autocomplete="off">
66
+ <div>
67
+ <label for="docId">Document ID</label>
68
+ <input type="number" id="docId" min="1" placeholder="e.g., 12" required />
69
+ </div>
70
+ <div>
71
+ <label for="filter">Text Filter (client)</label>
72
+ <input type="text" id="filter" placeholder="filter text..." />
73
+ </div>
74
+ <div>
75
+ <label for="pageSize">Page Size</label>
76
+ <input type="number" id="pageSize" min="5" max="200" value="25" />
77
+ </div>
78
+ <div style="display:flex;gap:8px;">
79
+ <button type="submit" id="fetchBtn">Fetch</button>
80
+ <button type="button" class="secondary" id="clearBtn">Clear</button>
81
+ </div>
82
+ </form>
83
+ <div class="toolbar">
84
+ <input type="text" id="sectionFilter" placeholder="filter by section (contains)" />
85
+ <input type="text" id="indexFilter" placeholder="filter by chunk index (exact)" />
86
+ </div>
87
+ <div class="status" id="status"></div>
88
+ </div>
89
+
90
+ <div class="panel results" id="resultsPanel" style="display:block;">
91
+ <div style="display:flex;gap:10px;flex-wrap:wrap;align-items:center;margin-bottom:6px;">
92
+ <div class="view-toggles">
93
+ <button type="button" id="cardsMode" class="active">Cards</button>
94
+ <button type="button" id="tableMode">Table</button>
95
+ </div>
96
+ <button type="button" id="globalMode" class="secondary" style="margin-left:auto;">Show All Chunks</button>
97
+ </div>
98
+ <div class="summary" id="summary"></div>
99
+ <div class="chunks" id="chunks" style="display:block;"></div>
100
+ <div class="table-wrapper" id="tableWrapper" style="display:none;"></div>
101
+ <div class="pagination" id="pagination"></div>
102
+ </div>
103
+ </div>
104
+
105
+ <script>
106
+ const form = document.getElementById('queryForm');
107
+ const docIdInput = document.getElementById('docId');
108
+ const filterInput = document.getElementById('filter');
109
+ const sectionFilter = document.getElementById('sectionFilter');
110
+ const indexFilter = document.getElementById('indexFilter');
111
+ const pageSizeInput = document.getElementById('pageSize');
112
+ const statusEl = document.getElementById('status');
113
+ const summaryEl = document.getElementById('summary');
114
+ const chunksEl = document.getElementById('chunks');
115
+ const tableWrapper = document.getElementById('tableWrapper');
116
+ const cardsModeBtn = document.getElementById('cardsMode');
117
+ const tableModeBtn = document.getElementById('tableMode');
118
+ const paginationEl = document.getElementById('pagination');
119
+ const clearBtn = document.getElementById('clearBtn');
120
+ const resultsPanel = document.getElementById('resultsPanel');
121
+ const globalModeBtn = document.getElementById('globalMode');
122
+
123
+ let rawChunks = [];
124
+ let currentPage = 1;
125
+
126
+ function esc(v){return String(v??'').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');}
127
+ function setStatus(msg,isErr=false){statusEl.innerHTML = msg?`<span style="${isErr?'color:#ff7b7b;font-weight:600;':''}">${esc(msg)}</span>`:'';}
128
+ function spinner(){setStatus(`<span style='display:inline-flex;align-items:center;gap:8px;'><span class="spinner"></span> Loading...</span>`);}
129
+
130
+ function fetchChunks(docId){
131
+ spinner();
132
+ fetch(`/api/chunks?doc_id=${encodeURIComponent(docId)}`)
133
+ .then(r=>r.json())
134
+ .then(data=>{
135
+ if(data.error){ setStatus(data.error,true); resultsPanel.style.display='none'; return; }
136
+ rawChunks = Array.isArray(data.chunks)?data.chunks:[];
137
+ setStatus(rawChunks.length?`Loaded ${rawChunks.length} chunk(s).`:'No chunks.');
138
+ buildSummary(data);
139
+ currentPage=1;
140
+ render();
141
+ resultsPanel.style.display='block';
142
+ })
143
+ .catch(err=>{ setStatus('Failed to load chunks: '+err.message,true); resultsPanel.style.display='none'; });
144
+ }
145
+
146
+ function buildSummary(apiData){
147
+ summaryEl.innerHTML='';
148
+ if(!rawChunks.length) return;
149
+ const last = rawChunks[rawChunks.length-1];
150
+ const meta = {
151
+ doc_id: apiData.doc_id,
152
+ total_chunks: rawChunks.length,
153
+ first_chunk_id: rawChunks[0]?.chunk_id,
154
+ last_chunk_id: last?.chunk_id,
155
+ token_version: last?.tok_ver,
156
+ segment_version: last?.seg_ver
157
+ };
158
+ Object.entries(meta).forEach(([k,v])=>{
159
+ summaryEl.insertAdjacentHTML('beforeend', `<div class="kv"><span class="k">${esc(k)}</span><span class="v">${esc(v)}</span></div>`);
160
+ });
161
+ }
162
+
163
+ function fetchAllChunks(){
164
+ setStatus('');
165
+ summaryEl.innerHTML='';
166
+ spinner();
167
+ const limit = Math.max(50, Math.min(500, parseInt(pageSizeInput.value,10)||200));
168
+ fetch(`/api/chunks/all?limit=${limit}`)
169
+ .then(r=>r.json())
170
+ .then(data => {
171
+ rawChunks = Array.isArray(data.chunks)?data.chunks:[];
172
+ setStatus(rawChunks.length?`Loaded ${rawChunks.length} chunk(s) (global slice).`:'No chunks.');
173
+ currentPage=1; render();
174
+ })
175
+ .catch(err=>{ setStatus('Failed to load global chunks: '+err.message,true); });
176
+ }
177
+
178
+ function applyFilters(list){
179
+ const t = filterInput.value.trim().toLowerCase();
180
+ const s = sectionFilter.value.trim().toLowerCase();
181
+ const idx = indexFilter.value.trim();
182
+ return list.filter(c=>{
183
+ if(t && !JSON.stringify(c).toLowerCase().includes(t)) return false;
184
+ if(s && !(c.section||'').toLowerCase().includes(s)) return false;
185
+ if(idx && String(c.chunk_index) !== idx) return false;
186
+ return true;
187
+ });
188
+ }
189
+
190
+ function paginate(list,page,pageSize){
191
+ const start=(page-1)*pageSize; return list.slice(start,start+pageSize);
192
+ }
193
+
194
+ function render(){
195
+ const filtered = applyFilters(rawChunks);
196
+ const pageSize = Math.max(5, Math.min(200, parseInt(pageSizeInput.value,10)||25));
197
+ const pageCount = Math.max(1, Math.ceil(filtered.length / pageSize));
198
+ if(currentPage>pageCount) currentPage=pageCount;
199
+ const pageItems = paginate(filtered,currentPage,pageSize);
200
+
201
+ if(!filtered.length){ chunksEl.innerHTML='<div class="empty">No chunks match filters.</div>'; paginationEl.innerHTML=''; return; }
202
+
203
+ if(cardsModeBtn.classList.contains('active')){
204
+ chunksEl.innerHTML = pageItems.map(ch => renderChunk(ch)).join('');
205
+ tableWrapper.innerHTML='';
206
+ attachExpandHandlers();
207
+ } else {
208
+ renderTable(filtered,pageSize,pageCount);
209
+ }
210
+ buildPagination(pageCount);
211
+ }
212
+
213
+ function renderTable(filtered,pageSize,pageCount){
214
+ const pageSizeVal = Math.max(5, Math.min(200, parseInt(pageSizeInput.value,10)||25));
215
+ const start=(currentPage-1)*pageSizeVal;
216
+ const subset=filtered.slice(start,start+pageSizeVal);
217
+ if(!subset.length){ tableWrapper.innerHTML='<div class="empty">No chunks match filters.</div>'; return; }
218
+ const columns=["chunk_id","chunk_index","token_count","tok_ver","seg_ver","text"];
219
+ let html='<table class="data-table"><thead><tr>'+columns.map(c=>`<th>${esc(c)}</th>`).join('')+'</tr></thead><tbody>';
220
+ html+= subset.map(r=>'<tr data-chunk="'+esc(r.chunk_id)+'">'+columns.map(c=>{
221
+ let val=r[c]; if(val==null) val=''; let display=String(val);
222
+ if(c==='text'){
223
+ const full=display; const trunc=full.length>240?full.slice(0,240)+'…':full;
224
+ return `<td data-text="1" data-full="${esc(full)}" data-trunc="${esc(trunc)}" data-expanded="0" class="${trunc!==full?'truncate':''}" title="Click row to toggle full text">${esc(trunc)}</td>`;
225
+ }
226
+ if(display.length>120) display=display.slice(0,120)+'…';
227
+ return `<td class="${display!==String(val)?'truncate':''}" title="${esc(String(val))}">${esc(display)}</td>`;
228
+ }).join('')+'</tr>').join('');
229
+ html+='</tbody></table>';
230
+ tableWrapper.innerHTML=html;
231
+ attachExpandHandlers();
232
+ }
233
+
234
+ function renderChunk(ch){
235
+ const full = ch.text||'';
236
+ const truncated = full.length>800? full.slice(0,800)+'…' : full;
237
+ const metaTags = [];
238
+ metaTags.push(`<span class='tag'>Idx ${esc(ch.chunk_index)}</span>`);
239
+ if(ch.token_count!=null) metaTags.push(`<span class='tag'>Tok ${esc(ch.token_count)}</span>`);
240
+ if(ch.section) metaTags.push(`<span class='tag'>Sec</span>`);
241
+ return `<div class='chunk' data-chunk='${esc(ch.chunk_id)}' data-expanded='0'>
242
+ <h3>Chunk ${esc(ch.chunk_id)}</h3>
243
+ <div class='meta-row'>${metaTags.join('')}</div>
244
+ <div class='text' data-full='${esc(full)}' data-trunc='${esc(truncated)}'>${esc(truncated)}</div>
245
+ </div>`;
246
+ }
247
+
248
+ function attachExpandHandlers(){
249
+ // Card mode
250
+ chunksEl.querySelectorAll('.chunk').forEach(div=>{
251
+ div.addEventListener('click',()=>{
252
+ const textDiv = div.querySelector('.text');
253
+ if(!textDiv) return;
254
+ const expanded = textDiv.classList.toggle('expanded');
255
+ if(expanded){
256
+ textDiv.textContent = textDiv.getAttribute('data-full');
257
+ div.dataset.expanded='1';
258
+ } else {
259
+ textDiv.textContent = textDiv.getAttribute('data-trunc');
260
+ div.dataset.expanded='0';
261
+ }
262
+ });
263
+ });
264
+ // Table mode
265
+ if(tableWrapper.innerHTML){
266
+ tableWrapper.querySelectorAll('tbody tr').forEach(tr=>{
267
+ tr.addEventListener('click',()=>{
268
+ const cell = tr.querySelector('td[data-text]');
269
+ if(!cell) return;
270
+ if(cell.dataset.expanded==='1'){
271
+ cell.textContent = cell.dataset.trunc;
272
+ cell.dataset.expanded='0';
273
+ } else {
274
+ cell.textContent = cell.dataset.full;
275
+ cell.dataset.expanded='1';
276
+ }
277
+ });
278
+ });
279
+ }
280
+ }
281
+
282
+ function buildPagination(pageCount){
283
+ paginationEl.innerHTML='';
284
+ if(pageCount<=1) return;
285
+ const makeBtn=(label,disabled,on)=>{const b=document.createElement('button');b.textContent=label;b.disabled=disabled;b.addEventListener('click',on);return b;};
286
+ paginationEl.appendChild(makeBtn('Prev',currentPage===1,()=>{currentPage--;render();}));
287
+ paginationEl.insertAdjacentHTML('beforeend', `<span>Page ${currentPage} / ${pageCount}</span>`);
288
+ paginationEl.appendChild(makeBtn('Next',currentPage===pageCount,()=>{currentPage++;render();}));
289
+ }
290
+
291
+ form.addEventListener('submit',e=>{e.preventDefault(); const id=docIdInput.value.trim(); if(!id){setStatus('Document ID required',true);return;} fetchChunks(id);});
292
+ clearBtn.addEventListener('click',()=>{docIdInput.value='';filterInput.value='';sectionFilter.value='';indexFilter.value='';rawChunks=[];resultsPanel.style.display='none';setStatus('');});
293
+ [filterInput, sectionFilter, indexFilter, pageSizeInput].forEach(inp=>inp.addEventListener('input',()=>{currentPage=1;render();}));
294
+ cardsModeBtn.addEventListener('click',()=>{ if(cardsModeBtn.classList.contains('active')) return; cardsModeBtn.classList.add('active'); tableModeBtn.classList.remove('active'); chunksEl.style.display='flex'; tableWrapper.style.display='none'; render(); });
295
+ tableModeBtn.addEventListener('click',()=>{ if(tableModeBtn.classList.contains('active')) return; tableModeBtn.classList.add('active'); cardsModeBtn.classList.remove('active'); chunksEl.style.display='none'; tableWrapper.style.display='block'; render(); });
296
+ globalModeBtn.addEventListener('click',()=>{fetchAllChunks(); resultsPanel.style.display='block';});
297
+
298
+ const params = new URLSearchParams(window.location.search); const qsId = params.get('doc_id'); if(qsId){ docIdInput.value=qsId; fetchChunks(qsId); } else { fetchAllChunks(); }
299
+ </script>
300
+ </body>
301
+ </html>
static/index.html ADDED
@@ -0,0 +1,431 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>Technology Transactions Assistant (RAG model query interface)</title>
7
+ <style>
8
+ * {
9
+ margin: 0;
10
+ padding: 0;
11
+ box-sizing: border-box;
12
+ }
13
+
14
+ body {
15
+ font-family: -apple-system, BlinkMacSystemFont, 'SF Pro Rounded', 'SF Pro Display', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
16
+ background: #001122;
17
+ min-height: 100vh;
18
+ display: flex;
19
+ flex-direction: column;
20
+ align-items: center;
21
+ justify-content: center;
22
+ padding: 20px;
23
+ color: #fff;
24
+ }
25
+
26
+ .header-section {
27
+ width: 100%;
28
+ max-width: 1200px;
29
+ background: #333;
30
+ border-radius: 20px;
31
+ padding: 20px;
32
+ margin-bottom: 20px;
33
+ box-shadow: 0 18px 50px rgba(0, 0, 0, 0.5);
34
+ text-align: center;
35
+ }
36
+
37
+ .header-title {
38
+ color: #fff;
39
+ font-size: 2.5rem;
40
+ font-weight: 500;
41
+ text-decoration: underline;
42
+ text-shadow: 0 4px 8px rgba(0, 0, 0, 0.5);
43
+ margin: 0;
44
+ }
45
+
46
+ .header-subtitle {
47
+ color: #ccc;
48
+ font-size: 0.85rem;
49
+ font-weight: 400;
50
+ font-style: italic;
51
+ margin: 20px;
52
+ }
53
+
54
+ .header-subtitle a.upload-link {
55
+ color: #87CEFA;
56
+ text-decoration: none;
57
+ }
58
+
59
+ .header-subtitle a.upload-link:hover {
60
+ text-decoration: underline;
61
+ }
62
+
63
+ .banner-image {
64
+ display: none;
65
+ }
66
+
67
+ .main-container {
68
+ display: flex;
69
+ gap: 18px;
70
+ width: 100%;
71
+ max-width: 1200px;
72
+ height: 60vh;
73
+ align-items: stretch;
74
+ }
75
+
76
+ .left-container {
77
+ flex: 1;
78
+ background: #333;
79
+ border-radius: 20px;
80
+ padding: 32px;
81
+ box-shadow: 0 18px 50px rgba(0, 0, 0, 0.5);
82
+ display: flex;
83
+ flex-direction: column;
84
+ justify-content: flex-start;
85
+ gap: 10px;
86
+ min-height: 0;
87
+ }
88
+
89
+ .right-container {
90
+ flex: 1;
91
+ background: #333;
92
+ border-radius: 20px;
93
+ padding: 32px;
94
+ box-shadow: 0 18px 50px rgba(0, 0, 0, 0.5);
95
+ display: flex;
96
+ flex-direction: column;
97
+ min-height: 0;
98
+ position: relative;
99
+ }
100
+
101
+ .left-container h1 {
102
+ display: none;
103
+ }
104
+
105
+ .form-group {
106
+ margin-bottom: 20px;
107
+ }
108
+
109
+ label {
110
+ display: block;
111
+ margin-bottom: 8px;
112
+ font-weight: 600;
113
+ color: #fff;
114
+ font-size: 0.95rem;
115
+ letter-spacing: 0.5px;
116
+ }
117
+
118
+ .char-count {
119
+ float: right;
120
+ font-size: 0.85rem;
121
+ color: #ccc;
122
+ font-weight: normal;
123
+ text-transform: none;
124
+ letter-spacing: normal;
125
+ }
126
+
127
+ input[type="text"],
128
+ textarea {
129
+ width: 100%;
130
+ padding: 12px 16px;
131
+ border: 2px solid #555;
132
+ border-radius: 10px;
133
+ font-size: 1rem;
134
+ font-family: inherit;
135
+ transition: all 0.3s ease;
136
+ background: #222;
137
+ color: #fff;
138
+ }
139
+
140
+ input[type="text"]:focus,
141
+ textarea:focus {
142
+ outline: none;
143
+ border-color: #cc0000;
144
+ box-shadow: 0 0 0 3px rgba(204, 0, 0, 0.1);
145
+ }
146
+
147
+ textarea {
148
+ resize: vertical;
149
+ min-height: 120px;
150
+ }
151
+
152
+ .button-row {
153
+ display: flex;
154
+ gap: 12px;
155
+ margin-top: 10px;
156
+ }
157
+
158
+ .button-row .submit-btn,
159
+ .button-row .cancel-btn {
160
+ flex: 1;
161
+ padding: 12px 18px;
162
+ border-radius: 10px;
163
+ font-size: 1rem;
164
+ font-weight: 600;
165
+ cursor: pointer;
166
+ transition: all 0.2s ease;
167
+ letter-spacing: 1px;
168
+ }
169
+
170
+ .submit-btn {
171
+ background: #cfdff0;
172
+ color: #0b2233;
173
+ border: 1px solid rgba(255,255,255,0.06);
174
+ }
175
+
176
+ .submit-btn:hover {
177
+ background: #b9cee3;
178
+ transform: translateY(-2px);
179
+ box-shadow: 0 8px 18px rgba(11,34,51,0.12);
180
+ }
181
+
182
+ .submit-btn:active {
183
+ transform: translateY(0);
184
+ }
185
+
186
+ .cancel-btn {
187
+ background: rgba(255,102,102,0.45);
188
+ color: #fff;
189
+ border: none;
190
+ }
191
+
192
+ .cancel-btn:hover {
193
+ background: rgba(255,102,102,0.60);
194
+ color: #fff;
195
+ }
196
+
197
+ .output-section {
198
+ background: #222;
199
+ border: 2px solid #555;
200
+ border-radius: 10px;
201
+ padding: 20px;
202
+ flex: 1;
203
+ display: flex;
204
+ flex-direction: column;
205
+ align-items: flex-start;
206
+ justify-content: flex-start;
207
+ white-space: pre-wrap;
208
+ word-wrap: break-word;
209
+ font-family: 'Consolas', 'Monaco', monospace;
210
+ font-size: 0.95rem;
211
+ line-height: 1.6;
212
+ color: #fff;
213
+ overflow-y: auto;
214
+ margin-bottom: 0;
215
+ }
216
+
217
+ .output-section.empty {
218
+ align-items: center;
219
+ justify-content: center;
220
+ text-align: center;
221
+ }
222
+
223
+ .output-placeholder {
224
+ color: #ccc;
225
+ font-style: italic;
226
+ display: block;
227
+ }
228
+
229
+ .loading {
230
+ display: none;
231
+ position: absolute;
232
+ top: 0;
233
+ left: 0;
234
+ right: 0;
235
+ bottom: 0;
236
+ align-items: center;
237
+ justify-content: center;
238
+ text-align: center;
239
+ color: #ffd700;
240
+ background: #222;
241
+ border-radius: 10px;
242
+ flex-direction: column;
243
+ gap: 12px;
244
+ }
245
+
246
+ .loading.active {
247
+ display: flex;
248
+ }
249
+
250
+ .spinner {
251
+ display: inline-block;
252
+ width: 20px;
253
+ height: 20px;
254
+ border: 3px solid rgba(255, 215, 0, 0.3);
255
+ border-radius: 50%;
256
+ border-top-color: #ffd700;
257
+ animation: spin 1s ease-in-out infinite;
258
+ }
259
+
260
+ @keyframes spin {
261
+ to { transform: rotate(360deg); }
262
+ }
263
+
264
+ @media (max-width: 768px) {
265
+ .main-container {
266
+ flex-direction: column;
267
+ height: auto;
268
+ }
269
+ }
270
+ </style>
271
+ </head>
272
+ <body>
273
+ <div class="header-section">
274
+ <h1 class="header-title">Technology Transactions Assistant</h1>
275
+ <p class="header-subtitle">A RAG model that restricts GPT-5 to technology transactions use cases in the legal domain. To add to the corpus, visit <a href="/upload" class="upload-link">/upload</a>.</p>
276
+ </div>
277
+
278
+ <div class="main-container">
279
+ <div class="left-container">
280
+ <h1>TechTrans Query</h1>
281
+
282
+ <form id="queryForm">
283
+ <div class="form-group">
284
+ <label for="query">
285
+ Query
286
+ <span class="char-count"><span id="queryCount">0</span>/1000</span>
287
+ </label>
288
+ <textarea
289
+ id="query"
290
+ name="query"
291
+ maxlength="1000"
292
+ placeholder="Enter query here (e.g., 'Show an example of a confidentiality clause,' 'Define the term Affiliate,' etc.)"
293
+ required
294
+ ></textarea>
295
+ </div>
296
+
297
+ <div class="form-group">
298
+ <label for="docType">Document Type (optional)
299
+ <span class="char-count"><span id="docTypeCount">0</span>/200</span>
300
+ </label>
301
+ <input type="text" id="docType" name="docType" maxlength="200" placeholder="e.g., License Agreement, Terms of Use..." />
302
+ </div>
303
+
304
+ <div class="form-group">
305
+ <label for="jurisdiction">Jurisdiction (optional)
306
+ <span class="char-count"><span id="jurisdictionCount">0</span>/200</span>
307
+ </label>
308
+ <input type="text" id="jurisdiction" name="jurisdiction" maxlength="200" placeholder="e.g., US-CA, US-DE, FRG..." />
309
+ </div>
310
+
311
+ <div class="form-group">
312
+ <label for="topK">Top K Chunks <span class="char-count" style="float:none;">(max 20)</span></label>
313
+ <input type="number" id="topK" name="topK" value="5" min="1" max="20" />
314
+ </div>
315
+
316
+ <div class="button-row">
317
+ <button type="button" class="cancel-btn" id="cancelBtn">Clear</button>
318
+ <button type="submit" class="submit-btn">Search</button>
319
+ </div>
320
+ </form>
321
+ </div>
322
+
323
+ <div class="right-container">
324
+ <label for="response">Query Results</label>
325
+ <div id="response" class="output-section empty">
326
+ <span class="output-placeholder">Response will appear here...</span>
327
+ </div>
328
+ <div class="loading" id="loading">
329
+ <div class="spinner"></div>
330
+ <p>Running vector search...</p>
331
+ </div>
332
+ </div>
333
+ </div>
334
+
335
+ <script>
336
+ // Character count for inputs
337
+ function updateCharCount(inputId, counterId) {
338
+ const input = document.getElementById(inputId);
339
+ const counter = document.getElementById(counterId);
340
+ input.addEventListener('input', () => counter.textContent = input.value.length);
341
+ counter.textContent = input.value.length;
342
+ }
343
+ updateCharCount('query', 'queryCount');
344
+ updateCharCount('docType', 'docTypeCount');
345
+ updateCharCount('jurisdiction', 'jurisdictionCount');
346
+
347
+ document.getElementById('cancelBtn').addEventListener('click', () => {
348
+ document.getElementById('query').value = '';
349
+ document.getElementById('docType').value = '';
350
+ document.getElementById('jurisdiction').value = '';
351
+ document.getElementById('topK').value = '5';
352
+ document.getElementById('queryCount').textContent = '0';
353
+ document.getElementById('docTypeCount').textContent = '0';
354
+ document.getElementById('jurisdictionCount').textContent = '0';
355
+ const responseDiv = document.getElementById('response');
356
+ responseDiv.innerHTML = '<span class="output-placeholder">Response will appear here...</span>';
357
+ responseDiv.classList.add('empty');
358
+ });
359
+
360
+ document.getElementById('queryForm').addEventListener('submit', async (e) => {
361
+ e.preventDefault();
362
+ const q = document.getElementById('query').value.trim();
363
+ const topK = parseInt(document.getElementById('topK').value, 10) || 5;
364
+ if (!q) return;
365
+
366
+ const filters = {};
367
+ const dt = document.getElementById('docType').value.trim();
368
+ const jur = document.getElementById('jurisdiction').value.trim();
369
+ if (dt) filters.doc_type = dt;
370
+ if (jur) filters.jurisdiction = jur;
371
+ const body = { query: q, top_k: topK, filters };
372
+ const responseDiv = document.getElementById('response');
373
+ const loadingDiv = document.getElementById('loading');
374
+ responseDiv.innerHTML = '';
375
+ responseDiv.classList.remove('empty');
376
+ loadingDiv.classList.add('active');
377
+
378
+ try {
379
+ const resp = await fetch('/api/query', {
380
+ method: 'POST',
381
+ headers: { 'Content-Type': 'application/json' },
382
+ body: JSON.stringify(body)
383
+ });
384
+ const data = await resp.json().catch(() => ({}));
385
+ loadingDiv.classList.remove('active');
386
+
387
+ const escape = (str) => String(str ?? '')
388
+ .replace(/&/g,'&amp;')
389
+ .replace(/</g,'&lt;')
390
+ .replace(/>/g,'&gt;');
391
+
392
+ if (!resp.ok) {
393
+ const msg = data.error || resp.statusText || 'Request failed';
394
+ responseDiv.innerHTML = `<span style="color:#e53e3e;">Error: ${escape(msg)}</span>`;
395
+ return;
396
+ }
397
+
398
+ if (data.error) {
399
+ responseDiv.innerHTML = `<span style="color:#e53e3e;">Error: ${escape(data.error)}</span>`;
400
+ return;
401
+ }
402
+
403
+ const parts = [];
404
+ parts.push(`<u>Query:</u> ${escape(data.query)}`);
405
+ if (data.filters && (data.filters.doc_type || data.filters.jurisdiction)) {
406
+ parts.push(`<u>Filters:</u> doc_type=${escape(data.filters.doc_type || '—')} jurisdiction=${escape(data.filters.jurisdiction || '—')}`);
407
+ }
408
+ const results = Array.isArray(data.results) ? data.results : [];
409
+ if (!results.length) {
410
+ parts.push('<u>Results:</u> <em>No chunks returned (vector index empty or not configured).</em>');
411
+ } else {
412
+ const list = results.map((r, idx) => {
413
+ const dist = (typeof r.distance === 'number') ? r.distance.toFixed(4) : escape(r.distance);
414
+ const txt = escape((r.text || '').slice(0, 500));
415
+ return `<li style="margin-bottom:14px; line-height:1.35;">
416
+ <div><strong>#${idx+1}</strong> chunk_id=${escape(r.chunk_id)} distance=${dist}</div>
417
+ <div style="color:#ccc; font-size:0.7rem; margin-top:2px; font-style:italic;">${escape(r.title || '')} ${r.doc_type ? '('+escape(r.doc_type)+')' : ''} ${r.jurisdiction ? '['+escape(r.jurisdiction)+']' : ''}</div>
418
+ <div style="color:#ccc; font-size:0.85rem; margin-top:4px;">${txt}${r.text && r.text.length > 500 ? '…' : ''}</div>
419
+ </li>`;
420
+ }).join('');
421
+ parts.push(`<details open><summary style="cursor:pointer; margin-top:10px;"><u>Results (${results.length})</u></summary><ol style="margin-top:8px; padding-left:20px;">${list}</ol></details>`);
422
+ }
423
+ responseDiv.innerHTML = parts.join('\n\n');
424
+ } catch (err) {
425
+ loadingDiv.classList.remove('active');
426
+ responseDiv.innerHTML = `<span style="color:#e53e3e;">Error: ${err.message}</span>`;
427
+ }
428
+ });
429
+ </script>
430
+ </body>
431
+ </html>
static/manifest.html ADDED
@@ -0,0 +1,394 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <meta name="viewport" content="width=device-width,initial-scale=1.0" />
6
+ <title>Document Manifest Viewer</title>
7
+ <style>
8
+ * { margin:0; padding:0; box-sizing:border-box; }
9
+ body {
10
+ font-family:-apple-system,BlinkMacSystemFont,'SF Pro Rounded','SF Pro Display',Roboto,Oxygen,Ubuntu,Cantarell,sans-serif;
11
+ background:#001122; color:#fff; min-height:100vh; padding:28px; display:flex; flex-direction:column; gap:28px; align-items:center;
12
+ }
13
+ .shell { width:100%; max-width:1200px; display:flex; flex-direction:column; gap:26px; }
14
+ .panel { background:#333; border-radius:20px; padding:28px 32px; box-shadow:0 18px 50px rgba(0,0,0,.5); }
15
+ h1 { font-size:2.2rem; font-weight:500; text-shadow:0 4px 8px rgba(0,0,0,.5); margin:0 0 8px; }
16
+ p.sub { font-size:.8rem; color:#ccc; font-style:italic; line-height:1.5; }
17
+ a { color:#87CEFA; text-decoration:none; }
18
+ a:hover { text-decoration:underline; }
19
+ form.query { display:flex; flex-wrap:wrap; gap:14px; align-items:flex-end; }
20
+ form.query > div { display:flex; flex-direction:column; gap:6px; }
21
+ label { font-size:.7rem; text-transform:uppercase; letter-spacing:1px; color:#ccc; }
22
+ input[type="number"], input[type="text"] { background:#222; border:2px solid #555; border-radius:10px; padding:10px 14px; color:#fff; font-family:inherit; min-width:140px; }
23
+ input:focus { outline:none; border-color:#7ec8ff; box-shadow:0 0 0 3px rgba(126,200,255,0.15); }
24
+ button { background:#7ec8ff; color:#001122; border:none; padding:12px 22px; border-radius:10px; font-weight:600; cursor:pointer; font-size:.9rem; letter-spacing:1px; transition:.25s; box-shadow:0 8px 18px rgba(126,200,255,0.25); }
25
+ button:hover { background:#6bb8ff; transform:translateY(-2px); }
26
+ button:active { transform:translateY(0); }
27
+ button.secondary { background:rgba(255,102,102,.45); color:#fff; box-shadow:none; }
28
+ button.secondary:hover { background:rgba(255,102,102,.6); }
29
+ .status { font-size:.75rem; color:#ccc; margin-top:6px; min-height:18px; }
30
+ .results { display:flex; flex-direction:column; gap:22px; }
31
+ .view-toggles { display:flex; gap:10px; flex-wrap:wrap; }
32
+ .view-toggles button { background:#2d3f4d; color:#cfe9ff; box-shadow:none; padding:8px 14px; font-size:.7rem; }
33
+ .view-toggles button.active { background:#7ec8ff; color:#001122; }
34
+ .meta-grid { display:grid; grid-template-columns:repeat(auto-fit,minmax(200px,1fr)); gap:14px; }
35
+ .kv { background:#222; border:2px solid #555; border-radius:12px; padding:12px 14px; display:flex; flex-direction:column; gap:4px; }
36
+ .kv span.k { font-size:.65rem; text-transform:uppercase; letter-spacing:1px; color:#999; }
37
+ .kv span.v { font-size:.85rem; word-break:break-word; }
38
+ .records { background:#222; border:2px solid #555; border-radius:16px; padding:20px; display:flex; flex-direction:column; gap:20px; max-height:50vh; overflow:auto; }
39
+ .table-wrapper { background:#222; border:2px solid #555; border-radius:16px; padding:14px 18px; max-height:55vh; overflow:auto; }
40
+ table.data-table { width:100%; border-collapse:collapse; font-size:.7rem; }
41
+ table.data-table th, table.data-table td { padding:6px 8px; text-align:left; border:1px solid #444; vertical-align:top; }
42
+ table.data-table th { position:sticky; top:0; background:#2d3f4d; z-index:2; font-weight:600; letter-spacing:.5px; }
43
+ table.data-table tbody tr:nth-child(even){ background:#1e2a33; }
44
+ .truncate { max-width:300px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
45
+ .row-expand { cursor:pointer; color:#87CEFA; font-size:.6rem; }
46
+ .record { background:#1b2733; border:1px solid #3d4c55; border-radius:12px; padding:16px 18px; display:flex; flex-direction:column; gap:10px; position:relative; }
47
+ .record h3 { margin:0; font-size:.95rem; font-weight:600; }
48
+ .badge-row { display:flex; flex-wrap:wrap; gap:6px; }
49
+ .badge { background:#2d3f4d; color:#cfe9ff; font-size:.6rem; padding:4px 8px; border-radius:100px; letter-spacing:.5px; text-transform:uppercase; }
50
+ .json-view { font-family:Consolas,Monaco,monospace; font-size:.7rem; background:#111a22; border:1px solid #2c3a44; border-radius:8px; padding:10px 12px; white-space:pre; overflow:auto; max-height:240px; }
51
+ .empty { text-align:center; font-style:italic; color:#ccc; }
52
+ .error { color:#ff7b7b; font-weight:600; }
53
+ .spinner { width:18px; height:18px; border:3px solid rgba(255,255,255,.2); border-top-color:#7ec8ff; border-radius:50%; animation:spin 1s linear infinite; }
54
+ .inline { display:inline-flex; align-items:center; gap:10px; }
55
+ @keyframes spin { to { transform:rotate(360deg);} }
56
+ .toolbar { display:flex; gap:10px; flex-wrap:wrap; }
57
+ .filter-box { background:#222; border:2px solid #555; border-radius:10px; padding:8px 12px; display:flex; gap:10px; }
58
+ .filter-box input { border:none; background:transparent; padding:0; font-size:.75rem; min-width:160px; }
59
+ .filter-box input:focus { outline:none; }
60
+ .copy-btn { position:absolute; top:10px; right:10px; font-size:.55rem; padding:4px 8px; background:#2d3f4d; color:#fff; border:none; border-radius:6px; cursor:pointer; }
61
+ .copy-btn:hover { background:#3d5566; }
62
+ @media (max-width:800px){ .panel { padding:22px 20px; } h1 { font-size:1.7rem; } }
63
+ .pagination { display:flex; gap:8px; align-items:center; flex-wrap:wrap; margin-top:12px; font-size:.65rem; }
64
+ .pagination button { padding:6px 10px; font-size:.65rem; background:#2d3f4d; color:#cfe9ff; box-shadow:none; }
65
+ .pagination button:disabled { opacity:.35; cursor:not-allowed; }
66
+ th.sortable { cursor:pointer; user-select:none; }
67
+ th.sortable:hover { background:#355064; }
68
+ th.sortable .indicator { font-size:.55rem; margin-left:4px; opacity:.8; }
69
+ tr.editing { background:#283745 !important; }
70
+ td.editable { cursor:text; }
71
+ td.editable:hover { background:#203240; }
72
+ .row-actions { display:flex; gap:6px; }
73
+ .row-actions button { padding:4px 10px; font-size:.6rem; background:#355064; color:#cfe9ff; }
74
+ .row-actions button.confirm { background:#4caf50; color:#fff; }
75
+ .row-actions button.cancel { background:#d9534f; color:#fff; }
76
+ </style>
77
+ </head>
78
+ <body>
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>
86
+ <input type="text" id="filter" placeholder="Type to filter rows" />
87
+ </div>
88
+ <div style="display:flex; gap:8px;">
89
+ <button type="button" id="refreshBtn">Refresh</button>
90
+ <button type="button" class="secondary" id="clearBtn">Clear</button>
91
+ </div>
92
+ </form>
93
+ <div class="status" id="status"></div>
94
+ </div>
95
+ <div class="panel" id="manifestPanel">
96
+ <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:10px;gap:10px;flex-wrap:wrap;">
97
+ <h2 style="font-size:1.2rem;margin:0;">Manifest Entries</h2>
98
+ <div style="font-size:.65rem;letter-spacing:1px;color:#ccc;">Total: <span id="rowCount">0</span></div>
99
+ </div>
100
+ <div class="table-wrapper" id="manifestTableWrapper"></div>
101
+ <div class="pagination" id="pagination" style="display:none;">
102
+ <button id="firstPage" title="First">⏮</button>
103
+ <button id="prevPage" title="Previous">◀</button>
104
+ <span>Page <span id="pageNum">1</span> / <span id="pageCount">1</span></span>
105
+ <button id="nextPage" title="Next">▶</button>
106
+ <button id="lastPage" title="Last">⏭</button>
107
+ <span>| Rows: <span id="visibleCount">0</span> / <span id="totalCount">0</span></span>
108
+ </div>
109
+ </div>
110
+ </div>
111
+
112
+ <script>
113
+ const filterForm = document.getElementById('filterForm');
114
+ const filterInput = document.getElementById('filter');
115
+ const statusEl = document.getElementById('status');
116
+ const refreshBtn = document.getElementById('refreshBtn');
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');
128
+ const firstPageBtn = document.getElementById('firstPage');
129
+ const prevPageBtn = document.getElementById('prevPage');
130
+ const nextPageBtn = document.getElementById('nextPage');
131
+ const lastPageBtn = document.getElementById('lastPage');
132
+ const pageNumEl = document.getElementById('pageNum');
133
+ const pageCountEl = document.getElementById('pageCount');
134
+ const visibleCountEl = document.getElementById('visibleCount');
135
+ const totalCountEl = document.getElementById('totalCount');
136
+
137
+ function esc(v){
138
+ return String(v ?? '').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
139
+ }
140
+
141
+ function setStatus(msg, isError=false){
142
+ statusEl.innerHTML = msg ? `<span class="${isError?'error':''}">${esc(msg)}</span>` : '';
143
+ }
144
+
145
+ function spinner(){
146
+ setStatus(`<span class='inline'><span class='spinner'></span> Loading...</span>`);
147
+ }
148
+
149
+ function buildMetaCard(k, v){
150
+ return `<div class="kv"><span class="k">${esc(k)}</span><span class="v">${esc(v)}</span></div>`;
151
+ }
152
+
153
+ function filteredRows(){
154
+ const term = filterInput.value.trim().toLowerCase();
155
+ if(!term) return manifestRows;
156
+ return manifestRows.filter(r => JSON.stringify(r).toLowerCase().includes(term));
157
+ }
158
+
159
+ function compareValues(a, b){
160
+ // Attempt numeric compare if both parse to numbers
161
+ const an = parseFloat(a); const bn = parseFloat(b);
162
+ const aNum = !isNaN(an) && String(an) === String(a).trim();
163
+ const bNum = !isNaN(bn) && String(bn) === String(b).trim();
164
+ if(aNum && bNum){
165
+ if(an < bn) return -1; if(an > bn) return 1; return 0;
166
+ }
167
+ const as = String(a).toLowerCase();
168
+ const bs = String(b).toLowerCase();
169
+ if(as < bs) return -1; if(as > bs) return 1; return 0;
170
+ }
171
+
172
+ function sortRows(rows){
173
+ if(!sortCol) return rows;
174
+ return [...rows].sort((r1, r2) => {
175
+ const v1 = r1[sortCol] ?? '';
176
+ const v2 = r2[sortCol] ?? '';
177
+ const cmp = compareValues(v1, v2);
178
+ return sortDir === 'asc' ? cmp : -cmp;
179
+ });
180
+ }
181
+
182
+ function setSort(col){
183
+ if(sortCol === col){
184
+ sortDir = sortDir === 'asc' ? 'desc' : 'asc';
185
+ } else {
186
+ sortCol = col;
187
+ sortDir = 'asc';
188
+ }
189
+ currentPage = 1;
190
+ renderTable();
191
+ }
192
+
193
+ function buildHeader(cols){
194
+ return cols.map(c => {
195
+ const active = c === sortCol;
196
+ const indicator = active ? (sortDir === 'asc' ? '▲' : '▼') : '';
197
+ return `<th class="sortable" data-col="${esc(c)}">${esc(c)}<span class="indicator">${indicator}</span></th>`;
198
+ }).join('');
199
+ }
200
+
201
+ function paginate(rows){
202
+ const pageCount = Math.max(1, Math.ceil(rows.length / PAGE_SIZE));
203
+ if(currentPage > pageCount) currentPage = pageCount;
204
+ const start = (currentPage - 1) * PAGE_SIZE;
205
+ const slice = rows.slice(start, start + PAGE_SIZE);
206
+ // Update controls
207
+ pageNumEl.textContent = String(currentPage);
208
+ pageCountEl.textContent = String(pageCount);
209
+ visibleCountEl.textContent = String(slice.length);
210
+ totalCountEl.textContent = String(rows.length);
211
+ firstPageBtn.disabled = currentPage === 1;
212
+ prevPageBtn.disabled = currentPage === 1;
213
+ nextPageBtn.disabled = currentPage === pageCount;
214
+ lastPageBtn.disabled = currentPage === pageCount;
215
+ paginationEl.style.display = rows.length ? 'flex' : 'none';
216
+ return slice;
217
+ }
218
+
219
+ function renderTable(){
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>';
245
+ manifestTableWrapper.innerHTML = html;
246
+ // Header sort handlers
247
+ manifestTableWrapper.querySelectorAll('th.sortable').forEach(th => {
248
+ th.addEventListener('click', () => {
249
+ const col = th.getAttribute('data-col');
250
+ if(col) setSort(col);
251
+ });
252
+ });
253
+ attachEditing();
254
+ }
255
+
256
+ function fetchManifestAll(){
257
+ spinner();
258
+ fetch('/api/manifest')
259
+ .then(r => r.json())
260
+ .then(data => {
261
+ // Endpoint returns the parsed JSONL. Expect either array or object with manifest key.
262
+ if(Array.isArray(data)) manifestRows = data;
263
+ else if(Array.isArray(data.manifest)) manifestRows = data.manifest;
264
+ else manifestRows = [];
265
+ setStatus(manifestRows.length ? `Loaded ${manifestRows.length} entries.` : 'No manifest entries.');
266
+ renderTable();
267
+ })
268
+ .catch(err => { setStatus('Failed to load manifest: ' + err.message, true); manifestRows = []; renderTable(); });
269
+ }
270
+
271
+ filterInput.addEventListener('input', renderTable);
272
+ refreshBtn.addEventListener('click', fetchManifestAll);
273
+ clearBtn.addEventListener('click', () => { filterInput.value=''; currentPage=1; renderTable(); setStatus(''); });
274
+ firstPageBtn.addEventListener('click', () => { currentPage = 1; renderTable(); });
275
+ prevPageBtn.addEventListener('click', () => { if(currentPage>1){ currentPage--; renderTable(); } });
276
+ nextPageBtn.addEventListener('click', () => { currentPage++; renderTable(); });
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',
360
+ headers: { 'Content-Type': 'application/json' },
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
391
+ fetchManifestAll();
392
+ </script>
393
+ </body>
394
+ </html>
static/upload.html ADDED
@@ -0,0 +1,518 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <title>Technology Transactions Assistant - Document Upload</title>
7
+ <style>
8
+ * {
9
+ margin: 0;
10
+ padding: 0;
11
+ box-sizing: border-box;
12
+ }
13
+
14
+ body {
15
+ font-family: -apple-system, BlinkMacSystemFont, 'SF Pro Rounded', 'SF Pro Display', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
16
+ background: #001122;
17
+ min-height: 100vh;
18
+ display: flex;
19
+ flex-direction: column;
20
+ align-items: center;
21
+ justify-content: center;
22
+ padding: 20px;
23
+ color: #fff;
24
+ }
25
+
26
+ .header-section {
27
+ width: 100%;
28
+ max-width: 800px;
29
+ background: #333;
30
+ border-radius: 20px;
31
+ padding: 20px;
32
+ margin-bottom: 20px;
33
+ box-shadow: 0 18px 50px rgba(0, 0, 0, 0.5);
34
+ text-align: center;
35
+ }
36
+
37
+ .header-title {
38
+ color: #fff;
39
+ font-size: 2.5rem;
40
+ font-weight: 500;
41
+ text-shadow: 0 4px 8px rgba(0, 0, 0, 0.5);
42
+ margin: 0;
43
+ }
44
+
45
+ .upload-container {
46
+ width: 100%;
47
+ max-width: 800px;
48
+ background: #333;
49
+ border-radius: 20px;
50
+ padding: 40px;
51
+ box-shadow: 0 18px 50px rgba(0, 0, 0, 0.5);
52
+ display: flex;
53
+ flex-direction: column;
54
+ align-items: center;
55
+ gap: 25px;
56
+ }
57
+
58
+ .upload-title {
59
+ color: #ccc;
60
+ font-size: 1.8rem;
61
+ font-weight: 500;
62
+ text-align: center;
63
+ text-shadow: 0 4px 8px rgba(0, 0, 0, 0.5);
64
+ margin-bottom: 10px;
65
+ }
66
+
67
+ .upload-description {
68
+ color: #ccc;
69
+ font-size: 1rem;
70
+ text-align: center;
71
+ margin-bottom: 20px;
72
+ line-height: 1.5;
73
+ }
74
+
75
+ .upload-area {
76
+ width: 100%;
77
+ border: 3px dashed #555;
78
+ border-radius: 15px;
79
+ padding: 40px 20px;
80
+ text-align: center;
81
+ background: #222;
82
+ transition: all 0.3s ease;
83
+ cursor: pointer;
84
+ position: relative;
85
+ }
86
+
87
+ .upload-area:hover {
88
+ border-color: #7ec8ff;
89
+ background: #2a2a2a;
90
+ }
91
+
92
+ .upload-area.dragover {
93
+ border-color: #7ec8ff;
94
+ background: #2a2a2a;
95
+ transform: scale(1.02);
96
+ }
97
+
98
+ .upload-icon {
99
+ font-size: 3rem;
100
+ color: #555;
101
+ margin-bottom: 15px;
102
+ }
103
+
104
+ .upload-text {
105
+ color: #ccc;
106
+ font-size: 1rem;
107
+ margin-bottom: 10px;
108
+ }
109
+
110
+ .upload-subtext {
111
+ color: #888;
112
+ font-size: 0.9rem;
113
+ }
114
+
115
+ .file-input {
116
+ position: absolute;
117
+ top: 0;
118
+ left: 0;
119
+ width: 100%;
120
+ height: 100%;
121
+ opacity: 0;
122
+ cursor: pointer;
123
+ }
124
+
125
+ .selected-file {
126
+ display: none;
127
+ background: #222;
128
+ border: 2px solid #555;
129
+ border-radius: 10px;
130
+ padding: 15px;
131
+ width: 100%;
132
+ margin-top: 20px;
133
+ }
134
+
135
+ .selected-file.visible {
136
+ display: block;
137
+ }
138
+
139
+ .file-info {
140
+ display: flex;
141
+ align-items: center;
142
+ gap: 10px;
143
+ color: #fff;
144
+ }
145
+
146
+ .file-name {
147
+ font-weight: 600;
148
+ }
149
+
150
+ .file-size {
151
+ color: #ccc;
152
+ font-size: 0.9rem;
153
+ }
154
+
155
+ .remove-file {
156
+ margin-left: auto;
157
+ background: rgba(255,102,102,0.45);
158
+ color: #fff;
159
+ border: none;
160
+ padding: 5px 10px;
161
+ border-radius: 5px;
162
+ cursor: pointer;
163
+ font-size: 0.8rem;
164
+ }
165
+
166
+ .remove-file:hover {
167
+ background: rgba(255,102,102,0.60);
168
+ }
169
+
170
+ .upload-button {
171
+ background: #7ec8ff;
172
+ color: #001122;
173
+ border: none;
174
+ padding: 14px 30px;
175
+ border-radius: 10px;
176
+ font-size: 1rem;
177
+ font-weight: 600;
178
+ cursor: pointer;
179
+ transition: all 0.3s ease;
180
+ letter-spacing: 1px;
181
+ margin-top: 10px;
182
+ display: none;
183
+ }
184
+
185
+ .upload-button.visible {
186
+ display: block;
187
+ }
188
+
189
+ .upload-button:hover {
190
+ background: #6bb8ff;
191
+ transform: translateY(-2px);
192
+ box-shadow: 0 8px 18px rgba(126, 200, 255, 0.3);
193
+ }
194
+
195
+ .upload-button:active {
196
+ transform: translateY(0);
197
+ }
198
+
199
+ .upload-button:disabled {
200
+ background: #555;
201
+ color: #999;
202
+ cursor: not-allowed;
203
+ transform: none;
204
+ box-shadow: none;
205
+ }
206
+
207
+ .progress-container {
208
+ width: 100%;
209
+ background: #222;
210
+ border-radius: 10px;
211
+ overflow: hidden;
212
+ margin-top: 20px;
213
+ display: none;
214
+ }
215
+
216
+ .progress-container.visible {
217
+ display: block;
218
+ }
219
+
220
+ .progress-bar {
221
+ height: 6px;
222
+ background: #7ec8ff;
223
+ width: 0%;
224
+ transition: width 0.3s ease;
225
+ }
226
+
227
+ .progress-text {
228
+ padding: 10px;
229
+ text-align: center;
230
+ color: #ccc;
231
+ font-size: 0.9rem;
232
+ }
233
+
234
+ .upload-result {
235
+ display: none;
236
+ padding: 20px;
237
+ border-radius: 10px;
238
+ margin-top: 20px;
239
+ text-align: center;
240
+ word-break: break-word;
241
+ }
242
+
243
+ .upload-result.success {
244
+ background: rgba(72, 187, 120, 0.2);
245
+ border: 2px solid rgba(72, 187, 120, 0.5);
246
+ color: #48bb78;
247
+ }
248
+
249
+ .upload-result.error {
250
+ background: rgba(245, 101, 101, 0.2);
251
+ border: 2px solid rgba(245, 101, 101, 0.5);
252
+ color: #f56565;
253
+ }
254
+
255
+ @media (max-width: 768px) {
256
+ .upload-container {
257
+ padding: 30px 20px;
258
+ }
259
+
260
+ .header-title {
261
+ font-size: 2rem;
262
+ }
263
+
264
+ .upload-title {
265
+ font-size: 1.5rem;
266
+ }
267
+ }
268
+ </style>
269
+ </head>
270
+ <body>
271
+ <div class="header-section">
272
+ <h1 class="header-title">Technology Transactions Assistant</h1>
273
+ </div>
274
+
275
+ <div class="upload-container">
276
+ <h2 class="upload-title">Document Upload</h2>
277
+ <p class="upload-description">
278
+ Upload a technology transactions document (pdf, txt, or docx; max 10MB)
279
+ </p>
280
+
281
+ <form id="uploadForm" enctype="multipart/form-data">
282
+ <div class="upload-area" id="uploadArea">
283
+ <div class="upload-icon">📄</div>
284
+ <div class="upload-text">Drag and drop file here</div>
285
+ <div class="upload-subtext">or click to browse</div>
286
+ <!-- Added name="file" so the backend sees the expected field name -->
287
+ <input type="file" id="fileInput" name="file" class="file-input" accept=".pdf,.docx,.txt" />
288
+ </div>
289
+
290
+ <div style="display:flex; gap:16px; width:100%; margin-top:18px;">
291
+ <div style="flex:1; display:flex; flex-direction:column; gap:6px;">
292
+ <label for="docType" style="font-size:0.8rem; color:#ccc;">Document Type (optional)</label>
293
+ <input id="docType" name="doc_type" type="text" maxlength="128" placeholder="e.g., License Agreement" style="background:#222; border:2px solid #555; border-radius:8px; padding:10px; color:#fff; font-family:inherit; font-size:0.85rem;" />
294
+ </div>
295
+ <div style="flex:1; display:flex; flex-direction:column; gap:6px;">
296
+ <label for="jurisdiction" style="font-size:0.8rem; color:#ccc;">Jurisdiction (optional)</label>
297
+ <input id="jurisdiction" name="jurisdiction" type="text" maxlength="64" placeholder="e.g., US-CA" style="background:#222; border:2px solid #555; border-radius:8px; padding:10px; color:#fff; font-family:inherit; font-size:0.85rem;" />
298
+ </div>
299
+ </div>
300
+
301
+ <div class="selected-file" id="selectedFile">
302
+ <div class="file-info">
303
+ <span class="file-name" id="fileName"></span>
304
+ <span class="file-size" id="fileSize"></span>
305
+ <button type="button" class="remove-file" id="removeFile">Remove</button>
306
+ </div>
307
+ </div>
308
+
309
+ <button type="submit" class="upload-button" id="uploadButton">Upload Document</button>
310
+ </form>
311
+
312
+ <div class="progress-container" id="progressContainer">
313
+ <div class="progress-bar" id="progressBar"></div>
314
+ <div class="progress-text" id="progressText">Uploading...</div>
315
+ <div style="font-size: 0.7rem; font-style: italic; text-align: center; color: #ccc; padding: 0 10px 10px;">
316
+ Note: Generating and indexing embeddings will take several minutes. Thank you for your patience.
317
+ </div>
318
+ </div>
319
+
320
+ <div class="upload-result" id="uploadResult"></div>
321
+ </div>
322
+
323
+ <script>
324
+ const uploadArea = document.getElementById('uploadArea');
325
+ const fileInput = document.getElementById('fileInput');
326
+ const selectedFile = document.getElementById('selectedFile');
327
+ const fileName = document.getElementById('fileName');
328
+ const fileSize = document.getElementById('fileSize');
329
+ const removeFile = document.getElementById('removeFile');
330
+ const uploadButton = document.getElementById('uploadButton');
331
+ const uploadForm = document.getElementById('uploadForm');
332
+ const progressContainer = document.getElementById('progressContainer');
333
+ const progressBar = document.getElementById('progressBar');
334
+ const progressText = document.getElementById('progressText');
335
+ const uploadResult = document.getElementById('uploadResult');
336
+
337
+ let selectedFileObj = null;
338
+
339
+ // File input change handler
340
+ fileInput.addEventListener('change', handleFileSelect);
341
+
342
+ // Drag and drop handlers
343
+ uploadArea.addEventListener('dragover', (e) => {
344
+ e.preventDefault();
345
+ uploadArea.classList.add('dragover');
346
+ });
347
+
348
+ uploadArea.addEventListener('dragleave', () => {
349
+ uploadArea.classList.remove('dragover');
350
+ });
351
+
352
+ uploadArea.addEventListener('drop', (e) => {
353
+ e.preventDefault();
354
+ uploadArea.classList.remove('dragover');
355
+
356
+ const files = e.dataTransfer.files;
357
+ if (files.length > 0) {
358
+ handleFile(files[0]);
359
+ }
360
+ });
361
+
362
+ // Remove file handler
363
+ removeFile.addEventListener('click', () => {
364
+ clearFileSelection();
365
+ uploadResult.style.display = 'none';
366
+ });
367
+
368
+ // Form submission handler — use XMLHttpRequest to support upload progress
369
+ uploadForm.addEventListener('submit', (e) => {
370
+ e.preventDefault();
371
+
372
+ if (!selectedFileObj) {
373
+ showResult('Please select a file to upload.', 'error');
374
+ return;
375
+ }
376
+
377
+ uploadButton.disabled = true;
378
+ progressContainer.classList.add('visible');
379
+ uploadResult.style.display = 'none';
380
+ progressBar.style.width = '0%';
381
+ progressText.textContent = 'Starting upload...';
382
+
383
+ const formData = new FormData();
384
+ formData.append('file', selectedFileObj);
385
+ const dt = document.getElementById('docType').value.trim();
386
+ const jur = document.getElementById('jurisdiction').value.trim();
387
+ if (dt) formData.append('doc_type', dt);
388
+ if (jur) formData.append('jurisdiction', jur);
389
+
390
+ const xhr = new XMLHttpRequest();
391
+ xhr.open('POST', '/api/upload', true);
392
+
393
+ // Upload progress
394
+ xhr.upload.onprogress = function(event) {
395
+ if (event.lengthComputable) {
396
+ const percent = Math.round((event.loaded / event.total) * 100);
397
+ progressBar.style.width = percent + '%';
398
+ progressText.textContent = `Uploading... ${percent}%`;
399
+ }
400
+ };
401
+
402
+ xhr.onload = function() {
403
+ uploadButton.disabled = false;
404
+ // Attempt to parse JSON response from server
405
+ let responseJson = null;
406
+ try {
407
+ responseJson = JSON.parse(xhr.responseText || '{}');
408
+ } catch (err) {
409
+ showResult('Upload failed: invalid server response.', 'error');
410
+ progressContainer.classList.remove('visible');
411
+ return;
412
+ }
413
+
414
+ if (xhr.status >= 200 && xhr.status < 300) {
415
+ progressBar.style.width = '100%';
416
+ progressText.textContent = 'Upload complete';
417
+ // Show returned metadata if present
418
+ const docId = responseJson.doc_id ? `Doc ID: ${responseJson.doc_id}` : '';
419
+ const sha = responseJson.sha256 ? `SHA256: ${responseJson.sha256}` : '';
420
+ const title = responseJson.title ? `Title: ${responseJson.title}` : '';
421
+ const dtEcho = responseJson.doc_type ? `Type: ${responseJson.doc_type}` : '';
422
+ const jurEcho = responseJson.jurisdiction ? `Jurisdiction: ${responseJson.jurisdiction}` : '';
423
+ const msgParts = ['Document uploaded successfully.', docId, title, dtEcho, jurEcho].filter(Boolean);
424
+ showResult(msgParts.join(' — '), 'success');
425
+ // Keep note about indexing in case embeddings are generated async
426
+ const indexingNote = document.createElement('div');
427
+ indexingNote.style.marginTop = '8px';
428
+ indexingNote.style.fontSize = '0.85rem';
429
+ indexingNote.style.color = '#ccc';
430
+ indexingNote.textContent = 'Embeddings/indexing may continue in the background.';
431
+ uploadResult.appendChild(indexingNote);
432
+ clearFileSelection();
433
+ } else {
434
+ // Try to show server error message
435
+ const errMsg = responseJson && responseJson.error ? responseJson.error : xhr.statusText || 'Upload failed';
436
+ showResult(`Upload failed: ${errMsg}`, 'error');
437
+ }
438
+ progressContainer.classList.remove('visible');
439
+ };
440
+
441
+ xhr.onerror = function() {
442
+ uploadButton.disabled = false;
443
+ showResult('Upload failed: network error.', 'error');
444
+ progressContainer.classList.remove('visible');
445
+ };
446
+
447
+ xhr.ontimeout = function() {
448
+ uploadButton.disabled = false;
449
+ showResult('Upload timed out.', 'error');
450
+ progressContainer.classList.remove('visible');
451
+ };
452
+
453
+ // Optional timeout (ms) — adjust or remove as needed
454
+ xhr.timeout = 500000; // 8 minutes
455
+
456
+ xhr.send(formData);
457
+ });
458
+
459
+ function handleFileSelect(e) {
460
+ const file = e.target.files[0];
461
+ if (file) {
462
+ handleFile(file);
463
+ }
464
+ }
465
+
466
+ function clearFileSelection() {
467
+ selectedFileObj = null;
468
+ fileInput.value = '';
469
+ selectedFile.classList.remove('visible');
470
+ uploadButton.classList.remove('visible');
471
+ }
472
+
473
+ function handleFile(file) {
474
+ // Validate file type by MIME or extension fallback
475
+ const allowedTypes = [
476
+ 'application/pdf',
477
+ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
478
+ 'application/msword',
479
+ 'text/plain'
480
+ ];
481
+
482
+ const ext = (file.name || '').split('.').pop().toLowerCase();
483
+ const allowedExt = ['pdf', 'docx', 'doc', 'txt'];
484
+
485
+ if (!allowedTypes.includes(file.type) && !allowedExt.includes(ext)) {
486
+ showResult('Please select a .pdf, .txt, .doc, or .docx file.', 'error');
487
+ return;
488
+ }
489
+
490
+ const maxSize = 10 * 1024 * 1024;
491
+ if (file.size > maxSize) {
492
+ showResult('File size must be less than 10MB.', 'error');
493
+ return;
494
+ }
495
+
496
+ selectedFileObj = file;
497
+ fileName.textContent = file.name;
498
+ fileSize.textContent = formatFileSize(file.size);
499
+ selectedFile.classList.add('visible');
500
+ uploadButton.classList.add('visible');
501
+ uploadResult.style.display = 'none';
502
+ }
503
+
504
+ function formatFileSize(bytes) {
505
+ if (bytes === 0) return '0 Bytes';
506
+ const k = 1024;
507
+ const sizes = ['Bytes', 'KB', 'MB', 'GB'];
508
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
509
+ return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
510
+ }
511
+
512
+ function showResult(message, type) {
513
+ uploadResult.textContent = message;
514
+ uploadResult.className = `upload-result ${type}`;
515
+ uploadResult.style.display = 'block';
516
+ }
517
+ </script>
518
+ </body>
tech-trans-rag ADDED
@@ -0,0 +1 @@
 
 
1
+ Subproject commit 6f0b1581fe21c43e860fa324491c6b3efa62b2cd