Skip to content

Commit bfdbd84

Browse files
authored
Pospell check (#153)
1 parent a125fa0 commit bfdbd84

6 files changed

Lines changed: 265 additions & 1 deletion

File tree

‎.github/actionlint.yaml‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
paths:
2+
.github/workflows/update-and-build.yml:
3+
ignore:
4+
# Remove once https://github.com/rhysd/actionlint/pull/732 is released.
5+
- ^reusable workflow call "\$/\.github/workflows/spellcheck\.yml" at "uses" is not following
6+
the format

‎.github/workflows/spellcheck.yml‎

Lines changed: 149 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,149 @@
1+
name: spellcheck
2+
3+
on:
4+
pull_request:
5+
workflow_dispatch:
6+
workflow_call:
7+
inputs:
8+
advisory:
9+
description: Report failures without failing the calling workflow
10+
type: boolean
11+
default: true
12+
version:
13+
description: CPython documentation version
14+
required: true
15+
type: string
16+
translations-ref:
17+
description: Translation branch updated by the calling workflow
18+
required: true
19+
type: string
20+
secrets:
21+
TX_TOKEN:
22+
description: Transifex API token with access to the Polish terminology glossary
23+
required: true
24+
25+
permissions:
26+
contents: read
27+
28+
jobs:
29+
pospell:
30+
# Fork PRs cannot access TX_TOKEN; forks can run manually with their own secret.
31+
if: ${{ github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository }}
32+
runs-on: ubuntu-latest
33+
continue-on-error: ${{ inputs.advisory || github.event_name == 'pull_request' || github.event_name == 'workflow_dispatch' }}
34+
timeout-minutes: 15
35+
defaults:
36+
run:
37+
working-directory: cpython/Doc
38+
steps:
39+
- uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
40+
with:
41+
python-version: 3
42+
- uses: astral-sh/setup-uv@20cfd1bf945f4377ade1205e4dbc17946fc9a30d # v10.0.1
43+
- name: Check out workflow tools
44+
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
45+
with:
46+
path: spellcheck-tools
47+
sparse-checkout: |
48+
/manage_translation.py
49+
sparse-checkout-cone-mode: false
50+
persist-credentials: false
51+
- name: Check out CPython documentation
52+
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
53+
with:
54+
repository: python/cpython
55+
ref: ${{ inputs.version || github.base_ref || github.ref_name }}
56+
path: cpython
57+
persist-credentials: false
58+
- name: Check out translations
59+
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
60+
with:
61+
ref: ${{ inputs.translations-ref }}
62+
path: cpython/Doc/locales/pl/LC_MESSAGES
63+
persist-credentials: false
64+
- name: Install dependencies
65+
run: |
66+
sudo apt-get update
67+
sudo apt-get install -y curl hunspell hunspell-pl unzip
68+
make venv
69+
# Pospell needs newer Docutils than the Sphinx used by older branches.
70+
uv venv "$RUNNER_TEMP/spellcheck-venv"
71+
# Pospell PR 24 provides --report; switch to a release when available.
72+
uv pip install --python "$RUNNER_TEMP/spellcheck-venv/bin/python" \
73+
sphinx-intl transifex-python six \
74+
'pospell @ git+https://git.afpy.org/maciek/pospell.git@feat/json-reports'
75+
- name: Prepare UTF-8 Polish dictionary
76+
# The packaged dictionary uses ISO-8859-2, which cannot represent all prose.
77+
run: |
78+
mkdir -p "$RUNNER_TEMP/hunspell-utf8"
79+
dictionary_encoding=$(sed -n 's/^SET //p' /usr/share/hunspell/pl_PL.aff)
80+
iconv -f "$dictionary_encoding" -t UTF-8 /usr/share/hunspell/pl_PL.aff \
81+
> "$RUNNER_TEMP/hunspell-utf8/pl_PL.aff"
82+
sed -i 's/^SET .*/SET UTF-8/' "$RUNNER_TEMP/hunspell-utf8/pl_PL.aff"
83+
iconv -f "$dictionary_encoding" -t UTF-8 /usr/share/hunspell/pl_PL.dic \
84+
> "$RUNNER_TEMP/hunspell-utf8/pl_PL.dic"
85+
- name: Download SJP Polish dictionary
86+
run: |
87+
curl --fail --location --retry 3 \
88+
https://sjp.pl/sl/ort/sjp-hunspell-pl-20261101.zip \
89+
--output "$RUNNER_TEMP/sjp-hunspell.zip"
90+
echo "a29b40d80a2501ba1ad84fa17f7d177e2ebe313082f74f837a77b3135c05340c $RUNNER_TEMP/sjp-hunspell.zip" \
91+
| sha256sum --check --strict
92+
# SJP wraps the dictionary files in a second ZIP archive.
93+
unzip -p "$RUNNER_TEMP/sjp-hunspell.zip" pl_PL.zip \
94+
> "$RUNNER_TEMP/sjp-pl_PL.zip"
95+
unzip -p "$RUNNER_TEMP/sjp-pl_PL.zip" pl_PL.aff \
96+
> "$RUNNER_TEMP/sjp-pl_PL.aff"
97+
unzip -p "$RUNNER_TEMP/sjp-pl_PL.zip" pl_PL.dic \
98+
> "$RUNNER_TEMP/sjp-pl_PL.dic"
99+
dictionary_encoding=$(sed -n 's/^SET //p' "$RUNNER_TEMP/sjp-pl_PL.aff")
100+
iconv -f "$dictionary_encoding" -t UTF-8 "$RUNNER_TEMP/sjp-pl_PL.aff" \
101+
> "$RUNNER_TEMP/hunspell-utf8/pl_SJP.aff"
102+
sed -i 's/^SET .*/SET UTF-8/' "$RUNNER_TEMP/hunspell-utf8/pl_SJP.aff"
103+
iconv -f "$dictionary_encoding" -t UTF-8 "$RUNNER_TEMP/sjp-pl_PL.dic" \
104+
> "$RUNNER_TEMP/hunspell-utf8/pl_SJP.dic"
105+
- name: Download Polish terminology glossary
106+
working-directory: spellcheck-tools
107+
env:
108+
TX_TOKEN: ${{ secrets.TX_TOKEN }}
109+
run: >
110+
"$RUNNER_TEMP/spellcheck-venv/bin/python"
111+
manage_translation.py fetch_glossary
112+
--output "$RUNNER_TEMP/hunspell-glossary.dic"
113+
- name: Generate POT files without literal blocks
114+
run: |
115+
if make -n gettext >/dev/null 2>&1; then
116+
make gettext SPHINXOPTS="-D gettext_additional_targets=index -D gettext_compact=0"
117+
else
118+
# CPython 3.10 and 3.11 do not have a dedicated gettext target.
119+
make build BUILDER=gettext SPHINXOPTS="-D gettext_additional_targets=index -D gettext_compact=0"
120+
fi
121+
- name: Prepare temporary PO files without literal blocks
122+
run: |
123+
# Only catalogs with a current POT have had literal blocks excluded.
124+
while IFS= read -r -d '' po; do
125+
resource=${po#locales/pl/LC_MESSAGES/}
126+
if [ ! -f "build/gettext/${resource%.po}.pot" ]; then
127+
rm "$po"
128+
fi
129+
done < <(find locales/pl/LC_MESSAGES -name '*.po' -type f -print0)
130+
"$RUNNER_TEMP/spellcheck-venv/bin/sphinx-intl" update \
131+
-p build/gettext -d locales -l pl --no-obsolete
132+
- name: Check Polish spelling
133+
id: spelling
134+
env:
135+
DICPATH: ${{ runner.temp }}/hunspell-utf8
136+
run: |
137+
"$RUNNER_TEMP/spellcheck-venv/bin/pospell" --language pl_PL,pl_SJP \
138+
--personal-dict "$RUNNER_TEMP/hunspell-glossary.dic" \
139+
--glob 'locales/pl/LC_MESSAGES/**/*.po' \
140+
--report-root locales/pl/LC_MESSAGES \
141+
--report "$RUNNER_TEMP/spellcheck.json"
142+
- name: Upload spelling report
143+
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
144+
if: ${{ !cancelled() && (steps.spelling.outcome == 'success' || steps.spelling.outcome == 'failure') }}
145+
with:
146+
name: spellcheck-pl
147+
path: ${{ runner.temp }}/spellcheck.json
148+
if-no-files-found: error
149+
# PO updates exist only in this disposable checkout; nothing is committed.

‎.github/workflows/update-and-build.yml‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,20 @@ jobs:
7272
branch: ${{ matrix.version }}
7373
github_token: ${{ secrets.GITHUB_TOKEN }}
7474

75+
spellcheck:
76+
needs: [update]
77+
# These are the runs in which update publishes the fetched translations.
78+
if: github.event_name == 'schedule' || github.ref_name == github.event.repository.default_branch
79+
permissions:
80+
contents: read
81+
uses: $/.github/workflows/spellcheck.yml
82+
with:
83+
advisory: true
84+
version: ${{ github.ref_name }}
85+
translations-ref: ${{ github.ref_name }}
86+
secrets:
87+
TX_TOKEN: ${{ secrets.TX_TOKEN }}
88+
7589
build:
7690
runs-on: ubuntu-latest
7791
strategy:

‎README.en.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,13 @@ $ uvx sphinx-lint library/turtle.po
8484
No problems found.
8585
```
8686

87+
### Spellchecking
88+
89+
The [spellcheck workflow](.github/workflows/spellcheck.yml) publishes
90+
`spellcheck.json` in the `spellcheck-pl` artifact.
91+
See the [pospell documentation](https://git.afpy.org/maciek/pospell/src/branch/feat/json-reports/README.md)
92+
for the report format and checking options.
93+
8794
### How do I see the latest build of the documentation?
8895

8996
Download the latest build from the list of artefacts in the latest GitHub Action (Actions Tab).

‎README.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,12 @@ $ uvx sphinx-lint library/turtle.po
8484
No problems found.
8585
```
8686

87+
### Sprawdzanie pisowni
88+
89+
Workflow [spellcheck](.github/workflows/spellcheck.yml) publikuje `spellcheck.json`
90+
w artefakcie `spellcheck-pl`.
91+
Format raportu i opcje sprawdzania opisuje [dokumentacja pospell](https://git.afpy.org/maciek/pospell/src/branch/feat/json-reports/README.md).
92+
8793
### Jak obejrzeć najnowszy build dokumentacji?
8894

8995
Pobierz ostatnią zbudowaną dokumentację z listy artefaktów w ostatniej GitHub Action (zakładka Actions).

‎manage_translation.py‎

Lines changed: 83 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,15 @@
1212
# * recreate_tx_config: recreate configuration for all resources.
1313
# * warn_about_files_to_delete: lists files that are not available upstream
1414
# * generate_commit_msg: generates commit message with co-authors
15+
# * fetch_glossary: download Polish terminology as a Hunspell personal dictionary
1516

17+
import csv
18+
import io
1619
import os
20+
import re
1721
import sys
22+
import time
23+
import unicodedata
1824
from argparse import ArgumentParser
1925
from collections.abc import Iterable
2026
from contextlib import chdir
@@ -25,12 +31,15 @@
2531
from typing import Self
2632
from warnings import warn
2733

34+
import requests
2835
from polib import POFile, pofile
2936
from transifex.api import transifex_api
37+
from transifex.api.jsonapi.exceptions import JsonApiException
3038

3139
LANGUAGE = 'pl'
3240
PROJECT_SLUG = 'python-newest'
3341
VERSION = '3.14'
42+
GLOSSARY_ID = 'o:python-doc:g:python_global'
3443

3544

3645
def fetch():
@@ -46,6 +55,59 @@ def fetch():
4655
_call(f'msgcat --no-location -o {file} {file}')
4756

4857

58+
def _download_glossary(token: str, *, max_wait: float = 300) -> str:
59+
transifex_api.setup(auth=token)
60+
# The SDK supports new API resource types before adding dedicated classes.
61+
download = transifex_api.new(
62+
type='glossaries_async_downloads',
63+
glossary=transifex_api.new(type='glossaries', id=GLOSSARY_ID),
64+
language=transifex_api.Language(id=f'l:{LANGUAGE}'),
65+
)
66+
download.save()
67+
deadline = time.monotonic() + max_wait
68+
while not download.redirect:
69+
status = download.attributes['status']
70+
if status == 'failed':
71+
raise ValueError('Transifex glossary export failed.')
72+
if status not in {'pending', 'processing'}:
73+
raise ValueError(f'Unexpected glossary export status: {status!r}')
74+
if time.monotonic() >= deadline:
75+
raise ValueError('Transifex glossary export timed out.')
76+
time.sleep(3)
77+
download.reload()
78+
# Download the CSV without sending the API token to the signed storage URL.
79+
export = requests.get(download.redirect, timeout=30)
80+
export.raise_for_status()
81+
return export.content.decode('utf-8-sig')
82+
83+
84+
def _glossary_words(content: str) -> list[str]:
85+
reader = csv.DictReader(io.StringIO(content))
86+
translation_column = f'translation_{LANGUAGE}'
87+
if not reader.fieldnames or translation_column not in reader.fieldnames:
88+
raise ValueError('Transifex glossary CSV has no Polish translation column.')
89+
words = {
90+
word
91+
for row in reader
92+
for word in re.findall(
93+
r'[^\W\d_]+', unicodedata.normalize('NFC', row[translation_column] or '')
94+
)
95+
}
96+
if not words:
97+
raise ValueError('Transifex glossary has no Polish terms.')
98+
return sorted(words)
99+
100+
101+
def fetch_glossary(output: Path):
102+
"""Fetch Polish terminology and write a UTF-8 Hunspell personal dictionary."""
103+
token = _get_tx_token().strip()
104+
if not token:
105+
raise ValueError('TX_TOKEN is required to download the Transifex glossary.')
106+
words = _glossary_words(_download_glossary(token))
107+
output.write_text(f'{len(words)}\n' + '\n'.join(words) + '\n', encoding='utf-8')
108+
print(f'Added {len(words)} Polish glossary words to {output}.')
109+
110+
49111
def _call(command: str):
50112
if (return_code := call(command, shell=True)) != 0:
51113
sys.exit(return_code)
@@ -224,10 +286,30 @@ def generate_commit_msg():
224286
'recreate_tx_config',
225287
'warn_about_files_to_delete',
226288
'generate_commit_msg',
289+
'fetch_glossary',
227290
)
228291

229292
parser = ArgumentParser()
230293
parser.add_argument('cmd', choices=RUNNABLE_SCRIPTS)
294+
parser.add_argument(
295+
'--output', type=Path, help='Hunspell dictionary path for fetch_glossary'
296+
)
231297
options = parser.parse_args()
232298

233-
eval(options.cmd)()
299+
if options.cmd == 'fetch_glossary':
300+
if options.output is None:
301+
parser.error('--output is required for fetch_glossary')
302+
try:
303+
fetch_glossary(options.output)
304+
except (requests.RequestException, JsonApiException) as error:
305+
# Exceptions may contain signed URLs; report the status without those URLs.
306+
status = (
307+
error.response.status_code
308+
if error.response is not None
309+
else 'network error'
310+
)
311+
parser.exit(1, f'Transifex glossary request failed: {status}.\n')
312+
except (ValueError, KeyError) as error:
313+
parser.exit(1, f'Invalid Transifex glossary export: {error}\n')
314+
else:
315+
eval(options.cmd)()

0 commit comments

Comments
 (0)