aboutsummaryrefslogtreecommitdiff
path: root/fi-wiktionary/fetch_finnish_words.py
diff options
context:
space:
mode:
Diffstat (limited to 'fi-wiktionary/fetch_finnish_words.py')
-rw-r--r--fi-wiktionary/fetch_finnish_words.py214
1 files changed, 214 insertions, 0 deletions
diff --git a/fi-wiktionary/fetch_finnish_words.py b/fi-wiktionary/fetch_finnish_words.py
new file mode 100644
index 0000000..cb06fec
--- /dev/null
+++ b/fi-wiktionary/fetch_finnish_words.py
@@ -0,0 +1,214 @@
+#!/usr/bin/env python3
+"""Fetch all Finnish words from fi.wiktionary.org.
+
+Finnish-language entries on the Finnish Wiktionary are categorized under
+"Luokka:Suomen sanat" ("Category:Finnish words"), so this script uses the
+MediaWiki API to enumerate every member of that category (and, by default,
+any subcategories), paging through the results with ``cmcontinue``.
+
+Only the Python standard library is required.
+
+Usage examples:
+
+ python3 fetch_finnish_words.py # -> finnish_words.txt
+ python3 fetch_finnish_words.py -o sanat.txt # custom output file
+ python3 fetch_finnish_words.py --max-pages 100 # quick smoke test
+ python3 fetch_finnish_words.py --json sanat.json # also write JSON
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import sys
+import time
+import urllib.error
+import urllib.parse
+import urllib.request
+from pathlib import Path
+from typing import Iterator, Optional
+
+API_URL = "https://fi.wiktionary.org/w/api.php"
+DEFAULT_CATEGORY = "Luokka:Suomen sanat" # "Category:Finnish words"
+DEFAULT_USER_AGENT = (
+ "finnish-wikt-fetcher/1.0 "
+ "(https://fi.wiktionary.org; contact set via WIKT_USER_AGENT env var)"
+)
+
+
+class ApiError(RuntimeError):
+ """Raised when the MediaWiki API request ultimately fails."""
+
+
+def api_request(
+ params: dict,
+ delay: float,
+ max_retries: int = 5,
+) -> dict:
+ """Perform a GET request against the MediaWiki API with retries."""
+ params = dict(params, format="json", formatversion="2")
+ url = API_URL + "?" + urllib.parse.urlencode(params)
+ user_agent = os.environ.get("WIKT_USER_AGENT", DEFAULT_USER_AGENT)
+ request = urllib.request.Request(url, headers={"User-Agent": user_agent})
+
+ for attempt in range(1, max_retries + 1):
+ try:
+ with urllib.request.urlopen(request, timeout=60) as response:
+ data = json.loads(response.read().decode("utf-8"))
+ time.sleep(delay) # be polite: pause after every request
+ if "error" in data:
+ info = data["error"].get("info", "unknown API error")
+ raise ApiError(f"API error: {info}")
+ return data
+ except (urllib.error.URLError, OSError, ValueError) as exc:
+ if attempt == max_retries:
+ raise ApiError(f"giving up after {attempt} attempts: {exc}") from exc
+ wait = min(2**attempt, 30)
+ print(f" ! request failed ({exc}); retrying in {wait}s", file=sys.stderr)
+ time.sleep(wait)
+
+ raise ApiError("unreachable") # pragma: no cover
+
+
+def iter_category_members(
+ category: str,
+ delay: float,
+ recurse: bool = True,
+) -> Iterator[dict]:
+ """Yield members of *category* (namespace 0 = entries, 14 = subcats).
+
+ Follows pagination via the API's ``continue`` mechanism and, when
+ *recurse* is true, also walks into subcategories breadth-first.
+ """
+ seen_categories: set[str] = set()
+ queue: list[str] = [category]
+
+ while queue:
+ current = queue.pop(0)
+ if current in seen_categories:
+ continue
+ seen_categories.add(current)
+
+ continue_token: Optional[str] = None
+ while True:
+ params = {
+ "action": "query",
+ "list": "categorymembers",
+ "cmtitle": current,
+ "cmnamespace": "0|14", # regular pages + subcategories
+ "cmlimit": "max", # 500 per request for anonymous clients
+ }
+ if continue_token:
+ params["cmcontinue"] = continue_token
+
+ data = api_request(params, delay=delay)
+ for member in data.get("query", {}).get("categorymembers", []):
+ if member["ns"] == 0:
+ yield {"title": member["title"], "category": current}
+ elif member["ns"] == 14 and recurse:
+ queue.append(member["title"])
+
+ continue_token = data.get("continue", {}).get("cmcontinue")
+ if not continue_token:
+ break
+
+
+def main(argv: Optional[list[str]] = None) -> int:
+ parser = argparse.ArgumentParser(
+ description="Fetch all Finnish words from fi.wiktionary.org."
+ )
+ parser.add_argument(
+ "-o",
+ "--output",
+ default="finnish_words.txt",
+ help="output text file, one word per line (default: %(default)s)",
+ )
+ parser.add_argument(
+ "--category",
+ default=DEFAULT_CATEGORY,
+ help="root category to enumerate (default: %(default)s)",
+ )
+ parser.add_argument(
+ "--delay",
+ type=float,
+ default=0.2,
+ help="seconds to wait between API requests (default: %(default)s)",
+ )
+ parser.add_argument(
+ "--max-pages",
+ type=int,
+ default=None,
+ help="stop after this many words (useful for testing)",
+ )
+ parser.add_argument(
+ "--no-recurse",
+ action="store_true",
+ help="do not descend into subcategories",
+ )
+ parser.add_argument(
+ "--json",
+ dest="json_output",
+ default=None,
+ help="additionally write a JSON file with metadata to this path",
+ )
+ args = parser.parse_args(argv)
+
+ words: list[str] = []
+ seen: set[str] = set()
+ started = time.monotonic()
+ interrupted = False
+
+ print(f"Fetching members of '{args.category}' from {API_URL} ...", file=sys.stderr)
+ try:
+ for member in iter_category_members(
+ args.category, delay=args.delay, recurse=not args.no_recurse
+ ):
+ title = member["title"]
+ if title in seen:
+ continue
+ seen.add(title)
+ words.append(title)
+ if len(words) % 500 == 0:
+ print(f" {len(words)} words fetched...", file=sys.stderr)
+ if args.max_pages is not None and len(words) >= args.max_pages:
+ break
+ except KeyboardInterrupt:
+ interrupted = True
+ print("\nInterrupted - saving what was fetched so far.", file=sys.stderr)
+ except ApiError as exc:
+ if not words:
+ print(f"error: {exc}", file=sys.stderr)
+ return 1
+ print(f"warning: {exc} - saving partial results", file=sys.stderr)
+
+ output_path = Path(args.output)
+ output_path.write_text("\n".join(words) + ("\n" if words else ""), encoding="utf-8")
+
+ elapsed = time.monotonic() - started
+ print(
+ f"Wrote {len(words)} words to {output_path} "
+ f"({output_path.stat().st_size} bytes) in {elapsed:.1f}s"
+ + (" [interrupted]" if interrupted else ""),
+ file=sys.stderr,
+ )
+
+ if args.json_output:
+ payload = {
+ "source": API_URL,
+ "category": args.category,
+ "fetched_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
+ "count": len(words),
+ "interrupted": interrupted,
+ "words": words,
+ }
+ Path(args.json_output).write_text(
+ json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8"
+ )
+ print(f"Wrote JSON metadata to {args.json_output}", file=sys.stderr)
+
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())