Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -4,8 +4,13 @@ import torch
|
|
4 |
import gradio as gr
|
5 |
from transformers import AutoModelForCausalLM, AutoTokenizer
|
6 |
from huggingface_hub import snapshot_download
|
7 |
-
|
8 |
-
|
|
|
|
|
|
|
|
|
|
|
9 |
|
10 |
# Check if CUDA is available
|
11 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
@@ -16,49 +21,57 @@ snac_model = snac_model.to(device)
|
|
16 |
|
17 |
model_name = "canopylabs/orpheus-3b-0.1-ft"
|
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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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)
|
52 |
-
end_tokens = torch.tensor([[128009, 128260]], dtype=torch.int64)
|
53 |
|
54 |
-
modified_input_ids = torch.cat([start_token, input_ids, end_tokens], dim=1)
|
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
|
@@ -84,35 +97,8 @@ def parse_output(generated_ids):
|
|
84 |
trimmed_row = [t - 128266 for t in trimmed_row]
|
85 |
code_lists.append(trimmed_row)
|
86 |
|
87 |
-
return code_lists[0]
|
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():
|
@@ -125,13 +111,13 @@ def generate_speech(text, voice, temperature, top_p, repetition_penalty, max_new
|
|
125 |
progress(0.3, "Generating speech tokens...")
|
126 |
with torch.no_grad():
|
127 |
generated_ids = model.generate(
|
128 |
-
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 |
)
|
@@ -147,87 +133,43 @@ def generate_speech(text, voice, temperature, top_p, repetition_penalty, max_new
|
|
147 |
print(f"Error generating speech: {e}")
|
148 |
return None
|
149 |
|
150 |
-
# Examples for the UI
|
151 |
-
examples = [
|
152 |
-
["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],
|
153 |
-
["I've also been taught to understand and produce paralinguistic things <sigh> like sighing, or <laugh> laughing, or <yawn> yawning!", "dan", 0.7, 0.95, 1.1, 1200],
|
154 |
-
["I live in San Francisco, and have, uhm let's see, 3 billion 7 hundred ... <gasp> well, lets just say a lot of parameters.", "leah", 0.6, 0.9, 1.2, 1200],
|
155 |
-
["Sometimes when I talk too much, I need to <cough> excuse myself. <sniffle> The weather has been quite cold lately.", "leo", 0.65, 0.9, 1.1, 1200],
|
156 |
-
["Public speaking can be challenging. <groan> But with enough practice, anyone can become better at it.", "jess", 0.7, 0.95, 1.1, 1200],
|
157 |
-
["The hike was exhausting but the view from the top was absolutely breathtaking! <sigh> It was totally worth it.", "mia", 0.65, 0.9, 1.15, 1200],
|
158 |
-
["Did you hear that joke? <laugh> I couldn't stop laughing when I first heard it. <chuckle> It's still funny.", "zac", 0.7, 0.95, 1.1, 1200],
|
159 |
-
["After running the marathon, I was so tired <yawn> and needed a long rest. <sigh> But I felt accomplished.", "zoe", 0.6, 0.95, 1.1, 1200]
|
160 |
-
]
|
161 |
-
|
162 |
-
# Available voices
|
163 |
-
VOICES = ["tara", "leah", "jess", "leo", "dan", "mia", "zac", "zoe"]
|
164 |
-
|
165 |
-
# Available Emotive Tags
|
166 |
-
EMOTIVE_TAGS = ["`<laugh>`", "`<chuckle>`", "`<sigh>`", "`<cough>`", "`<sniffle>`", "`<groan>`", "`<yawn>`", "`<gasp>`"]
|
167 |
-
|
168 |
# Create Gradio interface
|
169 |
-
with gr.Blocks(title="
|
170 |
-
gr.Markdown(f"""
|
171 |
-
# 🎵 [Orpheus Text-to-Speech](https://github.com/canopyai/Orpheus-TTS)
|
172 |
-
Enter your text below and hear it converted to natural-sounding speech with the Orpheus TTS model.
|
173 |
-
|
174 |
-
## Tips for better prompts:
|
175 |
-
- Add paralinguistic elements like {", ".join(EMOTIVE_TAGS)} or `uhm` for more human-like speech.
|
176 |
-
- Longer text prompts generally work better than very short phrases
|
177 |
-
- Increasing `repetition_penalty` and `temperature` makes the model speak faster.
|
178 |
-
""")
|
179 |
with gr.Row():
|
180 |
-
with gr.Column(scale=
|
181 |
-
|
182 |
-
|
183 |
-
|
184 |
-
|
185 |
-
)
|
186 |
-
|
187 |
-
|
188 |
-
|
189 |
-
|
190 |
-
)
|
|
|
191 |
|
192 |
-
with gr.
|
193 |
-
temperature = gr.Slider(
|
194 |
-
|
195 |
-
label="Temperature",
|
196 |
-
info="Higher values (0.7-1.0) create more expressive but less stable speech"
|
197 |
-
)
|
198 |
-
top_p = gr.Slider(
|
199 |
-
minimum=0.1, maximum=1.0, value=0.95, step=0.05,
|
200 |
-
label="Top P",
|
201 |
-
info="Nucleus sampling threshold"
|
202 |
-
)
|
203 |
-
repetition_penalty = gr.Slider(
|
204 |
-
minimum=1.0, maximum=2.0, value=1.1, step=0.05,
|
205 |
-
label="Repetition Penalty",
|
206 |
-
info="Higher values discourage repetitive patterns"
|
207 |
-
)
|
208 |
-
max_new_tokens = gr.Slider(
|
209 |
-
minimum=100, maximum=2000, value=1200, step=100,
|
210 |
-
label="Max Length",
|
211 |
-
info="Maximum length of generated audio (in tokens)"
|
212 |
-
)
|
213 |
|
214 |
with gr.Row():
|
215 |
-
|
216 |
-
|
|
|
|
|
|
|
217 |
|
218 |
with gr.Column(scale=2):
|
219 |
audio_output = gr.Audio(label="Generated Speech", type="numpy")
|
220 |
|
221 |
-
# Set up
|
222 |
-
|
223 |
-
|
224 |
-
inputs=[
|
225 |
-
outputs=
|
226 |
-
fn=generate_speech,
|
227 |
-
cache_examples=True,
|
228 |
)
|
229 |
|
230 |
-
# Set up event handlers
|
231 |
submit_btn.click(
|
232 |
fn=generate_speech,
|
233 |
inputs=[text_input, voice, temperature, top_p, repetition_penalty, max_new_tokens],
|
@@ -242,4 +184,4 @@ with gr.Blocks(title="Orpheus Text-to-Speech") as demo:
|
|
242 |
|
243 |
# Launch the app
|
244 |
if __name__ == "__main__":
|
245 |
-
demo.queue().launch(share=False, ssr_mode=False)
|
|
|
4 |
import gradio as gr
|
5 |
from transformers import AutoModelForCausalLM, AutoTokenizer
|
6 |
from huggingface_hub import snapshot_download
|
7 |
+
import google.generativeai as genai
|
8 |
+
import re
|
9 |
+
import logging
|
10 |
+
|
11 |
+
# Set up logging
|
12 |
+
logging.basicConfig(level=logging.INFO)
|
13 |
+
logger = logging.getLogger(__name__)
|
14 |
|
15 |
# Check if CUDA is available
|
16 |
device = "cuda" if torch.cuda.is_available() else "cpu"
|
|
|
21 |
|
22 |
model_name = "canopylabs/orpheus-3b-0.1-ft"
|
23 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
24 |
model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype=torch.bfloat16)
|
25 |
model.to(device)
|
26 |
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
27 |
print(f"Orpheus model loaded to {device}")
|
28 |
|
29 |
+
@spaces.GPU()
|
30 |
+
def generate_podcast_script(api_key, content, uploaded_file, duration, num_hosts):
|
31 |
+
try:
|
32 |
+
genai.configure(api_key=api_key)
|
33 |
+
model = genai.GenerativeModel('gemini-2.5-pro-preview-03-25')
|
34 |
+
|
35 |
+
combined_content = content or ""
|
36 |
+
if uploaded_file:
|
37 |
+
file_content = uploaded_file.read().decode('utf-8')
|
38 |
+
combined_content += "\n" + file_content if combined_content else file_content
|
39 |
+
|
40 |
+
prompt = f"""
|
41 |
+
Create a podcast script for {'one person' if num_hosts == 1 else 'two people'} discussing:
|
42 |
+
{combined_content}
|
43 |
+
|
44 |
+
Duration: {duration}. Include natural speech, humor, and occasional off-topic thoughts.
|
45 |
+
Use speech fillers like um, ah. Vary emotional tone.
|
46 |
+
|
47 |
+
Format: {'Monologue' if num_hosts == 1 else 'Alternating dialogue'} without speaker labels.
|
48 |
+
Separate {'paragraphs' if num_hosts == 1 else 'lines'} with blank lines.
|
49 |
+
|
50 |
+
Use emotion tags in angle brackets: <laugh>, <sigh>, <chuckle>, <cough>, <sniffle>, <groan>, <yawn>, <gasp>.
|
51 |
+
|
52 |
+
Example: "I can't believe I stayed up all night <yawn> only to find out the meeting was canceled <groan>."
|
53 |
+
|
54 |
+
Ensure content flows naturally and stays on topic. Match the script length to {duration}.
|
55 |
+
"""
|
56 |
+
|
57 |
+
response = model.generate_content(prompt)
|
58 |
+
return re.sub(r'[^a-zA-Z0-9\s.,?!<>]', '', response.text)
|
59 |
+
except Exception as e:
|
60 |
+
logger.error(f"Error generating podcast script: {str(e)}")
|
61 |
+
raise
|
62 |
+
|
63 |
def process_prompt(prompt, voice, tokenizer, device):
|
64 |
prompt = f"{voice}: {prompt}"
|
65 |
input_ids = tokenizer(prompt, return_tensors="pt").input_ids
|
66 |
|
67 |
+
start_token = torch.tensor([[128259]], dtype=torch.int64)
|
68 |
+
end_tokens = torch.tensor([[128009, 128260]], dtype=torch.int64)
|
69 |
|
70 |
+
modified_input_ids = torch.cat([start_token, input_ids, end_tokens], dim=1)
|
|
|
|
|
71 |
attention_mask = torch.ones_like(modified_input_ids)
|
72 |
|
73 |
return modified_input_ids.to(device), attention_mask.to(device)
|
74 |
|
|
|
75 |
def parse_output(generated_ids):
|
76 |
token_to_find = 128257
|
77 |
token_to_remove = 128258
|
|
|
97 |
trimmed_row = [t - 128266 for t in trimmed_row]
|
98 |
code_lists.append(trimmed_row)
|
99 |
|
100 |
+
return code_lists[0]
|
101 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
102 |
@spaces.GPU()
|
103 |
def generate_speech(text, voice, temperature, top_p, repetition_penalty, max_new_tokens, progress=gr.Progress()):
|
104 |
if not text.strip():
|
|
|
111 |
progress(0.3, "Generating speech tokens...")
|
112 |
with torch.no_grad():
|
113 |
generated_ids = model.generate(
|
114 |
+
input_ids,
|
115 |
attention_mask=attention_mask,
|
|
|
116 |
do_sample=True,
|
117 |
temperature=temperature,
|
118 |
top_p=top_p,
|
119 |
repetition_penalty=repetition_penalty,
|
120 |
+
max_new_tokens=max_new_tokens,
|
121 |
num_return_sequences=1,
|
122 |
eos_token_id=128258,
|
123 |
)
|
|
|
133 |
print(f"Error generating speech: {e}")
|
134 |
return None
|
135 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
136 |
# Create Gradio interface
|
137 |
+
with gr.Blocks(title="AI Podcaster") as demo:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
138 |
with gr.Row():
|
139 |
+
with gr.Column(scale=1):
|
140 |
+
gemini_api_key = gr.Textbox(label="Gemini API Key", type="password")
|
141 |
+
content = gr.Textbox(label="Content", lines=5)
|
142 |
+
uploaded_file = gr.File(label="Upload File")
|
143 |
+
duration = gr.Slider(minimum=1, maximum=60, value=5, step=1, label="Duration (minutes)")
|
144 |
+
num_hosts = gr.Radio(["1", "2"], label="Number of Hosts", value="1")
|
145 |
+
generate_script_btn = gr.Button("Generate Podcast Script")
|
146 |
+
|
147 |
+
with gr.Column(scale=2):
|
148 |
+
script_output = gr.Textbox(label="Generated Script", lines=10)
|
149 |
+
text_input = gr.Textbox(label="Text to speak", lines=5)
|
150 |
+
voice = gr.Dropdown(choices=["Narrator", "Male", "Female"], value="Narrator", label="Voice")
|
151 |
|
152 |
+
with gr.Row():
|
153 |
+
temperature = gr.Slider(minimum=0.1, maximum=1.0, value=0.7, step=0.1, label="Temperature")
|
154 |
+
top_p = gr.Slider(minimum=0.1, maximum=1.0, value=0.9, step=0.1, label="Top P")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
155 |
|
156 |
with gr.Row():
|
157 |
+
repetition_penalty = gr.Slider(minimum=1.0, maximum=2.0, value=1.2, step=0.1, label="Repetition Penalty")
|
158 |
+
max_new_tokens = gr.Slider(minimum=100, maximum=1000, value=500, step=50, label="Max New Tokens")
|
159 |
+
|
160 |
+
submit_btn = gr.Button("Generate Speech")
|
161 |
+
clear_btn = gr.Button("Clear")
|
162 |
|
163 |
with gr.Column(scale=2):
|
164 |
audio_output = gr.Audio(label="Generated Speech", type="numpy")
|
165 |
|
166 |
+
# Set up event handlers
|
167 |
+
generate_script_btn.click(
|
168 |
+
fn=generate_podcast_script,
|
169 |
+
inputs=[gemini_api_key, content, uploaded_file, duration, num_hosts],
|
170 |
+
outputs=script_output
|
|
|
|
|
171 |
)
|
172 |
|
|
|
173 |
submit_btn.click(
|
174 |
fn=generate_speech,
|
175 |
inputs=[text_input, voice, temperature, top_p, repetition_penalty, max_new_tokens],
|
|
|
184 |
|
185 |
# Launch the app
|
186 |
if __name__ == "__main__":
|
187 |
+
demo.queue().launch(share=False, ssr_mode=False)
|