Skip to content

About

Domain-neutral core for anonymizable report pipelines: extract source documents, build a schema-bound LLM prompt, fill a Word template with the result

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Latest commit

Β 

History

22 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

report-forge

ReportForge banner

Language: English | Deutsch | EspaΓ±ol

CI License Python Pytest Code Style Architecture Privacy Security SLA Status Context Organization Umbrella

Note

This repository is optimized for AI agents and automated workflows. Machine-readable specifications, runtime invariants, and integration blueprints can be found in llms.txt, SKILL.md, and MARKETING-LOG.txt.

Domain-neutral core engine for schema-bound, anonymizable report generation pipelines: extract source documents β†’ build LLM prompt bound to a JSON schema β†’ populate Word (.docx) template with structured LLM responses. Privacy modes switchable between mode="anonymized" (GDPR Art. 4(5) fail-closed pseudonymization) and mode="plain".


Table of Contents


πŸ—οΈ System Architecture

flowchart TD
    A["Source Documents<br/>(Word / PDF / Text / Excel / Mail)"] -->|"prepare()"| B["Session Workspace<br/>(prompt.txt & data_bundled)"]
    B -->|"External LLM Inference<br/>(Decoupled Process Boundary)"| C["JSON Structured Response<br/>(report.json)"]
    C -->|"finish()"| D["Finalized Report<br/>(.docx in output_dir)"]

    subgraph PrivacyLayer ["Privacy Protection Layer (Fail-Closed)"]
        E["anonymizer module &gt;=0.2.5<br/>(mode='anonymized')"]
    end
    E -.-|"PII Masking &amp; Keying"| B
    E -.-|"De-Anonymization"| D
Loading

πŸ”„ Lifecycle Sequence

The sequence diagram below visualizes the decoupled 3-phase execution lifecycle, highlighting the privacy boundary, external inference separation, and fail-closed schema validation:

sequenceDiagram
    autonumber
    actor Client as Caller
    participant Workflow as ReportWorkflow
    participant LLM as External LLM
    participant Generator as ReportGenerator
    participant Publisher as publish_copy
    Client->>Workflow: "prepare(source_folder, work_root, mode)"
    Note over Workflow: "Extract sources; anonymize when requested; write prompt and session"
    Workflow-->>Client: "PrepareResult(success, errors, session_dir, prompt_path)"
    Client->>LLM: "Submit prompt outside this module"
    LLM-->>Client: "Save report.json"
    Client->>Workflow: "finish(session_dir, llm_json_path, output_folder)"
    Note over Workflow: "Validate schema; return errors on invalid input"
    Workflow->>Generator: "fill_report(report_data, template_path, output_path)"
    Note over Workflow: "Restore identifiers locally in anonymized mode"
    opt "output_dir requested and local output succeeded"
        Workflow->>Publisher: "publish_copy(output_folder, output_dir)"
        Publisher-->>Workflow: "Unique path, or exception recorded as warning"
    end
    Workflow-->>Client: "FinishResult(success, errors, output_folder, published_path, warnings)"
Loading

⚑ Feature Overview

Feature Description Invariant
3-Phase Pipeline Clean separation of extraction (prepare), external inference, and rendering (finish) INV-FORGE-01
Fail-Closed Privacy Pseudonymization & Fernet encryption (mode="anonymized") via anonymizer module (β‰₯0.2.5) INV-FORGE-03
Schema Validation Strict JSON Schema validation (Draft 2020-12 / Draft 7) prior to document rendering INV-FORGE-02
Word Template Engine Deterministic .docx replacement ({{KEY}}, multi-run tokens, dynamic tables, checkboxes) INV-FORGE-04
Batch Inbox Runner One-shot process-inbox: .processed markers skip completed preparation; errors retry on the next invocation INV-FORGE-06
Publishing & Storage Complete copies to output_dir, atomically created without replacing existing files; timestamps and counters resolve collisions INV-FORGE-05
Non-Interactive CLI Headless CI/daemon execution via --*-env variable resolution with zero stdout secret leakage INV-FORGE-07
Local-First & Offline Complete zero-egress architecture; zero unexpected remote network calls or telemetry INV-FORGE-08

