Ivan000 commited on
Commit
2b4016e
·
verified ·
1 Parent(s): 516a722

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +39 -33
app.py CHANGED
@@ -8,57 +8,54 @@ import matplotlib.pyplot as plt
8
  import librosa
9
  import librosa.display
10
  import os
11
- import moviepy.video.io.ImageSequenceClip
12
 
13
  # Function to generate frequency visualization frames from audio
14
- def generate_frequency_visualization(audio_path):
15
  try:
16
  # Load the audio file
17
  y, sr = librosa.load(audio_path, sr=None)
18
- print(f"Loaded audio file with sampling rate: {sr}, and duration: {librosa.get_duration(y=y, sr=sr)} seconds.")
 
19
 
20
  if sr == 0 or len(y) == 0:
21
  raise ValueError("Invalid audio file: sampling rate or audio data is zero.")
22
 
23
  # Perform Short-Time Fourier Transform (STFT)
24
- n_fft = 2048 # Ensure n_fft is set to a valid number
25
- hop_length = 512 # Ensure hop_length is set to a valid number
26
- D = librosa.amplitude_to_db(np.abs(librosa.stft(y, n_fft=n_fft, hop_length=hop_length)), ref=np.max)
 
 
 
 
 
 
 
 
 
 
27
 
28
  # Create a directory to save the frames
29
  os.makedirs('frames', exist_ok=True)
30
 
31
  # Generate and save each frame
32
- for i in range(D.shape[1]): # Iterate over columns of D (time frames)
33
  plt.figure(figsize=(10, 6))
34
- librosa.display.specshow(D[:, i].reshape(-1, 1), sr=sr, x_axis='time', y_axis='log', hop_length=hop_length, cmap='viridis')
 
35
  plt.axis('off')
36
  plt.savefig(f'frames/frame_{i:04d}.png', bbox_inches='tight', pad_inches=0)
37
  plt.close()
38
 
39
- print(f"Generated {D.shape[1]} frames for visualization.")
40
- return 'frames'
41
  except Exception as e:
42
  print(f"Error generating frequency visualization: {e}")
43
- # Fallback: Generate a default visualization
44
- generate_default_visualization()
45
- return 'frames'
46
-
47
- # Function to generate a default visualization
48
- def generate_default_visualization():
49
- # Create a directory to save the frames
50
- os.makedirs('frames', exist_ok=True)
51
-
52
- # Generate and save default frames
53
- for i in range(10): # Generate 10 default frames
54
- plt.figure(figsize=(10, 6))
55
- plt.plot(np.sin(np.linspace(0, 10, 100)) * (i + 1))
56
- plt.axis('off')
57
- plt.savefig(f'frames/frame_{i:04d}.png', bbox_inches='tight', pad_inches=0)
58
- plt.close()
59
 
60
  # Function to create a video from the generated frames
61
- def create_video_from_frames(frames_directory):
62
  try:
63
  # Get the list of frame files
64
  frame_files = [os.path.join(frames_directory, f) for f in os.listdir(frames_directory) if f.endswith('.png')]
@@ -68,9 +65,13 @@ def create_video_from_frames(frames_directory):
68
  raise ValueError("No frames found to create the video.")
69
 
70
  # Create a video from the frames
71
- clip = moviepy.video.io.ImageSequenceClip.ImageSequenceClip(frame_files, fps=10) # Set fps to 10 for better visibility
72
  video_path = 'output_video.mp4'
73
- clip.write_videofile(video_path, codec='libx264')
 
 
 
 
74
 
75
  print(f"Video created with {len(frame_files)} frames.")
76
  return video_path
@@ -81,9 +82,14 @@ def create_video_from_frames(frames_directory):
81
  # Gradio interface function
82
  def process_audio(audio):
83
  audio_path = audio
84
- frames_directory = generate_frequency_visualization(audio_path)
85
- video_path = create_video_from_frames(frames_directory)
86
- return video_path
 
 
 
 
 
87
 
88
  # Create the Gradio interface with explanations and recommendations
