sudo-soldier commited on
Commit
147c80a
·
verified ·
1 Parent(s): 5e89487

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +43 -51
app.py CHANGED
@@ -1,71 +1,72 @@
1
  import os
2
- import gradio as gr
3
  import yt_dlp
4
- from pydub import AudioSegment
5
  import re
6
  import subprocess
 
7
 
8
 
9
- if not os.path.exists("downloads"):
10
- os.makedirs("downloads")
11
 
12
  def sanitize_filename(filename):
13
- """Sanitize filenames to avoid special characters."""
14
  return re.sub(r'[^a-zA-Z0-9_-]', '_', filename)
15
 
16
  def process_youtube_or_audio(url, recorded_audio, start_time, end_time):
 
17
  try:
18
- filename = None
19
- song_name = None
20
 
21
-
22
  if url:
23
  ydl_opts = {
24
  'format': 'bestaudio/best',
25
- 'outtmpl': 'downloads/%(id)s.%(ext)s',
26
  'cookiefile': 'cookies.txt'
27
  }
28
  with yt_dlp.YoutubeDL(ydl_opts) as ydl:
29
  info = ydl.extract_info(url, download=True)
30
- filename = os.path.join('downloads', f"{info['id']}.webm")
31
  song_name = sanitize_filename(info['title'])
32
 
33
-
34
- elif recorded_audio:
35
- filename = recorded_audio
36
  song_name = "recorded_audio"
37
-
 
38
  if not filename or not os.path.exists(filename):
39
  return None, None
40
 
41
-
42
- audio = AudioSegment.from_file(filename)
43
 
44
-
45
- start_time_ms = start_time * 1000
46
- end_time_ms = end_time * 1000
47
 
48
 
49
- start_time_ms = max(0, min(start_time_ms, len(audio)))
50
- end_time_ms = max(start_time_ms, min(end_time_ms, len(audio)))
51
 
52
-
53
- trimmed_audio = audio[start_time_ms:end_time_ms]
54
 
55
-
56
  mp3_filename = f"downloads/{song_name}.mp3"
57
  trimmed_audio.export(mp3_filename, format="mp3")
58
 
59
-
60
  m4a_filename = f"downloads/{song_name}.m4a"
