Repository navigation
Add SoMark as a layout-aware OCR parser - #15486
limuting233 wants to merge 16 commits into
Conversation
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdds SoMark OCR support end-to-end: a SoMark parser adapter (submit/poll + conversion), a SoMarkOcrModel wrapper, pipeline wiring and parse_method normalization, async provider verification and tenant provisioning, frontend modal/hooks for config, constants/i18n/icon additions, and unit tests. ChangesSoMark OCR Integration
Estimated code review effort🎯 4 (Complex) | ⏱️ ~75 minutes Possibly related PRs
Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 8
🧹 Nitpick comments (4)
deepdoc/parser/somark_parser.py (2)
454-457: 💤 Low valueUnnecessary
enumerateusage.The index from
enumerateis discarded. Iterate directly over the pages.♻️ Suggested simplification
self.page_images = [ - p.to_image(resolution=72 * zoomin, antialias=True).original - for _, p in enumerate(self.pdf.pages[page_from:page_to]) + page.to_image(resolution=72 * zoomin, antialias=True).original + for page in self.pdf.pages[page_from:page_to] ]🤖 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/parser/somark_parser.py` around lines 454 - 457, The list comprehension assigning self.page_images unnecessarily uses enumerate and discards the index; update the comprehension in the self.page_images assignment to iterate directly over self.pdf.pages[page_from:page_to] (e.g., for p in self.pdf.pages[page_from:page_to]) and call p.to_image(...).original so the index is not created or captured anywhere.
49-51: 💤 Low valueUnused lock definition.
The lock
LOCK_KEY_pdfplumberis defined but never used anywhere in the class. If thread-safe access topdfplumberis required, consider using this lock in__images__. Otherwise, remove this dead code.🤖 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/parser/somark_parser.py` around lines 49 - 51, The LOCK_KEY_pdfplumber lock is declared (LOCK_KEY_pdfplumber) but never used; either remove that dead declaration or wrap all pdfplumber accesses in the parser's __images__ method with that lock to ensure thread-safe use. To fix, locate the LOCK_KEY_pdfplumber declaration and either delete it (and any related sys.modules entry) if no synchronization is needed, or modify the __images__ method to retrieve the lock from sys.modules[LOCK_KEY_pdfplumber] and acquire/release it (or use a context manager) around any pdfplumber open/read operations so all pdfplumber usage is protected.api/apps/restful_apis/provider_api.py (1)
33-65: ⚡ Quick winAdd non-secret logs around provider-instance verification.
This new verify flow has no start/success/failure logging, so OCR credential checks are opaque when they time out or fail in production. Logging
provider_name,model_type,model_name/instance_name, and outcome would make these failures diagnosable without exposing secrets.💡 Suggested fix
async def _verify_provider_instance_model(provider_name: str, data: dict): model_type = data.get("model_type") model_name = data.get("llm_name") or data.get("model_name") or "" api_key = data.get("api_key", "") base_url = data.get("base_url") or data.get("api_base", "") timeout_seconds = int(data.get("verify_timeout", 60)) + + logging.info( + "provider verify started provider=%s model_type=%s model_name=%s", + provider_name, + model_type, + model_name, + ) if model_type == LLMType.OCR.value: from rag.llm import OcrModel if provider_name not in OcrModel: raise RuntimeError(f"OCR model from {provider_name} is not supported yet.") @@ ok, reason = await asyncio.wait_for( asyncio.to_thread(mdl.check_available), timeout=timeout_seconds, ) if not ok: + logging.warning( + "provider verify failed provider=%s model_type=%s model_name=%s reason=%s", + provider_name, + model_type, + model_name, + reason, + ) raise RuntimeError(reason or "Model not available") + logging.info( + "provider verify succeeded provider=%s model_type=%s model_name=%s", + provider_name, + model_type, + model_name, + ) returnAs per coding guidelines
**/*.py: Add logging for new flows.Also applies to: 378-384
🤖 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 `@api/apps/restful_apis/provider_api.py` around lines 33 - 65, Add non-secret start/success/failure logs in _verify_provider_instance_model: log an info/debug at the start including provider_name, model_type and model_name/instance_name (but never log api_key or base_url), log success when the check passes, and log a clear error/warning when the check fails or raises (including timeout) with the failure reason. Wrap the asyncio.wait_for call around mdl.check_available in a try/except to catch asyncio.TimeoutError and other Exceptions, and use the module logger (logging.getLogger(__name__) or existing logger) to emit these messages; reference the function _verify_provider_instance_model, variables provider_name, model_type, model_name, timeout_seconds, OcrModel, and mdl.check_available to locate where to add the logs.rag/flow/parser/parser.py (1)
511-565: ⚡ Quick winAdd a SoMark-specific breadcrumb here.
This introduces a new external OCR flow, but there is no SoMark-specific log/callback around model resolution or parser selection. A small breadcrumb before/after the provider-instance/env fallback will make production failures much easier to diagnose.
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 `@rag/flow/parser/parser.py` around lines 511 - 565, Add SoMark-specific breadcrumb logs around model resolution in resolve_somark_llm_name and the provider-instance/env fallback: log (using the existing logging facility such as self.callback or processLogger) immediately before calling resolve_somark_llm_name with tenant_id and parser_model_name (if set), then log again after attempting get_model_config_from_provider_instance and in the exception fallback branch where TenantLLMService.get_model_config is used, indicating which resolution path succeeded and include tenant_id and parser_model_name; reference the functions/variables resolve_somark_llm_name, parser_model_name, get_model_config_from_provider_instance, TenantLLMService.get_model_config and pdf_parser so the breadcrumb surrounds the model resolution and parser selection steps.
🤖 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 `@api/db/services/tenant_llm_service.py`:
- Around line 487-545: The code currently auto-provisions a SoMark model when
any SOMARK env var exists; change it to require actual credential values before
creating a model: update _collect_somark_env_config (or add a post-check in
ensure_somark_from_env) to verify at least one required credential key (e.g.,
SOMARK_API_KEY or whatever credential key(s) your app expects) is present and
non-empty in the collected cfg (use SOMARK_ENV_KEYS and SOMARK_DEFAULT_CONFIG to
locate keys), return None if no credentials are provided, and/or have
ensure_somark_from_env call _parse_api_key and abort creation if the parsed
api_key lacks required credential fields so save(...) is never called with an
empty/unusable api_key.
In `@deepdoc/parser/somark_parser.py`:
- Around line 742-748: The code writes 'binary' directly to disk but the
signature allows a BytesIO so f.write(binary) raises TypeError when binary is a
BytesIO; update the block that creates tmp_dir/temp_pdf (variables tmp_dir,
temp_pdf, and filepath) to detect io.BytesIO (or any file-like object) and write
its bytes (e.g., use binary.getvalue() or binary.read()) instead of writing the
BytesIO object itself—convert to a bytes object first and then write to the
file.
In `@rag/app/naive.py`:
- Around line 324-350: The branch that handles somark_llm_name swallows lookup
and parse failures and returns (None, None, None) without invoking the callback;
update the exception paths in the somark_llm_name block so any model lookup
failure (from get_model_config_from_provider_instance or
TenantLLMService.get_model_config) or parse exception from
LLMBundle/pdf_parser.parse_pdf calls invoke callback(-1, "<descriptive
message>") with the error details before returning, and ensure the same
callback(-1, "SoMark not found.") behavior remains for the final fallback;
reference somark_llm_name, get_model_config_from_provider_instance,
TenantLLMService.get_model_config, LLMBundle, and pdf_parser.parse_pdf to locate
the code to change.
In `@rag/flow/parser/parser.py`:
- Around line 715-716: The branch that sets b["doc_type_kwd"] for media boxes
currently assigns "image" for layout values in {"figure","image"}, which later
prevents the markdown writer (which only handles layout_type == "figure") from
rendering inline images; change the normalization so that when layout == "image"
you set b["doc_type_kwd"] = "figure" (or otherwise ensure the markdown writer
accepts both "figure" and "image"), targeting the assignment that sets
b["doc_type_kwd"] and the markdown writer branch that checks layout_type so they
agree.
In `@web/src/locales/en.ts`:
- Around line 1709-1721: The new English labels are in Title Case but the repo
convention requires sentence case; update the values for the keys
sectionElementFormats, imageFormat, formulaFormat, tableFormat, csFormat,
sectionFeatureConfig, enableInlineImage, enableTableImage,
enableImageUnderstanding, enableTitleLevelRecognition, enableTextCrossPage,
enableTableCrossPage, and keepHeaderFooter to sentence case (first word
capitalized, remaining words lowercase) so they match the rest of en.ts (e.g.,
"Element Formats" -> "Element formats", "Enable Inline Image" -> "Enable inline
image", etc.).
In `@web/src/locales/zh.ts`:
- Line 1398: The locale value for key sectionFeatureConfig contains an extra
leading space; update the string for sectionFeatureConfig in the zh locale to
remove the leading whitespace so it reads '特色功能配置' (no leading space) to match
neighboring labels and avoid unintended indentation.
In `@web/src/pages/user-setting/setting-model/hooks.tsx`:
- Around line 872-917: The onSoMarkOk callback leaves saveLoading
(somarkLoading) set when submitProviderInstance rejects; wrap the
submitProviderInstance call inside a try/finally (or try/catch/finally) within
onSoMarkOk so that setSaveLoading(false) always runs when isVerify is false,
reference the onSoMarkOk function and the submitProviderInstance call and ensure
you still return the appropriate VerifyResult when isVerify is true and
hideSoMarkModal()/true on successful save.
In `@web/src/pages/user-setting/setting-model/modal/somark-modal/index.tsx`:
- Around line 24-38: FORMAT_LABELS is a static, English-only map causing
untranslated dropdown labels; change the component to derive labels via the i18n
translator by replacing usages of FORMAT_LABELS with calls to t(...) (e.g.,
t('somark.format.url'), t('somark.format.base64') etc.) and build option lists
from IMAGE_FORMATS, FORMULA_FORMATS, TABLE_FORMATS, CS_FORMATS inside the
component so labels are generated at render time; update the component where
FORMAT_LABELS is referenced (and remove or deprecate the FORMAT_LABELS constant)
to use the translated strings and ensure keys align with the new translation
keys.
---
Nitpick comments:
In `@api/apps/restful_apis/provider_api.py`:
- Around line 33-65: Add non-secret start/success/failure logs in
_verify_provider_instance_model: log an info/debug at the start including
provider_name, model_type and model_name/instance_name (but never log api_key or
base_url), log success when the check passes, and log a clear error/warning when
the check fails or raises (including timeout) with the failure reason. Wrap the
asyncio.wait_for call around mdl.check_available in a try/except to catch
asyncio.TimeoutError and other Exceptions, and use the module logger
(logging.getLogger(__name__) or existing logger) to emit these messages;
reference the function _verify_provider_instance_model, variables provider_name,
model_type, model_name, timeout_seconds, OcrModel, and mdl.check_available to
locate where to add the logs.
In `@deepdoc/parser/somark_parser.py`:
- Around line 454-457: The list comprehension assigning self.page_images
unnecessarily uses enumerate and discards the index; update the comprehension in
the self.page_images assignment to iterate directly over
self.pdf.pages[page_from:page_to] (e.g., for p in
self.pdf.pages[page_from:page_to]) and call p.to_image(...).original so the
index is not created or captured anywhere.
- Around line 49-51: The LOCK_KEY_pdfplumber lock is declared
(LOCK_KEY_pdfplumber) but never used; either remove that dead declaration or
wrap all pdfplumber accesses in the parser's __images__ method with that lock to
ensure thread-safe use. To fix, locate the LOCK_KEY_pdfplumber declaration and
either delete it (and any related sys.modules entry) if no synchronization is
needed, or modify the __images__ method to retrieve the lock from
sys.modules[LOCK_KEY_pdfplumber] and acquire/release it (or use a context
manager) around any pdfplumber open/read operations so all pdfplumber usage is
protected.
In `@rag/flow/parser/parser.py`:
- Around line 511-565: Add SoMark-specific breadcrumb logs around model
resolution in resolve_somark_llm_name and the provider-instance/env fallback:
log (using the existing logging facility such as self.callback or processLogger)
immediately before calling resolve_somark_llm_name with tenant_id and
parser_model_name (if set), then log again after attempting
get_model_config_from_provider_instance and in the exception fallback branch
where TenantLLMService.get_model_config is used, indicating which resolution
path succeeded and include tenant_id and parser_model_name; reference the
functions/variables resolve_somark_llm_name, parser_model_name,
get_model_config_from_provider_instance, TenantLLMService.get_model_config and
pdf_parser so the breadcrumb surrounds the model resolution and parser selection
steps.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: d3673967-a2ef-46b7-af48-15f262da68af
⛔ Files ignored due to path filters (1)
web/src/assets/svg/llm/somark.svgis excluded by!**/*.svg
📒 Files selected for processing (21)
api/apps/llm_app.pyapi/apps/restful_apis/provider_api.pyapi/db/joint_services/tenant_model_service.pyapi/db/services/tenant_llm_service.pycommon/constants.pycommon/parser_config_utils.pyconf/llm_factories.jsondeepdoc/parser/somark_parser.pyrag/app/naive.pyrag/flow/parser/parser.pyrag/llm/ocr_model.pytest/unit_test/deepdoc/parser/test_somark_parser.pyweb/src/components/svg-icon.tsxweb/src/constants/llm.tsweb/src/locales/en.tsweb/src/locales/zh.tsweb/src/pages/user-setting/setting-model/hooks.tsxweb/src/pages/user-setting/setting-model/index.tsxweb/src/pages/user-setting/setting-model/modal/somark-modal/index.tsxweb/src/pages/user-setting/setting-model/modal/verify-button/index.tsxweb/src/pages/user-setting/setting-model/payload-utils.ts
| sectionElementFormats: 'Element Formats', | ||
| imageFormat: 'Image Format', | ||
| formulaFormat: 'Formula Format', | ||
| tableFormat: 'Table Format', | ||
| csFormat: 'Chemical Structural Formula Format', | ||
| sectionFeatureConfig: 'Feature Config', | ||
| enableInlineImage: 'Enable Inline Image', | ||
| enableTableImage: 'Enable Table Image', | ||
| enableImageUnderstanding: 'Enable Image Understanding', | ||
| enableTitleLevelRecognition: 'Enable Title Level Recognition', | ||
| enableTextCrossPage: 'Enable Text Cross Page', | ||
| enableTableCrossPage: 'Enable Table Cross Page', | ||
| keepHeaderFooter: 'Keep Header Footer', |
There was a problem hiding this comment.
Normalize the new English labels to sentence case.
Several added strings are title-cased (Element Formats, Feature Config, Enable Inline Image, etc.), which breaks the en.ts copy convention and makes this section read inconsistently with the rest of the settings UI.
As per coding guidelines, web/src/locales/{en,zh}.ts: “Use sentence case for en.ts: first word capitalized, rest lowercase (e.g., referenceAnswer: 'Reference answer').”
🤖 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 `@web/src/locales/en.ts` around lines 1709 - 1721, The new English labels are
in Title Case but the repo convention requires sentence case; update the values
for the keys sectionElementFormats, imageFormat, formulaFormat, tableFormat,
csFormat, sectionFeatureConfig, enableInlineImage, enableTableImage,
enableImageUnderstanding, enableTitleLevelRecognition, enableTextCrossPage,
enableTableCrossPage, and keepHeaderFooter to sentence case (first word
capitalized, remaining words lowercase) so they match the rest of en.ts (e.g.,
"Element Formats" -> "Element formats", "Enable Inline Image" -> "Enable inline
image", etc.).
There was a problem hiding this comment.
Leaving the casing as-is for now and deferring to maintainers' final call on copy style — these are section headers / toggle labels written to match the visual rhythm of the modal, and I'd rather not flip them in this PR than risk diverging from the rest of the SoMark labels. Happy to fix in a quick follow-up if the team prefers strict sentence case here.
There was a problem hiding this comment.
@limuting233, understood — happy to defer to the maintainers on the final copy style call. Would you like me to open a follow-up GitHub issue to track the sentence-case alignment for these SoMark labels, so it doesn't get lost?
🐇 (。•́︿•̀。)
There was a problem hiding this comment.
No need — I'll let the maintainers decide whether to track this. Thanks!
| const IMAGE_FORMATS = ['url', 'base64', 'none'] as const; | ||
| const FORMULA_FORMATS = ['latex', 'mathml', 'ascii'] as const; | ||
| const TABLE_FORMATS = ['html', 'markdown', 'image'] as const; | ||
| const CS_FORMATS = ['image'] as const; | ||
| const FORMAT_LABELS = { | ||
| url: 'URL', | ||
| base64: 'Base64', | ||
| none: 'None', | ||
| latex: 'LaTeX', | ||
| mathml: 'MathML', | ||
| ascii: 'ASCII', | ||
| html: 'HTML', | ||
| markdown: 'Markdown', | ||
| image: 'Image', | ||
| } as const; |
There was a problem hiding this comment.
Localize the new SoMark option labels.
These dropdown labels are hardcoded in English, so the new provider modal will stay partially untranslated in non-English locales. Build the option labels from t(...) inside the component instead of a static FORMAT_LABELS map.
🤖 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 `@web/src/pages/user-setting/setting-model/modal/somark-modal/index.tsx` around
lines 24 - 38, FORMAT_LABELS is a static, English-only map causing untranslated
dropdown labels; change the component to derive labels via the i18n translator
by replacing usages of FORMAT_LABELS with calls to t(...) (e.g.,
t('somark.format.url'), t('somark.format.base64') etc.) and build option lists
from IMAGE_FORMATS, FORMULA_FORMATS, TABLE_FORMATS, CS_FORMATS inside the
component so labels are generated at render time; update the component where
FORMAT_LABELS is referenced (and remove or deprecate the FORMAT_LABELS constant)
to use the translated strings and ensure keys align with the new translation
keys.
There was a problem hiding this comment.
Skipping for now — every value in FORMAT_LABELS is a proper noun or technical acronym (URL, Base64, LaTeX, MathML, ASCII, HTML, Markdown, Image, None) that conventionally is not translated even in non-English locales, so wiring them through t(...) would mostly add empty translation keys. Happy to revisit if maintainers want them explicitly routed through i18n.
There was a problem hiding this comment.
@limuting233, that's a fair and well-reasoned point. Terms like URL, Base64, LaTeX, MathML, ASCII, HTML, and Markdown are universally used as-is across locales, so keeping them as static constants rather than routing through t(...) is a sensible call here. Acknowledged!
(ᵔᴥᵔ)
ff4894c to
f3cf27e
Compare
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #15486 +/- ##
=======================================
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. 🚀 New features to boost your workflow:
|
f3cf27e to
f02c8ff
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (2)
api/apps/restful_apis/provider_api.py (1)
33-65: ⚡ Quick winAdd logging for the OCR verification flow.
The new verification function performs critical operations (dynamic import, model instantiation, availability check) but logs nothing. Add logging at key points: verification start (with provider/model), success, and failure (with reason) to aid debugging and monitoring.
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 `@api/apps/restful_apis/provider_api.py` around lines 33 - 65, The OCR verification flow in _verify_provider_instance_model currently has no logs—add structured logging at start (including provider_name and model_name), after instantiating the OcrModel (log provider_name and any sanitized extra), on successful availability check (log success with provider_name/model_name), and on failure or exception (log the reason and full exception). Use the module logger (e.g., logger = logging.getLogger(__name__)) and call logger.info/debug for start/success and logger.error with the reason/exception when ok is False or an exception is raised around mdl.check_available and model construction; reference the OcrModel lookup, the mdl variable, and mdl.check_available when placing the logs.api/db/joint_services/tenant_model_service.py (1)
110-110: 💤 Low valueConsider adding JSON parse error handling for
model_obj.extra.Line 110 calls
json.loads(model_obj.extra)without error handling. If the database contains malformed JSON, this will raiseJSONDecodeErrorand fail the request. While the DB should enforce valid JSON, defensive parsing (with try/except returning{}on error) would improve resilience.🛡️ Proposed defensive parsing
if model_obj: - model_extra_fields = json.loads(model_obj.extra) if model_obj.extra else {} + try: + model_extra_fields = json.loads(model_obj.extra) if model_obj.extra else {} + except (json.JSONDecodeError, TypeError): + logger.warning(f"Invalid JSON in model.extra for model {model_obj.id}") + model_extra_fields = {} if model_obj.status == ActiveStatusEnum.INACTIVE.value:🤖 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 `@api/db/joint_services/tenant_model_service.py` at line 110, Wrap the json.loads(model_obj.extra) call in a try/except to guard against malformed JSON: when computing model_extra_fields from model_obj.extra, catch json.JSONDecodeError (and ValueError as a fallback) and set model_extra_fields = {} on error; also emit a short warning via the module's logger if available to aid diagnostics. Target the expression that assigns model_extra_fields in tenant_model_service.py so the function/method that reads model_obj.extra handles invalid JSON safely.
🤖 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 `@api/db/joint_services/tenant_model_service.py`:
- Line 120: tenant_model_service.py currently emits "is_tools" but tenant
records encoded with the legacy "is_tool" key will be lost because
TenantLLMService._decode_api_key_config only reads "is_tools"; update the
decoding to fallback to "is_tool" when "is_tools" is missing and keep emission
as "is_tools" (i.e., where you construct the payload "is_tools":
extra_fields.get("is_tools", is_tool) continue emitting the new key, and modify
TenantLLMService._decode_api_key_config to check for
api_key_json.get("is_tools") first then api_key_json.get("is_tool") as a
fallback so legacy records retain tool-enablement).
---
Nitpick comments:
In `@api/apps/restful_apis/provider_api.py`:
- Around line 33-65: The OCR verification flow in
_verify_provider_instance_model currently has no logs—add structured logging at
start (including provider_name and model_name), after instantiating the OcrModel
(log provider_name and any sanitized extra), on successful availability check
(log success with provider_name/model_name), and on failure or exception (log
the reason and full exception). Use the module logger (e.g., logger =
logging.getLogger(__name__)) and call logger.info/debug for start/success and
logger.error with the reason/exception when ok is False or an exception is
raised around mdl.check_available and model construction; reference the OcrModel
lookup, the mdl variable, and mdl.check_available when placing the logs.
In `@api/db/joint_services/tenant_model_service.py`:
- Line 110: Wrap the json.loads(model_obj.extra) call in a try/except to guard
against malformed JSON: when computing model_extra_fields from model_obj.extra,
catch json.JSONDecodeError (and ValueError as a fallback) and set
model_extra_fields = {} on error; also emit a short warning via the module's
logger if available to aid diagnostics. Target the expression that assigns
model_extra_fields in tenant_model_service.py so the function/method that reads
model_obj.extra handles invalid JSON safely.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 3ffae95b-0d6e-43c0-847d-26cc5a5f846a
⛔ Files ignored due to path filters (1)
web/src/assets/svg/llm/somark.svgis excluded by!**/*.svg
📒 Files selected for processing (21)
api/apps/llm_app.pyapi/apps/restful_apis/provider_api.pyapi/db/joint_services/tenant_model_service.pyapi/db/services/tenant_llm_service.pycommon/constants.pycommon/parser_config_utils.pyconf/llm_factories.jsondeepdoc/parser/somark_parser.pyrag/app/naive.pyrag/flow/parser/parser.pyrag/llm/ocr_model.pytest/unit_test/deepdoc/parser/test_somark_parser.pyweb/src/components/svg-icon.tsxweb/src/constants/llm.tsweb/src/locales/en.tsweb/src/locales/zh.tsweb/src/pages/user-setting/setting-model/hooks.tsxweb/src/pages/user-setting/setting-model/index.tsxweb/src/pages/user-setting/setting-model/modal/somark-modal/index.tsxweb/src/pages/user-setting/setting-model/modal/verify-button/index.tsxweb/src/pages/user-setting/setting-model/payload-utils.ts
🚧 Files skipped from review as they are similar to previous changes (18)
- web/src/pages/user-setting/setting-model/modal/verify-button/index.tsx
- web/src/pages/user-setting/setting-model/payload-utils.ts
- web/src/components/svg-icon.tsx
- common/parser_config_utils.py
- common/constants.py
- rag/app/naive.py
- web/src/pages/user-setting/setting-model/index.tsx
- web/src/constants/llm.ts
- test/unit_test/deepdoc/parser/test_somark_parser.py
- rag/llm/ocr_model.py
- api/apps/llm_app.py
- web/src/locales/zh.ts
- web/src/pages/user-setting/setting-model/modal/somark-modal/index.tsx
- deepdoc/parser/somark_parser.py
- web/src/pages/user-setting/setting-model/hooks.tsx
- conf/llm_factories.json
- api/db/services/tenant_llm_service.py
- rag/flow/parser/parser.py
|
Conflict arises here |
f02c8ff to
81b0b9a
Compare
There was a problem hiding this comment.
Actionable comments posted: 6
🧹 Nitpick comments (1)
api/db/services/tenant_llm_service.py (1)
503-545: ⚡ Quick winAdd logs for the new SoMark env-provisioning flow.
This new path is silent on successful reuse/creation, which makes tenant bootstrap and misconfiguration diagnosis harder.
Suggested fix
for item in saved_models: api_cfg = _parse_api_key(item.api_key) normalized = {k: api_cfg.get(k, SOMARK_DEFAULT_CONFIG.get(k)) for k in SOMARK_ENV_KEYS} if normalized == cfg: + logging.info("Reusing SoMark env model %s for tenant %s", item.llm_name, tenant_id) return item.llm_name @@ cls.save( tenant_id=tenant_id, llm_factory="SoMark", llm_name=candidate, model_type=LLMType.OCR.value, api_key=json.dumps(cfg), api_base="", max_tokens=0, ) + logging.info("Created SoMark env model %s for tenant %s", candidate, tenant_id) return candidateAs 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 `@api/db/services/tenant_llm_service.py` around lines 503 - 545, The ensure_somark_from_env method is silent on reuse/creation; add structured logging so operator can see decisions: log at info/debug when cfg is missing (use _collect_somark_env_config), when an existing model is found and returned (include tenant_id, item.llm_name and a normalized-vs-cfg diff), when trying candidate names and when save succeeds (include tenant_id and candidate), and log exceptions on IntegrityError/failure (include tenant_id, candidate, and exception). Use the class logger (or module logger) inside ensure_somark_from_env around calls to query, the matching branch, the candidate loop before/after cls.save, and in the except block so reuse/creation and errors are visible.
🤖 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 `@api/apps/restful_apis/provider_api.py`:
- Around line 117-126: The instance creation is not atomic:
TenantModelInstanceService.create_instance(...) runs before
add_model_to_instance(...), leaving an orphaned instance if model attachment
fails. Fix by performing both operations inside a single DB transaction (wrap
create_instance and add_model_to_instance in a transactional context/session so
both commit or roll back together) or, if transactions are not available, ensure
you delete the created instance on failure (call the corresponding delete/remove
method such as TenantModelInstanceService.delete_instance or similar) when
add_model_to_instance returns failure; update the code around create_instance
and add_model_to_instance accordingly to guarantee atomicity.
- Around line 108-110: The duplicate-instance error is echoing the raw API key;
change the return to avoid leaking secrets by removing the full api_key from the
message and instead reference the existing instance via its name and an optional
redacted suffix (e.g., show only last 4 chars or replace with a fixed
placeholder). Update the block that calls
TenantModelInstanceService.get_by_provider_id_and_api_key(provider_obj.id,
api_key_str) and the returned tuple that currently includes
same_key_instance.instance_name and api_key so it only returns
same_key_instance.instance_name and either a redacted api key suffix (derived
from api_key_str) or no key at all in the error string.
- Around line 33-65: Add structured logging to the new OCR verify/create flow
inside _verify_provider_instance_model: log entry into the OCR branch with
provider_name and model_type, log the extracted parameters (masking secrets like
api_key), log before calling mdl.check_available, catch asyncio.TimeoutError
from asyncio.wait_for and log a timeout error including timeout_seconds and
provider_name, and log the check_available result (success or provider rejection
with reason) and any RuntimeError raised when model is not available; also apply
the same logging additions around the similar OCR verify/create flows referenced
by the other diffs (the blocks corresponding to lines 447-463 and 531-538) so
controller-side create failures and successes are logged consistently.
- Around line 33-55: _verify_provider_instance_model currently reads top-level
keys (model_name/llm_name and somark_*) but new payloads put OCR settings under
model_info; update this helper to merge data with data.get("model_info", {}) so
model_name, api_key, base_url and any somark_* extras are read from model_info
when present, or — preferably — refactor the verification to call the shared
LLMBundle path from api.db.services.llm_service (use LLMBundle to
construct/validate the OCR provider) so the contract is centralized; ensure you
reference OcrModel, include model_info.extra fields when building the extra
dict, and keep behavior for backwards-compatible top-level keys.
In `@api/db/services/tenant_llm_service.py`:
- Around line 232-238: The code currently json.loads(model_extra) but doesn't
verify the result is a mapping, so if model_extra parses to a non-object (list,
number, etc.) the dict-unpacking at ocr_kwargs = {**model_extra, **kwargs} will
raise a TypeError; update the block around model_extra in tenant_llm_service.py
to check the parsed value is a dict/mapping (e.g., isinstance(model_extra,
dict)) and otherwise set model_extra = {} before building ocr_kwargs, ensuring
you handle the original dict case and any parse failures uniformly.
- Around line 526-549: The current ensure_somark_from_env loop can still create
duplicates under race; change the IntegrityError handler in
ensure_somark_from_env so that instead of just adding a new candidate name and
retrying, you immediately re-query the persisted models for tenant_id and the
same SoMark config (e.g., matching llm_factory "SoMark" and api_key JSON cfg)
and if a matching row exists return its llm_name; only if no matching persisted
model is found continue the naming loop (or retry insert). In short: keep the
naming/insert loop around cls.save, but on IntegrityError call the lookup that
finds the existing SoMark env model for this tenant/config and return that name
(use the same class methods used to load saved_models and reference cls.save and
IntegrityError in the implementation).
---
Nitpick comments:
In `@api/db/services/tenant_llm_service.py`:
- Around line 503-545: The ensure_somark_from_env method is silent on
reuse/creation; add structured logging so operator can see decisions: log at
info/debug when cfg is missing (use _collect_somark_env_config), when an
existing model is found and returned (include tenant_id, item.llm_name and a
normalized-vs-cfg diff), when trying candidate names and when save succeeds
(include tenant_id and candidate), and log exceptions on IntegrityError/failure
(include tenant_id, candidate, and exception). Use the class logger (or module
logger) inside ensure_somark_from_env around calls to query, the matching
branch, the candidate loop before/after cls.save, and in the except block so
reuse/creation and errors are visible.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: ed1d5746-6e55-49de-8496-6807519111fb
⛔ Files ignored due to path filters (1)
web/src/assets/svg/llm/somark.svgis excluded by!**/*.svg
📒 Files selected for processing (21)
api/apps/llm_app.pyapi/apps/restful_apis/provider_api.pyapi/db/joint_services/tenant_model_service.pyapi/db/services/tenant_llm_service.pycommon/constants.pycommon/parser_config_utils.pyconf/llm_factories.jsondeepdoc/parser/somark_parser.pyrag/app/naive.pyrag/flow/parser/parser.pyrag/llm/ocr_model.pytest/unit_test/deepdoc/parser/test_somark_parser.pyweb/src/components/svg-icon.tsxweb/src/constants/llm.tsweb/src/locales/en.tsweb/src/locales/zh.tsweb/src/pages/user-setting/setting-model/hooks.tsxweb/src/pages/user-setting/setting-model/index.tsxweb/src/pages/user-setting/setting-model/modal/somark-modal/index.tsxweb/src/pages/user-setting/setting-model/modal/verify-button/index.tsxweb/src/pages/user-setting/setting-model/payload-utils.ts
💤 Files with no reviewable changes (13)
- web/src/components/svg-icon.tsx
- web/src/constants/llm.ts
- web/src/locales/zh.ts
- web/src/pages/user-setting/setting-model/modal/verify-button/index.tsx
- web/src/locales/en.ts
- web/src/pages/user-setting/setting-model/payload-utils.ts
- web/src/pages/user-setting/setting-model/index.tsx
- rag/llm/ocr_model.py
- web/src/pages/user-setting/setting-model/hooks.tsx
- test/unit_test/deepdoc/parser/test_somark_parser.py
- rag/app/naive.py
- web/src/pages/user-setting/setting-model/modal/somark-modal/index.tsx
- rag/flow/parser/parser.py
🚧 Files skipped from review as they are similar to previous changes (5)
- api/db/joint_services/tenant_model_service.py
- common/parser_config_utils.py
- api/apps/llm_app.py
- common/constants.py
- deepdoc/parser/somark_parser.py
| model_extra = model_config.get("extra") or {} | ||
| if isinstance(model_extra, str): | ||
| try: | ||
| model_extra = json.loads(model_extra) | ||
| except Exception: | ||
| model_extra = {} | ||
| ocr_kwargs = {**model_extra, **kwargs} |
There was a problem hiding this comment.
Guard extra after json.loads().
If extra is valid JSON but not an object, json.loads() succeeds and Line 238 crashes with TypeError when **model_extra runs. That turns a bad persisted provider config into a runtime failure during OCR model creation instead of safely ignoring the malformed payload.
Suggested fix
model_extra = model_config.get("extra") or {}
if isinstance(model_extra, str):
try:
model_extra = json.loads(model_extra)
except Exception:
model_extra = {}
+ if not isinstance(model_extra, dict):
+ model_extra = {}
ocr_kwargs = {**model_extra, **kwargs}🤖 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 `@api/db/services/tenant_llm_service.py` around lines 232 - 238, The code
currently json.loads(model_extra) but doesn't verify the result is a mapping, so
if model_extra parses to a non-object (list, number, etc.) the dict-unpacking at
ocr_kwargs = {**model_extra, **kwargs} will raise a TypeError; update the block
around model_extra in tenant_llm_service.py to check the parsed value is a
dict/mapping (e.g., isinstance(model_extra, dict)) and otherwise set model_extra
= {} before building ocr_kwargs, ensuring you handle the original dict case and
any parse failures uniformly.
2c0f314 to
39e0797
Compare
|
CI failed |
新增SoMark的OCR模型配置项,完善模型配置列表
- Add SoMarkParser supporting both naive 2-tuple and rag/flow 3-tuple paths - Add SoMarkOcrModel as auto-registered OCR factory - Hook into naive.py PDF chunking and rag/flow Parser node (pipeline mode) - Add SoMark configuration UI (provider modal, icon, env-based auto-provisioning) - Aligned with MinerU integration pattern; PDF-only scope
39e0797 to
2d5006a
Compare
|
Conflicts arise here |
… - resolve conflicts
Lynn-Inf
left a comment
There was a problem hiding this comment.
Thanks for the PR. Here are a few suggestions for improvement:
-
Verify implementation: The
verifylogic forocrtype models should be implemented as part of thegeneral verifyflow, specifically under the ocr logic branch, rather than as a standalone method. Additionally, this should be placed inapi/apps/services/provider_api_service.py, not directly in theapifile. -
Verify parameters: Since
verifyis only used to test model availability, consider using a low-cost default configuration (e.g., minimal resource consumption) as the parameter set for verification. -
Extra fields handling: The
extrafield may contain many fields unrelated to ocr configuration. Consider grouping them under a dedicated field (e.g.,ocr_config). When returningmodel_config, only extract and return the content ofocr_configto avoid parameter conflicts when expanding the dict with**. -
Legacy tables: The
tenant_llmrelated tables and interfaces will be deprecated and removed in future iterations. No changes are needed inapi/apps/llm_app.py.
…der ocr_config - Remove _verify_provider_instance_model and _create_ocr_provider_instance from provider_api.py (controller-level OCR-specific functions) - Route all create/verify through provider_api_service layer - Nest OCR extra fields under ocr_config in add_model_to_instance - Extract only ocr_config content in get_model_config_from_provider_instance to avoid ** expansion conflicts
Lynn-Inf
left a comment
There was a problem hiding this comment.
Thanks for the updates. I see that suggestions 1–3 have been addressed. However, suggestion 4 still remains an issue — and in fact, the new commits have moved even more model creation and retrieval logic into the deprecated database tables and code files that are scheduled for removal.
Please implement the corresponding validation and creation logic in provider_api_service.py instead.
…omark to new joint service - Revert all SoMark changes in api/apps/llm_app.py (deprecated interface) - Add ensure_somark_from_env to api/db/joint_services/tenant_model_service.py using the generic _ensure_ocr_provider_from_env helper (new tables) - Update rag/flow/parser/parser.py and rag/app/naive.py to call the new joint service instead of deprecated TenantLLMService - Build model_info from flat payload in create/verify route handlers for providers with empty static model lists (e.g. SoMark)
Lynn-Inf
left a comment
There was a problem hiding this comment.
Thanks for the updates. I noticed that some logic has been relocated to provider_api.py and provider_api_services.py, which is good progress.
However, there are still a number of changes in tenant_llm_service — a file that is already marked for deprecation. We should avoid adding new logic there.
Also, the logic that processes parameters such as api_key based on the provider type is currently in provider_api.py. I think it would be better to move this to provider_api_services.py to align with the separation of concerns (API layer vs. service layer).
…ve flat-payload logic to service layer - Remove _collect_somark_env_config and ensure_somark_from_env from TenantLLMService (deprecated table); callers already use the new joint-service version in tenant_model_service.py - Remove SOMARK_DEFAULT_CONFIG/SOMARK_ENV_KEYS imports (only dead code used them) - Add _normalize_model_info() helper in provider_api_service.py to synthesize model_info from flat request payload for providers with empty static model lists (generic, keyed by provider name prefix) - Add flat_config param to create_provider_instance and verify_api_key so the service layer handles provider-specific payload normalization - Remove duplicate model_info-from-flat-payload construction from both route handlers in provider_api.py; routes now just pass flat_config=data through to the service layer
Lynn-Inf
left a comment
There was a problem hiding this comment.
Glad to see the parameter logic moved to the service layer. A few things:
-
Since all SoMark models fit into
model_name,model_type,max_tokens, andextra, consider using a unified request format instead of backend‑specific handling. -
The
ocr_configassignment (line 776) should only apply toSoMark— other OCR models may not support it. -
Keep
tenant_llm_service.pyunchanged — it's deprecated.
…SoMark, revert tenant_llm_service - Frontend sends standard model_info array instead of flat somark_* fields, removing the need for backend-specific _normalize_model_info helper - Embed SoMark OCR config into instance api_key JSON so it reaches SoMarkOcrModel via the existing api_key_payload -> key path, avoiding changes in the deprecated LLMBundle (tenant_llm_service.py) - Limit ocr_config wrapping in add_model_to_instance to SoMark only; other OCR models (MinerU, PaddleOCR) are unaffected - Revert LLMBundle OCR path in tenant_llm_service.py to original; file is now identical to main
…correct merge The GitHub web merge resolved conflicts by renaming provider_name to provider_id_or_name in function signatures (from soulcode/main fork), but function bodies still reference provider_name. infiniflow/ragflow:main (the PR target) uses provider_name throughout. Revert the rename to match upstream/main and fix the undefined name error.
2285a99 to
0671f57
Compare
|
Hi @limuting233, your PR looks good. However, it accidentally reverts changes from PR #16336. |
…F821 - Merge upstream/main (infiniflow/ragflow) into feature branch - Resolve svg-icon.tsx and llm.ts conflicts: keep both SoMark and NewAPI - Fix provider_id_or_name -> provider_name in provider_api.py (2 F821 errors)
|
@limuting233 Please take a look at #16482. I've resolved the conflicts and removed the unrelated changes. |
The test_elasticsearch keeps failing, and it does not look like one of our problems, please check |
Follow #15486 Co-authored-by: limuting <[email protected]> Co-authored-by: lutianyi <[email protected]> Co-authored-by: justinychuang <[email protected]> Co-authored-by: maybehokori <[email protected]>
|
Merged in #16482 |
What problem does this PR solve?
Adds SoMark (https://somark.tech) as a new layout-aware OCR/PDF parser, following the existing OCR parser integration pattern.
SoMark provides layout-aware PDF parsing with support for text, tables, equations, figures, stamps, QR codes, chemical structures, and image-understanding captions. This enables parsed figure/table content to be indexed and retrieved instead of being lost in text-only extraction.
This PR integrates SoMark into both ingestion paths:
rag/app/naive.pyrag/flow/parser/parser.pyIt also adds frontend provider configuration so tenants can add their own SoMark API key through the existing Model Providers flow. No new infrastructure is required, and RAGFlow operators do not bear SoMark API cost.
Implementation details:
SoMarkOcrModelsupport through the existing OCR model abstraction.extra.Verified locally with:
Parser(SoMark) -> Token Chunker -> Tokenizer(Full text + Embedding)Tests:
PYTHONDONTWRITEBYTECODE=1 uv run pytest test/unit_test/deepdoc/parser/test_somark_parser.py— 20 passedcd web && npx eslint src/pages/user-setting/setting-model/hooks.tsx src/pages/user-setting/setting-model/payload-utils.tsgit diff --checkType of change