polish-dynaword / src /review_source_candidates.py
kacperwikiel's picture
Add v0.3 source license review and quality mix workflow
3c0bb29
Raw
History Blame Contribute Delete
5.83 kB
#!/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()