File size: 27,563 Bytes
300ac85
 
 
 
 
 
 
 
 
 
 
20aa29e
300ac85
 
20aa29e
300ac85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5adf257
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
300ac85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bfeef61
 
300ac85
 
 
 
 
 
bfeef61
 
 
 
 
 
 
 
 
 
 
 
 
 
0de1b3e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
300ac85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20aa29e
300ac85
 
 
 
 
 
 
 
 
 
 
 
 
20aa29e
 
 
 
300ac85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20aa29e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
300ac85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5adf257
300ac85
 
 
 
 
 
 
5adf257
 
 
 
300ac85
5adf257
 
 
 
 
300ac85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5adf257
300ac85
 
 
 
 
 
 
 
5adf257
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
300ac85
 
 
 
 
 
 
5adf257
 
 
 
 
 
 
 
300ac85
 
 
 
 
 
 
 
bfeef61
 
300ac85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import argparse
import hashlib
import json
import re
import sys
import time
from collections import Counter
from dataclasses import asdict
from pathlib import Path
from urllib import robotparser
from urllib.parse import urljoin, urlsplit

import httpx
import yaml
from bs4 import BeautifulSoup

try:
    from advisors.cache import CacheRecord, CacheStore, RobotsPolicy, fetch_source_entry
    from advisors.discover import (
        DiscoveredSource,
        _clean_anchor_text,
        _looks_like_faculty_list_text,
        _looks_like_unit_text,
        write_discovered_sources_yaml,
    )
    from advisors.registry import SourceEntry, load_registry
    from advisors.url_utils import cache_key_for_url, host_matches, normalize_url
except ModuleNotFoundError:
    sibling_src = Path(__file__).resolve().parents[2] / "Advisors" / "src"
    if sibling_src.exists():
        sys.path.insert(0, str(sibling_src))
        from advisors.cache import CacheRecord, CacheStore, RobotsPolicy, fetch_source_entry
        from advisors.discover import (
            DiscoveredSource,
            _clean_anchor_text,
            _looks_like_faculty_list_text,
            _looks_like_unit_text,
            write_discovered_sources_yaml,
        )
        from advisors.registry import SourceEntry, load_registry
        from advisors.url_utils import cache_key_for_url, host_matches, normalize_url
    else:
        raise


