File size: 5,833 Bytes
3c0bb29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Review Hugging Face source candidates for Polish DynaWord.

This is an audit helper, not a legal opinion. It records HF metadata, README
signals, configured curation decisions, and obvious license warnings.
"""

from __future__ import annotations

import argparse
import json
import re
from pathlib import Path

from huggingface_hub import HfApi, hf_hub_download


WARNING_TERMS = [
    "cc-by-nc",
    "noncommercial",
    "research-only",
    "proprietary",
    "unknown",
    "no license",
]


def read_config(path: Path) -> dict:
    return json.loads(path.read_text(encoding="utf-8"))


def fetch_readme(repo_id: str, cache_dir: Path) -> str:
    cache_dir.mkdir(parents=True, exist_ok=True)
    out = cache_dir / f"{repo_id.replace('/', '__')}__README.md"
    if out.exists():
        return out.read_text(encoding="utf-8", errors="replace")
    try:
        path = hf_hub_download(repo_id=repo_id, repo_type="dataset", filename="README.md")
        text = Path(path).read_text(encoding="utf-8", errors="replace")
    except Exception as exc:
        text = f"README_DOWNLOAD_ERROR: {type(exc).__name__}: {exc}"
    out.write_text(text, encoding="utf-8")
    return text


def extract_license_tags(tags: list[str]) -> list[str]:
    return [tag.removeprefix("license:") for tag in tags if tag.startswith("license:")]


def extract_language_tags(tags: list[str]) -> list[str]:
    return [tag.removeprefix("language:") for tag in tags if tag.startswith("language:")]


def readme_license_lines(readme: str) -> list[str]:
    lines = []
    for line in readme.splitlines():
        if re.search(r"license|licen|public domain|copyright|cc-by|cc0|apache|mit", line, re.I):
            clean = re.sub(r"\s+", " ", line).strip()
            if clean:
                lines.append(clean)
        if len(lines) >= 12:
            break
    return lines


def warnings_for(license_tags: list[str], readme: str) -> list[str]:
    haystack = " ".join(license_tags).lower() + "\n" + readme[:20000].lower()
    return sorted({term for term in WARNING_TERMS if term in haystack})


def review_candidate(api: HfApi, candidate: dict, cache_dir: Path) -> dict:
    repo_id = candidate["repo_id"]
    info = api.dataset_info(repo_id, files_metadata=False)
    tags = info.tags or []
    readme = fetch_readme(repo_id, cache_dir)
    files = [s.rfilename for s in (info.siblings or [])[:30]]
    return {
        "repo_id": repo_id,
        "configured_decision": candidate.get("decision", ""),
        "target_bucket": candidate.get("target_bucket", ""),
        "priority": candidate.get("priority", ""),
        "notes": candidate.get("notes", ""),
        "gated": getattr(info, "gated", None),
        "private": info.private,
        "downloads": getattr(info, "downloads", None),
        "license_tags": extract_license_tags(tags),
        "language_tags": extract_language_tags(tags),
        "size_tags": [tag.removeprefix("size_categories:") for tag in tags if tag.startswith("size_categories:")],
        "task_tags": [tag.removeprefix("task_categories:") for tag in tags if tag.startswith("task_categories:")],
        "readme_license_lines": readme_license_lines(readme),
        "warnings": warnings_for(extract_license_tags(tags), readme),
        "sample_files": files,
    }


def write_json(rows: list[dict], out_path: Path) -> None:
    out_path.parent.mkdir(parents=True, exist_ok=True)
    out_path.write_text(json.dumps(rows, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")


def write_markdown(rows: list[dict], out_path: Path) -> None:
    lines = [
        "# Source candidate audit",
        "",
        "| repo | decision | bucket | license tags | gated | warnings |",
        "|---|---|---|---|---:|---|",
    ]
    for row in rows:
        lines.append(
            f"| `{row['repo_id']}` | `{row['configured_decision']}` | `{row['target_bucket']}` | "
            f"`{', '.join(row['license_tags']) or 'none'}` | `{row['gated']}` | "
            f"`{', '.join(row['warnings']) or '-'}` |"
        )

    for row in rows:
        lines.extend([
            "",
            f"## {row['repo_id']}",
            "",
            f"- decision: `{row['configured_decision']}`",
            f"- bucket: `{row['target_bucket']}`",
            f"- priority: `{row['priority']}`",
            f"- license tags: `{', '.join(row['license_tags']) or 'none'}`",
            f"- language tags: `{', '.join(row['language_tags']) or 'none'}`",
            f"- gated: `{row['gated']}`",
            f"- notes: {row['notes']}",
            "",
            "README/license signals:",
        ])
        if row["readme_license_lines"]:
            for line in row["readme_license_lines"]:
                lines.append(f"- {line}")
        else:
            lines.append("- no obvious README license lines found")

    out_path.parent.mkdir(parents=True, exist_ok=True)
    out_path.write_text("\n".join(lines) + "\n", encoding="utf-8")


def parse_args() -> argparse.Namespace:
    ap = argparse.ArgumentParser()
    ap.add_argument("--config", type=Path, default=Path("configs/source_candidates_v0_3.json"))
    ap.add_argument("--readme-cache", type=Path, default=Path("artifacts/hf_readmes"))
    ap.add_argument("--out-json", type=Path, default=Path("artifacts/source_candidate_audit_v0_3.json"))
    ap.add_argument("--out-md", type=Path, default=Path("artifacts/source_candidate_audit_v0_3.md"))
    return ap.parse_args()


def main() -> None:
    args = parse_args()
    config = read_config(args.config)
    api = HfApi()
    rows = [review_candidate(api, c, args.readme_cache) for c in config["candidates"]]
    write_json(rows, args.out_json)
    write_markdown(rows, args.out_md)
    print(f"wrote: {args.out_json}")
    print(f"wrote: {args.out_md}")


if __name__ == "__main__":
    main()