πŸ“¦ Installation

pip install .
pip install ".[formats]"  # Optional: PDF, Excel, and Outlook MSG extraction

The canonical runtime versions and optional format extras are declared in pyproject.toml. Optional anonymization requires the separately installed anonymizer module β‰₯0.2.5.


πŸš€ Quick Start

1. Plain Mode (mode="plain", unencrypted)

from pathlib import Path
from report_forge.workflow import ReportWorkflow

workflow = ReportWorkflow()

# Phase 1: Read source documents and construct schema-bound prompt
prepared = workflow.prepare(
    source_folder=Path("source_docs/"),
    work_root=Path("sessions/"),
    mode="plain",
)
if not prepared.success:
    raise RuntimeError(prepared.errors)
print(f"Session workspace initialized: {prepared.session_dir}")
print(f"Prompt prepared at: {prepared.prompt_path}")

# Phase 2: Execute external LLM (outside module boundary)
#          Save JSON output to: prepared.session_dir / "data_bundled" / "report.json"

# Phase 3: Validate JSON response, populate Word template, and publish report
finished = workflow.finish(
    session_dir=prepared.session_dir,
    llm_json_path=prepared.session_dir / "data_bundled" / "report.json",
    output_folder=Path("output/final_report.docx"),
)
if not finished.success:
    raise RuntimeError(finished.errors)
print(f"Report successfully rendered: {finished.output_folder}")

2. Anonymized Mode (mode="anonymized", Default)

When running in mode="anonymized", personal identifiers are pseudonymized prior to prompt construction:

prepared = workflow.prepare(
    source_folder=Path("client_docs/"),
    work_root=Path("sessions/"),
    mode="anonymized",
    real_name="Max Mustermann",
    birth_date="2012-05-14",
    password="secure-user-passphrase",
)

if not prepared.success:
    raise RuntimeError(prepared.errors)

# During finish(), provide the password to restore real identifiers in the final DOCX:
finished = workflow.finish(
    session_dir=prepared.session_dir,
    llm_json_path=prepared.session_dir / "data_bundled" / "report.json",
    output_folder=Path("output/final_report.docx"),
    password="secure-user-passphrase",
)
if not finished.success:
    raise RuntimeError(finished.errors)

πŸ“ Template Engine & Placeholders

report-forge includes a resilient .docx template engine (WordTemplateService):

  1. Simple Placeholders ({{KEY}}): Replaces tokens in paragraphs, table cells, headers, and footers, including tokens fragmented across multiple Word XML runs (w:r).
  2. Dynamic Table Rows (fill_table_rows): Clones template rows dynamically according to JSON array data, matching keys to configured table column mappings.
  3. ICF / Key-Field Table Patterns ({CODE-Field}): Fills matching code-field placeholders and purges rows devoid of data.
  4. Checkbox Toggling ([X] / [ ]): Toggles checkbox state characters or Wingdings glyphs deterministically based on boolean schema flags.

πŸ“₯ Batch Inbox & Publishing

Configure directory targets in config.json or config.local.json:

  • output_dir: Central destination directory for collision-proof report publication.
  • inbox_dir: Input pickup directory for the automated batch runner process-inbox.
# Run inbox processor in dry-run mode
python -m report_forge process-inbox --work sessions/ --mode plain --dry-run

πŸ’» CLI Usage

report-forge provides a full suite of CLI commands:

# Prepare a session prompt from source files
python -m report_forge prepare --source source_docs/ --work sessions/ --mode plain

# Validate and render from a completed LLM JSON
python -m report_forge finish --session sessions/20260911_010000 --json sessions/20260911_010000/data_bundled/report.json --output dist/report.docx

# Run the automated inbox processor
python -m report_forge process-inbox --work sessions/ --mode plain

