Skip to content

feat(stt): add FunASR / SenseVoice as a built-in speech-to-text provider (#15449) - #15526

Closed
Rene0422 wants to merge 5 commits into
infiniflow:mainfrom
Rene0422:feat/funasr-sensevoice-stt-provider
Closed

Rene0422 wants to merge 5 commits into
infiniflow:mainfrom
Rene0422:feat/funasr-sensevoice-stt-provider

Conversation

@Rene0422

@Rene0422 Rene0422 commented Jun 2, 2026

Copy link
Copy Markdown
Contributor

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)

  • Self-hosted — aligns with RAGFlow's self-hosted philosophy
  • OpenAI-compatible API — no custom HTTP code on our side
  • Fast — SenseVoice is ~5× faster than Whisper
    (non-autoregressive, 234M params)
  • 50+ languages with automatic language detection
  • One toolkit — VAD + ASR + punctuation + speaker diarization

Files changed

File Change
rag/llm/sequence2txt_model.py New FunASRSeq2txt(GPTSeq2txt) class. _FACTORY_NAME = "FunASR". Defaults base_url="http://localhost:8000/v1" and model_name="SenseVoiceSmall". Empty key is replaced with "funasr" so the OpenAI client constructs. transcription() is inherited from Base.
conf/llm_factories.json New factory entry {"name": "FunASR", "tags": "SPEECH2TEXT", "status": "1", "llm": []}. rag/llm/__init__.py auto-discovers it by _FACTORY_NAME.
web/src/constants/llm.ts LLMFactory.FunASR = 'FunASR' + IconMap[FunASR] = 'funasr'.
web/src/pages/user-setting/constants.tsx Added to LocalLlmFactories so the local-server config modal handles it.
web/src/pages/user-setting/setting-model/modal/ollama-modal/index.tsx optionsMap[FunASR] = ['speech2text'] (single allowed model type) + docs URL to the FunASR GitHub repo.

What's intentionally not in this PR

  • Custom asset. IconMap[FunASR] = 'funasr' references
    funasr.svg (or .png); follow the project's usual icon-asset
    PR pattern to drop it in.
  • Local server bundling. RAGFlow remains a remote client of
    FunASR, mirroring the MinerU / Docling / OpenDataLoader story.
    Users run funasr-server themselves.
  • i18n strings. No new copy added; the existing model-type
    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'))" ✓
  • Runtime smoke-load of the new class via importlib.util with
    project-internal deps stubbed: confirmed
    • _FACTORY_NAME == "FunASR" (matches JSON entry and FE enum)
    • MRO is FunASRSeq2txt → GPTSeq2txt → Base → ABC → object so
      transcription() is inherited correctly
    • constructs with both default and custom base_url
    • empty key is replaced with "funasr" before reaching the
      OpenAI 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 the
