funasr-haystack 0.0.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,146 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ pip-wheel-metadata/
24
+ share/python-wheels/
25
+ *.egg-info/
26
+ .installed.cfg
27
+ *.egg
28
+ MANIFEST
29
+
30
+ # PyInstaller
31
+ # Usually these files are written by a python script from a template
32
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
33
+ *.manifest
34
+ *.spec
35
+
36
+ # Installer logs
37
+ pip-log.txt
38
+ pip-delete-this-directory.txt
39
+
40
+ # Unit test / coverage reports
41
+ htmlcov/
42
+ .tox/
43
+ .nox/
44
+ .coverage
45
+ .coverage.*
46
+ .cache
47
+ nosetests.xml
48
+ coverage.xml
49
+ *.cover
50
+ *.py,cover
51
+ .hypothesis/
52
+ .pytest_cache/
53
+ volumes/
54
+
55
+ # Translations
56
+ *.mo
57
+ *.pot
58
+
59
+ # Django stuff:
60
+ *.log
61
+ local_settings.py
62
+ db.sqlite3
63
+ db.sqlite3-journal
64
+
65
+ # Flask stuff:
66
+ instance/
67
+ .webassets-cache
68
+
69
+ # Scrapy stuff:
70
+ .scrapy
71
+
72
+ # Sphinx documentation
73
+ docs/_build/
74
+
75
+ # PyBuilder
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ .python-version
87
+
88
+ # pipenv
89
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
90
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
91
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
92
+ # install all needed dependencies.
93
+ #Pipfile.lock
94
+
95
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow
96
+ __pypackages__/
97
+
98
+ # Celery stuff
99
+ celerybeat-schedule
100
+ celerybeat.pid
101
+
102
+ # SageMath parsed files
103
+ *.sage.py
104
+
105
+ # Environments
106
+ .env
107
+ .venv
108
+ env/
109
+ venv/
110
+ ENV/
111
+ env.bak/
112
+ venv.bak/
113
+
114
+ # Spyder project settings
115
+ .spyderproject
116
+ .spyproject
117
+
118
+ # Rope project settings
119
+ .ropeproject
120
+
121
+ # mkdocs documentation
122
+ /site
123
+
124
+ # mypy
125
+ .mypy_cache/
126
+ .dmypy.json
127
+ dmypy.json
128
+
129
+ # Pyre type checker
130
+ .pyre/
131
+
132
+ # IDEs
133
+ .vscode
134
+
135
+ # Docs generation artifacts
136
+ _readme_*.md
137
+ .idea
138
+
139
+ # macOS
140
+ .DS_Store
141
+
142
+ # http cache (requests-cache)
143
+ **/http_cache.sqlite
144
+
145
+ # ruff
146
+ .ruff_cache
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2023-present deepset GmbH
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,39 @@
1
+ Metadata-Version: 2.4
2
+ Name: funasr-haystack
3
+ Version: 0.0.1
4
+ Summary: FunASR speech-to-text transcriber for Haystack
5
+ Project-URL: Documentation, https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/funasr#readme
6
+ Project-URL: Issues, https://github.com/deepset-ai/haystack-core-integrations/issues
7
+ Project-URL: Source, https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/funasr
8
+ Author-email: deepset GmbH <info@deepset.ai>
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE.txt
11
+ Keywords: asr,audio,funasr,haystack,llm,rag,speech-to-text,transcription
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: License :: OSI Approved :: Apache Software License
14
+ Classifier: Programming Language :: Python
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Programming Language :: Python :: 3.14
20
+ Classifier: Programming Language :: Python :: Implementation :: CPython
21
+ Requires-Python: >=3.10
22
+ Requires-Dist: funasr>=1.0.0
23
+ Requires-Dist: haystack-ai>=2.9.0
24
+ Requires-Dist: torch
25
+ Requires-Dist: torchaudio
26
+ Description-Content-Type: text/markdown
27
+
28
+ # funasr-haystack
29
+
30
+ [![PyPI - Version](https://img.shields.io/pypi/v/funasr-haystack.svg)](https://pypi.org/project/funasr-haystack)
31
+ [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/funasr-haystack.svg)](https://pypi.org/project/funasr-haystack)
32
+
33
+ - [Changelog](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/funasr/CHANGELOG.md)
34
+
35
+ ---
36
+
37
+ ## Contributing
38
+
39
+ Refer to the general [Contribution Guidelines](https://github.com/deepset-ai/haystack-core-integrations/blob/main/CONTRIBUTING.md).
@@ -0,0 +1,12 @@
1
+ # funasr-haystack
2
+
3
+ [![PyPI - Version](https://img.shields.io/pypi/v/funasr-haystack.svg)](https://pypi.org/project/funasr-haystack)
4
+ [![PyPI - Python Version](https://img.shields.io/pypi/pyversions/funasr-haystack.svg)](https://pypi.org/project/funasr-haystack)
5
+
6
+ - [Changelog](https://github.com/deepset-ai/haystack-core-integrations/blob/main/integrations/funasr/CHANGELOG.md)
7
+
8
+ ---
9
+
10
+ ## Contributing
11
+
12
+ Refer to the general [Contribution Guidelines](https://github.com/deepset-ai/haystack-core-integrations/blob/main/CONTRIBUTING.md).
@@ -0,0 +1,13 @@
1
+ loaders:
2
+ - modules:
3
+ - haystack_integrations.components.audio.funasr.transcriber
4
+ search_path: [../src]
5
+ processors:
6
+ - type: filter
7
+ documented_only: true
8
+ skip_empty_modules: true
9
+ renderer:
10
+ description: FunASR speech-to-text integration for Haystack
11
+ id: integrations-funasr
12
+ filename: funasr.md
13
+ title: FunASR
@@ -0,0 +1,170 @@
1
+ [build-system]
2
+ requires = ["hatchling", "hatch-vcs"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "funasr-haystack"
7
+ dynamic = ["version"]
8
+ description = "FunASR speech-to-text transcriber for Haystack"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "Apache-2.0"
12
+ keywords = ["funasr", "speech-to-text", "asr", "audio", "transcription", "haystack", "llm", "rag"]
13
+ authors = [{ name = "deepset GmbH", email = "info@deepset.ai" }]
14
+ classifiers = [
15
+ "License :: OSI Approved :: Apache Software License",
16
+ "Development Status :: 4 - Beta",
17
+ "Programming Language :: Python",
18
+ "Programming Language :: Python :: 3.10",
19
+ "Programming Language :: Python :: 3.11",
20
+ "Programming Language :: Python :: 3.12",
21
+ "Programming Language :: Python :: 3.13",
22
+ "Programming Language :: Python :: 3.14",
23
+ "Programming Language :: Python :: Implementation :: CPython",
24
+ ]
25
+ dependencies = [
26
+ "haystack-ai>=2.9.0",
27
+ "funasr>=1.0.0",
28
+ "torch",
29
+ "torchaudio",
30
+ ]
31
+
32
+ [project.urls]
33
+ Documentation = "https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/funasr#readme"
34
+ Issues = "https://github.com/deepset-ai/haystack-core-integrations/issues"
35
+ Source = "https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/funasr"
36
+
37
+ [tool.hatch.build.targets.wheel]
38
+ packages = ["src/haystack_integrations"]
39
+
40
+ [tool.hatch.version]
41
+ source = "vcs"
42
+ tag-pattern = 'integrations\/funasr-v(?P<version>.*)'
43
+
44
+ [tool.hatch.version.raw-options]
45
+ root = "../.."
46
+ git_describe_command = 'git describe --tags --match="integrations/funasr-v[0-9]*"'
47
+
48
+ [tool.hatch.envs.default]
49
+ installer = "uv"
50
+ dependencies = ["haystack-pydoc-tools", "ruff"]
51
+
52
+ [tool.hatch.envs.default.scripts]
53
+ docs = ["haystack-pydoc pydoc/config_docusaurus.yml"]
54
+ fmt = "ruff check --fix {args}; ruff format {args}"
55
+ fmt-check = "ruff check {args} && ruff format --check {args}"
56
+
57
+ [tool.hatch.envs.test]
58
+ dependencies = [
59
+ "pytest",
60
+ "pytest-asyncio",
61
+ "pytest-cov",
62
+ "pytest-rerunfailures",
63
+ "mypy",
64
+ "pip",
65
+ "funasr>=1.0.0",
66
+ ]
67
+
68
+ [tool.hatch.envs.test.scripts]
69
+ unit = 'pytest -m "not integration" {args:tests}'
70
+ integration = 'pytest -m "integration" {args:tests}'
71
+ all = 'pytest {args:tests}'
72
+ unit-cov-retry = 'pytest --cov=haystack_integrations --reruns 3 --reruns-delay 30 -x -m "not integration" {args:tests}'
73
+ integration-cov-append-retry = 'pytest --cov=haystack_integrations --cov-append --reruns 3 --reruns-delay 30 -x -m "integration" {args:tests}'
74
+ types = "mypy -p haystack_integrations.components.audio.funasr {args}"
75
+
76
+ [tool.mypy]
77
+ install_types = true
78
+ non_interactive = true
79
+ check_untyped_defs = true
80
+ disallow_incomplete_defs = true
81
+
82
+ [[tool.mypy.overrides]]
83
+ module = ["funasr", "funasr.*"]
84
+ ignore_missing_imports = true
85
+
86
+ [tool.ruff]
87
+ line-length = 120
88
+
89
+ [tool.ruff.lint]
90
+ select = [
91
+ "A",
92
+ "ANN",
93
+ "ARG",
94
+ "B",
95
+ "C",
96
+ "D102", # Missing docstring in public method
97
+ "D103", # Missing docstring in public function
98
+ "D205", # 1 blank line required between summary line and description
99
+ "D209", # Closing triple quotes go to new line
100
+ "D213", # summary lines must be positioned on the second physical line of the docstring
101
+ "D417", # Missing argument descriptions in the docstring
102
+ "D419", # Docstring is empty
103
+ "DTZ",
104
+ "E",
105
+ "EM",
106
+ "F",
107
+ "I",
108
+ "ICN",
109
+ "ISC",
110
+ "N",
111
+ "PLC",
112
+ "PLE",
113
+ "PLR",
114
+ "PLW",
115
+ "Q",
116
+ "RUF",
117
+ "S",
118
+ "T",
119
+ "TID",
120
+ "UP",
121
+ "W",
122
+ "YTT",
123
+ ]
124
+ ignore = [
125
+ # Allow non-abstract empty methods in abstract base classes
126
+ "B027",
127
+ # Allow function calls in argument defaults (common Haystack pattern for Secret.from_env_var)
128
+ "B008",
129
+ # Ignore checks for possible passwords
130
+ "S105",
131
+ "S106",
132
+ "S107",
133
+ # Ignore complexity
134
+ "C901",
135
+ "PLR0911",
136
+ "PLR0912",
137
+ "PLR0913",
138
+ "PLR0915",
139
+ # Allow `Any` type - used legitimately for dynamic types and SDK boundaries
140
+ "ANN401",
141
+ ]
142
+
143
+ [tool.ruff.lint.isort]
144
+ known-first-party = ["haystack_integrations"]
145
+
146
+ [tool.ruff.lint.flake8-tidy-imports]
147
+ ban-relative-imports = "parents"
148
+
149
+ [tool.ruff.lint.per-file-ignores]
150
+ # Tests can use magic values, assertions, relative imports, and don't need type annotations
151
+ "tests/**/*" = ["PLR2004", "S101", "TID252", "D", "ANN"]
152
+
153
+ [tool.coverage.run]
154
+ source = ["haystack_integrations"]
155
+ branch = true
156
+ parallel = false
157
+ relative_files = true
158
+
159
+ [tool.coverage.report]
160
+ omit = ["*/tests/*", "*/__init__.py"]
161
+ show_missing = true
162
+ exclude_lines = ["no cov", "if __name__ == .__main__.:", "if TYPE_CHECKING:"]
163
+
164
+ [tool.pytest.ini_options]
165
+ addopts = "--strict-markers"
166
+ markers = [
167
+ "integration: integration tests",
168
+ ]
169
+ log_cli = true
170
+ asyncio_default_fixture_loop_scope = "function"
@@ -0,0 +1,7 @@
1
+ # SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ from haystack_integrations.components.audio.funasr.transcriber import FunASRTranscriber
6
+
7
+ __all__ = ["FunASRTranscriber"]
@@ -0,0 +1,270 @@
1
+ # SPDX-FileCopyrightText: 2023-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ import contextlib
6
+ import os
7
+ import tempfile
8
+ from pathlib import Path
9
+ from typing import Any
10
+
11
+ from haystack import Document, component, default_from_dict, default_to_dict, logging
12
+ from haystack.components.converters.utils import normalize_metadata
13
+ from haystack.dataclasses import ByteStream
14
+ from haystack.utils import ComponentDevice
15
+
16
+ from funasr import AutoModel
17
+
18
+ logger = logging.getLogger(__name__)
19
+
20
+ _MIME_TO_SUFFIX: dict[str, str] = {
21
+ "audio/wav": ".wav",
22
+ "audio/wave": ".wav",
23
+ "audio/x-wav": ".wav",
24
+ "audio/mpeg": ".mp3",
25
+ "audio/mp3": ".mp3",
26
+ "audio/ogg": ".ogg",
27
+ "audio/flac": ".flac",
28
+ "audio/aac": ".aac",
29
+ "audio/m4a": ".m4a",
30
+ "audio/webm": ".webm",
31
+ "audio/mp4": ".mp4",
32
+ "video/mp4": ".mp4",
33
+ "video/webm": ".webm",
34
+ }
35
+
36
+
37
+ @component
38
+ class FunASRTranscriber:
39
+ """
40
+ Transcribes audio files to Documents using [FunASR](https://github.com/modelscope/FunASR).
41
+
42
+ FunASR is an open-source speech recognition toolkit from Alibaba DAMO Academy.
43
+ It supports 50+ languages, speaker diarization, and timestamp extraction, and runs
44
+ entirely locally — no API key required.
45
+
46
+ Models are downloaded from ModelScope on first use and cached in `~/.cache/modelscope`.
47
+
48
+ **Usage Example:**
49
+
50
+ ```python
51
+ from haystack_integrations.components.audio.funasr import FunASRTranscriber
52
+
53
+ transcriber = FunASRTranscriber()
54
+ result = transcriber.run(sources=["speech.wav", "interview.mp3"])
55
+ documents = result["documents"]
56
+ ```
57
+
58
+ **Speaker diarization and punctuation:**
59
+
60
+ ```python
61
+ from haystack.utils import ComponentDevice
62
+
63
+ transcriber = FunASRTranscriber(
64
+ model="paraformer-zh",
65
+ vad_model="fsmn-vad",
66
+ punc_model="ct-punc",
67
+ spk_model="cam++",
68
+ device=ComponentDevice.from_str("cuda"),
69
+ )
70
+ ```
71
+
72
+ **SenseVoice with inverse text normalisation:**
73
+
74
+ ```python
75
+ transcriber = FunASRTranscriber(
76
+ model="iic/SenseVoiceSmall",
77
+ generation_kwargs={"use_itn": True, "merge_vad": True, "language": "auto"},
78
+ )
79
+ ```
80
+ """
81
+
82
+ def __init__(
83
+ self,
84
+ *,
85
+ model: str = "iic/SenseVoiceSmall",
86
+ vad_model: str | None = "fsmn-vad",
87
+ punc_model: str | None = "ct-punc",
88
+ spk_model: str | None = None,
89
+ device: ComponentDevice | None = None,
90
+ batch_size_s: int = 300,
91
+ store_full_path: bool = False,
92
+ generation_kwargs: dict[str, Any] | None = None,
93
+ ) -> None:
94
+ """
95
+ Create a FunASRTranscriber component.
96
+
97
+ :param model: FunASR model name or local path. Defaults to `"iic/SenseVoiceSmall"`,
98
+ a multilingual model supporting 50+ languages that is 5-10x faster than Whisper.
99
+ Alternatives include `"paraformer-zh"` (Chinese) or `"paraformer-en"` (English).
100
+ Browse available models at https://modelscope.github.io/FunASR/model-selection.html.
101
+ :param vad_model: Voice activity detection model used to split long audio into segments.
102
+ Set to `None` to process the audio as a single stream.
103
+ Browse available VAD models at https://www.modelscope.cn/models.
104
+ :param punc_model: Punctuation restoration model. Set to `None` to disable punctuation.
105
+ Browse available punctuation models at https://www.modelscope.cn/models.
106
+ :param spk_model: Speaker diarization model (e.g. `"cam++"`). When set, a `"speakers"`
107
+ key is included in the Document metadata. Defaults to `None` (diarization disabled).
108
+ Browse available speaker diarization models at https://www.modelscope.cn/models.
109
+ :param device: The device to run inference on. If `None`, the default device is selected
110
+ automatically. Use `ComponentDevice.from_str("cuda")` for GPU inference.
111
+ :param batch_size_s: Batch size in seconds for VAD-segmented audio. Larger values
112
+ improve throughput at the cost of memory.
113
+ :param store_full_path: If `True`, store the full audio file path in Document metadata.
114
+ If `False` (default), store only the file name.
115
+ :param generation_kwargs: Extra keyword arguments forwarded to `AutoModel.generate()`.
116
+ Use this for model-specific options such as `use_itn=True` or `merge_vad=True`
117
+ for SenseVoice, or `hotword="..."` for contextual recognition.
118
+ """
119
+ self.model = model
120
+ self.vad_model = vad_model
121
+ self.punc_model = punc_model
122
+ self.spk_model = spk_model
123
+ self.device = device
124
+ self.batch_size_s = batch_size_s
125
+ self.store_full_path = store_full_path
126
+ self.generation_kwargs: dict[str, Any] = generation_kwargs or {}
127
+ self._asr_model: Any = None
128
+
129
+ def warm_up(self) -> None:
130
+ """
131
+ Load the FunASR model into memory.
132
+
133
+ Models are downloaded from ModelScope on first call and cached locally.
134
+ This method is idempotent — calling it multiple times is safe.
135
+ """
136
+ if self._asr_model is not None:
137
+ return
138
+ self._asr_model = AutoModel(
139
+ model=self.model,
140
+ vad_model=self.vad_model,
141
+ punc_model=self.punc_model,
142
+ spk_model=self.spk_model,
143
+ device=ComponentDevice.resolve_device(self.device).to_torch_str(),
144
+ )
145
+
146
+ def to_dict(self) -> dict[str, Any]:
147
+ """
148
+ Serialize the component to a dictionary.
149
+
150
+ :returns: Dictionary with serialized data.
151
+ """
152
+ return default_to_dict(
153
+ self,
154
+ model=self.model,
155
+ vad_model=self.vad_model,
156
+ punc_model=self.punc_model,
157
+ spk_model=self.spk_model,
158
+ device=self.device.to_dict() if self.device else None,
159
+ batch_size_s=self.batch_size_s,
160
+ store_full_path=self.store_full_path,
161
+ generation_kwargs=self.generation_kwargs or None,
162
+ )
163
+
164
+ @classmethod
165
+ def from_dict(cls, data: dict[str, Any]) -> "FunASRTranscriber":
166
+ """
167
+ Deserialize the component from a dictionary.
168
+
169
+ :param data: Dictionary to deserialize from.
170
+ :returns: Deserialized component.
171
+ """
172
+ init_params = data.get("init_parameters", {})
173
+ if init_params.get("device"):
174
+ init_params["device"] = ComponentDevice.from_dict(init_params["device"])
175
+ return default_from_dict(cls, data)
176
+
177
+ @component.output_types(documents=list[Document])
178
+ def run(
179
+ self,
180
+ sources: list[str | Path | ByteStream],
181
+ meta: dict[str, Any] | list[dict[str, Any]] | None = None,
182
+ ) -> dict[str, list[Document]]:
183
+ """
184
+ Transcribe audio sources to Documents.
185
+
186
+ :param sources: Audio file paths (`str` or `Path`) or `ByteStream` objects.
187
+ Supported formats: WAV, MP3, FLAC, OGG, M4A, AAC, and any format that
188
+ FunASR's underlying audio backend (soundfile/ffmpeg) can decode.
189
+ :param meta: Metadata to attach to the produced Documents. Pass a single dict
190
+ to apply the same metadata to all Documents, or a list aligned with `sources`.
191
+ :returns: Dictionary with key `"documents"` — one `Document` per source whose
192
+ `content` holds the full transcript text.
193
+ """
194
+ if not sources:
195
+ return {"documents": []}
196
+ self.warm_up()
197
+
198
+ meta_list = normalize_metadata(meta, sources_count=len(sources))
199
+ documents: list[Document] = []
200
+
201
+ for source, user_meta in zip(sources, meta_list, strict=True):
202
+ try:
203
+ doc = self._transcribe(source, user_meta)
204
+ if doc is not None:
205
+ documents.append(doc)
206
+ except Exception as e:
207
+ logger.warning(
208
+ "Could not transcribe {source}. Skipping it. Error: {error}",
209
+ source=source,
210
+ error=e,
211
+ )
212
+
213
+ return {"documents": documents}
214
+
215
+ def _transcribe(
216
+ self,
217
+ source: str | Path | ByteStream,
218
+ user_meta: dict[str, Any],
219
+ ) -> Document | None:
220
+ """Transcribe a single audio source and return a Document, or None on empty result."""
221
+ tmp_path: str | None = None
222
+
223
+ if isinstance(source, ByteStream):
224
+ suffix = _mime_to_suffix(source.mime_type)
225
+ with tempfile.NamedTemporaryFile(suffix=suffix, delete=False) as tmp:
226
+ tmp.write(source.data)
227
+ tmp_path = tmp.name
228
+ audio_path: str = tmp_path
229
+ raw_name: str = str(source.meta.get("file_path") or source.meta.get("file_name") or "audio")
230
+ source_name = raw_name if self.store_full_path else Path(raw_name).name
231
+ else:
232
+ audio_path = str(source)
233
+ source_name = str(source) if self.store_full_path else Path(source).name
234
+
235
+ try:
236
+ results: list[dict[str, Any]] = self._asr_model.generate(
237
+ input=audio_path,
238
+ batch_size_s=self.batch_size_s,
239
+ **self.generation_kwargs,
240
+ )
241
+
242
+ if not results:
243
+ logger.warning("FunASR returned no results for {source}.", source=source)
244
+ return None
245
+
246
+ text = " ".join(r.get("text", "") for r in results).strip()
247
+
248
+ doc_meta: dict[str, Any] = {"file_path": source_name}
249
+
250
+ timestamps = [ts for r in results for ts in (r.get("timestamp") or [])]
251
+ if timestamps:
252
+ doc_meta["timestamps"] = timestamps
253
+
254
+ speakers = [sp for r in results for sp in (r.get("spk") or [])]
255
+ if speakers:
256
+ doc_meta["speakers"] = speakers
257
+
258
+ doc_meta.update(user_meta)
259
+ return Document(content=text, meta=doc_meta)
260
+ finally:
261
+ if tmp_path is not None:
262
+ with contextlib.suppress(OSError):
263
+ os.unlink(tmp_path)
264
+
265
+
266
+ def _mime_to_suffix(mime_type: str | None) -> str:
267
+ """Return a file extension for the given MIME type, defaulting to `.wav`."""
268
+ if mime_type:
269
+ return _MIME_TO_SUFFIX.get(mime_type.lower(), ".wav")
270
+ return ".wav"
@@ -0,0 +1,3 @@
1
+ # SPDX-FileCopyrightText: 2022-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
@@ -0,0 +1,8 @@
1
+ from pathlib import Path
2
+
3
+ import pytest
4
+
5
+
6
+ @pytest.fixture()
7
+ def test_files_path():
8
+ return Path(__file__).parent / "test_files"
@@ -0,0 +1,365 @@
1
+ # SPDX-FileCopyrightText: 2023-present deepset GmbH <info@deepset.ai>
2
+ #
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ import os
6
+ import sys
7
+ from unittest.mock import MagicMock, patch
8
+
9
+ import pytest
10
+ from haystack.dataclasses import ByteStream
11
+ from haystack.utils import ComponentDevice
12
+
13
+ from haystack_integrations.components.audio.funasr import FunASRTranscriber
14
+
15
+
16
+ def _make_transcriber(**kwargs) -> FunASRTranscriber:
17
+ return FunASRTranscriber(**kwargs)
18
+
19
+
20
+ def _inject_mock_model(transcriber: FunASRTranscriber, results: list[dict]) -> MagicMock:
21
+ mock_model = MagicMock()
22
+ mock_model.generate.return_value = results
23
+ transcriber._asr_model = mock_model
24
+ return mock_model
25
+
26
+
27
+ class TestFunASRTranscriberInit:
28
+ def test_defaults(self):
29
+ t = _make_transcriber()
30
+ assert t.model == "iic/SenseVoiceSmall"
31
+ assert t.vad_model == "fsmn-vad"
32
+ assert t.punc_model == "ct-punc"
33
+ assert t.spk_model is None
34
+ assert t.device is None
35
+ assert t.batch_size_s == 300
36
+ assert t.store_full_path is False
37
+ assert t.generation_kwargs == {}
38
+ assert t._asr_model is None
39
+
40
+ def test_custom_params(self):
41
+ t = _make_transcriber(
42
+ model="paraformer-zh",
43
+ vad_model=None,
44
+ punc_model=None,
45
+ spk_model="cam++",
46
+ device=ComponentDevice.from_str("cuda"),
47
+ batch_size_s=60,
48
+ store_full_path=True,
49
+ generation_kwargs={"use_itn": True},
50
+ )
51
+ assert t.model == "paraformer-zh"
52
+ assert t.vad_model is None
53
+ assert t.punc_model is None
54
+ assert t.spk_model == "cam++"
55
+ assert t.device == ComponentDevice.from_str("cuda")
56
+ assert t.batch_size_s == 60
57
+ assert t.store_full_path is True
58
+ assert t.generation_kwargs == {"use_itn": True}
59
+
60
+
61
+ class TestFunASRTranscriberSerialization:
62
+ def test_to_dict(self):
63
+ t = _make_transcriber()
64
+ d = t.to_dict()
65
+ assert d["type"].endswith("FunASRTranscriber")
66
+ p = d["init_parameters"]
67
+ assert p["model"] == "iic/SenseVoiceSmall"
68
+ assert p["vad_model"] == "fsmn-vad"
69
+ assert p["punc_model"] == "ct-punc"
70
+ assert p["spk_model"] is None
71
+ assert p["device"] is None
72
+ assert p["batch_size_s"] == 300
73
+ assert p["store_full_path"] is False
74
+ assert p["generation_kwargs"] is None
75
+
76
+ def test_to_dict_with_generation_kwargs(self):
77
+ t = _make_transcriber(generation_kwargs={"use_itn": True, "merge_vad": True})
78
+ d = t.to_dict()
79
+ assert d["init_parameters"]["generation_kwargs"] == {"use_itn": True, "merge_vad": True}
80
+
81
+ def test_to_dict_with_device(self):
82
+ t = _make_transcriber(device=ComponentDevice.from_str("cuda"))
83
+ d = t.to_dict()
84
+ assert d["init_parameters"]["device"] == {"type": "single", "device": "cuda"}
85
+
86
+ def test_from_dict(self):
87
+ data = {
88
+ "type": "haystack_integrations.components.audio.funasr.transcriber.FunASRTranscriber",
89
+ "init_parameters": {
90
+ "model": "paraformer-zh",
91
+ "vad_model": "fsmn-vad",
92
+ "punc_model": "ct-punc",
93
+ "spk_model": "cam++",
94
+ "device": {"type": "single", "device": "cuda"},
95
+ "batch_size_s": 60,
96
+ "store_full_path": False,
97
+ "generation_kwargs": {"use_itn": True},
98
+ },
99
+ }
100
+ t = FunASRTranscriber.from_dict(data)
101
+ assert t.model == "paraformer-zh"
102
+ assert t.spk_model == "cam++"
103
+ assert t.device == ComponentDevice.from_str("cuda")
104
+ assert t.generation_kwargs == {"use_itn": True}
105
+
106
+ def test_from_dict_no_device(self):
107
+ data = {
108
+ "type": "haystack_integrations.components.audio.funasr.transcriber.FunASRTranscriber",
109
+ "init_parameters": {
110
+ "model": "iic/SenseVoiceSmall",
111
+ "vad_model": "fsmn-vad",
112
+ "punc_model": "ct-punc",
113
+ "spk_model": None,
114
+ "device": None,
115
+ "batch_size_s": 300,
116
+ "store_full_path": False,
117
+ "generation_kwargs": None,
118
+ },
119
+ }
120
+ t = FunASRTranscriber.from_dict(data)
121
+ assert t.device is None
122
+
123
+ def test_to_from_dict_roundtrip(self):
124
+ t = _make_transcriber(
125
+ model="paraformer-zh",
126
+ spk_model="cam++",
127
+ batch_size_s=60,
128
+ device=ComponentDevice.from_str("cpu"),
129
+ )
130
+ t2 = FunASRTranscriber.from_dict(t.to_dict())
131
+ assert t.model == t2.model
132
+ assert t.spk_model == t2.spk_model
133
+ assert t.batch_size_s == t2.batch_size_s
134
+ assert t.device == t2.device
135
+
136
+
137
+ class TestFunASRTranscriberWarmUp:
138
+ def test_warm_up_loads_model(self):
139
+ t = _make_transcriber()
140
+ mock_instance = MagicMock()
141
+ mock_cls = MagicMock(return_value=mock_instance)
142
+
143
+ with patch("haystack_integrations.components.audio.funasr.transcriber.AutoModel", mock_cls):
144
+ t.warm_up()
145
+
146
+ assert t._asr_model is mock_instance
147
+ expected_device = ComponentDevice.resolve_device(None).to_torch_str()
148
+ mock_cls.assert_called_once_with(
149
+ model="iic/SenseVoiceSmall",
150
+ vad_model="fsmn-vad",
151
+ punc_model="ct-punc",
152
+ spk_model=None,
153
+ device=expected_device,
154
+ )
155
+
156
+ def test_warm_up_idempotent(self):
157
+ t = _make_transcriber()
158
+ existing_model = MagicMock()
159
+ t._asr_model = existing_model
160
+ t.warm_up()
161
+ assert t._asr_model is existing_model
162
+
163
+
164
+ class TestFunASRTranscriberRun:
165
+ def test_run_empty_sources(self):
166
+ t = _make_transcriber()
167
+ result = t.run(sources=[])
168
+ assert result == {"documents": []}
169
+
170
+ def test_run_single_file(self, tmp_path):
171
+ t = _make_transcriber()
172
+ audio_file = tmp_path / "test.wav"
173
+ audio_file.write_bytes(b"fake audio")
174
+ _inject_mock_model(t, [{"text": "Hello world"}])
175
+
176
+ result = t.run(sources=[str(audio_file)])
177
+ assert len(result["documents"]) == 1
178
+ assert result["documents"][0].content == "Hello world"
179
+ assert result["documents"][0].meta["file_path"] == "test.wav"
180
+
181
+ def test_run_multiple_files(self, tmp_path):
182
+ t = _make_transcriber()
183
+ f1, f2 = tmp_path / "a.wav", tmp_path / "b.wav"
184
+ f1.write_bytes(b"x")
185
+ f2.write_bytes(b"x")
186
+ mock = _inject_mock_model(t, [{"text": "one"}])
187
+ mock.generate.side_effect = [
188
+ [{"text": "one"}],
189
+ [{"text": "two"}],
190
+ ]
191
+
192
+ result = t.run(sources=[str(f1), str(f2)])
193
+ assert len(result["documents"]) == 2
194
+ assert result["documents"][0].content == "one"
195
+ assert result["documents"][1].content == "two"
196
+
197
+ def test_run_merges_vad_segments(self, tmp_path):
198
+ t = _make_transcriber()
199
+ audio = tmp_path / "long.wav"
200
+ audio.write_bytes(b"x")
201
+ _inject_mock_model(t, [{"text": "Hello"}, {"text": "world"}])
202
+
203
+ result = t.run(sources=[str(audio)])
204
+ assert result["documents"][0].content == "Hello world"
205
+
206
+ def test_run_with_metadata(self, tmp_path):
207
+ t = _make_transcriber()
208
+ audio = tmp_path / "test.wav"
209
+ audio.write_bytes(b"x")
210
+ _inject_mock_model(t, [{"text": "Hi"}])
211
+
212
+ result = t.run(sources=[str(audio)], meta={"topic": "greeting"})
213
+ assert result["documents"][0].meta["topic"] == "greeting"
214
+
215
+ def test_run_with_metadata_list(self, tmp_path):
216
+ t = _make_transcriber()
217
+ f1, f2 = tmp_path / "a.wav", tmp_path / "b.wav"
218
+ f1.write_bytes(b"x")
219
+ f2.write_bytes(b"x")
220
+ mock = _inject_mock_model(t, [{"text": "one"}])
221
+ mock.generate.side_effect = [[{"text": "one"}], [{"text": "two"}]]
222
+
223
+ result = t.run(sources=[str(f1), str(f2)], meta=[{"idx": 0}, {"idx": 1}])
224
+ assert result["documents"][0].meta["idx"] == 0
225
+ assert result["documents"][1].meta["idx"] == 1
226
+
227
+ def test_run_store_full_path(self, tmp_path):
228
+ t = _make_transcriber(store_full_path=True)
229
+ audio = tmp_path / "test.wav"
230
+ audio.write_bytes(b"x")
231
+ _inject_mock_model(t, [{"text": "Hi"}])
232
+
233
+ result = t.run(sources=[str(audio)])
234
+ assert result["documents"][0].meta["file_path"] == str(audio)
235
+
236
+ def test_run_with_timestamps(self, tmp_path):
237
+ t = _make_transcriber()
238
+ audio = tmp_path / "test.wav"
239
+ audio.write_bytes(b"x")
240
+ _inject_mock_model(t, [{"text": "Hi", "timestamp": [[0, 500], [500, 1000]]}])
241
+
242
+ result = t.run(sources=[str(audio)])
243
+ assert result["documents"][0].meta["timestamps"] == [[0, 500], [500, 1000]]
244
+
245
+ def test_run_with_speakers(self, tmp_path):
246
+ t = _make_transcriber(spk_model="cam++")
247
+ audio = tmp_path / "test.wav"
248
+ audio.write_bytes(b"x")
249
+ _inject_mock_model(t, [{"text": "Hi", "spk": [0, 1]}])
250
+
251
+ result = t.run(sources=[str(audio)])
252
+ assert result["documents"][0].meta["speakers"] == [0, 1]
253
+
254
+ def test_run_no_timestamps_or_speakers_when_absent(self, tmp_path):
255
+ t = _make_transcriber()
256
+ audio = tmp_path / "test.wav"
257
+ audio.write_bytes(b"x")
258
+ _inject_mock_model(t, [{"text": "Hi"}])
259
+
260
+ result = t.run(sources=[str(audio)])
261
+ assert "timestamps" not in result["documents"][0].meta
262
+ assert "speakers" not in result["documents"][0].meta
263
+
264
+ def test_run_empty_result_skipped(self, tmp_path):
265
+ t = _make_transcriber()
266
+ audio = tmp_path / "test.wav"
267
+ audio.write_bytes(b"x")
268
+ _inject_mock_model(t, [])
269
+
270
+ result = t.run(sources=[str(audio)])
271
+ assert result["documents"] == []
272
+
273
+ def test_run_error_skips_source(self, tmp_path):
274
+ t = _make_transcriber()
275
+ audio = tmp_path / "test.wav"
276
+ audio.write_bytes(b"x")
277
+ mock = _inject_mock_model(t, [])
278
+ mock.generate.side_effect = RuntimeError("model error")
279
+
280
+ result = t.run(sources=[str(audio)])
281
+ assert result["documents"] == []
282
+
283
+ def test_run_passes_generation_kwargs(self, tmp_path):
284
+ t = _make_transcriber(generation_kwargs={"use_itn": True, "language": "en"})
285
+ audio = tmp_path / "test.wav"
286
+ audio.write_bytes(b"x")
287
+ mock = _inject_mock_model(t, [{"text": "Hello"}])
288
+
289
+ t.run(sources=[str(audio)])
290
+ call_kwargs = mock.generate.call_args
291
+ assert call_kwargs.kwargs.get("use_itn") is True
292
+ assert call_kwargs.kwargs.get("language") == "en"
293
+ assert call_kwargs.kwargs.get("batch_size_s") == 300
294
+
295
+
296
+ class TestFunASRTranscriberByteStream:
297
+ def test_run_bytestream(self):
298
+ t = _make_transcriber()
299
+ bs = ByteStream(data=b"fake audio", mime_type="audio/wav", meta={"file_name": "clip.wav"})
300
+ _inject_mock_model(t, [{"text": "Hello from bytes"}])
301
+
302
+ result = t.run(sources=[bs])
303
+ assert len(result["documents"]) == 1
304
+ assert result["documents"][0].content == "Hello from bytes"
305
+ assert result["documents"][0].meta["file_path"] == "clip.wav"
306
+
307
+ def test_run_bytestream_unknown_mime(self):
308
+ t = _make_transcriber()
309
+ bs = ByteStream(data=b"fake", mime_type=None)
310
+ mock = _inject_mock_model(t, [{"text": "text"}])
311
+
312
+ t.run(sources=[bs])
313
+ mock.generate.assert_called_once()
314
+
315
+ def test_run_bytestream_cleans_up_temp_file(self):
316
+ t = _make_transcriber()
317
+ bs = ByteStream(data=b"x", mime_type="audio/wav")
318
+ _inject_mock_model(t, [{"text": "hi"}])
319
+
320
+ created_paths: list[str] = []
321
+ original_ntf = __import__("tempfile").NamedTemporaryFile
322
+
323
+ def tracking_ntf(**kwargs):
324
+ f = original_ntf(**kwargs)
325
+ created_paths.append(f.name)
326
+ return f
327
+
328
+ with patch("tempfile.NamedTemporaryFile", side_effect=tracking_ntf):
329
+ t.run(sources=[bs])
330
+
331
+ for p in created_paths:
332
+ assert not os.path.exists(p), f"Temp file {p} was not cleaned up"
333
+
334
+ def test_run_bytestream_cleans_up_on_error(self):
335
+ t = _make_transcriber()
336
+ bs = ByteStream(data=b"x", mime_type="audio/wav")
337
+ mock = _inject_mock_model(t, [])
338
+ mock.generate.side_effect = RuntimeError("boom")
339
+
340
+ created_paths: list[str] = []
341
+ original_ntf = __import__("tempfile").NamedTemporaryFile
342
+
343
+ def tracking_ntf(**kwargs):
344
+ f = original_ntf(**kwargs)
345
+ created_paths.append(f.name)
346
+ return f
347
+
348
+ with patch("tempfile.NamedTemporaryFile", side_effect=tracking_ntf):
349
+ t.run(sources=[bs])
350
+
351
+ for p in created_paths:
352
+ assert not os.path.exists(p), f"Temp file {p} leaked after error"
353
+
354
+
355
+ @pytest.mark.integration
356
+ @pytest.mark.skipif(sys.version_info < (3, 14) or sys.platform != "linux", reason="slow")
357
+ class TestFunASRTranscriberIntegration:
358
+ def test_transcribe_wav(self, test_files_path):
359
+ audio_path = test_files_path / "answer.wav"
360
+
361
+ t = FunASRTranscriber(model="iic/SenseVoiceSmall", vad_model=None, punc_model=None)
362
+ t.warm_up()
363
+ result = t.run(sources=[str(audio_path)])
364
+ assert len(result["documents"]) == 1
365
+ assert "answer" in result["documents"][0].content.lower()