MohamedRashad commited on
Commit
b35040f
·
1 Parent(s): 1810d80

Add requirements.txt and .gitignore files

Browse files
Files changed (3) hide show
  1. .gitignore +177 -0
  2. app.py +260 -0
  3. requirements.txt +2 -0
.gitignore ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Created by https://www.toptal.com/developers/gitignore/api/python
2
+ # Edit at https://www.toptal.com/developers/gitignore?templates=python
3
+
4
+ ### Python ###
5
+ # Byte-compiled / optimized / DLL files
6
+ __pycache__/
7
+ *.py[cod]
8
+ *$py.class
9
+
10
+ # C extensions
11
+ *.so
12
+
13
+ # Distribution / packaging
14
+ .Python
15
+ build/
16
+ develop-eggs/
17
+ dist/
18
+ downloads/
19
+ eggs/
20
+ .eggs/
21
+ lib/
22
+ lib64/
23
+ parts/
24
+ sdist/
25
+ var/
26
+ wheels/
27
+ share/python-wheels/
28
+ *.egg-info/
29
+ .installed.cfg
30
+ *.egg
31
+ MANIFEST
32
+
33
+ # PyInstaller
34
+ # Usually these files are written by a python script from a template
35
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
36
+ *.manifest
37
+ *.spec
38
+
39
+ # Installer logs
40
+ pip-log.txt
41
+ pip-delete-this-directory.txt
42
+
43
+ # Unit test / coverage reports
44
+ htmlcov/
45
+ .tox/
46
+ .nox/
47
+ .coverage
48
+ .coverage.*
49
+ .cache
50
+ nosetests.xml
51
+ coverage.xml
52
+ *.cover
53
+ *.py,cover
54
+ .hypothesis/
55
+ .pytest_cache/
56
+ cover/
57
+
58
+ # Translations
59
+ *.mo
60
+ *.pot
61
+
62
+ # Django stuff:
63
+ *.log
64
+ local_settings.py
65
+ db.sqlite3
66
+ db.sqlite3-journal
67
+
68
+ # Flask stuff:
69
+ instance/
70
+ .webassets-cache
71
+
72
+ # Scrapy stuff:
73
+ .scrapy
74
+
75
+ # Sphinx documentation
76
+ docs/_build/
77
+
78
+ # PyBuilder
79
+ .pybuilder/
80
+ target/
81
+
82
+ # Jupyter Notebook
83
+ .ipynb_checkpoints
84
+
85
+ # IPython
86
+ profile_default/
87
+ ipython_config.py
88
+
89
+ # pyenv
90
+ # For a library or package, you might want to ignore these files since the code is
91
+ # intended to run in multiple environments; otherwise, check them in:
92
+ # .python-version
93
+
94
+ # pipenv
95
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
96
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
97
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
98
+ # install all needed dependencies.
99
+ #Pipfile.lock
100
+
101
+ # poetry
102
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
103
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
104
+ # commonly ignored for libraries.
105
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
106
+ #poetry.lock
107
+
108
+ # pdm
109
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
110
+ #pdm.lock
111
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
112
+ # in version control.
113
+ # https://pdm.fming.dev/#use-with-ide
114
+ .pdm.toml
115
+
116
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
117
+ __pypackages__/
118
+
119
+ # Celery stuff
120
+ celerybeat-schedule
121
+ celerybeat.pid
122
+
123
+ # SageMath parsed files
124
+ *.sage.py
125
+
126
+ # Environments
127
+ .env
128
+ .venv
129
+ env/
130
+ venv/
131
+ ENV/
132
+ env.bak/
133
+ venv.bak/
134
+
135
+ # Spyder project settings
136
+ .spyderproject
137
+ .spyproject
138
+
139
+ # Rope project settings
140
+ .ropeproject
141
+
142
+ # mkdocs documentation
143
+ /site
144
+
145
+ # mypy
146
+ .mypy_cache/
147
+ .dmypy.json
148
+ dmypy.json
149
+
150
+ # Pyre type checker
151
+ .pyre/
152
+
153
+ # pytype static type analyzer
154
+ .pytype/
155
+
156
+ # Cython debug symbols
157
+ cython_debug/
158
+
159
+ # PyCharm
160
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
161
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
162
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
163
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
164
+ #.idea/
165
+
166
+ ### Python Patch ###
167
+ # Poetry local configuration file - https://python-poetry.org/docs/configuration/#local-configuration
168
+ poetry.toml
169
+
170
+ # ruff
171
+ .ruff_cache/
172
+
173
+ # LSP config files
174
+ pyrightconfig.json
175
+
176
+ # .env file
177
+ .env
app.py ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from snac import SNAC
2
+ import torch
3
+ import gradio as gr
4
+ from transformers import AutoModelForCausalLM, AutoTokenizer
5
+ from huggingface_hub import snapshot_download
6
+ from dotenv import load_dotenv
7
+ load_dotenv()
8
+
9
+ # Load models function
10
+ def load_models():
11
+ # Check if CUDA is available
12
+ device = "cuda" if torch.cuda.is_available() else "cpu"
13
+
14
+ print("Loading SNAC model...")
15
+ snac_model = SNAC.from_pretrained("hubertsiuzdak/snac_24khz")
16
+ snac_model = snac_model.to(device)
17
+
18
+ model_name = "canopylabs/orpheus-3b-0.1-ft"
19
+
20
+ # Download only model config and safetensors
21
+ snapshot_download(
22
+ repo_id=model_name,
23
+ allow_patterns=[
24
+ "config.json",
25
+ "*.safetensors",
26
+ "model.safetensors.index.json",
27
+ ],
28
+ ignore_patterns=[
29
+ "optimizer.pt",
30
+ "pytorch_model.bin",
31
+ "training_args.bin",
32
+ "scheduler.pt",
33
+ "tokenizer.json",
34
+ "tokenizer_config.json",
35
+ "special_tokens_map.json",
36
+ "vocab.json",
37
+ "merges.txt",
38
+ "tokenizer.*"
39
+ ]
40
+ )
41
+
42
+ model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.bfloat16)
43
+ model.to(device)
44
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
45
+ print(f"Orpheus model loaded to {device}")
46
+
47
+ return snac_model, model, tokenizer, device
48
+
49
+ # Process text prompt
50
+ def process_prompt(prompt, voice, tokenizer, device):
51
+ prompt = f"{voice}: {prompt}"
52
+ input_ids = tokenizer(prompt, return_tensors="pt").input_ids
53
+
54
+ start_token = torch.tensor([[128259]], dtype=torch.int64) # Start of human
55
+ end_tokens = torch.tensor([[128009, 128260]], dtype=torch.int64) # End of text, End of human
56
+
57
+ modified_input_ids = torch.cat([start_token, input_ids, end_tokens], dim=1) # SOH SOT Text EOT EOH
58
+
59
+ # No padding needed for single input
60
+ attention_mask = torch.ones_like(modified_input_ids)
61
+
62
+ return modified_input_ids.to(device), attention_mask.to(device)
63
+
64
+ # Generate speech tokens
65
+ def generate_speech_tokens(input_ids, attention_mask, model, params):
66
+ with torch.no_grad():
67
+ generated_ids = model.generate(
68
+ input_ids=input_ids,
69
+ attention_mask=attention_mask,
70
+ max_new_tokens=params["max_new_tokens"],
71
+ do_sample=True,
72
+ temperature=params["temperature"],
73
+ top_p=params["top_p"],
74
+ repetition_penalty=params["repetition_penalty"],
75
+ num_return_sequences=1,
76
+ eos_token_id=128258,
77
+ )
78
+ return generated_ids
79
+
80
+ # Parse output tokens to audio
81
+ def parse_output(generated_ids):
82
+ token_to_find = 128257
83
+ token_to_remove = 128258
84
+
85
+ token_indices = (generated_ids == token_to_find).nonzero(as_tuple=True)
86
+
87
+ if len(token_indices[1]) > 0:
88
+ last_occurrence_idx = token_indices[1][-1].item()
89
+ cropped_tensor = generated_ids[:, last_occurrence_idx+1:]
90
+ else:
91
+ cropped_tensor = generated_ids
92
+
93
+ processed_rows = []
94
+ for row in cropped_tensor:
95
+ masked_row = row[row != token_to_remove]
96
+ processed_rows.append(masked_row)
97
+
98
+ code_lists = []
99
+ for row in processed_rows:
100
+ row_length = row.size(0)
101
+ new_length = (row_length // 7) * 7
102
+ trimmed_row = row[:new_length]
103
+ trimmed_row = [t - 128266 for t in trimmed_row]
104
+ code_lists.append(trimmed_row)
105
+
106
+ return code_lists[0] # Return just the first one for single sample
107
+
108
+ # Redistribute codes for audio generation
109
+ def redistribute_codes(code_list, snac_model):
110
+ device = next(snac_model.parameters()).device # Get the device of SNAC model
111
+
112
+ layer_1 = []
113
+ layer_2 = []
114
+ layer_3 = []
115
+ for i in range((len(code_list)+1)//7):
116
+ layer_1.append(code_list[7*i])
117
+ layer_2.append(code_list[7*i+1]-4096)
118
+ layer_3.append(code_list[7*i+2]-(2*4096))
119
+ layer_3.append(code_list[7*i+3]-(3*4096))
120
+ layer_2.append(code_list[7*i+4]-(4*4096))
121
+ layer_3.append(code_list[7*i+5]-(5*4096))
122
+ layer_3.append(code_list[7*i+6]-(6*4096))
123
+
124
+ # Move tensors to the same device as the SNAC model
125
+ codes = [
126
+ torch.tensor(layer_1, device=device).unsqueeze(0),
127
+ torch.tensor(layer_2, device=device).unsqueeze(0),
128
+ torch.tensor(layer_3, device=device).unsqueeze(0)
129
+ ]
130
+
131
+ audio_hat = snac_model.decode(codes)
132
+ return audio_hat.detach().squeeze().cpu().numpy() # Always return CPU numpy array
133
+
134
+ # Main generation function
135
+ def generate_speech(text, voice, temperature, top_p, repetition_penalty, max_new_tokens, progress=gr.Progress()):
136
+ if not text.strip():
137
+ return None
138
+
139
+ try:
140
+ progress(0.1, "Processing text...")
141
+ input_ids, attention_mask = process_prompt(text, voice, tokenizer, device)
142
+
143
+ progress(0.3, "Generating speech tokens...")
144
+ params = {
145
+ "temperature": temperature,
146
+ "top_p": top_p,
147
+ "repetition_penalty": repetition_penalty,
148
+ "max_new_tokens": max_new_tokens
149
+ }
150
+ generated_ids = generate_speech_tokens(input_ids, attention_mask, model, params)
151
+
152
+ progress(0.6, "Processing speech tokens...")
153
+ code_list = parse_output(generated_ids)
154
+
155
+ progress(0.8, "Converting to audio...")
156
+ audio_samples = redistribute_codes(code_list, snac_model)
157
+
158
+ return (24000, audio_samples) # Return sample rate and audio
159
+ except Exception as e:
160
+ print(f"Error generating speech: {e}")
161
+ return None
162
+
163
+ # Examples for the UI
164
+ examples = [
165
+ ["Hey there my name is Tara, <chuckle> and I'm a speech generation model that can sound like a person.", "tara", 0.6, 0.95, 1.1, 1200],
166
+ ["I've also been taught to understand and produce paralinguistic things like sighing, or chuckling, or yawning!", "dan", 0.7, 0.95, 1.1, 1200],
167
+ ["I live in San Francisco, and have, uhm let's see, 3 billion 7 hundred ... well, lets just say a lot of parameters.", "emma", 0.6, 0.9, 1.2, 1200]
168
+ ]
169
+
170
+ # Available voices
171
+ VOICES = ["tara", "dan", "josh", "emma"]
172
+
173
+ # Load models globally
174
+ try:
175
+ snac_model, model, tokenizer, device = load_models()
176
+ except Exception as e:
177
+ print(f"Error loading models: {e}")
178
+ raise
179
+
180
+ # Create Gradio interface
181
+ with gr.Blocks(title="Orpheus Text-to-Speech") as demo:
182
+ gr.Markdown("""
183
+ # 🎵 Orpheus Text-to-Speech
184
+ Enter your text below and hear it converted to natural-sounding speech with the Orpheus TTS model.
185
+
186
+ ## Tips for better prompts:
187
+ - Add paralinguistic elements like `<chuckle>`, `<sigh>`, or `uhm` for more human-like speech.
188
+ - Longer text prompts generally work better than very short phrases
189
+ - Adjust the temperature slider for more varied (higher) or consistent (lower) speech patterns
190
+ """)
191
+ with gr.Row():
192
+ with gr.Column(scale=3):
193
+ text_input = gr.Textbox(
194
+ label="Text to speak",
195
+ placeholder="Enter your text here...",
196
+ lines=5
197
+ )
198
+ voice = gr.Dropdown(
199
+ choices=VOICES,
200
+ value="tara",
201
+ label="Voice"
202
+ )
203
+
204
+ with gr.Accordion("Advanced Settings", open=False):
205
+ temperature = gr.Slider(
206
+ minimum=0.1, maximum=1.5, value=0.6, step=0.05,
207
+ label="Temperature",
208
+ info="Higher values (0.7-1.0) create more expressive but less stable speech"
209
+ )
210
+ top_p = gr.Slider(
211
+ minimum=0.1, maximum=1.0, value=0.95, step=0.05,
212
+ label="Top P",
213
+ info="Nucleus sampling threshold"
214
+ )
215
+ repetition_penalty = gr.Slider(
216
+ minimum=1.0, maximum=2.0, value=1.1, step=0.05,
217
+ label="Repetition Penalty",
218
+ info="Higher values discourage repetitive patterns"
219
+ )
220
+ max_new_tokens = gr.Slider(
221
+ minimum=100, maximum=2000, value=1200, step=100,
222
+ label="Max Length",
223
+ info="Maximum length of generated audio (in tokens)"
224
+ )
225
+
226
+ with gr.Row():
227
+ submit_btn = gr.Button("Generate Speech", variant="primary")
228
+ clear_btn = gr.Button("Clear")
229
+
230
+ with gr.Column(scale=2):
231
+ audio_output = gr.Audio(label="Generated Speech", type="numpy")
232
+
233
+ # Set up examples
234
+ gr.Examples(
235
+ examples=examples,
236
+ inputs=[text_input, voice, temperature, top_p, repetition_penalty, max_new_tokens],
237
+ outputs=audio_output,
238
+ fn=generate_speech,
239
+ cache_examples=True,
240
+ )
241
+
242
+ # Set up event handlers
243
+ submit_btn.click(
244
+ fn=generate_speech,
245
+ inputs=[text_input, voice, temperature, top_p, repetition_penalty, max_new_tokens],
246
+ outputs=audio_output
247
+ )
248
+
249
+ clear_btn.click(
250
+ fn=lambda: (None, None),
251
+ inputs=[],
252
+ outputs=[text_input, audio_output]
253
+ )
254
+
255
+ # Launch the app
256
+ if __name__ == "__main__":
257
+ try:
258
+ demo.queue().launch(share=False)
259
+ except Exception as e:
260
+ print(f"Error launching app: {e}")
requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ snac
2
+ python-dotenv