Bils commited on
Commit
213e5d3
·
verified ·
1 Parent(s): 2019ee0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +113 -107
app.py CHANGED
@@ -1,120 +1,126 @@
1
- import gradio as gr
2
  import os
 
 
 
3
  import torch
4
- from transformers import (
5
- AutoTokenizer,
6
- AutoModelForCausalLM,
7
- pipeline,
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,
23
- use_auth_token=token,
24
- torch_dtype=torch.float16,
25
- device_map="auto", # Use device map to offload computations
26
- trust_remote_code=True # Enables execution of remote code for Zero GPU
27
- )
28
- return pipeline("text-generation", model=model, tokenizer=tokenizer)
 
 
29
  except Exception as e:
30
- return str(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()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import spaces
2
  import os
3
+ import tempfile
4
+ import gradio as gr
5
+ from dotenv import load_dotenv
6
  import torch
7
+ from scipy.io.wavfile import write
8
+ from diffusers import DiffusionPipeline
9
+ from transformers import pipeline
10
+ from pathlib import Path
11
+
12
+ load_dotenv()
13
+ hf_token = os.getenv("HF_TKN")
14
+
15
+ device_id = 0 if torch.cuda.is_available() else -1
16
+
17
+ captioning_pipeline = pipeline(
18
+ "image-to-text",
19
+ model="nlpconnect/vit-gpt2-image-captioning",
20
+ device=device_id
21
+ )
22
+
23
+ pipe = DiffusionPipeline.from_pretrained(
24
+ "cvssp/audioldm2",
25
+ use_auth_token=hf_token
26
  )
 
27
 
28
+ @spaces.GPU(duration=120)
29
+ def analyze_image_with_free_model(image_file):
 
 
30
  try:
31
+ with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as temp_file:
32
+ temp_file.write(image_file)
33
+ temp_image_path = temp_file.name
34
+
35
+ results = captioning_pipeline(temp_image_path)
36
+ if not results or not isinstance(results, list):
37
+ return "Error: Could not generate caption.", True
38
+
39
+ caption = results[0].get("generated_text", "").strip()
40
+ if not caption:
41
+ return "No caption was generated.", True
42
+ return caption, False
43
+
44
  except Exception as e:
45
+ return f"Error analyzing image: {e}", True
46
 
47
+ @spaces.GPU(duration=120)
48
+ def get_audioldm_from_caption(caption):
 
 
49
  try:
50
+ pipe.to("cuda")
51
+ audio_output = pipe(
52
+ prompt=caption,
53
+ num_inference_steps=50,
54
+ guidance_scale=7.5
55
  )
56
+ pipe.to("cpu")
57
+ audio = audio_output.audios[0]
 
 
 
58
 
59
+ with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as temp_wav:
60
+ write(temp_wav.name, 16000, audio)
61
+ return temp_wav.name
 
 
 
 
 
 
 
62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
  except Exception as e:
64
+ print(f"Error generating audio from caption: {e}")
65
+ return None
66
+
67
+ with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue")) as demo:
68
+ with gr.Row():
69
+ with gr.Column(scale=1):
70
+ gr.Image(value="https://via.placeholder.com/150", interactive=False, label="App Logo", elem_id="app-logo")
71
+ with gr.Column(scale=5):
72
+ gr.HTML("""
73
+ <div style="text-align: center; font-size: 32px; font-weight: bold; margin-bottom: 10px;">🎶 Image-to-Sound Generator</div>
74
+ <div style="text-align: center; font-size: 16px; color: #6c757d;">Transform your images into descriptive captions and immersive soundscapes.</div>
75
+ """)
76
+
77
+ with gr.Row():
78
+ with gr.Column():
79
+ gr.Markdown("""
80
+ ### How It Works
81
+ 1. **Upload an Image**: Select an image to analyze.
82
+ 2. **Generate Description**: Get a detailed caption describing your image.
83
+ 3. **Generate Sound**: Create an audio representation based on the caption.
84
+ """)
85
+
86
+ with gr.Row():
87
+ with gr.Column(scale=1):
88
+ image_upload = gr.File(label="Upload Image", type="binary")
89
+ generate_description_button = gr.Button("Generate Description", variant="primary")
90
+ with gr.Column(scale=2):
91
+ caption_display = gr.Textbox(label="Generated Caption", interactive=False, placeholder="Your image caption will appear here.")
92
+ generate_sound_button = gr.Button("Generate Sound", variant="primary")
93
+ with gr.Column(scale=1):
94
+ audio_output = gr.Audio(label="Generated Sound Effect", interactive=False)
95
+
96
  with gr.Row():
97
+ gr.Markdown("""
98
+ ## About This App
99
+ This application uses advanced machine learning models to transform images into text captions and generate matching sound effects. It's a unique blend of visual and auditory creativity, powered by state-of-the-art AI technology.
100
+
101
+ For inquiries, contact us at [[email protected]](mailto:[email protected]).
102
+ """)
103
+
104
+ def update_caption(image_file):
105
+ description, _ = analyze_image_with_free_model(image_file)
106
+ return description
107
+
108
+ def generate_sound(description):
109
+ if not description or description.startswith("Error"):
110
+ return None
111
+ audio_path = get_audioldm_from_caption(description)
112
+ return audio_path
113
+
114
+ generate_description_button.click(
115
+ fn=update_caption,
116
+ inputs=image_upload,
117
+ outputs=caption_display
118
+ )
119
+
120
+ generate_sound_button.click(
121
+ fn=generate_sound,
122
+ inputs=caption_display,
123
+ outputs=audio_output
124
+ )
125
+
126
+ demo.launch(debug=True, share=True)