Skip to content

Refactor: migrate pdf_parser.py to golang - #16323

Merged
JinHai-CN merged 22 commits into
infiniflow:mainfrom
xugangqiang:feat/oss-parser-to-go
Jun 25, 2026
Merged

JinHai-CN merged 22 commits into
infiniflow:mainfrom
xugangqiang:feat/oss-parser-to-go

Conversation

@xugangqiang

@xugangqiang xugangqiang commented Jun 24, 2026 •

Copy link
Copy Markdown
Contributor

What problem does this PR solve?

Http API based on onnx model.
pdf_parser.py to golang

Type of change

  • Refactoring

@coderabbitai

coderabbitai Bot commented Jun 24, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds an OSS DeepDoc service, Go-side client/render bridges, parser OCR and table-processing changes, and deployment/integration wiring with broad validation coverage.

Changes

DeepDoc OSS parser

Layer / File(s) Summary
Docs and deployment wiring
CLAUDE.md, docker/*, deepdoc/server/*, internal/parser/.gitignore
Documents the OSS DeepDoc service, Docker wiring, and package metadata alongside the new ignore rules.
DeepDoc service runtime
deepdoc/docker_stub/*, deepdoc/server/adapters/*, deepdoc/server/endpoints/*, deepdoc/server/deepdoc_svr.py
Implements the Docker stubs, DeepDoc adapters, LitServe endpoints, and the service entrypoint.
Parser bridges and renderers
go.mod, internal/parser/deepdoc.go, internal/parser/pdfoxide_bridge.go, internal/parser/renderer*.go, internal/parser/image_utils.go, internal/parser/python_char_adapter.go, internal/parser/mock_deepdoc_test.go, internal/parser/deepdoc_test.go, internal/parser/deepdoc_http_test.go, internal/parser/pdfium_integration_test.go, internal/parser/render_compare_test.go
Adds the Go DeepDoc client, PDF engine/render bridges, and HTTP/rendering tests.
Parser foundations
internal/parser/{cleanup,geometry,kmeans,position,garbled}.go, internal/parser/{cleanup,geometry,position,garbled,parser}_test.go
Adds low-level cleanup, geometry, clustering, position-tag, and garbled-text helpers.
Parser OCR and layout core
internal/parser/{parser,crop,layout}.go, internal/parser/{parser_ocr,crop,layout}_test.go, internal/parser/parser_test.go
Adds parser orchestration, OCR, crop/rotation helpers, and layout merging logic.
Table extraction and table post-processing
internal/parser/{table,table_builder,table_cells,table_layout}.go, internal/parser/{saas,oss}_deepdoc_service*.go, internal/parser/{deepdoc,table_layout,table_section,table_rotate}_test.go, internal/parser/parser_test.go, internal/parser/deepdoc_test.go
Adds table-builder interfaces, cell/layout grouping, table extraction, and table-focused unit tests.
Integration and parity tests
internal/parser/*integration_test.go, internal/parser/*_compare_test.go, internal/parser/chunk_test.go, internal/parser/generate_test.go, internal/parser/pipeline_parity_test.go, internal/parser/rotate_test.go, internal/parser/snapshot_test.go, internal/parser/scan_all_pdfs_test.go, internal/parser/table_parity*.go, internal/parser/deepdoc_no_crash_manual_test.go, internal/parser/ocr_merge_test.go, internal/parser/dla_*_test.go
Adds batch, parity, snapshot, rotation, and live-service integration tests across the parser and table flows.

Sequence Diagram(s)

sequenceDiagram
  participant Parser
  participant DeepDocClient
  participant DLAEndpoint
  participant OCREndpoint
  participant TSREndpoint
  Parser->>DeepDocClient: DLA / OCR / TSR calls
  DeepDocClient->>DLAEndpoint: POST /predict/dla
  DeepDocClient->>OCREndpoint: POST /predict/ocr with operator=det or rec
  DeepDocClient->>TSREndpoint: POST /predict/tsr
Loading

Estimated Code Review Effort

🎯 5 (Critical) | ⏱️ ~120 minutes

Suggested Labels

🧪 test

Poem

A bunny hopped through DeepDoc light,
With tables, OCR, and bridges bright.
I nibbled tests, then gave a cheer:
“This stack now hops from docs to gear!” 🐇

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 53.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title matches the main change: a refactor migrating the PDF parser from Python to Go.
Description check ✅ Passed The description includes the required problem statement and type-of-change section, and it aligns with the refactoring scope.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@xugangqiang xugangqiang changed the title Feat/oss parser to go Refactor: parser migration to to Jun 24, 2026
@xugangqiang xugangqiang added the ci Continue Integration label Jun 25, 2026
@xugangqiang
xugangqiang marked this pull request as ready for review June 25, 2026 03:02
@dosubot dosubot Bot added the size:XXL This PR changes 1000+ lines, ignoring generated files. label Jun 25, 2026
@xugangqiang
xugangqiang marked this pull request as draft June 25, 2026 03:11
@xugangqiang
xugangqiang marked this pull request as ready for review June 25, 2026 03:11
@dosubot dosubot Bot added the ☯️ refactor Pull request that refactor/refine code label Jun 25, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 20

Note

Due to the large number of review comments, Critical, Major severity comments were prioritized as inline comments.

🟡 Minor comments (13)
internal/parser/deepdoc_http_test.go-128-129 (1)

128-129: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Don't discard the FormFile error before dereferencing file/header.

If FormFile fails, file and header are nil, so defer file.Close() and header.Filename panic on the handler goroutine. Check the error and t.Errorf + return.

🛠️ Proposed fix
-		file, header, _ := r.FormFile("request")
-		defer file.Close()
+		file, header, err := r.FormFile("request")
+		if err != nil {
+			t.Errorf("missing 'request' multipart field: %v", err)
+			return
+		}
+		defer file.Close()
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/parser/deepdoc_http_test.go` around lines 128 - 129, The request
handler in deepdoc_http_test is ignoring the error from r.FormFile("request"),
which can leave file and header nil and cause a panic when file.Close() or
header.Filename is used. Update the FormFile handling to check the returned
error first, and in the handler or test path using those values, call t.Errorf
with the failure and return immediately before dereferencing file or header.
internal/parser/deepdoc_http_test.go-48-51 (1)

48-51: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Use t.Errorf + return inside the HTTP handler goroutine.

t.Fatalf here runs on the test server's handler goroutine, not the test goroutine. runtime.Goexit() only terminates the handler goroutine and may not reliably fail the overall test. The same applies to the t.Fatal calls at Line 122 and Line 167.

🛠️ Proposed fix
 	file, header, err := r.FormFile("request")
 	if err != nil {
-		t.Fatalf("missing 'request' multipart field: %v", err)
+		t.Errorf("missing 'request' multipart field: %v", err)
+		return
 	}

Based on learnings: inside an http.HandlerFunc, use t.Errorf(...) instead of t.Fatalf(...) because t.Fatalf only triggers runtime.Goexit() on the handler goroutine and may not fail the overall test.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/parser/deepdoc_http_test.go` around lines 48 - 51, The HTTP handler
in the deepdoc tests is calling t.Fatalf from the server goroutine, which can
exit only that goroutine and fail to surface the test failure reliably. In the
handler code around the multipart request handling in deepdoc_http_test.go,
replace t.Fatal/t.Fatalf usages with t.Errorf and then return from the handler
so the test goroutine can continue and observe the failure; apply the same
pattern to the other handler-side fatal calls in the same test (including the
ones in the upload flow and later assertions).

Source: Learnings

internal/parser/table_parity_test.go-35-53 (1)

35-53: 🎯 Functional Correctness | 🟡 Minor

LayoutType will fail to unmarshal — Add explicit JSON tags.

The Python dumper at internal/parser/tools/dump_py_results.py (lines 108–116) outputs a layout_type key, but the Go anonymous struct field is LayoutType. Go's json.Unmarshal matches case-insensitively but treats underscores as distinct from camelCase. Thus, LayoutType remains empty ("") silently. Other fields like x0, SP match correctly, but layout_type breaks parity coverage for this field.

Apply explicit JSON tags:

Suggested Update
			var pyBoxes []struct {
				X0         float64 `json:"x0"`
				X1         float64 `json:"x1"`
				Top        float64 `json:"top"`
				Bottom     float64 `json:"bottom"`
				Text       string  `json:"text"`
				R          int     `json:"R"`
				C          int     `json:"C"`
				H          int     `json:"H"`
				SP         int     `json:"SP"`
				LayoutType string  `json:"layout_type"`
			}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/parser/table_parity_test.go` around lines 35 - 53, The parity test’s
anonymous struct in the table parser test is not mapping the Python dumper’s
layout_type key into LayoutType, so that field stays empty during
json.Unmarshal. Update the pyBoxes struct in the test to use explicit JSON tags
for all fields, especially LayoutType with json:"layout_type", so the
unmarshaled data matches the output from dump_py_results.py and preserves field
parity.
internal/parser/renderer_pdfium.go-21-30 (1)

21-30: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Typed-nil guard is claimed in the comment but not implemented. Lines 21–22 say it guards against a typed-nil image, yet line 27 only checks plain img == nil. If pdfium.RenderPage ever returns a typed-nil (e.g. (*image.RGBA)(nil)) wrapped in a non-nil interface, it passes this check and panics later on .Bounds(). Mirror fallbackRender's reflect-based guard (or route both through the same helper).

🛡️ Align with fallbackRender
-	if img == nil {
+	if img == nil || (reflect.ValueOf(img).Kind() == reflect.Ptr && reflect.ValueOf(img).IsNil()) {
 		return nil, ErrNoPDFData
 	}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/parser/renderer_pdfium.go` around lines 21 - 30, The typed-nil
protection in the render path is incomplete: renderer_pdfium.go currently only
checks img == nil after pdfium.RenderPage, so a typed-nil image can still slip
through and panic later. Update the RenderPage flow to use the same
reflect-based typed-nil guard as fallbackRender, or extract that nil-check into
a shared helper and call it here so both render paths reject typed-nil images
consistently.
internal/parser/renderer.go-27-29 (1)

27-29: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

reflect.ValueOf(img).IsNil() can panic for non-nilable concrete kinds. IsNil panics unless the underlying kind is a pointer/slice/map/chan/func/interface. Standard image.Image impls are pointers, so this is safe today, but a value-type implementation would turn the guard into a panic. A Kind check makes it robust.

🛡️ Proposed guard
-	if img == nil || reflect.ValueOf(img).IsNil() {
+	if img == nil {
+		return nil, ErrNoPDFData
+	}
+	if v := reflect.ValueOf(img); v.Kind() == reflect.Ptr && v.IsNil() {
 		return nil, ErrNoPDFData
 	}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/parser/renderer.go` around lines 27 - 29, In renderer.go, the nil
guard in the image check uses reflect.ValueOf(img).IsNil(), which can panic for
non-nilable concrete types. Update the check in the renderer function that
handles img so it first handles a plain nil and then verifies the reflect.Value
kind is one of the nilable kinds before calling IsNil, keeping the ErrNoPDFData
return behavior unchanged.
deepdoc/servers/endpoints/ocr_endpoint.py-40-44 (1)

40-44: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Missing request form field will 500 instead of the documented 400.

If the request field is absent, request.get("request") returns None and .file.read() raises AttributeError, which surfaces as an internal 500 rather than the 400 the README documents for empty/corrupt input. Guard the lookup and raise a ValueError so the failure maps to a 400.

🛡️ Proposed guard
         else:
             # FormData: get file and operator form fields
-            data = request.get("request").file.read()
+            file_field = request.get("request")
+            if file_field is None:
+                raise ValueError("Missing 'request' file field")
+            data = file_field.file.read()
             op_val = request.get("operator")
             operator = str(op_val) if op_val else ""
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@deepdoc/servers/endpoints/ocr_endpoint.py` around lines 40 - 44, The FormData
handling in ocr_endpoint’s request parsing will 500 when the request field is
missing because request.get("request").file.read() assumes a present file
object. Update the branch that reads the uploaded file to first validate the
lookup result, and if the request field is absent or invalid, raise a ValueError
so the existing error mapping returns a 400 instead of an AttributeError-driven
500. Use the ocr endpoint’s request/form parsing logic and the
request.get("request") access path to locate the fix.
deepdoc/servers/adapters/ocr_adapter.py-33-47 (1)

33-47: 🩺 Stability & Availability | 🟡 Minor

Correct close() to iterate over recognizer/detector collections and log errors

The OCR class in deepdoc/vision/ocr.py initializes text_recognizer and detector as lists. The current close() implementation attempts to call .close() directly on the list objects, which raises an AttributeError that is silently swallowed, leaking resources.

Update the logic to iterate over each element in the collections and log any exceptions encountered:

    def close(self):
        """Clean up OCR model resources."""
        if self._ocr is not None:
            try:
                if hasattr(self._ocr, "detector") and self._ocr.detector is not None:
-                    self._ocr.detector.close()
+                    for det in self._ocr.detector:
+                        det.close()
            except Exception as e:
+                import logging
+                logging.error(f"Failed to close OCR detector: {e}")
+
            try:
                if hasattr(self._ocr, "text_recognizer") and self._ocr.text_recognizer is not None:
-                    self._ocr.text_recognizer.close()
+                    for rec in self._ocr.text_recognizer:
+                        rec.close()
            except Exception as e:
+                import logging
+                logging.error(f"Failed to close OCR text recognizer: {e}")
            self._ocr = None
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@deepdoc/servers/adapters/ocr_adapter.py` around lines 33 - 47, The OCR
cleanup in OCRAdapter.close is treating detector and text_recognizer as single
objects, but OCR initializes them as collections. Update close() to iterate
through each detector and recognizer item and call close() on each element
instead of the list itself. Keep the cleanup in OCRAdapter.close resilient, and
replace the silent pass blocks with error logging so any per-item close failures
are visible while still clearing self._ocr at the end.
deepdoc/servers/adapters/tsr_adapter.py-33-41 (1)

33-41: 🎯 Functional Correctness | 🟡 Minor

Remove unused model_dir parameter from TSRAdapter.

The model_dir parameter is accepted in __init__ but ignored during initialization. TableStructureRecognizer hardcodes its model path via get_project_base_directory() and does not accept an external path override. Keeping this unused parameter creates dead code and confusion.

Remove the parameter from TSRAdapter.__init__ to align with the actual implementation logic:

# deepdoc/servers/adapters/tsr_adapter.py
def __init__(self, thr: float = 0.2):
    self.thr = thr
    self._tsr: TableStructureRecognizer | None = None

Apply the same cleanup to OCRAdapter and DLAAdapter if they also ignore their model_dir arguments.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@deepdoc/servers/adapters/tsr_adapter.py` around lines 33 - 41,
TSRAdapter.__init__ accepts a model_dir argument that is never used, so remove
it and keep only the thr parameter to match the actual initialization flow in
TSRAdapter and TableStructureRecognizer. Update any call sites or constructor
signatures that reference TSRAdapter with model_dir, and apply the same cleanup
to OCRAdapter and DLAAdapter if their __init__ methods also ignore model_dir.
deepdoc/servers/endpoints/dla_endpoint.py-27-37 (1)

27-37: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Missing request form field yields an opaque AttributeError.

In the FormData branch, request.get("request") returns None when the field is absent, so .file.read() raises AttributeError: 'NoneType' instead of the intended ValueError("Empty request body"). A small guard gives clients a clear 4xx. The OCR and TSR endpoints share this pattern, so consider fixing consistently.

🛡️ Proposed guard
         if hasattr(request, "file"):
             data = request.file.read()
         else:
-            data = request.get("request").file.read()
+            file_field = request.get("request")
+            if file_field is None:
+                raise ValueError("Missing 'request' form field")
+            data = file_field.file.read()
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@deepdoc/servers/endpoints/dla_endpoint.py` around lines 27 - 37, The FormData
path in decode_request currently assumes request.get("request") always exists,
so a missing form field raises an AttributeError instead of the intended
ValueError. Add a guard before accessing .file.read() to handle a missing
request field and raise the same empty-body error path, and apply the same fix
consistently in the matching decode_request implementations used by the OCR and
TSR endpoints.
deepdoc/servers/_docker_common_init.py-6-6 (1)

6-6: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Non-numeric PARALLEL_DEVICES crashes at import.

int(os.environ.get("PARALLEL_DEVICES", "0")) runs at module-load time, so a malformed env value (e.g. empty string or "auto") raises ValueError and breaks every importer of this stub. Consider guarding the parse.

🛡️ Proposed guard
 class _Settings:
-    PARALLEL_DEVICES = int(os.environ.get("PARALLEL_DEVICES", "0"))
+    try:
+        PARALLEL_DEVICES = int(os.environ.get("PARALLEL_DEVICES", "0"))
+    except ValueError:
+        PARALLEL_DEVICES = 0
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@deepdoc/servers/_docker_common_init.py` at line 6, The PARALLEL_DEVICES
module constant is parsed eagerly in _docker_common_init, so a malformed
environment value can raise during import and break all callers. Update the
PARALLEL_DEVICES initialization to safely guard the int conversion in the
module-level config path, using a defensive parse with a fallback value when
os.environ.get("PARALLEL_DEVICES") is missing or non-numeric, so imports remain
robust.
deepdoc/servers/_docker_misc_utils.py-11-14 (1)

11-14: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Log torch-import fallback explicitly.

Swallowing ImportError without a log makes GPU/CPU provider selection hard to diagnose in production.

As per coding guidelines, **/*.py: Add logging for new flows.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@deepdoc/servers/_docker_misc_utils.py` around lines 11 - 14, The torch import
fallback in the module-level try/except is silently swallowing ImportError, so
add an explicit log in the except block to record that torch is unavailable and
the CPU/GPU provider path will be used. Update the import handling around the
torch import in the utility module to use the existing logging approach for
Python flows, so this fallback is visible during startup and easier to diagnose
in production.

Source: Coding guidelines

internal/parser/oss_deepdoc_service.go-91-96 (1)

91-96: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Use all row extents when synthesizing the fallback column.

When TSR omits column cells, the fallback column inherits X0/X1 from only the first row. Wider later rows will be clipped, so box matching and generated cells can miss text outside that first row.

Proposed fix
 	if len(cols) == 0 {
 		x0 := rows[0].X0
 		x1 := rows[0].X1
+		for _, row := range rows[1:] {
+			if row.X0 < x0 {
+				x0 = row.X0
+			}
+			if row.X1 > x1 {
+				x1 = row.X1
+			}
+		}
 		cols = []TSRCell{{X0: x0, Y0: rows[0].Y0, X1: x1, Y1: rows[len(rows)-1].Y1, Label: "table column"}}
 	}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/parser/oss_deepdoc_service.go` around lines 91 - 96, The fallback
