File size: 6,013 Bytes
2142ea2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0124826
 
 
 
b3812f7
1d40f41
b3812f7
 
 
 
 
 
7f45569
 
 
 
 
 
 
2142ea2
 
 
 
 
 
0124826
2142ea2
0124826
2142ea2
 
 
 
 
7663981
0124826
 
 
2142ea2
 
0124826
2142ea2
0124826
 
 
2142ea2
0124826
 
 
2142ea2
0124826
 
2142ea2
0124826
 
2142ea2
 
0124826
 
 
 
 
 
 
2142ea2
0124826
 
 
2142ea2
0124826
2142ea2
0124826
2142ea2
 
 
 
 
 
 
 
 
0124826
2142ea2
 
 
 
 
0124826
 
2142ea2
 
 
 
0124826
2142ea2
 
 
0124826
 
2142ea2
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
# import torch
# import torchaudio
# from einops import rearrange
# import gradio as gr
# import spaces
# import os
# import uuid

# # Importing the model-related functions
# from stable_audio_tools import get_pretrained_model
# from stable_audio_tools.inference.generation import generate_diffusion_cond


# from huggingface_hub import login

# hf_token = os.getenv('HF_TOKEN')
# login(token=hf_token,add_to_git_credential=True)

# # Load the model outside of the GPU-decorated function
# def load_model():
#     print("Loading model...")
#     model, model_config = get_pretrained_model("stabilityai/stable-audio-open-1.0")
#     print("Model loaded successfully.")
#     return model, model_config

# # Define the function to generate audio
# @spaces.GPU(duration=120)
# def generate_audio(prompt, bpm, seconds_total):
#     device = "cuda" if torch.cuda.is_available() else "cpu"

#     # Download model
#     model, model_config = load_model()
#     sample_rate = model_config["sample_rate"]
#     sample_size = model_config["sample_size"]

#     model = model.to(device)

#     # Set up text and timing conditioning
#     conditioning = [{
#         "prompt": f"{bpm} BPM {prompt}",
#         "seconds_start": 0,
#         "seconds_total": seconds_total
#     }]

#     # Generate stereo audio
#     output = generate_diffusion_cond(
#         model,
#         steps=100,
#         cfg_scale=7,
#         conditioning=conditioning,
#         sample_size=sample_size,
#         sigma_min=0.3,
#         sigma_max=500,
#         sampler_type="dpmpp-3m-sde",
#         device=device
#     )

#     # Rearrange audio batch to a single sequence
#     output = rearrange(output, "b d n -> d (b n)")

#     # Peak normalize, clip, convert to int16, and save to file
#     output = output.to(torch.float32).div(torch.max(torch.abs(output))).clamp(-1, 1).mul(32767).to(torch.int16).cpu()
    
#     output_path = "output.wav"
#     torchaudio.save(output_path, output, sample_rate)
    
#     return output_path

# # Define the Gradio interface
# iface = gr.Interface(
#     fn=generate_audio,
#     inputs=[
#         gr.Textbox(label="Prompt", placeholder="Enter the description of the audio (e.g., tech house drum loop)"),
#         gr.Number(label="BPM", value=128),
#         gr.Number(label="Duration (seconds)", value=30)
#     ],
#     outputs=gr.Audio(label="Generated Audio"),
#     title="Stable Audio Generation",
#     description="Generate audio based on a text prompt using stable audio tools.",
# )

# # Launch the interface
# iface.launch()

import torch
import torchaudio
from einops import rearrange
import gradio as gr
import spaces
import os
import uuid

# Importing the model-related functions
from stable_audio_tools import get_pretrained_model
from stable_audio_tools.inference.generation import generate_diffusion_cond

# Load the model outside of the GPU-decorated function
def load_model():
    print("Loading model...")
    model, model_config = get_pretrained_model("stabilityai/stable-audio-open-1.0")
    print("Model loaded successfully.")
    return model, model_config

# Function to set up, generate, and process the audio
@spaces.GPU(duration=120)  # Allocate GPU only when this function is called
def generate_audio(prompt, seconds_total=30, steps=100, cfg_scale=7):
    print(f"Prompt received: {prompt}")
    print(f"Settings: Duration={seconds_total}s, Steps={steps}, CFG Scale={cfg_scale}")

    device = "cuda" if torch.cuda.is_available() else "cpu"
    print(f"Using device: {device}")

    # Fetch the Hugging Face token from the environment variable
    hf_token = os.getenv('HF_TOKEN')
    print(f"Hugging Face token: {hf_token}")

    # Use pre-loaded model and configuration
    model, model_config = load_model()
    sample_rate = model_config["sample_rate"]
    sample_size = model_config["sample_size"]

    print(f"Sample rate: {sample_rate}, Sample size: {sample_size}")

    model = model.to(device)
    print("Model moved to device.")

    # Set up text and timing conditioning
    conditioning = [{
        "prompt": prompt,
        "seconds_start": 0,
        "seconds_total": seconds_total
    }]
    print(f"Conditioning: {conditioning}")

    # Generate stereo audio
    print("Generating audio...")
    output = generate_diffusion_cond(
        model,
        steps=steps,
        cfg_scale=cfg_scale,
        conditioning=conditioning,
        sample_size=sample_size,
        sigma_min=0.3,
        sigma_max=500,
        sampler_type="dpmpp-3m-sde",
        device=device
    )
    print("Audio generated.")

    # Rearrange audio batch to a single sequence
    output = rearrange(output, "b d n -> d (b n)")
    print("Audio rearranged.")

    # Peak normalize, clip, convert to int16
    output = output.to(torch.float32).div(torch.max(torch.abs(output))).clamp(-1, 1).mul(32767).to(torch.int16).cpu()
    print("Audio normalized and converted.")

    # Generate a unique filename for the output
    unique_filename = f"output_{uuid.uuid4().hex}.wav"
    print(f"Saving audio to file: {unique_filename}")

    # Save to file
    torchaudio.save(unique_filename, output, sample_rate)
    print(f"Audio saved: {unique_filename}")

    # Return the path to the generated audio file
    return unique_filename

# Setting up the Gradio Interface
interface = gr.Interface(
    fn=generate_audio,
    inputs=[
        gr.Textbox(label="Prompt", placeholder="Enter your text prompt here"),
        gr.Slider(0, 47, value=30, label="Duration in Seconds"),
        gr.Slider(10, 150, value=100, step=10, label="Number of Diffusion Steps"),
        gr.Slider(1, 15, value=7, step=0.1, label="CFG Scale")
    ],
    outputs=gr.Audio(type="filepath", label="Generated Audio"),
    title="Stable Audio Generator",
    description="Generate variable-length stereo audio at 44.1kHz from text prompts using Stable Audio Open 1.0."
)

# Pre-load the model to avoid multiprocessing issues
model, model_config = load_model()

# Launch the Interface
interface.launch()