Skip to content

About

This repository contains a "very simple" recept digitalisation application prototype. It is completely vibe coded and was a playground for different models and getting practical knowledge. The best way is run it as a docker-container.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Recipe Digitizer

License: MIT Python FastAPI Docker OCR

A modern web application for digitizing recipes from PDF files and web URLs — using OCR and multi-provider AI processing.


🏗️ Architecture

Architecture

Data flow (PDF): Browser → POST /api/upload → PDF saved → POST /api/process/{filename} → poppler-utils → Tesseract OCR → (optional) AI Service → Markdown → uploads/markdown/

Data flow (URL): Browser → POST /api/process/url → URL extractor (JSON-LD → trafilatura → readability → BeautifulSoup4) → (optional) AI Service → Markdown → uploads/markdown/

Download: Browser → GET /api/download/{filename} → file from uploads/pdf/ or uploads/markdown/

🧰 Tools & Versions

Python packages (requirements.txt)

Package Version Purpose
FastAPI 0.162.0 Web framework / REST API
Uvicorn 0.54.0 ASGI server
Jinja2 3.1.6 HTML templating
httpx 0.28.1 HTTP client (URL processing, AI providers)
Pillow 13.0.0 Image processing (OCR preprocessing)
pytesseract 0.3.13 Tesseract OCR binding
pdf2image 1.17.0 PDF → image conversion (via poppler)
beautifulsoup4 4.15.0 HTML parsing (URL fallback)
trafilatura 2.3.1 Main-content extraction
readability-lxml 0.9 Readability extraction
python-dotenv 1.2.4 .env configuration
python-multipart 0.0.32 File uploads

System dependencies

Tool Version Purpose
Python 3.14 (Docker image: python:3.14-slim) Runtime
Tesseract OCR system package (tesseract-ocr, tesseract-ocr-deu) Text recognition
poppler-utils system package PDF rendering
Docker / Compose optional Container hosting

🚀 Features

📁 PDF-Based Processing

  • PDF upload via a user-friendly web interface
  • OCR-based text extraction from scanned recipes (Tesseract)
  • PDF conversion via poppler-utils

🔗 URL-Based Processing

  • Intelligent extraction using multiple methods with automatic fallback:
    • JSON-LD/Schema.org for structured recipe data (best quality)
    • trafilatura for automatic main-content extraction
    • readability-lxml for readability-optimized extraction
    • BeautifulSoup4 as a last-resort fallback with recipe-specific parsing
  • Clean quantities such as "300 g flour", "200 g sugar"

🤖 AI-Powered Processing (optional)

  • Multi-provider support: Mammouth, OpenAI, Mistral, Groq, OpenRouter, DeepSeek, Ollama (local), Anthropic (Claude), Google Gemini
  • Provider switchable via environment variables (AI_PROVIDER, AI_API_KEY, AI_MODEL, AI_BASE_URL)
  • Intelligent recipe structuring in Markdown with consistent formatting
  • Output follows the language of the original recipe (not the UI language)

📄 Output & Export

  • Conversion to structured Markdown format with download option
  • Organized directory structure: PDFs in uploads/pdf/, Markdown in uploads/markdown/
  • Custom filenames: optional independent naming for all generated files

🎨 Modern Web Interface

  • Mobile-First Design: custom CSS design system with variables (colors, radii, shadows, spacing)
  • Touch-optimized: large touch targets (min. 44–48px), sticky header
  • Recipe Overview (/recipes): one-click display, client-side search, responsive card grid
  • Recipe Editor: EasyMDE/CodeMirror editor with live preview, automatic local drafts, Ctrl+S/Cmd+S save, data-loss protection
  • UI Internationalization: English (default) and German, switchable via header toggle (cookie-based)
  • Stable Template Engine: custom Jinja2 integration bypasses Starlette/FastAPI template bugs

📋 Requirements

Local Hosting

  • Python 3.9+
  • Tesseract OCR (tesseract-ocr, tesseract-ocr-deu)
  • Poppler Utilities (poppler-utils)

Docker Hosting

  • Docker + Docker Compose (all other dependencies are installed in the container)

🛠️ Installation

