├── requirements.txt ├── watermarking.py ├── README.md ├── voice_clone.py ├── generator.py ├── models.py ├── LICENSE └── modal_voice_cloning.py /requirements.txt: -------------------------------------------------------------------------------- 1 | torch==2.4.0 2 | torchaudio==2.4.0 3 | tokenizers==0.21.0 4 | transformers==4.49.0 5 | huggingface_hub==0.28.1 6 | moshi==0.2.2 7 | torchtune==0.4.0 8 | torchao==0.9.0 9 | silentcipher @ git+https://github.com/SesameAILabs/silentcipher@master 10 | numpy 11 | -------------------------------------------------------------------------------- /watermarking.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | 3 | import silentcipher 4 | import torch 5 | import torchaudio 6 | 7 | # This watermark key is public, it is not secure. 8 | # If using CSM 1B in another application, use a new private key and keep it secret. 9 | CSM_1B_GH_WATERMARK = [212, 211, 146, 56, 201] 10 | 11 | 12 | def cli_check_audio() -> None: 13 | parser = argparse.ArgumentParser() 14 | parser.add_argument("--audio_path", type=str, required=True) 15 | args = parser.parse_args() 16 | 17 | check_audio_from_file(args.audio_path) 18 | 19 | 20 | def load_watermarker(device: str = "cuda") -> silentcipher.server.Model: 21 | model = silentcipher.get_model( 22 | model_type="44.1k", 23 | device=device, 24 | ) 25 | return model 26 | 27 | 28 | @torch.inference_mode() 29 | def watermark( 30 | watermarker: silentcipher.server.Model, 31 | audio_array: torch.Tensor, 32 | sample_rate: int, 33 | watermark_key: list[int], 34 | ) -> tuple[torch.Tensor, int]: 35 | audio_array_44khz = torchaudio.functional.resample(audio_array, orig_freq=sample_rate, new_freq=44100) 36 | encoded, _ = watermarker.encode_wav(audio_array_44khz, 44100, watermark_key, calc_sdr=False, message_sdr=36) 37 | 38 | output_sample_rate = min(44100, sample_rate) 39 | encoded = torchaudio.functional.resample(encoded, orig_freq=44100, new_freq=output_sample_rate) 40 | return encoded, output_sample_rate 41 | 42 | 43 | @torch.inference_mode() 44 | def verify( 45 | watermarker: silentcipher.server.Model, 46 | watermarked_audio: torch.Tensor, 47 | sample_rate: int, 48 | watermark_key: list[int], 49 | ) -> bool: 50 | watermarked_audio_44khz = torchaudio.functional.resample(watermarked_audio, orig_freq=sample_rate, new_freq=44100) 51 | result = watermarker.decode_wav(watermarked_audio_44khz, 44100, phase_shift_decoding=True) 52 | 53 | is_watermarked = result["status"] 54 | if is_watermarked: 55 | is_csm_watermarked = result["messages"][0] == watermark_key 56 | else: 57 | is_csm_watermarked = False 58 | 59 | return is_watermarked and is_csm_watermarked 60 | 61 | 62 | def check_audio_from_file(audio_path: str) -> None: 63 | watermarker = load_watermarker(device="cuda") 64 | 65 | audio_array, sample_rate = load_audio(audio_path) 66 | is_watermarked = verify(watermarker, audio_array, sample_rate, CSM_1B_GH_WATERMARK) 67 | 68 | outcome = "Watermarked" if is_watermarked else "Not watermarked" 69 | print(f"{outcome}: {audio_path}") 70 | 71 | 72 | def load_audio(audio_path: str) -> tuple[torch.Tensor, int]: 73 | audio_array, sample_rate = torchaudio.load(audio_path) 74 | audio_array = audio_array.mean(dim=0) 75 | return audio_array, int(sample_rate) 76 | 77 | 78 | if __name__ == "__main__": 79 | cli_check_audio() 80 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Voice Cloning with CSM-1B 2 | 3 | This repository contains tools to clone your voice using the Sesame CSM-1B model. It provides two methods for voice cloning: 4 | 1. Local execution on your own GPU 5 | 2. Cloud execution using Modal 6 | 7 | > **Note:** While this solution does capture some voice characteristics and provides a recognizable clone, it's not the best voice cloning solution available. The results are decent but not perfect. If you have ideas on how to improve the cloning quality, feel free to contribute! 8 | 9 | ## Prerequisites 10 | 11 | - Python 3.10+ 12 | - CUDA-compatible GPU (for local execution) 13 | - Hugging Face account with access to the CSM-1B model 14 | - Hugging Face API token 15 | 16 | ## Installation 17 | 18 | 1. Clone this repository: 19 | ```bash 20 | git clone https://github.com/isaiahbjork/csm-voice-cloning.git 21 | cd csm-voice-cloning 22 | ``` 23 | 24 | 2. Install the required dependencies: 25 | ```bash 26 | pip install -r requirements.txt 27 | ``` 28 | 29 | ## Setting Up Your Hugging Face Token 30 | 31 | You need to set your Hugging Face token to download the model. You can do this in two ways: 32 | 33 | 1. Set it as an environment variable: 34 | ```bash 35 | export HF_TOKEN="your_hugging_face_token" 36 | ``` 37 | 38 | 2. Or directly in the `voice_clone.py` file: 39 | ```python 40 | os.environ["HF_TOKEN"] = "your_hugging_face_token" 41 | ``` 42 | 43 | ## Accepting the Model on Hugging Face 44 | 45 | Before using the model, you need to accept the terms on Hugging Face: 46 | 47 | 1. Visit the [Sesame CSM-1B model page](https://huggingface.co/sesame/csm-1b) 48 | 2. Click on "Access repository" and accept the terms 49 | 3. Make sure you're logged in with the same account that your HF_TOKEN belongs to 50 | 51 | ## Preparing Your Voice Sample 52 | 53 | 1. Record a clear audio sample of your voice (2-3 minutes is recommended) 54 | 2. Save it as an MP3 or WAV file 55 | 3. Transcribe the audio using Whisper or another transcription tool to get the exact text 56 | 57 | ## Running Voice Cloning Locally 58 | 59 | 1. Edit the `voice_clone.py` file to set your parameters directly in the code: 60 | 61 | ```python 62 | # Set the path to your voice sample 63 | context_audio_path = "path/to/your/voice/sample.mp3" 64 | 65 | # Set the transcription of your voice sample 66 | # You need to use Whisper or another tool to transcribe your audio 67 | context_text = "The exact transcription of your voice sample..." 68 | 69 | # Set the text you want to synthesize 70 | text = "Text you want to synthesize with your voice." 71 | 72 | # Set the output filename 73 | output_filename = "output.wav" 74 | ``` 75 | 76 | 2. Run the script: 77 | ```bash 78 | python voice_clone.py 79 | ``` 80 | 81 | ## Running Voice Cloning on Modal 82 | 83 | Modal provides cloud GPU resources for faster processing: 84 | 85 | 1. Install Modal: 86 | ```bash 87 | pip install modal 88 | ``` 89 | 90 | 2. Set up Modal authentication: 91 | ```bash 92 | modal token new 93 | ``` 94 | 95 | 3. Edit the `modal_voice_cloning.py` file to set your parameters directly in the code: 96 | 97 | ```python 98 | # Set the path to your voice sample 99 | context_audio_path = "path/to/your/voice/sample.mp3" 100 | 101 | # Set the transcription of your voice sample 102 | # You need to use Whisper or another tool to transcribe your audio 103 | context_text = "The exact transcription of your voice sample..." 104 | 105 | # Set the text you want to synthesize 106 | text = "Text you want to synthesize with your voice." 107 | 108 | # Set the output filename 109 | output_filename = "output.wav" 110 | ``` 111 | 112 | 4. Run the Modal script: 113 | ```bash 114 | modal run modal_voice_cloning.py 115 | ``` 116 | 117 | ## Important Note on Model Sequence Length 118 | 119 | If you encounter tensor dimension errors, you may need to adjust the model's maximum sequence length in `models.py`. The default sequence length is 2048, which works for most cases, but if you're using longer audio samples, you might need to increase this value. 120 | 121 | Look for the `max_seq_len` parameter in the `llama3_2_1B()` and `llama3_2_100M()` functions in `models.py` and ensure they have the same value: 122 | 123 | ```python 124 | def llama3_2_1B(): 125 | return llama3_2.llama3_2( 126 | # other parameters... 127 | max_seq_len=2048, # Increase this value if needed 128 | # other parameters... 129 | ) 130 | ``` 131 | 132 | ## Example 133 | 134 | Using a 2 minute and 50 second audio sample works fine with the default settings. For longer samples, you may need to adjust the sequence length as mentioned above. 135 | 136 | ## Troubleshooting 137 | 138 | - **Tensor dimension errors**: Adjust the model sequence length as described above 139 | - **CUDA out of memory**: Try reducing the audio sample length or use a GPU with more memory 140 | - **Model download issues**: Ensure you've accepted the model terms on Hugging Face and your token is correct 141 | 142 | ## License 143 | 144 | This project uses the Sesame CSM-1B model, which is subject to its own license terms. Please refer to the [model page](https://huggingface.co/sesame/csm-1b) for details. -------------------------------------------------------------------------------- /voice_clone.py: -------------------------------------------------------------------------------- 1 | import os 2 | from pathlib import Path 3 | import os 4 | import torch 5 | import torchaudio 6 | from huggingface_hub import hf_hub_download 7 | import numpy as np 8 | import sys 9 | import io 10 | 11 | os.environ["HF_TOKEN"] = "" # Need to set token here 12 | 13 | def generate_speech_with_context( 14 | text="Hello, this is my voice speaking with context.", 15 | speaker_id=999, 16 | context_audio_path="audio.mp3", 17 | context_text="This is a sample of my voice for context.", 18 | output_filename="output_with_context.wav" 19 | ): 20 | # Import the generator 21 | from generator import load_csm_1b, Segment 22 | 23 | # Download the model if not already cached 24 | model_path = hf_hub_download(repo_id="sesame/csm-1b", filename="ckpt.pt") 25 | 26 | # Load the model 27 | generator = load_csm_1b(model_path, "cuda") 28 | print("Model loaded successfully!") 29 | print(f"Generating speech with context") 30 | print(f"Context audio: {context_audio_path}") 31 | print(f"Text: {text}") 32 | 33 | # Load context audio 34 | context_audio, sr = torchaudio.load(context_audio_path) 35 | context_audio = context_audio.mean(dim=0) # Convert to mono 36 | 37 | # Resample if needed 38 | if sr != generator.sample_rate: 39 | context_audio = torchaudio.functional.resample( 40 | context_audio, orig_freq=sr, new_freq=generator.sample_rate 41 | ) 42 | 43 | # Normalize audio volume for better consistency 44 | context_audio = context_audio / (torch.max(torch.abs(context_audio)) + 1e-8) 45 | 46 | # Improved silence removal that handles internal silences 47 | def remove_silence(audio, threshold=0.01, min_silence_duration=0.2, sample_rate=24000): 48 | # Convert to numpy for easier processing 49 | audio_np = audio.cpu().numpy() 50 | 51 | # Calculate energy 52 | energy = np.abs(audio_np) 53 | 54 | # Find regions above threshold (speech) 55 | is_speech = energy > threshold 56 | 57 | # Convert min_silence_duration to samples 58 | min_silence_samples = int(min_silence_duration * sample_rate) 59 | 60 | # Find speech segments 61 | speech_segments = [] 62 | in_speech = False 63 | speech_start = 0 64 | 65 | for i in range(len(is_speech)): 66 | if is_speech[i] and not in_speech: 67 | # Start of speech segment 68 | in_speech = True 69 | speech_start = i 70 | elif not is_speech[i] and in_speech: 71 | # Potential end of speech segment 72 | # Only end if silence is long enough 73 | silence_count = 0 74 | for j in range(i, min(len(is_speech), i + min_silence_samples)): 75 | if not is_speech[j]: 76 | silence_count += 1 77 | else: 78 | break 79 | 80 | if silence_count >= min_silence_samples: 81 | # End of speech segment 82 | in_speech = False 83 | speech_segments.append((speech_start, i)) 84 | 85 | # Handle case where audio ends during speech 86 | if in_speech: 87 | speech_segments.append((speech_start, len(is_speech))) 88 | 89 | # Concatenate speech segments 90 | if not speech_segments: 91 | return audio # Return original if no speech found 92 | 93 | # Add small buffer around segments 94 | buffer_samples = int(0.05 * sample_rate) # 50ms buffer 95 | processed_segments = [] 96 | 97 | for start, end in speech_segments: 98 | buffered_start = max(0, start - buffer_samples) 99 | buffered_end = min(len(audio_np), end + buffer_samples) 100 | processed_segments.append(audio_np[buffered_start:buffered_end]) 101 | 102 | # Concatenate all segments 103 | processed_audio = np.concatenate(processed_segments) 104 | 105 | return torch.tensor(processed_audio, device=audio.device) 106 | 107 | # Apply improved silence removal with slightly more aggressive settings for longer files 108 | audio_duration_sec = len(context_audio) / generator.sample_rate 109 | print(f"Original audio duration: {audio_duration_sec:.2f} seconds") 110 | 111 | # Adjust threshold based on audio length 112 | silence_threshold = 0.015 113 | if audio_duration_sec > 10: 114 | # For longer files, be more aggressive with silence removal 115 | silence_threshold = 0.02 116 | 117 | context_audio = remove_silence(context_audio, threshold=silence_threshold, 118 | min_silence_duration=0.15, 119 | sample_rate=generator.sample_rate) 120 | 121 | processed_duration_sec = len(context_audio) / generator.sample_rate 122 | print(f"Processed audio duration: {processed_duration_sec:.2f} seconds") 123 | 124 | # Use the entire audio file for better voice cloning 125 | print(f"Using the entire processed audio file ({processed_duration_sec:.2f} seconds) for voice cloning") 126 | 127 | # Create context segment 128 | context_segment = Segment( 129 | text=context_text, 130 | speaker=speaker_id, 131 | audio=context_audio 132 | ) 133 | 134 | # Preprocess text for better pronunciation 135 | # Add punctuation if missing to help with phrasing 136 | if not any(p in text for p in ['.', ',', '!', '?']): 137 | text = text + '.' 138 | 139 | # Generate audio with context 140 | audio = generator.generate( 141 | text=text, 142 | speaker=speaker_id, 143 | context=[context_segment], 144 | max_audio_length_ms=15_000, # Adjusted based on your feedback 145 | temperature=0.6, # Lower temperature for more accurate pronunciation 146 | topk=20, # More focused sampling for clearer speech 147 | max_seq_len=2048 # Increase max seq len for longer audio but might cause issues so you might need to edit in the models.py as well 148 | ) 149 | 150 | # Save the audio to the output directory 151 | torchaudio.save(output_filename, audio.unsqueeze(0).cpu(), generator.sample_rate) 152 | print(f"Speech with context generated successfully! Saved to {output_filename}") 153 | return 154 | 155 | def main(): 156 | context_audio_path = "audio.mp3" 157 | 158 | context_text = "" # Use whisper to transcribe the audio 159 | 160 | # Generate speech using the approach that worked best 161 | print("Generating speech with the successful approach...") 162 | generate_speech_with_context( 163 | text="My name is Zay. I am speaking clearly. This is my voice.", 164 | speaker_id=999, 165 | context_audio_path=context_audio_path, 166 | context_text=context_text, 167 | output_filename="cloned_voice.wav" 168 | ) 169 | 170 | if __name__ == "__main__": 171 | main() -------------------------------------------------------------------------------- /generator.py: -------------------------------------------------------------------------------- 1 | from dataclasses import dataclass 2 | from typing import List, Tuple 3 | 4 | import torch 5 | import torchaudio 6 | from huggingface_hub import hf_hub_download 7 | from models import Model, ModelArgs 8 | from moshi.models import loaders 9 | from tokenizers.processors import TemplateProcessing 10 | from transformers import AutoTokenizer 11 | from watermarking import CSM_1B_GH_WATERMARK, load_watermarker, watermark 12 | 13 | 14 | @dataclass 15 | class Segment: 16 | speaker: int 17 | text: str 18 | # (num_samples,), sample_rate = 24_000 19 | audio: torch.Tensor 20 | 21 | 22 | def load_llama3_tokenizer(): 23 | """ 24 | https://github.com/huggingface/transformers/issues/22794#issuecomment-2092623992 25 | """ 26 | tokenizer_name = "meta-llama/Llama-3.2-1B" 27 | tokenizer = AutoTokenizer.from_pretrained(tokenizer_name) 28 | bos = tokenizer.bos_token 29 | eos = tokenizer.eos_token 30 | tokenizer._tokenizer.post_processor = TemplateProcessing( 31 | single=f"{bos}:0 $A:0 {eos}:0", 32 | pair=f"{bos}:0 $A:0 {eos}:0 {bos}:1 $B:1 {eos}:1", 33 | special_tokens=[(f"{bos}", tokenizer.bos_token_id), (f"{eos}", tokenizer.eos_token_id)], 34 | ) 35 | 36 | return tokenizer 37 | 38 | 39 | class Generator: 40 | def __init__( 41 | self, 42 | model: Model, 43 | ): 44 | self._model = model 45 | self._model.setup_caches(1) 46 | 47 | self._text_tokenizer = load_llama3_tokenizer() 48 | 49 | device = next(model.parameters()).device 50 | mimi_weight = hf_hub_download(loaders.DEFAULT_REPO, loaders.MIMI_NAME) 51 | mimi = loaders.get_mimi(mimi_weight, device=device) 52 | mimi.set_num_codebooks(32) 53 | self._audio_tokenizer = mimi 54 | 55 | self._watermarker = load_watermarker(device=device) 56 | 57 | self.sample_rate = mimi.sample_rate 58 | self.device = device 59 | 60 | def _tokenize_text_segment(self, text: str, speaker: int) -> Tuple[torch.Tensor, torch.Tensor]: 61 | frame_tokens = [] 62 | frame_masks = [] 63 | 64 | text_tokens = self._text_tokenizer.encode(f"[{speaker}]{text}") 65 | text_frame = torch.zeros(len(text_tokens), 33).long() 66 | text_frame_mask = torch.zeros(len(text_tokens), 33).bool() 67 | text_frame[:, -1] = torch.tensor(text_tokens) 68 | text_frame_mask[:, -1] = True 69 | 70 | frame_tokens.append(text_frame.to(self.device)) 71 | frame_masks.append(text_frame_mask.to(self.device)) 72 | 73 | return torch.cat(frame_tokens, dim=0), torch.cat(frame_masks, dim=0) 74 | 75 | def _tokenize_audio(self, audio: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: 76 | frame_tokens = [] 77 | frame_masks = [] 78 | 79 | # (K, T) 80 | audio = audio.to(self.device) 81 | audio_tokens = self._audio_tokenizer.encode(audio.unsqueeze(0).unsqueeze(0))[0] 82 | # add EOS frame 83 | eos_frame = torch.zeros(audio_tokens.size(0), 1).to(self.device) 84 | audio_tokens = torch.cat([audio_tokens, eos_frame], dim=1) 85 | 86 | audio_frame = torch.zeros(audio_tokens.size(1), 33).long().to(self.device) 87 | audio_frame_mask = torch.zeros(audio_tokens.size(1), 33).bool().to(self.device) 88 | audio_frame[:, :-1] = audio_tokens.transpose(0, 1) 89 | audio_frame_mask[:, :-1] = True 90 | 91 | frame_tokens.append(audio_frame) 92 | frame_masks.append(audio_frame_mask) 93 | 94 | return torch.cat(frame_tokens, dim=0), torch.cat(frame_masks, dim=0) 95 | 96 | def _tokenize_segment(self, segment: Segment) -> Tuple[torch.Tensor, torch.Tensor]: 97 | """ 98 | Returns: 99 | (seq_len, 33), (seq_len, 33) 100 | """ 101 | text_tokens, text_masks = self._tokenize_text_segment(segment.text, segment.speaker) 102 | audio_tokens, audio_masks = self._tokenize_audio(segment.audio) 103 | 104 | return torch.cat([text_tokens, audio_tokens], dim=0), torch.cat([text_masks, audio_masks], dim=0) 105 | 106 | @torch.inference_mode() 107 | def generate( 108 | self, 109 | text: str, 110 | speaker: int, 111 | context: List[Segment], 112 | max_audio_length_ms: float = 90_000, 113 | temperature: float = 0.9, 114 | topk: int = 50, 115 | max_seq_len: int = 2048, 116 | ) -> torch.Tensor: 117 | self._model.reset_caches() 118 | 119 | max_audio_frames = int(max_audio_length_ms / 80) 120 | tokens, tokens_mask = [], [] 121 | for segment in context: 122 | segment_tokens, segment_tokens_mask = self._tokenize_segment(segment) 123 | tokens.append(segment_tokens) 124 | tokens_mask.append(segment_tokens_mask) 125 | 126 | gen_segment_tokens, gen_segment_tokens_mask = self._tokenize_text_segment(text, speaker) 127 | tokens.append(gen_segment_tokens) 128 | tokens_mask.append(gen_segment_tokens_mask) 129 | 130 | prompt_tokens = torch.cat(tokens, dim=0).long().to(self.device) 131 | prompt_tokens_mask = torch.cat(tokens_mask, dim=0).bool().to(self.device) 132 | 133 | samples = [] 134 | curr_tokens = prompt_tokens.unsqueeze(0) 135 | curr_tokens_mask = prompt_tokens_mask.unsqueeze(0) 136 | curr_pos = torch.arange(0, prompt_tokens.size(0)).unsqueeze(0).long().to(self.device) 137 | 138 | max_seq_len = max_seq_len - max_audio_frames 139 | if curr_tokens.size(1) >= max_seq_len: 140 | raise ValueError(f"Inputs too long, must be below max_seq_len - max_audio_frames: {max_seq_len}") 141 | 142 | for _ in range(max_audio_frames): 143 | sample = self._model.generate_frame(curr_tokens, curr_tokens_mask, curr_pos, temperature, topk) 144 | if torch.all(sample == 0): 145 | break # eos 146 | 147 | samples.append(sample) 148 | 149 | curr_tokens = torch.cat([sample, torch.zeros(1, 1).long().to(self.device)], dim=1).unsqueeze(1) 150 | curr_tokens_mask = torch.cat( 151 | [torch.ones_like(sample).bool(), torch.zeros(1, 1).bool().to(self.device)], dim=1 152 | ).unsqueeze(1) 153 | curr_pos = curr_pos[:, -1:] + 1 154 | 155 | audio = self._audio_tokenizer.decode(torch.stack(samples).permute(1, 2, 0)).squeeze(0).squeeze(0) 156 | 157 | # This applies an imperceptible watermark to identify audio as AI-generated. 158 | # Watermarking ensures transparency, dissuades misuse, and enables traceability. 159 | # Please be a responsible AI citizen and keep the watermarking in place. 160 | # If using CSM 1B in another application, use your own private key and keep it secret. 161 | audio, wm_sample_rate = watermark(self._watermarker, audio, self.sample_rate, CSM_1B_GH_WATERMARK) 162 | audio = torchaudio.functional.resample(audio, orig_freq=wm_sample_rate, new_freq=self.sample_rate) 163 | 164 | return audio 165 | 166 | 167 | def load_csm_1b(ckpt_path: str = "ckpt.pt", device: str = "cuda") -> Generator: 168 | model_args = ModelArgs( 169 | backbone_flavor="llama-1B", 170 | decoder_flavor="llama-100M", 171 | text_vocab_size=128256, 172 | audio_vocab_size=2051, 173 | audio_num_codebooks=32, 174 | ) 175 | model = Model(model_args).to(device=device, dtype=torch.bfloat16) 176 | state_dict = torch.load(ckpt_path) 177 | model.load_state_dict(state_dict) 178 | 179 | generator = Generator(model) 180 | return generator 181 | -------------------------------------------------------------------------------- /models.py: -------------------------------------------------------------------------------- 1 | from dataclasses import dataclass 2 | 3 | import torch 4 | import torch.nn as nn 5 | import torchtune 6 | from torchtune.models import llama3_2 7 | 8 | 9 | def llama3_2_1B() -> torchtune.modules.transformer.TransformerDecoder: 10 | return llama3_2.llama3_2( 11 | vocab_size=128_256, 12 | num_layers=16, 13 | num_heads=32, 14 | num_kv_heads=8, 15 | embed_dim=2048, 16 | max_seq_len=2048, 17 | intermediate_dim=8192, 18 | attn_dropout=0.0, 19 | norm_eps=1e-5, 20 | rope_base=500_000, 21 | scale_factor=32, 22 | ) 23 | 24 | 25 | def llama3_2_100M() -> torchtune.modules.transformer.TransformerDecoder: 26 | return llama3_2.llama3_2( 27 | vocab_size=128_256, 28 | num_layers=4, 29 | num_heads=8, 30 | num_kv_heads=2, 31 | embed_dim=1024, 32 | max_seq_len=2048, 33 | intermediate_dim=8192, 34 | attn_dropout=0.0, 35 | norm_eps=1e-5, 36 | rope_base=500_000, 37 | scale_factor=32, 38 | ) 39 | 40 | 41 | FLAVORS = { 42 | "llama-1B": llama3_2_1B, 43 | "llama-100M": llama3_2_100M, 44 | } 45 | 46 | 47 | def _prepare_transformer(model): 48 | embed_dim = model.tok_embeddings.embedding_dim 49 | model.tok_embeddings = nn.Identity() 50 | model.output = nn.Identity() 51 | return model, embed_dim 52 | 53 | 54 | def _create_causal_mask(seq_len: int, device: torch.device): 55 | return torch.tril(torch.ones(seq_len, seq_len, dtype=torch.bool, device=device)) 56 | 57 | 58 | def _index_causal_mask(mask: torch.Tensor, input_pos: torch.Tensor): 59 | """ 60 | Args: 61 | mask: (max_seq_len, max_seq_len) 62 | input_pos: (batch_size, seq_len) 63 | 64 | Returns: 65 | (batch_size, seq_len, max_seq_len) 66 | """ 67 | r = mask[input_pos, :] 68 | return r 69 | 70 | 71 | def _multinomial_sample_one_no_sync(probs): # Does multinomial sampling without a cuda synchronization 72 | q = torch.empty_like(probs).exponential_(1) 73 | return torch.argmax(probs / q, dim=-1, keepdim=True).to(dtype=torch.int) 74 | 75 | 76 | def sample_topk(logits: torch.Tensor, topk: int, temperature: float): 77 | logits = logits / temperature 78 | 79 | filter_value: float = -float("Inf") 80 | indices_to_remove = logits < torch.topk(logits, topk)[0][..., -1, None] 81 | scores_processed = logits.masked_fill(indices_to_remove, filter_value) 82 | scores_processed = torch.nn.functional.log_softmax(scores_processed, dim=-1) 83 | probs = torch.nn.functional.softmax(scores_processed, dim=-1) 84 | 85 | sample_token = _multinomial_sample_one_no_sync(probs) 86 | return sample_token 87 | 88 | 89 | @dataclass 90 | class ModelArgs: 91 | backbone_flavor: str 92 | decoder_flavor: str 93 | text_vocab_size: int 94 | audio_vocab_size: int 95 | audio_num_codebooks: int 96 | 97 | 98 | class Model(nn.Module): 99 | def __init__(self, args: ModelArgs): 100 | super().__init__() 101 | self.args = args 102 | 103 | self.backbone, backbone_dim = _prepare_transformer(FLAVORS[args.backbone_flavor]()) 104 | self.decoder, decoder_dim = _prepare_transformer(FLAVORS[args.decoder_flavor]()) 105 | 106 | self.text_embeddings = nn.Embedding(args.text_vocab_size, backbone_dim) 107 | self.audio_embeddings = nn.Embedding(args.audio_vocab_size * args.audio_num_codebooks, backbone_dim) 108 | 109 | self.projection = nn.Linear(backbone_dim, decoder_dim, bias=False) 110 | self.codebook0_head = nn.Linear(backbone_dim, args.audio_vocab_size, bias=False) 111 | self.audio_head = nn.Parameter(torch.empty(args.audio_num_codebooks - 1, decoder_dim, args.audio_vocab_size)) 112 | 113 | def setup_caches(self, max_batch_size: int) -> torch.Tensor: 114 | """Setup KV caches and return a causal mask.""" 115 | dtype = next(self.parameters()).dtype 116 | device = next(self.parameters()).device 117 | 118 | with device: 119 | self.backbone.setup_caches(max_batch_size, dtype) 120 | self.decoder.setup_caches(max_batch_size, dtype, decoder_max_seq_len=self.args.audio_num_codebooks) 121 | 122 | self.register_buffer("backbone_causal_mask", _create_causal_mask(self.backbone.max_seq_len, device)) 123 | self.register_buffer("decoder_causal_mask", _create_causal_mask(self.args.audio_num_codebooks, device)) 124 | 125 | def generate_frame( 126 | self, 127 | tokens: torch.Tensor, 128 | tokens_mask: torch.Tensor, 129 | input_pos: torch.Tensor, 130 | temperature: float, 131 | topk: int, 132 | ) -> torch.Tensor: 133 | """ 134 | Args: 135 | tokens: (batch_size, seq_len, audio_num_codebooks+1) 136 | tokens_mask: (batch_size, seq_len, audio_num_codebooks+1) 137 | input_pos: (batch_size, seq_len) positions for each token 138 | mask: (batch_size, seq_len, max_seq_len 139 | 140 | Returns: 141 | (batch_size, audio_num_codebooks) sampled tokens 142 | """ 143 | dtype = next(self.parameters()).dtype 144 | b, s, _ = tokens.size() 145 | 146 | assert self.backbone.caches_are_enabled(), "backbone caches are not enabled" 147 | curr_backbone_mask = _index_causal_mask(self.backbone_causal_mask, input_pos) 148 | embeds = self._embed_tokens(tokens) 149 | masked_embeds = embeds * tokens_mask.unsqueeze(-1) 150 | h = masked_embeds.sum(dim=2) 151 | h = self.backbone(h, input_pos=input_pos, mask=curr_backbone_mask).to(dtype=dtype) 152 | 153 | last_h = h[:, -1, :] 154 | c0_logits = self.codebook0_head(last_h) 155 | c0_sample = sample_topk(c0_logits, topk, temperature) 156 | c0_embed = self._embed_audio(0, c0_sample) 157 | 158 | curr_h = torch.cat([last_h.unsqueeze(1), c0_embed], dim=1) 159 | curr_sample = c0_sample.clone() 160 | curr_pos = torch.arange(0, curr_h.size(1), device=curr_h.device).unsqueeze(0).repeat(curr_h.size(0), 1) 161 | 162 | # Decoder caches must be reset every frame. 163 | self.decoder.reset_caches() 164 | for i in range(1, self.args.audio_num_codebooks): 165 | curr_decoder_mask = _index_causal_mask(self.decoder_causal_mask, curr_pos) 166 | decoder_h = self.decoder(self.projection(curr_h), input_pos=curr_pos, mask=curr_decoder_mask).to( 167 | dtype=dtype 168 | ) 169 | ci_logits = torch.mm(decoder_h[:, -1, :], self.audio_head[i - 1]) 170 | ci_sample = sample_topk(ci_logits, topk, temperature) 171 | ci_embed = self._embed_audio(i, ci_sample) 172 | 173 | curr_h = ci_embed 174 | curr_sample = torch.cat([curr_sample, ci_sample], dim=1) 175 | curr_pos = curr_pos[:, -1:] + 1 176 | 177 | return curr_sample 178 | 179 | def reset_caches(self): 180 | self.backbone.reset_caches() 181 | self.decoder.reset_caches() 182 | 183 | def _embed_audio(self, codebook: int, tokens: torch.Tensor) -> torch.Tensor: 184 | return self.audio_embeddings(tokens + codebook * self.args.audio_vocab_size) 185 | 186 | def _embed_tokens(self, tokens: torch.Tensor) -> torch.Tensor: 187 | text_embeds = self.text_embeddings(tokens[:, :, -1]).unsqueeze(-2) 188 | 189 | audio_tokens = tokens[:, :, :-1] + ( 190 | self.args.audio_vocab_size * torch.arange(self.args.audio_num_codebooks, device=tokens.device) 191 | ) 192 | audio_embeds = self.audio_embeddings(audio_tokens.view(-1)).reshape( 193 | tokens.size(0), tokens.size(1), self.args.audio_num_codebooks, -1 194 | ) 195 | 196 | return torch.cat([audio_embeds, text_embeds], dim=-2) 197 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 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 [yyyy] [name of copyright owner] 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. -------------------------------------------------------------------------------- /modal_voice_cloning.py: -------------------------------------------------------------------------------- 1 | import os 2 | from pathlib import Path 3 | import modal 4 | 5 | # Define the Modal app 6 | app = modal.App("csm-voice-cloning") 7 | 8 | # Set up the image with required dependencies 9 | image = ( 10 | modal.Image.debian_slim(python_version="3.10") 11 | .apt_install("git", "ffmpeg", "libsox-dev", "libsox-fmt-all", "sox") # Added sox libraries 12 | .pip_install( 13 | "torch==2.4.0", 14 | "torchaudio==2.4.0", 15 | "tokenizers==0.21.0", 16 | "transformers==4.49.0", 17 | "huggingface_hub==0.28.1", 18 | "moshi==0.2.2", 19 | "torchtune==0.4.0", 20 | "torchao==0.9.0", 21 | "silentcipher @ git+https://github.com/SesameAILabs/silentcipher@master", 22 | "numpy", 23 | ).add_local_file("/Users/zay/csm/generator.py", "/root/generator.py") 24 | .add_local_file("/Users/zay/csm/models.py", "/root/models.py") 25 | .add_local_file("/Users/zay/csm/watermarking.py", "/root/watermarking.py") 26 | .add_local_file("/Users/zay/csm/audio.mp3", "/root/audio.mp3") 27 | ) 28 | 29 | # Create a volume to cache the model weights 30 | cache_dir = "/cache" 31 | model_cache = modal.Volume.from_name( 32 | "csm-model-cache", create_if_missing=True 33 | ) 34 | 35 | # Create a volume to store voice outputs 36 | voice_output_dir = "/voice_output" 37 | voice_output_volume = modal.Volume.from_name( 38 | "csm-voice-output", create_if_missing=True 39 | ) 40 | 41 | # Function to generate speech with a specific speaker ID 42 | @app.function(gpu="l40s", image=image, volumes={cache_dir: model_cache, voice_output_dir: voice_output_volume}) 43 | def generate_speech_with_speaker( 44 | text="Hello, this is my voice speaking.", 45 | speaker_id=0, 46 | output_filename="output.wav" 47 | ): 48 | import os 49 | import torch 50 | import torchaudio 51 | from huggingface_hub import hf_hub_download 52 | 53 | # Set HF cache directory to our persistent volume 54 | os.environ["HF_HOME"] = cache_dir 55 | os.environ["HF_TOKEN"] = "" 56 | 57 | # Import the generator 58 | from generator import load_csm_1b, Segment 59 | 60 | # Download the model if not already cached 61 | model_path = hf_hub_download(repo_id="sesame/csm-1b", filename="ckpt.pt") 62 | 63 | # Load the model 64 | generator = load_csm_1b(model_path, "cuda") 65 | print("Model loaded successfully!") 66 | 67 | # Create output directory 68 | os.makedirs(voice_output_dir, exist_ok=True) 69 | output_path = os.path.join(voice_output_dir, output_filename) 70 | 71 | print(f"Generating speech with speaker ID {speaker_id}") 72 | print(f"Text: {text}") 73 | 74 | # Generate audio 75 | audio = generator.generate( 76 | text=text, 77 | speaker=speaker_id, 78 | context=[], 79 | max_audio_length_ms=30_000, # Increased from 10_000 to allow for longer utterances 80 | temperature=0.7, # Reduced temperature for more accurate pronunciation 81 | topk=30, # Reduced from default 50 to make output more focused 82 | max_seq_len=2048 # Increase max seq len for longer audio but might cause issues so you might need to edit in the models.py as well 83 | ) 84 | 85 | # Save the audio 86 | torchaudio.save(output_path, audio.unsqueeze(0).cpu(), generator.sample_rate) 87 | 88 | # Also save to a temporary file for returning 89 | temp_output_path = "/tmp/output.wav" 90 | torchaudio.save(temp_output_path, audio.unsqueeze(0).cpu(), generator.sample_rate) 91 | 92 | # Read the file and return the bytes 93 | with open(temp_output_path, "rb") as f: 94 | audio_bytes = f.read() 95 | 96 | print(f"Speech generated successfully! Saved to {output_path}") 97 | return audio_bytes 98 | 99 | # Function to generate speech with context from a previous audio sample 100 | @app.function(gpu="l40s", image=image, volumes={cache_dir: model_cache, voice_output_dir: voice_output_volume}) 101 | def generate_speech_with_context( 102 | text="Hello, this is my voice speaking with context.", 103 | speaker_id=0, 104 | context_audio_path="/root/zay-1.mp3", 105 | context_text="This is a sample of my voice for context.", 106 | output_filename="output_with_context.wav" 107 | ): 108 | import os 109 | import torch 110 | import torchaudio 111 | from huggingface_hub import hf_hub_download 112 | import numpy as np 113 | 114 | # Set HF cache directory to our persistent volume 115 | os.environ["HF_HOME"] = cache_dir 116 | os.environ["HF_TOKEN"] = "" # Need to set token here 117 | 118 | # Import the generator 119 | from generator import load_csm_1b, Segment 120 | 121 | # Download the model if not already cached 122 | model_path = hf_hub_download(repo_id="sesame/csm-1b", filename="ckpt.pt") 123 | 124 | # Load the model 125 | generator = load_csm_1b(model_path, "cuda") 126 | print("Model loaded successfully!") 127 | 128 | # Create output directory 129 | os.makedirs(voice_output_dir, exist_ok=True) 130 | output_path = os.path.join(voice_output_dir, output_filename) 131 | 132 | print(f"Generating speech with context") 133 | print(f"Context audio: {context_audio_path}") 134 | print(f"Text: {text}") 135 | 136 | # Load context audio 137 | context_audio, sr = torchaudio.load(context_audio_path) 138 | context_audio = context_audio.mean(dim=0) # Convert to mono 139 | 140 | # Resample if needed 141 | if sr != generator.sample_rate: 142 | context_audio = torchaudio.functional.resample( 143 | context_audio, orig_freq=sr, new_freq=generator.sample_rate 144 | ) 145 | 146 | # Normalize audio volume for better consistency 147 | context_audio = context_audio / (torch.max(torch.abs(context_audio)) + 1e-8) 148 | 149 | # Improved silence removal that handles internal silences 150 | def remove_silence(audio, threshold=0.01, min_silence_duration=0.2, sample_rate=24000): 151 | # Convert to numpy for easier processing 152 | audio_np = audio.cpu().numpy() 153 | 154 | # Calculate energy 155 | energy = np.abs(audio_np) 156 | 157 | # Find regions above threshold (speech) 158 | is_speech = energy > threshold 159 | 160 | # Convert min_silence_duration to samples 161 | min_silence_samples = int(min_silence_duration * sample_rate) 162 | 163 | # Find speech segments 164 | speech_segments = [] 165 | in_speech = False 166 | speech_start = 0 167 | 168 | for i in range(len(is_speech)): 169 | if is_speech[i] and not in_speech: 170 | # Start of speech segment 171 | in_speech = True 172 | speech_start = i 173 | elif not is_speech[i] and in_speech: 174 | # Potential end of speech segment 175 | # Only end if silence is long enough 176 | silence_count = 0 177 | for j in range(i, min(len(is_speech), i + min_silence_samples)): 178 | if not is_speech[j]: 179 | silence_count += 1 180 | else: 181 | break 182 | 183 | if silence_count >= min_silence_samples: 184 | # End of speech segment 185 | in_speech = False 186 | speech_segments.append((speech_start, i)) 187 | 188 | # Handle case where audio ends during speech 189 | if in_speech: 190 | speech_segments.append((speech_start, len(is_speech))) 191 | 192 | # Concatenate speech segments 193 | if not speech_segments: 194 | return audio # Return original if no speech found 195 | 196 | # Add small buffer around segments 197 | buffer_samples = int(0.05 * sample_rate) # 50ms buffer 198 | processed_segments = [] 199 | 200 | for start, end in speech_segments: 201 | buffered_start = max(0, start - buffer_samples) 202 | buffered_end = min(len(audio_np), end + buffer_samples) 203 | processed_segments.append(audio_np[buffered_start:buffered_end]) 204 | 205 | # Concatenate all segments 206 | processed_audio = np.concatenate(processed_segments) 207 | 208 | return torch.tensor(processed_audio, device=audio.device) 209 | 210 | # Apply improved silence removal with slightly more aggressive settings for longer files 211 | audio_duration_sec = len(context_audio) / generator.sample_rate 212 | print(f"Original audio duration: {audio_duration_sec:.2f} seconds") 213 | 214 | # Adjust threshold based on audio length 215 | silence_threshold = 0.015 216 | if audio_duration_sec > 10: 217 | # For longer files, be more aggressive with silence removal 218 | silence_threshold = 0.02 219 | 220 | context_audio = remove_silence(context_audio, threshold=silence_threshold, 221 | min_silence_duration=0.15, 222 | sample_rate=generator.sample_rate) 223 | 224 | processed_duration_sec = len(context_audio) / generator.sample_rate 225 | print(f"Processed audio duration: {processed_duration_sec:.2f} seconds") 226 | 227 | # Use the entire audio file for better voice cloning 228 | print(f"Using the entire processed audio file ({processed_duration_sec:.2f} seconds) for voice cloning") 229 | 230 | # Create context segment 231 | context_segment = Segment( 232 | text=context_text, 233 | speaker=speaker_id, 234 | audio=context_audio 235 | ) 236 | 237 | # Preprocess text for better pronunciation 238 | # Add punctuation if missing to help with phrasing 239 | if not any(p in text for p in ['.', ',', '!', '?']): 240 | text = text + '.' 241 | 242 | # Generate audio with context 243 | audio = generator.generate( 244 | text=text, 245 | speaker=speaker_id, 246 | context=[context_segment], 247 | max_audio_length_ms=15_000, # Adjusted based on your feedback 248 | temperature=0.6, # Lower temperature for more accurate pronunciation 249 | topk=20, # More focused sampling for clearer speech 250 | ) 251 | 252 | # Save the audio 253 | torchaudio.save(output_path, audio.unsqueeze(0).cpu(), generator.sample_rate) 254 | 255 | # Also save to a temporary file for returning 256 | temp_output_path = "/tmp/output_with_context.wav" 257 | torchaudio.save(temp_output_path, audio.unsqueeze(0).cpu(), generator.sample_rate) 258 | 259 | # Read the file and return the bytes 260 | with open(temp_output_path, "rb") as f: 261 | audio_bytes = f.read() 262 | 263 | print(f"Speech with context generated successfully! Saved to {output_path}") 264 | return audio_bytes 265 | 266 | # Main entrypoint for the app 267 | @app.local_entrypoint() 268 | def main(): 269 | import sys 270 | import os 271 | 272 | # Check if a custom audio file is provided as an argument 273 | if len(sys.argv) > 1 and os.path.exists(sys.argv[1]): 274 | context_audio_path = sys.argv[1] 275 | print(f"Using custom audio file: {context_audio_path}") 276 | else: 277 | context_audio_path = "/root/audio.mp3" 278 | print(f"Using default audio file: {context_audio_path}") 279 | 280 | # Define the context text - try to match what's in your sample 281 | context_text = "" # Use whisper to transcribe the audio 282 | 283 | # Generate speech using the approach that worked best 284 | print("Generating speech with the successful approach...") 285 | audio_bytes = generate_speech_with_context.remote( 286 | text="My name is Zay. I am speaking clearly. This is my voice. Bro what", 287 | speaker_id=999, 288 | context_audio_path=context_audio_path, 289 | context_text=context_text, 290 | output_filename="cloned_voice.wav" 291 | ) 292 | 293 | # Save the output locally 294 | output_file = "cloned_voice.wav" 295 | with open(output_file, "wb") as f: 296 | f.write(audio_bytes) 297 | 298 | print(f"Cloned voice audio saved to {output_file}") --------------------------------------------------------------------------------