column synthesis in ossDeepDocService currently uses only the first row’s X0/X1,
which can clip wider later rows. Update the fallback logic in the table parsing
path to compute the synthetic column bounds from all row extents in the rows
slice, while keeping the existing TSRCell construction and label. Use the
row-handling code around the len(cols) == 0 branch in ossDeepDocService to
locate the fix.
internal/parser/table.go-1538-1544 (1)

1538-1544: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Preserve layout metadata when converting boxes to crop space.

fillCellTextFromBoxes skips captions by LayoutType, but boxToCropSpace drops that field. Caption boxes whose text does not match the regex can be copied into table cells.

Proposed fix
 	return TextBox{
 		X0: b.X0*scale - cropOffX, X1: b.X1*scale - cropOffX,
 		Top: b.Top*scale - cropOffY, Bottom: b.Bottom*scale - cropOffY,
-		Text: b.Text,
+		Text:       b.Text,
+		LayoutType: b.LayoutType,
+		PageNumber: b.PageNumber,
 	}
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/parser/table.go` around lines 1538 - 1544, boxToCropSpace is
stripping layout metadata from TextBox, which breaks downstream filtering in
fillCellTextFromBoxes. Update boxToCropSpace to preserve the LayoutType field
(and any other relevant metadata on TextBox) when converting coordinates to
crop-pixel space so caption boxes can still be শনotted by their layout type
instead of falling through the regex path.
🧹 Nitpick comments (13)
internal/parser/table_parity_issues_test.go (1)

843-848: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low value

Compile the regex once outside the loop.

regexp.MustCompile(dataSourcePattern) is recompiled on every iteration. Hoist it out of the loop (or make a compiled package-level var) for clarity.

♻️ Suggested change
+	re := regexp.MustCompile(dataSourcePattern)
 	for _, tt := range tests {
-		matched := regexp.MustCompile(dataSourcePattern).MatchString(tt.text)
+		matched := re.MatchString(tt.text)
 		if matched != tt.want {
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/parser/table_parity_issues_test.go` around lines 843 - 848, Compile
dataSourcePattern once instead of inside the test loop: in the table-driven test
around the repeated regexp.MustCompile(dataSourcePattern).MatchString call,
hoist the compiled regex to a local variable before the for _, tt := range tests
loop (or use a package-level compiled var) and reuse it for each tt to avoid
recompiling on every iteration.
internal/parser/dla_realworld_test.go (1)

