Skip to content

feat: OCR pipeline and context optimization - #8

Merged
rookslog merged 8 commits into
mainfrom
feature/ocr-integration
Jan 6, 2026
Merged

feat: OCR pipeline and context optimization#8
rookslog merged 8 commits into
mainfrom
feature/ocr-integration

Conversation

@rookslog

Copy link
Copy Markdown
Owner

Summary

  • Add OCR pipeline module structure with two-tier dependencies
  • Condense CLAUDE.md via progressive disclosure (87% reduction)
  • Optimize project commands with progressive disclosure (~23% reduction)
  • Remove unused Context7 MCP from permissions

Changes

OCR Pipeline

  • New module structure for OCR integration
  • Two-tier dependency management

Context Optimization (Phases 1-5)

  • Phase 1: CLAUDE.md 523→68 lines, moved to docs/
  • Phase 4: Command optimization:
    • analyze-logs.md: automation → docs/LOG_ANALYSIS_AUTOMATION.md
    • init.md: templates → docs/INIT_TEMPLATES.md
    • improve.md, review-pr.md: condensed templates
  • Phase 5: Removed unused Context7 MCP

Test Plan

  • Run /project:init validate to verify setup
  • Test condensed commands work correctly
  • Verify Serena memories are accessible

- Add scholardoc/ocr/ module with 6 files (dictionary, linebreak, detector, reocr, pipeline, __init__)
- Update pyproject.toml with two-tier OCR strategy:
  - [ocr]: CPU-optimized with Tesseract (~1.35s per dirty page)
  - [ocr-gpu]: GPU-optimized with docTR + Tesseract fallback (~0.45s per dirty page)
- Core dependencies: pymupdf, pyspellchecker, pillow only
- OCR engines now optional for maximum compatibility

Part of Phase 1 milestone 1.6 (OCR correction pipeline)
Implements plan from .claude/logs/plan_ocr_integration.md
Moves 5 large plan files (~8k tokens) to .claude/logs/archive/
to reduce context overhead during sessions.

Archived:
- plan_ocr_implementation_session2.md
- plan_ocr_implementation_session2_REVISED.md
- plan_ocr_integration.md
- plan_convert_orchestrator.md
- plan_document_profiles.md

Session logs retained for /project:analyze-logs
- CLAUDE.md: 523 lines → 68 lines (87% reduction, ~4k token savings)
- Extracted to docs/:
  - VISION.md - Full vision and applications
  - TESTING_METHODOLOGY.md - Validation guidelines
  - COMMANDS.md - Full command reference
  - RULES.md - Development rules
  - GIT_WORKFLOW.md - Branching strategy

Part of context optimization initiative.
Phase 4-5 of context optimization:
- Extract automation examples from analyze-logs.md to docs/
- Extract templates from init.md to docs/INIT_TEMPLATES.md
- Condense output templates in improve.md and review-pr.md
- Remove unused Context7 MCP from permissions

Total word reduction: ~1327 words across 4 commands
- Move 5 commands from .claude/commands/ to .claude/agents/
  - analyze-logs, create-pr, diagnose, improve, review-pr
- Add session logs for development tracking
- Add backup files to .gitignore
Production-ready OCR correction pipeline for scholarly PDF extraction.

Components added to scholardoc/ocr/:
- AdaptiveDictionary: Morphological word validation with scholarly vocabulary
- OCRErrorDetector: Pattern-based error detection (96.9% detection rate)
- LineBreakRejoiner: Block-based hyphenation handling (ADR-003)
- HybridReOCREngine: 4-tier fallback (docTR GPU → Tesseract → docTR CPU → skip)
- OCRPipeline: Main orchestrator coordinating all components

Integration:
- Add OCRConfig to config.py (disabled by default for backward compatibility)
- Add OCRErrorType, OCRCorrectionRecord enums to models.py
- Integrate conditional OCR processing in convert.py

Validation results:
- Detection rate: 96.9% on 130 error pairs
- False positive rate: 20.8% (target ≤25%)
- 320 tests passing, including 37 new OCR unit tests

Closes Phase 1 of the OCR pipeline roadmap.
- Add 16 multilingual edge case tests:
  - Accented character handling (French, German)
  - Case sensitivity for scholarly vocabulary
  - Latin phrase recognition
  - Greek transliterations
  - Mixed-language text
  - OCR corruption scenarios
  - Edge cases (empty strings, punctuation, hyphenated terms)

- Add 7 validation set integration tests:
  - Detection rate verification (>= 95% target)
  - Detection rate by error type
  - False positive rate verification (<= 25% target)
  - Scholarly vocabulary verification
  - Pipeline integration with validation data
  - Regression tests for known difficult cases

- Add 6 performance tests:
  - Dictionary lookup speed (< 1ms per word)
  - Morphology check speed (< 5ms per word)
  - Detector page speed (< 50ms for 500 words)
  - Pipeline page speed (< 100ms for 500 words)
  - Bulk processing performance
  - Memory leak detection

Total: 349 tests passing (up from 320)
- Add OCRSourceInfo dataclass to models.py for tracking OCR engine metadata
- Parse PDF producer/creator fields to identify OCR engine (Adobe, ABBYY, Tesseract)
- Integrate OCR source extraction into DocumentBuilder.build()
- Store in QualityInfo.ocr_source for traceability

Documentation:
- Add ADR-004: OCR Source Tracking and Engine Validation
- Document current validation coverage (Adobe Paper Capture 2009-2023)
- Add multi-OCR-engine validation to future considerations in ROADMAP.md

Analysis: Current samples use Adobe Paper Capture only (single vendor, 14-year span).
Detection approach is engine-agnostic (dictionary + patterns), so should generalize.
@rookslog

rookslog commented Jan 6, 2026

Copy link
Copy Markdown
Owner Author

Code Review: Phase 1 OCR Integration

Reviewer: Claude Opus 4.5
Verdict: ✅ APPROVED with minor suggestions

Summary

This PR implements a well-designed OCR error detection and correction pipeline for scholarly documents. The architecture follows the validated ADR-002 approach of using spellcheck as a selector for re-OCR rather than auto-correction - the correct choice for scholarly text with specialized vocabulary.

Metrics

Metric Result Target Status
Detection rate 96.9% 99% ⚠️ Acceptable
False positive rate 20.8% ≤25% ✅ Pass
Tests passing 349 -

Strengths

  • Solid architecture: ADR-002/003/004 decisions are well-reasoned
  • Clean code: Good separation of concerns, comprehensive docstrings, proper type hints
  • Multilingual support: German, French, Latin, Greek philosophical vocabulary
  • Thorough tests: 66 unit tests + validation set + performance benchmarks
  • Backward compatible: Disabled by default, legacy pipeline preserved

Minor Issues (Non-blocking)

Location Issue
pipeline.py:197-210 Re-OCR line coordinate mapping incomplete (Phase 2 work)
config.py:38 min_confidence_to_flag defined but unused
convert.py:333 Language detection TODO deferred

Suggestions for Future

  1. Add confidence bands to OCRErrorCandidate for prioritization
  2. Make scholarly vocabulary extensible via config
  3. Track validation metrics in CI for regression detection

Risk Assessment

Area Risk
Detection accuracy Low - 96.9% acceptable; FPs safe
Performance Low - <100ms/page meets targets
Re-OCR integration Medium - Needs Phase 2 work

Reviewed using Opus 4.5. Full review saved to project memory.

@rookslog
rookslog merged commit 711674e into main Jan 6, 2026
2 checks passed
@rookslog
rookslog deleted the feature/ocr-integration branch February 18, 2026 19:27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant