-
Notifications
You must be signed in to change notification settings - Fork 3k
Add num channels to audio #7840
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
lhoestq
merged 7 commits into
huggingface:main
from
CloseChoice:add-num-channels-to-audio
Nov 3, 2025
+52
−10
Merged
Changes from 4 commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
70a5afa
WIP: add audio, tests failing
CloseChoice c82d958
WIP: add mono argument, tests failing
CloseChoice a7b3c41
change from mono to num_channels in documentation, audio tests passing
CloseChoice 0418ce9
update docs and move test for audio
CloseChoice 64b1567
update audio
CloseChoice 361ec6a
update docstring for audio
CloseChoice 6d0a2f5
Apply suggestions from code review
lhoestq File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -49,9 +49,12 @@ class Audio: | |
| Args: | ||
| sampling_rate (`int`, *optional*): | ||
| Target sampling rate. If `None`, the native sampling rate is used. | ||
| mono (`bool`, defaults to `True`): | ||
| num_channels (`int`, *optional*): | ||
| The desired number of channels of the decoded samples. By default, the number of channels of the source is used. | ||
| Currently `None` (number of channels of the source), `1` (mono) or `2` (stereo) channels are supported. | ||
| mono (Optiona[`bool`], defaults to `None`): | ||
| Whether to convert the audio signal to mono by averaging samples across | ||
| channels. | ||
| channels. If `None`, the audio signal is left in its original number of channels. | ||
| decode (`bool`, defaults to `True`): | ||
| Whether to decode the audio data. If `False`, | ||
| returns the underlying dictionary in the format `{"path": audio_path, "bytes": audio_bytes}`. | ||
|
|
@@ -78,6 +81,7 @@ class Audio: | |
|
|
||
| sampling_rate: Optional[int] = None | ||
| decode: bool = True | ||
| num_channels: Optional[int] = None | ||
| stream_index: Optional[int] = None | ||
| id: Optional[str] = field(default=None, repr=False) | ||
| # Automatically constructed | ||
|
|
@@ -126,7 +130,7 @@ def encode_example(self, value: Union[str, bytes, bytearray, dict, "AudioDecoder | |
| buffer = BytesIO() | ||
| AudioEncoder( | ||
| torch.from_numpy(value["array"].astype(np.float32)), sample_rate=value["sampling_rate"] | ||
| ).to_file_like(buffer, format="wav") | ||
| ).to_file_like(buffer, format="wav", num_channels=self.num_channels) | ||
| return {"bytes": buffer.getvalue(), "path": None} | ||
| elif value.get("path") is not None and os.path.isfile(value["path"]): | ||
| # we set "bytes": None to not duplicate the data if they're already available locally | ||
|
|
@@ -143,7 +147,7 @@ def encode_example(self, value: Union[str, bytes, bytearray, dict, "AudioDecoder | |
|
|
||
| buffer = BytesIO() | ||
| AudioEncoder(torch.from_numpy(bytes_value), sample_rate=value["sampling_rate"]).to_file_like( | ||
| buffer, format="wav" | ||
| buffer, format="wav", num_channels=self.num_channels | ||
| ) | ||
| return {"bytes": buffer.getvalue(), "path": None} | ||
| else: | ||
|
|
@@ -188,7 +192,9 @@ def decode_example( | |
| raise ValueError(f"An audio sample should have one of 'path' or 'bytes' but both are None in {value}.") | ||
|
|
||
| if bytes is None and is_local_path(path): | ||
| audio = AudioDecoder(path, stream_index=self.stream_index, sample_rate=self.sampling_rate) | ||
| audio = AudioDecoder( | ||
| path, stream_index=self.stream_index, sample_rate=self.sampling_rate, num_channels=self.num_channels | ||
| ) | ||
|
|
||
| elif bytes is None: | ||
| token_per_repo_id = token_per_repo_id or {} | ||
|
|
@@ -201,10 +207,14 @@ def decode_example( | |
|
|
||
| download_config = DownloadConfig(token=token) | ||
| f = xopen(path, "rb", download_config=download_config) | ||
| audio = AudioDecoder(f, stream_index=self.stream_index, sample_rate=self.sampling_rate) | ||
| audio = AudioDecoder( | ||
| f, stream_index=self.stream_index, sample_rate=self.sampling_rate, num_channels=self.num_channels | ||
| ) | ||
|
|
||
| else: | ||
| audio = AudioDecoder(bytes, stream_index=self.stream_index, sample_rate=self.sampling_rate) | ||
| audio = AudioDecoder( | ||
| bytes, stream_index=self.stream_index, sample_rate=self.sampling_rate, num_channels=self.num_channels | ||
| ) | ||
| audio._hf_encoded = {"path": path, "bytes": bytes} | ||
| audio.metadata.path = path | ||
| return audio | ||
|
|
@@ -312,5 +322,8 @@ def encode_torchcodec_audio(audio: "AudioDecoder") -> dict: | |
|
|
||
| samples = audio.get_all_samples() | ||
| buffer = BytesIO() | ||
| AudioEncoder(samples.data.cpu(), sample_rate=samples.sample_rate).to_file_like(buffer, format="wav") | ||
| num_channels = samples.data.shape[0] | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This isn't strictly necessary but added it to be explicit |
||
| AudioEncoder(samples.data.cpu(), sample_rate=samples.sample_rate).to_file_like( | ||
| buffer, format="wav", num_channels=num_channels | ||
| ) | ||
| return {"bytes": buffer.getvalue(), "path": None} | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.