Commit graph

665 commits

Author SHA1 Message Date
LLLin000
0859652396 feat(#81): Release N+1 owner cutover — Python 3.11+ gate, fail-closed dispatch
- managed-runtime: collapse MIN_PYTHON_LEGACY/MIN_PYTHON_NEW → MIN_PYTHON (3.11)
- managed-runtime: remove PYTHON_310_DEPRECATED warning (3.10 now needs_repair)
- managed-runtime: single 3.11+ hard gate for all installations
- settings: cut getCachedPython fallback in _resolveRuntimeCommand → fail-closed
- settings: update Python version notices 3.10→3.11
- i18n: update user-facing Python version messages 3.10→3.11
- Python backend: checker.py, setup_wizard.py, status.py → 3.11 minimum
- Test updates: legacy fallback tests now verify fail-closed, 3.10 gating removed

Build: 264.4KB | Tests: 384/384 passed | Typecheck: clean
2026-07-19 14:32:12 +08:00
LLLin000
69a6223910 feat: expose library OCR and memory capability tracers (#78) 2026-07-18 18:13:08 +08:00
LLLin000
349d4f6dcb feat: add streaming OCR rebuild progress 2026-07-14 18:05:49 +08:00
LLLin000
27e45f9419 feat(#37): auto-backup fulltext before rebuild
backup_render_before_rebuild() copies render/fulltext.md (and
render-map.json, heading-events.json) to versions/v{N}/ before
rebuild overwrites them. Creates/updates versions/manifest.json
with version metadata. Idempotent: skips when no render exists.

Hook placed between phase 3 and phase 4 in _rebuild_one_paper.

6 new tests.
2026-07-10 00:34:44 +08:00
LLLin000
06fec04651 feat: Phase 0, 1, 3a — legacy OCR fix, ChromaDB migration, search bar UI
Phase 0 (#35): _needs_derived_rebuild returns (False, 'legacy_ocr') for
papers without structured blocks and derived_version. _can_rebuild adds
has_structured check. No misleading rebuild suggestions for legacy users.

Phase 1 (#36): migrate_chroma_to_vec0() copies existing ChromaDB vectors
to vec0 tables with zero API calls. Idempotent (skips by paper_id).
delete_paper_vectors() cleans both ChromaDB and vec0. CLI: embed migrate.
5 new tests.

Phase 3a (#39): Search bar in collection panel — two-mode input
(M metadata / @ deep) with card results display. JSON output parsed
from search/retrieve CLI. 289 lines TypeScript, 175 lines CSS.
Build passes clean.

Co-authored-by: Phase0LegacyOcr <agent>
Co-authored-by: ChromaMigration <agent>
Co-authored-by: SearchBarUI <agent>
2026-07-10 00:02:02 +08:00
LLLin000
8699733b09 feat(#21): show structured_content_hash in paperforge status output
Add structured_content_hash field to OCRMaintenanceRow for display.
- Terminal table: new 'Hash' column showing first 12 chars of hash
- JSON output: structured_content_hash included in to_dict()
- Empty hash displayed as '-'
2026-07-09 18:14:15 +08:00
LLLin000
2b23ad716f feat(#20): hash-based OCR change detection — two-tier mtime+xxhash staleness
Replace version-constant-only detection with two-tier content-hash
detection against blocks.structured.jsonl.

Tier 1 (stat): compare st_mtime + st_size of blocks.structured.jsonl
against stored values in meta.json. Microsecond skip for unchanged files.

Tier 2 (hash): compute xxhash of the file when stat changes. If the hash
matches stored structured_content_hash, update mtime/size only (false
alarm recovery). If it differs, mark paper for rebuild.

Changes:
- pyproject.toml: add xxhash>=3.4.0 dependency
- paperforge/worker/ocr_versions.py: add compute_structured_hash()
- paperforge/worker/ocr_rebuild.py: _apply_post_rebuild_version_flags()
  writes hash+mtime+size to meta.json when vault+key provided
- paperforge/commands/ocr.py: _needs_derived_rebuild() two-tier check
  before version-constant fallback
- New tests: hash compute (hex, determinism, missing file),
  stat skip, hash match (false alarm recovery), hash mismatch trigger

61 tests pass (14 existing + 3 hash rebuild + 4 hash compute + 40 other).
2026-07-09 17:09:28 +08:00
LLLin000
89f5a3fce6 PR9A: Resume & Rebuild Correctness
- OCR rebuild --all: version/artifact-based selection via _needs_derived_rebuild()
- --status and explicit keys: manual override, no version filter
- Removed .done.{key} checkpoint markers from selection logic
- _apply_post_rebuild_version_flags now writes derived_version
- Embed resume entry: three-gate protection (stale state / missing DB / corrupt DB)
- _pid_alive() cross-platform PID health check
- _assert_collections_healthy() explicit ChromaDB probe
- 14 regression tests for selection logic, version flags, and resume guards
2026-07-06 22:33:08 +08:00
LLLin000
01461330bb fix: final hardening — policy revision + Layer A all green
- _body_unit_role_kind now excludes only reference_item/reference_heading
  (per policy: everything in fulltext except ref zone)
- backmatter_body unit_kind removed; all units are 'body'
- bounds_map in structure_tree uses page-qualified key (fixes collision
  when same block_id appears on different pages)
- Layer A test plan: emitted_ids uses page-qualified keys + handles
  block_id=0 (falsy value)
- Layer A: 1609 passed, 0 failed on real vault (22 papers)
- Unit tests: 152 passed, 1 pre-existing skip
2026-07-06 19:08:54 +08:00
LLLin000
77a6e0cfec fix: heading→emitted events, backmatter→heading events, page-qualified keys
- Section/subsection headings now appear in BOTH heading_events and
  emitted_block_events (emitted_as='heading') for complete event stream
- Backmatter headings (Funding/Acknowledgments/Data Availability/Conflicts)
  now generate heading_events → appear as structure tree sections with
  their own body_units
- Page-qualified block IDs (p{page}:{block_id}) in tree own/subtree_block_ids
  and body_units block_map: eliminates ambiguous block_id collisions when
  same block_id appears on multiple pages in real OCR data
- TC-9.2 wording fix, KEYS empty guard, global unit_id uniqueness check
2026-07-06 18:19:17 +08:00
LLLin000
288829bb5b feat: PR 1 — nested structure tree + body_units correctness
- RenderOutput dataclass with heading_events/emitted_block_events tracking
- Stack-algorithm structure tree with own/subtree block IDs
- Recursive body_units builder with role helper + token cap splitting
- Schema v4: section_path_json, section_level, section_title, part_ordinal
- Phase 4/5 reorder in ocr_rebuild.py and ocr.py
- 12 new test cases for tree nesting, own_block_ids, rendered-order intervals
2026-07-06 16:42:08 +08:00
LLLin000
b12ef301f9 fix: two regression fixes
1. sidecar match record now includes 'text': caption legend was
   missing from the rendered figure_001.md because the sidecar
   materialization did not copy the text field.

2. _find_table_caption_continuation now rejects actual <table> HTML
   blocks as continuations. Previously the very next block after a
   truncated caption (which was the table_html itself) got merged into
   caption_text.
2026-07-06 02:49:42 +08:00
LLLin000
36d7f79d50 fix: rescue single narrow side-caption figure layouts
Add a narrow sidecar rescue for the 37-like pattern:
- one formal narrow figure caption on a page
- same-row right-side image
- no x-overlap required
- bounded x-gap and strong y-overlap
- only when primary same-page matching missed the caption

This preserves the existing >=2 narrow-caption sidecar behavior while
rescuing left-caption/right-image layouts that previously fell to
cross_page_reservation.

Verified on real vault:
- 37LK5T97 page 2: FIG. 1 now matches as figure_001 via sidecar
- QGCAFI3P page 4: narrow side-caption rescued
- QZXT9L27 page 11: narrow side-caption rescued

Targeted tests: 296 passed
2026-07-06 02:38:59 +08:00
LLLin000
7b29ab68ca feat: improve vnext figure matching and split OCR status
This batch implements the validated PR-2 / PR-3 workstreams.

PR-2b: continued captions in vnext
- add figure continuation helpers
- mark continuation legends in candidate indexing
- run ContinuationCaptionPass before PrimarySamePagePass
- emit unique continuation records with trace metadata
- skip continuation legends in ordinary same-page proposals

PR-2a: short-caption geometry
- reuse _TRUNCATED_LEGEND_ONLY_PATTERN
- add narrow short-caption branch at the vnext group/page seam
- require same page, same column/x-overlap, tight gap, and local uniqueness
- avoid global threshold changes or score_figure_match edits

PR-3: completeness normalization and additive status split
- normalize legacy/vnext figure completeness shapes
- keep overall unchanged
- add structure_status, figure_status, table_status,
  dimension_statuses, status_reasons

Verification:
- 443 targeted tests passing
- real-vault rebuilds:
  * SKXTCE6M: unmatched_legends 6->0, overall green
  * SRNJDAA2: unmatched_legends 9->0, figure green
  * 6QNRHRKX: matched 0->4, figure yellow (improved, not solved)
  * 9DM6MCIF: unmatched_legends 3->0, figure green
  * XGT9Z257: unmatched_legends 4->0, figure green
  * V4UTP5X7: figure green while structure remains red
2026-07-06 00:55:40 +08:00
LLLin000
7c702b1bcf fix: exclude table-owned media and inline figure body refs from figure matching
PR-1 of the architecture review fixes.

Two entry-level filters before figure matching:

1. _is_table_owned_media(): excludes media_asset blocks with table
   roles/raw_labels/hints from the figure asset pool. Previously these
   entered as figure candidates and ended up as unmatched legends/orphans.

2. _looks_like_inline_figure_body_reference(): detects body text like
   'Figure 11-10 shows...' (hyphenated ranges, list ranges) and flags
   it as an inline reference, not a figure legend. Applied in both
   ocr_figures.py and ocr_roles.py for consistent early rejection.

Verified on real vault:
  SKXTCE6M: unmatched_legends 6→0, overall yellow→green
  SRNJDAA2: unmatched_legends 9→0

Tests: 384 pass (+9 new), 0 fail
2026-07-05 22:36:17 +08:00
LLLin000
cd352cb007 fix: rebuild path writes meta.ocr_health_overall
_phase4_render_health now returns (markdown, health_overall),
_phase5_finalize writes it to meta before write_json.

Also adds ADR with architecture review decisions:
- #2 Meta divergence — fixed
- #3 Quality signals for consumers — deferred to role-override v1
- #4 Health report richness — keep all fields
- #5 PDF lines cache — rejected
- #6 Integration tests — deferred to role-override v1
2026-07-05 22:02:40 +08:00
LLLin000
d50ea4631b fix: final cleanup before merge — stale test, helper, RGB safety
1. Stale test: test_extract_objects_renders_same_page_once_for_multiple_crops
   now asserts render_pdf_page_cached is NOT called (new PageRenderContext path)
   and pages/page_001.jpg is NOT created.

2. Extract _resolve_object_crop_pdf_path() helper with 4-case test.
   Phase 4 now uses it instead of inline fallback logic.
   Test locks in: Phase 1 resolved path beats stale meta['source_pdf'].

3. PageRenderContext: use fitz.csRGB in get_pixmap() for safe CMYK/n>3 handling.
   Removed fragile pix.n mode detection.

4. Added test_extract_and_write_objects_with_use_disk_page_cache_false_and_valid_pdf
2026-07-05 21:36:17 +08:00
LLLin000
643052489a fix: determinism + correctness fixes before further optimization
6 fixes bundled:

1. Cleanup: remove accidental empty file '6s}'

2. Rebuild determinism: add 'use_disk_page_cache' gate to _crop_asset_from_pdf.
   Rebuild (use_disk_page_cache=False) never reads or writes pages/page_XXX.jpg.
   All rendering goes through PageRenderContext in-memory.
   Legacy callers keep backward-compat behavior (default True).

3. PageRenderContext safety:
   - Only use when page_width>0 and page_height>0 and not rotation_deg
   - Fix Pixmap.n mode detection (L/RGB/RGBA -> convert to RGB)
   - Fix Image.Resampling name bug (Image -> PILImage)
   - Rotated crops always fall back to direct PDF clip path

4. Phase 1+2a merged traversal: always extract PDF lines on every page,
   regardless of whether span_metadata already exists. Fixes figure inventory
   data gaps when pages have pre-existing span coverage.

5. Phase 4: use resolved source_pdf_path from Phase 1, not ocr_meta['source_pdf']
   fallback (which may be stale or missing).

6. Added 5 determinism tests
2026-07-05 21:32:05 +08:00
LLLin000
b977adc1d8 perf: PageRenderContext — in-memory page rendering for Phase 4a, no disk writes
Add PageRenderContext class that renders each page once into memory
(PIL Image via get_pixmap + frombytes), shared across all crop tasks
in a single rebuild session. No full-page JPG is written to disk.

- _crop_asset_from_pdf: new fast path (page_render_context kwarg)
- Three task functions pass context through
- extract_and_write_objects opens PDF once, creates context, closes after
- Cold Phase 4a: 4.0s → 1.24s (60p, 30 unique pages, 42 crops)
- Full cold rebuild: 10.9s → 7.17s
2026-07-05 21:13:29 +08:00
LLLin000
9ebd1f3dcb perf: merge Phase 1+2a into single PDF pass, add _extract_lines_from_rawdict
- Extract PDF lines from rawdict data that was already fetched for span backfill,
  eliminating the separate page.get_text('dict') pass (~6s for 60 pages)
- Add _extract_lines_from_rawdict() helper to avoid rawdict re-parse
- Keep extract_pdf_lines_normalized() as backward-compatible API
- First-rebuild: 14.2s -> 10.9s (60p), 8.8s -> 8.0s (81p)
2026-07-05 20:55:10 +08:00
LLLin000
83b516aac0 fix: optimize span backfill with per-page rawdict batching and incremental re-extraction
- Group raw_blocks by page, call get_text('rawdict') once per page instead of once per block
  (1433 calls → 60 calls, 68s → 16.6s for a 60-page paper)
- Add _spans_from_rawdict() helper to filter cached rawdict by char bbox center overlap
- Keep extract_pdf_spans_for_block() as single-block compatibility API unchanged
- Add incremental backfill: skip pages where all blocks already have span_metadata
- Remove figure_title from _is_text_like_raw_block() coverage count (figure titles are
  typically image-rendered, not selectable PDF text)
- Add regression test: fast path output matches single-block API
2026-07-05 20:39:52 +08:00
LLLin000
c34ebbce81 feat: rebuild speed-up with parallel rebuild, threaded asset cropping, maintenance refactor, embed progress, CLI docs 2026-07-05 19:43:07 +08:00
LLLin000
7931f658bd feat: add rebuild-time fulltext backups and provenance 2026-07-05 17:00:41 +08:00
LLLin000
cdf969d85e feat: persist machine fulltext hash for initial OCR 2026-07-05 16:58:23 +08:00
LLLin000
1474c061a8 feat: surface drift state and invalidate maintenance cache 2026-07-05 16:52:17 +08:00
LLLin000
d8451947ad refactor: separate render artifact writes from user fulltext commit 2026-07-05 16:50:58 +08:00
LLLin000
0a3e40fd92 feat: add fulltext writeback state helpers 2026-07-05 16:45:31 +08:00
LLLin000
12b930c31d feat: add structure tree builder for paper navigation 2026-07-05 14:12:36 +08:00
LLLin000
7917858e24 feat: PR D — Base view cleanup
- Removed "重做OCR" view from build_base_views() (3 standard views)
- Changed ocr_status displayName to "状态"
- Removed ocr_redo property from _build_base_yaml()
- Removed deprecated ocr_redo insertion from _sanitize_base_file()
- Updated tests (28 passed)
2026-07-05 01:26:34 +08:00
LLLin000
b585e42ab2 fix: 3 micro-patches from 9.4/10 review
1. show_in_base — separate hidden from maintenance vs hidden from both
2. Unified is_degraded check — done_degraded and health yellow/red
   share one entry point
3. Hash error_summary in manifest instead of raw string
4. Fix Promise.withResolvers for ES compat
2026-07-05 01:19:59 +08:00
LLLin000
e15edb1161 feat: PR A — backend display contract + manifest
- 7 display fields on OCRMaintenanceRow (display_action, label, label_key,
  reason, reason_key, group, severity, visible_in_maintenance)
- _compute_display_fields() pure function with 12 mapping rules
- compute_maintenance_manifest() lightweight hash function
- Integration in collect_maintenance_rows()
- 45 tests covering all mapping rules + manifest
2026-07-05 00:53:18 +08:00
LLLin000
96fd9771ef fix(ocr-quality): contract polish — 4 P0/P1 fixes
1. compute_use_cases output uses status/gates/reasons (not recommended/gate_results)
2. write_feedback validates every mark has result_hash and fulltext_hash
3. load_readiness_policy(policy=...) bypasses user override (reproducible)
4. confidence_and_fallbacks yellow for degraded=True or weak span coverage

Minor: append_mark doesn't mutate caller dict; has_figure_evidence includes
unmatched_legend_count and held_count.
2026-07-04 23:38:03 +08:00
LLLin000
8aba7feb48 Merge branch 'feat/ocr-quality-feedback' 2026-07-04 23:28:29 +08:00
LLLin000
c76f1569aa feat(ocr-quality): add evaluate_readiness() with YAML policy evaluator
Adds readiness policy evaluator layer:
- load_readiness_policy() with deep-merge, importlib.resources, user override
- _resolve_field() dotted path resolver, _apply_op() operator matcher
- _check_hard_red() for hard-red rule evaluation
- evaluate_readiness() with weighted scoring + status determination
- compute_use_cases() for all 4 use cases (reading, qa, figure_table, chunking)
- Default YAML policy with weights, hard_red rules, use_case gates
- pyproject.toml: policies/*.yaml added to package-data
- 7 tests (B1-B7) covering all paths

17/17 tests pass (A10 + B7).
2026-07-04 23:28:06 +08:00
LLLin000
3299c606d7 feat(ocr-quality): add human feedback sidecar
Standalone module (ocr_quality_feedback.py) with:
- read_feedback / write_feedback (atomic via temp+rename)
- append_mark (auto-injects hashes, preserves old marks)
- resolve_human_validation (unreviewed/confirmed/disputed/stale)
- Hashes stored per-mark, stale detection via latest_mark hash comparison

5 unit tests covering roundtrip, hash validation, append, stale, and
resolve without UI dependency.
2026-07-04 23:24:06 +08:00
LLLin000
51e16066c9 feat(ocr-quality): add build_quality_indicators() with 5 normalizers
Creates new ocr_quality.py module as pure function layer between
build_ocr_health() and evaluate_readiness(). All 5 indicators:
- rendered_text_integrity
- body_reference_structure
- figure_table_integrity
- metadata_frontmatter_quality
- confidence_and_fallbacks

10 unit tests covering shape, thresholds, applicability,
health_profile spelling, inventory precedence, and run_integrity.
2026-07-04 23:23:51 +08:00
LLLin000
2216ac7d87 fix(pr3): remove same-column guard from body_blocks, fix _page_width_for_zone_block arg 2026-07-04 22:36:46 +08:00
LLLin000
53a5336b6a feat(pr3): add column-aware same-page reference boundary 2026-07-04 22:36:46 +08:00
LLLin000
59b303dd66 feat(pr4): add column compatibility check for figure caption-asset pairing 2026-07-04 22:35:57 +08:00
LLLin000
2375f3c984 feat(pr2): tighten figure caption heuristic with inline mention escape 2026-07-04 22:35:50 +08:00
LLLin000
17b02b8abf fix(pr4): handle column_band=0 falsy correctly in score_legend_to_group 2026-07-04 22:35:28 +08:00
LLLin000
5cac8d1e08 fix(pr4): remove unused _column_compatible_for_caption_asset helper 2026-07-04 22:29:09 +08:00
LLLin000
08a52dcb48 feat(pr4): add column compatibility check for figure caption-asset pairing 2026-07-04 22:28:43 +08:00
LLLin000
f97365b5b4 fix(pr2): return body_paragraph for inline figure mentions regardless of zone 2026-07-04 22:28:23 +08:00
LLLin000
30cc7c3f7b feat(pr2): tighten figure caption heuristic with inline mention escape 2026-07-04 22:28:17 +08:00
LLLin000
a138100398 fix(pr1): remove has_any_author gate from affiliation/email fallback 2026-07-04 22:17:43 +08:00
LLLin000
57bb73556b feat(pr1): add frontmatter render fallback for empty metadata 2026-07-04 21:57:04 +08:00
LLLin000
914acd6aa5 feat: enable OCR_PIPELINE_V3 by default
The V3 pipeline has been tested against the full 555-paper vault vs legacy:

  No diff: 547 (98.6%)
  Diff:     5 (0.9%) — all in v3's favor: 3 papers find 1 more figure
                        (v3 softens role before matching), 2 papers shift
                        1 block boundary (body_paragraph vs frontmatter_noise)
  Error:    3 (0.5%) — 2 missing raw data, 1 pre-existing v3 pipeline edge case

The 5 diffs are marginal improvements, not regressions. V3's shadow-normalize
approach defers role commit until after figure/table matching, so captions
that legacy normalize prematurely hardened to 'body_paragraph' are correctly
found as figure captions.

Changes:
- _ocr_pipeline_v3_enabled() defaults to True now; set OCR_PIPELINE_V3=0 to
  revert to legacy normalize-then-match order
- Test updated to assert default=True
- Full vault corpus diff script + result report archived
2026-07-04 20:04:39 +08:00
LLLin000
c42da204bb fix: expand crop bbox to include figure_inner_text (figures show their own labels)
figure_inner_text role means the text IS part of the figure content
(forest plot y-axis labels, nomogram variable names, panel markers).
The earlier fix listed the text as a separate below the image — that
was wrong: the text already lives inside the cropped image when the
crop bbox covers it.

Now extract_and_write_objects expands the crop bbox to include all
figure_inner_text blocks owned by the figure (via _object_owner_id,
same page). The cropped jpg contains the labels; render only emits
image + Legend.

Verified: M84CTEM9 figure_a001 (forest plot) now crops to 787x363
(previously 444x358 — missed the y-axis labels); figure_a002
(nomogram) still includes its variable labels. 105 focused tests pass.
2026-07-04 19:54:40 +08:00
LLLin000
34827f2af0 fix: merge figure_inner_text into figure render output
figure_inner_text role has been recognized (side-adjacent + contained
passes) but its blocks were dropped from body AND silently dropped from
figure render output — they had nowhere to go. The owner contract
(_object_owner_id) was already stamped on the block; the renderer
just never consumed it.

Three changes:
- extract_and_write_objects now accepts structured_blocks and matches
  figure_inner_text blocks to their owner figure via _object_owner_id
- render_figure_object_markdown merges the inner text as figure body
  (no separate Note section — figure_inner_text IS the figure content)
- tag_figure_contained_text now stamps _object_owner_id on contained
  blocks claimed via the matched-figure path, so contained text also
  flows back to its owning figure (previously only side-adjacent was
  bound)

Rebuild ordering fixed too: apply_object_writebacks now runs BEFORE
write_figure_inventory so claims land in the persisted inventory.

Tested: M84CTEM9 figure_a001.md now includes the forest plot y-axis
variable labels (Age/SPADI/Sex/...) as figure content; body no longer
leaks them; 105 focused tests pass.
2026-07-04 19:49:38 +08:00