UNIT_INDEX_TEXT_RE = re.compile(
    r"(院系设置|院系机构|院系部门|院系概览|学院设置|院部设置|教学单位|"
    r"教学机构|教学科研机构|学部院系|组织机构|机构设置|Schools|Colleges|Departments)",
    re.IGNORECASE,
)
SKIP_URL_RE = re.compile(
    r"(?i)(?:javascript:|mailto:|#|/login|passport|webvpn|ivpn|auth/login|"
    r"\.(?:pdf|docx?|xlsx?|pptx?|zip|rar|jpg|jpeg|png|gif|svg)(?:$|[?#]))"
)
ZH_NAME_RE = re.compile(r"^[\u4e00-\u9fff·]{2,4}$")
PROFILE_PATH_RE = re.compile(r"/[A-Za-z0-9_.-]+/(?:zh_CN|en)/index\.htm$")
WEBPLUS_PROFILE_PAGE_RE = re.compile(
    r"/(?:[0-9a-f]{2}/[0-9a-f]{2}|\d{4}/\d{4})/c\d+a\d+/page\.htm$",
    re.IGNORECASE,
)
INFO_PROFILE_PAGE_RE = re.compile(r"/info/\d+/\d+\.htm$", re.IGNORECASE)
HTML_PAGE_RE = re.compile(r"(?:/|\.)html?(?:$|[?#])", re.IGNORECASE)
FACULTY_LIST_PAGINATION_TEXT_RE = re.compile(r"(下一页|尾页|末页|Next)", re.IGNORECASE)
FACULTY_LIST_PAGINATION_URL_RE = re.compile(
    r"(?:/[^/]*list\d+\.htm$|(?:^|[?&])(?:PAGENUM|pageindex)=\d+|(?:^|[?&])totalpage=\d+)",
    re.IGNORECASE,
)
FACULTY_SYSTEM_LIST_URL_RE = re.compile(
    r"/(?:pi|py)?jslb\.jsp\?|/(?:xyjslb|jsjs|jscx|xylb)\.jsp\?",
    re.IGNORECASE,
)
IMAGESCALE_PROFILE_RE = re.compile(
    r"addimg\(\s*['\"][^'\"]*['\"]\s*,\s*['\"](?P<href>[^'\"]+/(?:zh_CN|en)/index\.htm)['\"]\s*,\s*['\"](?P<text>[^'\"]{1,40})['\"]",
    re.IGNORECASE,
)
HTTPS_CANONICAL_HOSTS = {
    "faculty.dlut.edu.cn",
    "faculty-cn.tju.edu.cn",
    "faculty.scut.edu.cn",
    "faculty.scu.edu.cn",
    "faculty.uestc.edu.cn",
    "faculty.tju.edu.cn",
    "jszy.whu.edu.cn",
}
NON_NAME_SUBSTRINGS = (
    "学院",
    "项目",
    "新闻",
    "通知",
    "公告",
    "队伍",
    "教育",
    "教学",
    "科研",
    "党团",
    "院友",
    "机构",
    "中心",
    "基地",
    "平台",
    "师资",
    "教师",
    "导师",
    "教授",
    "院士",
    "名医",
    "列表",
    "详情",
    "更多",
    "首页",
    "登录",
    "搜索",
    "招生",
    "招聘",
    "访客",
    "校历",
    "校友",
    "捐赠",
    "门户",
    "邮箱",
    "期刊",
    "平台",
    "看点",
    "风光",
    "生活",
    "文化",
    "党风",
    "党群",
    "党务",
    "党建",
    "理论",
    "工会",
    "论坛",
    "公文",
    "政策",
    "文件",
    "方案",
    "招考",
    "学生",
    "学工",
    "下载",
    "资料",
    "联系",
    "我们",
    "现任",
    "历任",
    "领导",
    "院长",
    "致辞",
    "院训",
    "院徽",
    "科研",
    "研究",
    "培养",
    "成果",
    "课程",
    "资源",
    "实验室",
    "管理",
    "服务",
    "规章",
    "制度",
    "毕业",
    "留影",
    "年报",
    "暑期",
    "萃英",
    "飞天",
    "访企",
    "拓岗",
    "实习",
    "信息",
    "招就",
    "动态",
    "专业",
    "推介",
    "人员",
    "分工",
    "常用",
    "历史",
    "沿革",
    "党史",
    "学校",
    "本科",
    "国际",
    "合作",
    "交流",
    "认证",
    "就业",
    "讲师",
    "青年",
    "全部",
    "二维码",
)
TYPE_PRIORITY = {
    "university_home": 10,
    "unit_index": 20,
    "profile_portal": 20,
    "faculty_portal": 20,
    "unit_home": 30,
    "faculty_list": 40,
    "profile_index": 40,
    "profile_index_api": 40,
    "teacher_profile": 50,
}