🖥️ Local Hosting

1. Install System Dependencies

Ubuntu/Debian:

sudo apt-get update
sudo apt-get install tesseract-ocr tesseract-ocr-deu poppler-utils

macOS (with Homebrew):

brew install tesseract poppler

2. Prepare the Project

cd recipe-digitizer

python -m venv .venv
source .venv/bin/activate   # Linux/macOS
# oder: .venv\Scripts\activate   # Windows

pip install -r requirements.txt

3. Configure Environment Variables

cp .env.example .env
nano .env

Examples:

# Mammouth (default)
AI_PROVIDER=mammouth
AI_API_KEY=sk-...

# OpenAI
AI_PROVIDER=openai
AI_API_KEY=sk-...

# Ollama (local)
AI_PROVIDER=ollama
AI_BASE_URL=http://localhost:11434/v1
AI_MODEL=llama3.1

4. Start the Application

mkdir -p uploads/pdf uploads/markdown static
python app.py

Open http://localhost:8000 in your browser.

🐳 Docker Hosting

1. Configure Environment Variables

cp .env.example .env
nano .env
# or export directly:
export AI_PROVIDER="mammouth"
export AI_API_KEY="sk-..."

2. Start the Application

docker-compose up --build

Open http://localhost:8000 in your browser.

3. Additional Docker Commands

docker-compose up -d --build      # start in background
docker-compose logs -f            # view logs
docker-compose down               # stop containers
docker-compose build --no-cache   # rebuild image

Volumes (configured automatically in docker-compose.yml):

  • uploads/ — persistent file storage
  • static/ — live CSS/JS updates without rebuilding
  • templates/ — live template updates

⚠️ Note: src/ (including endpoints.py) is not mounted as a volume — after backend changes run docker-compose up --build.

