File size: 2,055 Bytes
77f0587
f52579e
 
77f0587
4d0fc4b
 
f52579e
4d0fc4b
f52579e
 
 
 
9b1d24e
f52579e
77f0587
f52579e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f14a1c1
f52579e
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import re
import unidecode
import yt_dlp
import os

# Function to clean the string for file naming
def cleanString(string):
  clean_string = unidecode.unidecode(string)
  clean_string = re.sub(r'[^\w\s]', '', clean_string)
  clean_string = clean_string.replace(" ", "_")
  return clean_string.lower()

# Function to download audio from YouTube
def download_audio(url):
  path_to_folder_audio_mp3 = "./"
  ydl_opts = {
      'format': 'bestaudio/best',
      'outtmpl': f'{path_to_folder_audio_mp3}%(title)s.%(ext)s',
      'postprocessors': [{
          'key': 'FFmpegExtractAudio',
          'preferredcodec': 'mp3',
          'preferredquality': '192',
      }],
      'noplaylist': True,  # Avoid downloading playlists
  }

  with yt_dlp.YoutubeDL(ydl_opts) as ydl:
      info_dict = ydl.extract_info(url, download=True)
      video_title = info_dict['title']

      # Clean the title for the filename
      new_local_link = cleanString(video_title) + ".mp3"
      original_file_path = os.path.join(path_to_folder_audio_mp3, f"{video_title}.mp3")

      # Rename the audio file if it exists
      if os.path.exists(original_file_path):
          os.rename(original_file_path, os.path.join(path_to_folder_audio_mp3, new_local_link))

      # Get the final file path
      file_path = os.path.join(path_to_folder_audio_mp3, new_local_link)

  return file_path, file_path

# Gradio interface
with gr.Blocks() as demo:
  gr.Markdown("<h1><center>Free YouTube URL Video-to-Audio</center></h1>")
  gr.Markdown("<center>Enter the link of any YouTube video to generate its mp3 audio file.</center>")
  
  input_text_url = gr.Textbox(placeholder='YouTube video URL', label='YouTube URL')
  result_button_audio = gr.Button('Get Audio File')
  output_audio_file = gr.File(label='MP3 Audio File')
  output_audio_play = gr.Audio(type="filepath", label="Listen to Audio")
  
  result_button_audio.click(download_audio, inputs=input_text_url, outputs=[output_audio_file, output_audio_play])

# Launch the Gradio app
demo.queue().launch(debug=True)