Bils commited on
Commit
cf3593c
·
verified ·
1 Parent(s): 6b30d40

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +28 -79
app.py CHANGED
@@ -8,15 +8,17 @@ from transformers import (
8
  AutoProcessor,
9
  MusicgenForConditionalGeneration
10
  )
11
- import scipy.io.wavfile as wav
 
 
 
12
 
13
- # ---------------------------------------------------------------------
14
- # Load Llama 3 Model with Zero GPU
15
- # ---------------------------------------------------------------------
 
16
  def load_llama_pipeline_zero_gpu(model_id: str, token: str):
17
  try:
18
- if not torch.cuda.is_available():
19
- raise RuntimeError("ZeroGPU is not properly initialized or GPU is unavailable.")
20
  tokenizer = AutoTokenizer.from_pretrained(model_id, use_auth_token=token)
21
  model = AutoModelForCausalLM.from_pretrained(
22
  model_id,
@@ -27,94 +29,41 @@ def load_llama_pipeline_zero_gpu(model_id: str, token: str):
27
  )
28
  return pipeline("text-generation", model=model, tokenizer=tokenizer)
29
  except Exception as e:
30
- return f"Error loading model: {e}"
31
-
32
- # ---------------------------------------------------------------------
33
- # Generate Radio Script
34
- # ---------------------------------------------------------------------
35
- def generate_script(user_input: str, pipeline_llama):
36
- try:
37
- system_prompt = (
38
- "You are a top-tier radio imaging producer using Llama 3. "
39
- "Take the user's concept and craft a short, creative promo script."
40
- )
41
- combined_prompt = f"{system_prompt}\nUser concept: {user_input}\nRefined script:"
42
- result = pipeline_llama(combined_prompt, max_new_tokens=200, do_sample=True, temperature=0.9)
43
- return result[0]['generated_text'].split("Refined script:")[-1].strip()
44
- except Exception as e:
45
- return f"Error generating script: {e}"
46
-
47
- # ---------------------------------------------------------------------
48
- # Load MusicGen Model
49
- # ---------------------------------------------------------------------
50
- def load_musicgen_model():
51
- try:
52
- model = MusicgenForConditionalGeneration.from_pretrained("facebook/musicgen-small")
53
- processor = AutoProcessor.from_pretrained("facebook/musicgen-small")
54
- return model, processor
55
- except Exception as e:
56
- return None, str(e)
57
 
58
- # ---------------------------------------------------------------------
59
- # Generate Audio
60
- # ---------------------------------------------------------------------
61
  def generate_audio(prompt: str, audio_length: int, mg_model, mg_processor):
62
  try:
 
63
  inputs = mg_processor(text=[prompt], padding=True, return_tensors="pt")
64
  outputs = mg_model.generate(**inputs, max_new_tokens=audio_length)
 
 
65
  sr = mg_model.config.audio_encoder.sampling_rate
66
  audio_data = outputs[0, 0].cpu().numpy()
67
  normalized_audio = (audio_data / max(abs(audio_data)) * 32767).astype("int16")
68
- output_file = "radio_jingle.wav"
69
- wav.write(output_file, rate=sr, data=normalized_audio)
70
- return sr, normalized_audio
71
- except Exception as e:
72
- return str(e)
73
-
74
- # ---------------------------------------------------------------------
75
- # Gradio Interface
76
- # ---------------------------------------------------------------------
77
- def radio_imaging_app(user_prompt, llama_model_id, hf_token, audio_length):
78
- # Load Llama 3 Pipeline with Zero GPU
79
- pipeline_llama = load_llama_pipeline_zero_gpu(llama_model_id, hf_token)
80
- if isinstance(pipeline_llama, str):
81
- return pipeline_llama, None
82
 
83
- # Generate Script
84
- script = generate_script(user_prompt, pipeline_llama)
85
-
86
- # Load MusicGen
87
- mg_model, mg_processor = load_musicgen_model()
88
- if isinstance(mg_processor, str):
89
- return script, mg_processor
90
-
91
- # Generate Audio
92
- audio_data = generate_audio(script, audio_length, mg_model, mg_processor)
93
- if isinstance(audio_data, str):
94
- return script, audio_data
95
-
96
- return script, audio_data
97
 
98
- # ---------------------------------------------------------------------
99
- # Interface
100
- # ---------------------------------------------------------------------
101
  with gr.Blocks() as demo:
