aboutsummaryrefslogtreecommitdiff
path: root/fi-wiktionary/fetch_finnish_words.py
blob: cb06feca888e4458e8cd71cf00d3135554f28171 (plain)
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
#!/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())