61
- subprocess.run([
62
- 'ffmpeg', '-i', mp3_filename, '-vn', '-acodec', 'aac', '-b:a', '192k', m4a_filename
63
- ], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
 
 
 
 
64
 
 
65
  m4r_filename = f"downloads/{song_name}.m4r"
66
  os.rename(m4a_filename, m4r_filename)
67
 
68
- return os.path.abspath(mp3_filename), os.path.abspath(m4r_filename)
69
 
70
  except Exception as e:
71
  print(f"Error: {e}")
@@ -74,24 +75,17 @@ def process_youtube_or_audio(url, recorded_audio, start_time, end_time):
74
 
75
  with gr.Blocks(css="""
76
  body { font-family: Arial, sans-serif; text-align: center; }
77
- .light-btn {
78
- background-color: #ADD8E6;
79
- color: #333;
80
- border: 2px solid #ccc;
81
- padding: 10px 20px;
82
- font-size: 16px;
83
- cursor: pointer;
84
- }
85
  .light-btn:hover { background-color: #87CEFA; }
86
  """) as interface:
87
 
88
  gr.HTML("""
89
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
90
- <h1><i class="fas fa-music"></i>&nbsp;PYTR</h1>
91
- <p>Python YouTube Ringtones. Enter a YouTube URL or record audio to create ringtones.</p>
92
  <p>
93
- <a href="https://ringtones.JesseJesse.xyz" target="_blank">slim UI</a>&nbsp;&nbsp;&nbsp;
94
- <a href="https://pub-c1de1cb456e74d6bbbee111ba9e6c757.r2.dev/iphone.png" target="_blank">iPhone xfers</a>&nbsp;&nbsp;&nbsp;
95
  <a href="https://youtube.com" target="_blank">YouTube</a>
96
  </p>
97
  """)
@@ -105,26 +99,24 @@ with gr.Blocks(css="""
105
  gr.HTML('<label><i class="fas fa-microphone"></i>&nbsp;Record Audio</label>')
106
  audio_record = gr.Audio(sources=["microphone"], type="filepath", show_label=False)
107
 
108
- with gr.Row():
109
- gr.HTML("<h3>Trim Audio (Optional)</h3>")
110
 
111
  with gr.Row():
112
  start_time = gr.Slider(0, 20, value=0, label="Start Time (seconds)")
113
  end_time = gr.Slider(1, 20, value=20, label="End Time (seconds)")
114
 
115
- with gr.Row():
116
- process_button = gr.Button("Create Ringtones", elem_classes="light-btn")
117
 
118
  with gr.Row():
119
  with gr.Column(scale=1, min_width=250):
120
- gr.HTML('<label>&nbsp;Android Ringtone</label>')
121
- mp3_download = gr.File(label="Android")
122
- android_instructions = gr.Textbox(label="Install", placeholder="Copy the mp3 file to the ringtones folder", lines=1)
123
 
124
  with gr.Column(scale=1, min_width=250):
125
- gr.HTML('<label>&nbsp;iPhone Ringtone</label>')
126
- iphone_ringtone = gr.File(label="Apple")
127
- iphone_instructions = gr.Textbox(label="Install", placeholder="Open GarageBand on your iPhone. Create a new project with Audio Recorder. Tap on the Tracks view (≡ icon in top-left). Tap the Loop icon (top-right corner). Select 'Files', then tap 'Browse items from the Files app'. Locate your .m4r file and tap it to import into GarageBand.", lines=4)
128
 
129
  process_button.click(process_youtube_or_audio, inputs=[youtube_url, audio_record, start_time, end_time], outputs=[mp3_download, iphone_ringtone])
130
 
 
1
  import os
 
2
  import yt_dlp
3
+ import gradio as gr
4
  import re
5
  import subprocess
6
+ from pydub import AudioSegment
7
 
8
 
9
+ os.makedirs("downloads", exist_ok=True)
 
10
 
11
  def sanitize_filename(filename):
12
+ """Sanitize filenames by replacing special characters."""
13
  return re.sub(r'[^a-zA-Z0-9_-]', '_', filename)
14
 
15
  def process_youtube_or_audio(url, recorded_audio, start_time, end_time):
16
+ """Downloads or processes audio, trims it, and exports ringtones."""
17
  try:
18
+ filename, song_name = None, None
 
19
 
20
+
21
  if url:
22
  ydl_opts = {
23
  'format': 'bestaudio/best',
24
+ 'outtmpl': 'downloads/%(title)s.%(ext)s',
25
  'cookiefile': 'cookies.txt'
26
  }
27
  with yt_dlp.YoutubeDL(ydl_opts) as ydl:
28
  info = ydl.extract_info(url, download=True)
29
+ filename = ydl.prepare_filename(info)
30
  song_name = sanitize_filename(info['title'])
31
 
32
+
33
+ elif recorded_audio and isinstance(recorded_audio, dict):
34
+ filename = recorded_audio["name"]
35
  song_name = "recorded_audio"
36
+
37
+
38
  if not filename or not os.path.exists(filename):
39
  return None, None
40
 
 
 
41
 
42
+ audio = AudioSegment.from_file(filename)
43
+ start_ms, end_ms = int(start_time * 1000), int(end_time * 1000)
 
44
 
45
 
46
+ start_ms = max(0, min(start_ms, len(audio)))
47
+ end_ms = max(start_ms, min(end_ms, len(audio)))
48
 
49
+ trimmed_audio = audio[start_ms:end_ms]
 
50
 
51
+
52
  mp3_filename = f"downloads/{song_name}.mp3"
53
  trimmed_audio.export(mp3_filename, format="mp3")
54
 
55
+
56
  m4a_filename = f"downloads/{song_name}.m4a"
57
+ result = subprocess.run([
58
+ 'ffmpeg', '-y', '-i', mp3_filename, '-vn', '-acodec', 'aac', '-b:a', '192k', m4a_filename
59
+ ], capture_output=True, text=True)
60
+
61
+ if result.returncode != 0 or not os.path.exists(m4a_filename):
62
+ print("FFmpeg Error:", result.stderr)
63
+ return mp3_filename, None #
64
 
65
+
66
  m4r_filename = f"downloads/{song_name}.m4r"
67
  os.rename(m4a_filename, m4r_filename)
68
 
69
+ return mp3_filename, m4r_filename
70
 
71
  except Exception as e:
72
  print(f"Error: {e}")
 
75
 
76
  with gr.Blocks(css="""
77
  body { font-family: Arial, sans-serif; text-align: center; }
78
+ .light-btn { background-color: #ADD8E6; color: #333; border: 2px solid #ccc; padding: 10px 20px; font-size: 16px; cursor: pointer; }
 
 
 
 
 
 
 
79
  .light-btn:hover { background-color: #87CEFA; }
80
  """) as interface:
81
 
82
  gr.HTML("""
83
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
84
+ <h1><i class="fas fa-music"></i>&nbsp;PYTR - Python YouTube Ringtones</h1>
85
+ <p>Enter a YouTube URL or record audio to create ringtones.</p>
86
  <p>
87
+ <a href="https://ringtones.JesseJesse.xyz" target="_blank">Ringtones API</a>&nbsp;&nbsp;&nbsp;
88
+ <a href="https://pub-c1de1cb456e74d6bbbee111ba9e6c757.r2.dev/iphone.png" target="_blank">iPhone Transfers</a>&nbsp;&nbsp;&nbsp;
89
  <a href="https://youtube.com" target="_blank">YouTube</a>
90
  </p>
91
  """)
 
99
  gr.HTML('<label><i class="fas fa-microphone"></i>&nbsp;Record Audio</label>')
100
  audio_record = gr.Audio(sources=["microphone"], type="filepath", show_label=False)
101
 
102
+ gr.HTML("<h3>Trim Audio</h3>")
 
103
 
104
  with gr.Row():
105
  start_time = gr.Slider(0, 20, value=0, label="Start Time (seconds)")
106
  end_time = gr.Slider(1, 20, value=20, label="End Time (seconds)")
107
 
108
+ process_button = gr.Button("Create Ringtones", elem_classes="light-btn")
 
109
 
110
  with gr.Row():
111
  with gr.Column(scale=1, min_width=250):
112
+ gr.HTML('<label>Android Ringtone</label>')
113
+ mp3_download = gr.File(label="Android", interactive=False)
114
+ gr.Textbox(label="Install", value="Copy the MP3 file to your ringtones folder", lines=1, interactive=False)
115
 
116
  with gr.Column(scale=1, min_width=250):
117
+ gr.HTML('<label>iPhone Ringtone</label>')
118
+ iphone_ringtone = gr.File(label="Apple", interactive=False)
119
+ gr.Textbox(label="Install", value="Open GarageBand on your iPhone, import the .m4r file, and set it as a ringtone.", lines=1, interactive=False)
120
 
121
  process_button.click(process_youtube_or_audio, inputs=[youtube_url, audio_record, start_time, end_time], outputs=[mp3_download, iphone_ringtone])
122