102
  gr.Markdown("# 🎧 AI Radio Imaging with Llama 3 + MusicGen (Zero GPU)")
103
- with gr.Row():
104
- user_prompt = gr.Textbox(label="Enter your promo idea", placeholder="E.g., A 15-second hype jingle for a morning talk show, fun and energetic.")
105
- llama_model_id = gr.Textbox(label="Llama 3 Model ID", value="meta-llama/Meta-Llama-3-70B")
106
- hf_token = gr.Textbox(label="Hugging Face Token", type="password")
107
- audio_length = gr.Slider(label="Audio Length (tokens)", minimum=128, maximum=1024, step=64, value=512)
108
 
109
  generate_button = gr.Button("Generate Promo Script and Audio")
110
  script_output = gr.Textbox(label="Generated Script")
111
- audio_output = gr.Audio(label="Generated Audio", type="numpy")
112
 
113
- generate_button.click(radio_imaging_app,
114
- inputs=[user_prompt, llama_model_id, hf_token, audio_length],
115
- outputs=[script_output, audio_output])
 
 
116
 
117
- # ---------------------------------------------------------------------
118
- # Launch App
119
- # ---------------------------------------------------------------------
120
  demo.launch(debug=True)
 
8
  AutoProcessor,
9
  MusicgenForConditionalGeneration
10
  )
11
+ from scipy.io.wavfile import write
12
+ import tempfile
13
+ from dotenv import load_dotenv
14
+ import spaces
15
 
16
+ load_dotenv()
17
+ hf_token = os.getenv("HF_TOKEN")
18
+
19
+ @spaces.GPU(duration=120)
20
  def load_llama_pipeline_zero_gpu(model_id: str, token: str):
21
  try:
 
 
22
  tokenizer = AutoTokenizer.from_pretrained(model_id, use_auth_token=token)
23
  model = AutoModelForCausalLM.from_pretrained(
24
  model_id,
 
29
  )
30
  return pipeline("text-generation", model=model, tokenizer=tokenizer)
31
  except Exception as e:
32
+ return str(e)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
 
34
+ @spaces.GPU(duration=120)
 
 
35
  def generate_audio(prompt: str, audio_length: int, mg_model, mg_processor):
36
  try:
37
+ mg_model.to("cuda")
38
  inputs = mg_processor(text=[prompt], padding=True, return_tensors="pt")
39
  outputs = mg_model.generate(**inputs, max_new_tokens=audio_length)
40
+ mg_model.to("cpu")
41
+
42
  sr = mg_model.config.audio_encoder.sampling_rate
43
  audio_data = outputs[0, 0].cpu().numpy()
44
  normalized_audio = (audio_data / max(abs(audio_data)) * 32767).astype("int16")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
 
46
+ with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as temp_wav:
47
+ write(temp_wav.name, sr, normalized_audio)
48
+ return temp_wav.name
49
+ except Exception as e:
50
+ return f"Error generating audio: {e}"
 
 
 
 
 
 
 
 
 
51
 
 
 
 
52
  with gr.Blocks() as demo:
53
  gr.Markdown("# 🎧 AI Radio Imaging with Llama 3 + MusicGen (Zero GPU)")
54
+ user_prompt = gr.Textbox(label="Enter your promo idea", placeholder="E.g., A 15-second hype jingle for a morning talk show.")
55
+ llama_model_id = gr.Textbox(label="Llama 3 Model ID", value="meta-llama/Meta-Llama-3-70B")
56
+ hf_token = gr.Textbox(label="Hugging Face Token", type="password")
57
+ audio_length = gr.Slider(label="Audio Length (tokens)", minimum=128, maximum=1024, step=64, value=512)
 
58
 
59
  generate_button = gr.Button("Generate Promo Script and Audio")
60
  script_output = gr.Textbox(label="Generated Script")
61
+ audio_output = gr.Audio(label="Generated Audio", type="filepath")
62
 
63
+ generate_button.click(
64
+ fn=lambda prompt, model_id, token, length: (prompt, None), # Simplify for demo
65
+ inputs=[user_prompt, llama_model_id, hf_token, audio_length],
66
+ outputs=[script_output, audio_output]
67
+ )
68
 
 
 
 
69
  demo.launch(debug=True)