Repository navigation
Expand file tree
/
Copy pathflame.py
More file actions
2594 lines (2320 loc) · 137 KB
/
Copy pathflame.py
File metadata and controls
2594 lines (2320 loc) · 137 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
import numpy as np
import glob
import hashlib
import json
import math
import os
import pathlib
import re
import sys
import unicodedata
from datetime import datetime
import fargv
import tqdm
from rapidfuzz import fuzz
from itertools import chain, combinations
from difflib import SequenceMatcher
from collections import defaultdict, Counter
from abc import ABC, abstractmethod
from typing import Dict, List, Tuple, Union, Optional
import tempfile
from scipy.sparse import coo_matrix, save_npz, vstack
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.feature_extraction.text import TfidfTransformer
import plotly.graph_objects as go
from skimage.filters import threshold_otsu
import nltk
from nltk.tokenize import word_tokenize
from nltk.tokenize.treebank import TreebankWordDetokenizer
from tokenizers import Tokenizer
from tokenizers.models import BPE
from tokenizers.trainers import BpeTrainer
from tokenizers.pre_tokenizers import Whitespace
import flame_clustering
# The command line as launched. fargv consumes sys.argv while parsing it, so the
# report's "reproduce with" line has to be copied out before main() runs.
_LAUNCH_ARGV = list(sys.argv)
def fast_str_to_numpy(s: str, dtype=np.uint32) -> np.ndarray:
"""Efficiently converts a string to a NumPy array via byte encoding.
Args:
s (str): The input string.
dtype (type): The target NumPy data type.
- np.uint32 (default): Safely handles all Unicode characters
by using the 'utf-32le' encoding.
- np.uint16: Faster for pure BMP text
outside the Basic Multilingual Plane (U+0000 to U+FFFF).
Returns:
np.ndarray: A NumPy array of character codes.
"""
if dtype == np.uint32:
return np.frombuffer(s.encode('utf-32le'), dtype=dtype)
elif dtype == np.uint16:
return np.frombuffer(s.encode('utf-16le'), dtype=dtype)
else:
raise ValueError(f"Unsupported dtype for fast string conversion: {dtype}")
def fast_numpy_to_str(np_arr: np.ndarray) -> str:
"""Efficiently converts a NumPy array of character codes back to a string."""
if np_arr.dtype == np.uint16:
return np_arr.tobytes().decode('utf-16le')
elif np_arr.dtype == np.uint32:
return np_arr.tobytes().decode('utf-32le')
else:
raise ValueError(f"Unsupported dtype for fast NumPy conversion: {np_arr.dtype}")
def suggest_vocab_size_optimized(
corpus: List[str],
min_word_freq: int = 3,
max_affix_len: int = 6,
coverage_percentile: float = 0.85
) -> int:
"""Proposes an optimal vocabulary size for the BPE tokenizer based on corpus analysis.
Args:
corpus (List[str]): List of text documents.
min_word_freq (int): Minimum frequency for a word to be considered.
max_affix_len (int): Maximum length of common prefixes/suffixes to analyze.
coverage_percentile (float): Target percentile of affix occurrences to cover.
Returns:
int: Suggested vocabulary size.
"""
print("\n--- Starting Automatic Vocab Size Suggestion (Optimized) ---")
print("Counting word frequencies...")
word_counts = Counter()
tokenizer = re.compile(r'\b\w+\b')
for doc in tqdm.tqdm(corpus, desc="Tokenizing corpus"):
word_counts.update(token.lower() for token in tokenizer.findall(doc))
frequent_word_counts = {
word: count for word, count in word_counts.items()
if count >= min_word_freq and len(word) > 1
}
print(f"Found {len(word_counts)} unique words, keeping {len(frequent_word_counts)} with frequency >= {min_word_freq}.")
if not frequent_word_counts:
print("Warning: No frequent words found. Returning a default vocab size.")
return 2000
print("Creating NumPy structured array for processing...")
max_len = max(len(w) for w in frequent_word_counts.keys())
structured_dtype = [('word', f'U{max_len}'), ('freq', 'i4'), ('rev_word', f'U{max_len}')]
word_data = np.array([
(word, freq, word[::-1]) for word, freq in frequent_word_counts.items()
], dtype=structured_dtype)
affix_counts = Counter()
print("Finding common prefixes with NumPy sort...")
word_data.sort(order='word')
for i in tqdm.tqdm(range(len(word_data) - 1), desc="Analyzing prefixes"):
w1, w2 = word_data[i], word_data[i+1]
common_prefix = os.path.commonprefix([w1['word'], w2['word']])
if 1 < len(common_prefix) <= max_affix_len:
affix_counts[common_prefix] += w1['freq'] + w2['freq']
print("Finding common suffixes with NumPy sort...")
word_data.sort(order='rev_word')
for i in tqdm.tqdm(range(len(word_data) - 1), desc="Analyzing suffixes"):
rw1, rw2 = word_data[i], word_data[i+1]
common_rev_suffix = os.path.commonprefix([rw1['rev_word'], rw2['rev_word']])
if 1 < len(common_rev_suffix) <= max_affix_len:
affix_counts[common_rev_suffix[::-1]] += rw1['freq'] + rw2['freq']
print(f"Found {len(affix_counts)} potential affixes (morpheme candidates).")
if not affix_counts:
print("Warning: No common affixes found. Returning a default vocab size.")
return 2000
print(f"Calculating vocab size for {coverage_percentile:.0%} coverage...")
sorted_affixes = affix_counts.most_common()
total_affix_occurrences = sum(count for _, count in sorted_affixes)
target_coverage_sum = total_affix_occurrences * coverage_percentile
current_sum = 0
suggested_size = 0
for affix, count in sorted_affixes:
current_sum += count
suggested_size += 1
if current_sum >= target_coverage_sum:
break
base_size = 256
suggested_size_with_base = suggested_size + base_size
print(f"Analysis complete. {suggested_size} affixes are needed to cover {coverage_percentile:.0%} of all affix occurrences.")
print(f"--- Suggested Vocab Size: {suggested_size_with_base} ---")
return suggested_size_with_base
class Alphabet(ABC):
"""Abstract Base Class for defining an alphabet handling interface."""
@property
@abstractmethod
def src_alphabet(self) -> str: pass
@property
@abstractmethod
def dst_alphabet(self) -> str: pass
@property
@abstractmethod
def unknown_chr(self) -> str: pass
class AlphabetBMP(Alphabet):
"""Handles character sets within the Unicode Basic Multilingual Plane (BMP)."""
def __init__(self, sample: Union[str, None] = None, alphabet_str: Union[str, None] = None, unknown_chr: str = ''):
assert bool(sample is None) != bool(alphabet_str is None), "Either 'sample' or 'alphabet_str' must be provided, but not both."
if sample is not None:
self.__src_alphabet_str = ''.join(sorted(set(sample) - set(unknown_chr)))
else:
if unknown_chr:
assert unknown_chr not in alphabet_str, "Alphabet string must not contain the unknown character."
assert len(alphabet_str) == len(set(alphabet_str)), "Alphabet string must not contain duplicates."
self.__src_alphabet_str = alphabet_str
self.__unknown_chr = unknown_chr
self._chr2chr, self._npint2int = self._create_mappers()
def _create_mappers(self) -> Tuple[defaultdict, np.ndarray]:
chr2chr = defaultdict(lambda: self.__unknown_chr)
chr2chr.update({a: a for a in self.__src_alphabet_str})
full_str = self.__unknown_chr + self.__src_alphabet_str
np_int2int = np.zeros(2**16, dtype=np.uint16)
if self.__unknown_chr:
np_int2int.fill(ord(self.__unknown_chr))
for c in full_str:
np_int2int[ord(c)] = ord(c)
return chr2chr, np_int2int
@property
def src_alphabet(self): return self.__src_alphabet_str
@property
def dst_alphabet(self): return self.__src_alphabet_str
@property
def unknown_chr(self): return self.__unknown_chr
def __call__(self, text: str) -> str:
return fast_numpy_to_str(self._npint2int[fast_str_to_numpy(text, dtype=np.uint16)])
def get_encoding_information_loss(self, text: str) -> float:
np_text = fast_str_to_numpy(text, dtype=np.uint16)
mapped_np_text = self._npint2int[np_text]
return np.mean(np_text != mapped_np_text)
class CharacterMapper(AlphabetBMP):
"""Extends AlphabetBMP to support custom, user-defined character-to-character mappings."""
def __init__(self, src_alphabet: str, mapping_dict: Dict[str, str], unknown_chr: str = ''):
self.__custom_mapping_dict = mapping_dict
super().__init__(alphabet_str=src_alphabet, unknown_chr=unknown_chr)
self.__dst_alphabet_str = ''.join(sorted(set(self.__custom_mapping_dict.values()) - set(unknown_chr)))
def _create_mappers(self) -> Tuple[defaultdict, np.ndarray]:
chr2chr, np_int2int = super()._create_mappers()
for src_char, dst_char in self.__custom_mapping_dict.items():
np_int2int[ord(src_char)] = ord(dst_char)
chr2chr.update(self.__custom_mapping_dict)
return chr2chr, np_int2int
def _update_mappings(self, new_mappings: Dict[str, str]):
self.__custom_mapping_dict.update(new_mappings)
self._chr2chr, self._npint2int = self._create_mappers()
class AdaptiveAlphabet(CharacterMapper):
"""An adaptive normalizer that learns character mappings from a text corpus dynamically."""
def __init__(self, src_alphabet: str, unknown_chr: str = '', initial_mapping_dict: Optional[Dict[str, str]] = None):
mapping_dict = initial_mapping_dict if initial_mapping_dict is not None else {}
super().__init__(src_alphabet=src_alphabet, mapping_dict=mapping_dict, unknown_chr=unknown_chr)
def analyze_lost_chars(self, text: str) -> defaultdict:
lost_chars_count = defaultdict(int)
np_text = fast_str_to_numpy(text, dtype=np.uint16)
mapped_np_text = fast_str_to_numpy(self(text), dtype=np.uint16)
if not self.unknown_chr:
return lost_chars_count
unknown_chr_ord = ord(self.unknown_chr)
lost_indices = np.where(mapped_np_text == unknown_chr_ord)[0]
original_lost_chars = np_text[lost_indices]
for char_ord in original_lost_chars:
if char_ord != unknown_chr_ord:
lost_chars_count[chr(char_ord)] += 1
return lost_chars_count
def learn_mappings(self, text: str, strategy: str = 'normalize', min_freq: int = 2):
print("\nStarting Autonomous Character Normalization")
lost_chars = self.analyze_lost_chars(text)
if not lost_chars:
print("No characters require normalization. The source alphabet is comprehensive.")
print("--- Character Normalization Complete ---\n")
return
unfound_chars_list = sorted(list(lost_chars.keys()))
print(f"Found {len(lost_chars)} unique characters not in the source alphabet: [{' '.join(unfound_chars_list)}]")
new_mappings = {}
if strategy == 'normalize':
print(f"Applying '{strategy}' strategy for characters with frequency >= {min_freq}...")
for char, count in sorted(lost_chars.items(), key=lambda item: item[1], reverse=True):
if count >= min_freq:
normalized_char_seq = unicodedata.normalize('NFKD', char)
if normalized_char_seq:
normalized_char = normalized_char_seq[0]
if normalized_char in self.src_alphabet and normalized_char != char:
new_mappings[char] = normalized_char
print(f" + Suggesting mapping: '{char}' -> '{normalized_char}' (found {count} times)")
else:
raise ValueError(f"Unknown strategy: {strategy}")
if new_mappings:
print(f"Generated {len(new_mappings)} new mapping rules. Updating normalizer.")
self._update_mappings(new_mappings)
else:
print("No new normalization rules were generated based on the current strategy and threshold.")
print("--- Character Normalization Complete ---\n")
DEFAULT_PARAMS = {
'input_path': '',
'input_path2': '',
'file_suffix': '.txt',
'keep_texts': 10000,
# Off by default: whether two identical files are two documents or one is a
# scholarly decision, not a technical one. Corpora assembled from editions and
# archival copies routinely hold the same charter under several names (a
# shelfmark, an edition, and a "(1)" re-download), and leaving the flag off
# reproduces exactly what is on disk.
'deduplicate': False,
'ngram': 6,
'n_out': 1,
'min_text_length': 150,
'similarity_threshold': 'auto',
'auto_threshold_method': 'otsu',
'char_norm_alphabet': 'abcdefghijklmnopqrstuvwxyz',
'char_norm_strategy': 'normalize',
'char_norm_min_freq': 1,
'phonetic_reduction_enabled': False,
'phonetic_reduction_alphabet': 'aefiklmnopqrstuwxz',
'phonetic_reduction_rules': 'b>p,c>k,d>t,g>k,j>i,q>k,v>f,y>i,z>s',
'bigram_normalization_enabled': False,
'bigram_normalization_rules': 'ss>s,ff>f,tt>t,ll>l,ie>i,au>u,ei>i,eu>u,oh>o,ah>a,eh>e,uh>u',
'vocab_size': 'auto',
'vocab_min_word_freq': 5,
'vocab_coverage': 0.85,
# Decides variant vs. bridge for the words between two matches (see classify_gap).
# Calibrated on a two-copies comparison (Georg_problems0928): genuine divergences
# scored <= 0.40 once folded, while spelling variants scored >= 0.72 -- so anything
# in 0.45-0.70 separates cleanly and 0.70 keeps the borderline cases as variants.
'fuzz_threshold': 0.70,
'max_gap_words': 5,
'auto_tune': False,
'auto_tune_sample_size': 30,
# Clustering (legal-formula): groups the surviving pairs by the formula
# core they share. cluster_threshold is the similarity two CORES must reach to
# merge, on the same 0-1 scale as fuzz_threshold but a different quantity --
# fuzz_threshold judges the words between two matches, this judges whole
# formulas against each other, so it is calibrated separately (KONI's default
# was 0.85). Measured on the MOM corpus at 0.85 vs 0.70: a papal privilege
# template whose recipients differ (one abbey against one hospital) had been
# split into four clusters of 24, 12, 6 and 2 charters; at 0.70 those four
# merge into one 49-charter cluster, and that was the only merge among the
# clusters of four or more members -- apart from a second papal formula
# ('militanti ecclesie'). 0.70 finds 40 clusters against 34, adds no
# near-duplicate (11 either way, the section is judged on coverage, not on
# this threshold), and 0.65 already over-merges (a 70-charter cluster with
# 0.44-0.50 cohesion), so 0.70 is the loose end of what still separates.
'cluster_threshold': 0.70,
'cluster_min': 2,
# What a cluster IS. 'louvain' (default) looks for cores that are denser
# among themselves than with the rest, which is what keeps one formula with
# variable slots in one piece; 'clique' splits each group into maximal
# cliques, so every core in a cluster agrees with every other; 'union' keeps
# KONI's connected components, which also merge A with C when only A~B and
# B~C hold. A string rather than a boolean because fargv treats a boolean as
# a presence switch: a True-defaulted flag could never be turned back off
# from the command line, only from the GUI.
'cluster_linkage': 'louvain',
# How far a formula's variable slot may open before the core is cut in two:
# the gapped alignment (flame_clustering.align_core) chains matching runs
# across gaps of at most this many tokens on either side. Eight spans the
# widest slot measured in the corpus (a name, a place, a case ending) without
# bridging the distance between two different formulas.
'core_gap_tolerance': 8,
# Shortest window (its shorter side) that still counts as a formula; below
# it the pair falls back to the strict contiguous core.
'core_min_tokens': 12,
# Where a formula is looked for: the performative verbs that carry a charter's
# legal act (donamus, contulimus, confirmamus...). Comma-separated *stems*,
# prefix-matched against the folded tokens, because the ending is what varies
# (donamus / donauimus / donauerunt) and folding keeps the corpus's u-for-v
# spelling (contulimus, uendidimus). Without anchoring the alignment maximises
# matched tokens, and the longest shared run in a mediaeval charter is the
# protocol -- measured on the MOM corpus, no core came out below 56 tokens and
# 28 of 40 clusters opened on a protocol phrase -- so the verbs are what tell
# the aligner where the act is. A pair whose shared text carries none keeps
# the unanchored window, which the report counts. Empty (or `none`) switches
# anchoring off and gives back the pre-anchor clustering word for word;
# `-core_anchors=` does the same from the CLI (the `=` form: fargv crashes on
# a bare empty argument).
#
# There is no built-in list, and that is a measured decision rather than an
# oversight. A hand-written Latin-and-German list was tried and is gone
# because it does not hold: on MOM, 11 of its 38 stems (vendidimus, vendimus,
# emancipauimus, concessimus, promittimus, assignauimus, commutauimus,
# verleihen, verkaufen, ubergeben, ...) do not occur in the corpus at all,
# and 153 of the 441 admitted pairs (34.7%) share no word of it, so a third
# of the corpus fell back to the unanchored window on the very corpus the
# list was written for.
#
# Discovering the verbs from the corpus was then tried and did *not* work,
# and the measurements are why the file ships without a list rather than
# with a worse one:
# * document frequency, occupancy, context entropy, positional spread, the
# IDF of a token's neighbours, and every conjunction of them were ranked
# against the verbs the hand list did reach: the best rule selected 8676
# tokens to find 45 verbs (precision 0.5%, recall 34.9%). The reason is
# that the verbs are 0.3% of the recurring vocabulary and statistically
# ordinary: `contulimus` has df 416 beside `iuris` at 1093, in a band
# holding 1241 tokens of which 16 are verbs.
# * phrase-level rarity (k-gram document frequency) does not locate the act
# either: ranked within a pair's shared span it puts the act at relative
# rank 0.467 -- chance.
# * rarity as the *objective* is the wrong sign: mean unigram IDF, summed
# IDF, rarest-word IDF and phrase DF all anti-select the act (median
# relative rank 0.57-0.70), because the act formula is shared by its act
# family while the average shared passage is a one-off list of names.
# * morphology is the signal a reader uses, and it is not separable on the
# surface: handed the ending inventory of the known verbs as an oracle,
# `-mus/-nt/-it` still selects 2215 tokens to find 50 verbs (2.3%).
# Identifying the performative verb is a lexical or morphological task, so
# the resource is per-corpus input, not a constant in this file.
'core_anchors': '',
# How far the window may extend past the anchor, in tokens, on either side.
# Fifteen is the length of the act's habitual surroundings (the operative
# clause plus the sanctio that follows it) without reaching the arenga.
'core_anchor_window': 15,
# Hard ceiling on the reported window, in tokens. The legal act is short --
# a dispositio runs 15-40 words -- while a protocol panel runs to 200, so
# without a ceiling a long generic overlap still outvotes a short specific
# one. 0 leaves the window uncapped (the pre-anchor behaviour).
'core_max_tokens': 50,
# A near-duplicate charter is reported separately from a shared formula when
# its shared window is at least this many words AND covers at least
# MAX_CORE_FRACTION of the shorter charter. Both are needed: the share alone
# calls a short charter duplicate when its text is mostly one formula.
'min_duplicate_tokens': 400,
# Minimum gap-only identity (2*matched/(len_a+len_b)) for an aligned core to
# be accepted as a formula; below it the pair falls back to the strict
# contiguous core. 0.0 accepts every window the aligner returns.
'core_identity_threshold': 0.0,
# Drops clusters whose specificity (core length x mean IDF of its words) is
# below this. 0.0 keeps every cluster: the specificity is reported either way,
# and whether a widespread panel counts as a finding is a scholarly call.
'min_core_specificity': 0.0,
# Optional file of tokens (one per line, '#' comments) whose IDF is forced to
# zero when specificity is measured -- a hand-curated diplomatic stop list.
# Empty by default: the corpus's own document frequencies already know that
# 'salutem' and 'benedictionem' are everywhere.
'stopwords_file': '',
'no_reports': False,
'gen_comparison_html': True,
'gen_summary_tsv': True,
'gen_linguistic_tsv': True,
# Off by default: a presence switch (-gen_spans_jsonl) turns it on, and an
# opt-in output leaves every existing run's files exactly as they were.
'gen_spans_jsonl': False,
'gen_heatmap': True,
'gen_clusters': True,
}
def parse_phonetic_rules(rules_str: str) -> Dict[str, str]:
"""Parse phonetic reduction rules from string format 'b>p,c>k,...' into a mapping dict.
Args:
rules_str: Comma-separated rules, each in 'src>dst' format.
Returns:
Dict mapping source characters to destination characters.
Invalid rules are skipped with a warning.
"""
mapping = {}
if not rules_str or not rules_str.strip():
return mapping
for rule in rules_str.split(','):
rule = rule.strip()
if not rule:
continue
parts = rule.split('>')
if len(parts) != 2:
print(f" Warning: Invalid phonetic rule '{rule}' — expected 'src>dst' format. Skipping.")
continue
src, dst = parts[0].strip(), parts[1].strip()
if len(src) != 1 or len(dst) != 1:
print(f" Warning: Invalid phonetic rule '{rule}' — both src and dst must be single characters. Skipping.")
continue
mapping[src] = dst
return mapping
def parse_bigram_rules(rules_str: str) -> Dict[str, str]:
"""Parse bigram normalization rules from string format 'ss>s,ff>f,...' into a mapping dict.
Unlike phonetic rules, the source side can be multiple characters (one-to-many).
The destination must be exactly one character.
Args:
rules_str: Comma-separated rules, each in 'src>dst' format.
Returns:
Dict mapping source strings to destination characters.
Invalid rules are skipped with a warning.
"""
mapping = {}
if not rules_str or not rules_str.strip():
return mapping
for rule in rules_str.split(','):
rule = rule.strip()
if not rule:
continue
parts = rule.split('>')
if len(parts) != 2:
print(f" Warning: Invalid bigram rule '{rule}' — expected 'src>dst' format. Skipping.")
continue
src, dst = parts[0].strip(), parts[1].strip()
if len(src) < 2:
print(f" Warning: Invalid bigram rule '{rule}' — src must be at least 2 characters. Skipping.")
continue
if len(dst) != 1:
print(f" Warning: Invalid bigram rule '{rule}' — dst must be a single character. Skipping.")
continue
mapping[src] = dst
return mapping
class Flame:
"""Main pipeline execution for medieval formulaic language alignment."""
def __init__(self, args, tmp_dir: str = '.'):
self.args = args
# What loading the corpus skipped, filled in by _load_corpus_from_path.
# Empty rather than absent so the report can read it even when a corpus
# was never loaded (a direct caller, a test).
self.load_stats: Dict[str, int] = {}
self.load_stats2: Dict[str, int] = {}
# The second input may be a directory or a glob pattern, so a pattern must not
# be mistaken for "no second corpus".
self.is_inter_comparison = bool(self.args.input_path2 and
(os.path.isdir(self.args.input_path2) or
looks_like_pattern(self.args.input_path2)))
self.tmp_dir = tmp_dir
self.corpus: List[str] = []
self.file_paths: List[pathlib.Path] = []
# Roots the reports name texts relative to (see display_path).
self.corpus_root: Optional[pathlib.Path] = None
self.corpus_root2: Optional[pathlib.Path] = None
self.tokenized_corpus: List[List[str]] = []
self.corpus2: List[str] = []
self.file_paths2: List[pathlib.Path] = []
self.tokenized_corpus2: List[List[str]] = []
self.encoder: Dict[str, int] = {}
self.dist_mat = None
self.tokenizer_model = None
def _find_text_files(self, input_path: str) -> Tuple[List[pathlib.Path], Optional[pathlib.Path]]:
"""Resolves an input path to a sorted file list plus the root that reported
paths are relative to.
The input may be a directory (searched recursively for files ending in
file_suffix) or a glob pattern such as ./fsdb/DE-LANRWR**/*.htr.txt. For a
pattern the pattern itself decides which files are read and file_suffix is
ignored, so a pattern like *.htr is not silently emptied by a .txt filter.
"""
if looks_like_pattern(input_path):
base = pattern_base(input_path)
files = find_pattern_files(input_path)
if not files:
print(f"Warning: Pattern '{input_path}' matched no files.")
return files, base
path = pathlib.Path(input_path)
if not path.exists() or not path.is_dir():
print(f"Warning: Input path {path} does not exist or is not a directory. Skipping.")
return [], None
# Sorted so the corpus order -- and with it the distance matrix -- is
# reproducible instead of depending on filesystem traversal order.
return sorted(path.rglob(f"*{self.args.file_suffix}")), path
def _read_text_file(self, file_path: pathlib.Path) -> Union[str, None]:
try:
with open(file_path, 'r', encoding='utf-8') as f:
return ' '.join(f.read().strip().split())
except Exception as e:
print(f"Warning: Could not read file {file_path}: {e}")
return None
def _load_corpus_from_path(self, path_str: str
) -> Tuple[List[str], List[pathlib.Path], Optional[pathlib.Path], Dict[str, int]]:
"""Loads texts from a directory or glob pattern; also returns the root that the
reports name these texts relative to, and what the loading skipped.
The counts come back rather than only being printed because the cluster
report has to state its own input: a reader who was handed the HTML and
nothing else cannot tell a 12 000-charter corpus from a 400-charter one,
and "how many charters was this computed on" is the first thing they ask.
"""
file_paths, root = self._find_text_files(path_str)
if looks_like_pattern(path_str):
print(f"Found {len(file_paths)} files for pattern '{path_str}'")
else:
print(f"Found {len(file_paths)} files in '{path_str}' with suffix '{self.args.file_suffix}'")
corpus_data, loaded_paths = [], []
skipped_short = 0
# Content hash -> the surviving file and its position in corpus_data, so an
# identical file can be recognised no matter what it is called. Only
# populated when deduplicating.
seen_texts: Dict[str, Tuple[pathlib.Path, int]] = {}
# key -> the files skipped for holding that key's text. A file lands here
# either because it lost to the current keeper or because it was the keeper
# and a shorter-named copy displaced it; either way exactly one entry is
# added per skipped file, so the grouped report stays truthful.
duplicates: Dict[str, List[pathlib.Path]] = {}
limit = self.args.keep_texts
# For a pattern, name the progress bar after the directory it starts in --
# basename would show the glob itself, e.g. "Loading files from *.htr.txt".
source = str(pattern_base(path_str)) if looks_like_pattern(path_str) else path_str
limit_reached = False
for file_path in tqdm.tqdm(file_paths, desc=f"Loading files from {os.path.basename(source)}"):
text = self._read_text_file(file_path)
if not text or len(text) < self.args.min_text_length:
skipped_short += 1
continue
if self.args.deduplicate:
# Hashed on the text as loaded, not on the raw bytes: two files
# differing only in whitespace are the same document to every part
# of the pipeline downstream, since that is the string the engine
# tokenizes.
key = hashlib.sha1(text.encode('utf-8')).hexdigest()
kept = seen_texts.get(key)
if kept is not None:
kept_path, kept_index = kept
# Among identical files the shorter name wins. Corpora assemble
# the same charter as "X.txt", "X (1).txt" and a long shelfmark,
# and the re-download -- the one name nobody wants to keep -- is
# never the shortest. The text is identical to the letter, so a
# swap changes only the name the reports use: the document keeps
# its position, and with it the distance matrix row it had.
if len(file_path.name) < len(kept_path.name):
duplicates.setdefault(key, []).append(kept_path)
loaded_paths[kept_index] = file_path
seen_texts[key] = (file_path, kept_index)
else:
duplicates.setdefault(key, []).append(file_path)
continue
seen_texts[key] = (file_path, len(corpus_data))
corpus_data.append(text)
loaded_paths.append(file_path)
if len(corpus_data) >= limit:
print(f"Reached limit of {limit} texts for this directory.")
limit_reached = True
break
if self.args.deduplicate:
self._report_duplicates(duplicates, seen_texts, len(file_paths))
stats = {
"found": len(file_paths),
"loaded": len(corpus_data),
"short": skipped_short,
"duplicate": sum(len(paths) for paths in duplicates.values()),
"limit_reached": limit_reached,
}
return corpus_data, loaded_paths, root, stats
@staticmethod
def _report_duplicates(duplicates: Dict[str, List[pathlib.Path]],
seen_texts: Dict[str, Tuple[pathlib.Path, int]],
scanned: int) -> None:
"""Prints what deduplication dropped, naming both sides of every match.
The full list is printed rather than a summary count on purpose: a corpus
that silently loses a third of its files to a wrong flag would be a nasty
surprise, and only the names show whether the dropped ones were true
repeats (an edition and its archival copy) or something unexpected.
Grouped by content, not listed pair by pair: the name that survives can
change while the scan runs (a later, shorter-named copy of the same text
takes its place), so a per-duplicate "same text as X" line could name a
file that was itself dropped a moment later. Printing the group with its
one survivor says the same thing without that trap.
"""
skipped = sum(len(paths) for paths in duplicates.values())
print(f"\n--- Deduplication: {skipped} of {scanned} file(s) skipped as repeats ---")
for key, dropped in duplicates.items():
kept = seen_texts[key][0]
print(f"'{kept}' -- {len(dropped) + 1} file(s) hold this text; kept this one, skipped:")
for path in dropped:
print(f" {path}")
if skipped:
print(f"Kept {scanned - skipped} file(s) out of {scanned}.")
else:
print("No two files held the same text.")
def load_corpus(self):
"""Loads files, runs character level mapping layers, and builds BPE vocabulary model."""
self.corpus, self.file_paths, self.corpus_root, self.load_stats = \
self._load_corpus_from_path(self.args.input_path)
if self.is_inter_comparison:
print("\n--- Two-directory comparison mode activated ---")
self.corpus2, self.file_paths2, self.corpus_root2, self.load_stats2 = \
self._load_corpus_from_path(self.args.input_path2)
if not self.corpus2:
print("Warning: Second directory is empty or invalid. Reverting to single-directory mode.")
self.is_inter_comparison = False
if not self.corpus:
print("Error: No valid texts loaded from the primary directory. Aborting.")
return
corpus_for_learning = self.corpus + self.corpus2
print(f"\nTotal texts for analysis: {len(corpus_for_learning)}")
lowercased_corpus = [text.lower() for text in corpus_for_learning]
# Shared with the visualizer (see MUFI_ONE_TO_MANY / MUFI_ONE_TO_ONE below), so
# that a gap is judged by the same normalization the matcher itself applied.
one_to_many_mappings = MUFI_ONE_TO_MANY
one_to_one_mappings = MUFI_ONE_TO_ONE
print("\n--- Applying 1-to-many character replacements (e.g., ligatures) ---")
pre_processed_corpus = []
for text in tqdm.tqdm(lowercased_corpus, desc="Pre-processing"):
for src, dst in one_to_many_mappings.items():
text = text.replace(src, dst)
pre_processed_corpus.append(text)
# --- BIGRAM NORMALIZATION ---
if self.args.bigram_normalization_enabled:
print("\n--- Applying Bigram Normalization ---")
bigram_rules = parse_bigram_rules(self.args.bigram_normalization_rules)
if bigram_rules:
rules_desc = ', '.join(f"'{s}'->'{d}'" for s, d in sorted(bigram_rules.items()))
print(f" Active rules: {rules_desc}")
for i in tqdm.tqdm(range(len(pre_processed_corpus)), desc="Bigram Normalization"):
for src, dst in bigram_rules.items():
pre_processed_corpus[i] = pre_processed_corpus[i].replace(src, dst)
print(f" Bigram normalization applied to {len(pre_processed_corpus)} texts.")
else:
print(" No valid bigram rules configured. Skipping.")
print("--- Bigram Normalization Complete ---\n")
full_corpus_text = "\n".join(pre_processed_corpus)
target_alphabet = self.args.char_norm_alphabet.replace(' ', '')
print("\n--- Initializing Character Normalizer with 1-to-1 MUFI rules ---")
learner = AdaptiveAlphabet(
src_alphabet=target_alphabet,
unknown_chr=' ',
initial_mapping_dict=one_to_one_mappings
)
learner.learn_mappings(
full_corpus_text,
strategy=self.args.char_norm_strategy,
min_freq=self.args.char_norm_min_freq
)
print("Applying final normalization rules to the corpus...")
normalized_corpus_full = [learner(text) for text in tqdm.tqdm(pre_processed_corpus, desc="Normalizing")]
# --- PHONETIC REDUCTION LAYER ---
if self.args.phonetic_reduction_enabled:
print("\n--- Applying Phonetic Reduction ---")
phonetic_alphabet = self.args.phonetic_reduction_alphabet.replace(' ', '')
if not phonetic_alphabet:
print("Warning: Phonetic reduction alphabet is empty. Skipping phonetic reduction.")
print("--- Phonetic Reduction Skipped ---\n")
else:
phonetic_rules = parse_phonetic_rules(self.args.phonetic_reduction_rules)
validated_rules = {}
for src, dst in phonetic_rules.items():
if dst not in phonetic_alphabet:
print(f" Warning: Rule '{src}>{dst}' maps to '{dst}' which is not in the reduced alphabet. Skipping.")
else:
validated_rules[src] = dst
if validated_rules:
rules_desc = ', '.join(f"'{s}'->'{d}'" for s, d in sorted(validated_rules.items()))
print(f" Active rules: {rules_desc}")
else:
print(" No valid phonetic rules configured. Only alphabet filtering will apply.")
phonetic_mapper = CharacterMapper(
src_alphabet=phonetic_alphabet,
mapping_dict=validated_rules,
unknown_chr=' '
)
normalized_corpus_full = [
phonetic_mapper(text)
for text in tqdm.tqdm(normalized_corpus_full, desc="Phonetic Reduction")
]
print(f" Phonetic reduction applied to {len(normalized_corpus_full)} texts.")
print("--- Phonetic Reduction Complete ---\n")
print("\n--- Training Subword Tokenizer ---")
corpus_file = os.path.join(self.tmp_dir, 'temp_corpus.txt')
with open(corpus_file, 'w', encoding='utf-8') as f:
for line in normalized_corpus_full:
f.write(line + '\n')
if str(self.args.vocab_size).lower() == 'auto':
vocab_size = suggest_vocab_size_optimized(
normalized_corpus_full,
min_word_freq=self.args.vocab_min_word_freq,
coverage_percentile=self.args.vocab_coverage
)
else:
try:
vocab_size = int(self.args.vocab_size)
print(f"\n--- Using specified vocab size: {vocab_size} ---")
except ValueError:
print(f"Error: Invalid vocab_size '{self.args.vocab_size}'. Please provide a number or 'auto'.")
return
print("Counting unique words to determine maximum possible vocab size...")
all_words = set(word for line in normalized_corpus_full for word in line.split())
max_possible_size = len(all_words) + 256
if vocab_size > max_possible_size:
print(f"Warning: Requested vocab size ({vocab_size}) is larger than the number of unique words found ({len(all_words)}).")
print(f"Adjusting vocab size to the maximum possible value: {max_possible_size}")
vocab_size = max_possible_size
tokenizer = Tokenizer(BPE(unk_token="[UNK]"))
tokenizer.pre_tokenizer = Whitespace()
trainer = BpeTrainer(
vocab_size=vocab_size,
special_tokens=["[UNK]", "[PAD]", "[CLS]", "[SEP]", "[MASK]"]
)
model_path = os.path.join(self.tmp_dir, 'bpe_tokenizer.json')
print(f"INFO: Training BPE tokenizer with final vocab_size: {vocab_size}")
tokenizer.train([corpus_file], trainer=trainer)
tokenizer.save(model_path)
self.tokenizer_model = Tokenizer.from_file(model_path)
print("--- Subword Tokenizer Trained and Loaded ---\n")
print("Tokenizing all documents using subword tokenizer...")
all_tokenized = [self.tokenize(text) for text in tqdm.tqdm(normalized_corpus_full, desc="Tokenizing")]
if all_tokenized:
print("\n--- Example of Subword Tokenization ---")
original_text_sample = ' '.join(normalized_corpus_full[0].split()[:25])
tokenized_sample = all_tokenized[0]
print(f"Original Text (first 25 words): '{original_text_sample}...'\n")
print(f"Tokenized Output:\n{tokenized_sample}")
print("---------------------------------------\n")
self.encoder = self.get_encoder(all_tokenized)
if not self.encoder:
print("Warning: Encoder could not be built (empty vocabulary). Aborting.")
return
if self.is_inter_comparison:
len_corpus1 = len(self.corpus)
self.tokenized_corpus = all_tokenized[:len_corpus1]
self.tokenized_corpus2 = all_tokenized[len_corpus1:]
else:
self.tokenized_corpus = all_tokenized
def auto_tune_parameters(self):
"""Performs unsupervised parameter digging (auto-tuning) by injecting synthetic noise
and performing a grid search to optimize the Signal-to-Noise Ratio (SNR) spread.
"""
print("\n--- Starting Unsupervised Parameter Auto-Tuning (Trial Digging) ---")
np.random.seed(42) # Secure structural repeatability across tuning checks
sample_size = min(int(self.args.auto_tune_sample_size), len(self.tokenized_corpus))
if sample_size < 2:
print("Corpus too small to evaluate statistical separation. Skipping tuning.")
return
# Prepare a sample and a perturbed twin corpus to emulate transcription / dialect noise
sample_tokens_list = self.tokenized_corpus[:sample_size]
perturbed_tokens_list = []
for tokens in sample_tokens_list:
perturbed = []
for t in tokens:
# 5% probability to simulate subword variation / spelling decay
if np.random.rand() < 0.05:
if np.random.rand() < 0.5 and len(perturbed) > 0:
perturbed.pop() # Simulating character/token dropping
continue
perturbed.append(t)
perturbed_tokens_list.append(perturbed)
best_snr = -float('inf')
best_ngram = self.args.ngram
best_n_out = self.args.n_out
# Search parameter space grid
candidate_grid = [(4, 0), (4, 1), (5, 0), (5, 1), (5, 2), (6, 0), (6, 1), (6, 2), (7, 1), (7, 2)]
orig_ngram, orig_n_out = self.args.ngram, self.args.n_out
print("Evaluating local parameters across structural separation bounds...")
for ngram, n_out in candidate_grid:
if ngram - n_out < 1: continue
self.args.ngram = ngram
self.args.n_out = n_out
orig_features = [self.leave_n_out_grams(t) for t in sample_tokens_list]
pert_features = [self.leave_n_out_grams(t) for t in perturbed_tokens_list]
local_vocab = {}
idx = 0
for feats in orig_features + pert_features:
for f in feats:
if f not in local_vocab:
local_vocab[f] = idx
idx += 1
if not local_vocab: continue
def generate_vector(feats):
vec = np.zeros(len(local_vocab))
if feats.size > 0:
u, c = np.unique(feats, return_counts=True)
for val, count in zip(u, c):
if val in local_vocab:
vec[local_vocab[val]] = count
norm = np.linalg.norm(vec)
return vec / norm if norm > 0 else vec
orig_vectors = [generate_vector(f) for f in orig_features]
pert_vectors = [generate_vector(f) for f in pert_features]
# Measure Signal (Similarity between original and matched perturbed target)
signals = [np.dot(orig_vectors[i], pert_vectors[i]) for i in range(sample_size)]
avg_signal = np.mean(signals)
# Measure Noise (Cross-similarities with wrong documents)
noises = []
for i in range(sample_size):
for j in range(sample_size):
if i != j:
noises.append(np.dot(orig_vectors[i], pert_vectors[j]))
avg_noise = np.mean(noises) if noises else 0.0
# Compute separation index optimization score
snr = avg_signal - avg_noise
if snr > best_snr and avg_signal > 0.05:
best_snr = snr
best_ngram = ngram
best_n_out = n_out
self.args.ngram = best_ngram
self.args.n_out = best_n_out
print(f"--- Auto-Tune Selection Complete ---")
print(f"Optimal N-Gram set to: {best_ngram}")
print(f"Optimal N-Out (Gaps) set to: {best_n_out}")
print(f"Optimized Separation Margin Spread: {best_snr:.4f}\n")
def tokenize(self, text_str: str) -> List[str]:
if not self.tokenizer_model:
raise RuntimeError("Tokenizer model is not loaded. Run load_corpus first.")
return self.tokenizer_model.encode(text_str).tokens
def get_encoder(self, all_tokenized_docs: List[List[str]]) -> Dict[str, int]:
print("Building vocabulary encoder...")
all_tokens = {token for doc in all_tokenized_docs for token in doc}
unique_tokens = sorted(list(all_tokens))
return {token: i for i, token in enumerate(unique_tokens)}
def tokens_to_int(self, tokens: List[str]) -> List[int]:
return [self.encoder[token] for token in tokens if token in self.encoder]
def _determine_auto_threshold(self, method: str = 'otsu', percentile: int = 99) -> float:
if self.dist_mat is None or self.dist_mat.nnz == 0:
print("Warning: Cannot determine auto threshold, similarity matrix is empty.")
return 0.01
scores = self.dist_mat.data
if method == 'otsu':
try:
auto_threshold = threshold_otsu(scores)
print(f"Automatically determined threshold (Otsu's method): {auto_threshold:.4f}")
return float(auto_threshold)
except ImportError:
print("Warning: scikit-image is not installed. Falling back to percentile method.")
return self._determine_auto_threshold(method='percentile', percentile=percentile)
elif method == 'percentile':
if scores.size == 0: return 0.01
auto_threshold = np.percentile(scores, percentile)
print(f"Automatically determined threshold ({percentile}th percentile): {auto_threshold:.4f}")
return float(auto_threshold)
else:
raise ValueError(f"Unknown auto-threshold method: {method}")
def leave_n_out_grams(self, tokens: List[str]) -> np.ndarray:
"""Vectorized rolling hash fingerprinting matching the leave-n-out specification."""
MOD = 2**61 - 1
int_tokens = np.array(self.tokens_to_int(tokens), dtype=np.int64)
seq_len = len(int_tokens)
elements_to_keep = self.args.ngram - self.args.n_out
if elements_to_keep < 1 or seq_len < self.args.ngram:
return np.array([], dtype=np.int64)
vocab_size = len(self.encoder)
if vocab_size == 0:
return np.array([], dtype=np.int64)
num_ngrams = seq_len - self.args.ngram + 1
ngram_matrix = np.array([
int_tokens[i : i + num_ngrams] for i in range(self.args.ngram)
], dtype=np.int64)
indices_to_keep_combinations = list(combinations(range(self.args.ngram), elements_to_keep))
all_feature_hashes = []
for combo_indices in indices_to_keep_combinations:
sub_gram_matrix = ngram_matrix[list(combo_indices), :]
num_sub_gram_tokens = len(combo_indices)
powers = np.power(vocab_size, np.arange(num_sub_gram_tokens), dtype=object) % MOD
hashed_values = np.mod(np.dot(powers, sub_gram_matrix), MOD)
all_feature_hashes.append(hashed_values)
return np.concatenate(all_feature_hashes) if all_feature_hashes else np.array([], dtype=np.int64)
def compute_similarity_matrix(self):
if not self.tokenized_corpus:
print("Corpus is not tokenized. Skipping similarity matrix computation.")
return
print("Generating features for all documents...")
doc_features1 = [self.leave_n_out_grams(tokens) for tokens in tqdm.tqdm(self.tokenized_corpus, desc="Generating features for Corpus 1")]
all_doc_features_lists = [doc_features1]