Files
OCR/openspec/changes/archive/2025-12-08-refactor-dual-track-architecture/proposal.md
egg 940a406dce chore: backup before code cleanup
Backup commit before executing remove-unused-code proposal.
This includes all pending changes and new features.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2025-12-11 11:55:39 +08:00

69 lines
3.1 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# Change: Refactor Dual-Track Architecture
## Why
目前雙軌制 OCR 系統存在多個已知問題和架構債務:
1. **Direct Track 表格問題**: `_detect_tables_by_position()` 無法識別合併單元格,導致 edit3.pdf 產生 204 個錯誤拆分的 cells應為 83 個)
2. **OCR Track 圖片路徑丟失**: CHART/DIAGRAM 等視覺元素的 `saved_path` 在轉換時丟失,導致圖片未放回 PDF
3. **OCR Track cell_boxes 座標錯亂**: PP-StructureV3 返回的 cell_boxes 超出頁面邊界
4. **服務層過度複雜**: OCRService (2,326 行) 承擔過多職責,難以維護和測試
5. **PDF 生成器過於龐大**: PDFGeneratorService (4,644 行) 是單體服務,難以擴展
## What Changes
### Phase 1: 修復已知 Bug優先級最高
- **Direct Track 表格修復**: 改用 PyMuPDF `find_tables()` API 取代 `_detect_tables_by_position()`
- **OCR Track 圖片路徑修復**: 擴展 `_convert_pp3_element` 處理所有視覺元素類型 (IMAGE, FIGURE, CHART, DIAGRAM, LOGO, STAMP)
- **Cell boxes 座標驗證**: 添加邊界檢查,超出範圍時使用 CV 線檢測 fallback
- **過濾極小裝飾圖片**: 過濾 < 200 px² 的圖片
- **移除覆蓋圖像**: 在渲染階段過濾與 covering_images 重疊的圖片
### Phase 2: 服務層重構(優先級:高)
- **拆分 OCRService**: 提取獨立的 `ProcessingOrchestrator` 負責流程編排
- **建立 Pipeline 模式**: 使用組合模式取代目前的聚合模式
- **提取 TableRenderer**: PDFGeneratorService 提取表格渲染邏輯
- **提取 FontManager**: PDFGeneratorService 提取字體管理邏輯
### Phase 3: 記憶體管理簡化(優先級:中)
- **統一記憶體策略**: 合併 MemoryManagerMemoryGuard各類 Semaphore 為單一策略引擎
- **簡化配置**: 減少 8+ 個記憶體相關配置項到核心 3-4
### Phase 4: 前端狀態管理改進(優先級:中)
- **新增 TaskStore**: 使用 Zustand 管理任務狀態取代分散的 useState
- **合併類型定義**: 統一 api.ts apiV2.ts 為單一類型定義檔案
## Impact
- Affected specs: `document-processing`
- Affected code:
- `backend/app/services/direct_extraction_engine.py` (表格檢測)
- `backend/app/services/ocr_to_unified_converter.py` (元素轉換)
- `backend/app/services/ocr_service.py` (服務編排)
- `backend/app/services/pdf_generator_service.py` (PDF 生成)
- `backend/app/services/memory_manager.py` (記憶體管理)
- `frontend/src/store/` (狀態管理)
- `frontend/src/types/` (類型定義)
## Risk Assessment
| 風險 | 嚴重性 | 緩解措施 |
|------|--------|----------|
| 表格渲染回歸 | | 使用 edit.pdf edit3.pdf 作為回歸測試 |
| 記憶體管理變更導致 OOM | | 保留現有閾值僅重構代碼結構 |
| 服務重構導致處理失敗 | | 逐步重構每階段完整測試 |
## Success Metrics
| 指標 | 目前 | 目標 |
|------|------|------|
| edit3.pdf Direct Track cells | 204 (錯誤) | 83 (正確) |
| OCR Track 圖片放回率 | 0% | 100% |
| cell_boxes 座標正確率 | ~40% | 100% |
| OCRService 行數 | 2,326 | < 800 |
| PDFGeneratorService 行數 | 4,644 | < 2,000 |