funasr-haystack 0.0.1__py3-none-any.whl

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,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,7 @@
1
+ haystack_integrations/components/audio/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ haystack_integrations/components/audio/funasr/__init__.py,sha256=ib-n7iBK5TL-CFD6TqkzNHf-v6bTfKWxbr-1IvvcBLE,232
3
+ haystack_integrations/components/audio/funasr/transcriber.py,sha256=B4pMwDJfAe-udZFPdIm6gur7s3e0wgp5lRWB4XMu1KY,10254
4
+ funasr_haystack-0.0.1.dist-info/METADATA,sha256=CYH2Vbe03NLfWTDiDUICTFPk1p37bueB3itNkQWV2PQ,1788
5
+ funasr_haystack-0.0.1.dist-info/WHEEL,sha256=mffPy8wBnZQn2VnJUU5jE99KsxaSfiyMHV9Yt0aLVxs,87
6
+ funasr_haystack-0.0.1.dist-info/licenses/LICENSE.txt,sha256=OrAtTu4aPmrTjKDSTzkSPgo_ji6NOMWO2N9JOTFyAzM,11350
7
+ funasr_haystack-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.30.1
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -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,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"
File without changes