def main() -> int:
    args = parse_args()
    registry = load_registry(args.sources)
    schools = set(args.school or [])
    universities = [
        university
        for university in registry.universities
        if not schools or university.id in schools or university.name_zh in schools
    ]
    if not universities:
        raise SystemExit("No universities selected.")

    errors_path = Path(args.working_root) / "errors.tsv"
    errors_path.parent.mkdir(parents=True, exist_ok=True)
    if not errors_path.exists():
        errors_path.write_text("school\tphase\tsource_id\turl\terror\n", encoding="utf-8")

    summary: list[dict[str, object]] = []
    for university in universities:
        result = crawl_university(args, university, errors_path)
        summary.append(result)
        write_json(Path(args.working_root) / "crawl_summary.json", summary)
        print(
            f"{university.id}: records={result['cache_records']} "
            f"profiles={result['cache_types'].get('teacher_profile', 0)} "
            f"fetched={result['fetched']} skipped={result['skipped']} errors={result['errors']}",
            flush=True,
        )

    write_json(Path(args.working_root) / "crawl_summary.json", summary)
    return 0


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description="Cache official faculty pages for 985 universities.")
    parser.add_argument("--sources", default="configs/985_sources.yaml")
    parser.add_argument("--cache-root", default="data/cache")
    parser.add_argument("--working-root", default="data/working/985")
    parser.add_argument("--school", action="append", default=[], help="School id or Chinese name to process.")
    parser.add_argument("--rounds", type=int, default=2)
    parser.add_argument("--delay-seconds", type=float, default=0.2)
    parser.add_argument("--timeout-seconds", type=float, default=20.0)
    parser.add_argument("--ignore-robots", action="store_true")
    parser.add_argument("--robots-timeout-seconds", type=float, default=5.0)
    parser.add_argument("--refresh", action="store_true")
    parser.add_argument("--max-unit-indexes", type=int, default=40)
    parser.add_argument("--max-units", type=int, default=300)
    parser.add_argument("--max-faculty-lists", type=int, default=1200)
    parser.add_argument("--max-profiles", type=int, default=8000)
    parser.add_argument("--progress-every", type=int, default=200)
    return parser.parse_args()


def crawl_university(args: argparse.Namespace, university, errors_path: Path) -> dict[str, object]:
    school_root = Path(args.cache_root) / university.id
    store = CacheStore(school_root)
    stats = Counter()
    robots_policy = TimeoutRobotsPolicy(
        "AdvisorsDataBot/0.1 (+https://github.com/open-data; research dataset)",
        timeout_seconds=args.robots_timeout_seconds,
    )

    seed_entries = list(university.entries)
    fetch_many(args, seed_entries, store, robots_policy, stats, errors_path, university.id, "seed")

    for round_index in range(1, args.rounds + 1):
        round_dir = Path(args.working_root) / university.id / f"round-{round_index}"
        round_dir.mkdir(parents=True, exist_ok=True)

        unit_indexes = discover_unit_indexes_from_cache(
            school_root,
            university_name_zh=university.name_zh,
            source_id_prefix=f"{university.id}-unit-index",
            allowed_domains=list(university.allowed_domains),
        )
        unit_indexes = limit_sources(unit_indexes, args.max_unit_indexes)
        write_sources(
            unit_indexes,
            round_dir / "discovered_unit_indexes.yaml",
            university,
        )
        fetch_many(
            args,
            to_entries(unit_indexes, university),
            store,
            robots_policy,
            stats,
            errors_path,
            university.id,
            f"round-{round_index}:unit_index",
        )

        units = discover_unit_homes_from_cache(
            school_root,
            university_name_zh=university.name_zh,
            source_id_prefix=f"{university.id}-unit",
            allowed_domains=list(university.allowed_domains),
        )
        units = limit_sources(units, args.max_units)
        write_sources(units, round_dir / "discovered_units.yaml", university)
        fetch_many(
            args,
            to_entries(units, university),
            store,
            robots_policy,
            stats,
            errors_path,
            university.id,
            f"round-{round_index}:unit_home",
        )

        faculty_lists = discover_faculty_lists_from_cache_safe(
            school_root,
            university_name_zh=university.name_zh,
            source_id_prefix=f"{university.id}-faculty-list",
            allowed_domains=list(university.allowed_domains),
        )
        faculty_lists = limit_sources(faculty_lists, args.max_faculty_lists)
        write_sources(faculty_lists, round_dir / "discovered_faculty_lists.yaml", university)
        fetch_many(
            args,
            to_entries(faculty_lists, university),
            store,
            robots_policy,
            stats,
            errors_path,
            university.id,
            f"round-{round_index}:faculty_list",
        )

        profiles = discover_profiles_from_cache_safe(
            school_root,
            university_name_zh=university.name_zh,
            source_id_prefix=f"{university.id}-profile",
            allowed_domains=list(university.allowed_domains),
        )
        profiles = limit_sources(profiles, args.max_profiles)
        write_sources(profiles, round_dir / "discovered_profiles.yaml", university)
        fetch_many(
            args,
            to_entries(profiles, university),
            store,
            robots_policy,
            stats,
            errors_path,
            university.id,
            f"round-{round_index}:teacher_profile",
        )

    cache_types = count_cache_types(store)
    return {
        "school": university.id,
        "university": university.name_zh,
        "fetched": stats["fetched"],
        "skipped": stats["skipped"],
        "errors": stats["errors"],
        "cache_records": sum(cache_types.values()),
        "cache_types": dict(cache_types),
    }