42-56: 🩺 Stability & Availability | 🔵 Trivial | 💤 Low value

defer eng.Close() in loop and single-digit page formatting are fragile.

defer eng.Close() accumulates and only runs when the test function returns, so all engines stay open for the whole run. Also string(rune('0'+pg)) (Lines 47, 55) only renders correctly for pg 0–9; any future fixture page ≥ 10 yields a wrong filename. Both are tolerable with the current single-page fixtures but worth tightening if this test grows.

♻️ Suggested adjustments
// close per-iteration instead of deferring to function end
func() {
    eng := mustOpenEngine(t, pdf.name)
    defer eng.Close()
    // ...
}()

// page formatting that survives >9
fmt.Sprintf("%s/page%d", pdf.name, pg)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/parser/dla_realworld_test.go` around lines 42 - 56, In the DLA
real-world test loop, avoid deferring eng.Close() at the outer loop scope so
engines are closed per PDF iteration instead of staying open until the test
returns; update the logic around mustOpenEngine and eng.Close to limit resource
lifetime. Also replace the fragile page-name construction using
string(rune('0'+pg)) in testName and imgPath with a proper numeric formatter in
the loop so page labels remain correct for multi-digit page numbers.
internal/parser/parser_ocr_test.go (1)

258-258: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Comment x0 values don't match the fixture.

The comment says 小(x0=3), 大(x0=15), 号(x0=30) but the chars above use X0: 3, 12, 24. The assertion is correct; only the inline comment is stale.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/parser/parser_ocr_test.go` at line 258, The inline X-order comment
in the OCR parser test is stale and does not match the fixture values. Update
the comment in parser_ocr_test.go near the assertion in the OCR test to reflect
the actual char positions used above (X0 3, 12, 24) while leaving the assertion
unchanged.
internal/parser/table_section_test.go (1)

389-398: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Dead computation in RenderPage mock.

w and h are computed but never used since the method returns nil, nil. Harmless for the tests (no caller decodes the bytes), but you can drop the dead locals to avoid confusion.

