Update app.py
Browse files
app.py
CHANGED
@@ -1,24 +1,19 @@
|
|
|
|
1 |
import os
|
2 |
import tempfile
|
3 |
import gradio as gr
|
4 |
from dotenv import load_dotenv
|
5 |
import torch
|
6 |
from scipy.io.wavfile import write
|
7 |
-
from diffusers import DiffusionPipeline
|
8 |
import google.generativeai as genai
|
9 |
from pathlib import Path
|
10 |
|
11 |
-
# Check CUDA availability
|
12 |
-
print(f"Is CUDA available: {torch.cuda.is_available()}")
|
13 |
-
if torch.cuda.is_available():
|
14 |
-
print(f"CUDA device: {torch.cuda.get_device_name(torch.cuda.current_device())}")
|
15 |
-
else:
|
16 |
-
print("Using CPU as fallback.")
|
17 |
|
18 |
# Load environment variables from .env file
|
19 |
load_dotenv()
|
20 |
|
21 |
-
#
|
22 |
genai.configure(api_key=os.getenv("API_KEY"))
|
23 |
|
24 |
# Hugging Face token from environment variables
|
@@ -29,26 +24,22 @@ def analyze_image_with_gemini(image_file):
|
|
29 |
Analyzes an uploaded image with Gemini and generates a descriptive caption.
|
30 |
"""
|
31 |
try:
|
32 |
-
|
33 |
temp_image_path = tempfile.NamedTemporaryFile(delete=False, suffix=".jpg").name
|
34 |
with open(temp_image_path, "wb") as temp_file:
|
35 |
temp_file.write(image_file)
|
36 |
|
37 |
-
|
38 |
image_parts = [{"mime_type": "image/jpeg", "data": Path(temp_image_path).read_bytes()}]
|
39 |
prompt_parts = ["Describe precisely the image in one sentence.\n", image_parts[0], "\n"]
|
40 |
generation_config = {"temperature": 0.05, "top_p": 1, "top_k": 26, "max_output_tokens": 4096}
|
41 |
-
safety_settings = [
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
model_name="gemini-1.0-pro-vision-latest",
|
49 |
-
generation_config=generation_config,
|
50 |
-
safety_settings=safety_settings
|
51 |
-
)
|
52 |
response = model.generate_content(prompt_parts)
|
53 |
return response.text.strip(), False # False indicates no error
|
54 |
except Exception as e:
|
@@ -59,11 +50,11 @@ def get_audioldm_from_caption(caption):
|
|
59 |
"""
|
60 |
Generates sound from a caption using the AudioLDM-2 model.
|
61 |
"""
|
62 |
-
|
63 |
pipe = DiffusionPipeline.from_pretrained("cvssp/audioldm2", use_auth_token=hf_token)
|
64 |
pipe = pipe.to("cuda" if torch.cuda.is_available() else "cpu")
|
65 |
|
66 |
-
|
67 |
audio_output = pipe(prompt=caption, num_inference_steps=50, guidance_scale=7.5)
|
68 |
audio = audio_output.audios[0]
|
69 |
|
@@ -72,12 +63,13 @@ def get_audioldm_from_caption(caption):
|
|
72 |
|
73 |
return temp_file.name
|
74 |
|
75 |
-
#
|
76 |
css="""
|
77 |
#col-container{
|
78 |
margin: 0 auto;
|
79 |
max-width: 800px;
|
80 |
-
}
|
|
|
81 |
"""
|
82 |
|
83 |
# Gradio interface setup
|
@@ -85,46 +77,44 @@ with gr.Blocks(css=css) as demo:
|
|
85 |
# Main Title and App Description
|
86 |
with gr.Column(elem_id="col-container"):
|
87 |
gr.HTML("""
|
88 |
-
|
89 |
-
|
90 |
</h1>
|
91 |
-
|
92 |
-
|
93 |
</p>
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
image_upload = gr.File(label="Upload Image", type="binary")
|
111 |
generate_description_button = gr.Button("Tap to Generate a Description from your image")
|
112 |
-
caption_display = gr.Textbox(label="Image Description", interactive=False) #
|
113 |
generate_sound_button = gr.Button("Generate Sound Effect")
|
114 |
audio_output = gr.Audio(label="Generated Sound Effect")
|
115 |
-
|
116 |
-
# Extra footer
|
117 |
gr.Markdown("""## π₯ How You Can Contribute
|
118 |
We welcome contributions and suggestions for improvements. Your feedback is invaluable to the continuous enhancement of this application.
|
119 |
-
|
120 |
For support, questions, or to contribute, please contact us at [contact@bilsimaging.com](mailto:contact@bilsimaging.com).
|
121 |
-
|
122 |
Support our work and get involved by donating through [Ko-fi](https://ko-fi.com/bilsimaging). - Bilel Aroua
|
123 |
-
|
124 |
gr.Markdown("""## π’ Stay Connected
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
# Function to update the caption display based on the uploaded image
|
129 |
def update_caption(image_file):
|
130 |
description, _ = analyze_image_with_gemini(image_file)
|
@@ -147,5 +137,7 @@ with gr.Blocks(css=css) as demo:
|
|
147 |
outputs=audio_output
|
148 |
)
|
149 |
|
|
|
|
|
150 |
# Launch the Gradio app
|
151 |
-
demo.launch(debug=True, share=True)
|
|
|
1 |
+
# Import necessary libraries
|
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 |
import google.generativeai as genai
|
10 |
from pathlib import Path
|
11 |
|
|
|
|
|
|
|
|
|
|
|
|
|
12 |
|
13 |
# Load environment variables from .env file
|
14 |
load_dotenv()
|
15 |
|
16 |
+
#Google Generative AI for Gemini
|
17 |
genai.configure(api_key=os.getenv("API_KEY"))
|
18 |
|
19 |
# Hugging Face token from environment variables
|
|
|
24 |
Analyzes an uploaded image with Gemini and generates a descriptive caption.
|
25 |
"""
|
26 |
try:
|
27 |
+
# Save uploaded image to a temporary file
|
28 |
temp_image_path = tempfile.NamedTemporaryFile(delete=False, suffix=".jpg").name
|
29 |
with open(temp_image_path, "wb") as temp_file:
|
30 |
temp_file.write(image_file)
|
31 |
|
32 |
+
# Prepare the image data and prompt for Gemini
|
33 |
image_parts = [{"mime_type": "image/jpeg", "data": Path(temp_image_path).read_bytes()}]
|
34 |
prompt_parts = ["Describe precisely the image in one sentence.\n", image_parts[0], "\n"]
|
35 |
generation_config = {"temperature": 0.05, "top_p": 1, "top_k": 26, "max_output_tokens": 4096}
|
36 |
+
safety_settings = [{"category": "HARM_CATEGORY_HARASSMENT", "threshold": "BLOCK_MEDIUM_AND_ABOVE"},
|
37 |
+
{"category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "BLOCK_MEDIUM_AND_ABOVE"},
|
38 |
+
{"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", "threshold": "BLOCK_MEDIUM_AND_ABOVE"},
|
39 |
+
{"category": "HARM_CATEGORY_DANGEROUS_CONTENT", "threshold": "BLOCK_MEDIUM_AND_ABOVE"}]
|
40 |
+
model = genai.GenerativeModel(model_name="gemini-1.0-pro-vision-latest",
|
41 |
+
generation_config=generation_config,
|
42 |
+
safety_settings=safety_settings)
|
|
|
|
|
|
|
|
|
43 |
response = model.generate_content(prompt_parts)
|
44 |
return response.text.strip(), False # False indicates no error
|
45 |
except Exception as e:
|
|
|
50 |
"""
|
51 |
Generates sound from a caption using the AudioLDM-2 model.
|
52 |
"""
|
53 |
+
# Initialize the model
|
54 |
pipe = DiffusionPipeline.from_pretrained("cvssp/audioldm2", use_auth_token=hf_token)
|
55 |
pipe = pipe.to("cuda" if torch.cuda.is_available() else "cpu")
|
56 |
|
57 |
+
# Generate audio from the caption
|
58 |
audio_output = pipe(prompt=caption, num_inference_steps=50, guidance_scale=7.5)
|
59 |
audio = audio_output.audios[0]
|
60 |
|
|
|
63 |
|
64 |
return temp_file.name
|
65 |
|
66 |
+
# css
|
67 |
css="""
|
68 |
#col-container{
|
69 |
margin: 0 auto;
|
70 |
max-width: 800px;
|
71 |
+
}
|
72 |
+
|
73 |
"""
|
74 |
|
75 |
# Gradio interface setup
|
|
|
77 |
# Main Title and App Description
|
78 |
with gr.Column(elem_id="col-container"):
|
79 |
gr.HTML("""
|
80 |
+
<h1 style="text-align: center;">
|
81 |
+
πΆ Generate Sound Effects from Image
|
82 |
</h1>
|
83 |
+
<p style="text-align: center;">
|
84 |
+
β‘ Powered by <a href="https://bilsimaging.com" _blank >Bilsimaging</a>
|
85 |
</p>
|
86 |
+
""")
|
87 |
+
|
88 |
+
gr.Markdown("""
|
89 |
+
Welcome to this unique sound effect generator! This tool allows you to upload an image and generate a descriptive caption and a corresponding sound effect. Whether you're exploring the sound of nature, urban environments, or anything in between, this app brings your images to auditory life.
|
90 |
+
|
91 |
+
**π‘ How it works:**
|
92 |
+
1. **Upload an image**: Choose an image that you'd like to analyze.
|
93 |
+
2. **Generate Description**: Click on 'Tap to Generate Description from the image' to get a textual description of your uploaded image.
|
94 |
+
3. **Generate Sound Effect**: Based on the image description, click on 'Generate Sound Effect' to create a sound effect that matches the image context.
|
95 |
+
|
96 |
+
Enjoy the journey from visual to auditory sensation with just a few clicks!
|
97 |
+
|
98 |
+
For Example Demos sound effects generated , check out our [YouTube channel](https://www.youtube.com/playlist?list=PLwEbW4bdYBSC8exiJ9PfzufGND_14f--C)
|
99 |
+
""")
|
100 |
+
|
101 |
+
# Interface Components
|
102 |
image_upload = gr.File(label="Upload Image", type="binary")
|
103 |
generate_description_button = gr.Button("Tap to Generate a Description from your image")
|
104 |
+
caption_display = gr.Textbox(label="Image Description", interactive=False) # Keep as read-only
|
105 |
generate_sound_button = gr.Button("Generate Sound Effect")
|
106 |
audio_output = gr.Audio(label="Generated Sound Effect")
|
107 |
+
# extra footer
|
|
|
108 |
gr.Markdown("""## π₯ How You Can Contribute
|
109 |
We welcome contributions and suggestions for improvements. Your feedback is invaluable to the continuous enhancement of this application.
|
110 |
+
|
111 |
For support, questions, or to contribute, please contact us at [contact@bilsimaging.com](mailto:contact@bilsimaging.com).
|
112 |
+
|
113 |
Support our work and get involved by donating through [Ko-fi](https://ko-fi.com/bilsimaging). - Bilel Aroua
|
114 |
+
""")
|
115 |
gr.Markdown("""## π’ Stay Connected
|
116 |
+
this app is a testament to the creative possibilities that emerge when technology meets art. Enjoy exploring the auditory landscape of your images!
|
117 |
+
""")
|
|
|
118 |
# Function to update the caption display based on the uploaded image
|
119 |
def update_caption(image_file):
|
120 |
description, _ = analyze_image_with_gemini(image_file)
|
|
|
137 |
outputs=audio_output
|
138 |
)
|
139 |
|
140 |
+
|
141 |
+
|
142 |
# Launch the Gradio app
|
143 |
+
demo.launch(debug=True, share=True)
|