-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdocs_crawler.py
More file actions
2474 lines (2178 loc) · 90.5 KB
/
Copy pathdocs_crawler.py
File metadata and controls
2474 lines (2178 loc) · 90.5 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
# -*- coding: utf-8 -*-
"""
Generic documentation crawler.
What it does:
1) Crawl docs pages from a configurable docs site and save markdown files.
2) Build a local HTML viewer with left navigation + right markdown panel.
No product-specific rewriting or brand-coupled behavior.
"""
from __future__ import annotations
import argparse
import datetime as dt
import html
import http.server
import json
import os
import re
import shutil
import socket
import socketserver
import sys
import threading
import time
import traceback
import urllib.error
import urllib.parse
import urllib.request
from pathlib import Path
from typing import Dict, List, Optional, Sequence, Tuple
DEFAULT_CONFIG_PATH = "crawler_config.json"
# -----------------------------
# basic io helpers
# -----------------------------
def now_iso() -> str:
return dt.datetime.now().astimezone().isoformat()
def now_hms() -> str:
return dt.datetime.now().strftime("%H:%M:%S")
def log(message: str) -> None:
text = f"[{now_hms()}] {message}"
try:
print(text, flush=True)
except UnicodeEncodeError:
enc = getattr(sys.stdout, "encoding", None) or "utf-8"
safe = text.encode(enc, errors="replace").decode(enc, errors="replace")
print(safe, flush=True)
def ensure_dir(path: Path) -> None:
path.mkdir(parents=True, exist_ok=True)
def load_json(path: Path, default):
if not path.exists():
return default
try:
return json.loads(path.read_text(encoding="utf-8"))
except Exception:
return default
def save_json(path: Path, data) -> None:
ensure_dir(path.parent)
path.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
def write_text(path: Path, text: str) -> None:
ensure_dir(path.parent)
path.write_text(text, encoding="utf-8")
def copy_file(src: Path, dst: Path) -> bool:
if not src.exists():
return False
ensure_dir(dst.parent)
shutil.copy2(src, dst)
return True
class ProgressHeartbeat:
"""
Periodically prints progress heartbeat so users can see the program is alive.
"""
def __init__(self, name: str, interval_seconds: int = 8) -> None:
self.name = name
self.interval_seconds = max(3, int(interval_seconds))
self._lock = threading.Lock()
self._stop = threading.Event()
self._thread: Optional[threading.Thread] = None
self._state = {
"phase": "初始化",
"step": "-",
"url": "-",
"done": 0,
"total": 0,
"last_touch": time.time(),
"started_at": time.time(),
}
def start(self) -> "ProgressHeartbeat":
self._thread = threading.Thread(target=self._run, name=f"heartbeat-{self.name}", daemon=True)
self._thread.start()
return self
def stop(self) -> None:
self._stop.set()
if self._thread and self._thread.is_alive():
self._thread.join(timeout=1.5)
def update(
self,
*,
phase: Optional[str] = None,
step: Optional[str] = None,
url: Optional[str] = None,
done: Optional[int] = None,
total: Optional[int] = None,
) -> None:
with self._lock:
if phase is not None:
self._state["phase"] = phase
if step is not None:
self._state["step"] = step
if url is not None:
self._state["url"] = url
if done is not None:
self._state["done"] = int(done)
if total is not None:
self._state["total"] = int(total)
self._state["last_touch"] = time.time()
def _run(self) -> None:
while not self._stop.wait(self.interval_seconds):
with self._lock:
phase = self._state["phase"]
step = self._state["step"]
url = self._state["url"]
done = int(self._state["done"])
total = int(self._state["total"])
idle = int(time.time() - float(self._state["last_touch"]))
started_at = float(self._state["started_at"])
percent = 0.0 if total <= 0 else (done / total) * 100
elapsed = max(0.001, time.time() - started_at)
speed = done / elapsed # docs/sec
speed_min = speed * 60
remain = max(0, total - done)
eta_seconds = int(remain / speed) if speed > 0 else -1
eta_text = "-" if eta_seconds < 0 else f"{eta_seconds}s"
log(
f"[保活] 阶段={phase} 进度={done}/{total} ({percent:.1f}%) "
f"速度={speed_min:.2f} docs/min ETA={eta_text} "
f"当前={step} 空闲={idle}s URL={url}"
)
def progress_bar(done: int, total: int, width: int = 28) -> str:
if total <= 0:
return "[----------------------------] 0.0%"
ratio = max(0.0, min(1.0, done / total))
filled = int(ratio * width)
bar = "█" * filled + "-" * (width - filled)
return f"[{bar}] {ratio * 100:5.1f}%"
def log_progress_line(prefix: str, done: int, total: int, started_at: float) -> None:
elapsed = max(0.001, time.time() - started_at)
speed = done / elapsed
speed_min = speed * 60
remain = max(0, total - done)
eta_seconds = int(remain / speed) if speed > 0 else -1
eta_text = "-" if eta_seconds < 0 else f"{eta_seconds}s"
bar = progress_bar(done, total)
log(f"{prefix} {bar} {done}/{total} 速度={speed_min:.2f} docs/min ETA={eta_text}")
def sanitize_segment(text: str, fallback: str = "uncategorized") -> str:
name = (text or "").strip()
if not name:
return fallback
name = re.sub(r'[\\/:*?"<>|]+', "_", name)
name = re.sub(r"\s+", "", name)
return name.strip("._") or fallback
def slug_to_source_filename(slug: str) -> str:
safe = re.sub(r"[^a-zA-Z0-9_\-/\.]+", "-", slug.strip("/"))
safe = safe.replace("/", "__")
if not safe:
safe = "index"
return f"{safe}.source.md"
def build_doc_source_url(base_url: str, docs_root: str, slug: str) -> str:
root = "/" + (docs_root or "/docs").strip("/")
s = (slug or "").strip("/")
if s in {"", "index"}:
return urllib.parse.urljoin(base_url, root.rstrip("/") + "/")
return urllib.parse.urljoin(base_url, f"{root.rstrip('/')}/{s}")
# -----------------------------
# http / parse helpers
# -----------------------------
def build_doc_source_url_with_meta(base_url: str, docs_root: str, slug: str, meta: Optional[dict] = None) -> str:
m = meta or {}
source_path = (m.get("source_path") or "").strip()
if source_path:
return urllib.parse.urljoin(base_url, source_path)
source_root = (m.get("source_root") or docs_root or "/docs").strip() or "/docs"
return build_doc_source_url(base_url, source_root, slug)
def make_source_path(docs_root: str, rel_slug: str) -> str:
root = "/" + (docs_root or "/docs").strip("/")
rel = (rel_slug or "").strip("/")
if rel in {"", "index"}:
return root.rstrip("/") + "/"
return f"{root.rstrip('/')}/{rel}"
def make_compound_slug(docs_root: str, rel_slug: str, multi_root: bool) -> str:
rel = (rel_slug or "").strip("/") or "index"
if not multi_root:
return rel
root_tag = (docs_root or "/docs").strip("/") or "docs"
return f"{root_tag}/{rel}"
def make_route_candidates(rel_slug: str, slug: str) -> List[str]:
candidates: List[str] = []
for raw in [rel_slug or "", slug or ""]:
s = raw.strip("/").lower()
if not s:
continue
for x in [s, s.rstrip("/"), s.removesuffix(".html")]:
if x and x not in candidates:
candidates.append(x)
if "index" not in candidates:
candidates.append("index")
return candidates
def http_get_text(
url: str,
timeout: int = 30,
retries: int = 3,
backoff_seconds: float = 1.5,
) -> str:
req = urllib.request.Request(url, headers={"User-Agent": "DocsCrawler/1.0"})
retries = max(1, int(retries))
last_error: Optional[Exception] = None
for attempt in range(1, retries + 1):
t0 = time.time()
log(f"[HTTP] 请求开始 attempt={attempt}/{retries} timeout={timeout}s url={url}")
try:
with urllib.request.urlopen(req, timeout=timeout) as resp:
raw = resp.read()
elapsed = time.time() - t0
log(f"[HTTP] 请求成功 status={getattr(resp, 'status', '?')} bytes={len(raw)} 耗时={elapsed:.2f}s url={url}")
return raw.decode("utf-8", errors="replace")
except (urllib.error.URLError, TimeoutError, socket.timeout) as e:
last_error = e
if attempt >= retries:
break
sleep_seconds = float(backoff_seconds) * attempt
elapsed = time.time() - t0
log(f"[HTTP][WARN] 请求失败 attempt={attempt}/{retries} 耗时={elapsed:.2f}s url={url} err={e}")
log(f"[HTTP][WARN] 等待重试 sleep={sleep_seconds:.1f}s")
time.sleep(sleep_seconds)
except Exception:
raise
raise RuntimeError(f"request failed after {retries} retries: {url} | {last_error}")
def infer_category_number(text: str) -> Optional[int]:
m = re.match(r"^\s*(\d+)(?:\.\d+)?", text or "")
if not m:
return None
try:
return int(m.group(1))
except Exception:
return None
def pick_attr_value(m: Optional[re.Match], start_idx: int = 1) -> str:
if not m:
return ""
end = (m.lastindex or 0) + 1
for i in range(start_idx, end):
val = m.group(i)
if val:
return val
return ""
def strip_tags(text: str) -> str:
return html.unescape(re.sub(r"<[^>]+>", "", text or "")).strip()
def normalize_docs_href(href: str, docs_root: str = "/docs") -> str:
docs_root = "/" + docs_root.strip("/")
p = urllib.parse.urlparse(href or "")
path = p.path or ""
if not path.startswith(docs_root + "/"):
return ""
return path[len(docs_root) + 1 :].strip("/")
def _looks_like_docs_html(page_html: str, docs_root: str) -> bool:
text = page_html or ""
if not text:
return False
markers = [
"theme-doc-sidebar-item",
"VPSidebar",
"VPDoc",
"vitepress",
"docusaurus",
]
if any(m.lower() in text.lower() for m in markers):
return True
docs_root = "/" + (docs_root or "/docs").strip("/")
if re.search(rf'href=(?:"|\')({re.escape(docs_root)}/)', text, re.I):
return True
return False
def _candidate_docs_roots_from_seed_html(seed_html: str, configured_docs_root: str) -> List[str]:
candidates: List[str] = []
seen: set[str] = set()
def _add(path: str) -> None:
p = "/" + (path or "").strip("/")
if not p or p == "//":
return
if p in seen:
return
seen.add(p)
candidates.append(p)
_add(configured_docs_root or "/docs")
for p in ["/docs", "/guide", "/manual", "/reference", "/api", "/help"]:
_add(p)
for m in re.finditer(r'href=(?:"([^"]+)"|\'([^\']+)\'|([^\s>]+))', seed_html or "", re.I):
href = (m.group(1) or m.group(2) or m.group(3) or "").strip()
if not href:
continue
pu = urllib.parse.urlparse(href)
path = (pu.path or "").strip()
if not path.startswith("/"):
continue
if path.startswith("/assets/") or path.startswith("/@") or path.startswith("/_"):
continue
segs = [x for x in path.split("/") if x]
if not segs:
continue
if "." in segs[0]:
continue
first = "/" + segs[0]
_add(first)
return candidates
def _candidate_docs_root_samples_from_seed_html(seed_html: str) -> Dict[str, List[str]]:
"""
Build sample doc paths by first path segment, for cases where root index
(e.g. /components/) is 404 but leaf docs (e.g. /components/xxx.html) exist.
"""
out: Dict[str, List[str]] = {}
for m in re.finditer(r'href=(?:"([^"]+)"|\'([^\']+)\'|([^\s>]+))', seed_html or "", re.I):
href = (m.group(1) or m.group(2) or m.group(3) or "").strip()
if not href:
continue
pu = urllib.parse.urlparse(href)
path = (pu.path or "").strip()
if not path.startswith("/"):
continue
if path.startswith("/assets/") or path.startswith("/@") or path.startswith("/_"):
continue
segs = [x for x in path.split("/") if x]
if not segs:
continue
if "." in segs[0]:
continue
root = "/" + segs[0]
arr = out.setdefault(root, [])
if path not in arr:
arr.append(path)
return out
def resolve_docs_root(
*,
base_url: str,
configured_docs_root: str,
seed_html: str,
timeout: int,
retries: int,
backoff: float,
) -> Tuple[str, str]:
"""
Resolve a valid docs_root automatically.
Returns: (resolved_docs_root, docs_home_html)
"""
last_error: Optional[Exception] = None
candidates = _candidate_docs_roots_from_seed_html(seed_html, configured_docs_root)
sample_map = _candidate_docs_root_samples_from_seed_html(seed_html)
probe_retries = 1 if retries > 1 else retries
probe_backoff = 0.0 if retries > 1 else backoff
for root in candidates:
url = urllib.parse.urljoin(base_url, root if root.endswith("/") else root + "/")
try:
html_text = http_get_text(
url,
timeout=timeout,
retries=probe_retries,
backoff_seconds=probe_backoff,
)
if _looks_like_docs_html(html_text, root):
if root != ("/" + configured_docs_root.strip("/")):
log(f"[!] 自动修正 docs_root: {configured_docs_root} -> {root}")
return root, html_text
except Exception as e:
last_error = e
for sample_path in (sample_map.get(root) or [])[:5]:
try:
sample_url = urllib.parse.urljoin(base_url, sample_path)
sample_html = http_get_text(
sample_url,
timeout=timeout,
retries=probe_retries,
backoff_seconds=probe_backoff,
)
if _looks_like_docs_html(sample_html, root):
if root != ("/" + configured_docs_root.strip("/")):
log(f"[!] 自动修正 docs_root: {configured_docs_root} -> {root}")
return root, sample_html
except Exception as e:
last_error = e
continue
cfg = "/" + configured_docs_root.strip("/")
if last_error:
log(f"[!] docs_root 自动探测失败,保留配置值:{cfg} ({last_error})")
return cfg, ""
def resolve_docs_roots(
*,
base_url: str,
configured_docs_root: str,
seed_html: str,
timeout: int,
retries: int,
backoff: float,
) -> Tuple[List[str], Dict[str, str]]:
"""
Resolve docs roots.
- If configured_docs_root is provided, keep single-root behavior.
- If configured_docs_root is empty, auto detect all valid roots from seed links.
Returns: (roots, root_home_html_map)
"""
configured = (configured_docs_root or "").strip()
if configured:
root, html_text = resolve_docs_root(
base_url=base_url,
configured_docs_root=configured,
seed_html=seed_html,
timeout=timeout,
retries=retries,
backoff=backoff,
)
return [root], {root: html_text or ""}
candidates = _candidate_docs_roots_from_seed_html(seed_html, "/docs")
sample_map = _candidate_docs_root_samples_from_seed_html(seed_html)
probe_retries = 1 if retries > 1 else retries
probe_backoff = 0.0 if retries > 1 else backoff
roots: List[str] = []
root_html_map: Dict[str, str] = {}
for root in candidates:
url = urllib.parse.urljoin(base_url, root if root.endswith("/") else root + "/")
resolved = False
try:
html_text = http_get_text(
url,
timeout=timeout,
retries=probe_retries,
backoff_seconds=probe_backoff,
)
if _looks_like_docs_html(html_text, root):
roots.append(root)
root_html_map[root] = html_text
resolved = True
except Exception:
pass
if resolved:
continue
for sample_path in (sample_map.get(root) or [])[:5]:
try:
sample_url = urllib.parse.urljoin(base_url, sample_path)
sample_html = http_get_text(
sample_url,
timeout=timeout,
retries=probe_retries,
backoff_seconds=probe_backoff,
)
if not _looks_like_docs_html(sample_html, root):
continue
roots.append(root)
root_html_map[root] = sample_html
resolved = True
break
except Exception:
continue
if not roots:
fallback_root, fallback_html = resolve_docs_root(
base_url=base_url,
configured_docs_root="/docs",
seed_html=seed_html,
timeout=timeout,
retries=retries,
backoff=backoff,
)
roots = [fallback_root]
root_html_map[fallback_root] = fallback_html or ""
log(f"[*] auto docs roots: {', '.join(roots)}")
return roots, root_html_map
def _extract_sidebar_structure_vitepress(seed_html: str, docs_root: str) -> Dict[str, dict]:
docs_root = "/" + docs_root.strip("/")
categories: Dict[str, dict] = {}
slug_to_category: Dict[str, str] = {}
slug_titles: Dict[str, str] = {}
ordered_keys: List[str] = []
aside_match = re.search(r"<aside[^>]*class=\"[^\"]*VPSidebar[^\"]*\"[^>]*>(.*?)</aside>", seed_html or "", re.I | re.S)
container = aside_match.group(1) if aside_match else (seed_html or "")
level0_re = re.compile(
r'<section[^>]*class="[^"]*VPSidebarItem[^"]*level-0[^"]*"[^>]*>(.*?)</section>',
re.I | re.S,
)
level0_blocks = level0_re.findall(container) or [container]
for idx, block in enumerate(level0_blocks):
title_match = re.search(r"<h2[^>]*class=\"[^\"]*text[^\"]*\"[^>]*>(.*?)</h2>", block, re.I | re.S)
cat_label = strip_tags(title_match.group(1)) if title_match else ""
if not cat_label:
cat_label = f"Section {idx + 1}"
cat_key = f"cat:{sanitize_segment(cat_label, fallback=f'section{idx + 1}')}"
if cat_key not in categories:
categories[cat_key] = {
"key": cat_key,
"label": cat_label,
"order": idx,
"number": None,
"folder": sanitize_segment(cat_label),
"kind": "group",
}
ordered_keys.append(cat_key)
for m in re.finditer(
r'<a[^>]*class="[^"]*VPLink[^"]*"[^>]*href=(?:"([^"]+)"|\'([^\']+)\'|([^\s>]+))[^>]*>(.*?)</a>',
block,
re.I | re.S,
):
href = (m.group(1) or m.group(2) or m.group(3) or "").strip()
if not href:
continue
p = urllib.parse.urlparse(href)
path = (p.path or "").rstrip("/")
if path == docs_root.rstrip("/"):
rel = "index"
else:
rel = normalize_docs_href(href, docs_root=docs_root)
if not rel:
continue
title = strip_tags(m.group(4) or "") or rel
slug_to_category.setdefault(rel, cat_key)
if title:
slug_titles.setdefault(rel, title)
return {
"categories": categories,
"slug_to_category": slug_to_category,
"slug_titles": slug_titles,
"ordered_keys": ordered_keys,
}
def extract_sidebar_structure(seed_html: str, docs_root: str = "/docs") -> Dict[str, dict]:
"""
Extract level-1 sidebar entries from docusaurus HTML.
- category items (/docs/category/*)
- direct doc links (/docs/*)
"""
docs_root = "/" + docs_root.strip("/")
item_re = re.compile(
r'<li class="(?P<class>[^"]*theme-doc-sidebar-item-(?:category|link)[^"]*level-1[^"]*)"[^>]*>'
r"(?P<body>.*?)"
r'(?=(?:<li class="[^"]*theme-doc-sidebar-item-(?:category|link)[^"]*level-1[^"]*"|</ul>\s*</nav>|</ul>\s*</div>\s*</nav>|$))',
re.S,
)
categories: Dict[str, dict] = {}
slug_to_category: Dict[str, str] = {}
slug_titles: Dict[str, str] = {}
ordered_keys: List[str] = []
for idx, m in enumerate(item_re.finditer(seed_html or "")):
cls = m.group("class") or ""
body = m.group("body") or ""
a_match = re.search(
r"<a[^>]*href=(?:\"([^\"]+)\"|'([^']+)'|([^\s>]+))[^>]*>(?P<a_body>.*?)</a>",
body,
re.S,
)
href = pick_attr_value(a_match, 1).strip()
if not href:
continue
a_body = a_match.group("a_body") if a_match else body
title_match = re.search(r"<span[^>]*title=(?:\"([^\"]+)\"|'([^']+)'|([^\s>]+))", a_body, re.S)
title = html.unescape(pick_attr_value(title_match, 1)).strip() or strip_tags(a_body)
if not title:
continue
rel = normalize_docs_href(href, docs_root=docs_root)
if not rel:
continue
number = infer_category_number(title)
order = number if number is not None else (1000 + idx)
if "theme-doc-sidebar-item-category-level-1" in cls and rel.startswith("category/"):
key = f"cat:{rel[len('category/'):]}"
categories[key] = {
"key": key,
"label": title,
"order": order,
"number": number,
"folder": sanitize_segment(title),
"kind": "category",
}
ordered_keys.append(key)
continue
if "theme-doc-sidebar-item-link-level-1" in cls and not rel.startswith("category/"):
slug = rel
key = f"doc:{slug}"
categories[key] = {
"key": key,
"label": title,
"order": order,
"number": number,
"folder": sanitize_segment(title),
"kind": "doc",
}
ordered_keys.append(key)
slug_to_category[slug] = key
slug_titles[slug] = title
# unique keep order
seen = set()
ordered: List[str] = []
for k in ordered_keys:
if k in seen:
continue
seen.add(k)
ordered.append(k)
result = {
"categories": categories,
"slug_to_category": slug_to_category,
"slug_titles": slug_titles,
"ordered_keys": ordered,
}
if categories or slug_to_category:
return result
# fallback: VitePress sidebar
vitepress = _extract_sidebar_structure_vitepress(seed_html, docs_root=docs_root)
if (vitepress.get("categories") or {}) or (vitepress.get("slug_to_category") or {}):
return vitepress
return result
def parse_doc_entries_from_category_page(page_html: str, docs_root: str = "/docs") -> List[Tuple[str, str]]:
"""
Parse second-level sidebar entries from category page.
Important: do NOT parse all <a> links in page body, otherwise article internal links
will pollute navigation and make level-2 menu differ from source site.
"""
out: List[Tuple[str, str]] = []
seen = set()
docs_root_norm = "/" + docs_root.strip("/")
# Prefer explicit sidebar level-2 link items.
sidebar_re = re.compile(
r'theme-doc-sidebar-item-link-level-2[^>]*>\s*<a[^>]*href=(?:"([^"]+)"|\'([^\']+)\'|([^\s>]+))[^>]*>'
r'(?:\s*<span[^>]*title=(?:"([^"]+)"|\'([^\']+)\'|([^\s>]+))[^>]*>)?',
re.S | re.I,
)
for m in sidebar_re.finditer(page_html or ""):
href = (m.group(1) or m.group(2) or m.group(3) or "").strip()
if not href:
continue
p = urllib.parse.urlparse(href)
path = (p.path or "").rstrip("/")
if path == docs_root_norm.rstrip("/"):
rel = "index"
else:
rel = normalize_docs_href(href, docs_root=docs_root)
if not rel or rel.startswith("category/"):
continue
label = html.unescape((m.group(4) or m.group(5) or m.group(6) or "").strip())
if not label:
label = rel
key = (rel, label)
if key in seen:
continue
seen.add(key)
out.append((rel, label))
if out:
return out
# Fallback for non-Docusaurus or unexpected structures.
a_re = re.compile(
r"<a[^>]*href=(?:\"([^\"]+)\"|'([^']+)'|([^\s>]+))[^>]*>(?P<body>.*?)</a>",
re.S | re.I,
)
for m in a_re.finditer(page_html or ""):
href = (m.group(1) or m.group(2) or m.group(3) or "").strip()
if not href:
continue
p = urllib.parse.urlparse(href)
path = (p.path or "").rstrip("/")
if path == docs_root_norm.rstrip("/"):
rel = "index"
else:
rel = normalize_docs_href(href, docs_root=docs_root)
if not rel or rel.startswith("category/"):
continue
label = strip_tags(m.group("body") or "")
if not label:
continue
key = (rel, label)
if key in seen:
continue
seen.add(key)
out.append((rel, label))
return out
def parse_doc_slugs_from_sitemap(xml_text: str, docs_root: str = "/docs") -> List[str]:
out: List[str] = []
seen = set()
docs_root = "/" + docs_root.strip("/")
for url in re.findall(r"<loc>(.*?)</loc>", xml_text or "", re.I | re.S):
u = url.strip()
if not u:
continue
p = urllib.parse.urlparse(u)
path = (p.path or "").rstrip("/")
if not path.startswith(docs_root):
continue
rel = path[len(docs_root) :].strip("/")
if not rel or rel.startswith("category/"):
continue
if rel in seen:
continue
seen.add(rel)
out.append(rel)
return out
def html_to_markdown(article_html: str) -> str:
text = article_html or ""
# remove script/style
text = re.sub(r"<(script|style)\b[^>]*>.*?</\1>", "", text, flags=re.I | re.S)
# code blocks first
code_blocks: List[str] = []
def _extract_code(m: re.Match) -> str:
raw = m.group(1) or ""
raw = re.sub(r"^\s*<code[^>]*>|</code>\s*$", "", raw, flags=re.I | re.S)
raw = re.sub(r"<[^>]+>", "", raw)
raw = html.unescape(raw)
raw = raw.strip("\n")
code_blocks.append(raw)
return f"\n@@CODEBLOCK_{len(code_blocks)-1}@@\n"
text = re.sub(r"<pre[^>]*>(.*?)</pre>", _extract_code, text, flags=re.I | re.S)
# links
text = re.sub(
r"<a[^>]*href=(?:\"([^\"]+)\"|'([^']+)'|([^\s>]+))[^>]*>(.*?)</a>",
lambda m: f"[{strip_tags(m.group(4) or '')}]({(m.group(1) or m.group(2) or m.group(3) or '').strip()})",
text,
flags=re.I | re.S,
)
# headings
for n in range(6, 0, -1):
text = re.sub(
rf"<h{n}[^>]*>(.*?)</h{n}>",
lambda m, lv=n: "\n" + ("#" * lv) + " " + strip_tags(m.group(1) or "") + "\n",
text,
flags=re.I | re.S,
)
# simple blocks
text = re.sub(r"<blockquote[^>]*>(.*?)</blockquote>", lambda m: "\n> " + strip_tags(m.group(1) or "") + "\n", text, flags=re.I | re.S)
text = re.sub(r"<li[^>]*>(.*?)</li>", lambda m: "\n- " + strip_tags(m.group(1) or ""), text, flags=re.I | re.S)
text = re.sub(r"<(p|div|section|article|main)[^>]*>", "\n", text, flags=re.I)
text = re.sub(r"</(p|div|section|article|main)>", "\n", text, flags=re.I)
text = re.sub(r"<br\s*/?>", "\n", text, flags=re.I)
# inline emphasis
text = re.sub(r"<(strong|b)[^>]*>(.*?)</\1>", lambda m: f"**{strip_tags(m.group(2) or '')}**", text, flags=re.I | re.S)
text = re.sub(r"<(em|i)[^>]*>(.*?)</\1>", lambda m: f"*{strip_tags(m.group(2) or '')}*", text, flags=re.I | re.S)
text = re.sub(r"<code[^>]*>(.*?)</code>", lambda m: f"`{strip_tags(m.group(1) or '')}`", text, flags=re.I | re.S)
# strip leftovers
text = strip_tags(text)
# restore code blocks
for idx, code in enumerate(code_blocks):
marker = f"@@CODEBLOCK_{idx}@@"
text = text.replace(marker, f"```\n{code}\n```")
# cleanup
lines = [ln.rstrip() for ln in text.replace("\r\n", "\n").split("\n")]
out: List[str] = []
blank = False
for ln in lines:
if not ln.strip():
if not blank:
out.append("")
blank = True
continue
out.append(ln)
blank = False
return "\n".join(out).strip() + "\n"
def extract_doc_from_html(page_html: str, slug: str) -> Tuple[str, str]:
article_match = re.search(r"<article\b[^>]*>(.*?)</article>", page_html or "", re.I | re.S)
article_html = article_match.group(1) if article_match else ""
title = ""
if article_html:
h1 = re.search(r"<h1\b[^>]*>(.*?)</h1>", article_html, re.I | re.S)
if h1:
title = strip_tags(h1.group(1))
if not title:
doc_title = re.search(r"<title\b[^>]*>(.*?)</title>", page_html or "", re.I | re.S)
title = strip_tags(doc_title.group(1)) if doc_title else ""
if not title:
title = slug
body_md = html_to_markdown(article_html or page_html or "")
return title, body_md
def build_source_markdown(title: str, source_url: str, body_markdown: str) -> str:
lines = [
f"# {title}",
"",
f"> Source: `{source_url}`",
"",
body_markdown.strip(),
"",
]
return "\n".join(lines)
def parse_script_src_urls(page_html: str, base_url: str) -> List[str]:
out: List[str] = []
seen: set[str] = set()
if not page_html:
return out
for m in re.finditer(r"<script\b[^>]*\bsrc\s*=\s*(\"([^\"]+)\"|'([^']+)'|([^\s>]+))", page_html, re.I | re.S):
src = (m.group(2) or m.group(3) or m.group(4) or "").strip()
if not src:
continue
full = urllib.parse.urljoin(base_url, src)
if full in seen:
continue
seen.add(full)
out.append(full)
return out
def is_thin_body_markdown(body_markdown: str) -> bool:
text = body_markdown or ""
cleaned = re.sub(r"\s+", "", text)
non_empty_lines = [ln.strip() for ln in text.splitlines() if ln.strip()]
heading_count = len(re.findall(r"^\s*#{1,6}\s+", text, re.M))
list_count = len(re.findall(r"^\s*[-*]\s+", text, re.M))
if len(cleaned) < 280:
return True
if len(non_empty_lines) <= 8 and any(token in text for token in ["本页总览", "官方广告"]):
return True
if heading_count <= 1 and list_count == 0 and len(cleaned) < 800:
return True
return False
def decode_js_string(raw: str) -> str:
s = raw or ""
try:
return _normalize_unicode_brace_escapes(json.loads(f"\"{s}\""))
except Exception:
if "\\" not in s:
return _normalize_unicode_brace_escapes(s)
try:
return _normalize_unicode_brace_escapes(bytes(s, "utf-8").decode("unicode_escape"))
except Exception:
return _normalize_unicode_brace_escapes(s)
def _normalize_unicode_brace_escapes(text: str) -> str:
s = text or ""
return re.sub(r"\\u\{([0-9a-fA-F]{1,6})\}", lambda m: chr(int(m.group(1), 16)), s)
def _scan_js_value(text: str, start: int) -> Tuple[str, int]:
i = start
depth_paren = depth_brace = depth_bracket = 0
in_str = False
quote = ""
escaped = False
while i < len(text):
ch = text[i]
if in_str:
if escaped:
escaped = False
elif ch == "\\":
escaped = True
elif ch == quote:
in_str = False
i += 1
continue
if ch in ("'", '"'):
in_str = True
quote = ch
i += 1
continue
if ch == "(":
depth_paren += 1
elif ch == ")":
if depth_paren > 0:
depth_paren -= 1
elif ch == "{":
depth_brace += 1
elif ch == "}":
if depth_brace > 0:
depth_brace -= 1
elif ch == "[":
depth_bracket += 1
elif ch == "]":
if depth_bracket > 0:
depth_bracket -= 1
elif ch == "," and depth_paren == 0 and depth_brace == 0 and depth_bracket == 0:
return text[start:i].strip(), i
elif ch in "}" and depth_paren == 0 and depth_brace == 0 and depth_bracket == 0:
return text[start:i].strip(), i
i += 1
return text[start:].strip(), len(text)