♻️ Simplify
 func (m *mockEngine) RenderPage(pg int, dpi float64) ([]byte, error) {
-	w, h := m.renderW, m.renderH
-	if w <= 0 {
-		w = 595
-	}
-	if h <= 0 {
-		h = 842
-	}
 	return nil, nil
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/parser/table_section_test.go` around lines 389 - 398, The
mockEngine.RenderPage helper contains dead local computations for w and h that
are never used because the method returns nil, nil; simplify the RenderPage mock
by removing those unused variables and any related fallback logic so the method
only keeps the behavior needed by the tests.
internal/parser/generate_test.go (1)

126-133: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low value

os.Stat inside the sort comparator runs O(n·log n) syscalls.

Each comparison stats both files, so sizes are fetched repeatedly. For a manual batch test this is fine, but pre-computing sizes once into a map (or a []struct{name; size}) before sorting avoids redundant syscalls and removes the per-compare error handling.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/parser/generate_test.go` around lines 126 - 133, The sort comparator
in generate_test.go is doing repeated os.Stat calls inside sort.Slice, which
causes redundant syscalls and per-compare error handling. Precompute the PDF
sizes once before sorting in the generate_test test helper (the logic around
sort.Slice(pdfs, ...) ), store them in a map or slice of name/size pairs, and
sort using those cached sizes while keeping a deterministic fallback for missing
metadata.
internal/parser/ocr_merge_test.go (1)

62-64: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Rune-unsafe truncation in log. b.Text[:end] with end = min(120, len(b.Text)) slices by bytes; for the Chinese scanned fixture this can split a rune and log invalid UTF-8. Diagnostic-only, so low impact. Same at Lines 70-72.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/parser/ocr_merge_test.go` around lines 62 - 64, The debug logging in
ocr_merge_test.go truncates b.Text by byte index in the test loop, which can
split multibyte runes and emit invalid UTF-8 for the Chinese fixture. Update the
truncation used in the logging block around the t.Logf call to slice by rune
count or otherwise preserve valid UTF-8, and apply the same fix to the matching
log at the other referenced location so both diagnostics remain rune-safe.
internal/parser/crop_integration_test.go (1)

39-39: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Byte-slicing on s.Text may split a multibyte rune.

s.Text[:min(30, len(s.Text))] slices by byte count; for Chinese fixtures (02_chinese_simple) this can cut mid-rune and emit invalid UTF-8 in the log. Since it's diagnostic-only the impact is cosmetic, but a rune-safe truncation is cleaner. Same pattern at Lines 44, 49, 53, and 89.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/parser/crop_integration_test.go` at line 39, The diagnostic logging
in crop integration tests slices s.Text by byte count, which can split multibyte
runes and produce invalid UTF-8 in logs. Update the truncation used in the
t.Logf calls in the crop integration test helpers to be rune-safe for s.Text,
and apply the same fix to all repeated occurrences in the test file, including
the log statements around the relevant crop cases.
internal/parser/deepdoc.go (2)

210-226: 🚀 Performance & Scalability | 🔵 Trivial | ⚖️ Poor tradeoff

OCRRecognizeBatch issues N sequential HTTP calls. Despite the "Batch" name it loops one image at a time, so latency scales linearly with crop count on the request path. If the DeepDoc OCR endpoint accepts multiple regions per request, consider a true batched call; otherwise bounded concurrency would help. Verify the server contract before changing.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/parser/deepdoc.go` around lines 210 - 226, OCRRecognizeBatch
currently makes one OCRRecognize call per image in a plain loop, so the “batch”
path is still fully sequential. Update DeepDocClient.OCRRecognizeBatch to either
use a true multi-region DeepDoc endpoint if the server supports it, or add
bounded concurrency around the existing OCRRecognize calls while preserving the
results/errs ordering and nil-image handling. Keep the existing OCRRecognize and
OCRRecognizeBatch signatures and ensure per-item errors still map to the same
input index.

75-75: 📐 Maintainability & Code Quality | 🔵 Trivial

Run gofmt -w on internal/parser/deepdoc.go.

Lines 75 (labels := c.DLALabels) and 107 (tlabels := c.TSRLabels) are indented with 1 tab, but they are inside a logic block already indented with 2 tabs. gofmt expects these lines to be indented with 2 tabs total to match the surrounding code structure.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/parser/deepdoc.go` at line 75, Update the formatting in deepdoc.go
by running gofmt on the parser code so the indentation inside the existing logic
block matches the surrounding structure. The misindented assignments in the
deepdoc parser, including labels in the DLALabels path and tlabels in the
TSRLabels path, should be aligned with the other statements in their blocks.
CLAUDE.md (1)

114-116: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Image tag here differs from the compose default.

The standalone build tags deepdoc_oss:latest, but docker/docker-compose.yml defaults DEEPDOC_IMAGE to infiniflow/deepdoc_oss:latest (and docker/.env sets the same). Readers building locally and expecting compose to pick up the image will be confused since the tags don't match. Consider aligning the documented build tag with the compose default.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@CLAUDE.md` around lines 114 - 116, The standalone DeepDoc OSS build tag does
not match the image name used by compose defaults, which will confuse local
setup. Update the documented docker build/run instructions in CLAUDE.md to use
the same image tag referenced by docker/docker-compose.yml and docker/.env (the
DEEPDOC_IMAGE default), so the standalone build produces the image compose
expects.
deepdoc/servers/pyproject.toml (1)

6-14: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

huggingface_hub is used by download_deps.py but isn't declared here.

deepdoc/servers/download_deps.py imports huggingface_hub and is part of this package. The script handles ImportError gracefully, so this isn't a hard failure, but a model download is required to run the service. Consider declaring huggingface_hub (e.g., as an optional extra) so the download step is reproducible from the manifest.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@deepdoc/servers/pyproject.toml` around lines 6 - 14, The server package
manifest is missing the dependency used by download_deps.py, so the model
download step is not reproducible from the declared requirements. Add
huggingface_hub to the packaging metadata in pyproject.toml, ideally as an
optional extra or other appropriate dependency group, and keep the declaration
aligned with the download_deps.py import so the package manifest reflects all
runtime requirements.
deepdoc/servers/download_deps.py (1)

36-42: 📐 Maintainability & Code Quality | 🔵 Trivial

Remove deprecated local_dir_use_symlinks argument

The local_dir_use_symlinks parameter is deprecated in huggingface_hub starting from version 0.29.0. Passing this flag currently triggers a deprecation warning and is ignored, as the library no longer uses the symlink mechanism for local directory downloads. Removing it is recommended to ensure clean execution and forward compatibility.

♻️ Proposed change
         hf_hub_download(
             repo_id=REPO_ID,
             filename=filename,
             local_dir=target_dir,
-            local_dir_use_symlinks=False,
             endpoint=hf_endpoint,
         )
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@deepdoc/servers/download_deps.py` around lines 36 - 42, Remove the deprecated
local_dir_use_symlinks argument from the hf_hub_download call in
download_deps.py; the download logic should keep using hf_hub_download with
repo_id, filename, local_dir, and endpoint only. Update the invocation inside
the dependency download flow so it no longer passes the ignored symlink flag,
preserving the same behavior while avoiding deprecation warnings.
deepdoc/servers/_docker_lazy_image.py (1)

5-15: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add a debug log when conversion falls back to None.

This path silently drops non-PIL input, which makes Docker parsing failures harder to trace.

As per coding guidelines, **/*.py: Add logging for new flows.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@deepdoc/servers/_docker_lazy_image.py` around lines 5 - 15, The fallback in
ensure_pil_image silently returns None for non-PIL inputs, so add a debug log in
that branch before returning None to make the conversion path traceable in
Docker. Use the ensure_pil_image function to locate the change, and log enough
context about the unsupported input type or conversion fallback so parsing
failures can be diagnosed without changing the return behavior.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@deepdoc/servers/adapters/dla_adapter.py`:
- Around line 35-43: The DLAAdapter initialization accepts model_dir but load()
ignores it by hardcoding LayoutRecognizer("layout"); update DLAAdapter.load() to
use the instance’s configured model path from self.model_dir so callers can
control which model is loaded, and keep the constructor/load contract aligned
with the _layouter setup.

In `@deepdoc/servers/deepdoc_svr.py`:
- Around line 41-48: The default --model-dir path in deepdoc_svr.py is
overshooting the repository root because it uses too many parent-directory
traversals. Update the argparse default in the model-dir setup to resolve from
deepdoc/servers via the correct number of ".." segments so it points to
rag/res/deepdoc within the project, and verify the path construction in the
parser.add_argument call for --model-dir.

In `@deepdoc/servers/endpoints/ocr_endpoint.py`:
- Around line 30-39: The operator lookup in decode_request is inconsistent
between the UploadFile path and the FormData path, causing the file branch to
miss the submitted operator value. Update the hasattr(request, "file") branch to
read operator directly from the request payload the same way the else branch
does, and remove the dependency on the private self._request attribute so both
branches resolve operator consistently.

In `@deepdoc/servers/endpoints/tsr_endpoint.py`:
- Around line 27-33: The fallback branch in decode_request currently assumes
request.get("request") always returns a valid object, which can raise an
AttributeError on malformed payloads. Update decode_request to validate the
fallback value before accessing .file, and return or raise the same handled
validation error path used for bad uploads when the key is missing or None. Keep
the fix localized to decode_request and preserve the existing Starlette
UploadFile/FormData handling.

In `@internal/parser/crop.go`:
- Around line 25-37: The position filtering in Crop logic accepts empty
PageNumbers, which later causes a panic when code like first.PageNumbers[0] is
accessed. Update the filtering in the Position selection flow in crop.go,
including the valid-position check used before indexing, to reject any Position
with an empty PageNumbers slice and treat it as invalid so the function returns
an empty string as documented.

In `@internal/parser/deepdoc_no_crash_manual_test.go`:
- Around line 68-77: The test in deepdoc_no_crash_manual_test.go is comparing
Section.TableItem against the address of a range loop copy, so the pointer check
is unstable and can fail even when the item exists. Update the verification
around result.Tables to iterate by index or otherwise take the address of the
actual slice element, and make sure Section.TableItem points to an element
stored in result.Tables rather than a temporary copy. Use the existing symbols
result.Tables, s.TableItem, and the table lookup loop in the manual test to
locate and fix the comparison.

In `@internal/parser/geometry.go`:
- Around line 18-23: CharWidth currently uses len(c.Text), which counts UTF-8
bytes instead of Unicode characters and produces incorrect widths for multi-byte
text. Update CharWidth in geometry.go to measure the text using
utf8.RuneCountInString, and add the unicode/utf8 import so the divisor matches
the Python reference behavior for multi-byte characters.

In `@internal/parser/ocr_merge_test.go`:
- Around line 5-10: The test in ocr_merge_test.go is missing the context package
needed by ocrMergeChars and ocrDetectAndRecognize. Add the context import
alongside the existing imports in the test file so the calls to
context.Background() compile correctly under the manual cgo test path.

In `@internal/parser/parser_ocr.go`:
- Around line 372-385: The batch OCR merge loop in parser OCR handling assumes
OCRRecognizeBatch always returns allTexts and allErrs entries for every needOCR
item, which can panic if either slice is shorter on partial failure. In the loop
that processes needOCR, add length checks before indexing allTexts[j] and
allErrs[j], and skip/log any missing result instead of dereferencing
out-of-range entries; keep the fix localized around OCRRecognizeBatch, allTexts,
allErrs, and the merge loop in parser_ocr.go.
- Around line 197-219: The OCR boxes produced in parserOCR are being returned in
raw image pixels instead of PDF-space coordinates, which makes them inconsistent
with the embedded-char path. Update the OCR box construction in parserOCR (where
TextBox values are appended after OCRRecognize) to convert x0/x1/y0/y1 back into
the same coordinate space used by ocrMergeChars, ideally by applying the render
scale rather than hard-coding 216 DPI. Keep the returned TextBox values aligned
with downstream layout/cropping expectations so scan-only OCR regions are
positioned correctly.

In `@internal/parser/parser.go`:
- Around line 40-43: The Parser state is not actually stateless because Parse
reads and clears debugDLA/debugTSR, which can race or leak debug data across
concurrent parses. Move this debug state out of Parser and make it per-parse
data, ideally flowing through Parse and enrichWithDeepDoc and returned via
ParseResult, or otherwise protect the mutable fields with synchronization. Also
remove or soften the stateless claim in the Parser comments/docs so it matches
the actual behavior.
- Around line 481-483: The early return in parser.go within
enrichWithDeepDoc/parser flow is skipping DLA/table enrichment whenever OCR
yields no text boxes, even if page images are present. Update this logic so
image-only pages still proceed into the deep-doc/table enrichment path instead
of returning immediately; only bypass enrichment when there are truly no page
images or no eligible content to analyze. Use the surrounding enrichWithDeepDoc
flow and the boxes/page image checks to preserve table/figure detection for
image-only pages, matching the behavior expected by the table_section_test
cases.
- Around line 447-448: `mergeCaptions` is changing figure section text after
`result.Figures` has already been collected, so the figure list becomes stale.
Update the parser flow in `parser.go` around `CollectFigures` and
`mergeCaptions` so figures are recomputed from the final `result.Sections` after
caption merging, keeping `result.Figures` and the section list consistent.
- Around line 593-600: The text assembly in fullTextFromChars is
non-deterministic because it ranges over pageChars as a map and it can merge
text across page boundaries, which affects isScanNoise. Update fullTextFromChars
to process pages in sorted key order, and insert a clear delimiter between pages
so word-run detection stays page-bounded. Keep the fix localized to
fullTextFromChars and any nearby isScanNoise callers that depend on its output.

In `@internal/parser/saas_deepdoc_service.go`:
- Around line 76-83: The table grouping logic is dropping `table column` TSR
cells because `clmns` is collected in `gatherTSR` and sorted in `sortXFirstly`,
but never merged into `grouped` when rows are present. Update the table assembly
flow in the `groupTSRCellsToRows`/row-grouping path to assign `clmns` into the
overlapping row groups the same way spans are handled, or remove the separate
branch if these cells are meant to be ignored. Make the same correction in the
duplicate logic referenced by the other affected block so `table column` cells
remain in the final table grid.

In `@internal/parser/table_layout.go`:
- Around line 3-6: The table layout parser is treating the first grid row as an
implicit header, never fills span annotations, and writes header/span positions
as zero-based values that downstream logic treats as unset. Update the table
layout/annotation generation logic in the code that builds `headers`, `spans`,
and emits `H`/`SP` so only explicit labels populate header/span metadata and the
stored positions are 1-based (or otherwise non-zero) to preserve the first
header/span and avoid marking ordinary first rows as headers.

In `@internal/parser/table.go`:
- Around line 200-208: The image-only table path in the table merge/replacement
flow is losing page metadata because `Positions` remains empty when `tm.boxIdx`
has no entries, causing downstream merge logic to drop multi-table results and
the fallback to emit `PageNumber: 0`. Update the table handling around
`tm.boxIdx`/`positions` to create a DLA-region fallback `Position` when no boxes
are present, and make the replacement emission logic use that fallback so
image-only tables still carry the correct page information.
- Around line 3-13: The table HTML rendering path currently writes
user-controlled PDF text directly into captions and cell bodies, which can emit
unsafe markup. Update the table rendering logic in the parser/table.go flow that
builds the `<caption>` and cell content (including the related code in the
1569-1604 range) to escape text before appending it to HTML, using the existing
HTML/text escaping approach consistently for all table strings.
- Around line 140-145: In extractTableAndReplace, do not append a TableItem when
tableBuilder.DetectCells returns an error or an empty cells slice; currently
that can cause a zero-cell item to be treated as a table removal signal and drop
the original text. Update the TSR handling around DetectCells so it logs the
warning and then continues without adding a TableItem unless cells were actually
detected, and apply the same guard in the later caller path that feeds
extractTableAndReplace.
- Around line 175-178: Rotated cell bounds are being mapped back in parser logic
without re-normalizing the rectangle, so `cells[i]` can end up with inverted
coordinates after `mapRotatedPointToOriginal` is applied in the table parsing
loop. Update the bounds normalization in `internal/parser/table.go` after the
`mapRotatedPointToOriginal` calls so each cell preserves `X0 <= X1` and `Y0 <=
Y1`, especially for 90°/270° rotations, before any later overlap or span checks
use the values.

---

Minor comments:
In `@deepdoc/servers/_docker_common_init.py`:
- Line 6: The PARALLEL_DEVICES module constant is parsed eagerly in
_docker_common_init, so a malformed environment value can raise during import
and break all callers. Update the PARALLEL_DEVICES initialization to safely
guard the int conversion in the module-level config path, using a defensive
parse with a fallback value when os.environ.get("PARALLEL_DEVICES") is missing
or non-numeric, so imports remain robust.

In `@deepdoc/servers/_docker_misc_utils.py`:
- Around line 11-14: The torch import fallback in the module-level try/except is
silently swallowing ImportError, so add an explicit log in the except block to
record that torch is unavailable and the CPU/GPU provider path will be used.
Update the import handling around the torch import in the utility module to use
the existing logging approach for Python flows, so this fallback is visible
during startup and easier to diagnose in production.

In `@deepdoc/servers/adapters/ocr_adapter.py`:
- Around line 33-47: The OCR cleanup in OCRAdapter.close is treating detector
and text_recognizer as single objects, but OCR initializes them as collections.
Update close() to iterate through each detector and recognizer item and call
close() on each element instead of the list itself. Keep the cleanup in
OCRAdapter.close resilient, and replace the silent pass blocks with error
logging so any per-item close failures are visible while still clearing
self._ocr at the end.

In `@deepdoc/servers/adapters/tsr_adapter.py`:
- Around line 33-41: TSRAdapter.__init__ accepts a model_dir argument that is
never used, so remove it and keep only the thr parameter to match the actual
initialization flow in TSRAdapter and TableStructureRecognizer. Update any call
sites or constructor signatures that reference TSRAdapter with model_dir, and
apply the same cleanup to OCRAdapter and DLAAdapter if their __init__ methods
also ignore model_dir.

In `@deepdoc/servers/endpoints/dla_endpoint.py`:
- Around line 27-37: The FormData path in decode_request currently assumes
request.get("request") always exists, so a missing form field raises an
AttributeError instead of the intended ValueError. Add a guard before accessing
.file.read() to handle a missing request field and raise the same empty-body
error path, and apply the same fix consistently in the matching decode_request
implementations used by the OCR and TSR endpoints.

In `@deepdoc/servers/endpoints/ocr_endpoint.py`:
- Around line 40-44: The FormData handling in ocr_endpoint’s request parsing
will 500 when the request field is missing because
request.get("request").file.read() assumes a present file object. Update the
branch that reads the uploaded file to first validate the lookup result, and if
the request field is absent or invalid, raise a ValueError so the existing error
mapping returns a 400 instead of an AttributeError-driven 500. Use the ocr
endpoint’s request/form parsing logic and the request.get("request") access path
to locate the fix.

In `@internal/parser/deepdoc_http_test.go`:
- Around line 128-129: The request handler in deepdoc_http_test is ignoring the
error from r.FormFile("request"), which can leave file and header nil and cause
a panic when file.Close() or header.Filename is used. Update the FormFile
handling to check the returned error first, and in the handler or test path
using those values, call t.Errorf with the failure and return immediately before
dereferencing file or header.
- Around line 48-51: The HTTP handler in the deepdoc tests is calling t.Fatalf
from the server goroutine, which can exit only that goroutine and fail to
surface the test failure reliably. In the handler code around the multipart
request handling in deepdoc_http_test.go, replace t.Fatal/t.Fatalf usages with
t.Errorf and then return from the handler so the test goroutine can continue and
observe the failure; apply the same pattern to the other handler-side fatal
calls in the same test (including the ones in the upload flow and later
assertions).

In `@internal/parser/oss_deepdoc_service.go`:
- Around line 91-96: The fallback column synthesis in ossDeepDocService
currently uses only the first row’s X0/X1, which can clip wider later rows.
Update the fallback logic in the table parsing path to compute the synthetic
column bounds from all row extents in the rows slice, while keeping the existing
TSRCell construction and label. Use the row-handling code around the len(cols)
== 0 branch in ossDeepDocService to locate the fix.

In `@internal/parser/renderer_pdfium.go`:
- Around line 21-30: The typed-nil protection in the render path is incomplete:
renderer_pdfium.go currently only checks img == nil after pdfium.RenderPage, so
a typed-nil image can still slip through and panic later. Update the RenderPage
flow to use the same reflect-based typed-nil guard as fallbackRender, or extract
that nil-check into a shared helper and call it here so both render paths reject
typed-nil images consistently.

In `@internal/parser/renderer.go`:
- Around line 27-29: In renderer.go, the nil guard in the image check uses
reflect.ValueOf(img).IsNil(), which can panic for non-nilable concrete types.
Update the check in the renderer function that handles img so it first handles a
plain nil and then verifies the reflect.Value kind is one of the nilable kinds
before calling IsNil, keeping the ErrNoPDFData return behavior unchanged.

In `@internal/parser/table_parity_test.go`:
- Around line 35-53: The parity test’s anonymous struct in the table parser test
is not mapping the Python dumper’s layout_type key into LayoutType, so that
field stays empty during json.Unmarshal. Update the pyBoxes struct in the test
to use explicit JSON tags for all fields, especially LayoutType with
json:"layout_type", so the unmarshaled data matches the output from
dump_py_results.py and preserves field parity.

In `@internal/parser/table.go`:
- Around line 1538-1544: boxToCropSpace is stripping layout metadata from
TextBox, which breaks downstream filtering in fillCellTextFromBoxes. Update
boxToCropSpace to preserve the LayoutType field (and any other relevant metadata
on TextBox) when converting coordinates to crop-pixel space so caption boxes can
still be শনotted by their layout type instead of falling through the regex path.

---

Nitpick comments:
In `@CLAUDE.md`:
- Around line 114-116: The standalone DeepDoc OSS build tag does not match the
image name used by compose defaults, which will confuse local setup. Update the
documented docker build/run instructions in CLAUDE.md to use the same image tag
referenced by docker/docker-compose.yml and docker/.env (the DEEPDOC_IMAGE
default), so the standalone build produces the image compose expects.

In `@deepdoc/servers/_docker_lazy_image.py`:
- Around line 5-15: The fallback in ensure_pil_image silently returns None for
non-PIL inputs, so add a debug log in that branch before returning None to make
the conversion path traceable in Docker. Use the ensure_pil_image function to
locate the change, and log enough context about the unsupported input type or
conversion fallback so parsing failures can be diagnosed without changing the
return behavior.

In `@deepdoc/servers/download_deps.py`:
- Around line 36-42: Remove the deprecated local_dir_use_symlinks argument from
the hf_hub_download call in download_deps.py; the download logic should keep
using hf_hub_download with repo_id, filename, local_dir, and endpoint only.
Update the invocation inside the dependency download flow so it no longer passes
the ignored symlink flag, preserving the same behavior while avoiding
deprecation warnings.

In `@deepdoc/servers/pyproject.toml`:
- Around line 6-14: The server package manifest is missing the dependency used
by download_deps.py, so the model download step is not reproducible from the
declared requirements. Add huggingface_hub to the packaging metadata in
pyproject.toml, ideally as an optional extra or other appropriate dependency
group, and keep the declaration aligned with the download_deps.py import so the
package manifest reflects all runtime requirements.

In `@internal/parser/crop_integration_test.go`:
- Line 39: The diagnostic logging in crop integration tests slices s.Text by
byte count, which can split multibyte runes and produce invalid UTF-8 in logs.
Update the truncation used in the t.Logf calls in the crop integration test
helpers to be rune-safe for s.Text, and apply the same fix to all repeated
occurrences in the test file, including the log statements around the relevant
crop cases.

In `@internal/parser/deepdoc.go`:
- Around line 210-226: OCRRecognizeBatch currently makes one OCRRecognize call
per image in a plain loop, so the “batch” path is still fully sequential. Update
DeepDocClient.OCRRecognizeBatch to either use a true multi-region DeepDoc
endpoint if the server supports it, or add bounded concurrency around the
existing OCRRecognize calls while preserving the results/errs ordering and
nil-image handling. Keep the existing OCRRecognize and OCRRecognizeBatch
signatures and ensure per-item errors still map to the same input index.
- Line 75: Update the formatting in deepdoc.go by running gofmt on the parser
code so the indentation inside the existing logic block matches the surrounding
structure. The misindented assignments in the deepdoc parser, including labels
in the DLALabels path and tlabels in the TSRLabels path, should be aligned with
the other statements in their blocks.

In `@internal/parser/dla_realworld_test.go`:
- Around line 42-56: In the DLA real-world test loop, avoid deferring
eng.Close() at the outer loop scope so engines are closed per PDF iteration
instead of staying open until the test returns; update the logic around
mustOpenEngine and eng.Close to limit resource lifetime. Also replace the
fragile page-name construction using string(rune('0'+pg)) in testName and
imgPath with a proper numeric formatter in the loop so page labels remain
correct for multi-digit page numbers.

In `@internal/parser/generate_test.go`:
- Around line 126-133: The sort comparator in generate_test.go is doing repeated
os.Stat calls inside sort.Slice, which causes redundant syscalls and per-compare
error handling. Precompute the PDF sizes once before sorting in the
generate_test test helper (the logic around sort.Slice(pdfs, ...) ), store them
in a map or slice of name/size pairs, and sort using those cached sizes while
keeping a deterministic fallback for missing metadata.

In `@internal/parser/ocr_merge_test.go`:
- Around line 62-64: The debug logging in ocr_merge_test.go truncates b.Text by
byte index in the test loop, which can split multibyte runes and emit invalid
UTF-8 for the Chinese fixture. Update the truncation used in the logging block
around the t.Logf call to slice by rune count or otherwise preserve valid UTF-8,
and apply the same fix to the matching log at the other referenced location so
both diagnostics remain rune-safe.

In `@internal/parser/parser_ocr_test.go`:
- Line 258: The inline X-order comment in the OCR parser test is stale and does
not match the fixture values. Update the comment in parser_ocr_test.go near the
assertion in the OCR test to reflect the actual char positions used above (X0 3,
12, 24) while leaving the assertion unchanged.

In `@internal/parser/table_parity_issues_test.go`:
- Around line 843-848: Compile dataSourcePattern once instead of inside the test
loop: in the table-driven test around the repeated
regexp.MustCompile(dataSourcePattern).MatchString call, hoist the compiled regex
to a local variable before the for _, tt := range tests loop (or use a
package-level compiled var) and reuse it for each tt to avoid recompiling on
every iteration.

In `@internal/parser/table_section_test.go`:
- Around line 389-398: The mockEngine.RenderPage helper contains dead local
computations for w and h that are never used because the method returns nil,
nil; simplify the RenderPage mock by removing those unused variables and any
related fallback logic so the method only keeps the behavior needed by the
tests.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

Comment on lines +35 to +43
def __init__(self, model_dir: str, thr: float = 0.2):
self.model_dir = model_dir
self.thr = thr
self._layouter: LayoutRecognizer | None = None

def load(self):
"""Initialize the layout recognizer. Called once per worker."""
self._layouter = LayoutRecognizer("layout")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ Data Integrity & Integration | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Confirm adapter-side usage
nl -ba deepdoc/servers/adapters/dla_adapter.py | sed -n '30,60p'

# Inspect LayoutRecognizer constructor/options
fd -i "layout_recognizer.py" deepdoc
ast-grep outline deepdoc/vision/layout_recognizer.py --view expanded || true
rg -n -C4 "class LayoutRecognizer|def __init__\\(" deepdoc/vision/layout_recognizer.py

Repository: infiniflow/ragflow

Length of output: 196


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Confirm adapter-side usage
cat -n deepdoc/servers/adapters/dla_adapter.py | sed -n '30,60p'

# Inspect LayoutRecognizer constructor/options
fd -i "layout_recognizer.py" deepdoc
if [ -f deepdoc/vision/layout_recognizer.py ]; then
    ast-grep outline deepdoc/vision/layout_recognizer.py --view expanded || true
    rg -n -C4 "class LayoutRecognizer\|def __init__" deepdoc/vision/layout_recognizer.py
else
    echo "File deepdoc/vision/layout_recognizer.py not found"
    # Fallback search for layout recognizer definitions
    fd -i "layout.*\.py" deepdoc
fi

Repository: infiniflow/ragflow

Length of output: 2232


Parameters model_dir is accepted but never used during model loading.

In load(), LayoutRecognizer is instantiated with a string literal "layout", completely ignoring the self.model_dir defined in the constructor. Consequently, callers cannot control the model path for this adapter instance.

    def load(self):
        """Initialize the layout recognizer. Called once per worker."""
        self._layouter = LayoutRecognizer("layout")
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@deepdoc/servers/adapters/dla_adapter.py` around lines 35 - 43, The DLAAdapter
initialization accepts model_dir but load() ignores it by hardcoding
LayoutRecognizer("layout"); update DLAAdapter.load() to use the instance’s
configured model path from self.model_dir so callers can control which model is
loaded, and keep the constructor/load contract aligned with the _layouter setup.

Comment on lines +41 to +48
parser.add_argument(
"--model-dir",
type=str,
default=os.path.join(
os.path.dirname(__file__), "..", "..", "..", "rag", "res", "deepdoc"
),
help="Model file directory",
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Confirm the location of rag/res/deepdoc relative to deepdoc/servers/deepdoc_svr.py
fd -t d -a 'deepdoc' rag/res 2>/dev/null
fd deepdoc_svr.py -a
fd -t d res rag -a 2>/dev/null
echo "--- tree of rag/res (if present) ---"
fd . rag/res -d 2 2>/dev/null

Repository: infiniflow/ragflow

Length of output: 309


Incorrect default --model-dir path resolution.

The default path construction uses three .. segments, which traverses from deepdoc/servers to the repository root and then overshoots to the parent directory. The file exists at deepdoc/servers/deepdoc_svr.py while the target models are located at rag/res/deepdoc relative to the repository root. Navigating to deepdoc then up to the root requires exactly two .. segments. The current path ../../../rag/res/deepdoc resolves outside the project directory, causing model loading failures.

Proposed fix
         default=os.path.join(
-            os.path.dirname(__file__), "..", "..", "..", "rag", "res", "deepdoc"
+            os.path.dirname(__file__), "..", "..", "rag", "res", "deepdoc"
         ),
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
parser.add_argument(
"--model-dir",
type=str,
default=os.path.join(
os.path.dirname(__file__), "..", "..", "..", "rag", "res", "deepdoc"
),
help="Model file directory",
)
parser.add_argument(
"--model-dir",
type=str,
default=os.path.join(
os.path.dirname(__file__), "..", "..", "rag", "res", "deepdoc"
),
help="Model file directory",
)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@deepdoc/servers/deepdoc_svr.py` around lines 41 - 48, The default --model-dir
path in deepdoc_svr.py is overshooting the repository root because it uses too
many parent-directory traversals. Update the argparse default in the model-dir
setup to resolve from deepdoc/servers via the correct number of ".." segments so
it points to rag/res/deepdoc within the project, and verify the path
construction in the parser.add_argument call for --model-dir.

Comment on lines +30 to +39
def decode_request(self, request):
# Handle both old Starlette UploadFile and new Starlette FormData
if hasattr(request, "file"):
data = request.file.read()
# Try to read operator from the underlying request context
operator = getattr(self, "_request", None)
if operator is not None:
operator = operator.query_params.get("operator", "")
else:
operator = ""

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major

🧩 Analysis chain

🌐 Web query:

In litserve 0.2.17, what object type does LitAPI.decode_request receive for a multipart/form-data POST, and how are form fields accessed?

💡 Result:

In LitServe (including version 0.2.17), the decode_request method receives a starlette.requests.Request object when handling a multipart/form-data POST request [1][2]. Because LitServe wraps Starlette, you access the form fields by awaiting the request.form() method within your decode_request implementation [1][2]. This returns a starlette.datastructures.FormData object, which behaves like a multi-dict that allows you to access uploaded files or simple form fields [2]. To handle multipart/form-data in your LitAPI subclass, you should define your decode_request method as an async function to accommodate the await call: async def decode_request(self, request): form = await request.form # Access a form field or file by its key file_item = form.get("your_field_name") # If the field is a file, it is typically an UploadFile object # from which you can read the file content file_bytes = await file_item.read return file_bytes Note that LitServe provides automatic handling for file uploads if you use specific type hints (like UploadFile) in certain contexts [3], but for manual multipart/form-data processing in decode_request, explicitly awaiting request.form() is the standard approach to access the form data structure [1][2].

Citations:


Align operator resolution in the file branch with the formData branch.

The if hasattr(request, "file") block ignores the operator form field and relies on a private self._request attribute that is likely unset, causing an empty operator and potential 400 errors. Read the operator directly from the request object (e.g., request.get("operator")) to match the logic used in the else block.

Diff suggestion
         if hasattr(request, "file"):
             data = request.file.read()
-            # Try to read operator from the underlying request context
-            operator = getattr(self, "_request", None)
-            if operator is not None:
-                operator = operator.query_params.get("operator", "")
-            else:
-                operator = ""
+            operator = request.get("operator", "") if hasattr(request, "get") else ""
         else:
             # FormData: get file and operator form fields
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def decode_request(self, request):
# Handle both old Starlette UploadFile and new Starlette FormData
if hasattr(request, "file"):
data = request.file.read()
# Try to read operator from the underlying request context
operator = getattr(self, "_request", None)
if operator is not None:
operator = operator.query_params.get("operator", "")
else:
operator = ""
def decode_request(self, request):
# Handle both old Starlette UploadFile and new Starlette FormData
if hasattr(request, "file"):
data = request.file.read()
operator = request.get("operator", "") if hasattr(request, "get") else ""
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@deepdoc/servers/endpoints/ocr_endpoint.py` around lines 30 - 39, The operator
lookup in decode_request is inconsistent between the UploadFile path and the
FormData path, causing the file branch to miss the submitted operator value.
Update the hasattr(request, "file") branch to read operator directly from the
request payload the same way the else branch does, and remove the dependency on
the private self._request attribute so both branches resolve operator
consistently.

Comment on lines +27 to +33
def decode_request(self, request):
# Handle both Starlette UploadFile (old) and FormData (Starlette >=1.3)
if hasattr(request, "file"):
data = request.file.read()
else:
data = request.get("request").file.read()
if not data:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Compare decode_request patterns across endpoint implementations
fd -i '*_endpoint.py' deepdoc/servers/endpoints | while read -r f; do
  echo "### $f"
  rg -n 'def decode_request|hasattr\(request,\s*"file"\)|request\.get\("request"\)' "$f" -C2
done

Repository: infiniflow/ragflow

Length of output: 449


Guard the fallback request path to prevent 500 errors on malformed payloads.

The fallback branch in decode_request assumes request.get("request") returns a valid object. If the key is missing or the value is None, accessing .file triggers an unhandled AttributeError, causing a server error (500) instead of a handled validation error. Add validation before accessing attributes.

Proposed fix
     def decode_request(self, request):
         # Handle both Starlette UploadFile (old) and FormData (Starlette >=1.3)
         if hasattr(request, "file"):
             data = request.file.read()
         else:
-            data = request.get("request").file.read()
+            req_obj = request.get("request") if hasattr(request, "get") else None
+            file_obj = getattr(req_obj, "file", None) if req_obj else None
+            if file_obj is None:
+                raise ValueError("Missing upload file")
+            data = file_obj.read()
         if not data:
             raise ValueError("Empty request body")
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def decode_request(self, request):
# Handle both Starlette UploadFile (old) and FormData (Starlette >=1.3)
if hasattr(request, "file"):
data = request.file.read()
else:
data = request.get("request").file.read()
if not data:
def decode_request(self, request):
# Handle both Starlette UploadFile (old) and FormData (Starlette >=1.3)
if hasattr(request, "file"):
data = request.file.read()
else:
req_obj = request.get("request") if hasattr(request, "get") else None
file_obj = getattr(req_obj, "file", None) if req_obj else None
if file_obj is None:
raise ValueError("Missing upload file")
data = file_obj.read()
if not data:
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@deepdoc/servers/endpoints/tsr_endpoint.py` around lines 27 - 33, The fallback
branch in decode_request currently assumes request.get("request") always returns
a valid object, which can raise an AttributeError on malformed payloads. Update
decode_request to validate the fallback value before accessing .file, and return
or raise the same handled validation error path used for bad uploads when the
key is missing or None. Keep the fix localized to decode_request and preserve
the existing Starlette UploadFile/FormData handling.

Comment thread internal/deepdoc/parser/pdf/crop.go Resolved
Comment thread internal/deepdoc/parser/pdf/table.go Resolved
Comment thread internal/deepdoc/parser/pdf/table.go Resolved
Comment on lines +175 to +178
for i := range cells {
cells[i].X0, cells[i].Y0 = mapRotatedPointToOriginal(cells[i].X0, cells[i].Y0, bestAngle, origW, origH)
cells[i].X1, cells[i].Y1 = mapRotatedPointToOriginal(cells[i].X1, cells[i].Y1, bestAngle, origW, origH)
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Normalize rotated cell bounds after mapping back.

For 90°/270° rotations, mapping only (X0,Y0) and (X1,Y1) can invert the rectangle. Later overlap checks assume X0 <= X1 and Y0 <= Y1, so rotated tables can fail text matching and span detection.

Proposed fix
 				}
 				for i := range cells {
-					cells[i].X0, cells[i].Y0 = mapRotatedPointToOriginal(cells[i].X0, cells[i].Y0, bestAngle, origW, origH)
-					cells[i].X1, cells[i].Y1 = mapRotatedPointToOriginal(cells[i].X1, cells[i].Y1, bestAngle, origW, origH)
+					x0, y0 := mapRotatedPointToOriginal(cells[i].X0, cells[i].Y0, bestAngle, origW, origH)
+					x1, y1 := mapRotatedPointToOriginal(cells[i].X1, cells[i].Y1, bestAngle, origW, origH)
+					cells[i].X0, cells[i].X1 = math.Min(x0, x1), math.Max(x0, x1)
+					cells[i].Y0, cells[i].Y1 = math.Min(y0, y1), math.Max(y0, y1)
 				}
 			}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
for i := range cells {
cells[i].X0, cells[i].Y0 = mapRotatedPointToOriginal(cells[i].X0, cells[i].Y0, bestAngle, origW, origH)
cells[i].X1, cells[i].Y1 = mapRotatedPointToOriginal(cells[i].X1, cells[i].Y1, bestAngle, origW, origH)
}
for i := range cells {
x0, y0 := mapRotatedPointToOriginal(cells[i].X0, cells[i].Y0, bestAngle, origW, origH)
x1, y1 := mapRotatedPointToOriginal(cells[i].X1, cells[i].Y1, bestAngle, origW, origH)
cells[i].X0, cells[i].X1 = math.Min(x0, x1), math.Max(x0, x1)
cells[i].Y0, cells[i].Y1 = math.Min(y0, y1), math.Max(y0, y1)
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/parser/table.go` around lines 175 - 178, Rotated cell bounds are
being mapped back in parser logic without re-normalizing the rectangle, so
`cells[i]` can end up with inverted coordinates after
`mapRotatedPointToOriginal` is applied in the table parsing loop. Update the
bounds normalization in `internal/parser/table.go` after the
`mapRotatedPointToOriginal` calls so each cell preserves `X0 <= X1` and `Y0 <=
Y1`, especially for 90°/270° rotations, before any later overlap or span checks
use the values.

Comment on lines +200 to +208
var positions []Position
for _, idx := range tm.boxIdx {
b := boxes[idx]
positions = append(positions, Position{
PageNumbers: []int{pageNum},
Left: b.X0, Right: b.X1,
Top: b.Top, Bottom: b.Bottom,
})
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Preserve page metadata for image-only tables.

When tm.boxIdx is empty, Positions stays empty; multi-table image-only results can be dropped by merge logic, and the fallback emits every table with PageNumber: 0. Add a DLA-region fallback position and use it when emitting the replacement.

Proposed fix
 		var positions []Position
-		for _, idx := range tm.boxIdx {
-			b := boxes[idx]
-			positions = append(positions, Position{
-				PageNumbers: []int{pageNum},
-				Left:        b.X0, Right: b.X1,
-				Top: b.Top, Bottom: b.Bottom,
-			})
+		if len(tm.boxIdx) == 0 {
+			positions = append(positions, Position{
+				PageNumbers: []int{pageNum},
+				Left: tm.region.X0 / scale, Right: tm.region.X1 / scale,
+				Top: tm.region.Y0 / scale, Bottom: tm.region.Y1 / scale,
+			})
+		} else {
+			for _, idx := range tm.boxIdx {
+				b := boxes[idx]
+				positions = append(positions, Position{
+					PageNumbers: []int{pageNum},
+					Left:        b.X0, Right: b.X1,
+					Top: b.Top, Bottom: b.Bottom,
+				})
+			}
 		}
 			html := constructTable(pageGlobalCells, tableBoxes, tables[ti].Caption, &tables[ti])
 			if html != "" {
+				pg := 0
+				if len(tables[ti].Positions) > 0 && len(tables[ti].Positions[0].PageNumbers) > 0 {
+					pg = tables[ti].Positions[0].PageNumbers[0]
+				}
 				out = append(out, TextBox{
-					Text: html, LayoutType: "table", PageNumber: 0,
+					Text: html, LayoutType: "table", PageNumber: pg,
 				})
 			}

Also applies to: 1265-1280

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/parser/table.go` around lines 200 - 208, The image-only table path
in the table merge/replacement flow is losing page metadata because `Positions`
remains empty when `tm.boxIdx` has no entries, causing downstream merge logic to
drop multi-table results and the fallback to emit `PageNumber: 0`. Update the
table handling around `tm.boxIdx`/`positions` to create a DLA-region fallback
`Position` when no boxes are present, and make the replacement emission logic
use that fallback so image-only tables still carry the correct page information.

@xugangqiang xugangqiang changed the title Refactor: parser migration to to Refactor: migrate pdf_parser.py to golang Jun 25, 2026
@xugangqiang
xugangqiang marked this pull request as draft June 25, 2026 03:25
@xugangqiang
xugangqiang marked this pull request as ready for review June 25, 2026 03:25

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
internal/parser/table_layout.go (1)

13-20: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Make the sort comparators transitive.

These threshold-based comparators can create cycles like A < B, B < C, and C < A, which violates Go sort’s required strict weak ordering and can scramble TSR cell order before cleanup/annotation. Bucket the primary coordinate first, or sort by the raw coordinate and do threshold grouping in a separate pass.

One way to make the ordering strict
 func sortYFirstly(cells []TSRCell, threshold float64) {
-	sort.Slice(cells, func(i, j int) bool {
-		diff := cells[i].Y0 - cells[j].Y0
-		if math.Abs(diff) < threshold {
-			return cells[i].X0 < cells[j].X0
-		}
-		return diff < 0
+	sort.SliceStable(cells, func(i, j int) bool {
+		yi, yj := cells[i].Y0, cells[j].Y0
+		if threshold > 0 {
+			yi = math.Floor(yi / threshold)
+			yj = math.Floor(yj / threshold)
+		}
+		if yi != yj {
+			return yi < yj
+		}
+		if cells[i].X0 != cells[j].X0 {
+			return cells[i].X0 < cells[j].X0
+		}
+		return cells[i].Y0 < cells[j].Y0
 	})
 }
 
 func sortXFirstly(cells []TSRCell, threshold float64) {
-	sort.Slice(cells, func(i, j int) bool {
-		diff := cells[i].X0 - cells[j].X0
-		if math.Abs(diff) < threshold {
-			return cells[i].Y0 < cells[j].Y0
-		}
-		return diff < 0
+	sort.SliceStable(cells, func(i, j int) bool {
+		xi, xj := cells[i].X0, cells[j].X0
+		if threshold > 0 {
+			xi = math.Floor(xi / threshold)
+			xj = math.Floor(xj / threshold)
+		}
+		if xi != xj {
+			return xi < xj
+		}
+		if cells[i].Y0 != cells[j].Y0 {
+			return cells[i].Y0 < cells[j].Y0
+		}
+		return cells[i].X0 < cells[j].X0
 	})
 }

Read-only check demonstrating the cycle:

#!/bin/bash
python3 - <<'PY'
threshold = 10
cells = [
    {"name": "A", "Y0": 18, "X0": 0},
    {"name": "B", "Y0": 9,  "X0": 1},
    {"name": "C", "Y0": 0,  "X0": 2},
]

def less(a, b):
    diff = a["Y0"] - b["Y0"]
    if abs(diff) < threshold:
        return a["X0"] < b["X0"]
    return diff < 0

for a, b in [(cells[0], cells[1]), (cells[1], cells[2]), (cells[2], cells[0])]:
    print(f'{a["name"]} < {b["name"]}: {less(a, b)}')
PY

Also applies to: 24-31

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/parser/table_layout.go` around lines 13 - 20, The comparator in
sortYFirstly is not transitive because the threshold check mixes Y0 and X0
ordering, which can create cycles and break Go sort’s strict weak ordering.
Update sortYFirstly to use a strict ordering based on the raw coordinate, or
bucket cells by Y0 first and only use X0 as a secondary key within stable
groups, so the less function in sort.Slice cannot produce A<B<B<C<C<A cycles.
🧹 Nitpick comments (1)
internal/parser/geometry_test.go (1)

123-125: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Assert that the merge keeps both fragments.

This test can still pass if "续文" is dropped and only "第一段" remains. Check both source strings in the merged text.

Proposed test tightening
-	if len(result) > 0 && !strings.Contains(result[0].Text, "第一段") {
-		t.Errorf("merged text should contain '第一段': got %q", result[0].Text)
+	if len(result) > 0 && (!strings.Contains(result[0].Text, "第一段") || !strings.Contains(result[0].Text, "续文")) {
+		t.Errorf("merged text should contain both fragments: got %q", result[0].Text)
 	}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/parser/geometry_test.go` around lines 123 - 125, The merge assertion
in geometry_test.go is too weak because it only checks for "第一段" and can still
pass if "续文" is lost. Tighten the test around the merge result in the relevant
parser/merge check by asserting the merged Text contains both source fragments
from the input, using the existing result[0].Text assertion so the test verifies
the full merge behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@internal/parser/table_layout.go`:
- Around line 13-20: The comparator in sortYFirstly is not transitive because
the threshold check mixes Y0 and X0 ordering, which can create cycles and break
Go sort’s strict weak ordering. Update sortYFirstly to use a strict ordering
based on the raw coordinate, or bucket cells by Y0 first and only use X0 as a
secondary key within stable groups, so the less function in sort.Slice cannot
produce A<B<B<C<C<A cycles.

---

Nitpick comments:
In `@internal/parser/geometry_test.go`:
- Around line 123-125: The merge assertion in geometry_test.go is too weak
because it only checks for "第一段" and can still pass if "续文" is lost. Tighten the
test around the merge result in the relevant parser/merge check by asserting the
merged Text contains both source fragments from the input, using the existing
result[0].Text assertion so the test verifies the full merge behavior.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 53c6a448-6f0e-4e5b-b239-0b7052d0abca

📥 Commits

Reviewing files that changed from the base of the PR and between e386d71 and e490e3b.

📒 Files selected for processing (20)
  • internal/parser/.gitignore
  • internal/parser/crop.go
  • internal/parser/crop_test.go
  • internal/parser/deepdoc.go
  • internal/parser/geometry.go
  • internal/parser/geometry_test.go
  • internal/parser/layout.go
  • internal/parser/parser.go
  • internal/parser/parser_ocr.go
  • internal/parser/parser_test.go
  • internal/parser/pipeline_parity_test.go
  • internal/parser/python_char_adapter.go
  • internal/parser/rotate_test.go
  • internal/parser/table.go
  • internal/parser/table_cells.go
  • internal/parser/table_layout.go
  • internal/parser/table_parity_issues_test.go
  • internal/parser/table_test.go
  • internal/parser/types.go
  • internal/parser/ycoord_test.go
💤 Files with no reviewable changes (3)
  • internal/parser/python_char_adapter.go
  • internal/parser/table_parity_issues_test.go
  • internal/parser/parser_test.go
✅ Files skipped from review due to trivial changes (1)
  • internal/parser/.gitignore
🚧 Files skipped from review as they are similar to previous changes (8)
  • internal/parser/pipeline_parity_test.go
  • internal/parser/crop.go
  • internal/parser/crop_test.go
  • internal/parser/parser_ocr.go
  • internal/parser/deepdoc.go
  • internal/parser/parser.go
  • internal/parser/table.go
  • internal/parser/rotate_test.go

@xugangqiang
xugangqiang marked this pull request as draft June 25, 2026 05:24
@xugangqiang
xugangqiang marked this pull request as ready for review June 25, 2026 05:24
@dosubot dosubot Bot added size:XL This PR changes 500-999 lines, ignoring generated files. and removed size:XXL This PR changes 1000+ lines, ignoring generated files. labels Jun 25, 2026
@xugangqiang
xugangqiang marked this pull request as draft June 25, 2026 05:49
@xugangqiang
xugangqiang marked this pull request as ready for review June 25, 2026 05:49
Comment thread docker/.env Outdated
# URL for the deepdoc vision API (DLA, OCR, TSR) served by OSS ONNX models.
# The `deepdoc` service defined in docker-compose.yml provides this endpoint.
# When unset, the parser falls back to inline ONNX Runtime inference.
DEEPDOC_URL=http://deepdoc:8124

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

9390

Comment thread docker/docker-compose.yml
- ./docker-compose-base.yml
# To ensure that the container processes the locally modified `service_conf.yaml.template` instead of the one included in its image, you need to mount the local `service_conf.yaml.template` to the container.
services:
deepdoc:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

profiles

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

rename

Comment thread Dockerfile_deepdoc_oss

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

move to root

@codecov

codecov Bot commented Jun 25, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (06d45c5) to head (72849f3).
⚠️ Report is 27 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #16323   +/-   ##
=======================================
  Coverage   93.16%   93.16%           
=======================================
  Files          10       10           
  Lines         717      717           
  Branches      118      118           
=======================================
  Hits          668      668           
  Misses         29       29           
  Partials       20       20           

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@dosubot dosubot Bot added size:XXL This PR changes 1000+ lines, ignoring generated files. and removed size:XL This PR changes 500-999 lines, ignoring generated files. labels Jun 25, 2026
@xugangqiang
xugangqiang marked this pull request as draft June 25, 2026 10:49
@xugangqiang
xugangqiang marked this pull request as ready for review June 25, 2026 10:49
@JinHai-CN
JinHai-CN merged commit 304d9e0 into infiniflow:main Jun 25, 2026
6 of 9 checks passed
@xugangqiang
xugangqiang deleted the feat/oss-parser-to-go branch August 7, 2026 12:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration ☯️ refactor Pull request that refactor/refine code size:XXL This PR changes 1000+ lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants