244 lines
8.1 KiB
Python
244 lines
8.1 KiB
Python
"""
|
|
Generate crawl seeds from an entity's accepted hierarchy.
|
|
|
|
The source truth uses the shared accepted hierarchy tree.
|
|
Configured seed_levels determine which entity levels are emitted.
|
|
"""
|
|
|
|
import argparse
|
|
import json
|
|
import os
|
|
from datetime import datetime, timezone
|
|
from urllib.parse import urldefrag, urlsplit, urlunsplit
|
|
|
|
from pipeline_utils import (
|
|
add_common_args,
|
|
generated_entities_path,
|
|
get_entity,
|
|
hierarchy_path,
|
|
load_config,
|
|
)
|
|
|
|
|
|
VALID_LEVELS = {"faculty", "institute", "chair"}
|
|
|
|
|
|
def normalize_url(url: str) -> str | None:
|
|
"""Return a stable seed URL, or None for missing/invalid truth values."""
|
|
if not isinstance(url, str):
|
|
return None
|
|
|
|
url = url.strip()
|
|
if not url or url.lower() == "none":
|
|
return None
|
|
|
|
url, _ = urldefrag(url)
|
|
parsed = urlsplit(url)
|
|
|
|
if parsed.scheme not in {"http", "https"} or not parsed.hostname:
|
|
return None
|
|
|
|
path = parsed.path.rstrip("/")
|
|
return urlunsplit((parsed.scheme, parsed.netloc, path, parsed.query, ""))
|
|
|
|
|
|
def hostname_is_blocked(hostname: str, blocked_hosts: list[str]) -> bool:
|
|
hostname = hostname.lower().rstrip(".")
|
|
for blocked in blocked_hosts:
|
|
blocked = blocked.lower().rstrip(".")
|
|
if hostname == blocked or hostname.endswith("." + blocked):
|
|
return True
|
|
return False
|
|
|
|
|
|
def hostname_is_allowed(hostname: str, allowed_domains: list[str]) -> bool:
|
|
hostname = hostname.lower().rstrip(".")
|
|
for allowed in allowed_domains:
|
|
allowed = allowed.lower().rstrip(".")
|
|
if hostname == allowed or hostname.endswith("." + allowed):
|
|
return True
|
|
return False
|
|
|
|
|
|
def extract_urls(node: dict) -> list[str]:
|
|
"""Extract all link_de/link_en/link_de_2/... fields from one truth node."""
|
|
urls = []
|
|
for key, value in node.items():
|
|
if key.startswith("link_"):
|
|
url = normalize_url(value)
|
|
if url:
|
|
urls.append(url)
|
|
return urls
|
|
|
|
|
|
def collect_seeds(truth: dict, seed_levels: set[str]) -> list[dict]:
|
|
seeds = []
|
|
|
|
for faculty in truth.get("faculties", []):
|
|
if "faculty" in seed_levels:
|
|
for url in extract_urls(faculty):
|
|
seeds.append({
|
|
"url": url,
|
|
"level": "faculty",
|
|
"name_de": faculty.get("name_de", ""),
|
|
"name_en": faculty.get("name_en", ""),
|
|
})
|
|
|
|
for institute in faculty.get("institutes", []):
|
|
if "institute" in seed_levels:
|
|
for url in extract_urls(institute):
|
|
seeds.append({
|
|
"url": url,
|
|
"level": "institute",
|
|
"name_de": institute.get("name_de", ""),
|
|
"name_en": institute.get("name_en", ""),
|
|
"faculty_de": faculty.get("name_de", ""),
|
|
"faculty_en": faculty.get("name_en", ""),
|
|
})
|
|
|
|
for chair in institute.get("chairs", []):
|
|
if "chair" in seed_levels:
|
|
for url in extract_urls(chair):
|
|
seeds.append({
|
|
"url": url,
|
|
"level": "chair",
|
|
"name_de": chair.get("name_de", ""),
|
|
"name_en": chair.get("name_en", ""),
|
|
"faculty_de": faculty.get("name_de", ""),
|
|
"faculty_en": faculty.get("name_en", ""),
|
|
})
|
|
|
|
for chair in faculty.get("chairs", []):
|
|
if "chair" in seed_levels:
|
|
for url in extract_urls(chair):
|
|
seeds.append({
|
|
"url": url,
|
|
"level": "chair",
|
|
"name_de": chair.get("name_de", ""),
|
|
"name_en": chair.get("name_en", ""),
|
|
"faculty_de": faculty.get("name_de", ""),
|
|
"faculty_en": faculty.get("name_en", ""),
|
|
})
|
|
|
|
return seeds
|
|
|
|
|
|
def collect_accepted_seeds(hierarchy: list[dict], seed_levels: set[str]) -> list[dict]:
|
|
seeds = []
|
|
|
|
def add(node, level, faculty):
|
|
if level not in seed_levels:
|
|
return
|
|
for url in extract_urls(node):
|
|
seed = {
|
|
"url": url,
|
|
"level": level,
|
|
"name_de": node.get("name_de", ""),
|
|
"name_en": node.get("name_en", ""),
|
|
}
|
|
if faculty:
|
|
seed.update(
|
|
faculty_de=faculty.get("name_de", ""),
|
|
faculty_en=faculty.get("name_en", ""),
|
|
)
|
|
seeds.append(seed)
|
|
|
|
for faculty in hierarchy:
|
|
add(faculty, "faculty", None)
|
|
for group in faculty.get("children") or []:
|
|
group_type = group.get("type")
|
|
if group_type == "institutes":
|
|
for institute in group.get("children") or []:
|
|
add(institute, "institute", faculty)
|
|
for chair_group in institute.get("children") or []:
|
|
if chair_group.get("type") == "chairs":
|
|
for chair in chair_group.get("children") or []:
|
|
add(chair, "chair", faculty)
|
|
elif group_type == "chairs":
|
|
for chair in group.get("children") or []:
|
|
add(chair, "chair", faculty)
|
|
|
|
return seeds
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(
|
|
description="Generate generic crawler seed URLs from an entity truth file."
|
|
)
|
|
add_common_args(parser)
|
|
args = parser.parse_args()
|
|
|
|
config = load_config(args.config)
|
|
entity = get_entity(config, args.entity)
|
|
crawl = entity.get("crawl", {})
|
|
|
|
seed_levels = set(crawl.get("seed_levels", ["institute", "chair"]))
|
|
invalid_levels = seed_levels - VALID_LEVELS
|
|
if invalid_levels:
|
|
raise SystemExit(
|
|
f"Invalid seed_levels for '{args.entity}': {sorted(invalid_levels)}. "
|
|
f"Allowed values: {sorted(VALID_LEVELS)}"
|
|
)
|
|
|
|
truth_path = hierarchy_path(config, args.entity)
|
|
output_path = generated_entities_path(config, args.entity)
|
|
|
|
with open(truth_path, encoding="utf-8") as handle:
|
|
truth = json.load(handle)
|
|
|
|
allowed_domains = crawl.get("allowed_domains", [])
|
|
blocked_hosts = crawl.get("banned_hostnames", [])
|
|
|
|
if not allowed_domains:
|
|
raise SystemExit(
|
|
f"Entity '{args.entity}' has no crawl.allowed_domains configuration."
|
|
)
|
|
|
|
seeds = []
|
|
skipped = []
|
|
|
|
seed_records = (
|
|
collect_accepted_seeds(truth, seed_levels)
|
|
if isinstance(truth, list)
|
|
else collect_seeds(truth, seed_levels)
|
|
)
|
|
for seed in seed_records:
|
|
hostname = urlsplit(seed["url"]).hostname
|
|
if hostname_is_blocked(hostname, blocked_hosts):
|
|
skipped.append({"url": seed["url"], "reason": "banned_hostname"})
|
|
continue
|
|
|
|
if not hostname_is_allowed(hostname, allowed_domains):
|
|
skipped.append({"url": seed["url"], "reason": "outside_allowed_domains"})
|
|
continue
|
|
|
|
seeds.append(seed)
|
|
|
|
# Deduplicate by normalized URL while retaining the first metadata record.
|
|
unique_seeds = {}
|
|
for seed in seeds:
|
|
unique_seeds.setdefault(seed["url"], seed)
|
|
|
|
output = {
|
|
"entity": args.entity,
|
|
"display_name": entity.get("display_name", args.entity),
|
|
"source_truth_file": truth_path,
|
|
"generated_at": datetime.now(timezone.utc).isoformat(),
|
|
"seed_levels": sorted(seed_levels),
|
|
"seed_count": len(unique_seeds),
|
|
"skipped_count": len(skipped),
|
|
"seeds": list(unique_seeds.values()),
|
|
"skipped": skipped,
|
|
}
|
|
|
|
os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
|
with open(output_path, "w", encoding="utf-8") as handle:
|
|
json.dump(output, handle, ensure_ascii=False, indent=2)
|
|
|
|
print(f"Generated {len(unique_seeds)} crawl seeds: {output_path}")
|
|
if skipped:
|
|
print(f"Skipped {len(skipped)} invalid, banned, or out-of-scope seed URLs.")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main() |