Repository navigation
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 FunASR/SenseVoice as a local OpenAI-compatible speech-to-text provider (backend class, config, frontend wiring), and updates the markdown parser to treat fenced code blocks as atomic with regression tests. ChangesFunASR Speech-to-Text Provider
Sequence Diagram (high-level FunASR transcription flow): sequenceDiagram
participant WebUI as Web UI
participant FunASRSeq2txt as FunASRSeq2txt
participant FunASRServer as FunASR Server
WebUI->>FunASRSeq2txt: request transcription (audio, model)
FunASRSeq2txt->>FunASRServer: POST /v1/audio/transcriptions
FunASRServer-->>FunASRSeq2txt: transcription response
FunASRSeq2txt-->>WebUI: return text
🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related issues
Possibly related PRs
Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ 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. Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (1)
rag/llm/sequence2txt_model.py (1)
453-467: ⚡ Quick winAlign the docstring with the placeholder-key behavior.
The docstring says empty keys are passed through verbatim, but Line 467 replaces falsy keys with
"funasr". That mismatch will mislead the next person debugging auth or config handling.Suggested wording fix
- The API key field is unused by upstream FunASR but the project's - LLM bundle plumbing requires a non-empty string; we accept the - user-supplied value verbatim and pass it through. + The API key field is unused by upstream FunASR but the project's + LLM bundle plumbing requires a non-empty string; when the supplied + key is empty, we substitute a stable placeholder so the OpenAI + client can be constructed.🤖 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/llm/sequence2txt_model.py` around lines 453 - 467, Update the class docstring to reflect that empty/falsy API keys are replaced with a stable placeholder ("funasr") before calling super().__init__, and not passed through verbatim; modify the docstring near _FACTORY_NAME or the class header to state that FunASR does not require auth and the initializer (__init__) substitutes a non-empty placeholder key when the provided key is falsy so the OpenAI-style client accepts it.
🤖 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.
Nitpick comments:
In `@rag/llm/sequence2txt_model.py`:
- Around line 453-467: Update the class docstring to reflect that empty/falsy
API keys are replaced with a stable placeholder ("funasr") before calling
super().__init__, and not passed through verbatim; modify the docstring near
_FACTORY_NAME or the class header to state that FunASR does not require auth and
the initializer (__init__) substitutes a non-empty placeholder key when the
provided key is falsy so the OpenAI-style client accepts it.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: fe5fdcc6-d453-4cd8-a402-fccc224d003d
📒 Files selected for processing (5)
conf/llm_factories.jsonrag/llm/sequence2txt_model.pyweb/src/constants/llm.tsweb/src/pages/user-setting/constants.tsxweb/src/pages/user-setting/setting-model/modal/ollama-modal/index.tsx
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 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 `@test/unit_test/deepdoc/parser/test_markdown_parser.py`:
- Around line 33-73: The tests fail because
MarkdownElementExtractor.extract_elements() and its helper _extract_code_block()
only detect backtick fences of exactly three backticks and always close on the
next ``` regardless of opener; update deepdoc/parser/markdown_parser.py so
_extract_code_block() captures the opening fence character (backtick or tilde)
and its run length, treat ~~~ the same as ``` and only terminate the block when
a closing fence line starts with the same character repeated at least the same
length (and ignore shorter inner runs), and ensure extract_elements() passes the
fence info so code_block detection supports both variable-length backtick fences
(e.g., ````) and tilde fences.
- Around line 100-154: The tests expect that
MarkdownElementExtractor.extract_elements preserves fenced code blocks (``` and
~~~) intact when a delimiter is supplied, but the current implementation applies
a global regex split and fragments those blocks; update extract_elements (or add
a helper used by it) to first locate and temporarily protect fenced code blocks
(both backtick and tilde fences, including info-strings) so the delimiter split
runs only on the non-protected regions, then restore the original code block
content into the resulting elements; reference the method
MarkdownElementExtractor.extract_elements and ensure tests
test_delimiter_split_skips_code_block and
test_delimiter_split_skips_tilde_code_block pass.
🪄 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: d9522ded-0e51-449d-aea0-d82582d4cb30
📒 Files selected for processing (2)
rag/llm/sequence2txt_model.pytest/unit_test/deepdoc/parser/test_markdown_parser.py
🚧 Files skipped from review as they are similar to previous changes (1)
- rag/llm/sequence2txt_model.py
| def test_delimiter_split_skips_code_block(self): | ||
| """A sentence-ending punctuation delimiter inside a code block | ||
| must not split the block.""" | ||
| doc = "\n".join( | ||
| [ | ||
| "Intro sentence.", | ||
| "More intro.", | ||
| "```python", | ||
| "print('hello.')", | ||
| "print('world.')", | ||
| "```", | ||
| "Outro sentence.", | ||
| ] | ||
| ) | ||
| # delimiter = "`.` `?`" — backticks-quoted tokens (this is how | ||
| # get_delimiters parses the config value) | ||
| elements = MarkdownElementExtractor(doc).extract_elements( | ||
| delimiter="`.`|`?`", include_meta=True | ||
| ) | ||
| # The code block must appear verbatim as a single element. The | ||
| # body inside the block contains "hello." and "world." which the | ||
| # delimiter would otherwise split on. | ||
| code_chunks = [e for e in elements if "```" in e["content"]] | ||
| assert len(code_chunks) == 1 | ||
| body = code_chunks[0]["content"] | ||
| assert "print('hello.')" in body | ||
| assert "print('world.')" in body | ||
| # Sanity: intro/outro DID get split by the delimiter. | ||
| outside_text = " | ".join( | ||
| e["content"] for e in elements if "```" not in e["content"] | ||
| ) | ||
| assert "Intro sentence" in outside_text | ||
| assert "More intro" in outside_text | ||
| assert "Outro sentence" in outside_text | ||
|
|
||
| @pytest.mark.p1 | ||
| def test_delimiter_split_skips_tilde_code_block(self): | ||
| """Same protection extends to tilde-fenced blocks.""" | ||
| doc = "\n".join( | ||
| [ | ||
| "Before.", | ||
| "~~~", | ||
| "do.", | ||
| "this.", | ||
| "~~~", | ||
| "After.", | ||
| ] | ||
| ) | ||
| elements = MarkdownElementExtractor(doc).extract_elements( | ||
| delimiter="`.`", include_meta=True | ||
| ) | ||
| code = [e for e in elements if e["content"].startswith("~~~")] | ||
| assert len(code) == 1 | ||
| assert "do." in code[0]["content"] | ||
| assert "this." in code[0]["content"] |
There was a problem hiding this comment.
Delimiter-mode expectations do not match the current extractor path.
When delimiter is set, extract_elements() does a raw regex split over the full text and never treats fenced blocks as atomic regions. That means the "hello." / "world." and tilde-fence bodies here will still be fragmented by the delimiter unless the parser implementation changes with these tests.
🤖 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 `@test/unit_test/deepdoc/parser/test_markdown_parser.py` around lines 100 -
154, The tests expect that MarkdownElementExtractor.extract_elements preserves
fenced code blocks (``` and ~~~) intact when a delimiter is supplied, but the
current implementation applies a global regex split and fragments those blocks;
update extract_elements (or add a helper used by it) to first locate and
temporarily protect fenced code blocks (both backtick and tilde fences,
including info-strings) so the delimiter split runs only on the non-protected
regions, then restore the original code block content into the resulting
elements; reference the method MarkdownElementExtractor.extract_elements and
ensure tests test_delimiter_split_skips_code_block and
test_delimiter_split_skips_tilde_code_block pass.
There was a problem hiding this comment.
🧹 Nitpick comments (1)
deepdoc/parser/markdown_parser.py (1)
135-168: ⚡ Quick winAdd debug logging for the new atomic-region delimiter flow.
The new delimiter path and unterminated-fence fallback are behaviorally significant but currently silent, which makes parsing regressions harder to diagnose in production logs.
Proposed patch
import re +import logging from markdown import markdown +logger = logging.getLogger(__name__) + class RAGFlowMarkdownParser: @@ def _atomic_region_ranges(self, text: str): @@ if close: end = close.end() else: # Unterminated fence: treat the rest of the document as # atomic so a stray ``` doesn't poison the delimiter pass. + logger.debug( + "Unterminated fenced code block at offset %d; marking remainder as atomic.", + m.start(), + ) end = len(text) ranges.append((m.start(), end)) pos = end return ranges @@ if len(dels) > 0: text = "\n".join(self.lines) atomic_ranges = self._atomic_region_ranges(text) pattern = re.compile(dels) + logger.debug( + "Delimiter extraction enabled: atomic_regions=%d delimiter=%s", + len(atomic_ranges), + delimiter, + )As per coding guidelines,
**/*.py: Add logging for new flows.Also applies to: 180-222
🤖 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/markdown_parser.py` around lines 135 - 168, Add debug logging to the new atomic-region delimiter flow: inside _atomic_region_ranges, when you hit the unterminated-fence fallback (the branch that sets end = len(text) after close is None) insert a logger.debug call that logs the opening fence start offset (use m.start()) and a short message like "Unterminated fenced code block at offset %d; marking remainder as atomic."; and in the delimiter-extraction block (the code that computes atomic_ranges = self._atomic_region_ranges(text) after checking if len(dels) > 0), add a logger.debug that logs the number of atomic regions and the delimiter string (e.g. "Delimiter extraction enabled: atomic_regions=%d delimiter=%s", len(atomic_ranges), delimiter). Use the existing module logger (don’t add a new logger) and keep level debug so it’s only visible with debug logging enabled.
🤖 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.
Nitpick comments:
In `@deepdoc/parser/markdown_parser.py`:
- Around line 135-168: Add debug logging to the new atomic-region delimiter
flow: inside _atomic_region_ranges, when you hit the unterminated-fence fallback
(the branch that sets end = len(text) after close is None) insert a logger.debug
call that logs the opening fence start offset (use m.start()) and a short
message like "Unterminated fenced code block at offset %d; marking remainder as
atomic."; and in the delimiter-extraction block (the code that computes
atomic_ranges = self._atomic_region_ranges(text) after checking if len(dels) >
0), add a logger.debug that logs the number of atomic regions and the delimiter
string (e.g. "Delimiter extraction enabled: atomic_regions=%d delimiter=%s",
len(atomic_ranges), delimiter). Use the existing module logger (don’t add a new
logger) and keep level debug so it’s only visible with debug logging enabled.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 56c0f41d-64ed-4626-80c8-eb2b5d5a6a70
📒 Files selected for processing (1)
deepdoc/parser/markdown_parser.py
693e68c to
2aa0a93
Compare
2aa0a93 to
26c38d8
Compare
|
Thanks for pushing this integration forward — RAGFlow + local FunASR/SenseVoice is a great fit. One compatibility issue to fix before merge: the current default I checked current FunASR
Suggested minimal fix: - a model_name (the default ``SenseVoiceSmall`` matches FunASR's
- out-of-the-box model alias).
+ a model_name (the default ``sensevoice`` matches FunASR's
+ out-of-the-box OpenAI API model alias).
@@
- def __init__(self, key, model_name="SenseVoiceSmall", base_url="http://localhost:8000/v1", **kwargs):
+ def __init__(self, key, model_name="sensevoice", base_url="http://localhost:8000/v1", **kwargs):It would also be worth adding a tiny unit test that instantiates Reference points:
|
|
I reproduced the current merge conflict against What this branch does:
Local verification on the conflict-resolved checkout: The branch is based on the latest |
|
I opened a draft conflict-resolved replacement PR so maintainers can review the same FunASR/SenseVoice provider work against current main: #16473. It uses the branch I linked above, now as a PR: #16473 Validation repeated on the clean checkout: Keeping it as draft initially so the original PR author can either take the branch/patch or maintainers can decide whether to continue review there. |
Add the OpenAI-compatible transcription adapter, dynamic model discovery, current provider-schema wiring, documentation, and focused tests. Based on the provider proposal in infiniflow#15526 by @Rene0422. Signed-off-by: LauraGPT <[email protected]>
### Summary Adds FunASR as a self-hosted speech-to-text provider through its OpenAI-compatible `/v1/audio/transcriptions` endpoint. This is a focused replacement for #15526 by @Rene0422 and relates to #15448. The unrelated Markdown parser changes from the previous branch are intentionally removed so this PR contains only the FunASR provider integration. - register FunASR as a `SPEECH2TEXT` factory; - add `FunASRSeq2txt` with `sensevoice` and `http://localhost:8000/v1` defaults, an optional API key, URL normalization, and inherited transcription handling; - wire FunASR into the current local-provider schema with a prefilled local URL and official documentation link; - discover the server's `/v1/models` dynamically and expose every returned model as speech-to-text in the model picker; - use RAGFlow's existing default provider icon fallback instead of referencing a missing `funasr` asset; - list FunASR in the supported-provider documentation; - add focused backend and frontend regression tests. ### Validation - focused backend pytest suite -> `7 passed` - real CPU `funasr-server` + RAGFlow provider smoke test -> discovered `fun-asr-nano`, `sensevoice`, and `paraformer`; transcribed a real WAV as `我现在在录一段测试音频` (`10` tokens, `0.504s`) - `ruff check` and `ruff format --check` on the changed Python files - `python3 -m py_compile` on the provider and its test - JSON parse and a semantic assertion for exactly one enabled FunASR `SPEECH2TEXT` factory - focused frontend Jest test -> `2 passed` - ESLint and Prettier on all changed TypeScript files - `npm run build` -> production build succeeded (`14,181` modules transformed) - `git diff --check` ### Deployment Run FunASR separately and point the RAGFlow provider at it: ```bash pip install funasr funasr-server --device cuda --model sensevoice ``` The API key remains optional because the stock local server does not require authentication. A key can still be supplied when the endpoint is protected by a gateway. --------- Signed-off-by: LauraGPT <[email protected]> Co-authored-by: LauraGPT <[email protected]>
|
duplicate with #16473 |
Summary
Closes #15449. Adds FunASR / SenseVoice as a built-in
speech-to-text provider so RAGFlow can transcribe audio/video
documents fully self-hosted without setting up a separate
transcription service.
FunASR exposes an OpenAI-compatible HTTP server at
/v1/audio/transcriptions— typical launch is:pip install funasr funasr-server --device cuda # serves http://localhost:8000/v1…so this is the same one-class subclass pattern the other
self-hosted OpenAI-compat providers (GiteeAI, DeepInfra, CometAPI,
FuturMix, RAGcon) already use.
Why FunASR
(from the issue)
(non-autoregressive, 234M params)
Files changed
rag/llm/sequence2txt_model.pyFunASRSeq2txt(GPTSeq2txt)class._FACTORY_NAME = "FunASR". Defaultsbase_url="http://localhost:8000/v1"andmodel_name="SenseVoiceSmall". Emptykeyis replaced with"funasr"so the OpenAI client constructs.transcription()is inherited fromBase.conf/llm_factories.json{"name": "FunASR", "tags": "SPEECH2TEXT", "status": "1", "llm": []}.rag/llm/__init__.pyauto-discovers it by_FACTORY_NAME.web/src/constants/llm.tsLLMFactory.FunASR = 'FunASR'+IconMap[FunASR] = 'funasr'.web/src/pages/user-setting/constants.tsxLocalLlmFactoriesso the local-server config modal handles it.web/src/pages/user-setting/setting-model/modal/ollama-modal/index.tsxoptionsMap[FunASR] = ['speech2text'](single allowed model type) + docs URL to the FunASR GitHub repo.What's intentionally not in this PR
IconMap[FunASR] = 'funasr'referencesfunasr.svg(or.png); follow the project's usual icon-assetPR pattern to drop it in.
FunASR, mirroring the MinerU / Docling / OpenDataLoader story.
Users run
funasr-serverthemselves.labels carry the UX.
Validation done in the sandbox
python -c "import ast; ast.parse('rag/llm/sequence2txt_model.py')"✓python -c "import json; json.load(open('conf/llm_factories.json'))"✓importlib.utilwithproject-internal deps stubbed: confirmed
_FACTORY_NAME == "FunASR"(matches JSON entry and FE enum)FunASRSeq2txt → GPTSeq2txt → Base → ABC → objectsotranscription()is inherited correctlybase_urlkeyis replaced with"funasr"before reaching theOpenAI client (verified
client.kw = {'api_key': 'funasr', 'base_url': '…/v1'})grep -c "FunASR"confirms wiring touches all 5 files.Validation not done in the sandbox
The local venv isn't
uv sync'd (project deps missing) and thesandbox blocked the
pip installofpytest. Please run in CI:uv run pytest— the changes are purely additive (noexisting fixture or service touched), so this should be a
no-op for existing tests.
cd web && npm run build— frontend changes are data-only(enum member, Record entries, array push) so are type-safe by
construction, but a full TS check confirms.
Test plan
funasr-server --device cuda(defaults tohttp://localhost:8000/v1).SPEECH2TEXTtag.speech2textas the only model type (notchat/embedding/
rerank). Defaultbase_urlshowshttp://localhost:8000/v1, defaultllm_nameisSenseVoiceSmall. The "Verify" button hits the live serverand returns a green check.
audio file (e.g.
.mp3/.wav/.m4a). Transcript appearsin the parsed document with correct text.
and confirm transcript ingestion.
base_url=http://gpu-host:9090/v1, modelparaformer-zh. Same flow works against a non-default hostand a non-default model.
succeeds (the placeholder
funasris substituted server-sideso the OpenAI client constructs).
Type of change