phaethon-order commited on
Commit
f74bbfd
·
1 Parent(s): 7de3e97

Add JSONL endpoint for chunk records and enhance HTML response formatting

Browse files
Files changed (3) hide show
  1. routes/api.py +135 -2
  2. static/chunks.html +20 -4
  3. static/index.html +88 -6
routes/api.py CHANGED
@@ -1,6 +1,7 @@
1
  # api.py
2
  import os
3
  from flask import Blueprint, request, jsonify, send_from_directory
 
4
  from flask_cors import CORS
5
  from werkzeug.utils import secure_filename
6
  from infrastructure.logger import get_logger
@@ -42,6 +43,7 @@ UPLOAD_FOLDER = os.getenv("UPLOAD_FOLDER", "/data/corpus_raw")
42
  CLEAN_FOLDER = os.getenv("CLEAN_FOLDER", "/data/corpus_clean")
43
  MANIFEST_DIR = os.getenv("MANIFEST_DIR", "/data/manifest")
44
  RAW_PREFIX = "/data/corpus_raw"
 
45
 
46
  def allowed_file(filename: str) -> bool:
47
  return "." in filename and filename.rsplit(".", 1)[1].lower() in ALLOWED_EXTENSIONS
@@ -284,6 +286,137 @@ def list_all_chunks():
284
 
285
  return jsonify({"chunks": out, "count": len(out), "limit": limit, "offset": offset}), 200
286
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
287
  @api_bp.route("/chunks", methods=["PATCH"])
288
  def update_chunks():
289
  """Update a chunk's metadata and optionally regenerate embedding if text changed."""
@@ -377,9 +510,9 @@ def query():
377
  "document": doc_info
378
  })
379
 
380
- answer = refine_query_response(question, results)
381
 
382
- return jsonify({"results": results, "answer": answer}), 200
383
  except Exception as e:
384
  logger.exception("Query failed: %s", e)
385
  return jsonify({"error": "Failed to execute query"}), 500
 
1
  # api.py
2
  import os
3
  from flask import Blueprint, request, jsonify, send_from_directory
4
+ import json
5
  from flask_cors import CORS
6
  from werkzeug.utils import secure_filename
7
  from infrastructure.logger import get_logger
 
43
  CLEAN_FOLDER = os.getenv("CLEAN_FOLDER", "/data/corpus_clean")
44
  MANIFEST_DIR = os.getenv("MANIFEST_DIR", "/data/manifest")
45
  RAW_PREFIX = "/data/corpus_raw"
46
+ CHUNKS_DIR = os.getenv("CHUNKS_DIR", "/data/chunks")
47
 
48
  def allowed_file(filename: str) -> bool:
49
  return "." in filename and filename.rsplit(".", 1)[1].lower() in ALLOWED_EXTENSIONS
 
286
 
287
  return jsonify({"chunks": out, "count": len(out), "limit": limit, "offset": offset}), 200
288
 
