Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -6,41 +6,52 @@ import tempfile
|
|
| 6 |
import os
|
| 7 |
|
| 8 |
def create_waveform_video(image, audio_path):
|
| 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 |
iface = gr.Interface(
|
| 46 |
fn=create_waveform_video,
|
|
|
|
| 6 |
import os
|
| 7 |
|
| 8 |
def create_waveform_video(image, audio_path):
|
| 9 |
+
# Check if audio file was uploaded
|
| 10 |
+
if audio_path is None:
|
| 11 |
+
return "Error: No audio file provided."
|
| 12 |
+
|
| 13 |
+
try:
|
| 14 |
+
# Save uploaded image temporarily
|
| 15 |
+
image_path = tempfile.mktemp(suffix=".png")
|
| 16 |
+
video_path = tempfile.mktemp(suffix=".mp4")
|
| 17 |
+
waveform_path = tempfile.mktemp(suffix=".png")
|
| 18 |
+
|
| 19 |
+
image.save(image_path)
|
| 20 |
+
|
| 21 |
+
# Load audio
|
| 22 |
+
audio_clip = AudioFileClip(audio_path)
|
| 23 |
+
|
| 24 |
+
# Generate waveform as an image
|
| 25 |
+
waveform = audio_clip.to_soundarray(fps=22050) # Convert audio to waveform array
|
| 26 |
+
if waveform.ndim > 1:
|
| 27 |
+
waveform = waveform.mean(axis=1) # Convert stereo to mono
|
| 28 |
+
|
| 29 |
+
waveform = np.interp(waveform, (waveform.min(), waveform.max()), (-1, 1)) # Normalize
|
| 30 |
+
|
| 31 |
+
# Plot waveform using matplotlib
|
| 32 |
+
plt.figure(figsize=(10, 2))
|
| 33 |
+
plt.plot(waveform, color="blue")
|
| 34 |
+
plt.axis("off")
|
| 35 |
+
plt.savefig(waveform_path, bbox_inches="tight", pad_inches=0)
|
| 36 |
+
plt.close()
|
| 37 |
+
|
| 38 |
+
# Load image and create a video clip of the same duration as the audio
|
| 39 |
+
img_clip = ImageClip(image_path).set_duration(audio_clip.duration).resize(height=720)
|
| 40 |
+
waveform_clip = ImageClip(waveform_path).set_duration(audio_clip.duration).resize(width=img_clip.w)
|
| 41 |
+
waveform_clip = waveform_clip.set_position(("center", img_clip.h - waveform_clip.h - 20))
|
| 42 |
+
|
| 43 |
+
# Combine image, waveform overlay, and audio into one video
|
| 44 |
+
final_clip = CompositeVideoClip([img_clip, waveform_clip.set_opacity(0.7)]).set_audio(audio_clip)
|
| 45 |
+
final_clip.write_videofile(video_path, codec="libx264", fps=24)
|
| 46 |
+
|
| 47 |
+
# Cleanup temporary files
|
| 48 |
+
os.remove(image_path)
|
| 49 |
+
os.remove(waveform_path)
|
| 50 |
+
|
| 51 |
+
return video_path
|
| 52 |
+
|
| 53 |
+
except Exception as e:
|
| 54 |
+
return f"An error occurred: {str(e)}"
|
| 55 |
|
| 56 |
iface = gr.Interface(
|
| 57 |
fn=create_waveform_video,
|