File size: 2,415 Bytes
44d9d8c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import gradio as gr
import numpy as np
import scipy.io.wavfile as wavfile
import scipy.fft as fft
import yt_dlp


def fft_derivative(audio_data: np.ndarray, sample_rate: int) -> np.ndarray:
    freq_domain = fft.fft(audio_data)
    freqs = fft.fftfreq(len(audio_data), 1 / sample_rate)
    freq_derivative = 1j * freqs * freq_domain
    time_domain_derivative = fft.ifft(freq_derivative)
    return np.real(time_domain_derivative)


def convert_file(audio_data: tuple[int, np.ndarray]) -> np.ndarray:
    sample_rate, audio = audio_data
    if len(audio.shape) == 2:
        audio = np.mean(audio, axis=1)
    derivative = fft_derivative(audio, sample_rate)
    derivative = np.int16(derivative / np.max(np.abs(derivative)) * 32767)
    return derivative


def process_audio_file(audio_file: str) -> tuple[int, np.ndarray]:
    sample_rate, audio_data = wavfile.read(audio_file)
    return sample_rate, audio_data


def process_youtube_link(youtube_link: str) -> str:
    song_file = "downloaded_song.wav"
    ydl_opts = {
        'outtmpl': song_file.replace(".wav", ""),
        'postprocessors': [{
            'key': 'FFmpegExtractAudio',
            'preferredcodec': 'wav',
        }]
    }
    with yt_dlp.YoutubeDL(ydl_opts) as ydl:
        ydl.download([youtube_link])
    return song_file


def process_audio(audio: tuple[int, np.ndarray]) -> tuple[int, np.ndarray]:
    return audio[0], convert_file(audio)


with gr.Blocks() as app:
    with gr.Column():
        youtube_link = gr.Textbox(label="YouTube Link", value="https://www.youtube.com/watch?v=YmJIccPWnEk")
        download_button = gr.Button("Download")
        audio_input = gr.Audio(label="Upload Audio File", type="numpy")
        process_button = gr.Button("Process Audio")
        audio_output = gr.Audio(label="Derivative Audio Output")


        def download_audio(youtube_link: str):
            song_file = process_youtube_link(youtube_link)
            sample_rate, audio_data = process_audio_file(song_file)
            return sample_rate, audio_data


        def process_audio_input(audio):
            sample_rate, processed_audio = process_audio(audio)
            return sample_rate, processed_audio


        download_button.click(download_audio, inputs=youtube_link, outputs=[audio_input])
        process_button.click(process_audio_input, inputs=audio_input, outputs=audio_output)

if __name__ == "__main__":
    app.launch()