Datasets:
File size: 9,586 Bytes
75d5ab7 | 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 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 | #!/usr/bin/env python3
"""Ingest Linear B (Mycenaean Greek) data from CC-BY-SA compatible sources.
Sources:
1. Unicode UCD — Sign inventory (88 syllabograms + 123 ideograms)
URL: https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
License: Unicode Terms (permissive, CC-BY-SA-4.0 compatible)
2. Wiktionary — Mycenaean Greek lemmas (~435 entries)
URL: https://en.wiktionary.org/w/api.php (MediaWiki API)
License: CC-BY-SA-3.0+
3. jhnwnstd/shannon — Linear B Lexicon (2,747 entries, MIT license)
URL: https://raw.githubusercontent.com/jhnwnstd/shannon/main/Linear_B_Lexicon.csv
License: MIT
Iron Rule: Data comes from downloaded files/API responses. No hardcoded word lists.
Usage:
python scripts/ingest_linear_b.py [--dry-run]
"""
from __future__ import annotations
import argparse
import csv
import io
import json
import logging
import os
import re
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
from pathlib import Path
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding="utf-8")
ROOT = Path(__file__).resolve().parent.parent
logger = logging.getLogger(__name__)
RAW_DIR = ROOT / "data" / "training" / "raw" / "linear_b"
# ── Source URLs ──
UNICODE_DATA_URL = "https://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt"
WIKTIONARY_API = "https://en.wiktionary.org/w/api.php"
SHANNON_LEXICON_URL = (
"https://raw.githubusercontent.com/jhnwnstd/shannon/main/Linear_B_Lexicon.csv"
)
# Linear B Unicode ranges
LINB_SYLLABARY_START = 0x10000
LINB_SYLLABARY_END = 0x1007F
LINB_IDEOGRAM_START = 0x10080
LINB_IDEOGRAM_END = 0x100FF
def download_file(url: str, dest: Path, label: str) -> bool:
"""Download a file, skipping if already present and non-empty."""
if dest.exists() and dest.stat().st_size > 0:
logger.info(f" {label}: already exists ({dest.stat().st_size:,} bytes)")
return True
logger.info(f" {label}: downloading from {url}")
try:
req = urllib.request.Request(url, headers={"User-Agent": "LinearB-Ingestion/1.0"})
with urllib.request.urlopen(req, timeout=60) as resp:
data = resp.read()
dest.parent.mkdir(parents=True, exist_ok=True)
dest.write_bytes(data)
logger.info(f" {label}: downloaded {len(data):,} bytes")
return True
except (urllib.error.URLError, urllib.error.HTTPError, OSError) as e:
logger.error(f" {label}: DOWNLOAD FAILED — {e}")
return False
def download_unicode_data(dry_run: bool = False) -> Path:
"""Download UnicodeData.txt."""
dest = RAW_DIR / "UnicodeData.txt"
if dry_run:
logger.info(f" [DRY RUN] Would download {UNICODE_DATA_URL}")
return dest
download_file(UNICODE_DATA_URL, dest, "UnicodeData.txt")
return dest
def download_shannon_lexicon(dry_run: bool = False) -> Path:
"""Download jhnwnstd/shannon Linear_B_Lexicon.csv."""
dest = RAW_DIR / "shannon_Linear_B_Lexicon.csv"
if dry_run:
logger.info(f" [DRY RUN] Would download {SHANNON_LEXICON_URL}")
return dest
download_file(SHANNON_LEXICON_URL, dest, "shannon_lexicon")
return dest
def download_wiktionary_lemmas(dry_run: bool = False) -> Path:
"""Download all Mycenaean Greek lemmas from Wiktionary API."""
dest = RAW_DIR / "wiktionary_gmy_lemmas.json"
if dest.exists() and dest.stat().st_size > 0:
logger.info(f" wiktionary: already exists ({dest.stat().st_size:,} bytes)")
return dest
if dry_run:
logger.info(f" [DRY RUN] Would fetch Wiktionary gmy lemmas")
return dest
all_titles = []
cmcontinue = None
page = 0
while True:
page += 1
params = {
"action": "query",
"list": "categorymembers",
"cmtitle": "Category:Mycenaean_Greek_lemmas",
"cmlimit": "500",
"format": "json",
}
if cmcontinue:
params["cmcontinue"] = cmcontinue
url = f"{WIKTIONARY_API}?{urllib.parse.urlencode(params)}"
logger.info(f" wiktionary: page {page}, {len(all_titles)} titles so far...")
req = urllib.request.Request(url, headers={"User-Agent": "LinearB-Ingestion/1.0"})
with urllib.request.urlopen(req, timeout=30) as resp:
data = json.loads(resp.read().decode("utf-8"))
members = data.get("query", {}).get("categorymembers", [])
for m in members:
all_titles.append(m["title"])
# Check for continuation
cont = data.get("continue", {})
if "cmcontinue" in cont:
cmcontinue = cont["cmcontinue"]
time.sleep(0.5) # Be polite to Wiktionary
else:
break
logger.info(f" wiktionary: fetched {len(all_titles)} lemma titles")
# Now fetch content for each lemma (in batches of 50)
lemma_data = []
batch_size = 50
for i in range(0, len(all_titles), batch_size):
batch = all_titles[i : i + batch_size]
titles_param = "|".join(batch)
params = {
"action": "query",
"titles": titles_param,
"prop": "revisions",
"rvprop": "content",
"rvslots": "main",
"format": "json",
}
url = f"{WIKTIONARY_API}?{urllib.parse.urlencode(params)}"
req = urllib.request.Request(url, headers={"User-Agent": "LinearB-Ingestion/1.0"})
try:
with urllib.request.urlopen(req, timeout=30) as resp:
data = json.loads(resp.read().decode("utf-8"))
pages = data.get("query", {}).get("pages", {})
for page_id, page_data in pages.items():
title = page_data.get("title", "")
revisions = page_data.get("revisions", [])
if revisions:
content = revisions[0].get("slots", {}).get("main", {}).get("*", "")
lemma_data.append({"title": title, "wikitext": content})
except Exception as e:
logger.warning(f" wiktionary batch {i//batch_size}: {e}")
if i + batch_size < len(all_titles):
time.sleep(1.0) # Rate limit
dest.parent.mkdir(parents=True, exist_ok=True)
dest.write_text(json.dumps(lemma_data, ensure_ascii=False, indent=2), encoding="utf-8")
logger.info(f" wiktionary: saved {len(lemma_data)} lemma entries to {dest}")
return dest
def download_wiktionary_swadesh(dry_run: bool = False) -> Path:
"""Download Mycenaean Greek Swadesh list from Wiktionary."""
dest = RAW_DIR / "wiktionary_gmy_swadesh.json"
if dest.exists() and dest.stat().st_size > 0:
logger.info(f" swadesh: already exists ({dest.stat().st_size:,} bytes)")
return dest
if dry_run:
logger.info(f" [DRY RUN] Would fetch Wiktionary gmy Swadesh list")
return dest
params = {
"action": "query",
"titles": "Appendix:Mycenaean_Greek_Swadesh_list",
"prop": "revisions",
"rvprop": "content",
"rvslots": "main",
"format": "json",
}
url = f"{WIKTIONARY_API}?{urllib.parse.urlencode(params)}"
req = urllib.request.Request(url, headers={"User-Agent": "LinearB-Ingestion/1.0"})
with urllib.request.urlopen(req, timeout=30) as resp:
data = json.loads(resp.read().decode("utf-8"))
pages = data.get("query", {}).get("pages", {})
for page_id, page_data in pages.items():
content = page_data.get("revisions", [{}])[0].get("slots", {}).get("main", {}).get("*", "")
dest.parent.mkdir(parents=True, exist_ok=True)
dest.write_text(json.dumps({"title": "Mycenaean_Greek_Swadesh_list", "wikitext": content},
ensure_ascii=False, indent=2), encoding="utf-8")
logger.info(f" swadesh: saved to {dest}")
return dest
def main():
parser = argparse.ArgumentParser(description="Ingest Linear B data from open sources")
parser.add_argument("--dry-run", action="store_true", help="Show what would be downloaded")
args = parser.parse_args()
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(message)s",
datefmt="%H:%M:%S",
)
RAW_DIR.mkdir(parents=True, exist_ok=True)
print("=" * 70)
print("LINEAR B DATA INGESTION")
print("=" * 70)
# 1. Unicode Data
print("\n[1/4] Unicode UCD (sign inventory)")
ucd_path = download_unicode_data(args.dry_run)
# 2. Shannon lexicon
print("\n[2/4] jhnwnstd/shannon Linear B Lexicon (MIT)")
shannon_path = download_shannon_lexicon(args.dry_run)
# 3. Wiktionary lemmas
print("\n[3/4] Wiktionary Mycenaean Greek lemmas (CC-BY-SA)")
wikt_path = download_wiktionary_lemmas(args.dry_run)
# 4. Wiktionary Swadesh list
print("\n[4/4] Wiktionary Mycenaean Greek Swadesh list")
swadesh_path = download_wiktionary_swadesh(args.dry_run)
print("\n" + "=" * 70)
print("INGESTION COMPLETE")
print("=" * 70)
# Verify files
for label, path in [
("UnicodeData.txt", ucd_path),
("Shannon Lexicon", shannon_path),
("Wiktionary Lemmas", wikt_path),
("Wiktionary Swadesh", swadesh_path),
]:
if path.exists():
size = path.stat().st_size
print(f" {label}: {path.name} ({size:,} bytes)")
else:
print(f" {label}: NOT DOWNLOADED")
print(f"\nAll raw data saved to: {RAW_DIR}")
if __name__ == "__main__":
main()
|