def fetch_many(
    args: argparse.Namespace,
    entries: list[SourceEntry],
    store: CacheStore,
    robots_policy: RobotsPolicy,
    stats: Counter,
    errors_path: Path,
    school_id: str,
    phase: str,
) -> None:
    seen: set[str] = set()
    processed = 0
    total = len(entries)
    for entry in entries:
        normalized = entry.normalized_url
        if normalized in seen:
            continue
        seen.add(normalized)
        processed += 1
        try:
            status = fetch_one(args, entry, store, robots_policy)
            stats[status] += 1
        except Exception as exc:  # noqa: BLE001 - long crawls should keep moving.
            stats["errors"] += 1
            append_error(errors_path, school_id, phase, entry.id, entry.url, repr(exc))
        if args.delay_seconds > 0 and stats["fetched"]:
            time.sleep(args.delay_seconds)
        if args.progress_every > 0 and processed % args.progress_every == 0:
            print(
                f"{school_id} {phase}: processed {processed}/{total} "
                f"fetched={stats['fetched']} skipped={stats['skipped']} errors={stats['errors']}",
                flush=True,
            )


def fetch_one(
    args: argparse.Namespace,
    entry: SourceEntry,
    store: CacheStore,
    robots_policy: RobotsPolicy,
) -> str:
    existing = load_existing_record(store.root, entry.normalized_url)
    if existing and not should_refetch(existing, entry, args.refresh):
        return "skipped"
    fetch_source_entry(
        entry,
        store,
        timeout_seconds=args.timeout_seconds,
        respect_robots=not args.ignore_robots,
        robots_policy=robots_policy,
    )
    return "fetched"


class TimeoutRobotsPolicy:
    def __init__(self, user_agent: str, *, timeout_seconds: float):
        self.user_agent = user_agent
        self.timeout_seconds = timeout_seconds
        self._parsers: dict[str, robotparser.RobotFileParser] = {}

    def can_fetch(self, url: str) -> bool:
        split = urlsplit(url)
        base = f"{split.scheme}://{split.netloc}"
        parser = self._parsers.get(base)
        if parser is None:
            parser = self._read_parser(base)
            self._parsers[base] = parser
        return parser.can_fetch(self.user_agent, url)

    def _read_parser(self, base: str) -> robotparser.RobotFileParser:
        robots_url = urljoin(base, "/robots.txt")
        parser = robotparser.RobotFileParser(robots_url)
        try:
            response = httpx.get(
                robots_url,
                follow_redirects=True,
                timeout=self.timeout_seconds,
                headers={"User-Agent": self.user_agent},
            )
        except httpx.HTTPError:
            parser.allow_all = True
            return parser
        if response.status_code in {401, 403}:
            parser.disallow_all = True
            return parser
        if 400 <= response.status_code < 500:
            parser.allow_all = True
            return parser
        parser.parse(response.text.splitlines())
        return parser


def should_refetch(existing: CacheRecord, entry: SourceEntry, refresh: bool) -> bool:
    if refresh:
        return True
    existing_priority = TYPE_PRIORITY.get(existing.source_type, 0)
    wanted_priority = TYPE_PRIORITY.get(entry.type, 0)
    if wanted_priority > existing_priority:
        return True
    return False


