glodov commited on
Commit
3464b5a
·
verified ·
1 Parent(s): a80c2b3

Audio generation.

Browse files
Files changed (1) hide show
  1. app.py +143 -52
app.py CHANGED
@@ -1,64 +1,155 @@
1
- import gradio as gr
2
- from huggingface_hub import InferenceClient
3
 
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- # client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
- client = InferenceClient("Qwen/Qwen2.5-Coder-3B-Instruct")
 
9
 
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
 
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
 
26
- messages.append({"role": "user", "content": message})
 
 
27
 
28
- response = ""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
 
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
 
39
- response += token
40
- yield response
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
 
 
 
 
 
 
 
 
 
 
 
42
 
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
- )
61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
 
 
63
  if __name__ == "__main__":
64
- demo.launch()
 
1
+ """Gradio app for Higgs Audio v2 on Hugging Face Spaces."""
 
2
 
3
+ import gradio as gr
4
+ import torch
5
+ import torchaudio
6
+ import soundfile as sf
7
+ import os
8
+ import tempfile
9
 
10
+ from boson_multimodal.serve.serve_engine import HiggsAudioServeEngine, HiggsAudioResponse
11
+ from boson_multimodal.data_types import ChatMLSample, Message, AudioContent
 
 
 
 
 
 
 
12
 
13
+ # Model and tokenizer paths
14
+ MODEL_PATH = "bosonai/higgs-audio-v2-generation-3B-base"
15
+ AUDIO_TOKENIZER_PATH = "bosonai/higgs-audio-v2-tokenizer"
 
 
16
 
17
+ # Initialize the engine once at startup
18
+ device = "cuda" if torch.cuda.is_available() else "cpu"
19
+ serve_engine = HiggsAudioServeEngine(MODEL_PATH, AUDIO_TOKENIZER_PATH, device=device)
20
 
21
+ def generate_audio(
22
+ text_input,
23
+ scene_description,
24
+ temperature,
25
+ top_p,
26
+ top_k,
27
+ max_new_tokens,
28
+ reference_audio_file
29
+ ):
30
+ """Generate audio from text using Higgs Audio v2."""
31
+ # Prepare system message
32
+ if scene_description:
33
+ system_prompt = (
34
+ "Generate audio following instruction.\n\n"
35
+ f"<|scene_desc_start|>\n{scene_description}\n<|scene_desc_end|>"
36
+ )
37
+ else:
38
+ system_prompt = (
39
+ "Generate audio following instruction.\n\n"
40
+ "<|scene_desc_start|>\nAudio is recorded from a quiet room.\n<|scene_desc_end|>"
41
+ )
42
 
43
+ messages = [
44
+ Message(role="system", content=system_prompt),
45
+ Message(role="user", content=text_input)
46
+ ]
 
 
 
 
47
 
48
+ # Add reference audio if provided
49
+ if reference_audio_file is not None:
50
+ # For reference audio, we need to add a placeholder message
51
+ # In a full implementation, you would encode the reference audio
52
+ # and include it in the context
53
+ messages.append(
54
+ Message(
55
+ role="user",
56
+ content="[SPEAKER0] This is a reference voice sample."
57
+ )
58
+ )
59
+ messages.append(
60
+ Message(
61
+ role="assistant",
62
+ content=AudioContent(audio_url=reference_audio_file.name)
63
+ )
64
+ )
65
 
66
+ try:
67
+ # Generate audio
68
+ output: HiggsAudioResponse = serve_engine.generate(
69
+ chat_ml_sample=ChatMLSample(messages=messages),
70
+ max_new_tokens=max_new_tokens,
71
+ temperature=temperature,
72
+ top_p=top_p,
73
+ top_k=top_k,
74
+ stop_strings=["<|end_of_text|>", "<|eot_id|>"],
75
+ )
76
 
77
+ # Save audio to temporary file
78
+ with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmp_file:
79
+ sf.write(tmp_file.name, output.audio, output.sampling_rate)
80
+ return tmp_file.name
81
+
82
+ except Exception as e:
83
+ raise gr.Error(f"Error during generation: {str(e)}")
 
 
 
 
 
 
 
 
 
 
 
84
 
85
+ # Gradio interface
86
+ with gr.Blocks(title="Higgs Audio v2") as demo:
87
+ gr.Markdown("""
88
+ # 🎵 Higgs Audio v2: Expressive Audio Generation
89
+
90
+ Generate expressive speech from text with Higgs Audio v2.
91
+ For best results, use a GPU-enabled space.
92
+ """)
93
+
94
+ with gr.Row():
95
+ with gr.Column():
96
+ text_input = gr.Textbox(
97
+ label="Input Text",
98
+ placeholder="Enter text to convert to speech...",
99
+ lines=5
100
+ )
101
+
102
+ scene_description = gr.Textbox(
103
+ label="Scene Description (Optional)",
104
+ placeholder="Describe the audio environment (e.g., 'Audio recorded in a noisy cafe')",
105
+ lines=2
106
+ )
107
+
108
+ reference_audio = gr.Audio(
109
+ label="Reference Audio (Optional) - Voice Cloning",
110
+ type="filepath"
111
+ )
112
+
113
+ with gr.Accordion("Generation Parameters", open=False):
114
+ temperature = gr.Slider(
115
+ minimum=0.1, maximum=2.0, value=0.7, step=0.1,
116
+ label="Temperature"
117
+ )
118
+
119
+ top_p = gr.Slider(
120
+ minimum=0.1, maximum=1.0, value=0.95, step=0.05,
121
+ label="Top-p (nucleus sampling)"
122
+ )
123
+
124
+ top_k = gr.Slider(
125
+ minimum=1, maximum=100, value=50, step=1,
126
+ label="Top-k"
127
+ )
128
+
129
+ max_new_tokens = gr.Slider(
130
+ minimum=128, maximum=4096, value=1024, step=128,
131
+ label="Max New Tokens"
132
+ )
133
+
134
+ generate_btn = gr.Button("Generate Audio", variant="primary")
135
+
136
+ with gr.Column():
137
+ audio_output = gr.Audio(label="Generated Audio")
138
+
139
+ generate_btn.click(
140
+ generate_audio,
141
+ inputs=[
142
+ text_input,
143
+ scene_description,
144
+ temperature,
145
+ top_p,
146
+ top_k,
147
+ max_new_tokens,
148
+ reference_audio
149
+ ],
150
+ outputs=audio_output
151
+ )
152
 
153
+ # For HF Spaces, we need to set up proper sharing
154
  if __name__ == "__main__":
155
+ demo.launch(share=True)