-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
2417 lines (2226 loc) · 237 KB
/
Copy pathapp.py
File metadata and controls
2417 lines (2226 loc) · 237 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
"""
Manuscript Workbench — local Python edition.
Run:
pip install -r requirements.txt
python app.py
Then open http://127.0.0.1:8765
"""
from __future__ import annotations
import base64
import datetime as _dt
import errno
import html as html_std
import ipaddress
import io
import json
import os
import re
import sys
import tempfile
import traceback
import urllib.parse
from html.parser import HTMLParser
from http import HTTPStatus
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from typing import Any, Dict, Iterable, List, Optional, Tuple
try:
import requests
except Exception: # pragma: no cover
requests = None
try:
import markdown as markdown_lib
except Exception: # pragma: no cover
markdown_lib = None
try:
from lxml import html as lxml_html
except Exception: # pragma: no cover
lxml_html = None
try:
import trafilatura
except Exception: # pragma: no cover
trafilatura = None
try:
from docx import Document
from docx.enum.style import WD_STYLE_TYPE
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.shared import Pt
except Exception: # pragma: no cover
Document = None
WD_STYLE_TYPE = None
WD_ALIGN_PARAGRAPH = None
Pt = None
APP_HOST = "127.0.0.1"
APP_PORT = int(os.environ.get("MANUSCRIPT_WORKBENCH_PORT") or os.environ.get("VELLUM_PREP_PORT", "8765"))
APP_NAME = "Manuscript Workbench — Python"
APP_VERSION = "1.2"
SETTINGS_PATH = Path(__file__).with_name("manuscript_workbench_settings.json")
MAX_JSON_BYTES = 80 * 1024 * 1024
MAX_URL_IMPORT_BYTES = 12 * 1024 * 1024
PARAGRAPH_STYLE_MAP = {
"chapter": "Heading 1",
"part": "Heading 1",
"subhead1": "Heading 2",
"subhead2": "Heading 3",
"subhead3": "Heading 4",
"subhead4": "Heading 5",
"subhead5": "Heading 6",
"subtitle": "Manuscript Element Subtitle",
"element-author": "Manuscript Element Author",
"hidden-heading": "Manuscript Hidden Heading",
"quote": "Manuscript Block Quote",
"verse": "Manuscript Verse",
"attribution": "Manuscript Attribution",
"centered": "Manuscript Centered Text",
"flush-left": "Manuscript Flush Left",
"written-note": "Manuscript Written Note",
"text-conversation": "Manuscript Text Conversation",
"caption": "Caption",
"inline-image": "Manuscript Inline Image",
"ornament": "Normal",
"scene": "Normal",
}
STYLE_TO_MARKER = {
"Heading 1": "chapter",
"Heading 2": "subhead1",
"Heading 3": "subhead2",
"Heading 4": "subhead3",
"Heading 5": "subhead4",
"Heading 6": "subhead5",
"Quote": "quote",
"Intense Quote": "quote",
"Caption": "caption",
"Manuscript Element Subtitle": "subtitle",
"Manuscript Element Author": "element-author",
"Manuscript Hidden Heading": "hidden-heading",
"Manuscript Block Quote": "quote",
"Manuscript Verse": "verse",
"Manuscript Attribution": "attribution",
"Manuscript Centered Text": "centered",
"Manuscript Flush Left": "flush-left",
"Manuscript Written Note": "written-note",
"Manuscript Text Conversation": "text-conversation",
"Manuscript Inline Image": "inline-image",
"Vellum Element Subtitle": "subtitle",
"Vellum Element Author": "element-author",
"Vellum Hidden Heading": "hidden-heading",
"Vellum Block Quote": "quote",
"Vellum Verse": "verse",
"Vellum Attribution": "attribution",
"Vellum Centered Text": "centered",
"Vellum Flush Left": "flush-left",
"Vellum Written Note": "written-note",
"Vellum Text Conversation": "text-conversation",
"Vellum Inline Image": "inline-image",
}
EXPORT_PARAGRAPH_STYLES = [
"Manuscript Element Subtitle",
"Manuscript Element Author",
"Manuscript Hidden Heading",
"Manuscript Block Quote",
"Manuscript Verse",
"Manuscript Attribution",
"Manuscript Centered Text",
"Manuscript Flush Left",
"Manuscript Written Note",
"Manuscript Text Conversation",
"Manuscript Inline Image",
]
EXPORT_CHARACTER_STYLES = [
"Manuscript Small Caps",
"Manuscript Monospace",
"Manuscript Sans Serif",
]
CHAPTER_CANDIDATE_RE = re.compile(
r"^\s*(?:(?:chapter|hoofdstuk|chapitre|cap[ií]tulo)\s+([0-9ivxlcdm]+|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|nineteen|twenty|een|twee|drie|vier|vijf|zes|zeven|acht|negen|tien)\b.*|(?:part|deel)\s+([0-9ivxlcdm]+|one|two|three|four|five|six|seven|eight|nine|ten|een|twee|drie|vier|vijf|zes|zeven|acht|negen|tien)\b.*|prologue|epilogue|acknowledg(?:e)?ments|about the author|copyright|dedication|preface|introduction|afterword|also by|inhoud|voorwoord|nawoord|dankwoord)\s*$",
re.I,
)
PAGE_NUMBER_RE = re.compile(
r"^\s*(?:[-—–]\s*)?(?:p\.?\s*|page\s+|pagina\s+)?(?:\d{1,4}|[ivxlcdm]{2,})(?:\s*(?:/|of|van)\s*\d{1,4})?(?:\s*[-—–])?\s*$",
re.I,
)
ROMAN_VALUES = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}
WORD_NUMS = {
"one": 1, "two": 2, "three": 3, "four": 4, "five": 5, "six": 6, "seven": 7,
"eight": 8, "nine": 9, "ten": 10, "eleven": 11, "twelve": 12, "thirteen": 13,
"fourteen": 14, "fifteen": 15, "sixteen": 16, "seventeen": 17, "eighteen": 18,
"nineteen": 19, "twenty": 20,
"een": 1, "twee": 2, "drie": 3, "vier": 4, "vijf": 5, "zes": 6, "zeven": 7,
"acht": 8, "negen": 9, "tien": 10,
}
def json_response(handler: BaseHTTPRequestHandler, payload: Any, status: int = 200) -> None:
body = json.dumps(payload, ensure_ascii=False, indent=None).encode("utf-8")
handler.send_response(status)
handler.send_header("Content-Type", "application/json; charset=utf-8")
handler.send_header("Content-Length", str(len(body)))
handler.end_headers()
handler.wfile.write(body)
def text_response(handler: BaseHTTPRequestHandler, text: str, status: int = 200, content_type: str = "text/plain; charset=utf-8") -> None:
body = text.encode("utf-8")
handler.send_response(status)
handler.send_header("Content-Type", content_type)
handler.send_header("Content-Length", str(len(body)))
handler.end_headers()
handler.wfile.write(body)
def read_app_settings() -> Dict[str, Any]:
try:
if SETTINGS_PATH.exists():
data = json.loads(SETTINGS_PATH.read_text(encoding="utf-8"))
return data if isinstance(data, dict) else {}
except Exception:
return {}
return {}
def write_app_settings(settings: Dict[str, Any]) -> None:
payload = {
"version": APP_VERSION,
"savedAt": _dt.datetime.now(_dt.timezone.utc).isoformat(),
"settings": settings if isinstance(settings, dict) else {},
}
tmp = SETTINGS_PATH.with_suffix(".json.tmp")
tmp.write_text(json.dumps(payload, ensure_ascii=False, indent=2, sort_keys=True), encoding="utf-8")
tmp.replace(SETTINGS_PATH)
def normalize_line_endings(text: str) -> Tuple[str, List[str]]:
notes: List[str] = []
if text.startswith("\ufeff"):
text = text[1:]
notes.append("BOM removed")
if "\r\n" in text:
text = text.replace("\r\n", "\n")
notes.append("CRLF → LF")
if "\r" in text:
text = text.replace("\r", "\n")
notes.append("CR → LF")
return text, notes
def decode_text_bytes(data: bytes) -> Tuple[str, List[str]]:
notes: List[str] = []
if data.startswith(b"\xff\xfe"):
text = data[2:].decode("utf-16-le", errors="replace")
notes.append("Read as UTF-16 LE")
elif data.startswith(b"\xfe\xff"):
text = data[2:].decode("utf-16-be", errors="replace")
notes.append("Read as UTF-16 BE")
elif data.startswith(b"\xef\xbb\xbf"):
text = data[3:].decode("utf-8", errors="replace")
notes.append("Read as UTF-8 BOM")
else:
text = data.decode("utf-8", errors="replace")
# Heuristic: a UTF-16 file without BOM usually contains many NUL bytes after UTF-8 decode.
if text.count("\x00") > max(4, len(text) // 50):
even_nuls = data[0::2].count(0)
odd_nuls = data[1::2].count(0)
try:
if odd_nuls > even_nuls:
text = data.decode("utf-16-le", errors="replace")
notes.append("Read as UTF-16 LE by NUL-byte heuristic")
else:
text = data.decode("utf-16-be", errors="replace")
notes.append("Read as UTF-16 BE by NUL-byte heuristic")
except Exception:
pass
elif "\ufffd" in text:
alt = data.decode("windows-1252", errors="replace")
if alt.count("\ufffd") < text.count("\ufffd"):
text = alt
notes.append("Read as Windows-1252")
else:
notes.append("Read as UTF-8 with replacement characters")
else:
notes.append("Read as UTF-8")
text, norm_notes = normalize_line_endings(text)
notes.extend(norm_notes)
return text, notes
def rtf_to_text(rtf: str) -> str:
"""Small, dependency-free RTF-to-text extractor. Good enough for manuscripts.
It handles common paragraph, tab, escaped hex, and unicode tokens. It intentionally
ignores most formatting and many RTF destinations.
"""
ignorable_destinations = {
"fonttbl", "colortbl", "stylesheet", "info", "pict", "object", "header", "footer",
"generator", "themedata", "datastore", "xmlnstbl", "listtable", "listoverridetable",
"revtbl", "rsidtbl", "latentstyles", "filetbl", "aftnsep", "aftnsepc", "aftncn",
}
stack: List[Tuple[bool, int]] = []
out: List[str] = []
i = 0
n = len(rtf)
skip_group = False
ucskip = 1
pending_ignorable = False
def emit(s: str) -> None:
if not skip_group:
out.append(s)
while i < n:
c = rtf[i]
if c == "{":
stack.append((skip_group, ucskip))
pending_ignorable = False
i += 1
elif c == "}":
if stack:
skip_group, ucskip = stack.pop()
pending_ignorable = False
i += 1
elif c == "\\":
i += 1
if i >= n:
break
c2 = rtf[i]
if c2 in "{}\\":
emit(c2)
i += 1
elif c2 == "~":
emit(" ")
i += 1
elif c2 == "-":
emit("-")
i += 1
elif c2 == "_":
emit("-")
i += 1
elif c2 == "*":
pending_ignorable = True
i += 1
elif c2 == "'" and i + 2 < n:
hx = rtf[i + 1:i + 3]
try:
emit(bytes.fromhex(hx).decode("windows-1252", errors="replace"))
except Exception:
pass
i += 3
elif c2.isalpha():
start = i
while i < n and rtf[i].isalpha():
i += 1
word = rtf[start:i]
sign = 1
if i < n and rtf[i] == "-":
sign = -1
i += 1
num_start = i
while i < n and rtf[i].isdigit():
i += 1
arg = None
if i > num_start:
arg = int(rtf[num_start:i]) * sign
if i < n and rtf[i] == " ":
i += 1
if pending_ignorable or word in ignorable_destinations:
skip_group = True
pending_ignorable = False
continue
pending_ignorable = False
if word in ("par", "pard", "line"):
emit("\n")
elif word == "tab":
emit("\t")
elif word == "emdash":
emit("—")
elif word == "endash":
emit("–")
elif word == "bullet":
emit("•")
elif word == "lquote":
emit("‘")
elif word == "rquote":
emit("’")
elif word == "ldblquote":
emit("“")
elif word == "rdblquote":
emit("”")
elif word == "uc" and arg is not None:
ucskip = max(0, arg)
elif word == "u" and arg is not None:
codepoint = arg if arg >= 0 else arg + 65536
try:
emit(chr(codepoint))
except Exception:
pass
# Skip fallback chars/tokens after unicode escape.
skip = ucskip
while skip > 0 and i < n:
if rtf[i] == "\\":
# Skip an escaped fallback token as one char.
i += 1
if i < n and rtf[i] == "'" and i + 2 < n:
i += 3
elif i < n:
i += 1
else:
i += 1
skip -= 1
# all other controls are formatting; ignore.
else:
# Control symbol; usually formatting. Consume it.
i += 1
else:
if c not in "\r\n":
emit(c)
i += 1
text = "".join(out)
text = re.sub(r"\n{3,}", "\n\n", text)
return text.strip("\n")
class ManuscriptHTMLTextExtractor(HTMLParser):
block_tags = {
"address", "article", "blockquote", "body", "dd", "details", "dialog", "div", "dl", "dt",
"fieldset", "figcaption", "figure", "h1", "h2", "h3", "h4", "h5", "h6",
"hr", "li", "main", "ol", "p", "pre", "section", "table", "tbody", "td", "tfoot", "th", "thead",
"tr", "ul",
}
skip_tags = {"script", "style", "noscript", "template", "head", "svg", "canvas", "nav", "header", "footer", "aside", "form", "menu"}
def __init__(self) -> None:
super().__init__(convert_charrefs=True)
self.parts: List[str] = []
self.skip_depth = 0
def newline(self) -> None:
if self.parts and not self.parts[-1].endswith("\n"):
self.parts.append("\n")
def handle_starttag(self, tag: str, attrs: List[Tuple[str, Optional[str]]]) -> None:
tag = tag.lower()
if tag in self.skip_tags:
self.skip_depth += 1
return
if self.skip_depth:
return
if tag == "br":
self.newline()
elif tag in self.block_tags:
self.newline()
def handle_endtag(self, tag: str) -> None:
tag = tag.lower()
if tag in self.skip_tags and self.skip_depth:
self.skip_depth -= 1
return
if self.skip_depth:
return
if tag in self.block_tags:
self.newline()
def handle_data(self, data: str) -> None:
if not self.skip_depth:
self.parts.append(data)
def text(self) -> str:
text = "".join(self.parts)
text = text.replace("\xa0", " ")
text = re.sub(r"[ \t\f\v]+", " ", text)
text = re.sub(r" *\n *", "\n", text)
text = re.sub(r"\n{3,}", "\n\n", text)
return text.strip()
def html_to_text(source: str) -> str:
if lxml_html is not None:
try:
source = readable_html_fragment(source)
except Exception:
pass
parser = ManuscriptHTMLTextExtractor()
parser.feed(source)
parser.close()
return parser.text()
def trafilatura_html_to_text(source: str, url: str = "") -> str:
if trafilatura is None:
raise RuntimeError("trafilatura is not installed. Run: pip install -r requirements.txt")
extracted = trafilatura.extract(
source or "",
url=url or None,
output_format="markdown",
include_comments=False,
include_tables=True,
include_images=False,
include_links=False,
favor_precision=True,
)
if not extracted or not extracted.strip():
raise ValueError("Trafilatura could not find readable main text.")
return normalize_imported_text(extracted)
def normalize_imported_text(text: str) -> str:
text, _notes = normalize_line_endings(text or "")
text = text.replace("\xa0", " ")
text = re.sub(r"[ \t\f\v]+\n", "\n", text)
text = re.sub(r"\n{4,}", "\n\n\n", text)
return text.strip()
def html_import_options(source: str, filename: str = "import.html", url: str = "") -> Dict[str, Any]:
simple = normalize_imported_text(html_to_text(source or ""))
main = ""
main_error = ""
try:
main = trafilatura_html_to_text(source or "", url=url)
except Exception as exc:
main_error = str(exc)
notes = []
if simple:
notes.append("Simple extraction available")
if main:
notes.append("Trafilatura main text available")
elif main_error:
notes.append(f"Trafilatura unavailable: {main_error}")
return {
"filename": filename,
"url": url,
"simple": {"text": simple, "chars": len(simple)},
"main": {"text": main, "chars": len(main), "error": main_error},
"notes": notes,
"engine": "trafilatura" if trafilatura is not None else "simple-only",
}
def is_blocked_import_host(hostname: str) -> bool:
host = (hostname or "").strip().lower().rstrip(".")
if not host or host in {"localhost", "127.0.0.1", "::1"} or host.endswith(".localhost"):
return True
try:
ip = ipaddress.ip_address(host)
return ip.is_private or ip.is_loopback or ip.is_link_local or ip.is_multicast or ip.is_reserved
except ValueError:
pass
return False
def validate_import_url(raw_url: str) -> str:
url = (raw_url or "").strip()
parsed = urllib.parse.urlparse(url)
if parsed.scheme not in {"http", "https"} or not parsed.netloc:
raise ValueError("Use a full http:// or https:// URL.")
if parsed.username or parsed.password:
raise ValueError("URLs with embedded usernames or passwords are not supported.")
if is_blocked_import_host(parsed.hostname or ""):
raise ValueError("Local, private, and internal addresses are blocked for URL import.")
return urllib.parse.urlunparse(parsed)
def fetch_url_bytes(url: str) -> Tuple[bytes, str, str]:
if requests is None:
raise RuntimeError("requests is not installed. Run: pip install -r requirements.txt")
safe_url = validate_import_url(url)
headers = {
"User-Agent": "ManuscriptWorkbench/1.0 (+local import)",
"Accept": "text/html,application/xhtml+xml,text/plain;q=0.8,*/*;q=0.5",
}
with requests.get(safe_url, headers=headers, timeout=(8, 25), stream=True, allow_redirects=True) as resp:
resp.raise_for_status()
final_url = validate_import_url(resp.url)
content_type = resp.headers.get("Content-Type", "")
chunks: List[bytes] = []
total = 0
for chunk in resp.iter_content(chunk_size=65536):
if not chunk:
continue
total += len(chunk)
if total > MAX_URL_IMPORT_BYTES:
raise ValueError("URL response is too large to import safely.")
chunks.append(chunk)
return b"".join(chunks), final_url, content_type
MARKDOWN_ALLOWED_TAGS = {
"a", "blockquote", "br", "code", "del", "div", "em", "h1", "h2", "h3", "h4", "h5", "h6",
"hr", "img", "li", "ol", "p", "pre", "span", "strong", "table", "tbody", "td", "th", "thead",
"tr", "u", "ul",
}
MARKDOWN_VOID_TAGS = {"br", "hr", "img"}
MARKDOWN_ALLOWED_ATTRS = {
"a": {"href", "title"},
"img": {"src", "alt", "title"},
"code": {"class"},
"div": {"class"},
"span": {"class"},
}
MARKDOWN_SAFE_CLASS_RE = re.compile(r"^(?:language-[A-Za-z0-9_-]+|block|block-label|block-[A-Za-z0-9_-]+|scene|sc|sans|task)$")
INLINE_MARKER_RE = re.compile(r"\[\[(sc|mono|sans|u):(.+?)\]\]", re.S)
def markdown_safe_url(value: str) -> str:
raw = (value or "").strip()
if not raw or re.search(r"[\s<>\"']", raw):
return ""
if re.match(r"^(?:https?:|mailto:|#|/|\./|\.\./)", raw, re.I):
return raw
return ""
class MarkdownHTMLSanitizer(HTMLParser):
def __init__(self) -> None:
super().__init__(convert_charrefs=True)
self.parts: List[str] = []
self.skip_depth = 0
def handle_starttag(self, tag: str, attrs: List[Tuple[str, Optional[str]]]) -> None:
tag = tag.lower()
if tag not in MARKDOWN_ALLOWED_TAGS:
self.skip_depth += 1
return
if self.skip_depth:
return
clean_attrs: List[str] = []
allowed = MARKDOWN_ALLOWED_ATTRS.get(tag, set())
for name, value in attrs:
name = name.lower()
value = value or ""
if name not in allowed:
continue
if name in {"href", "src"}:
value = markdown_safe_url(value)
if not value:
continue
elif name == "class":
classes = [c for c in value.split() if MARKDOWN_SAFE_CLASS_RE.fullmatch(c)]
if not classes:
continue
value = " ".join(classes)
clean_attrs.append(f'{name}="{html_std.escape(value, quote=True)}"')
attr_text = (" " + " ".join(clean_attrs)) if clean_attrs else ""
self.parts.append(f"<{tag}{attr_text}>")
def handle_startendtag(self, tag: str, attrs: List[Tuple[str, Optional[str]]]) -> None:
self.handle_starttag(tag, attrs)
def handle_endtag(self, tag: str) -> None:
tag = tag.lower()
if tag not in MARKDOWN_ALLOWED_TAGS:
if self.skip_depth:
self.skip_depth -= 1
return
if self.skip_depth:
return
if tag not in MARKDOWN_VOID_TAGS:
self.parts.append(f"</{tag}>")
def handle_data(self, data: str) -> None:
if not self.skip_depth:
self.parts.append(html_std.escape(data, quote=False))
def handle_entityref(self, name: str) -> None:
if not self.skip_depth:
self.parts.append(f"&{name};")
def handle_charref(self, name: str) -> None:
if not self.skip_depth:
self.parts.append(f"&#{name};")
def html(self) -> str:
return "".join(self.parts)
def sanitize_markdown_html(value: str) -> str:
parser = MarkdownHTMLSanitizer()
parser.feed(value or "")
parser.close()
return parser.html()
def render_inline_markers_for_preview(line: str) -> str:
def repl(match: re.Match[str]) -> str:
kind = match.group(1)
content = html_std.escape(match.group(2) or "", quote=False)
if kind == "u":
return f"<u>{content}</u>"
if kind == "mono":
return f"<code>{content}</code>"
return f'<span class="{kind}">{content}</span>'
return INLINE_MARKER_RE.sub(repl, line)
def preprocess_manuscript_markdown(text: str) -> str:
lines = (text or "").splitlines()
out: List[str] = []
open_block = False
code_fence = ""
for line in lines:
fence = re.match(r"^\s*(```+|~~~+)", line)
if code_fence:
out.append(line)
if fence and fence.group(1).startswith(code_fence[0]):
code_fence = ""
continue
if fence:
code_fence = fence.group(1)
out.append(line)
continue
marker = re.match(r"^\s*:::\s*([A-Za-z0-9_-]+)?\s*$", line)
if marker:
if open_block:
out.append("")
out.append("</div>")
open_block = False
else:
name = canonical_structure_marker(marker.group(1) or "block")
safe_name = html_std.escape(name, quote=True)
out.append(f'<div class="block block-{safe_name}" markdown="1">')
out.append(f'<div class="block-label">{safe_name}</div>')
out.append("")
open_block = True
continue
if re.fullmatch(r"\s*(?:\*\s*){3,}\s*|\s*[-–—]{3,}\s*|\s*~{3,}\s*", line):
out.append('<div class="scene">* * *</div>')
continue
list_indent = re.match(r"^( +)((?:[-+*])|(?:\d+[.)]))\s+", line)
if list_indent and (len(list_indent.group(1)) % 4):
depth = max(1, (len(list_indent.group(1)) + 1) // 2)
line = (" " * (depth * 4)) + line[len(list_indent.group(1)):]
out.append(render_inline_markers_for_preview(line))
if open_block:
out.append("")
out.append("</div>")
return "\n".join(out)
def render_markdown_html(text: str) -> str:
if markdown_lib is None:
raise RuntimeError("Python-Markdown is not installed. Run: pip install -r requirements.txt")
rendered = markdown_lib.markdown(
preprocess_manuscript_markdown(text or ""),
extensions=["extra", "sane_lists", "nl2br"],
output_format="html5",
)
return sanitize_markdown_html(rendered)
def render_help_page(markdown_text: str) -> str:
try:
body = render_markdown_html(markdown_text)
except Exception:
body = f"<pre>{html_std.escape(markdown_text)}</pre>"
return f"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Manuscript Workbench Help</title>
<style>
body{{margin:0;background:#171613;color:#ede7da;font-family:Inter,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;line-height:1.65}}
main{{max-width:900px;margin:0 auto;padding:34px 28px 64px}}
h1,h2,h3{{line-height:1.2;color:#fff}} h1{{font-size:32px}} h2{{margin-top:2em;border-top:1px solid #3a372f;padding-top:1em}}
a{{color:#7fc4ef}} code{{background:#2a2823;border-radius:4px;padding:.1em .32em}} pre{{background:#211f1b;border:1px solid #3a372f;border-radius:8px;padding:14px;overflow:auto}}
blockquote{{border-left:4px solid #e0a458;margin:1em 0;padding:.2em 0 .2em 1em;color:#d8d0c1}} table{{border-collapse:collapse;width:100%}} th,td{{border:1px solid #3a372f;padding:6px 8px}}
</style>
</head>
<body><main>{body}</main></body>
</html>"""
def readable_html_fragment(source: str) -> str:
tree = lxml_html.fromstring(source)
boilerplate_xpath = (
"//script|//style|//noscript|//template|//svg|//canvas|//nav|//header|//footer|//aside|//form|//menu|"
"//*[contains(translate(concat(' ', @class, ' '), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), ' sidebar ')]|"
"//*[contains(translate(concat(' ', @class, ' '), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), ' navigation ')]|"
"//*[contains(translate(concat(' ', @class, ' '), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), ' menu ')]|"
"//*[contains(translate(concat(' ', @class, ' '), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), ' footer ')]|"
"//*[contains(translate(concat(' ', @class, ' '), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), ' header ')]|"
"//*[contains(translate(concat(' ', @id, ' '), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), ' sidebar ')]|"
"//*[contains(translate(concat(' ', @id, ' '), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), ' navigation ')]|"
"//*[contains(translate(concat(' ', @id, ' '), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), ' menu ')]|"
"//*[contains(translate(concat(' ', @id, ' '), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), ' footer ')]|"
"//*[contains(translate(concat(' ', @id, ' '), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), ' header ')]"
)
for el in tree.xpath(boilerplate_xpath):
parent = el.getparent()
if parent is not None:
parent.remove(el)
candidates = tree.xpath(
"//main|//article|//*[@role='main']|"
"//*[contains(translate(concat(' ', @class, ' '), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), ' content ')]|"
"//*[contains(translate(concat(' ', @class, ' '), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), ' post ')]|"
"//*[contains(translate(concat(' ', @class, ' '), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'), ' entry ')]|"
"//*[@id='content' or @id='main' or @id='article']"
)
if candidates:
best = max(candidates, key=lambda el: len(" ".join(el.itertext()).strip()))
return lxml_html.tostring(best, encoding="unicode", method="html")
return lxml_html.tostring(tree, encoding="unicode", method="html")
def import_docx_bytes(data: bytes) -> Tuple[str, List[str]]:
if Document is None:
raise RuntimeError("python-docx is not installed. Run: pip install -r requirements.txt")
with tempfile.NamedTemporaryFile(delete=False, suffix=".docx") as tmp:
tmp.write(data)
path = tmp.name
try:
doc = Document(path)
lines: List[str] = []
for p in doc.paragraphs:
style_name = p.style.name if p.style is not None else ""
marker = STYLE_TO_MARKER.get(style_name)
text = paragraph_runs_to_marked_text(p)
plain = text.strip()
if not marker and plain and re.fullmatch(r"(?:[*•·]\s*){3,}|[-–—]{3,}|#", plain):
# Practical round-trip for common ornamental/scene-break lines.
marker = "ornament"
if marker:
lines.append(marker_to_markdown_text(marker, text))
else:
lines.append(text)
text = "\n".join(lines)
text, notes = normalize_line_endings(text)
notes.insert(0, f"Imported DOCX paragraphs: {len(lines):,}")
if getattr(doc, "tables", None):
notes.append(f"Skipped DOCX tables: {len(doc.tables):,}")
return text, notes
finally:
try:
os.unlink(path)
except Exception:
pass
def paragraph_runs_to_marked_text(p: Any) -> str:
pieces: List[str] = []
for run in p.runs:
text = run.text or ""
if not text:
continue
style_name = run.style.name if run.style is not None else ""
if style_name in ("Manuscript Small Caps", "Vellum Small Caps"):
pieces.append(f"[[sc:{text}]]")
elif style_name in ("Manuscript Monospace", "Vellum Monospace"):
pieces.append(f"[[mono:{text}]]")
elif style_name in ("Manuscript Sans Serif", "Vellum Sans Serif"):
pieces.append(f"[[sans:{text}]]")
elif run.underline:
pieces.append(f"[[u:{text}]]")
elif run.bold and run.italic:
pieces.append(f"***{text}***")
elif run.bold:
pieces.append(f"**{text}**")
elif run.italic:
pieces.append(f"*{text}*")
else:
pieces.append(text)
return "".join(pieces)
def marker_to_markdown_text(marker: str, text: str) -> str:
text = (text or "").strip()
prefixes = {
"chapter": "# ",
"part": "# ",
"subhead1": "## ",
"subhead2": "### ",
"subhead3": "#### ",
"subhead4": "##### ",
"subhead5": "###### ",
"quote": "> ",
}
if marker in prefixes:
return (prefixes[marker] + text).rstrip()
if marker in ("scene", "ornament"):
return "***"
if not text:
return f"::: {marker}\n:::"
return f"::: {marker}\n{text}\n:::"
def import_file(filename: str, data: bytes, html_mode: str = "main") -> Dict[str, Any]:
lower = filename.lower()
notes: List[str] = []
sniff = data[:4096].lstrip()
is_docx = data.startswith(b"PK\x03\x04")
is_rtf = sniff.startswith(b"{\\rtf")
is_html = bool(re.match(br"(?is)^(?:<!doctype\s+html|<html\b|<!--.*?-->\s*<html\b|<head\b|<body\b)", sniff))
if lower.endswith(".doc") and not lower.endswith(".docx"):
raise ValueError(".doc is an old binary Word format. Please save it as .docx, .rtf, or .txt first.")
if lower.endswith(".docx") or is_docx:
text, notes = import_docx_bytes(data)
if is_docx and not lower.endswith(".docx"):
notes.insert(0, "Detected DOCX content from file signature")
elif lower.endswith(".rtf") or is_rtf:
decoded, notes = decode_text_bytes(data)
text = rtf_to_text(decoded)
notes.insert(0, "Imported RTF as plain text" if lower.endswith(".rtf") else "Detected RTF content and imported as plain text")
elif lower.endswith((".html", ".htm")) or is_html:
decoded, notes = decode_text_bytes(data)
if html_mode == "simple":
text = html_to_text(decoded)
notes.insert(0, "Imported HTML with simple extraction" if lower.endswith((".html", ".htm")) else "Detected HTML content and imported with simple extraction")
else:
try:
text = trafilatura_html_to_text(decoded)
notes.insert(0, "Imported HTML main text with Trafilatura")
except Exception as exc:
text = html_to_text(decoded)
notes.insert(0, f"Trafilatura failed; used simple HTML extraction: {exc}")
elif lower.endswith((".md", ".markdown")):
text, notes = decode_text_bytes(data)
notes.insert(0, "Imported Markdown")
else:
text, notes = decode_text_bytes(data)
return {"text": text, "notes": notes, "filename": filename}
def ensure_paragraph_style(doc: Any, name: str) -> None:
try:
_ = doc.styles[name]
return
except KeyError:
pass
if name.startswith("Heading") or name in ("Normal", "Caption"):
return
style = doc.styles.add_style(name, WD_STYLE_TYPE.PARAGRAPH)
style.font.name = "Times New Roman"
style.font.size = Pt(11)
def ensure_character_style(doc: Any, name: str) -> None:
try:
_ = doc.styles[name]
return
except KeyError:
pass
style = doc.styles.add_style(name, WD_STYLE_TYPE.CHARACTER)
style.font.name = "Times New Roman"
style.font.size = Pt(11)
if name == "Manuscript Monospace":
style.font.name = "Courier New"
elif name == "Manuscript Sans Serif":
style.font.name = "Arial"
elif name == "Manuscript Small Caps":
style.font.small_caps = True
MARKDOWN_HEADING_TO_MARKER = {
1: "chapter",
2: "subhead1",
3: "subhead2",
4: "subhead3",
5: "subhead4",
6: "subhead5",
}
MARKDOWN_CONTAINER_ALIASES = {
"note": "written-note",
"written-note": "written-note",
"text": "text-conversation",
"text-conversation": "text-conversation",
"verse": "verse",
"quote": "quote",
"attribution": "attribution",
"centered": "centered",
"flush-left": "flush-left",
"caption": "caption",
"image": "inline-image",
"inline-image": "inline-image",
"subtitle": "subtitle",
"element-author": "element-author",
"hidden-heading": "hidden-heading",
}
MARKDOWN_CONTAINER_RE = re.compile(r"^\s*:::\s*([a-z0-9_-]+)?\s*$", re.I)
def canonical_structure_marker(marker: str) -> str:
return MARKDOWN_CONTAINER_ALIASES.get((marker or "").lower(), (marker or "").lower())
def is_part_heading(content: str) -> bool:
return bool(re.match(r"^\s*(?:part|deel)\b", content or "", re.I))
def markdown_line_marker(line: str) -> Tuple[str, str]:
stripped = line.strip()
heading = re.match(r"^\s{0,3}(#{1,6})\s+(.+?)\s*#*\s*$", line)
if heading:
content = heading.group(2).strip()
level = len(heading.group(1))
if level == 1 and is_part_heading(content):
return "part", content
return MARKDOWN_HEADING_TO_MARKER.get(level, ""), content
quote = re.match(r"^\s{0,3}>\s?(.*)$", line)
if quote:
return "quote", quote.group(1).strip()
if re.fullmatch(r"(?:\*\s*){3,}|[-–—]{3,}|~{3,}", stripped):
return "scene", ""
return "", line
def structure_marker_for_line(line: str, block_marker: str = "") -> Tuple[str, str]:
marker, content = markdown_line_marker(line)
if marker:
return marker, content
if block_marker and line.strip():
return block_marker, line.strip()
return "", line
def strip_structure_line(line: str) -> str:
marker, content = structure_marker_for_line(line)
return content.rstrip() if marker else line.rstrip()