datatab commited on
Commit
303099b
·
verified ·
1 Parent(s): d5237ae

Upload 5 files

Browse files
Files changed (3) hide show
  1. .gitignore +177 -0
  2. app.py +235 -0
  3. requirements.txt +5 -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,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import spaces
2
+ from snac import SNAC
3
+ import torch
4
+ import gradio as gr
5
+ from transformers import AutoModelForCausalLM, AutoTokenizer
6
+ from huggingface_hub import snapshot_download
7
+ from dotenv import load_dotenv
8
+ load_dotenv()
9
+
10
+ # Check if CUDA is available
11
+ device = "cuda" if torch.cuda.is_available() else "cpu"
12
+
13
+ print("Loading SNAC model...")
14
+ snac_model = SNAC.from_pretrained("hubertsiuzdak/snac_24khz")
15
+ snac_model = snac_model.to(device)
16
+
17
+ model_name = "datatab/aida-parla-16bit-v1"
18
+
19
+ # Download only model config and safetensors
20
+ snapshot_download(
21
+ repo_id=model_name,
22
+ allow_patterns=[
23
+ "config.json",
24
+ "*.safetensors",
25
+ "model.safetensors.index.json",
26
+ ],
27
+ ignore_patterns=[
28
+ "optimizer.pt",
29
+ "pytorch_model.bin",
30
+ "training_args.bin",
31
+ "scheduler.pt",
32
+ "tokenizer.json",
33
+ "tokenizer_config.json",
34
+ "special_tokens_map.json",
35
+ "vocab.json",
36
+ "merges.txt",
37
+ "tokenizer.*"
38
+ ]
39
+ )
40
+
41
+ model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.bfloat16)
42
+ model.to(device)
43
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
44
+ print(f"Orpheus model loaded to {device}")
45
+
46
+ # Process text prompt
47
+ def process_prompt(prompt, voice, tokenizer, device):
48
+ prompt = f"{voice}: {prompt}"
49
+ input_ids = tokenizer(prompt, return_tensors="pt").input_ids
50
+
51
+ start_token = torch.tensor([[128259]], dtype=torch.int64) # Start of human
52
+ end_tokens = torch.tensor([[128009, 128260]], dtype=torch.int64) # End of text, End of human
53
+
54
+ modified_input_ids = torch.cat([start_token, input_ids, end_tokens], dim=1) # SOH SOT Text EOT EOH
55
+
56
+ # No padding needed for single input
57
+ attention_mask = torch.ones_like(modified_input_ids)
58
+
59
+ return modified_input_ids.to(device), attention_mask.to(device)
60
+
61
+ # Parse output tokens to audio
62
+ def parse_output(generated_ids):
63
+ token_to_find = 128257
64
+ token_to_remove = 128258
65
+
66
+ token_indices = (generated_ids == token_to_find).nonzero(as_tuple=True)
67
+
68
+ if len(token_indices[1]) > 0:
69
+ last_occurrence_idx = token_indices[1][-1].item()
70
+ cropped_tensor = generated_ids[:, last_occurrence_idx+1:]
71
+ else:
72
+ cropped_tensor = generated_ids
73
+
74
+ processed_rows = []
75
+ for row in cropped_tensor:
76
+ masked_row = row[row != token_to_remove]
77
+ processed_rows.append(masked_row)
78
+
79
+ code_lists = []
80
+ for row in processed_rows:
81
+ row_length = row.size(0)
82
+ new_length = (row_length // 7) * 7
83
+ trimmed_row = row[:new_length]
84
+ trimmed_row = [t - 128266 for t in trimmed_row]
85
+ code_lists.append(trimmed_row)
86
+
87
+ return code_lists[0] # Return just the first one for single sample
88
+
89
+ # Redistribute codes for audio generation
90
+ def redistribute_codes(code_list, snac_model):
91
+ device = next(snac_model.parameters()).device # Get the device of SNAC model
92
+
93
+ layer_1 = []
94
+ layer_2 = []
95
+ layer_3 = []
96
+ for i in range((len(code_list)+1)//7):
97
+ layer_1.append(code_list[7*i])
98
+ layer_2.append(code_list[7*i+1]-4096)
99
+ layer_3.append(code_list[7*i+2]-(2*4096))
100
+ layer_3.append(code_list[7*i+3]-(3*4096))
101
+ layer_2.append(code_list[7*i+4]-(4*4096))
102
+ layer_3.append(code_list[7*i+5]-(5*4096))
103
+ layer_3.append(code_list[7*i+6]-(6*4096))
104
+
105
+ # Move tensors to the same device as the SNAC model
106
+ codes = [
107
+ torch.tensor(layer_1, device=device).unsqueeze(0),
108
+ torch.tensor(layer_2, device=device).unsqueeze(0),
109
+ torch.tensor(layer_3, device=device).unsqueeze(0)
110
+ ]
111
+
112
+ audio_hat = snac_model.decode(codes)
113
+ return audio_hat.detach().squeeze().cpu().numpy() # Always return CPU numpy array
114
+
115
+ # Main generation function
116
+ @spaces.GPU()
117
+ def generate_speech(text, voice, temperature, top_p, repetition_penalty, max_new_tokens, progress=gr.Progress()):
118
+ if not text.strip():
119
+ return None
120
+
121
+ try:
122
+ progress(0.1, "Procesuirnje Teksta...")
123
+ input_ids, attention_mask = process_prompt(text, voice, tokenizer, device)
124
+
125
+ progress(0.3, "Generisanje Tokena Govora...")
126
+ with torch.no_grad():
127
+ generated_ids = model.generate(
128
+ input_ids=input_ids,
129
+ attention_mask=attention_mask,
130
+ max_new_tokens=max_new_tokens,
131
+ do_sample=True,
132
+ temperature=temperature,
133
+ top_p=top_p,
134
+ repetition_penalty=repetition_penalty,
135
+ num_return_sequences=1,
136
+ eos_token_id=128258,
137
+ )
138
+
139
+ progress(0.6, "Procesuirnje tokena govora...")
140
+ code_list = parse_output(generated_ids)
141
+
142
+ progress(0.8, "Konverzija u audio...")
143
+ audio_samples = redistribute_codes(code_list, snac_model)
144
+
145
+ return (24000, audio_samples) # Return sample rate and audio
146
+ except Exception as e:
147
+ print(f"Error generating speech: {e}")
148
+ return None
149
+
150
+ # UI config
151
+ primeri = [
152
+ ["Sastanak je tačno u 5 sati, nemoj da kasniš.", "alek", 0.1, 0.85, 1.6, 2048],
153
+ ["Ono kada imamo 60 raznih primera samo dokazuje hipotezu.", "alek", 0.1, 0.85, 1.6, 2048],
154
+ ["Unesite svoj tekst ispod i poslušajte ga pretvorenog u prirodan govor pomoću Aida TTS modela.", "alek", 0.1, 0.85, 1.6, 2048],
155
+ ]
156
+
157
+ VOICES = ["alek", "arsa", "janko", "bora", "zoki", "mila", "mia", "senka", "judita", "saska", "goga"]
158
+ EMOTIVE_TAGS = ["`<laugh>`", "`<chuckle>`", "`<sigh>`", "`<cough>`", "`<sniffle>`", "`<groan>`", "`<yawn>`", "`<gasp>`"]
159
+
160
+ # Create Gradio interface
161
+ with gr.Blocks(title="AiDA Text-to-Speech") as demo:
162
+ gr.Markdown(f"""
163
+ # 🎵 [AiDA Text-to-Speech](https://aida.guru)
164
+ Unesite tekst ispod i uradite konverziju u prirodni govor pomoću AiDA TTS modela.
165
+
166
+ ## Savet za bolji prompt:
167
+ - Povećanje `repetition_penalty` i `temperature` omogućava da model govori brže.
168
+ """)
169
+ with gr.Row():
170
+ with gr.Column(scale=3):
171
+ text_input = gr.Textbox(
172
+ label="Tekst za izgovor",
173
+ placeholder="Unesite Vaš tekst ovde...",
174
+ lines=5
175
+ )
176
+ voice = gr.Dropdown(
177
+ choices=VOICES,
178
+ value="mila",
179
+ label="Glasovi"
180
+ )
181
+
182
+ with gr.Accordion("Napredna Podešavanja", open=False):
183
+ temperature = gr.Slider(
184
+ minimum=0.01, maximum=1.5, value=0.1, step=0.05,
185
+ label="Temperature",
186
+ info="Više vrednosti (0,7-1,0) stvaraju ekspresivniji, ali manje stabilan govor"
187
+ )
188
+ top_p = gr.Slider(
189
+ minimum=0.1, maximum=1.0, value=0.95, step=0.05,
190
+ label="Top P",
191
+ info="Prag uzorkovanja jezgra"
192
+ )
193
+ repetition_penalty = gr.Slider(
194
+ minimum=1.0, maximum=2.0, value=1.6, step=0.05,
195
+ label="Repetition Penalty",
196
+ info="Više vrednosti smanjuju ponavljajuće obrasce"
197
+ )
198
+ max_new_tokens = gr.Slider(
199
+ minimum=100, maximum=4096, value=2048, step=100,
200
+ label="Max Length",
201
+ info="Maksimalna dužina generisanog zvuka (u tokenima)"
202
+ )
203
+
204
+ with gr.Row():
205
+ submit_btn = gr.Button("Kreiraj Govor", variant="primary")
206
+ clear_btn = gr.Button("Obriši")
207
+
208
+ with gr.Column(scale=2):
209
+ audio_output = gr.Audio(label="Kreiran Govor", type="numpy")
210
+
211
+ # Set up examples
212
+ gr.Examples(
213
+ examples=primeri,
214
+ inputs=[text_input, voice, temperature, top_p, repetition_penalty, max_new_tokens],
215
+ outputs=audio_output,
216
+ fn=generate_speech,
217
+ cache_examples=True,
218
+ )
219
+
220
+ # Set up event handlers
221
+ submit_btn.click(
222
+ fn=generate_speech,
223
+ inputs=[text_input, voice, temperature, top_p, repetition_penalty, max_new_tokens],
224
+ outputs=audio_output
225
+ )
226
+
227
+ clear_btn.click(
228
+ fn=lambda: (None, None),
229
+ inputs=[],
230
+ outputs=[text_input, audio_output]
231
+ )
232
+
233
+ # Launch the app
234
+ if __name__ == "__main__":
235
+ demo.queue().launch(share=False, ssr_mode=False)
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ snac
2
+ python-dotenv
3
+ transformers
4
+ torch
5
+ spaces