def load_existing_record(cache_root: Path, url: str) -> CacheRecord | None:
    key = cache_key_for_url(normalize_url(url))
    path = cache_root / "metadata" / key[:2] / key[2:4] / f"{key}.json"
    if not path.exists():
        return None
    return CacheRecord(**json.loads(path.read_text(encoding="utf-8")))


def discover_unit_indexes_from_cache(
    cache_root: str | Path,
    *,
    university_name_zh: str,
    source_id_prefix: str,
    allowed_domains: list[str],
) -> list[DiscoveredSource]:
    records = list(CacheStore(cache_root).iter_records())
    discovered: dict[str, DiscoveredSource] = {}
    for record in records:
        if record.university != university_name_zh:
            continue
        if record.source_type not in {"university_home", "unit_index"}:
            continue
        for url, text in iter_links(record, allowed_domains):
            if not UNIT_INDEX_TEXT_RE.search(text):
                continue
            discovered.setdefault(
                url,
                DiscoveredSource(
                    id=source_id(url, prefix=source_id_prefix),
                    url=url,
                    type="unit_index",
                    department=None,
                    status="discovered",
                    notes=f"Discovered from {record.source_type} page.",
                    discovered_from=record.source_url,
                    anchor_text=text,
                ),
            )
    return sorted(discovered.values(), key=lambda item: item.url)


def discover_unit_homes_from_cache(
    cache_root: str | Path,
    *,
    university_name_zh: str,
    source_id_prefix: str,
    allowed_domains: list[str],
) -> list[DiscoveredSource]:
    records = list(CacheStore(cache_root).iter_records())
    discovered: dict[str, DiscoveredSource] = {}
    for record in records:
        if record.university != university_name_zh:
            continue
        if record.source_type not in {"university_home", "unit_index"}:
            continue
        for url, text in iter_links(record, allowed_domains):
            if not _looks_like_unit_text(text):
                continue
            discovered.setdefault(
                url,
                DiscoveredSource(
                    id=source_id(url, prefix=source_id_prefix),
                    url=url,
                    type="unit_home",
                    department=text,
                    status="discovered",
                    notes=f"Discovered from {record.source_type} page.",
                    discovered_from=record.source_url,
                    anchor_text=text,
                ),
            )
    return sorted(discovered.values(), key=lambda item: item.url)


def discover_faculty_lists_from_cache_safe(
    cache_root: str | Path,
    *,
    university_name_zh: str,
    source_id_prefix: str,
    allowed_domains: list[str],
) -> list[DiscoveredSource]:
    records = list(CacheStore(cache_root).iter_records())
    discovered: dict[str, DiscoveredSource] = {}
    for record in records:
        if record.university != university_name_zh:
            continue
        if record.source_type not in {"unit_home", "faculty_portal", "profile_portal", "unit_index", "faculty_list"}:
            continue
        for url, text in iter_links(record, allowed_domains):
            is_faculty_list = _looks_like_faculty_list_text(text)
            is_pagination = (
                record.source_type == "faculty_list"
                and FACULTY_LIST_PAGINATION_TEXT_RE.search(text)
                and FACULTY_LIST_PAGINATION_URL_RE.search(urlsplit(url).path)
            ) or (
                record.source_type == "faculty_list"
                and FACULTY_LIST_PAGINATION_TEXT_RE.search(text)
                and FACULTY_LIST_PAGINATION_URL_RE.search(urlsplit(url).query)
            )
            is_faculty_system_list = (
                record.source_type in {"profile_portal", "faculty_portal", "faculty_list"}
                and FACULTY_SYSTEM_LIST_URL_RE.search(urlsplit(url).path + "?" + urlsplit(url).query)
            )
            if not is_faculty_list and not is_pagination and not is_faculty_system_list:
                continue
            discovered.setdefault(
                url,
                DiscoveredSource(
                    id=source_id(url, prefix=source_id_prefix),
                    url=url,
                    type="faculty_list",
                    department=record.department,
                    status="discovered",
                    notes=f"Discovered from {record.source_type} page.",
                    discovered_from=record.source_url,
                    anchor_text=text,
                ),
            )
    return sorted(discovered.values(), key=lambda item: item.url)


