| """ |
| Wiktionary Verification Script (v2 - with corrected title building) |
| Verifies that entries sourced from Wiktionary actually exist on Wiktionary |
| by querying the MediaWiki API. |
| |
| Key fixes from v1: |
| - Preserve trailing dashes for reconstruction forms (PIE, Semitic, etc.) |
| - Use "Proto-Hellenic" instead of "Proto-Greek" for grk-pro |
| - Batch queries (up to 50 titles per API call) for efficiency |
| """ |
|
|
| import csv |
| import json |
| import random |
| import sys |
| import time |
| from pathlib import Path |
|
|
| |
| if sys.platform == "win32": |
| sys.stdout.reconfigure(encoding="utf-8", errors="replace") |
| sys.stderr.reconfigure(encoding="utf-8", errors="replace") |
|
|
| import requests |
|
|
| LEXICON_DIR = Path(r"C:\Users\alvin\hf-ancient-scripts\data\training\lexicons") |
| API_URL = "https://en.wiktionary.org/w/api.php" |
| SAMPLE_SIZE = 20 |
| RATE_LIMIT = 0.5 |
|
|
| |
| SESSION = requests.Session() |
| SESSION.headers.update({ |
| "User-Agent": "AncientScriptsVerifier/1.0 (https://github.com/; academic research) python-requests", |
| }) |
|
|
| |
| |
| RECONSTRUCTION_LANGS = { |
| "ine-pro": "Proto-Indo-European", |
| "sem-pro": "Proto-Semitic", |
| "ccs-pro": "Proto-Kartvelian", |
| "dra-pro": "Proto-Dravidian", |
| "grk-pro": "Proto-Hellenic", |
| } |
|
|
| |
| LANG_NAMES = { |
| "hit": "Hittite", |
| "uga": "Ugaritic", |
| "phn": "Phoenician", |
| "ave": "Avestan", |
| "peo": "Old Persian", |
| "xpg": "Phrygian", |
| "xle": "Lemnian", |
| "cms": "Messapic", |
| "elx": "Elamite", |
| "ett": "Etruscan", |
| "xcr": "Carian", |
| "xlc": "Lycian", |
| "xld": "Lydian", |
| "xlw": "Luwian", |
| "xrr": "Raetic", |
| "xur": "Urartian", |
| "txb": "Tocharian B", |
| "xto": "Tocharian A", |
| "xhu": "Hurrian", |
| "ine-pro": "Proto-Indo-European", |
| "sem-pro": "Proto-Semitic", |
| "ccs-pro": "Proto-Kartvelian", |
| "dra-pro": "Proto-Dravidian", |
| "grk-pro": "Proto-Greek (Proto-Hellenic on Wiktionary)", |
| } |
|
|
|
|
| def load_wiktionary_entries(lang_code: str) -> list[dict]: |
| """Load entries from a TSV where Source contains 'wiktionary'.""" |
| tsv_path = LEXICON_DIR / f"{lang_code}.tsv" |
| entries = [] |
| with open(tsv_path, "r", encoding="utf-8") as f: |
| reader = csv.DictReader(f, delimiter="\t") |
| for row in reader: |
| src = row.get("Source", "") |
| if "wiktionary" in src.lower(): |
| entries.append(row) |
| return entries |
|
|
|
|
| def build_wiktionary_title(word: str, lang_code: str) -> str: |
| """Build the Wiktionary page title for a given word and language. |
| |
| For reconstruction languages, uses Reconstruction: namespace. |
| IMPORTANT: Trailing dashes are PRESERVED for reconstruction forms, |
| as Wiktionary uses them in page titles (e.g., h₃rewk- not h₃rewk). |
| """ |
| clean = word.strip() |
|
|
| if lang_code in RECONSTRUCTION_LANGS: |
| lang_name = RECONSTRUCTION_LANGS[lang_code] |
| |
| stem = clean.lstrip("*").strip() |
| return f"Reconstruction:{lang_name}/{stem}" |
|
|
| |
| |
| clean = clean.lstrip("-") |
| return clean |
|
|
|
|
| def query_wiktionary_batch(titles: list[str]) -> dict[str, bool]: |
| """Query Wiktionary API for up to 50 titles at once. |
| Returns dict mapping title -> exists (bool). |
| """ |
| results = {} |
| for i in range(0, len(titles), 50): |
| batch = titles[i:i + 50] |
| params = { |
| "action": "query", |
| "titles": "|".join(batch), |
| "format": "json", |
| } |
| try: |
| resp = SESSION.get(API_URL, params=params, timeout=15) |
| resp.raise_for_status() |
| data = resp.json() |
| pages = data.get("query", {}).get("pages", {}) |
|
|
| |
| normalized = {} |
| for n in data.get("query", {}).get("normalized", []): |
| normalized[n["to"]] = n["from"] |
|
|
| for page_id, page_info in pages.items(): |
| api_title = page_info.get("title", "") |
| exists = int(page_id) != -1 and "missing" not in page_info |
| orig_title = normalized.get(api_title, api_title) |
| results[orig_title] = exists |
| results[api_title] = exists |
|
|
| except Exception as e: |
| for t in batch: |
| results[t] = False |
| print(f" API error for batch: {e}") |
|
|
| if i + 50 < len(titles): |
| time.sleep(RATE_LIMIT) |
|
|
| return results |
|
|
|
|
| def verify_language(lang_code: str, rng: random.Random) -> dict: |
| """Verify a sample of entries for one language.""" |
| entries = load_wiktionary_entries(lang_code) |
| if not entries: |
| return { |
| "lang": lang_code, |
| "lang_name": LANG_NAMES.get(lang_code, lang_code), |
| "total_entries": 0, |
| "sampled": 0, |
| "verified": 0, |
| "not_found": 0, |
| "verification_rate": 0, |
| "results": [], |
| } |
|
|
| sample_size = min(SAMPLE_SIZE, len(entries)) |
| sample = rng.sample(entries, sample_size) |
|
|
| |
| word_to_title = {} |
| for entry in sample: |
| word = entry["Word"] |
| title = build_wiktionary_title(word, lang_code) |
| word_to_title[word] = title |
|
|
| |
| unique_titles = list(set(word_to_title.values())) |
| existence_map = query_wiktionary_batch(unique_titles) |
|
|
| |
| results = [] |
| for entry in sample: |
| word = entry["Word"] |
| title = word_to_title[word] |
| exists = existence_map.get(title, False) |
| results.append({ |
| "original_word": word, |
| "query_title": title, |
| "exists": exists, |
| }) |
|
|
| verified = sum(1 for r in results if r["exists"]) |
| not_found = sum(1 for r in results if not r["exists"]) |
|
|
| return { |
| "lang": lang_code, |
| "lang_name": LANG_NAMES.get(lang_code, lang_code), |
| "total_entries": len(entries), |
| "sampled": sample_size, |
| "verified": verified, |
| "not_found": not_found, |
| "verification_rate": verified / sample_size * 100 if sample_size > 0 else 0, |
| "results": results, |
| } |
|
|
|
|
| def main(): |
| rng = random.Random(42) |
|
|
| |
| all_langs = [] |
| for tsv in sorted(LEXICON_DIR.glob("*.tsv")): |
| lang_code = tsv.stem |
| with open(tsv, "r", encoding="utf-8") as f: |
| content = f.read() |
| if "\twiktionary" in content.lower(): |
| all_langs.append(lang_code) |
|
|
| print(f"Found {len(all_langs)} languages with Wiktionary sources: {', '.join(all_langs)}") |
| print(f"Sampling up to {SAMPLE_SIZE} entries per language") |
| print("=" * 100) |
|
|
| all_results = [] |
| total_sampled = 0 |
| total_verified = 0 |
| total_not_found = 0 |
| flagged_words = [] |
|
|
| for i, lang_code in enumerate(all_langs): |
| print(f"\n[{i+1}/{len(all_langs)}] Verifying {lang_code} ({LANG_NAMES.get(lang_code, '?')})...") |
| result = verify_language(lang_code, rng) |
| all_results.append(result) |
|
|
| total_sampled += result["sampled"] |
| total_verified += result["verified"] |
| total_not_found += result["not_found"] |
|
|
| for r in result["results"]: |
| if not r["exists"]: |
| flagged_words.append({ |
| "lang": lang_code, |
| "lang_name": LANG_NAMES.get(lang_code, lang_code), |
| "word": r["original_word"], |
| "query_title": r["query_title"], |
| }) |
|
|
| |
| print(f" Total entries: {result['total_entries']}, Sampled: {result['sampled']}, " |
| f"Verified: {result['verified']}, Not found: {result['not_found']} " |
| f"({result['verification_rate']:.0f}% verified)") |
| if result["not_found"] > 0: |
| missing = [r for r in result["results"] if not r["exists"]] |
| for m in missing[:5]: |
| print(f" NOT FOUND: '{m['original_word']}' (queried as: '{m['query_title']}')") |
| if len(missing) > 5: |
| print(f" ... and {len(missing) - 5} more") |
|
|
| |
| print("\n" + "=" * 100) |
| print("SUMMARY") |
| print("=" * 100) |
| print(f"\nTotal languages checked: {len(all_langs)}") |
| print(f"Total entries sampled: {total_sampled}") |
| print(f"Total verified on Wiktionary: {total_verified}") |
| print(f"Total NOT found: {total_not_found}") |
| if total_sampled > 0: |
| print(f"Overall verification rate: {total_verified / total_sampled * 100:.1f}%") |
|
|
| print("\n" + "-" * 100) |
| print("PER-LANGUAGE BREAKDOWN (sorted by verification rate)") |
| print("-" * 100) |
| header = f"{'Lang':<10} {'Name':<42} {'Total':<8} {'Sampled':<9} {'Verified':<9} {'Not Found':<10} {'Rate':<8}" |
| print(header) |
| print("-" * 100) |
| for r in sorted(all_results, key=lambda x: x["verification_rate"]): |
| print(f"{r['lang']:<10} {r['lang_name']:<42} {r['total_entries']:<8} {r['sampled']:<9} " |
| f"{r['verified']:<9} {r['not_found']:<10} {r['verification_rate']:.0f}%") |
|
|
| |
| high_confidence = [r for r in all_results if r["verification_rate"] >= 80] |
| medium_confidence = [r for r in all_results if 40 <= r["verification_rate"] < 80] |
| low_confidence = [r for r in all_results if r["verification_rate"] < 40] |
|
|
| print("\n" + "=" * 100) |
| print("INTERPRETATION") |
| print("=" * 100) |
|
|
| if high_confidence: |
| print(f"\nHIGH CONFIDENCE (>=80% verified) - {len(high_confidence)} languages:") |
| print(" These entries are strongly validated as real Wiktionary content.") |
| for r in sorted(high_confidence, key=lambda x: -x["verification_rate"]): |
| print(f" {r['lang']:<10} {r['lang_name']:<40} {r['verification_rate']:.0f}%") |
|
|
| if medium_confidence: |
| print(f"\nMEDIUM CONFIDENCE (40-79% verified) - {len(medium_confidence)} languages:") |
| print(" Many entries verified, but some may use different transliteration/spelling conventions.") |
| print(" The unverified entries may still be real but use non-standard forms.") |
| for r in sorted(medium_confidence, key=lambda x: -x["verification_rate"]): |
| print(f" {r['lang']:<10} {r['lang_name']:<40} {r['verification_rate']:.0f}%") |
|
|
| if low_confidence: |
| print(f"\nLOW CONFIDENCE (<40% verified) - {len(low_confidence)} languages:") |
| print(" These may be from Wiktionary appendices/categories rather than individual pages,") |
| print(" or use significantly different transliteration conventions than Wiktionary page titles.") |
| for r in sorted(low_confidence, key=lambda x: -x["verification_rate"]): |
| print(f" {r['lang']:<10} {r['lang_name']:<40} {r['verification_rate']:.0f}%") |
|
|
| if flagged_words: |
| print("\n" + "-" * 100) |
| print(f"ALL FLAGGED WORDS NOT FOUND ON WIKTIONARY ({len(flagged_words)} total)") |
| print("-" * 100) |
| current_lang = None |
| for fw in flagged_words: |
| if fw["lang"] != current_lang: |
| current_lang = fw["lang"] |
| print(f"\n [{fw['lang']}] {fw['lang_name']}:") |
| print(f" word='{fw['word']}' queried='{fw['query_title']}'") |
|
|
| |
| output_path = Path(r"C:\Users\alvin\hf-ancient-scripts\wiktionary_verification_results.json") |
| with open(output_path, "w", encoding="utf-8") as f: |
| json.dump({ |
| "summary": { |
| "total_languages": len(all_langs), |
| "total_sampled": total_sampled, |
| "total_verified": total_verified, |
| "total_not_found": total_not_found, |
| "overall_verification_rate": total_verified / total_sampled * 100 if total_sampled > 0 else 0, |
| }, |
| "per_language": all_results, |
| "flagged_words": flagged_words, |
| }, f, indent=2, ensure_ascii=False) |
| print(f"\nDetailed results saved to: {output_path}") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|