-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathedit_dicta_cli.py
More file actions
935 lines (817 loc) · 37.4 KB
/
Copy pathedit_dicta_cli.py
File metadata and controls
935 lines (817 loc) · 37.4 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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
edit_dicta_cli.py — CLI / headless עטיפה לסקריפטים של EditingDictaBooks.
המטרה: לאפשר הרצה אוטומטית של כל פעולת עריכה (יצירת כותרות, ניקוי טקסט,
בדיקת תגים וכו') ללא PyQt5, מתאים ל-CI, agents, scripting.
הסקריפט מחלץ את הלוגיקה הטהורה מ-EditingDictaBooks.py - אינו מייבא אותו,
ואינו תלוי ב-Qt / win32. כל פקודה כותבת תוצאה אנושית ל-stderr, וב-`--json`
פלט JSON ל-stdout. קוד יציאה:
0 = הצלחה (או "אין מה לשנות" עבור פעולות עריכה)
1 = נמצאו בעיות (לבדיקות validate)
2 = שגיאה (קלט שגוי / IO / חריגה לא מטופלת)
תלויות:
pip install gematriapy pyluach beautifulsoup4
"""
from __future__ import annotations
import argparse
import json
import re
import sys
import unicodedata
from pathlib import Path
# ----------------------------------------------------------------------------
# תלויות אופציונליות - מייבא בעצלתיים כדי שכל פקודה תוכל לרוץ גם אם חבילה
# ספציפית לא הותקנה (למשל validate-tags שאינה צריכה gematriapy).
# ----------------------------------------------------------------------------
def _require(modname: str, install_name: str | None = None):
try:
return __import__(modname)
except ImportError as exc:
pkg = install_name or modname
sys.stderr.write(
f"שגיאה: חסרה החבילה '{pkg}'. התקן: pip install {pkg}\n"
f"(פרטים: {exc})\n"
)
sys.exit(2)
# ----------------------------------------------------------------------------
# תוצאת פקודה - אובייקט אחיד שמומר ל-JSON או לטקסט.
# ----------------------------------------------------------------------------
class Result(dict):
@classmethod
def ok(cls, command: str, file: str, **extra):
return cls(command=command, file=file, status="success", **extra)
@classmethod
def no_change(cls, command: str, file: str, **extra):
return cls(command=command, file=file, status="no-changes", **extra)
@classmethod
def issues(cls, command: str, file: str, **extra):
return cls(command=command, file=file, status="issues-found", **extra)
@classmethod
def error(cls, command: str, file: str, message: str, **extra):
return cls(command=command, file=file, status="error", message=message,
**extra)
def emit(result: Result, as_json: bool) -> int:
if as_json:
print(json.dumps(result, ensure_ascii=False, indent=2))
else:
# פלט קריא לאדם ל-stderr (כך שב-CI יוכלו לבלוע stdout בלי לאבד מידע)
status = result.get("status")
msg = result.get("message", "")
line = f"[{result['command']}] {result['file']} :: {status}"
if msg:
line += f" - {msg}"
if "changes" in result:
line += f" (changes: {result['changes']})"
sys.stderr.write(line + "\n")
# פירוט בעיות
for key in ("unmatched_regex", "unmatched_tags", "missing_levels",
"opening_without_closing", "closing_without_opening",
"heading_errors"):
if result.get(key):
sys.stderr.write(f" -- {key} ({len(result[key])}):\n")
for item in result[key][:50]:
sys.stderr.write(f" {item}\n")
if len(result[key]) > 50:
sys.stderr.write(f" ... ועוד {len(result[key]) - 50}\n")
if result["status"] == "error":
return 2
if result["status"] == "issues-found":
return 1
return 0
def _read_text(path: Path) -> str:
return path.read_text(encoding="utf-8")
def _write_text(path: Path, text: str) -> None:
path.write_text(text, encoding="utf-8")
def _validate_txt(path: Path) -> str | None:
if not path.exists():
return f"הקובץ לא נמצא: {path}"
if path.suffix.lower() != ".txt":
return "סוג הקובץ אינו נתמך - נדרש קובץ .txt"
return None
# ============================================================================
# Script 1: create-headers (CreateHeadersOtZria)
# ============================================================================
# קבועים שמשותפים בין סקריפט 1 ל-2
_REMOVE_TAGS_BASE = ["<b>", "</b>", "<big>", "</big>", "<i>", "</i>",
"</small>", "</small>", "<span>", "</span>",
"<br>", "</br>", "<p>", "</p>"]
_REMOVE_PUNCT = [":", ",", ";", "[", "]", "(", ")", "{", "}", ".", "‚",
'"', "'", "״", "”", "’", "׳", "‘", "„", "`", "´", "“",
"❝", "❞", "ˮ", "″", "ʺ", "ˈ", "´", "ʹ", "′", "ʾ", "ʽ"]
_AA = ["ק", "ר", "ש", "ת", "תק", "תר", "תש", "תת", "תתק",
"יה", "יו", "קיה", "קיו", "ריה", "ריו", "שיה", "שיו",
"תיה", "תיו", "תקיה", "תקיו", "תריה", "תריו",
"תשיה", "תשיו", "תתיה", "תתיו", "תתקיה", "תתקיו"]
_BB = ["ם", "ן", "ץ", "ף", "ך"]
_CC = ["ראשון", "שני", "שלישי", "רביעי", "חמישי", "שישי", "ששי",
"שביעי", "שמיני", "תשיעי", "עשירי", "יוד", "למד", "נון",
"דש", "חי", "טל", "שדמ", "ער", "שדם", "תשדם", "תשדמ",
"ערב", "ערה", "עדר", "רחצ"]
def _strip_html_tags(text: str, ignore: list[str] | None = None) -> str:
tags = list(_REMOVE_TAGS_BASE) + _REMOVE_PUNCT
if ignore is not None:
tags = ignore
for tag in tags:
text = text.replace(tag, "")
return text
def _strip_strict(text: str) -> str:
"""ניקוי מחמיר - מסיר תגים ופיסוק (כמו strip_html_tags במקור)."""
out = text
for tag in _REMOVE_TAGS_BASE + _REMOVE_PUNCT:
out = out.replace(tag, "")
return out
def _is_ot(text: str, end: int) -> bool:
"""החזר True אם הטקסט הוא גימטריה / סופית / ספיריאלי תקין (כפי שבמקור)."""
gematriapy = _require("gematriapy")
pyluach = _require("pyluach")
from pyluach import gematria # noqa: F401 - חלק מהאימות
cleaned = _strip_strict(text)
extras = []
for i in _AA:
for sof in _BB:
extras.append(i + sof)
candidates = [
gematria._num_to_str(i, thousands=False, withgershayim=False)
for i in range(1, end)
] + _BB + _CC + extras + _AA
return cleaned in candidates
def cmd_create_headers(args) -> Result:
path = Path(args.file)
err = _validate_txt(path)
if err:
return Result.error("create-headers", str(path), err)
finde_cleaned = _strip_strict(args.word).strip()
end = args.max_num + 1
level = args.level
content = _read_text(path).splitlines()
all_lines = content[0:2]
found = False
count = 0
i = 2
while i < len(content):
line = content[i]
words = line.split()
try:
if (len(words) >= 2
and _strip_strict(words[0]) == finde_cleaned
and _is_ot(words[1], end)):
found = True
count += 1
heading = (f"<h{level}>{_strip_strict(words[0])} "
f"{_strip_strict(words[1])}</h{level}>")
all_lines.append(heading)
if words[2:]:
all_lines.append(" ".join(words[2:]))
elif (len(words) == 1
and _strip_strict(words[0]) == finde_cleaned
and i + 1 < len(content)):
next_line = content[i + 1]
next_words = next_line.split()
if next_words and _is_ot(next_words[0], end):
found = True
count += 1
heading = (f"<h{level}>{_strip_strict(words[0])} "
f"{_strip_strict(next_words[0])}</h{level}>")
all_lines.append(heading)
if next_words[1:]:
all_lines.append(" ".join(next_words[1:]))
i += 1
else:
all_lines.append(line)
else:
all_lines.append(line)
except IndexError:
all_lines.append(line)
i += 1
if not found:
return Result.no_change("create-headers", str(path), changes=0,
message="לא נמצאו כותרות להוסיף")
_write_text(path, "\n".join(all_lines))
# מקביל לפעולה האוטומטית של ה-GUI: כשנבחרה המילה "דף", להשלים עם
# החלפת מספר עמוד (סקריפט 3)
page_changes = 0
if args.word == "דף":
page_changes = _add_page_number(path, "נקודה ונקודותיים")
return Result.ok("create-headers", str(path), changes=count,
auto_page_number_changes=page_changes,
word=args.word, level=level)
# ============================================================================
# Script 2: single-letter (CreateSingleLetterHeaders)
# ============================================================================
def cmd_single_letter(args) -> Result:
path = Path(args.file)
err = _validate_txt(path)
if err:
return Result.error("single-letter", str(path), err)
end = args.max_num + 1
level = args.level
start = args.start
finde = args.suffix
extra_remove = args.remove.split() if args.remove else []
remove = list(_REMOVE_TAGS_BASE) + extra_remove
ignore = args.ignore.split() if args.ignore else []
if args.bold:
finde = (finde or "") + "</b>"
start = "<b>" + (start or "")
else:
ignore += ["<b>", "</b>"]
content = _read_text(path).splitlines()
all_lines = content[0:1]
count = 0
for line in content[1:]:
words = line.split()
try:
first = words[0]
cleaned = _strip_html_tags(first, ignore)
if (cleaned.endswith(finde)
and _is_ot(first, end)
and cleaned.startswith(start)):
heading = f"<h{level}>{_strip_html_tags(first, remove)}</h{level}>"
all_lines.append(heading)
if words[1:]:
all_lines.append(" ".join(words[1:]))
count += 1
else:
all_lines.append(line)
except IndexError:
all_lines.append(line)
if count == 0:
return Result.no_change("single-letter", str(path), changes=0,
message="לא נמצא מה להחליף")
_write_text(path, "\n".join(all_lines))
return Result.ok("single-letter", str(path), changes=count, level=level)
# ============================================================================
# Script 3: page-number (AddPageNumberToHeading)
# ============================================================================
def _add_page_number(path: Path, replace_with: str) -> int:
"""מחזיר את מספר ההחלפות שבוצעו."""
content = path.read_text(encoding="utf-8").splitlines(keepends=True)
pattern_va_vb = (
r'(<[a-z]+>)?(ע["\']+?[א-ב]|עמוד [א-ב])'
r'[.,:()\[\]\'"״׳”’‘„`´“❝❞ˮ″ʺˈʹ′ʾʽ]?(</[a-z]+>)?\s?'
)
updated = []
changes = 0
i = 0
while i < len(content):
line = content[i]
m = re.match(r'<h([2-9])>(דף \S+)</h\1>', line)
if m:
level = m.group(1)
title = m.group(2)
if i + 1 < len(content):
next_line = content[i + 1].strip()
m2 = re.match(pattern_va_vb, next_line)
if m2:
changes += 1
if replace_with == "נקודה ונקודותיים":
if "א" in m2.group(2):
new = f'<h{level}>{title.rstrip(".")}.</h{level}>\n'
else:
new = f'<h{level}>{title.rstrip(".")}:</h{level}>\n'
else: # ע"א וע"ב
suf = 'ע"א' if "א" in m2.group(2) else 'ע"ב'
new = f'<h{level}>{title.rstrip(".")} {suf}</h{level}>\n'
updated.append(new)
rest = re.sub(pattern_va_vb, "", next_line, count=1).strip()
if rest:
updated.append(rest + "\n")
i += 2
continue
updated.append(line)
i += 1
if changes:
path.write_text("".join(updated), encoding="utf-8")
return changes
def cmd_page_number(args) -> Result:
path = Path(args.file)
err = _validate_txt(path)
if err:
return Result.error("page-number", str(path), err)
style_map = {
"dot-colon": "נקודה ונקודותיים",
"ayin": 'ע"א וע"ב',
}
replace_with = style_map[args.style]
changes = _add_page_number(path, replace_with)
if not changes:
return Result.no_change("page-number", str(path), changes=0)
return Result.ok("page-number", str(path), changes=changes,
style=args.style)
# ============================================================================
# Script 4: change-level (ChangeHeadingLevel)
# ============================================================================
def cmd_change_level(args) -> Result:
path = Path(args.file)
err = _validate_txt(path)
if err:
return Result.error("change-level", str(path), err)
cur = f"h{args.from_level}"
new = f"h{args.to_level}"
text = _read_text(path)
updated = re.sub(f"<{cur}>(.*?)</{cur}>",
f"<{new}>\\1</{new}>", text, flags=re.DOTALL)
if text == updated:
return Result.no_change("change-level", str(path), changes=0)
_write_text(path, updated)
# ספירת ההחלפות בפועל
changes = len(re.findall(f"<{cur}>.*?</{cur}>", text, flags=re.DOTALL))
return Result.ok("change-level", str(path), changes=changes,
from_level=args.from_level, to_level=args.to_level)
# ============================================================================
# Script 5: emphasize-first (EmphasizeAndPunctuate)
# ============================================================================
def cmd_emphasize_first(args) -> Result:
path = Path(args.file)
err = _validate_txt(path)
if err:
return Result.error("emphasize-first", str(path), err)
add_ending = args.punctuation # "dot" / "colon" / "none"
add_ending_map = {
"dot": "הוסף נקודה",
"colon": "הוסף נקודותיים",
"none": "ללא שינוי",
}
mode = add_ending_map[add_ending]
emphasize = not args.no_bold
lines = path.read_text(encoding="utf-8").splitlines(keepends=True)
changed = False
for i in range(len(lines)):
line = lines[i].rstrip()
words = line.split()
if (len(words) > 10
and not any(line.startswith(f'<h{n}>') for n in range(2, 10))):
if line.endswith(('.', ':')):
line = line.rstrip()
if mode != "ללא שינוי":
if line.endswith(','):
line = line.rstrip()
if mode == "הוסף נקודה":
lines[i] = line[:-1] + ".\n"
else:
lines[i] = line[:-1] + ":\n"
changed = True
elif (not line.endswith(('.', ':', '!', '?'))
and not any(line.endswith(t)
for t in ['</small>', '</big>', '</b>'])):
line = line.rstrip()
if mode == "הוסף נקודה":
lines[i] = line.rstrip() + ".\n"
else:
lines[i] = line.rstrip() + ":\n"
changed = True
if emphasize:
first = words[0]
if not any(t in first for t in
['<b>', '<small>', '<big>', '<h2>', '<h3>',
'<h4>', '<h5>', '<h6>']):
if not (first.startswith('<') and first.endswith('>')):
lines[i] = ('<b>' + first + '</b> '
+ ' '.join(words[1:]) + '\n')
changed = True
if not changed:
return Result.no_change("emphasize-first", str(path), changes=0)
path.write_text("".join(lines), encoding="utf-8")
return Result.ok("emphasize-first", str(path),
punctuation=add_ending, emphasize=emphasize)
# ============================================================================
# Script 6: page-b (CreatePageBHeaders)
# ============================================================================
def _build_tag_agnostic(word: str, optional_end_chars: str = "['\"’]*") -> str:
ANY_TAGS_SPACES = r'(?:<[^>]+>\s*)*'
p = ''
for ch in word:
p += ANY_TAGS_SPACES + re.escape(ch)
p += ANY_TAGS_SPACES
if optional_end_chars:
p += optional_end_chars + ANY_TAGS_SPACES
return p
def _strip_and_replace_page_b(text: str, level: int, counter: list[int]) -> str:
ANY_TAGS_SPACES = r'(?:<[^>]+>\s*)*'
NON_WORD = r'(?:[^\w<>]|$)'
pattern = r"^\s*" + ANY_TAGS_SPACES
shem = _build_tag_agnostic('שם', optional_end_chars='')
pattern += r"(?P<shem>" + shem + r"\s*)?"
gmarah_variants = ['גמרא', 'בגמרא', "גמ'", "בגמ'"]
gmarah_patterns = [_build_tag_agnostic(w, optional_end_chars='')
for w in gmarah_variants]
pattern += r"(?:(?P<gmarah>" + '|'.join(gmarah_patterns) + r")\s*)?"
ab_variants = ['עמוד ב', 'ע"ב', "ע''ב", "ע'ב"]
ab_patterns = [r"(?<!\w)" + _build_tag_agnostic(w) + r"(?!\w)"
for w in ab_variants]
pattern += r"(?P<ab>" + '|'.join(ab_patterns) + r")"
pattern += NON_WORD
pattern += r"(?P<rest>.*)"
rgx = re.compile(pattern, re.IGNORECASE | re.UNICODE)
def repl(m):
header = f"<h{level}>עמוד ב</h{level}>"
rest = m.group('rest').lstrip()
gmarah = m.group('gmarah')
if gmarah:
gmarah = re.sub(ANY_TAGS_SPACES, '', gmarah).strip()
counter[0] += 1
if gmarah:
return (f"{header}\n{gmarah} {rest}\n" if rest
else f"{header}\n{gmarah}\n")
return f"{header}\n{rest}\n" if rest else f"{header}\n"
if re.search(r"<h\d>.*?</h\d>", text, re.IGNORECASE):
return text
new = rgx.sub(repl, text)
return re.sub(r'\n\s*\n', '\n', new)
def cmd_page_b(args) -> Result:
path = Path(args.file)
err = _validate_txt(path)
if err:
return Result.error("page-b", str(path), err)
lines = path.read_text(encoding="utf-8").splitlines(keepends=True)
counter = [0]
new_lines = [_strip_and_replace_page_b(ln, args.level, counter)
for ln in lines]
if not counter[0]:
return Result.no_change("page-b", str(path), changes=0)
path.write_text("".join(new_lines), encoding="utf-8")
return Result.ok("page-b", str(path), changes=counter[0], level=args.level)
# ============================================================================
# Script 7: replace-page-b (ReplacePageBHeaders)
# ============================================================================
def cmd_replace_page_b(args) -> Result:
path = Path(args.file)
err = _validate_txt(path)
if err:
return Result.error("replace-page-b", str(path), err)
replace_type = "נקודותיים" if args.style == "colon" else 'ע"ב'
text = path.read_text(encoding="utf-8")
state = {"prev_title": "", "prev_level": "", "count": 0}
def repl(m):
level = m.group(1)
title = m.group(2)
if re.match(r"דף \S+\.?", title):
state["prev_title"] = title.strip()
state["prev_level"] = level
return m.group(0)
if title == "עמוד ב":
state["count"] += 1
if replace_type == "נקודותיים":
return (f'<h{state["prev_level"]}>'
f'{state["prev_title"].rstrip(".")}:'
f'</h{state["prev_level"]}>')
mod = re.sub(r'( ע"א| עמוד א)$', '', state["prev_title"])
return (f'<h{state["prev_level"]}>'
f'{mod.rstrip(".")} ע"ב</h{state["prev_level"]}>')
return m.group(0)
new = re.sub(r'<h([1-9])>(.*?)</h\1>', repl, text)
if not state["count"]:
return Result.no_change("replace-page-b", str(path), changes=0)
path.write_text(new, encoding="utf-8")
return Result.ok("replace-page-b", str(path), changes=state["count"],
style=args.style)
# ============================================================================
# Script 8 + 9: validate-headings (CheckHeadingErrorsOriginal / Custom)
# ============================================================================
def _validate_headings_logic(html: str, re_start: str, re_end: str,
gershayim: bool, shas_mode: bool):
"""מחזיר (unmatched_regex, unmatched_tags, missing_levels)."""
_require("bs4", "beautifulsoup4")
from bs4 import BeautifulSoup
gematriapy = _require("gematriapy")
soup = BeautifulSoup(html, "html.parser")
if re_start and re_end:
pat = re.compile(
f"^[{re.escape(re_start)}]*[א-ת]([א-ת \\-]*[א-ת])?"
f"[{re.escape(re_end)}]*$")
elif re_start:
pat = re.compile(
f"^[{re.escape(re_start)}]*[א-ת]([א-ת \\-]*[א-ת])?$")
elif re_end:
pat = re.compile(
f"^[א-ת]([א-ת \\-]*[א-ת])?[{re.escape(re_end)}]*$")
else:
pat = re.compile(r"^[א-ת]([א-ת \-]*[א-ת])?$")
unmatched_regex: list[str] = []
unmatched_tags: list[str] = []
missing_levels: list[int] = []
for i in range(2, 7):
tags = soup.find_all(f"h{i}")
if not tags:
missing_levels.append(i)
continue
# מצב רגיל - מתפקיד כל הבדיקות זוג-זוג רציף.
# מצב ש"ס - מדלג על כותרת אחת בכל פעם (כי "עמוד ב" נחשב כפול).
step_window = 2 if shas_mode else 1
# סריקה זוגית
for index in range(len(tags) - step_window):
current_tag = tags[index].string or ""
next_tag = tags[index + step_window].string or ""
if not current_tag or not next_tag:
continue
cur_parts = current_tag.split()
nxt_parts = next_tag.split()
cur_h = cur_parts[1] if len(cur_parts) > 1 else current_tag
nxt_h = nxt_parts[1] if len(nxt_parts) > 1 else next_tag
if not re.match(pat, current_tag):
if not (gershayim
and ("'" in current_tag or '"' in current_tag)):
unmatched_regex.append(current_tag)
if "'" in cur_h or '"' in cur_h:
unmatched_tags.append(cur_h)
try:
if (gematriapy.to_number(cur_h) + 1
!= gematriapy.to_number(nxt_h)):
unmatched_tags.append(
f"כותרת נוכחית - {current_tag} || "
f"כותרת הבאה - {next_tag}")
except Exception:
unmatched_tags.append(
f"כותרת נוכחית - {current_tag} || "
f"כותרת הבאה - {next_tag}")
# תגים אחרונים
if shas_mode:
if len(tags) >= 2:
last_tags = (tags[-2].string or "", tags[-1].string or "")
elif len(tags) == 1:
last_tags = ("", tags[-1].string or "")
else:
last_tags = ("", "")
for last in last_tags:
if last and not re.match(pat, last):
if not (gershayim and ("'" in last or '"' in last)):
unmatched_regex.append(last)
last_parts = last_tags[-1].split()
last_h = last_parts[1] if len(last_parts) > 1 else last_tags[-1]
if "'" in last_h or '"' in last_h:
unmatched_tags.append(last_h)
else:
last = tags[-1].string or ""
if last and not re.match(pat, last):
if not (gershayim and ("'" in last or '"' in last)):
unmatched_regex.append(last)
last_parts = last.split()
last_h = last_parts[1] if len(last_parts) > 1 else last
if "'" in last_h or '"' in last_h:
unmatched_tags.append(last_h)
return unmatched_regex, unmatched_tags, missing_levels
def cmd_validate_headings(args) -> Result:
path = Path(args.file)
err = _validate_txt(path)
if err:
return Result.error("validate-headings", str(path), err)
html = _read_text(path)
unmatched_regex, unmatched_tags, missing_levels = _validate_headings_logic(
html, args.start_chars, args.end_chars, args.allow_gershayim, args.shas)
has_issues = bool(unmatched_regex or unmatched_tags)
payload = dict(
unmatched_regex=unmatched_regex,
unmatched_tags=unmatched_tags,
missing_levels=missing_levels,
shas=args.shas,
)
if has_issues:
return Result.issues("validate-headings", str(path), **payload)
return Result.ok("validate-headings", str(path),
message="לא נמצאו שגיאות בכותרות", **payload)
# ============================================================================
# Script 8 (חלק שני): validate-tags - בדיקת תגים פותחים/סוגרים והכותרות
# ============================================================================
def cmd_validate_tags(args) -> Result:
path = Path(args.file)
err = _validate_txt(path)
if err:
return Result.error("validate-tags", str(path), err)
LRM = ''
lines = path.read_text(encoding="utf-8").splitlines()
opening_without_closing: list[str] = []
closing_without_opening: list[str] = []
heading_errors: list[str] = []
for line_no, line in enumerate(lines, start=1):
all_tags = []
for m in re.finditer(r'<(/?\w+)>', line):
tag = m.group(1)
pos = m.start()
if tag.startswith('/'):
all_tags.append(('close', tag[1:], pos))
else:
all_tags.append(('open', tag, pos))
all_tags.sort(key=lambda x: x[2])
stack = []
for ttype, tname, _ in all_tags:
if ttype == 'open':
stack.append(tname)
else:
found = False
for j in range(len(stack) - 1, -1, -1):
if stack[j] == tname:
stack.pop(j)
found = True
break
if not found:
closing_without_opening.append(
f"שורה {line_no}: {LRM}</{tname}>{LRM} "
f"|| {LRM}{line.strip()}{LRM}")
for tag in stack:
opening_without_closing.append(
f"שורה {line_no}: {LRM}<{tag}>{LRM} "
f"|| {LRM}{line.strip()}{LRM}")
for tag in ("h2", "h3", "h4", "h5", "h6"):
hp = rf'<{tag}>.*?</{tag}>'
hm = re.search(hp, line)
if hm:
start, end = hm.span()
before = line[:start].strip()
after = line[end:].strip()
if before or after:
heading_errors.append(
f"שורה {line_no}: {LRM}{line.strip()}{LRM}")
has_issues = bool(opening_without_closing or closing_without_opening
or heading_errors)
payload = dict(
opening_without_closing=opening_without_closing,
closing_without_opening=closing_without_opening,
heading_errors=heading_errors,
)
if has_issues:
return Result.issues("validate-tags", str(path), **payload)
return Result.ok("validate-tags", str(path),
message="לא נמצאו שגיאות בתגים", **payload)
# ============================================================================
# Script 11: clean-text (TextCleanerApp)
# ============================================================================
CLEAN_OPTIONS = [
"remove_empty_lines",
"remove_double_spaces",
"remove_spaces_before",
"remove_spaces_after",
"remove_spaces_around_newlines",
"replace_double_quotes",
"normalize_quotes",
]
def cmd_clean_text(args) -> Result:
path = Path(args.file)
err = _validate_txt(path)
if err:
return Result.error("clean-text", str(path), err)
enabled = set(CLEAN_OPTIONS)
if args.only:
enabled = set(args.only)
if args.disable:
enabled -= set(args.disable)
invalid = enabled - set(CLEAN_OPTIONS)
if invalid:
return Result.error("clean-text", str(path),
f"אופציות לא תקינות: {sorted(invalid)}")
text = _read_text(path)
original = text
if "remove_empty_lines" in enabled:
text = re.sub(r'\n\s*\n', '\n', text)
if "remove_double_spaces" in enabled:
text = re.sub(r' +', ' ', text)
if "remove_spaces_before" in enabled:
text = re.sub(r'[ \t]+([\)\],.:])', r'\1', text)
if "remove_spaces_after" in enabled:
text = re.sub(r'(\s|^)([\[\(])(\s+)', r'\1\2', text, flags=re.MULTILINE)
if "remove_spaces_around_newlines" in enabled:
text = re.sub(r'\s*\n\s*', '\n', text)
if "replace_double_quotes" in enabled:
text = (text.replace("''", '"').replace("``", '"')
.replace("´´", '"').replace("׳׳", '"')
.replace("’’", '"').replace("‘‘", '"'))
if "normalize_quotes" in enabled:
text = (text.replace("“", '"').replace("”", '"')
.replace("‘", "'").replace("’", "'")
.replace("„", '"').replace("״", '"')
.replace("׳", "'").replace("`", "'").replace("´", "'"))
if args.normalize_unicode:
text = unicodedata.normalize("NFC", text)
text = text.rstrip()
if text == original:
return Result.no_change("clean-text", str(path), changes=0)
_write_text(path, text)
return Result.ok("clean-text", str(path),
enabled=sorted(enabled),
normalized_unicode=args.normalize_unicode)
# ============================================================================
# argparse
# ============================================================================
def build_parser() -> argparse.ArgumentParser:
p = argparse.ArgumentParser(
prog="edit-dicta",
description=("CLI לסקריפטי EditingDictaBooks - ללא Qt, מתאים ל-CI / "
"agents. כל פקודה מחזירה קוד יציאה (0=הצלחה, 1=נמצאו "
"בעיות, 2=שגיאה) ובאופציה --json מדפיסה תוצאה ל-stdout. "
"סקריפטי GUI 10 (OCR) ו-12 (סנכרון) אינם נכללים - "
"תלויים ב-Windows / רשת."),
formatter_class=argparse.RawDescriptionHelpFormatter,
)
p.add_argument("--json", action="store_true",
help="הדפס פלט JSON מובנה ל-stdout")
sub = p.add_subparsers(dest="command", required=True)
# 1
sp = sub.add_parser("create-headers",
help="יצירת כותרות לפי מילה ומספר גימטריה")
sp.add_argument("--file", required=True)
sp.add_argument("--word", required=True,
help="המילה הפותחת כותרת (פרק/סימן/דף וכו')")
sp.add_argument("--level", type=int, default=2, choices=range(2, 7))
sp.add_argument("--max-num", type=int, default=999,
help="מספר סימן/פרק מקסימלי (ברירת מחדל: 999)")
sp.set_defaults(func=cmd_create_headers)
# 2
sp = sub.add_parser("single-letter",
help="כותרות לאותיות בודדות (גימטריה)")
sp.add_argument("--file", required=True)
sp.add_argument("--suffix", default="",
help="תו/ים בסוף האות (למשל '.', '),', וכו')")
sp.add_argument("--start", default="", help="תו פותח אופציונלי, '(' או '['")
sp.add_argument("--level", type=int, default=3, choices=range(2, 7))
sp.add_argument("--max-num", type=int, default=999)
sp.add_argument("--bold", action="store_true", default=True,
help="חפש רק אותיות מודגשות (ברירת מחדל)")
sp.add_argument("--no-bold", dest="bold", action="store_false")
sp.add_argument("--remove",
default=', : " \' . ( ) [ ] { }',
help="תווים נוספים להסרה מהכותרת שתיווצר")
sp.add_argument("--ignore",
default='<big> </big> <i> </i> </small> </small> '
'<span> </span> <br> </br> <p> </p>',
help="תגים שיתעלמו מהם בעת ההשוואה")
sp.set_defaults(func=cmd_single_letter)
# 3
sp = sub.add_parser("page-number",
help="הוספת מספר עמוד לכותרת 'דף'")
sp.add_argument("--file", required=True)
sp.add_argument("--style", choices=["dot-colon", "ayin"],
default="dot-colon",
help="dot-colon = 'דף ב.' / 'דף ב:' ; "
"ayin = 'דף ב ע\"א' / 'דף ב ע\"ב'")
sp.set_defaults(func=cmd_page_number)
# 4
sp = sub.add_parser("change-level", help="שינוי רמת כותרת")
sp.add_argument("--file", required=True)
sp.add_argument("--from-level", required=True, type=int,
dest="from_level", choices=range(1, 10))
sp.add_argument("--to-level", required=True, type=int,
dest="to_level", choices=range(1, 10))
sp.set_defaults(func=cmd_change_level)
# 5
sp = sub.add_parser("emphasize-first",
help="הדגשת מילה ראשונה והוספת פיסוק בסוף קטע")
sp.add_argument("--file", required=True)
sp.add_argument("--punctuation", choices=["dot", "colon", "none"],
default="colon")
sp.add_argument("--no-bold", action="store_true",
help="אל תוסיף <b> למילה הראשונה")
sp.set_defaults(func=cmd_emphasize_first)
# 6
sp = sub.add_parser("page-b",
help="יצירת כותרת 'עמוד ב' (סקריפט 6)")
sp.add_argument("--file", required=True)
sp.add_argument("--level", type=int, default=3, choices=range(2, 7))
sp.set_defaults(func=cmd_page_b)
# 7
sp = sub.add_parser("replace-page-b",
help="החלפת כותרות 'עמוד ב' בנקודותיים / ע\"ב")
sp.add_argument("--file", required=True)
sp.add_argument("--style", choices=["colon", "ayin"], default="colon")
sp.set_defaults(func=cmd_replace_page_b)
# 8
sp = sub.add_parser("validate-tags",
help="בדיקת תגים פותחים/סוגרים וכותרות עם טקסט נילווה")
sp.add_argument("--file", required=True)
sp.set_defaults(func=cmd_validate_tags)
# 8/9
sp = sub.add_parser("validate-headings",
help="בדיקת תקינות כותרות h2..h6")
sp.add_argument("--file", required=True)
sp.add_argument("--shas", action="store_true",
help="מצב ש\"ס - מדלג בכל פעם על כותרת אחת (עמוד ב כפול)")
sp.add_argument("--start-chars", default="",
help="תווים מותרים בתחילת כותרת")
sp.add_argument("--end-chars", default="",
help="תווים מותרים בסוף כותרת")
sp.add_argument("--allow-gershayim", action="store_true",
help="הגדר גרש/ים כתקינים בכותרות")
sp.set_defaults(func=cmd_validate_headings)
# 11
sp = sub.add_parser("clean-text", help="ניקוי טקסט (TextCleaner)")
sp.add_argument("--file", required=True)
sp.add_argument("--only", nargs="*", choices=CLEAN_OPTIONS,
help=f"הפעל רק את האופציות הללו ({', '.join(CLEAN_OPTIONS)})")
sp.add_argument("--disable", nargs="*", choices=CLEAN_OPTIONS,
help="כבה אופציות מסוימות")
sp.add_argument("--normalize-unicode", action="store_true",
help="הפעל unicodedata.normalize('NFC', ...)")
sp.set_defaults(func=cmd_clean_text)
return p
def main(argv: list[str] | None = None) -> int:
parser = build_parser()
args = parser.parse_args(argv)
try:
result = args.func(args)
except SystemExit:
raise
except Exception as exc:
result = Result.error(args.command, getattr(args, "file", "-"),
f"חריגה: {exc!r}")
return emit(result, as_json=args.json)
if __name__ == "__main__":
sys.exit(main())