-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdocfeatures.py
More file actions
executable file
·1375 lines (1181 loc) · 50.7 KB
/
Copy pathdocfeatures.py
File metadata and controls
executable file
·1375 lines (1181 loc) · 50.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
docfeatures.py — Document Feature Identification Tool
Scans a corpus of text documents using a local LLM (via OpenAI-compatible API)
to identify researcher-defined features. Results are stored in MySQL.
Setup:
pip install pymysql pyyaml requests python-dotenv
cp .env.example .env # edit with your DB credentials
Usage:
python docfeatures.py --config features.yaml --corpus /data/notes/ --run-name v1 --limit 10
python docfeatures.py --config features.yaml --corpus /data/notes/ --run-name v1
python docfeatures.py --list-runs
python docfeatures.py --purge-run v1
"""
import argparse
import hashlib
import json
import os
import re
import signal
import sys
import time
from pathlib import Path
import pymysql
import requests
import yaml
from dotenv import load_dotenv
load_dotenv()
# ---------------------------------------------------------------------------
# Constants
# ---------------------------------------------------------------------------
# Chunk target: ~128k token context minus prompt/output overhead.
# At ~3 chars/token for clinical text, 350k chars ≈ 117k tokens,
# leaving room for the prompt (~1k tokens) and response (~500 tokens).
# Override with --chunk-size if your model has a different context window.
CHUNK_TARGET_CHARS = os.environ.get("CHUNK_TARGET_CHARS",200_000)
DEFAULT_LLM_HOST = os.environ.get("DEFAULT_LLM_HOST","http://127.0.0.1:11433")
DEFAULT_LLM_MODEL = os.environ.get("DEFAULT_LLM_MODEL","default")
TEXT_EXTENSIONS = {".txt", ".html", ".htm", ".md", ".text"}
# ---------------------------------------------------------------------------
# Graceful Ctrl+C
# ---------------------------------------------------------------------------
_interrupted = False
def _handle_sigint(sig, frame):
global _interrupted
if _interrupted:
sys.exit(1) # second Ctrl+C = immediate
_interrupted = True
print("\n[Ctrl+C] Finishing current document, then stopping...", file=sys.stderr)
signal.signal(signal.SIGINT, _handle_sigint)
# ===========================================================================
# Database
# ===========================================================================
def get_connection():
"""Connect to MySQL using credentials from environment / .env file."""
return pymysql.connect(
host=os.environ.get("DB_HOST", "localhost"),
port=int(os.environ.get("DB_PORT", 3306)),
user=os.environ.get("DB_USER", "root"),
password=os.environ.get("DB_PASSWORD", ""),
database=os.environ.get("DB_NAME", "docfeatures"),
charset="utf8mb4",
cursorclass=pymysql.cursors.DictCursor,
autocommit=True,
)
def get_or_create_run(conn, run_name, config, config_hash, host, model, temperature):
with conn.cursor() as cur:
cur.execute("SELECT run_name FROM runs WHERE run_name = %s", (run_name,))
if cur.fetchone():
return
desc = config.get("run_description", "")
cur.execute(
"INSERT INTO runs (run_name, config_hash, config_yaml, "
"description, llm_host, llm_model, llm_temperature) VALUES (%s,%s,%s,%s,%s,%s,%s)",
(run_name, config_hash, yaml.dump(config), desc, host, model, temperature),
)
def cleanup_incomplete(conn, run_name):
"""Remove docs stuck in 'processing' (interrupted mid-flight)."""
with conn.cursor() as cur:
cur.execute(
"DELETE FROM document_runs WHERE run_name=%s AND status='processing'",
(run_name,),
)
if cur.rowcount:
print(
f" Cleaned up {cur.rowcount} interrupted document(s) "
"from previous session.",
file=sys.stderr,
)
def get_finished_paths(conn, run_name, include_errors=False):
"""Return set of file_paths already finished for this run."""
# We skip 'complete' always; we skip 'error' unless retrying
with conn.cursor() as cur:
if include_errors:
# retrying errors — only skip 'complete'
cur.execute(
"SELECT f.file_path FROM document_runs dr "
"JOIN files f ON dr.file_id = f.file_id "
"WHERE dr.run_name=%s AND dr.status='complete'",
(run_name,),
)
else:
# default — skip both 'complete' and 'error'
cur.execute(
"SELECT f.file_path FROM document_runs dr "
"JOIN files f ON dr.file_id = f.file_id "
"WHERE dr.run_name=%s AND dr.status IN ('complete','error')",
(run_name,),
)
return {row["file_path"] for row in cur.fetchall()}
def validate_filter(conn, filter_config):
"""Check that the source run exists and that referenced features are valid.
Returns the source run's feature config for cross-reference."""
from_run = filter_config.get("from_run")
if not from_run:
raise ValueError("Filter config must include 'from_run'.")
with conn.cursor() as cur:
cur.execute(
"SELECT config_yaml FROM runs WHERE run_name = %s", (from_run,)
)
row = cur.fetchone()
if not row:
raise ValueError(
f"Filter references run '{from_run}', but it does not exist. "
f"Use --list-runs to see available runs."
)
source_config = yaml.safe_load(row["config_yaml"])
source_features = set(source_config.get("features", {}).keys())
# Validate that all referenced feature names exist in the source run
for section_name in ("require", "exclude"):
section = filter_config.get(section_name, {})
for feat_name in section:
if feat_name not in source_features:
raise ValueError(
f"Filter {section_name} references feature "
f"'{feat_name}', but run '{from_run}' does not "
f"have that feature. Available: "
f"{', '.join(sorted(source_features))}"
)
# Check that the source run has completed documents
cur.execute(
"SELECT COUNT(*) AS cnt FROM document_runs "
"WHERE run_name=%s AND status='complete'",
(from_run,),
)
count = cur.fetchone()["cnt"]
if count == 0:
raise ValueError(
f"Run '{from_run}' has no completed documents to filter."
)
return source_config
def get_filtered_paths(conn, filter_config):
"""Build a JOIN-based query to select file_paths matching the filter.
Uses INNER JOINs for 'require' criteria and LEFT JOIN + IS NULL for
'exclude' criteria. Designed for corpora with hundreds of millions of
rows where IN (SELECT ...) subqueries would be prohibitively slow.
Returns a list of file_path strings.
"""
from_run = filter_config["from_run"]
require = filter_config.get("require", {})
exclude = filter_config.get("exclude", {})
# Start building the query
# d = source document_runs table, joined to files for file_path
joins = []
where_clauses = ["d.run_name = %s", "d.status = 'complete'"]
params = []
# --- REQUIRE: INNER JOIN for each required feature ---
for i, (feat_name, feat_value) in enumerate(require.items()):
alias = f"req{i}"
if isinstance(feat_value, bool) and feat_value is True:
# Boolean true: row must exist (we only store positive values)
joins.append(
f"INNER JOIN document_features {alias} "
f"ON d.doc_id = {alias}.doc_id "
f"AND {alias}.feature_name = %s"
)
params.append(feat_name)
elif isinstance(feat_value, bool) and feat_value is False:
# Boolean false: row must NOT exist (same as exclude)
joins.append(
f"LEFT JOIN document_features {alias} "
f"ON d.doc_id = {alias}.doc_id "
f"AND {alias}.feature_name = %s"
)
params.append(feat_name)
where_clauses.append(f"{alias}.id IS NULL")
elif isinstance(feat_value, list):
# Enum: row must exist with one of the listed values
placeholders = ", ".join(["%s"] * len(feat_value))
joins.append(
f"INNER JOIN document_features {alias} "
f"ON d.doc_id = {alias}.doc_id "
f"AND {alias}.feature_name = %s "
f"AND {alias}.value_text IN ({placeholders})"
)
params.append(feat_name)
params.extend(str(v) for v in feat_value)
else:
# Single enum value (string)
joins.append(
f"INNER JOIN document_features {alias} "
f"ON d.doc_id = {alias}.doc_id "
f"AND {alias}.feature_name = %s "
f"AND {alias}.value_text = %s"
)
params.append(feat_name)
params.append(str(feat_value))
# --- EXCLUDE: LEFT JOIN + IS NULL for each excluded feature ---
for i, (feat_name, feat_value) in enumerate(exclude.items()):
alias = f"exc{i}"
if isinstance(feat_value, bool) and feat_value is True:
# Exclude documents where this feature is true (row exists)
joins.append(
f"LEFT JOIN document_features {alias} "
f"ON d.doc_id = {alias}.doc_id "
f"AND {alias}.feature_name = %s"
)
params.append(feat_name)
where_clauses.append(f"{alias}.id IS NULL")
elif isinstance(feat_value, list):
# Exclude documents with any of these values
placeholders = ", ".join(["%s"] * len(feat_value))
joins.append(
f"LEFT JOIN document_features {alias} "
f"ON d.doc_id = {alias}.doc_id "
f"AND {alias}.feature_name = %s "
f"AND {alias}.value_text IN ({placeholders})"
)
params.append(feat_name)
params.extend(str(v) for v in feat_value)
where_clauses.append(f"{alias}.id IS NULL")
else:
# Exclude documents with this specific value
joins.append(
f"LEFT JOIN document_features {alias} "
f"ON d.doc_id = {alias}.doc_id "
f"AND {alias}.feature_name = %s "
f"AND {alias}.value_text = %s"
)
params.append(feat_name)
params.append(str(feat_value))
where_clauses.append(f"{alias}.id IS NULL")
sql = (
"SELECT f.file_path FROM document_runs d\n"
"JOIN files f ON d.file_id = f.file_id\n"
+ "\n".join(joins)
+ "\nWHERE " + " AND ".join(where_clauses)
+ "\nORDER BY f.file_path"
)
params.append(from_run)
with conn.cursor() as cur:
cur.execute(sql, params)
return [row["file_path"] for row in cur.fetchall()]
def get_or_create_file(conn, file_path, file_hash, file_size):
"""Return file_id for file_path, creating the 'files' row on first sight.
file_hash/file_size_bytes are the file's identity and are set once, on
first sight, and never overwritten. If a later run sees a different
hash/size for the same path, the file changed on disk between runs —
that's logged as an anomaly (it may affect the validity of earlier
runs' results) rather than silently treated as the new canonical value.
"""
with conn.cursor() as cur:
cur.execute(
"SELECT file_id, file_hash, file_size_bytes FROM files "
"WHERE file_path=%s",
(file_path,),
)
row = cur.fetchone()
if row is None:
cur.execute(
"INSERT INTO files (file_path, file_hash, file_size_bytes) "
"VALUES (%s,%s,%s)",
(file_path, file_hash, file_size),
)
return cur.lastrowid
if row["file_hash"] != file_hash or row["file_size_bytes"] != file_size:
print(
f" [ANOMALY] {file_path} differs from its first-seen "
f"hash/size — the file changed on disk since an earlier "
f"run processed it. Keeping the original as canonical; "
f"features from earlier runs may no longer reflect the "
f"current file contents.",
file=sys.stderr,
)
return row["file_id"]
def upsert_document(conn, run_name, file_id, total_chunks):
"""Insert or reset a document_runs row. Returns doc_id."""
with conn.cursor() as cur:
# Delete any prior incomplete row (cascade cleans chunks/features)
cur.execute(
"DELETE FROM document_runs "
"WHERE run_name=%s AND file_id=%s AND status != 'complete'",
(run_name, file_id),
)
cur.execute(
"INSERT INTO document_runs "
"(run_name, file_id, total_chunks, status) "
"VALUES (%s,%s,%s,'processing')",
(run_name, file_id, total_chunks),
)
return cur.lastrowid
def save_chunk_result(conn, doc_id, chunk_index, raw_json_str):
with conn.cursor() as cur:
cur.execute(
"INSERT INTO chunk_results (doc_id, chunk_index, raw_json) "
"VALUES (%s,%s,%s) "
"ON DUPLICATE KEY UPDATE raw_json=VALUES(raw_json)",
(doc_id, chunk_index, raw_json_str),
)
def save_document_features(conn, doc_id, file_id, features, features_config):
"""Save only positive/non-default feature values. Skips False booleans,
the lowest (first) enum option, null text, and null integers.
Completeness is provable via the document_runs table (status='complete').
file_id is denormalized here so features for a document can be looked
up across every run without joining back through document_runs."""
with conn.cursor() as cur:
for name, value in features.items():
fdef = features_config.get(name, {})
ftype = fdef.get("type", "boolean")
# Skip false booleans
if ftype == "boolean" and value is False:
continue
# Skip the default (first/lowest) enum value
if ftype == "enum":
default_val = fdef.get("options", [""])[0]
if str(value).lower().strip() == default_val.lower().strip():
continue
# Skip null text values
if ftype == "text" and (value is None or str(value).strip() == ""):
continue
# Skip null integer values
if ftype == "integer" and value is None:
continue
cur.execute(
"INSERT INTO document_features (doc_id, file_id, feature_name, value_text) "
"VALUES (%s,%s,%s,%s) "
"ON DUPLICATE KEY UPDATE value_text=VALUES(value_text)",
(doc_id, file_id, name, str(value)),
)
def mark_document(conn, doc_id, status, elapsed=None, error=None):
with conn.cursor() as cur:
cur.execute(
"UPDATE document_runs SET status=%s, processing_secs=%s, "
"error_message=%s WHERE doc_id=%s",
(status, elapsed, error, doc_id),
)
def list_runs_db(conn):
with conn.cursor() as cur:
cur.execute("""
SELECT r.run_name, r.description, r.llm_model, r.llm_temperature, r.created_at,
COUNT(d.doc_id) AS total_docs,
SUM(CASE WHEN d.status='complete' THEN 1 ELSE 0 END) AS completed,
SUM(CASE WHEN d.status='error' THEN 1 ELSE 0 END) AS errors
FROM runs r
LEFT JOIN document_runs d ON r.run_name = d.run_name
GROUP BY r.run_name
ORDER BY r.created_at DESC
""")
return cur.fetchall()
def purge_run_db(conn, run_name):
with conn.cursor() as cur:
cur.execute("SELECT run_name FROM runs WHERE run_name=%s", (run_name,))
if not cur.fetchone():
print(f"Run '{run_name}' not found.", file=sys.stderr)
return False
cur.execute("DELETE FROM runs WHERE run_name=%s", (run_name,))
print(f"Purged run '{run_name}' and all associated data.")
return True
# ===========================================================================
# Text Sanitization
# ===========================================================================
# Control characters that are illegal in JSON (and useless to the LLM)
_CONTROL_CHAR_RE = re.compile(
r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]"
)
# HTML tag pattern (keeps text content, strips markup)
_HTML_TAG_RE = re.compile(r"<[^>]+>", re.DOTALL)
# Collapse runs of whitespace
_MULTI_SPACE_RE = re.compile(r"[ \t]+")
_MULTI_NEWLINE_RE = re.compile(r"\n{3,}")
def sanitize_text(text):
"""Clean document text for LLM consumption.
- Strips HTML tags (keeps text content)
- Removes control characters that break JSON encoding
- Decodes common HTML entities
- Normalizes excessive whitespace
This handles Word-generated HTML, malformed markup, and documents
with embedded control characters.
"""
# Strip HTML tags if present (check before expensive regex)
if "<" in text and ">" in text:
# Decode common HTML entities first
text = text.replace(" ", " ")
text = text.replace("&", "&")
text = text.replace("<", "<")
text = text.replace(">", ">")
text = text.replace(""", '"')
text = text.replace("'", "'")
text = text.replace("’", "\u2019")
text = text.replace("“", "\u201c")
text = text.replace("”", "\u201d")
text = text.replace("—", "\u2014")
text = text.replace("–", "\u2013")
# Strip HTML comments
text = re.sub(r"<!--.*?-->", "", text, flags=re.DOTALL)
# Strip style/script blocks entirely
text = re.sub(
r"<(style|script)[^>]*>.*?</\1>", "", text,
flags=re.DOTALL | re.IGNORECASE,
)
# Strip remaining tags
text = _HTML_TAG_RE.sub(" ", text)
# Remove control characters
text = _CONTROL_CHAR_RE.sub("", text)
# Normalize whitespace
text = _MULTI_SPACE_RE.sub(" ", text)
text = _MULTI_NEWLINE_RE.sub("\n\n", text)
return text.strip()
# ===========================================================================
# Chunking
# ===========================================================================
def split_into_sections(text, target_chars):
"""Split text into sections using cascading strategies.
Tries each strategy in order; any section still over *target_chars*
is re-split with the next finer strategy. Final fallback is a hard
character-boundary split.
Strategy hierarchy:
1. HTML headers (<h1>–<h3>)
2. Markdown headers (# ## ###)
3. Paragraph breaks (double newline)
4. Sentence boundaries (after . ! ?)
5. Single line breaks
6. Hard split at target_chars (last resort)
"""
strategies = [
re.compile(r"(?=<h[1-3][\s>])", re.IGNORECASE),
re.compile(r"(?=^#{1,3}\s)", re.MULTILINE),
re.compile(r"\n\s*\n"),
re.compile(r"(?<=[.!?])\s+"),
re.compile(r"\n"),
]
sections = [text]
for pattern in strategies:
# Stop early if everything already fits
if all(len(s) <= target_chars for s in sections):
break
refined = []
for section in sections:
if len(section) <= target_chars:
refined.append(section)
continue
# Attempt to split the oversized section
parts = pattern.split(section)
parts = [p for p in parts if p.strip()]
if len(parts) > 1:
refined.extend(parts)
else:
# Strategy didn't help — pass through for the next one
refined.append(section)
sections = refined
# Final fallback: hard split any remaining oversized sections
final = []
for section in sections:
if len(section) <= target_chars:
final.append(section)
else:
# Split at target_chars, trying to break at a space
pos = 0
while pos < len(section):
end = pos + target_chars
if end < len(section):
# Look back up to 200 chars for a space to break on
space = section.rfind(" ", end - 200, end)
if space > pos:
end = space
chunk = section[pos:end].strip()
if chunk:
final.append(chunk)
pos = end
return final if final else [text]
def build_chunks(text, target_chars=CHUNK_TARGET_CHARS):
"""Pack sections into chunks up to *target_chars*, never splitting
mid-section. A single oversized section becomes its own chunk."""
if len(text) <= target_chars:
return [text]
sections = split_into_sections(text, target_chars)
chunks = []
buf = []
buf_len = 0
for sec in sections:
sec_len = len(sec)
# Cost of adding this section: its length + 2 for "\n\n" if not first
add_len = sec_len + (2 if buf else 0)
if buf and buf_len + add_len > target_chars:
chunks.append("\n\n".join(buf))
buf = []
buf_len = 0
add_len = sec_len # first in new buffer, no separator
buf.append(sec)
buf_len += add_len
if buf:
chunks.append("\n\n".join(buf))
return chunks or [text]
# ===========================================================================
# Prompt Generation
# ===========================================================================
def build_prompt(features_config, text, chunk_info=None):
"""Assemble the extraction prompt from feature definitions + document."""
parts = [
"You are a clinical document analyst. Given the document text below, "
"extract the requested features.",
"",
"Respond with ONLY a valid JSON object - no explanation, no markdown "
"fencing, no commentary, no additional text whatsoever.",
"",
]
if chunk_info:
idx, total = chunk_info
parts.append(
f"NOTE: This is section {idx} of {total} from a larger document. "
"Evaluate features for THIS section only."
)
parts.append("")
parts.append("Features to extract:")
parts.append("")
for name, fdef in features_config.items():
ftype = fdef.get("type", "boolean")
if ftype == "boolean":
hint = "respond with true or false"
elif ftype == "enum":
opts = ", ".join(fdef["options"])
hint = f"respond with exactly one of: {opts}"
elif ftype == "text":
max_len = fdef.get("max_length")
if max_len:
hint = f"respond with a text string of at most {max_len} characters, or null if not found"
else:
hint = "respond with a text string, or null if not found"
elif ftype == "integer":
hint = "respond with an integer, or null if not applicable"
else:
hint = "respond with true or false"
desc = fdef.get("description", "").strip()
parts.append(f"- {name} ({hint})")
if desc:
parts.append(f" {desc}")
parts.append("")
parts += ["Document text:", "---", text, "---", "", "JSON output:"]
return "\n".join(parts)
# ===========================================================================
# LLM Interaction
# ===========================================================================
# Retry configuration
RETRY_DELAY_SECS = 15 # wait between retries on 503 / transient errors
RETRY_MAX_ATTEMPTS = 12 # give up after ~3 minutes of retries
RETRY_HTTP_CODES = {502, 503} # codes that trigger a retry
HALT_ON_CONN_FAILURE = False # Connection failure = exit script vs. just wait
class LLMServerDead(Exception):
"""Raised when the LLM server is unreachable (connection refused)."""
pass
def call_llm(host, model, prompt, temperature=0.0):
"""Send prompt to llama-server with retry on transient errors.
- 502/503: server restarting → retry up to RETRY_MAX_ATTEMPTS
- ConnectionError: server dead → raise LLMServerDead immediately
- Other HTTP errors: raise normally (per-document error)
"""
url = f"{host.rstrip('/')}/v1/chat/completions"
payload = {
"model": model,
"messages": [{"role": "user", "content": prompt}],
"temperature": temperature,
# "max_completion_tokens": 2048,
}
for attempt in range(1, RETRY_MAX_ATTEMPTS + 1):
if _interrupted:
raise KeyboardInterrupt
try:
resp = requests.post(url, json=payload, timeout=600)
except (requests.ConnectionError, requests.exceptions.ConnectionError) as e:
if HALT_ON_CONN_FAILURE is False and attempt < RETRY_MAX_ATTEMPTS:
print(
f" [RETRY {attempt}/{RETRY_MAX_ATTEMPTS}] "
f"Server returned connection error, "
f"waiting {RETRY_DELAY_SECS}s...",
file=sys.stderr,
)
time.sleep(RETRY_DELAY_SECS)
continue
else:
raise LLMServerDead(
f"Cannot connect to LLM server at {host} — server may be down. "
f"({e})"
) from e
if resp.status_code not in RETRY_HTTP_CODES:
break
# Transient error — wait and retry
if attempt < RETRY_MAX_ATTEMPTS:
print(
f" [RETRY {attempt}/{RETRY_MAX_ATTEMPTS}] "
f"Server returned {resp.status_code}, "
f"waiting {RETRY_DELAY_SECS}s...",
file=sys.stderr,
)
time.sleep(RETRY_DELAY_SECS)
else:
raise LLMServerDead(
f"Server returned {resp.status_code} after "
f"{RETRY_MAX_ATTEMPTS} retries (~{RETRY_MAX_ATTEMPTS * RETRY_DELAY_SECS}s). "
f"Halting run."
)
resp.raise_for_status()
return resp.json()["choices"][0]["message"]["content"]
def parse_json_response(raw):
"""Extract a JSON object (dict) from the LLM response, tolerating
markdown fences, chain-of-thought preamble, and other wrapping.
Raises ValueError with diagnostic detail if parsing fails.
"""
if raw is None:
raise ValueError("LLM returned None (empty response).")
# Strip markdown code fences
cleaned = raw.strip()
cleaned = re.sub(r"^```(?:json)?\s*\n?", "", cleaned)
cleaned = re.sub(r"\n?\s*```\s*$", "", cleaned)
def _validate(obj):
"""Ensure the parsed JSON is a dict, not null/list/string."""
if obj is None:
raise ValueError(
"LLM returned JSON null instead of an object. "
"The model may have failed to extract features from "
"this document."
)
if not isinstance(obj, dict):
raise ValueError(
f"LLM returned JSON {type(obj).__name__} instead of "
f"an object: {str(obj)[:200]}"
)
return obj
# Direct parse
try:
return _validate(json.loads(cleaned))
except json.JSONDecodeError:
pass
# Greedy search for outermost { ... }
depth = 0
start = None
for i, ch in enumerate(cleaned):
if ch == "{":
if depth == 0:
start = i
depth += 1
elif ch == "}":
depth -= 1
if depth == 0 and start is not None:
try:
return _validate(json.loads(cleaned[start : i + 1]))
except json.JSONDecodeError:
start = None
# Attempt to repair truncated JSON (response hit token limit)
if start is not None and depth > 0:
# We found an opening { but never closed it — try closing it
fragment = cleaned[start:]
# Close any open strings, then close braces
repair = fragment.rstrip()
if repair.endswith(","):
repair = repair[:-1]
# Close any open string
if repair.count('"') % 2 == 1:
repair += '"'
# Close braces
repair += "}" * depth
try:
return _validate(json.loads(repair))
except json.JSONDecodeError:
pass
# Build a diagnostic message
preview = raw[:500]
if len(raw) > 500:
preview += f"\n... ({len(raw)} chars total)"
raise ValueError(f"Could not parse JSON from LLM response:\n{raw}")
# ===========================================================================
# Feature Merging (across chunks)
# ===========================================================================
def validate_enum_values(parsed, features_config, chunk_info=None):
"""Raise ValueError if any enum feature in a single chunk's parsed
response isn't one of its declared options (case-insensitive). LLMs
occasionally hallucinate an option that was never offered; catching it
here fails the document fast (before spending more LLM calls on it)
instead of letting merge_chunk_results silently store the made-up
value. Booleans/text/integers aren't validated -- this hasn't been an
observed problem for those types.
"""
where = f" (chunk {chunk_info[0]}/{chunk_info[1]})" if chunk_info else ""
for name, fdef in features_config.items():
if fdef.get("type", "boolean") != "enum" or name not in parsed:
continue
value = parsed[name]
options = fdef.get("options", [])
if str(value).strip().lower() not in [o.lower() for o in options]:
raise ValueError(
f"Feature '{name}'{where}: LLM returned {value!r}, which is "
f"not one of the declared options {options}"
)
def merge_chunk_results(chunk_jsons, features_config):
"""Combine per-chunk extractions into a single feature dict.
- boolean: OR (any chunk True → document True)
- enum: MAX by option-list position (later = stronger)
- text: configurable via 'strategy': last-chunk (default),
first-chunk, or concatenate
- integer: MAX of non-null values; null if all chunks are null
"""
merged = {}
for name, fdef in features_config.items():
ftype = fdef.get("type", "boolean")
values = [cj[name] for cj in chunk_jsons if name in cj]
if not values:
if ftype == "boolean":
merged[name] = False
elif ftype == "enum":
merged[name] = fdef.get("options", ["unknown"])[0]
elif ftype in ("text", "integer"):
merged[name] = None
else:
merged[name] = False
continue
if ftype == "boolean":
merged[name] = any(
v is True or (isinstance(v, str) and v.lower() == "true")
for v in values
)
elif ftype == "enum":
options = [o.lower() for o in fdef.get("options", [])]
best_idx = -1
best_val = None
for v in values:
v_lower = str(v).lower().strip()
if v_lower in options:
idx = options.index(v_lower)
if idx > best_idx:
best_idx = idx
best_val = fdef["options"][idx]
if best_val is None:
# Every chunk's value was outside the declared options.
# validate_enum_values() should already have caught this
# per-chunk and aborted the document; this is a safety net,
# not the primary check -- never silently store a made-up
# value.
raise ValueError(
f"Feature '{name}': none of the LLM's returned values "
f"{values!r} match the declared options {fdef.get('options', [])}"
)
merged[name] = best_val
elif ftype == "text":
strategy = fdef.get("strategy", "last-chunk")
# Filter out null / None / empty / "not found" values
non_empty = [
str(v) for v in values
if v is not None
and str(v).strip() != ""
and str(v).strip().lower() not in ("null", "not found", "n/a", "none")
]
if not non_empty:
merged[name] = None
elif strategy == "first-chunk":
merged[name] = non_empty[0]
elif strategy == "concatenate":
merged[name] = " ".join(non_empty)
else: # last-chunk (default)
merged[name] = non_empty[-1]
elif ftype == "integer":
# Parse to int, skip nulls
int_values = []
for v in values:
if v is None or str(v).strip().lower() in ("null", "none", "n/a", "-1"):
continue
try:
int_values.append(int(float(str(v))))
except (ValueError, TypeError):
continue
merged[name] = max(int_values) if int_values else None
else:
merged[name] = values[0]
return merged
# ===========================================================================
# File Discovery
# ===========================================================================
def discover_files(corpus_paths):
"""Yield deduplicated paths of text files under one or more corpus paths.
*corpus_paths* can be a single string/Path or a list of them.
Each entry can be a directory (searched recursively) or a single file.
Files are deduplicated by resolved path so overlapping directories
don't cause duplicate processing.
"""
if isinstance(corpus_paths, (str, Path)):
corpus_paths = [corpus_paths]
seen = set()
for cp in corpus_paths:
root = Path(cp)
if root.is_file():
resolved = str(root.resolve())
if resolved not in seen:
seen.add(resolved)
yield str(root)
continue
for f in sorted(root.rglob("*")):
if f.is_file() and f.suffix.lower() in TEXT_EXTENSIONS:
resolved = str(f.resolve())
if resolved not in seen:
seen.add(resolved)
yield str(f)
def file_hash(path):
h = hashlib.sha256()
with open(path, "rb") as f:
for block in iter(lambda: f.read(65536), b""):
h.update(block)
return h.hexdigest()
# ===========================================================================
# Formatting helpers
# ===========================================================================
def fmt_duration(secs):
if secs < 60:
return f"{secs:.0f}s"
if secs < 3600:
return f"{int(secs)//60}m {int(secs)%60}s"
h = int(secs) // 3600
m = (int(secs) % 3600) // 60
return f"{h}h {m}m"
def fmt_feature_value(v):
"""Short display string for a feature value."""
if isinstance(v, bool):
return "Y" if v else "n"
if v is None:
return "–"
s = str(v)
if len(s) > 40:
return s[:37] + "..."
return s
# ===========================================================================
# Main processing loop
# ===========================================================================
def process_corpus(args, config):
features_config = config["features"]
host = args.host or config.get("llm", {}).get("host", DEFAULT_LLM_HOST)
model = args.model or config.get("llm", {}).get("model", DEFAULT_LLM_MODEL)
temperature = (
args.temperature if args.temperature is not None
else config.get("llm", {}).get("temperature", 0.0)
)
conn = get_connection()
config_hash = hashlib.sha256(yaml.dump(config).encode()).hexdigest()
if not args.dry_run:
get_or_create_run(conn, args.run_name, config, config_hash, host, model, temperature)
cleanup_incomplete(conn, args.run_name)