# Inspect available schemas and templates
python -m report_forge --info

Non-Interactive & Headless CI Mode

Interactive terminal runs preserve hidden getpass prompts. In non-interactive environments (CI runners, cron daemons, pipes), resolve secrets via environment variables:

  • REPORT_FORGE_REAL_NAME, REPORT_FORGE_BIRTH_DATE, REPORT_FORGE_PASSWORD for prepare
  • REPORT_FORGE_PASSWORD for finish
  • REPORT_FORGE_INBOX_PASSWORD for process-inbox

The --*-env options accept environment variable names only (never raw secret values). Missing secrets in non-TTY mode terminate with exit code 2 immediately (fail-closed). Secrets are never printed to stdout or log files.


πŸ›‘οΈ Governance & Runtime Invariants

The report-forge architecture guarantees the following 8 runtime invariants:

Identifier Invariant Name Formal Specification
INV-FORGE-01 3-Phase Architectural Separation prepare(), external inference, and finish() remain strictly separated; inference never occurs in-process.
INV-FORGE-02 Schema-Bound Output Gate LLM JSON output must pass strict JSON Schema validation (Draft 2020-12 / Draft 7) prior to template rendering.
INV-FORGE-03 Fail-Closed Privacy Boundary mode="anonymized" requires anonymizer β‰₯0.2.5; missing dependencies or keys halt execution immediately without cleartext fallback.
INV-FORGE-04 Template Engine Integrity Multi-run XML placeholder substitutions and table expansions preserve valid OpenXML markup without corruption.
INV-FORGE-05 Collision-Safe Distribution Output copies to output_dir use native no-replace rename on Windows and atomic hardlinks on other systems, with timestamps and collision counters. Windows does not require hardlinks; other systems require hardlink support at the destination. Unsupported operations fail explicitly; finish retains its local output and reports a publish warning.
INV-FORGE-06 Idempotent Batch State process-inbox runs once, marks successful preparation with .processed, skips marked folders and retries failures on later calls. It provides no archive, quarantine, watcher or cross-process item lock.
INV-FORGE-07 Secret Leakage Prevention Secrets are resolved exclusively via secure TTY prompts or environment variable names, never logged or displayed.
INV-FORGE-08 Zero Unexpected Network Egress All document extraction, prompt generation, schema validation, and rendering execute 100% local-first.

🌐 Sister Repositories & Ecosystem

report-forge functions as the core reporting engine within the broader open-source ecosystem:

Repository Role & Focus Integration Point
anonymizer PII Masking & Cryptographic Engine Privacy protection layer for mode="anonymized"
foerderplaner Educational & Assessment Domain Overlay Domain overlay implementing ICF schemas and school report templates
worksheet-generator Educational Task Sheet Compiler Generates complementary exercise sheets and instructional handouts
coma Headless Multi-Agent Harness Orchestrates autonomous background report processing pipelines
usmc Universal State Machine Controller Governs batch pipeline transitions and lifecycle safety
open-bricks Umbrella Developer Tool Ecosystem Cross-project governance, standards, and packaging

πŸ§ͺ Testing & Verification

Run the comprehensive pytest suite:

PYTHONIOENCODING=utf-8 python -m pytest tests/ -ra -q

All 43 tests verify:

  • Functional 3-phase workflows (plain & anonymized prepare/finish)
  • DOCX template placeholder substitution & dynamic table generation
  • JSON schema validation gates & error formatting
  • Batch inbox processing state machine & collision protection
  • PEP 621 metadata, extended URLs, .gitignore hygiene, CI matrix, and documentation parity

πŸ”’ Security & Privacy

report-forge enforces strict local-first processing, zero unexpected network egress, and fail-closed pseudonymization. For vulnerability disclosures and security policies, see SECURITY.md.


πŸ“„ License

Distributed under the MIT License. See LICENSE for full details.

About

Domain-neutral core for anonymizable report pipelines: extract source documents, build a schema-bound LLM prompt, fill a Word template with the result

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages