maliahson commited on
Commit
60634e1
·
verified ·
1 Parent(s): 65a9a1e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -47
app.py CHANGED
@@ -1,72 +1,85 @@
1
  import gradio as gr
 
 
2
  import numpy as np
3
- import os
4
- import zipfile
5
  from pydub import AudioSegment
6
  import io
7
- import tempfile
8
 
9
 
10
- # Function to split audio and save as separate files in a zip folder
11
- def split_audio_and_zip(audio, chunk_length_s):
12
- # Temporary directory to store the split audio files
13
- temp_dir = tempfile.mkdtemp()
 
 
14
 
15
- # Convert the numpy audio array into an AudioSegment object
16
  audio_segment = AudioSegment(
17
- audio.tobytes(),
18
- frame_rate=16000, # Assuming the sample rate is 16kHz, you can adjust this
19
- sample_width=audio.dtype.itemsize,
20
  channels=1
21
  )
22
 
23
- # Get the length of the audio in milliseconds
24
- audio_length_ms = len(audio_segment)
 
25
 
26
- # Create a list to store paths of split audio files
27
- split_audio_paths = []
 
28
 
29
- # Split the audio into chunks based on the specified length
30
- chunk_length_ms = chunk_length_s * 1000 # Convert chunk length from seconds to milliseconds
31
- num_chunks = int(np.ceil(audio_length_ms / chunk_length_ms))
32
 
33
- for i in range(num_chunks):
34
- start_ms = i * chunk_length_ms
35
- end_ms = min((i + 1) * chunk_length_ms, audio_length_ms)
36
- chunk = audio_segment[start_ms:end_ms]
37
 
38
- # Save each chunk as an MP3 file in the temporary directory
39
- chunk_filename = os.path.join(temp_dir, f"chunk_{i + 1}.mp3")
40
- chunk.export(chunk_filename, format="mp3")
41
- split_audio_paths.append(chunk_filename)
 
 
 
42
 
43
- # Create a zip file to download
44
- zip_filename = tempfile.mktemp(suffix=".zip")
45
- with zipfile.ZipFile(zip_filename, 'w') as zipf:
46
- for chunk_path in split_audio_paths:
47
- zipf.write(chunk_path, os.path.basename(chunk_path))
48
 
49
- # Return the zip file
50
- return zip_filename
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
 
52
 
53
- # Gradio interface
54
  with gr.Blocks() as demo:
55
  with gr.Row():
56
  with gr.Column():
57
- # Audio file upload interface (no 'source' argument)
58
- audio_in = gr.Audio(type="numpy", label="Upload Your Audio File")
59
- chunk_length = gr.Slider(minimum=1, maximum=30, value=5, step=1, label="Chunk length (seconds)")
60
- run_button = gr.Button("Split and Zip Audio")
61
  with gr.Column():
62
- # Download option for the zip file containing split audio files
63
- output_zip = gr.File(label="Download Split Audio Files (Zip)")
64
-
65
- # Run the split audio function and output the zip file
66
- run_button.click(
67
- fn=split_audio_and_zip,
68
- inputs=[audio_in, chunk_length],
69
- outputs=output_zip
70
- )
71
 
72
  demo.launch()
 
1
  import gradio as gr
2
+ import math
3
+ import time
4
  import numpy as np
 
 
5
  from pydub import AudioSegment
6
  import io
 
7
 
8
 
9
+ def numpy_to_mp3(audio_array, sampling_rate):
10
+ # Normalize audio_array if it's floating-point
11
+ if np.issubdtype(audio_array.dtype, np.floating):
12
+ max_val = np.max(np.abs(audio_array))
13
+ audio_array = (audio_array / max_val) * 32767 # Normalize to 16-bit range
14
+ audio_array = audio_array.astype(np.int16)
15
 
16
+ # Create an audio segment from the numpy array
17
  audio_segment = AudioSegment(
18
+ audio_array.tobytes(),
19
+ frame_rate=sampling_rate,
20
+ sample_width=audio_array.dtype.itemsize,
21
  channels=1
22
  )
23
 
24
+ # Export the audio segment to MP3 bytes - use a high bitrate to maximise quality
25
+ mp3_io = io.BytesIO()
26
+ audio_segment.export(mp3_io, format="mp3", bitrate="320k")
27
 
28
+ # Get the MP3 bytes
29
+ mp3_bytes = mp3_io.getvalue()
30
+ mp3_io.close()
31
 
32
+ return mp3_bytes
 
 
33
 
 
 
 
 
34
 
35
+ def stream(audio, chunk_length_s):
36
+ start_time = time.time()
37
+ sampling_rate, array = audio
38
+ chunk_length = int(chunk_length_s * sampling_rate)
39
+ time_length = chunk_length_s / 2 # always stream outputs faster than it takes to process
40
+ audio_length = len(array)
41
+ num_batches = math.ceil(audio_length / chunk_length)
42
 
43
+ # Initialize a list to store timestamps for a 30-second timespan
44
+ timestamps = []
 
 
 
45
 
46
+ for idx in range(num_batches):
47
+ time.sleep(time_length)
48
+ start_pos = idx * chunk_length
49
+ end_pos = min((idx + 1) * chunk_length, audio_length)
50
+ chunk_start_time = start_pos / sampling_rate
51
+ chunk_end_time = end_pos / sampling_rate
52
+
53
+ # Save timestamps for a 30-second window
54
+ if chunk_start_time < 30:
55
+ timestamps.append((chunk_start_time, chunk_end_time))
56
+
57
+ chunk = array[start_pos: end_pos]
58
+ chunk_mp3 = numpy_to_mp3(chunk, sampling_rate=sampling_rate)
59
+
60
+ if idx == 0:
61
+ first_time = round(time.time() - start_time, 2)
62
+ run_time = round(time.time() - start_time, 2)
63
+
64
+ yield chunk_mp3, first_time, run_time
65
+
66
+ # Print the timestamps after streaming
67
+ print("Timestamps for the first 30 seconds:")
68
+ for start, end in timestamps:
69
+ print(f"Start: {start:.2f}s, End: {end:.2f}s")
70
 
71
 
 
72
  with gr.Blocks() as demo:
73
  with gr.Row():
74
  with gr.Column():
75
+ audio_in = gr.Audio(value="librispeech.wav", sources=["upload"], type="numpy")
76
+ chunk_length = gr.Slider(minimum=2, maximum=10, value=2, step=2, label="Chunk length (s)")
77
+ run_button = gr.Button("Stream audio")
 
78
  with gr.Column():
79
+ audio_out = gr.Audio(streaming=True, autoplay=True, format="mp3", label="mp3")
80
+ first_time = gr.Textbox(label="Time to first chunk (s)")
81
+ run_time = gr.Textbox(label="Time to current chunk (s)")
82
+
83
+ run_button.click(fn=stream, inputs=[audio_in, chunk_length], outputs=[audio_out, first_time, run_time])
 
 
 
 
84
 
85
  demo.launch()