289
+
290
+ @api_bp.route("/chunks/jsonl", methods=["GET"])
291
+ def list_chunks_from_jsonl():
292
+ """Return all chunk records found in /data/chunks/chunks.jsonl for viewing.
293
+
294
+ This endpoint parses the JSONL (or JSON-array) file produced by the chunker
295
+ and normalizes records to the same shape used in the table UI. It also
296
+ augments with embedding_count using the ChromaDB store when chunk IDs exist.
297
+ """
298
+ path = os.path.join(CHUNKS_DIR, "chunks.jsonl")
299
+ rows: list[dict] = []
300
+
301
+ if not os.path.exists(path):
302
+ return jsonify({"chunks": [], "count": 0}), 200
303
+
304
+ try:
305
+ with open(path, "r", encoding="utf-8") as f:
306
+ content = f.read()
307
+ except Exception as e:
308
+ logger.error("Failed reading %s: %s", path, e)
309
+ return jsonify({"error": "failed to read chunks.jsonl"}), 500
310
+
311
+ content_stripped = (content or "").strip()
312
+ # Try robust parsing:
313
+ # 1) Whole-file JSON (array or object)
314
+ # 2) Streaming JSON decoder to handle concatenated JSON values
315
+ # 3) Line-by-line JSONL fallback
316
+ parsed_ok = False
317
+ if content_stripped:
318
+ try:
319
+ parsed = json.loads(content_stripped)
320
+ if isinstance(parsed, list):
321
+ rows = [r for r in parsed if isinstance(r, dict)]
322
+ elif isinstance(parsed, dict):
323
+ rows = [parsed]
324
+ parsed_ok = True
325
+ except Exception:
326
+ parsed_ok = False
327
+
328
+ if not parsed_ok and content_stripped:
329
+ try:
330
+ dec = json.JSONDecoder()
331
+ s = content_stripped
332
+ idx = 0
333
+ out: list[dict] = []
334
+ while idx < len(s):
335
+ # Skip whitespace between values
336
+ while idx < len(s) and s[idx].isspace():
337
+ idx += 1
338
+ if idx >= len(s):
339
+ break
340
+ obj, end = dec.raw_decode(s, idx)
341
+ if isinstance(obj, list):
342
+ out.extend([r for r in obj if isinstance(r, dict)])
343
+ elif isinstance(obj, dict):
344
+ out.append(obj)
345
+ idx = end
346
+ if out:
347
+ rows = out
348
+ parsed_ok = True
349
+ except Exception:
350
+ parsed_ok = False
351
+
352
+ if not parsed_ok:
353
+ # Fallback: line-by-line JSONL
354
+ rows = []
355
+ for line in (content.splitlines() if content else []):
356
+ line = line.strip()
357
+ if not line:
358
+ continue
359
+ try:
360
+ obj = json.loads(line)
361
+ if isinstance(obj, list):
362
+ rows.extend([r for r in obj if isinstance(r, dict)])
363
+ elif isinstance(obj, dict):
364
+ rows.append(obj)
365
+ except Exception:
366
+ # tolerate malformed lines
367
+ continue
368
+
369
+ if not rows:
370
+ return jsonify({"chunks": [], "count": 0}), 200
371
+
372
+ # Normalize shape and collect IDs for embedding counts
373
+ normalized: list[dict] = []
374
+ chunk_ids: list[int] = []
375
+ for r in rows:
376
+ cid = r.get("chunk_id") or r.get("id")
377
+ try:
378
+ cid_int = int(cid) if cid is not None else None
379
+ except Exception:
380
+ cid_int = None
381
+ if cid_int is not None:
382
+ chunk_ids.append(cid_int)
383
+ normalized.append({
384
+ "chunk_id": cid_int,
385
+ "doc_id": r.get("doc_id"),
386
+ "chunk_index": r.get("chunk_index") or r.get("index"),
387
+ "token_count": r.get("token_count"),
388
+ "tok_ver": r.get("tok_ver"),
389
+ "seg_ver": r.get("seg_ver"),
390
+ "text": str(r.get("text") or ""),
391
+ "page_start": r.get("page_start"),
392
+ "page_end": r.get("page_end"),
393
+ "section_number": r.get("section_number"),
394
+ "section_title": r.get("section_title"),
395
+ "clause_type": r.get("clause_type"),
396
+ "path": r.get("path"),
397
+ "numbers_present": r.get("numbers_present"),
398
+ "definition_terms": r.get("definition_terms"),
399
+ # embedding_count filled below
400
+ })
401
+
402
+ # Populate embedding counts where possible
403
+ embedding_counts: dict[int, int] = {}
404
+ try:
405
+ if chunk_ids:
406
+ embedding_counts = get_embedding_counts_for_chunks(chunk_ids)
407
+ except Exception as e:
408
+ logger.error("Failed to get embedding counts for JSONL rows: %s", e)
409
+ embedding_counts = {}
410
+
411
+ for item in normalized:
412
+ cid = item.get("chunk_id")
413
+ item["embedding_count"] = int(embedding_counts.get(int(cid), 0)) if isinstance(cid, int) else 0
414
+
415
+ # Sort by chunk_id asc when available
416
+ normalized.sort(key=lambda x: (x["chunk_id"] is None, x.get("chunk_id") or 0))
417
+
418
+ return jsonify({"chunks": normalized, "count": len(normalized)}), 200
419
+
420
  @api_bp.route("/chunks", methods=["PATCH"])
421
  def update_chunks():
422
  """Update a chunk's metadata and optionally regenerate embedding if text changed."""
 
510
  "document": doc_info
511
  })
512
 
513
+ response = refine_query_response(question, results)
514
 
515
+ return jsonify({"results": results, "response": response}), 200
516
  except Exception as e:
517
  logger.exception("Query failed: %s", e)
518
  return jsonify({"error": "Failed to execute query"}), 500
static/chunks.html CHANGED
@@ -203,12 +203,28 @@
203
  setStatus('');
204
  summaryEl.innerHTML = '';
205
  spinner();
206
- const limit = 0; // No limit
207
- fetch(`/api/chunks/all?limit=${limit}`)
208
  .then(r => r.json())