📖 Usage

  1. Upload PDF: For scanned or PDF recipes → process → download Markdown
  2. Process URL: Enter a recipe URL (e.g. https://www.chefkoch.de/rezepte/12345/) → process → download Markdown
  3. My Recipes: Overview of all digitized recipes with Markdown rendering, search, and built-in editing

Filename note: The optional custom filename is used for both files (uploads/pdf/<name>.pdf and uploads/markdown/<name>.md). Without user input, a filename is generated automatically.

🔑 Environment Variables

Variable Description
AI_PROVIDER Selected AI provider (default: mammouth). Values: mammouth, openai, mistral, groq, openrouter, deepseek, ollama, anthropic, gemini
AI_API_KEY API key for the selected provider (not required for Ollama)
AI_MODEL Optional model override; otherwise a cheap provider default applies (see below)
AI_BASE_URL Optional base URL override (e.g. http://localhost:11434/v1 for Ollama or a proxy server)

Default models (cheap models, sufficient for recipe structuring)

Provider Default model
Mammouth gpt-5.4-nano
OpenAI gpt-6-luna
Mistral mistral-small-latest
Groq openai/gpt-oss-20b
OpenRouter openai/gpt-6-luna
DeepSeek deepseek-flash
Ollama llama3.1
Anthropic claude-haiku-5-5
Google Gemini gemini-flash-latest

Configuration Flow

  1. src/config.py loads the .env file (if it exists)
  2. Falls back to the system environment variable
  3. Works in Docker (environment variable) and locally (.env)

📁 Project Structure

recipe-digitizer/
├── app.py                       # FastAPI app + custom render_template()
├── requirements.txt             # Python dependencies (pinned versions)
├── Dockerfile                   # Docker configuration (python:3.14-slim)
├── docker-compose.yml           # Docker Compose with volumes
├── .env.example                 # Environment variable template
├── docs/
│   └── architecture.svg         # Architecture diagram (this README)
├── src/                         # Modular source code
│   ├── config.py                # Central configuration (dotenv + env, provider resolution)
│   ├── i18n.py                  # UI translations (en/de)
│   ├── api/endpoints.py         # All REST API endpoints
│   ├── services/ai_service.py   # Multi-provider AI service
│   └── utils/
│       ├── pdf_extractor.py     # OCR & Markdown conversion
│       ├── url_extractor.py     # HTML → text (legacy)
│       └── url_extractor_enhanced.py  # JSON-LD + trafilatura + readability + BS4
├── templates/                   # Jinja2 HTML templates
│   ├── base.html · index.html · recipes.html
│   └── partials/header.html     # Sticky navigation + language toggle
├── static/
│   ├── css/style.css            # Mobile-first design system
│   └── js/main.js               # Frontend logic (PDF + URL)
├── uploads/                     # File storage (created at startup)
│   ├── pdf/ · markdown/
└── tests/                       # Full test suite (see tests/README.md)

Architecture principles: separation of concerns (API / services / utils), modularity, reusability, easy extensibility.

🌐 API Endpoints

All API endpoints live in src/api/endpoints.py.

Health & Pages

  • GET / — main page
  • GET /recipes — recipe overview page (frontend)
  • GET /api/health — health check ({"status": "healthy"})

PDF Processing

  • POST /api/upload — PDF upload (FormData: file, optional custom_filename)
  • POST /api/process/{filename} — PDF → Markdown conversion (JSON: optional use_ai, custom_filename)

Upload response:

{
  "filename": "mein_rezept.pdf",
  "saved_path": "uploads/pdf/mein_rezept.pdf",
  "directory": "pdf"
}

Process response:

{
  "markdown_filename": "mein_rezeptname.md",
  "markdown_path": "uploads/markdown/mein_rezeptname.md",
  "pdf_filename": "hochgeladenes_rezept.pdf",
  "directory": "markdown"
}

URL Processing

  • POST /api/process/url — URL → Markdown conversion

Request:

{
  "url": "https://www.chefkoch.de/rezepte/12345/rezeptname",
  "use_ai": true,
  "custom_filename": "mein_rezeptname"
}

Response:

{
  "markdown_filename": "mein_rezeptname.md",
  "markdown_path": "uploads/markdown/mein_rezeptname.md",
  "original_url": "https://www.chefkoch.de/rezepte/12345/rezeptname",
  "directory": "markdown"
}

Recipe Management

  • GET /api/recipes/list — list of all Markdown recipes
  • GET /api/recipes/{filename} — content of a specific recipe
  • PUT /api/recipes — overwrite a recipe ({"filename", "content"}); no creation of new files, 400 on directory traversal, 404 if missing

Download

  • GET /api/download/{filename} — file download, optional ?directory=pdf|markdown (all directories searched if omitted; old files in uploads/ root remain supported)

🐳 Docker Details

  • Base image: Python 3.14-slim
  • System packages: poppler-utils, tesseract-ocr, tesseract-ocr-deu
  • Port: 8000 exposed
  • Stable template rendering: custom Jinja2 integration (bypasses Starlette/FastAPI incompatibilities)
volumes:
  - ./uploads:/app/uploads       # persistent uploads
  - ./static:/app/static         # live CSS/JS updates
  - ./templates:/app/templates   # live template updates

environment:
  - AI_PROVIDER=${AI_PROVIDER:-mammouth}

env_file:
  - .env

🔧 Development & Testing

from src.services.ai_service import ai_service
from src.utils.pdf_extractor import extract_text_from_pdf
from src.utils.url_extractor_enhanced import extract_recipe_url
# Run all tests (one at a time, sys.path setup included in each test)
for test in tests/*.py; do
  echo "=== Testing $test ==="
  python "$test"
done

# Specific tests
python tests/test_api_complete.py          # complete API test
python tests/test_recipe_edit.py           # recipe editing (GET/PUT + frontend)
python tests/test_docker_complete.py       # Docker E2E test
python tests/test_providers.py             # multi-provider tests (offline)
python tests/test_enhanced_url_extractor.py  # URL extraction diagnostics

Import gotcha: every test file must include sys.path.insert(0, str(Path(__file__).parent.parent)) — see tests/README.md.

🐛 Troubleshooting

401 Unauthorized (AI Service)
python -c "import os; from dotenv import load_dotenv; load_dotenv(); print('AI_API_KEY:', os.getenv('AI_API_KEY', 'NOT SET'))"

# In Docker:
docker exec -it rezept-digitizer python -c "import os; print('AI_API_KEY:', os.getenv('AI_API_KEY', 'NOT SET'))"
OCR / PDF problems
tesseract --version   # check Tesseract
pdftoppm -v           # check Poppler
URL extraction does not work or has poor quality
  • Check the internet connection; the URL must be publicly accessible (no login-protected pages)
  • JavaScript-heavy pages may be incomplete
  • For best quality, the page should contain structured JSON-LD/Schema.org data
  • Diagnose with python tests/test_enhanced_url_extractor.py
  • Check extraction_method in the API response (json-ld, trafilatura, readability, bs4)
Template rendering error (Starlette/Jinja2)
  • Symptom: TypeError: cannot use 'tuple' as a dict key (unhashable type: 'dict')
  • Cause: Starlette 1.1.0 + FastAPI 0.136.3 incompatibility
  • Solution: app.py uses a custom Jinja2 integration; ensure the pinned versions from requirements.txt are installed
Saving in the recipe editor does nothing

src/api/endpoints.py is not a Docker volume but part of the image — rebuild after backend changes:

docker-compose up --build

On 404/405 for PUT /api/recipes, the frontend displays a rebuild notice.

Docker: port conflicts / permissions / logs
docker ps                    # running containers
# different port: ports: "8001:8000" in docker-compose.yml
chmod 777 uploads            # or USER 1000:1000 in the Dockerfile
docker-compose logs -f
docker logs rezept-digitizer

🆕 Changelog

Version 1.8 — UI Internationalization
  • UI in English (default) and German, switchable via header toggle (cookie lang, 1 year)
  • Central translations in src/i18n.py; all templates use {{ t('key') }}
  • Recipe output follows the language of the original recipe (not the UI language)
  • URL extraction picks Markdown headings (## Zutaten vs ## Ingredients) based on detected content language
Version 1.7 — Multi-Provider AI Support
  • 9 providers via adapters (src/services/providers/): openai-compatible, Anthropic Messages API, Gemini generateContent
  • Generic key resolution: AI_API_KEY for all providers; AI_MODEL/AI_BASE_URL override defaults (legacy provider-specific keys removed)
Version 1.6.x — Recipe Editing Mode
  • EasyMDE editor with toolbar, live preview, side-by-side mode (desktop), automatic local drafts, Ctrl+S/Cmd+S
  • PUT /api/recipes endpoint with directory traversal protection
  • Mobile optimizations: 16px editor font (no iOS zoom), 44px touch toolbar, no horizontal overflow
  • Status messages inside the recipe view; rebuild notice on stale backend (404/405)
Version 1.5 — Mobile-First Redesign
  • Central design system with CSS variables, sticky navigation, touch-optimized controls, recipe search
  • Fixed horizontal overflow on mobile with long filenames
Version 1.4 — Stable Template Integration
  • Custom Jinja2 environment bypassing Starlette/FastAPI bugs; all dependencies updated and tested
Version 1.3 — Improved URL Extraction
  • JSON-LD/Schema.org support + trafilatura + readability fallbacks; clean quantities
Version 1.2 — Recipe Overview Page
  • Browser-based display of all recipes, one-click rendering, responsive navigation, recipe list API
Version 1.0 / 1.1 — Foundations
  • 1.0: PDF and URL processing, AI integration, Docker support
  • 1.1: Organized file management (uploads/pdf/, uploads/markdown/), custom filenames, unified API parameters

Possible Future Extensions

  • Batch processing (multiple PDFs/URLs at once)
  • Export formats (JSON, YAML, XML)
  • Image extraction from websites
  • OCR quality assessment
  • File deletion via the web interface

📄 License

Released under the MIT License — Copyright (c) 2026 Kamlkatze.

🙏 Acknowledgments

  • Tesseract OCR — open-source OCR engine
  • FastAPI — modern Python web framework
  • trafilatura & readability-lxml — improved content extraction
  • BeautifulSoup4 — HTML parsing fallback
  • Schema.org/JSON-LD — structured recipe data standard

About

This repository contains a "very simple" recept digitalisation application prototype. It is completely vibe coded and was a playground for different models and getting practical knowledge. The best way is run it as a docker-container.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages