diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..27edc3f --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,106 @@ +name: CI + +on: + push: + branches: [main] + pull_request: + branches: [main] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ci-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +jobs: + windows: + name: Windows / Python ${{ matrix.python }} + runs-on: windows-2025 + timeout-minutes: 20 + strategy: + fail-fast: false + matrix: + python: ["3.11", "3.12", "3.13", "3.14"] + defaults: + run: + shell: pwsh + env: + PYTHONUTF8: "1" + # Typer otherwise forces ANSI styling when GITHUB_ACTIONS is set. + _TYPER_FORCE_DISABLE_TERMINAL: "1" + NO_COLOR: "1" + steps: + - name: Check out source + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - name: Set up uv + uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 + with: + version: "0.12.19" + python-version: ${{ matrix.python }} + enable-cache: true + cache-dependency-glob: uv.lock + + - name: Install Python + run: uv python install "${{ matrix.python }}" + + - name: Install locked dependencies + run: uv sync --locked --group dev + + - name: Isolate MatnOCR settings + run: | + $configHome = Join-Path $env:RUNNER_TEMP 'matnocr-config' + Add-Content -LiteralPath $env:GITHUB_ENV -Value "MATNOCR_CONFIG_HOME=$configHome" -Encoding utf8 + + - name: Record runtime and OCR languages + run: uv run --no-sync python tools/ci_smoke.py --diagnostics-only + + - name: Ruff check + run: uv run --no-sync ruff check . + + - name: Ruff format + run: uv run --no-sync ruff format --check . + + - name: Type check + run: uv run --no-sync ty check + + - name: Unit and integration tests + run: uv run --no-sync pytest --cov=matnocr + + - name: Build wheel and source distribution + run: uv build --out-dir "${{ runner.temp }}/matnocr-dist" + + - name: Export locked runtime dependencies + run: uv export --locked --no-dev --no-emit-project --format requirements-txt --output-file "${{ runner.temp }}/matnocr-runtime.txt" + + - name: Create fresh wheel environment + run: uv venv --python "${{ matrix.python }}" "${{ runner.temp }}/matnocr-wheel-env" + + - name: Install locked runtime dependencies into wheel environment + run: uv pip sync --python "${{ runner.temp }}/matnocr-wheel-env/Scripts/python.exe" "${{ runner.temp }}/matnocr-runtime.txt" + + - name: Install built wheel + run: | + $wheels = @(Get-ChildItem -LiteralPath '${{ runner.temp }}/matnocr-dist' -Filter '*.whl') + if ($wheels.Count -ne 1) { throw 'Expected exactly one built wheel.' } + uv pip install --no-deps --python '${{ runner.temp }}/matnocr-wheel-env/Scripts/python.exe' $wheels[0].FullName + + - name: Smoke-test installed wheel and console command + run: | + & '${{ runner.temp }}/matnocr-wheel-env/Scripts/python.exe' -I tools/ci_smoke.py + + ci: + name: CI + if: always() + needs: [windows] + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - name: Require all Windows jobs to succeed + env: + WINDOWS_RESULT: ${{ needs.windows.result }} + run: test "$WINDOWS_RESULT" = success diff --git a/AGENTS.md b/AGENTS.md index 9166f35..41c1dbd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -406,7 +406,7 @@ coverage.py Ruff, ty, pytest und pytest-cov sind bereits als Dev Dependencies eingetragen. Die Konfiguration steht in `pyproject.toml`: Ruff prüft aktiven Code und Tests (ohne die historischen Experimente `prototype.py` und `add_new_white_page.py`), -ty prüft `src/` und `tests/` für Python 3.11 unter Windows. Unit- und mit +ty prüft `src/`, `tests/` und `tools/` für Python 3.11 unter Windows. Unit- und mit `integration` markierte Integrationstests sind getrennt. Aktuellen Status und weitere Aufgaben in `TODO.md` beachten. diff --git a/CHANGELOG.md b/CHANGELOG.md index cbab77d..dfd010d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,6 +22,10 @@ development work, not a claim that a public release has been published. staged writes that preserve existing exports if replacement fails. - Unit tests, synthetic English/German/Arabic integration documents, and local Ruff, ty, pytest, and coverage configuration. +- GitHub Actions CI for Python 3.11–3.14 on Windows Server 2025, including + locked dependencies, code checks, capability-aware integration tests, package + builds, and CLI smoke tests in a fresh wheel environment. A combined `CI` + check reports the overall matrix result for branch protection. - Usage and development documentation, screenshots, contributor guidance, security and conduct policies, and GitHub issue and pull request templates. @@ -30,4 +34,4 @@ development work, not a claim that a public release has been published. - Suppressed the PDFium foreign-bitmap close warning in the scan fast path after verifying that OCR uses an independent pixel copy. -Public PyPI releases, GitHub CI, and packaged Windows releases are still planned. +Public PyPI releases and packaged Windows releases are still planned. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 5cd8cb7..7437289 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -12,7 +12,8 @@ features or changes to the renderer, OCR engine, dependencies, or packaging, open a feature request before implementation so the scope can be discussed. MatnOCR is in development. The package version is not evidence of a published -release; see [CHANGELOG.md](CHANGELOG.md). CI and publishing remain planned work. +release; see [CHANGELOG.md](CHANGELOG.md). The CI workflow is configured in +`.github/workflows/ci.yml`; publishing remains planned work. ## Report an Issue diff --git a/PROJECT.md b/PROJECT.md index 4932bfb..c25f012 100644 --- a/PROJECT.md +++ b/PROJECT.md @@ -657,8 +657,8 @@ Ruff, ty, pytest, and pytest-cov (coverage.py) are already included in the `pyproject.toml` development dependency group and recorded in `uv.lock`. Ruff, ty, pytest, and branch coverage are configured in `pyproject.toml`. Ruff checks active code and tests; the historical experiments `prototype.py` -and `add_new_white_page.py` are excluded. ty checks `src/` and `tests/` for -Python 3.11 on Windows. The installed PyWinRT types require no global rule +and `add_new_white_page.py` are excluded. ty checks `src/`, `tests/`, and +`tools/` for Python 3.11 on Windows. The installed PyWinRT types require no global rule suppression; existing `Any` boundaries for native objects are explained in `README.md`. Local commands are documented there as well. @@ -717,8 +717,8 @@ project/ The package lives under `src/matnocr/`; unit tests are in `tests/unit/`, and integration tests are in `tests/integration/`. The tree also shows planned -files: GitHub workflows are still pending. Community documents, issue forms, -and the pull request template are present. `TODO.md` describes the authoritative +files: the CI workflow is present; release and CodeQL workflows are still +pending. Community documents, issue forms, and the pull request template are present. `TODO.md` describes the authoritative implementation status. ## 15. Packaging and Installation @@ -733,8 +733,9 @@ matnocr = "matnocr.cli:app" ``` The console entry point launches `matnocr`; `python -m matnocr` is also -available. Full build and wheel verification remains part of the packaging -roadmap. +available. Local wheel/sdist builds, archive checks, fresh wheel installation, +and CLI smoke checks have passed on Python 3.13. Validation on the GitHub runner +and across the full Python matrix remains part of the CI and packaging roadmap. ## 16. Installation for Users @@ -826,11 +827,19 @@ with: ## 19. CI – Continuous Integration -CI should run through GitHub Actions. +GitHub Actions CI is configured in `.github/workflows/ci.yml`. It runs on +pushes to `main`, pull requests targeting `main`, and manual dispatch. The +application jobs use `windows-2025` with Python 3.11, 3.12, 3.13, and 3.14. +The first hosted run must still confirm compatibility and actual OCR capability +availability; Windows Server language packs must not be assumed to match a +Windows desktop. -Because OCR is Windows-specific, at least one Windows runner is required. +The workflow pins uv 0.12.19 and action commit SHAs, uses read-only repository +permissions, and does not publish packages. A final `CI` job combines the Windows +matrix results and can become the required branch-protection check after the +first successful hosted run. This gate uses Ubuntu only to combine results. -Planned workflow for pull requests and pushes: +Configured workflow: ```text Checkout @@ -848,7 +857,7 @@ Checkout ### Python Matrix -Versions planned for evaluation: +Configured CI versions, pending their first successful hosted evaluation: ```text 3.11 diff --git a/TODO.md b/TODO.md index e01a16a..c90743f 100644 --- a/TODO.md +++ b/TODO.md @@ -421,9 +421,9 @@ offline-ocr ### 27. Branch Protection später aktivieren -- [ ] Pull Requests vor Merge -- [ ] CI muss erfolgreich sein -- [ ] versehentliches Force Push verhindern +- [x] Pull Requests vor Merge +- [ ] CI muss erfolgreich sein (Check `CI` nach erstem erfolgreichen GitHub-Lauf verpflichtend machen) +- [x] versehentliches Force Push verhindern - [ ] Tags / Releases schützen ## Phase 6 – GitHub CI @@ -439,29 +439,38 @@ pull_request Schritte: -- [ ] Checkout -- [ ] uv installieren -- [ ] Python installieren -- [ ] `uv sync --locked` -- [ ] `ruff check` -- [ ] `ruff format --check` -- [ ] `ty check` -- [ ] `pytest` -- [ ] Package bauen -- [ ] gebauten Wheel installieren -- [ ] CLI Smoke Test +- [x] Checkout +- [x] uv installieren +- [x] Python installieren +- [x] `uv sync --locked` +- [x] `ruff check` +- [x] `ruff format --check` +- [x] `ty check` +- [x] `pytest` +- [x] Package bauen +- [x] gebauten Wheel installieren +- [x] CLI Smoke Test + +Der Workflow ist implementiert und lokal unter Python 3.13 geprüft. +Der erste ausgeführte Hosted-Testlauf zeigte CLI-Tests mit einer Abhängigkeit +von der nicht versionierten `prototype.py` sowie von Typer erzwungene ANSI-Codes. +Die Tests erzeugen nun eigene Eingabepfade; der Workflow deaktiviert erzwungene +Terminalformatierung. Lokal bestehen damit alle 144 Tests auch mit den +CI-Umgebungsvariablen. Der erfolgreiche Hosted-Wiederholungslauf steht noch aus. + +- [ ] ersten GitHub-Lauf auf dem PR prüfen (Matrix und echte Runner-Capabilities) ### 29. Windows Runner -- [ ] Windows GitHub Runner verwenden -- [ ] genaue Runner-Version festlegen -- [ ] verfügbare Windows-OCR-Sprachen untersuchen -- [ ] falls sinnvoll kleine Integrationstests aktivieren -- [ ] OCR-Sprachabhängige Tests sauber skippen +- [x] Windows GitHub Runner konfigurieren (`windows-2025`; erster Hosted-Lauf noch offen) +- [x] Runner-Image-Familie festlegen (`windows-2025`; konkrete Image-Version im Actions-Log) +- [ ] verfügbare Windows-OCR-Sprachen im ersten GitHub-Lauf untersuchen (Diagnose-Schritt konfiguriert) +- [x] kleine Integrationstests im Workflow aktivieren +- [x] OCR-Sprachabhängige Tests bei fehlender Runtime oder Sprache sauber skippen ### 30. Python CI Matrix -Prüfen: +Matrix 3.11–3.14 ist konfiguriert; erfolgreiche Hosted-Läufe noch prüfen: - [ ] Python 3.11 - [ ] Python 3.12 @@ -474,8 +483,8 @@ Nur nach erfolgreichem Test offiziell unterstützen. - [ ] Dependabot - [ ] CodeQL -- [ ] minimale GitHub-Action-Berechtigungen -- [ ] Actions möglichst auf stabile Versionen / SHAs pinnen +- [x] minimale GitHub-Action-Berechtigungen (`contents: read` im CI-Workflow) +- [x] CI-Actions auf geprüfte Commit-SHAs und uv auf Version pinnen ## Phase 7 – Python Packaging / PyPI @@ -497,11 +506,11 @@ Nur nach erfolgreichem Test offiziell unterstützen. ### 33. Build lokal testen -- [ ] `uv build` -- [ ] sdist prüfen -- [ ] wheel prüfen -- [ ] frische virtuelle Umgebung erstellen -- [ ] wheel dort installieren +- [x] `uv build` +- [x] sdist prüfen +- [x] wheel prüfen +- [x] frische virtuelle Umgebung erstellen +- [x] wheel dort installieren - [ ] CLI vollständig testen ### 34. TestPyPI diff --git a/docs/development.md b/docs/development.md index 26f0d98..e4d761a 100644 --- a/docs/development.md +++ b/docs/development.md @@ -47,7 +47,7 @@ Ruff, ty, pytest, and branch coverage are configured in `pyproject.toml`. Ruff targets Python 3.11 and checks common syntax errors, undefined names, imports, modernization, and common bug patterns. Its formatter uses 88 columns and double quotes. The historical `prototype.py` and `add_new_white_page.py` -experiments are excluded from Ruff; ty checks `src/` and `tests/`, targeting +experiments are excluded from Ruff; ty checks `src/`, `tests/`, and `tools/`, targeting Python 3.11 on Windows. These scripts are not distributed application code. The installed PyWinRT typing works with ty without global rule suppression or @@ -69,7 +69,39 @@ and the locally installed Arial font; affected tests skip if these capabilities are unavailable. No new package dependencies or bundled font files are needed. No language packs are installed by tests, and no private book pages are used. See [the integration test notes](../tests/integration/README.md) for details. -The full suite currently requires Windows -because application modules imported by unit tests use WinRT. GitHub CI remains -a later roadmap task. +The full suite currently requires Windows because application modules imported +by unit tests use WinRT. + +## GitHub Actions CI + +The workflow in [ci.yml](../.github/workflows/ci.yml) runs on pushes to `main`, +pull requests targeting `main`, and manual dispatch. Each matrix job uses +`windows-2025` with Python 3.11, 3.12, 3.13, or 3.14. setup-uv selects the matrix +interpreter independently of the local `.python-version` file. uv is pinned to +0.12.19, and third-party actions are pinned to commit SHAs. The workflow has +read-only repository permissions and does not publish artifacts or use deployment +secrets. + +Every Windows job synchronizes `uv.lock`, logs the runtime and available OCR +languages, runs Ruff, formatting, ty, and all tests with coverage, and builds a +wheel and source distribution. It then creates a separate environment, installs +the locked runtime dependencies and built wheel, and runs `tools/ci_smoke.py` +with isolated Python imports. The smoke test verifies that the imported package +lives in that environment, checks CLI help/version output, and invokes the +installed `matnocr.exe` console entry point. It deliberately uses OCR-command +help rather than requiring an OCR engine for help on a server runner. + +OCR capabilities on Windows Server runners may differ from a desktop Windows +installation. Integration tests skip an unavailable OCR runtime or missing +language pack and report the reasons. The diagnostics step records the actual +languages without installing system capabilities or opening an administrative +PowerShell. CLI unit tests use synthetic language discovery. + +The final `CI` job runs even if a matrix job fails or is skipped, and succeeds +only when the Windows matrix succeeds. After the first successful GitHub run, +require this check in the `main` ruleset. Do not require all possible OCR +languages or assume that a configured Python matrix is already validated: +inspect the first run and its skipped tests before marking compatibility tasks +complete. The final gate uses Ubuntu only to combine results; all application +checks run on Windows. diff --git a/pyproject.toml b/pyproject.toml index b6f8470..b979db1 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -51,7 +51,7 @@ indent-style = "space" line-ending = "auto" [tool.ty.src] -include = ["src", "tests"] +include = ["src", "tests", "tools"] [tool.ty.environment] python-version = "3.11" diff --git a/tests/integration/conftest.py b/tests/integration/conftest.py index 30ee209..637e488 100644 --- a/tests/integration/conftest.py +++ b/tests/integration/conftest.py @@ -25,7 +25,12 @@ def pdfium() -> Any: def windows_ocr() -> Any: if sys.platform != "win32": pytest.skip("Windows OCR requires Windows") - return pytest.importorskip("winrt.windows.media.ocr") + module = pytest.importorskip("winrt.windows.media.ocr") + try: + tuple(module.OcrEngine.available_recognizer_languages) + except (OSError, RuntimeError) as error: + pytest.skip(f"Windows OCR runtime is unavailable: {error}") + return module @pytest.fixture diff --git a/tests/unit/test_cli.py b/tests/unit/test_cli.py index e6baeae..9538097 100644 --- a/tests/unit/test_cli.py +++ b/tests/unit/test_cli.py @@ -19,9 +19,23 @@ runner = CliRunner() +@pytest.fixture +def existing_file(tmp_path: Path) -> Path: + """Supply an input path for CLI validation; PDF/OCR access is mocked.""" + source = tmp_path / "input.pdf" + source.touch() + return source + + @pytest.fixture(autouse=True) def isolated_settings(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setenv("MATNOCR_CONFIG_HOME", str(tmp_path)) + # CLI validation must not depend on a runner's installed OCR capabilities. + monkeypatch.setattr( + "matnocr.languages.get_available_languages", + lambda: (OcrLanguage("ar-SA", "Arabic", "Arabic"),), + ) + monkeypatch.setattr(cli, "get_language_display_name", lambda _tag: "Arabic") def test_help_is_available() -> None: @@ -136,8 +150,7 @@ def test_pdf_argument_must_exist() -> None: assert "does not exist" in result.stderr -def test_invalid_page_selection_is_reported() -> None: - existing_file = Path(__file__).resolve().parents[2] / "prototype.py" +def test_invalid_page_selection_is_reported(existing_file: Path) -> None: result = runner.invoke(app, [str(existing_file), "--pages", "8-3"]) @@ -145,8 +158,9 @@ def test_invalid_page_selection_is_reported() -> None: assert "Page range must be ascending; got 8-3." in result.stderr -def test_page_count_prints_only_the_number(monkeypatch: pytest.MonkeyPatch) -> None: - existing_file = Path(__file__).resolve().parents[2] / "prototype.py" +def test_page_count_prints_only_the_number( + existing_file: Path, monkeypatch: pytest.MonkeyPatch +) -> None: monkeypatch.setattr("matnocr.cli.get_pdf_page_count", lambda _path: 6) result = runner.invoke(app, [str(existing_file), "--page-count"]) @@ -155,8 +169,7 @@ def test_page_count_prints_only_the_number(monkeypatch: pytest.MonkeyPatch) -> N assert result.stdout == "6\n" -def test_page_count_rejects_page_selection() -> None: - existing_file = Path(__file__).resolve().parents[2] / "prototype.py" +def test_page_count_rejects_page_selection(existing_file: Path) -> None: result = runner.invoke( app, @@ -176,8 +189,7 @@ def test_version_does_not_require_a_pdf() -> None: assert result.stdout == f"{version('matnocr')}\n" -def test_dpi_and_quality_cannot_be_combined() -> None: - existing_file = Path(__file__).resolve().parents[2] / "prototype.py" +def test_dpi_and_quality_cannot_be_combined(existing_file: Path) -> None: result = runner.invoke( app, @@ -188,8 +200,9 @@ def test_dpi_and_quality_cannot_be_combined() -> None: assert "--dpi and --quality cannot be combined." in result.stderr -def test_quality_output_and_quiet_options(monkeypatch: pytest.MonkeyPatch) -> None: - existing_file = Path(__file__).resolve().parents[2] / "prototype.py" +def test_quality_output_and_quiet_options( + existing_file: Path, monkeypatch: pytest.MonkeyPatch +) -> None: output_path = Path.cwd() / "chosen-output.txt" captured: dict[str, object] = {} @@ -297,9 +310,9 @@ def test_languages_command_shows_installed_languages( def test_missing_ocr_language_has_an_actionable_error( + existing_file: Path, monkeypatch: pytest.MonkeyPatch, ) -> None: - existing_file = Path(__file__).resolve().parents[2] / "prototype.py" monkeypatch.setattr(cli, "load_default_language", lambda: "en") def missing_language(_requested: str) -> str: @@ -419,9 +432,9 @@ def test_doctor_command_reports_success(monkeypatch: pytest.MonkeyPatch) -> None def test_output_write_failure_is_a_clean_stderr_error( + existing_file: Path, monkeypatch: pytest.MonkeyPatch, ) -> None: - existing_file = Path(__file__).resolve().parents[2] / "prototype.py" monkeypatch.setattr(cli, "resolve_language", lambda _language: "ar-SA") async def fake_recognize_pdf( @@ -547,9 +560,10 @@ async def fake_recognize(*_args: object, **_kwargs: object) -> OcrRunResult: @pytest.mark.parametrize( "options", [["-o", "notes.pdf"], ["-o", "notes.md", "--format", "txt"]] ) -def test_invalid_output_format_is_rejected_before_ocr(options: list[str]) -> None: - source = Path(__file__).resolve().parents[2] / "prototype.py" - result = runner.invoke(app, [str(source), *options]) +def test_invalid_output_format_is_rejected_before_ocr( + existing_file: Path, options: list[str] +) -> None: + result = runner.invoke(app, [str(existing_file), *options]) assert result.exit_code == 2 assert "--format/--output" in result.stderr assert "Traceback" not in result.stderr diff --git a/tools/ci_smoke.py b/tools/ci_smoke.py new file mode 100644 index 0000000..825ca33 --- /dev/null +++ b/tools/ci_smoke.py @@ -0,0 +1,69 @@ +"""Record CI capabilities and verify an independently installed wheel.""" + +import argparse +import importlib +import platform +import subprocess +import sys +import sysconfig +from importlib.metadata import version +from pathlib import Path + + +def print_diagnostics() -> None: + print(f"Platform: {platform.platform()}") + print(f"Python: {platform.python_version()}") + print(f"Interpreter: {sys.executable}") + print(f"PDFium package: {version('pypdfium2')}") + try: + from winrt.windows.media.ocr import OcrEngine + + tags = [ + language.language_tag + for language in OcrEngine.available_recognizer_languages + ] + print(f"Installed OCR languages: {', '.join(tags) or 'none'}") + except (ImportError, OSError, RuntimeError) as error: + print(f"Windows OCR capability unavailable: {error}") + + +def smoke_test() -> None: + package = importlib.import_module("matnocr") + package_path = Path(package.__file__).resolve() + if not package_path.is_relative_to(Path(sys.prefix).resolve()): + raise RuntimeError( + f"Expected a wheel in the fresh environment, got {package_path}" + ) + print(f"Installed package: {package_path}") + + for arguments in (["--version"], ["ocr", "--help"], ["output", "--help"]): + subprocess.run( + [sys.executable, "-I", "-m", "matnocr", *arguments], + check=True, + timeout=30, + ) + + console = Path(sysconfig.get_path("scripts")) / "matnocr.exe" + result = subprocess.run( + [str(console), "--version"], + check=True, + capture_output=True, + text=True, + timeout=30, + ) + if result.stdout.strip() != version("matnocr"): + raise RuntimeError("Console entry point returned an unexpected version") + print("Wheel and console smoke tests passed.") + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--diagnostics-only", action="store_true") + arguments = parser.parse_args() + print_diagnostics() + if not arguments.diagnostics_only: + smoke_test() + + +if __name__ == "__main__": + main()