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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Add per-item Wikipedia citations to tendencies_by_language.yaml.
|
| 3 |
+
|
| 4 |
+
For each snake_case tendency we attempt three lookups in order:
|
| 5 |
+
|
| 6 |
+
1. The target-language Wikipedia opensearch API for the snake_case label
|
| 7 |
+
converted to plain words (e.g. "tahdig_perfection" -> "tahdig").
|
| 8 |
+
2. English Wikipedia opensearch for the same query.
|
| 9 |
+
3. Mark `lookup_status: not_found` and leave the citation slot empty.
|
| 10 |
+
|
| 11 |
+
Writes the enriched file to tendencies_by_language_cited.yaml — preserves
|
| 12 |
+
the existing tendencies_by_language.yaml as-is (no in-place mutation).
|
| 13 |
+
|
| 14 |
+
Wikipedia opensearch is rate-limited; we sleep 0.5s between calls and
|
| 15 |
+
honour Retry-After on 429s.
|
| 16 |
+
"""
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
import json
|
| 20 |
+
import re
|
| 21 |
+
import sys
|
| 22 |
+
import time
|
| 23 |
+
from pathlib import Path
|
| 24 |
+
from typing import Optional
|
| 25 |
+
|
| 26 |
+
import requests
|
| 27 |
+
import yaml
|
| 28 |
+
|
| 29 |
+
PERSONA_DIR = Path(__file__).resolve().parent.parent # persona/
|
| 30 |
+
REPO_ROOT = PERSONA_DIR.parent # kyiv/
|
| 31 |
+
SRC = PERSONA_DIR / "data" / "tendencies_by_language.yaml"
|
| 32 |
+
DEST = PERSONA_DIR / "data" / "tendencies_by_language_cited.yaml"
|
| 33 |
+
LOG = REPO_ROOT / "logs" / f"cite_tendencies_{int(time.time())}.log"
|
| 34 |
+
|
| 35 |
+
WIKIPEDIA_OPENSEARCH = "https://{lang}.wikipedia.org/w/api.php"
|
| 36 |
+
HEADERS = {"User-Agent": "uncgpt-persona-pool/0.2 (research; uncgpt citations)"}
|
| 37 |
+
SLEEP_BETWEEN_CALLS = 0.4
|
| 38 |
+
|
| 39 |
+
_session = requests.Session()
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def log(msg: str) -> None:
|
| 43 |
+
line = f"[{time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())}] {msg}"
|
| 44 |
+
print(line, flush=True)
|
| 45 |
+
LOG.parent.mkdir(parents=True, exist_ok=True)
|
| 46 |
+
with LOG.open("a", encoding="utf-8") as fh:
|
| 47 |
+
fh.write(line + "\n")
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def _query_terms_from_snake(label: str) -> list[str]:
|
| 51 |
+
"""Produce a few search queries from a snake_case identifier.
|
| 52 |
+
|
| 53 |
+
Examples:
|
| 54 |
+
tahdig_perfection -> ["tahdig perfection", "tahdig"]
|
| 55 |
+
poetry_recitation_hafez -> ["poetry recitation hafez", "hafez", "poetry"]
|
| 56 |
+
pub_quiz_nights -> ["pub quiz nights", "pub quiz"]
|
| 57 |
+
"""
|
| 58 |
+
base = label.replace("_", " ")
|
| 59 |
+
tokens = [t for t in re.split(r"\s+", base) if t]
|
| 60 |
+
queries: list[str] = [base]
|
| 61 |
+
if len(tokens) > 1:
|
| 62 |
+
# Try the most-distinctive token last (typically a culture-marked noun)
|
| 63 |
+
queries.append(" ".join(tokens[:-1]))
|
| 64 |
+
queries.append(tokens[-1])
|
| 65 |
+
if len(tokens) > 2:
|
| 66 |
+
queries.append(" ".join(tokens[:2]))
|
| 67 |
+
# Deduplicate while preserving order
|
| 68 |
+
seen = set()
|
| 69 |
+
out = []
|
| 70 |
+
for q in queries:
|
| 71 |
+
ql = q.strip()
|
| 72 |
+
if ql and ql.lower() not in seen:
|
| 73 |
+
seen.add(ql.lower())
|
| 74 |
+
out.append(ql)
|
| 75 |
+
return out
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def _wikipedia_search(lang: str, query: str, *, attempt_cap: int = 3) -> Optional[dict]:
|
| 79 |
+
"""Try Wikipedia opensearch in the given language. Return the top hit dict
|
| 80 |
+
{title, url} or None if no result."""
|
| 81 |
+
params = {
|
| 82 |
+
"action": "opensearch",
|
| 83 |
+
"search": query,
|
| 84 |
+
"limit": 1,
|
| 85 |
+
"namespace": 0,
|
| 86 |
+
"format": "json",
|
| 87 |
+
}
|
| 88 |
+
url = WIKIPEDIA_OPENSEARCH.format(lang=lang)
|
| 89 |
+
for attempt in range(attempt_cap):
|
| 90 |
+
try:
|
| 91 |
+
resp = _session.get(url, params=params, headers=HEADERS, timeout=(8, 12))
|
| 92 |
+
except requests.RequestException as e:
|
| 93 |
+
if attempt >= attempt_cap - 1:
|
| 94 |
+
log(f" ERROR {lang} '{query}': {e}")
|
| 95 |
+
return None
|
| 96 |
+
time.sleep(1.0 * (attempt + 1))
|
| 97 |
+
continue
|
| 98 |
+
if resp.status_code == 429:
|
| 99 |
+
retry = float(resp.headers.get("Retry-After", "4"))
|
| 100 |
+
time.sleep(min(retry + 0.5, 15))
|
| 101 |
+
continue
|
| 102 |
+
if not resp.ok:
|
| 103 |
+
return None
|
| 104 |
+
data = resp.json()
|
| 105 |
+
# opensearch returns [query, [titles], [descs], [urls]]
|
| 106 |
+
if len(data) >= 4 and data[1] and data[3]:
|
| 107 |
+
return {"title": data[1][0], "url": data[3][0]}
|
| 108 |
+
return None
|
| 109 |
+
return None
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def cite_one(label: str, lang: str) -> dict:
|
| 113 |
+
"""Return a citation dict for one tendency label."""
|
| 114 |
+
queries = _query_terms_from_snake(label)
|
| 115 |
+
for q in queries:
|
| 116 |
+
hit = _wikipedia_search(lang, q)
|
| 117 |
+
time.sleep(SLEEP_BETWEEN_CALLS)
|
| 118 |
+
if hit:
|
| 119 |
+
return {
|
| 120 |
+
"label": label,
|
| 121 |
+
"wikipedia_url": hit["url"],
|
| 122 |
+
"wikipedia_title": hit["title"],
|
| 123 |
+
"lookup_lang": lang,
|
| 124 |
+
"lookup_query": q,
|
| 125 |
+
"lookup_status": "found_native",
|
| 126 |
+
}
|
| 127 |
+
# Fall back to English Wikipedia
|
| 128 |
+
for q in queries:
|
| 129 |
+
hit = _wikipedia_search("en", q)
|
| 130 |
+
time.sleep(SLEEP_BETWEEN_CALLS)
|
| 131 |
+
if hit:
|
| 132 |
+
return {
|
| 133 |
+
"label": label,
|
| 134 |
+
"wikipedia_url": hit["url"],
|
| 135 |
+
"wikipedia_title": hit["title"],
|
| 136 |
+
"lookup_lang": "en",
|
| 137 |
+
"lookup_query": q,
|
| 138 |
+
"lookup_status": "found_english_fallback",
|
| 139 |
+
}
|
| 140 |
+
return {
|
| 141 |
+
"label": label,
|
| 142 |
+
"wikipedia_url": None,
|
| 143 |
+
"wikipedia_title": None,
|
| 144 |
+
"lookup_lang": None,
|
| 145 |
+
"lookup_query": queries[0] if queries else label,
|
| 146 |
+
"lookup_status": "not_found",
|
| 147 |
+
}
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def main() -> int:
|
| 151 |
+
data = yaml.safe_load(SRC.read_text(encoding="utf-8"))
|
| 152 |
+
generic = list(data.get("generic", []))
|
| 153 |
+
languages = data.get("languages", {})
|
| 154 |
+
|
| 155 |
+
cited_generic: list[dict] = []
|
| 156 |
+
cited_languages: dict[str, list[dict]] = {}
|
| 157 |
+
|
| 158 |
+
log(f"--- generic ({len(generic)} items) ---")
|
| 159 |
+
for label in generic:
|
| 160 |
+
rec = cite_one(label, "en")
|
| 161 |
+
cited_generic.append(rec)
|
| 162 |
+
status = rec["lookup_status"]
|
| 163 |
+
log(f" {label:<35} -> {status}")
|
| 164 |
+
|
| 165 |
+
for lang, items in languages.items():
|
| 166 |
+
log(f"--- {lang} ({len(items)} items) ---")
|
| 167 |
+
cited_languages[lang] = []
|
| 168 |
+
for label in items:
|
| 169 |
+
rec = cite_one(label, lang)
|
| 170 |
+
cited_languages[lang].append(rec)
|
| 171 |
+
log(f" {lang}:{label:<35} -> {rec['lookup_status']}")
|
| 172 |
+
|
| 173 |
+
out = {
|
| 174 |
+
"license": data.get("license", "CC0"),
|
| 175 |
+
"license_url": data.get("license_url"),
|
| 176 |
+
"source": data.get("source"),
|
| 177 |
+
"citation_methodology": (
|
| 178 |
+
"Each item snake_case label was queried against Wikipedia opensearch "
|
| 179 |
+
"in the target language. On miss we fall back to English Wikipedia. "
|
| 180 |
+
"Items that resolved to a native-language article are tagged "
|
| 181 |
+
"lookup_status=found_native; English fallbacks are flagged "
|
| 182 |
+
"lookup_status=found_english_fallback; items with no Wikipedia "
|
| 183 |
+
"match in either language are flagged lookup_status=not_found for "
|
| 184 |
+
"board review (rename or replace with a citable variant)."
|
| 185 |
+
),
|
| 186 |
+
"generic": cited_generic,
|
| 187 |
+
"languages": cited_languages,
|
| 188 |
+
}
|
| 189 |
+
DEST.write_text(
|
| 190 |
+
yaml.safe_dump(out, allow_unicode=True, sort_keys=False, width=140),
|
| 191 |
+
encoding="utf-8",
|
| 192 |
+
)
|
| 193 |
+
|
| 194 |
+
# Summary report
|
| 195 |
+
from collections import Counter
|
| 196 |
+
|
| 197 |
+
counter = Counter()
|
| 198 |
+
for item in cited_generic:
|
| 199 |
+
counter[item["lookup_status"]] += 1
|
| 200 |
+
for items in cited_languages.values():
|
| 201 |
+
for item in items:
|
| 202 |
+
counter[item["lookup_status"]] += 1
|
| 203 |
+
total = sum(counter.values())
|
| 204 |
+
log("--- summary ---")
|
| 205 |
+
for status, count in counter.most_common():
|
| 206 |
+
log(f" {status}: {count}/{total} ({100*count/total:.1f}%)")
|
| 207 |
+
return 0
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
if __name__ == "__main__":
|
| 211 |
+
sys.exit(main())
|