89
  iface = gr.Interface(
@@ -94,7 +100,7 @@ iface = gr.Interface(
94
  description="Upload an audio file to generate a video with frequency visualization. "
95
  "Supported file types: WAV, MP3, FLAC. "
96
  "Recommended file duration: 10 seconds to 5 minutes. "
97
- "If the file is invalid or cannot be processed, a default visualization will be generated.",
98
  )
99
 
100
  # Launch the Gradio interface
 
8
  import librosa
9
  import librosa.display
10
  import os
11
+ import moviepy.editor as mp
12
 
13
  # Function to generate frequency visualization frames from audio
14
+ def generate_frequency_visualization(audio_path, fps, num_bars):
15
  try:
16
  # Load the audio file
17
  y, sr = librosa.load(audio_path, sr=None)
18
+ duration = librosa.get_duration(y=y, sr=sr)
19
+ print(f"Loaded audio file with sampling rate: {sr}, and duration: {duration} seconds.")
20
 
21
  if sr == 0 or len(y) == 0:
22
  raise ValueError("Invalid audio file: sampling rate or audio data is zero.")
23
 
24
  # Perform Short-Time Fourier Transform (STFT)
25
+ hop_length = int(sr / fps) # Hop length to match the desired fps
26
+ S = np.abs(librosa.stft(y, n_fft=2048, hop_length=hop_length))
27
+ frequencies = librosa.fft_frequencies(sr=sr)
28
+
29
+ # Create frequency bins for the bars
30
+ bins = np.linspace(0, len(frequencies), num_bars + 1, dtype=int)
31
+ bar_heights = []
32
+
33
+ # Aggregate power for each bar
34
+ for i in range(len(S[0])):
35
+ frame = S[:, i]
36
+ bar_frame = [np.mean(frame[bins[j]:bins[j+1]]) for j in range(num_bars)]
37
+ bar_heights.append(bar_frame)
38
 
39
  # Create a directory to save the frames
40
  os.makedirs('frames', exist_ok=True)
41
 
42
  # Generate and save each frame
43
+ for i, heights in enumerate(bar_heights):
44
  plt.figure(figsize=(10, 6))
45
+ plt.bar(range(num_bars), heights, color=plt.cm.viridis(np.linspace(0, 1, num_bars)))
46
+ plt.ylim(0, np.max(S))
47
  plt.axis('off')
48
  plt.savefig(f'frames/frame_{i:04d}.png', bbox_inches='tight', pad_inches=0)
49
  plt.close()
50
 
51
+ print(f"Generated {len(bar_heights)} frames for visualization.")
52
+ return 'frames', duration
53
  except Exception as e:
54
  print(f"Error generating frequency visualization: {e}")
55
+ return None, None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
 
57
  # Function to create a video from the generated frames
58
+ def create_video_from_frames(frames_directory, audio_path, fps, duration):
59
  try:
60
  # Get the list of frame files
61
  frame_files = [os.path.join(frames_directory, f) for f in os.listdir(frames_directory) if f.endswith('.png')]
 
65
  raise ValueError("No frames found to create the video.")
66
 
67
  # Create a video from the frames
68
+ clip = mp.ImageSequenceClip(frame_files, fps=fps)
69
  video_path = 'output_video.mp4'
70
+
71
+ # Add the audio to the video
72
+ audio_clip = mp.AudioFileClip(audio_path)
73
+ final_clip = clip.set_audio(audio_clip.subclip(0, duration))
74
+ final_clip.write_videofile(video_path, codec='libx264', audio_codec='aac')
75
 
76
  print(f"Video created with {len(frame_files)} frames.")
77
  return video_path
 
82
  # Gradio interface function
83
  def process_audio(audio):
84
  audio_path = audio
85
+ fps = 60
86
+ num_bars = 12
87
+ frames_directory, duration = generate_frequency_visualization(audio_path, fps, num_bars)
88
+ if frames_directory:
89
+ video_path = create_video_from_frames(frames_directory, audio_path, fps, duration)
90
+ return video_path
91
+ else:
92
+ return None
93
 
94
  # Create the Gradio interface with explanations and recommendations
95
  iface = gr.Interface(
 
100
  description="Upload an audio file to generate a video with frequency visualization. "
101
  "Supported file types: WAV, MP3, FLAC. "
102
  "Recommended file duration: 10 seconds to 5 minutes. "
103
+ "The visualization will consist of 12 bars representing frequency ranges.",
104
  )
105
 
106
  # Launch the Gradio interface