def discover_profiles_from_cache_safe(
    cache_root: str | Path,
    *,
    university_name_zh: str,
    source_id_prefix: str,
    allowed_domains: list[str],
) -> list[DiscoveredSource]:
    records = list(CacheStore(cache_root).iter_records())
    discovered: dict[str, DiscoveredSource] = {}
    for record in records:
        if record.university != university_name_zh:
            continue
        if record.source_type not in {"faculty_list", "profile_index", "profile_portal"}:
            continue
        for url, text in iter_links(record, allowed_domains):
            name_hint = name_hint_from_anchor(text)
            if looks_like_profile_url(url) or (
                name_hint and (looks_like_faculty_detail_link(url) or looks_like_html_page(url))
            ):
                discovered.setdefault(
                    url,
                    DiscoveredSource(
                        id=source_id(url, prefix=source_id_prefix),
                        url=url,
                        type="teacher_profile",
                        department=record.department,
                        status="discovered",
                        notes=f"Discovered from {record.source_type} page.",
                        discovered_from=record.source_url,
                        anchor_text=name_hint or text,
                    ),
                )
    return sorted(discovered.values(), key=lambda item: item.url)


def iter_links(record: CacheRecord, allowed_domains: list[str]) -> list[tuple[str, str]]:
    if not record.cache_path:
        return []
    html_path = Path(record.cache_path)
    if not html_path.exists():
        return []
    try:
        html = html_path.read_text(encoding=record.encoding or "utf-8", errors="replace")
    except OSError:
        return []
    soup = BeautifulSoup(html, "html.parser")
    links: list[tuple[str, str]] = []
    for anchor in soup.find_all("a", href=True):
        href = anchor["href"].strip()
        if SKIP_URL_RE.search(href):
            continue
        text = _clean_anchor_text(anchor.get_text(" ", strip=True))
        if not text or len(text) > 80:
            continue
        try:
            url = canonicalize_discovered_url(normalize_url(urljoin(record.final_url or record.source_url, href)))
        except ValueError:
            continue
        if SKIP_URL_RE.search(url):
            continue
        host = urlsplit(url).hostname or ""
        if not host_matches(host, allowed_domains):
            continue
        links.append((url, text))
    links.extend(iter_embedded_profile_links(html, record.final_url or record.source_url, allowed_domains))
    return links


def iter_embedded_profile_links(html: str, base_url: str, allowed_domains: list[str]) -> list[tuple[str, str]]:
    links: list[tuple[str, str]] = []
    for match in IMAGESCALE_PROFILE_RE.finditer(html):
        text = _clean_anchor_text(match.group("text"))
        if not text or len(text) > 40:
            continue
        try:
            url = canonicalize_discovered_url(normalize_url(urljoin(base_url, match.group("href"))))
        except ValueError:
            continue
        host = urlsplit(url).hostname or ""
        if host_matches(host, allowed_domains):
            links.append((url, text))
    return links


def looks_like_profile_url(url: str) -> bool:
    return bool(PROFILE_PATH_RE.search(urlsplit(url).path))


def canonicalize_discovered_url(url: str) -> str:
    split = urlsplit(url)
    host = split.hostname or ""
    if split.scheme == "http" and host in HTTPS_CANONICAL_HOSTS:
        return "https://" + split.netloc + split.path + (f"?{split.query}" if split.query else "")
    return url


def looks_like_faculty_detail_link(url: str) -> bool:
    path = urlsplit(url).path
    return bool(INFO_PROFILE_PAGE_RE.search(path) or WEBPLUS_PROFILE_PAGE_RE.search(path))