sandbox blocked the pip install of pytest. Please run in CI:

  • uv run pytest — the changes are purely additive (no
    existing 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

  • Start FunASR locally:
    funasr-server --device cuda (defaults to
    http://localhost:8000/v1).
  • In Model providers, FunASR appears in the list with the
    SPEECH2TEXT tag.
  • Click Add the model on FunASR; the modal shows
    speech2text as the only model type (not chat / embedding
    / rerank). Default base_url shows
    http://localhost:8000/v1, default llm_name is
    SenseVoiceSmall. The "Verify" button hits the live server
    and returns a green check.
  • Set FunASR as the tenant Sequence2Text model. Ingest an
    audio file (e.g. .mp3 / .wav / .m4a). Transcript appears
    in the parsed document with correct text.
  • Repeat with a video file (the existing audio-extract path)
    and confirm transcript ingestion.
  • Custom remote endpoint:
    base_url=http://gpu-host:9090/v1, model
    paraformer-zh. Same flow works against a non-default host
    and a non-default model.
  • Empty API-key field — the modal still saves and verification
    succeeds (the placeholder funasr is substituted server-side
    so the OpenAI client constructs).

Type of change

  • Bug Fix (non-breaking change which fixes an issue)
  • New Feature (non-breaking change which adds functionality)
  • Documentation Update
  • Refactoring
  • Performance Improvement
  • Other (please describe):

@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. 💞 feature Feature request, pull request that fullfill a new feature. labels Jun 2, 2026
@coderabbitai

coderabbitai Bot commented Jun 2, 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 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.

Changes

FunASR Speech-to-Text Provider

Layer / File(s) Summary
Backend FunASR provider class
rag/llm/sequence2txt_model.py
FunASRSeq2txt extends GPTSeq2txt with OpenAI-compatible endpoint targeting http://localhost:8000/v1, defaults to SenseVoiceSmall, substitutes a placeholder API key when needed, and logs initialization.
Provider configuration and registration
conf/llm_factories.json
FunASR factory registered with SPEECH2TEXT tag, enabled status, and empty llm array for discovery.
Frontend provider constants and icon mapping
web/src/constants/llm.ts, web/src/pages/user-setting/constants.tsx
LLMFactory.FunASR enum member added, mapped to 'funasr' icon, and included in LocalLlmFactories as locally supported.
Frontend modal configuration
web/src/pages/user-setting/setting-model/modal/ollama-modal/index.tsx
FunASR added to documentation URL mapping and options map, restricted to speech2text model type only with reference to issue #15449.
Parser atomic-region logic and tests
deepdoc/parser/markdown_parser.py, test/unit_test/deepdoc/parser/test_markdown_parser.py
Adds _atomic_region_ranges() and updates extract_elements(), _extract_code_block(), and _extract_text_block() to support backtick/tilde fences and CommonMark-style matching; adds regression tests covering nested/tilde/unterminated fences and delimiter-splitting atomic regions.

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
Loading

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related issues

  • #15448: The main changes implement a FunASR speech-to-text provider (FunASRSeq2txt, factory entry, UI hooks) that directly correspond to the requested FunASR transcription integration.

Possibly related PRs

  • infiniflow/ragflow#15630: Similar fixes to deepdoc/parser/markdown_parser.py and tests for fenced code block handling and delimiter-safe extraction.

Suggested labels

size:M

Suggested reviewers

  • KevinHuSh

Poem

🐰 I hopped in code to hear a new voice sing,
FunASR listens, tiny bits take wing.
Fences stay whole, the parser keeps them tight,
Tests pass the tune in the soft morning light.
Hooray — the rabbit hums, a joyful spring.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 52.94% 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 Title clearly and concisely summarizes the main feature: adding FunASR/SenseVoice as a speech-to-text provider, with relevant issue reference (#15449).
Description check ✅ Passed PR description provides comprehensive context, rationale, detailed file-by-file changes, validation performed, and test plan covering all scenarios.
Linked Issues check ✅ Passed All objectives from issue #15449 are met: self-hosted STT option via FunASR's OpenAI-compatible API, configurable base_url and model_name with sensible defaults, and support for 50+ languages with existing FunASR capabilities.
Out of Scope Changes check ✅ Passed All changes are directly aligned with adding FunASR as a speech-to-text provider; no out-of-scope modifications detected beyond the stated scope.

✏️ 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 and usage tips.

@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.

🧹 Nitpick comments (1)
rag/llm/sequence2txt_model.py (1)

453-467: ⚡ Quick win

Align 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

📥 Commits

Reviewing files that changed from the base of the PR and between 9799f33 and c94934f.

📒 Files selected for processing (5)
  • conf/llm_factories.json
  • rag/llm/sequence2txt_model.py
  • web/src/constants/llm.ts
  • web/src/pages/user-setting/constants.tsx
  • web/src/pages/user-setting/setting-model/modal/ollama-modal/index.tsx

@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: 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

📥 Commits

Reviewing files that changed from the base of the PR and between c94934f and f782500.

📒 Files selected for processing (2)
  • rag/llm/sequence2txt_model.py
  • test/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

Comment on lines +100 to +154
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"]

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.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

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.

@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. and removed size:M This PR changes 30-99 lines, ignoring generated files. labels Jun 3, 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.

🧹 Nitpick comments (1)
deepdoc/parser/markdown_parser.py (1)

135-168: ⚡ Quick win

Add 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

📥 Commits

Reviewing files that changed from the base of the PR and between f782500 and f57c510.

📒 Files selected for processing (1)
  • deepdoc/parser/markdown_parser.py

@Rene0422
Rene0422 force-pushed the feat/funasr-sensevoice-stt-provider branch 2 times, most recently from 693e68c to 2aa0a93 Compare June 4, 2026 12:03
@Rene0422
Rene0422 force-pushed the feat/funasr-sensevoice-stt-provider branch from 2aa0a93 to 26c38d8 Compare June 8, 2026 09:37
@LauraGPT

Copy link
Copy Markdown
Contributor

Thanks for pushing this integration forward — RAGFlow + local FunASR/SenseVoice is a great fit.

One compatibility issue to fix before merge: the current default model_name="SenseVoiceSmall" in FunASRSeq2txt does not match the model IDs accepted by FunASR's OpenAI-compatible server.

I checked current FunASR main:

  • examples/openai_api/server.py registers the default SenseVoice endpoint as the alias sensevoice.
  • funasr/bin/_server_app.py also exposes /v1/models with aliases such as fun-asr-nano, sensevoice, and paraformer.
  • Requests to /v1/audio/transcriptions validate the submitted model form field against those aliases, so SenseVoiceSmall will be rejected as an unknown model by the stock server.

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 FunASRSeq2txt("", base_url="http://localhost:8000/v1") and asserts model_name == "sensevoice". That test does not need to hit a running FunASR server, but it prevents the alias from drifting back to the checkpoint name.

Reference points:

  • https://github.com/modelscope/FunASR/blob/main/examples/openai_api/server.py
  • https://github.com/modelscope/FunASR/blob/main/funasr/bin/_server_app.py

@LauraGPT

Copy link
Copy Markdown
Contributor

I reproduced the current merge conflict against infiniflow/main@5276baf and prepared a conflict-resolved branch here:

https://github.com/LauraGPT/ragflow/tree/funasr/ragflow-15526-conflict-fix

What this branch does:

  • keeps both current main additions and this PR's FunASR integration (New API remains registered, FunASR remains registered);
  • resolves the markdown parser conflict by using the current _extract_delimited_elements() / _protected_ranges() path, so fenced code, Markdown tables, and HTML tables stay protected, while preserving the newer lone-header merge behavior;
  • keeps the FunASR provider/config/UI wiring from this PR;
  • fixes the default FunASR OpenAI API model alias from SenseVoiceSmall to sensevoice, matching the stock FunASR /v1/audio/transcriptions model aliases.

Local verification on the conflict-resolved checkout:

python -m py_compile deepdoc/parser/markdown_parser.py rag/llm/sequence2txt_model.py
python -m pytest -c /dev/null --confcutdir=test/unit_test/deepdoc/parser test/unit_test/deepdoc/parser/test_markdown_parser.py -q
# 12 passed
git diff --check

The branch is based on the latest main I tested (5276baf) and should be usable as a replacement head or as a reference patch for updating this PR branch.

@LauraGPT

Copy link
Copy Markdown
Contributor

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:

python -m py_compile deepdoc/parser/markdown_parser.py rag/llm/sequence2txt_model.py
python -m pytest -c /dev/null --confcutdir=test/unit_test/deepdoc/parser test/unit_test/deepdoc/parser/test_markdown_parser.py -q
# 12 passed
git diff --check origin/main...HEAD

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.

LauraGPT added a commit to LauraGPT/ragflow that referenced this pull request Jul 13, 2026
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]>
yuzhichang pushed a commit that referenced this pull request Jul 15, 2026
### 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]>
@JinHai-CN

Copy link
Copy Markdown
Member

duplicate with #16473

@JinHai-CN JinHai-CN closed this Aug 31, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

💞 feature Feature request, pull request that fullfill a new feature. size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature Request]: Add FunASR/SenseVoice as built-in Speech-to-Text provider

3 participants