Download code/e5cb5ca/src/domain_blocklist.py from Podtech/abeja-cc-ja-cleaned: direct link, hf CLI and curl.
- Browser
- Download file 15.7 kB
-
https://huggingface.co/datasets/Podtech/abeja-cc-ja-cleaned/resolve/main/code/e5cb5ca/src/domain_blocklist.py
- Command line
-
hf download hf://datasets/Podtech/abeja-cc-ja-cleaned/code/e5cb5ca/src/domain_blocklist.py
-
curl -L -o domain_blocklist.py https://huggingface.co/datasets/Podtech/abeja-cc-ja-cleaned/resolve/main/code/e5cb5ca/src/domain_blocklist.py
15.7 kB
| """URLのドメインをブロックリストと照合する。 | |
| UT1 blacklists(トゥールーズ・キャピトル大学、CC BY-SA)のカテゴリ別リストと、 | |
| このリポジトリで管理するドメインリスト・ドメイン名規則を統合する。適用した | |
| リストの出典・取得日時・SHA-256・件数はマニフェストとして summary.json に | |
| 記録する(監査項目10「適用したリストを記録」)。 | |
| 取得:: | |
| python domain_blocklist.py fetch --dest ../data/blocklists/ut1 | |
| 確認:: | |
| python domain_blocklist.py check https://example.com/path ... | |
| 設定は ``blocklists/blocklist_config.json`` にあり、UT1カテゴリごとに | |
| ``delete``(削除)か ``flag``(記録のみ)を指定する。 | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import hashlib | |
| import io | |
| import json | |
| import re | |
| import tarfile | |
| import unicodedata | |
| import urllib.error | |
| import urllib.request | |
| from dataclasses import asdict, dataclass | |
| from datetime import datetime, timezone | |
| from pathlib import Path | |
| from typing import Any, Iterable | |
| from urllib.parse import urlparse | |
| UT1_DOWNLOAD_URL = "https://dsi.ut-capitole.fr/blacklists/download/{category}.tar.gz" | |
| UT1_MIRROR_URL = "https://raw.githubusercontent.com/olbat/ut1-blacklists/master/blacklists/{category}/{member}" | |
| UT1_LICENSE = "CC BY-SA 4.0 (Université Toulouse Capitole, Fabrice Prigent)" | |
| CONFIG_FILE = "blocklist_config.json" | |
| MANIFEST_FILE = "manifest.json" | |
| USER_AGENT = "MHI_Dataset-domain-blocklist/1.0" | |
| class BlocklistSource: | |
| """適用したリスト1件分のメタデータ。summary.json にそのまま記録する。""" | |
| name: str | |
| kind: str # ut1 | local_domains | local_rules | |
| action: str # delete | flag | |
| entries: int | |
| path: str | |
| license: str = "" | |
| source_url: str | None = None | |
| sha256: str | None = None | |
| fetched_at_utc: str | None = None | |
| def normalize_host(url: Any) -> str | None: | |
| """URLからホスト名を取り出す。小文字化し、ポートと末尾のドットを除く。""" | |
| if not url: | |
| return None | |
| text = unicodedata.normalize("NFKC", str(url)).strip().lower() | |
| if "://" not in text: | |
| text = "http://" + text | |
| try: | |
| host = urlparse(text).hostname | |
| except ValueError: | |
| return None | |
| if not host: | |
| return None | |
| return host.strip(".") | |
| def host_suffixes(host: str) -> list[str]: | |
| """``a.b.example.com`` → ``[a.b.example.com, b.example.com, example.com]``(TLD単独は除く)。""" | |
| parts = host.split(".") | |
| return [".".join(parts[index:]) for index in range(len(parts) - 1)] | |
| def _sha256(data: bytes) -> str: | |
| return hashlib.sha256(data).hexdigest() | |
| def _download(url: str, timeout: int) -> bytes: | |
| request = urllib.request.Request(url, headers={"User-Agent": USER_AGENT}) | |
| with urllib.request.urlopen(request, timeout=timeout) as response: | |
| return response.read() | |
| def _count_entries(content: bytes) -> int: | |
| return sum(1 for line in content.splitlines() if line.strip() and not line.startswith(b"#")) | |
| def fetch_ut1(categories: Iterable[str], dest: Path, timeout: int = 300, prefer_mirror: bool = False) -> dict[str, Any]: | |
| """UT1のカテゴリ別tarballを取得し、domains/urls を展開してマニフェストを書く。 | |
| 公式サイトが応答しない場合はGitHubミラー(olbat/ut1-blacklists)へ | |
| フォールバックする。どちらから取得したかはマニフェストに残る。 | |
| """ | |
| dest.mkdir(parents=True, exist_ok=True) | |
| manifest: dict[str, Any] = { | |
| "source": "UT1 blacklists", | |
| "license": UT1_LICENSE, | |
| "fetched_at_utc": datetime.now(timezone.utc).isoformat(), | |
| "categories": {}, | |
| } | |
| for category in categories: | |
| entry: dict[str, Any] = {} | |
| members: dict[str, bytes] = {} | |
| data: bytes | None = None | |
| if not prefer_mirror: | |
| official_url = UT1_DOWNLOAD_URL.format(category=category) | |
| try: | |
| data = _download(official_url, timeout) | |
| entry["source_url"] = official_url | |
| except (urllib.error.URLError, TimeoutError, OSError) as error: | |
| entry["official_error"] = str(error) | |
| if data is not None: | |
| entry["sha256"] = _sha256(data) | |
| entry["bytes"] = len(data) | |
| with tarfile.open(fileobj=io.BytesIO(data), mode="r:gz") as archive: | |
| for member in archive.getmembers(): | |
| name = Path(member.name).name | |
| if name in ("domains", "urls") and member.isfile(): | |
| handle = archive.extractfile(member) | |
| if handle is not None: | |
| members[name] = handle.read() | |
| else: | |
| for name in ("domains", "urls"): | |
| mirror_url = UT1_MIRROR_URL.format(category=category, member=name) | |
| try: | |
| members[name] = _download(mirror_url, timeout) | |
| except urllib.error.HTTPError as error: | |
| if error.code != 404: | |
| raise | |
| entry["source_url"] = UT1_MIRROR_URL.format(category=category, member="{domains,urls}") | |
| entry["sha256"] = _sha256(b"".join(members[name] for name in sorted(members))) | |
| entry["bytes"] = sum(len(value) for value in members.values()) | |
| if "domains" not in members: | |
| raise RuntimeError(f"UT1カテゴリ {category} の domains を取得できませんでした") | |
| category_dir = dest / category | |
| category_dir.mkdir(parents=True, exist_ok=True) | |
| for name, content in members.items(): | |
| (category_dir / name).write_bytes(content) | |
| entry[f"{name}_entries"] = _count_entries(content) | |
| manifest["categories"][category] = entry | |
| (dest / MANIFEST_FILE).write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") | |
| return manifest | |
| def _read_list_lines(path: Path) -> list[str]: | |
| lines: list[str] = [] | |
| for raw_line in path.read_text(encoding="utf-8", errors="replace").splitlines(): | |
| line = raw_line.strip() | |
| if line and not line.startswith("#"): | |
| lines.append(line) | |
| return lines | |
| class DomainBlocklist: | |
| """ドメイン一致(親ドメインを含む)、URL接頭辞一致、ドメイン名規則の照合。""" | |
| def __init__(self) -> None: | |
| self.sources: list[BlocklistSource] = [] | |
| self._domain_index: dict[str, list[str]] = {} | |
| self._url_index: dict[str, list[tuple[str, str]]] = {} | |
| self._rules: list[tuple[str, re.Pattern[str], str]] = [] | |
| self._actions: dict[str, str] = {} | |
| self._allowlist: set[str] = set() | |
| self._allowlist_source: str | None = None | |
| def add_domains(self, source: BlocklistSource, domains: Iterable[str]) -> None: | |
| self.sources.append(source) | |
| self._actions[source.name] = source.action | |
| for domain in domains: | |
| self._domain_index.setdefault(domain.lower(), []).append(source.name) | |
| def add_urls(self, source_name: str, urls: Iterable[str]) -> None: | |
| for raw in urls: | |
| entry = raw.lower().strip("/") | |
| host = entry.split("/", 1)[0] | |
| self._url_index.setdefault(host, []).append((entry, source_name)) | |
| def add_rules(self, source: BlocklistSource, rules: Iterable[tuple[str, str]]) -> None: | |
| self.sources.append(source) | |
| self._actions[source.name] = source.action | |
| for label, expression in rules: | |
| self._rules.append((label, re.compile(expression), source.name)) | |
| def add_allowlist(self, source: BlocklistSource, domains: Iterable[str]) -> None: | |
| """UT1由来のドメイン一致を適用しないドメイン(プラットフォーム等)。""" | |
| self.sources.append(source) | |
| self._actions[source.name] = source.action | |
| self._allowlist_source = source.name | |
| self._allowlist.update(domain.lower() for domain in domains) | |
| def load(cls, blocklist_dir: Path, cache_dir: Path | None) -> "DomainBlocklist": | |
| config = json.loads((blocklist_dir / CONFIG_FILE).read_text(encoding="utf-8")) | |
| blocklist = cls() | |
| categories: dict[str, str] = config.get("ut1", {}).get("categories", {}) | |
| if categories: | |
| if cache_dir is None or not (cache_dir / MANIFEST_FILE).exists(): | |
| raise FileNotFoundError( | |
| f"UT1ブロックリストが未取得です: {cache_dir}. 先に " | |
| f"`python {Path(__file__).name} fetch --dest {cache_dir}` を実行してください。" | |
| ) | |
| manifest = json.loads((cache_dir / MANIFEST_FILE).read_text(encoding="utf-8")) | |
| for category, action in categories.items(): | |
| meta = manifest["categories"].get(category) | |
| domains_path = cache_dir / category / "domains" | |
| if meta is None or not domains_path.exists(): | |
| raise FileNotFoundError(f"UT1カテゴリ {category} が取得されていません: {domains_path}") | |
| domains = _read_list_lines(domains_path) | |
| source = BlocklistSource( | |
| name=f"ut1:{category}", | |
| kind="ut1", | |
| action=action, | |
| entries=len(domains), | |
| path=str(domains_path), | |
| license=manifest.get("license", UT1_LICENSE), | |
| source_url=meta.get("source_url"), | |
| sha256=meta.get("sha256"), | |
| fetched_at_utc=manifest.get("fetched_at_utc"), | |
| ) | |
| blocklist.add_domains(source, domains) | |
| urls_path = cache_dir / category / "urls" | |
| if urls_path.exists(): | |
| blocklist.add_urls(source.name, _read_list_lines(urls_path)) | |
| local = config.get("local", {}) | |
| if local.get("allowlist"): | |
| path = blocklist_dir / local["allowlist"] | |
| domains = [line.split()[0].lower() for line in _read_list_lines(path)] | |
| blocklist.add_allowlist( | |
| BlocklistSource( | |
| name="local:allowlist", | |
| kind="local_allowlist", | |
| action="allow", | |
| entries=len(domains), | |
| path=str(path), | |
| license="repository", | |
| sha256=_sha256(path.read_bytes()), | |
| ), | |
| domains, | |
| ) | |
| if local.get("domains"): | |
| path = blocklist_dir / local["domains"] | |
| domains = [line.split()[0].lower() for line in _read_list_lines(path)] | |
| source = BlocklistSource( | |
| name="local:domains", | |
| kind="local_domains", | |
| action=local.get("action", "delete"), | |
| entries=len(domains), | |
| path=str(path), | |
| license="repository", | |
| sha256=_sha256(path.read_bytes()), | |
| ) | |
| blocklist.add_domains(source, domains) | |
| if local.get("rules"): | |
| path = blocklist_dir / local["rules"] | |
| rules: list[tuple[str, str]] = [] | |
| for line in _read_list_lines(path): | |
| label, _, expression = line.partition("\t") | |
| if not expression: | |
| raise ValueError(f"規則の形式が不正です(ラベル<TAB>正規表現): {line}") | |
| rules.append((label.strip(), expression.strip())) | |
| source = BlocklistSource( | |
| name="local:rules", | |
| kind="local_rules", | |
| action=local.get("action", "delete"), | |
| entries=len(rules), | |
| path=str(path), | |
| license="repository", | |
| sha256=_sha256(path.read_bytes()), | |
| ) | |
| blocklist.add_rules(source, rules) | |
| return blocklist | |
| def match(self, url: Any) -> list[dict[str, Any]]: | |
| host = normalize_host(url) | |
| if not host: | |
| return [] | |
| results: list[dict[str, Any]] = [] | |
| seen: set[tuple[str, str]] = set() | |
| def add(source_name: str, matched: str, kind: str) -> None: | |
| key = (source_name, matched) | |
| if key not in seen: | |
| seen.add(key) | |
| results.append({"source": source_name, "action": self._actions[source_name], "matched": matched, "kind": kind}) | |
| suffixes = host_suffixes(host) | |
| allowed = next((suffix for suffix in suffixes if suffix in self._allowlist), None) | |
| for suffix in suffixes: | |
| for source_name in self._domain_index.get(suffix, ()): | |
| if allowed is not None and source_name.startswith("ut1:"): | |
| add(self._allowlist_source or "local:allowlist", f"{allowed} (suppressed {source_name})", "allowlist") | |
| continue | |
| add(source_name, suffix, "domain") | |
| if self._url_index and allowed is None: | |
| path = urlparse(unicodedata.normalize("NFKC", str(url)).strip().lower()).path or "/" | |
| full = host + path.rstrip("/") | |
| for suffix in suffixes: | |
| for entry, source_name in self._url_index.get(suffix, ()): | |
| if full == entry or full.startswith(entry + "/"): | |
| add(source_name, entry, "url") | |
| for label, pattern, source_name in self._rules: | |
| if pattern.search(host): | |
| add(source_name, f"{label}:{pattern.pattern}", "rule") | |
| return results | |
| def manifest(self) -> list[dict[str, Any]]: | |
| return [asdict(source) for source in self.sources] | |
| def main(argv: list[str] | None = None) -> None: | |
| here = Path(__file__).resolve().parent | |
| parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) | |
| sub = parser.add_subparsers(dest="command", required=True) | |
| fetch = sub.add_parser("fetch", help="UT1のカテゴリ別リストを取得する") | |
| fetch.add_argument("--dest", type=Path, required=True) | |
| fetch.add_argument("--config", type=Path, default=here / "blocklists" / CONFIG_FILE) | |
| fetch.add_argument("--category", action="append", default=None, help="省略時は設定ファイルの全カテゴリ") | |
| fetch.add_argument("--mirror", action="store_true", help="公式サイトではなくGitHubミラーから取得する") | |
| fetch.add_argument("--timeout", type=int, default=300) | |
| check = sub.add_parser("check", help="URLを照合して結果を表示する") | |
| check.add_argument("urls", nargs="+") | |
| check.add_argument("--blocklist-dir", type=Path, default=here / "blocklists") | |
| check.add_argument("--cache-dir", type=Path, default=here.parents[0] / "data" / "blocklists" / "ut1") | |
| args = parser.parse_args(argv) | |
| if args.command == "fetch": | |
| config = json.loads(args.config.read_text(encoding="utf-8")) | |
| categories = args.category or list(config.get("ut1", {}).get("categories", {})) | |
| manifest = fetch_ut1(categories, args.dest, timeout=args.timeout, prefer_mirror=args.mirror) | |
| summary = {category: {key: value for key, value in meta.items() if key != "sha256"} for category, meta in manifest["categories"].items()} | |
| print(json.dumps(summary, ensure_ascii=False, indent=2)) | |
| else: | |
| blocklist = DomainBlocklist.load(args.blocklist_dir, args.cache_dir) | |
| for url in args.urls: | |
| print(url, json.dumps(blocklist.match(url), ensure_ascii=False)) | |
| if __name__ == "__main__": | |
| main() | |