def looks_like_html_page(url: str) -> bool:
    split = urlsplit(url)
    path = split.path
    if re.search(r"(?i)(?:^|/)(?:index|news|kxyj|zs|zs1|xxg|yxsz|szdw1)(?:/|\\.|$)", path):
        return False
    if HTML_PAGE_RE.search(path):
        return True
    suffix = Path(path).suffix.lower()
    return not suffix and path.rstrip("/").count("/") >= 1


def name_hint_from_anchor(anchor_text: str) -> str | None:
    text = _clean_anchor_text(anchor_text)
    text = re.sub(r"[((].*?[))]", "", text)
    text = re.sub(r"\s+", "", text)
    repeat_match = re.match(r"^([\u4e00-\u9fff·]{2,4})\1", text)
    if repeat_match and looks_like_name_anchor(repeat_match.group(1)):
        return repeat_match.group(1)
    title_match = re.match(
        r"^([\u4e00-\u9fff·]{2,4})(?:教授|副教授|研究员|副研究员|讲师|助理教授|"
        r"助理研究员|博士生导师|硕士生导师)",
        text,
    )
    if title_match and looks_like_name_anchor(title_match.group(1)):
        return title_match.group(1)
    return text if looks_like_name_anchor(text) else None


def looks_like_name_anchor(anchor_text: str) -> bool:
    return bool(
        ZH_NAME_RE.fullmatch(anchor_text)
        and not any(token in anchor_text for token in NON_NAME_SUBSTRINGS)
        and not anchor_text.lower().startswith(("http://", "https://"))
    )


def to_entries(sources: list[DiscoveredSource], university) -> list[SourceEntry]:
    return [
        SourceEntry(
            id=source.id,
            university_id=university.id,
            university_name_zh=university.name_zh,
            university_name_en=university.name_en,
            url=source.url,
            type=source.type,
            allowed_domains=university.allowed_domains,
            department=source.department,
            status=source.status,
            notes=f"{source.notes} anchor={source.anchor_text!r}; from={source.discovered_from}",
            name_hint=source.anchor_text if source.type == "teacher_profile" else None,
        )
        for source in sources
    ]


def write_sources(sources: list[DiscoveredSource], path: Path, university) -> None:
    if not sources:
        path.parent.mkdir(parents=True, exist_ok=True)
        path.write_text(
            yaml.safe_dump(
                {
                    "version": 1,
                    "universities": [
                        {
                            "id": university.id,
                            "name_zh": university.name_zh,
                            "name_en": university.name_en,
                            "allowed_domains": list(university.allowed_domains),
                            "entries": [],
                        }
                    ],
                },
                allow_unicode=True,
                sort_keys=False,
            ),
            encoding="utf-8",
        )
        return
    write_discovered_sources_yaml(
        sources,
        path,
        university_id=university.id,
        university_name_zh=university.name_zh,
        university_name_en=university.name_en,
        allowed_domains=list(university.allowed_domains),
    )


def limit_sources(sources: list[DiscoveredSource], limit: int | None) -> list[DiscoveredSource]:
    if limit is None or limit <= 0:
        return sources
    return sources[:limit]


def source_id(url: str, *, prefix: str) -> str:
    split = urlsplit(url)
    slug = re.sub(r"[^A-Za-z0-9]+", "-", f"{split.netloc}{split.path}").strip("-").lower()
    digest = hashlib.sha1(url.encode("utf-8")).hexdigest()[:8]
    return f"{prefix}-{slug[:72]}-{digest}"


def count_cache_types(store: CacheStore) -> Counter:
    counts: Counter = Counter()
    for record in store.iter_records():
        counts[record.source_type] += 1
    return counts


def append_error(path: Path, school_id: str, phase: str, source_id_: str, url: str, error: str) -> None:
    safe_error = error.replace("\t", " ").replace("\n", " ")
    with path.open("a", encoding="utf-8") as handle:
        handle.write(f"{school_id}\t{phase}\t{source_id_}\t{url}\t{safe_error}\n")


def write_json(path: Path, data: object) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")


if __name__ == "__main__":
    raise SystemExit(main())