209
  .then(data => {
210
- rawChunks = Array.isArray(data.chunks) ? data.chunks : [];
211
- setStatus(rawChunks.length ? `Loaded ${rawChunks.length} chunk(s) (global).` : 'No chunks.');
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
212
  currentPage = 1;
213
  render();
214
  resultsPanel.style.display = 'block';
 
203
  setStatus('');
204
  summaryEl.innerHTML = '';
205
  spinner();
206
+ // Prefer JSONL source so we can show all records
207
+ fetch(`/api/chunks/jsonl`)
208
  .then(r => r.json())
209
  .then(data => {
210
+ if (data && data.chunks) {
211
+ rawChunks = Array.isArray(data.chunks) ? data.chunks : [];
212
+ } else if (Array.isArray(data)) {
213
+ rawChunks = data; // tolerate direct array response
214
+ } else {
215
+ rawChunks = [];
216
+ }
217
+ // If JSONL missing/empty, fall back to DB list with max limit
218
+ if (!rawChunks.length) {
219
+ return fetch(`/api/chunks/all?limit=500&offset=0`).then(r => r.json());
220
+ }
221
+ return { chunks: rawChunks };
222
+ })
223
+ .then(data => {
224
+ if (data && data.chunks && !rawChunks.length) {
225
+ rawChunks = Array.isArray(data.chunks) ? data.chunks : [];
226
+ }
227
+ setStatus(rawChunks.length ? `Loaded ${rawChunks.length} chunk(s).` : 'No chunks.');
228
  currentPage = 1;
229
  render();
230
  resultsPanel.style.display = 'block';
static/index.html CHANGED
@@ -215,6 +215,46 @@
215
  margin-bottom: 0;
216
  }
217
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
218
  .output-section.empty {
219
  align-items: center;
220
  justify-content: center;
@@ -413,13 +453,48 @@
413
  }
414
 
415
  const parts = [];
416
- parts.push(`<u>Query:</u> ${escape(data.query)}`);
 
 
417
  if (data.filters && (data.filters.doc_type || data.filters.jurisdiction)) {
418
- parts.push(`<u>Filters:</u> doc_type=${escape(data.filters.doc_type || '—')} jurisdiction=${escape(data.filters.jurisdiction || '—')}`);
419
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
420
  const results = Array.isArray(data.results) ? data.results : [];
 
421
  if (!results.length) {
422
- parts.push('<u>Results:</u> <em>No chunks returned (vector index empty or not configured).</em>');
423
  } else {
424
  const list = results.map((r, idx) => {
425
  const dist = (typeof r.distance === 'number') ? r.distance.toFixed(4) : escape(r.distance);
@@ -428,15 +503,22 @@
428
  const title = r.title || doc.title || '';
429
  const dtype = r.doc_type || doc.doc_type || '';
430
  const juris = r.jurisdiction || doc.jurisdiction || '';
431
- return `<li style="margin-bottom:14px; line-height:1.35;">
432
  <div><strong>#${idx+1}</strong> chunk_id=${escape(r.chunk_id)} distance=${dist}</div>
433
  <div style="color:#ccc; font-size:0.7rem; margin-top:2px; font-style:italic;">${escape(title)} ${dtype ? '('+escape(dtype)+')' : ''} ${juris ? '['+escape(juris)+']' : ''}</div>
434
  <div style="color:#ccc; font-size:0.85rem; margin-top:4px;">${txt}${r.text && r.text.length > 500 ? '…' : ''}</div>
435
  </li>`;
436
  }).join('');
437
- 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>`);
438
  }
439
- responseDiv.innerHTML = parts.join('\n\n');
 
 
 
 
 
 
 
440
  } catch (err) {
441
  loadingDiv.classList.remove('active');
442
  responseDiv.innerHTML = `<span style="color:#e53e3e;">Error: ${err.message}</span>`;
 
215
  margin-bottom: 0;
216
  }
217
 
218
+ /* New formatting for Response and Results sections */
219
+ .section-title {
220
+ font-family: inherit;
221
+ font-weight: 700;
222
+ font-size: 1.05rem;
223
+ text-decoration: underline;
224
+ margin: 2px 0 8px 0;
225
+ color: #f7fafc;
226
+ }
227
+ .response-block {
228
+ width: 100%;
229
+ margin-bottom: 14px;
230
+ }
231
+ .response-text {
232
+ white-space: pre-wrap;
233
+ line-height: 1.55;
234
+ color: #e6eef6;
235
+ }
236
+ .citations {
237
+ margin-top: 10px;
238
+ }
239
+ .citations ul, .results-section ol {
240
+ margin-top: 6px;
241
+ padding-left: 20px;
242
+ }
243
+ .citations li {
244
+ margin-bottom: 4px;
245
+ }
246
+ .results-section {
247
+ width: 100%;
248
+ border-top: 1px solid #444;
249
+ margin-top: 8px;
250
+ padding-top: 8px;
251
+ font-size: 0.9rem; /* slightly smaller */
252
+ }
253
+ .meta-line {
254
+ color: #cbd5e1;
255
+ font-size: 0.85rem;
256
+ }
257
+
258
  .output-section.empty {
259
  align-items: center;
260
  justify-content: center;
 
453
  }
454
 
455
  const parts = [];
456
+
457
+ // Small meta lines for query and filters
458
+ parts.push(`<div class="meta-line"><u>Query:</u> ${escape(data.query)}</div>`);
459
  if (data.filters && (data.filters.doc_type || data.filters.jurisdiction)) {
460
+ parts.push(`<div class="meta-line"><u>Filters:</u> doc_type=${escape(data.filters.doc_type || '—')} jurisdiction=${escape(data.filters.jurisdiction || '—')}</div>`);
461
  }
462
+
463
+ // Response section (from LLM)
464
+ const answerText = (typeof data.response === 'string' && data.response) ? data.response : (typeof data.answer === 'string' ? data.answer : '');
465
+ const sources = Array.isArray(data.sources) ? data.sources : [];
466
+ if (answerText || sources.length) {
467
+ let citationsHtml = '';
468
+ if (sources.length) {
469
+ const citeItems = sources.map((s) => {
470
+ const docId = s.doc_id ?? s.id ?? '';
471
+ const docType = s.doc_type ? ` (${escape(s.doc_type)})` : '';
472
+ const juris = s.jurisdiction ? ` [${escape(s.jurisdiction)}]` : '';
473
+ const chunks = Array.isArray(s.chunks) ? s.chunks : [];
474
+ const chunkItems = chunks.map((ch) => {
475
+ const sn = (ch.section_number != null && ch.section_number !== '') ? ` §${escape(ch.section_number)}` : '';
476
+ const st = ch.section_title ? ` — ${escape(ch.section_title)}` : '';
477
+ return `<li>chunk_id=${escape(ch.chunk_id)}${sn}${st}</li>`;
478
+ }).join('');
479
+ const inner = chunkItems ? `<ul>${chunkItems}</ul>` : '';
480
+ return `<li>Doc ${escape(String(docId))}${docType}${juris}${inner}</li>`;
481
+ }).join('');
482
+ citationsHtml = `<div class="citations"><em>Citations</em><ul>${citeItems}</ul></div>`;
483
+ }
484
+ parts.push(`
485
+ <div class="response-block">
486
+ <div class="section-title">Response</div>
487
+ <div class="response-text">${escape(answerText)}</div>
488
+ ${citationsHtml}
489
+ </div>
490
+ `);
491
+ }
492
+
493
+ // Results section (vector hits)
494
  const results = Array.isArray(data.results) ? data.results : [];
495
+ let resultsHtml = '';
496
  if (!results.length) {
497
+ resultsHtml = '<em>No chunks returned (vector index empty or not configured).</em>';
498
  } else {
499
  const list = results.map((r, idx) => {
500
  const dist = (typeof r.distance === 'number') ? r.distance.toFixed(4) : escape(r.distance);
 
503
  const title = r.title || doc.title || '';
504
  const dtype = r.doc_type || doc.doc_type || '';
505
  const juris = r.jurisdiction || doc.jurisdiction || '';
506
+ return `<li style="margin-bottom:12px; line-height:1.35;">
507
  <div><strong>#${idx+1}</strong> chunk_id=${escape(r.chunk_id)} distance=${dist}</div>
508
  <div style="color:#ccc; font-size:0.7rem; margin-top:2px; font-style:italic;">${escape(title)} ${dtype ? '('+escape(dtype)+')' : ''} ${juris ? '['+escape(juris)+']' : ''}</div>
509
  <div style="color:#ccc; font-size:0.85rem; margin-top:4px;">${txt}${r.text && r.text.length > 500 ? '…' : ''}</div>
510
  </li>`;
511
  }).join('');
512
+ resultsHtml = `<ol>${list}</ol>`;
513
  }
514
+ parts.push(`
515
+ <div class="results-section">
516
+ <div class="section-title">Results</div>
517
+ ${resultsHtml}
518
+ </div>
519
+ `);
520
+
521
+ responseDiv.innerHTML = parts.join('\n');
522
  } catch (err) {
523
  loadingDiv.classList.remove('active');
524
  responseDiv.innerHTML = `<span style="color:#e53e3e;">Error: ${err.message}</span>`;