Kryptone commited on
Commit
ca6924e
·
verified ·
1 Parent(s): e39b309

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +6 -308
app.py CHANGED
@@ -1,108 +1,7 @@
1
- import gradio as gr, glob, os, auditok, zipfile, wave, pytube.exceptions, urllib.error, requests, json, traceback, yt_dlp, tempfile
2
- from pytube import YouTube
3
  from moviepy.editor import *
4
  from pydub import AudioSegment
5
 
6
-
7
- def download_video(url, download_as, use_ytdlp):
8
- if use_ytdlp == True:
9
- try:
10
- ydl_opts = {
11
- 'format': f"{download_as}/bestaudio/best",
12
- 'postprocessors': [{
13
- 'key': 'FFmpegExtractAudio',
14
- 'preferredcodec': download_as,
15
- }]
16
- }
17
- with yt_dlp.YoutubeDL(ydl_opts) as ydl:
18
- ydl.download(url)
19
- for i in glob.glob(f"*.{download_as}"):
20
- if os.path.exists(i):
21
- os.rename(i, f"output.{download_as}")
22
- return "Finished downloading! Please proceed to next tab."
23
- except:
24
- raise gr.Error(traceback.format_exc())
25
- else:
26
- try:
27
- yt = YouTube(url)
28
- except pytube.exceptions.RegexMatchError:
29
- raise gr.Error("URL not valid or is empty! Please fix the link or enter one!")
30
- except urllib.error.HTTPError as not_ok:
31
- raise gr.Error(f"Recieved {not_ok}")
32
- except pytube.exceptions.AgeRestrictedError:
33
- raise gr.Error("The video you inputted is age-restricted! Please try another link.")
34
- video = yt.streams.get_highest_resolution()
35
- video.download()
36
- video_path = f"{video.default_filename}"
37
- video_clip = VideoFileClip(video_path)
38
- audio_clip = video_clip.audio
39
- if download_as == "wav":
40
- audio_clip.write_audiofile("output.wav")
41
- elif download_as == "mp3":
42
- audio_clip.write_audiofile("output.mp3")
43
- audio_clip.close()
44
- video_clip.close()
45
- for removalmp4 in glob.glob("*.mp4"):
46
- os.remove(removalmp4)
47
- return "Finished downloading! Please proceed to next tab."
48
-
49
- def split_audio_from_yt_video(mindur, maxdur, name_for_split_files, show_amount_of_files_and_file_dur):
50
- if show_amount_of_files_and_file_dur == True:
51
- gr.Warning(f"show_amount_of_files_and_file_dur set to True. This will take longer if your audio file is long.")
52
- if not os.path.exists("output.mp3") and not os.path.exists("output.wav"):
53
- raise gr.Error("Neither output.mp3 or output.wav exist! Did the video download correctly?")
54
- if mindur == maxdur:
55
- raise gr.Error(f"Cannot split mindur={mindur} and maxdur={maxdur}, min and max are the same number.")
56
- elif mindur > maxdur:
57
- raise gr.Error(f"Cannot split mindur={mindur} and maxdur={maxdur}, mindur is higher than maxdur.")
58
- elif name_for_split_files == None:
59
- raise gr.Error("Split files name cannot be empty!")
60
- else:
61
- audio_path = "output.wav" if not os.path.exists("output.mp3") else "output.mp3"
62
- audio_regions = auditok.split(
63
- audio_path,
64
- min_dur=mindur,
65
- max_dur=maxdur,
66
- max_silence=0.3,
67
- energy_threshold=45
68
- )
69
- os.remove(audio_path)
70
- for i, r in enumerate(audio_regions):
71
- filename = r.save(f"{name_for_split_files}-{i+1}.wav")
72
- for f in sorted(glob.glob("*.wav")):
73
- audio_files = glob.glob("*.wav")
74
- zip_file_name = "audio_files.zip"
75
- with zipfile.ZipFile(zip_file_name, "w") as zip_file:
76
- for audio_file in audio_files:
77
- zip_file.write(audio_file, os.path.basename(audio_file))
78
- if show_amount_of_files_and_file_dur == False:
79
- for file2 in glob.glob("*.wav"):
80
- os.remove(file2)
81
- return "Files split successfully!\nCheck below for zipped files.", zip_file_name
82
- elif show_amount_of_files_and_file_dur == True:
83
- largest_file = ("", 0)
84
- total_files = 0
85
- total_length = 0.0
86
- for file_name in glob.glob("*.wav"):
87
- file_path = os.path.join(os.getcwd(), file_name)
88
- if file_path.lower().endswith(".wav"):
89
- try:
90
- with wave.open(file_path, 'r') as audio_file:
91
- frames = audio_file.getnframes()
92
- rate = audio_file.getframerate()
93
- duration = frames / float(rate)
94
- file_size = os.path.getsize(file_path)
95
- if file_size > largest_file[1]:
96
- largest_file = (file_name, file_size)
97
- total_length += duration
98
- total_files += 1
99
- except wave.Error as e:
100
- raise gr.Error(f"Error reading file: {e}")
101
- length_mins = total_length / 60
102
- for file2 in glob.glob("*.wav"):
103
- os.remove(file2)
104
- return f"Files split successfully!\nCheck below for zipped files.\n\n{total_files} files created, {length_mins:.2f} minutes total.", zip_file_name
105
-
106
  def split_wav_or_mp3_file(audiofileuploader, mindur2, maxdur2, name_for_split_files2, strict):
107
  if audiofileuploader == None:
108
  raise gr.Error("Audio file cannot be empty!")
@@ -135,50 +34,6 @@ def split_wav_or_mp3_file(audiofileuploader, mindur2, maxdur2, name_for_split_fi
135
  os.remove(file2)
136
  return f"File split successfully!\nCheck below for zipped files.\nAmount created: {len(audio_files)}", zip_file_name2
137
 
138
- def download_video_as_audio_only(yt_video, audio_output_format):
139
- try:
140
- ydl_opts = {
141
- 'format': f"{audio_output_format}/bestaudio/best",
142
- 'postprocessors': [{
143
- 'key': 'FFmpegExtractAudio',
144
- 'preferredcodec': "mp3"
145
- }]
146
- }
147
- with yt_dlp.YoutubeDL(ydl_opts) as ydl:
148
- ydl.download(yt_video)
149
- except pytube.exceptions.RegexMatchError:
150
- raise gr.Error("URL not valid or is empty! Please fix the link or enter one!")
151
- except urllib.error.HTTPError as not_ok:
152
- raise gr.Error(f"Recieved {not_ok}")
153
- except pytube.exceptions.AgeRestrictedError:
154
- raise gr.Error("The video you inputted is age-restricted! Please try another link.")
155
- #video = yt.streams.get_audio_only()
156
- #video.download()
157
- #video_path = f"{video.default_filename}"
158
- #video_clip = VideoFileClip(video_path)
159
- #audio_clip = video_clip.audio
160
- #if audio_output_format == "wav":
161
- # audio_clip.write_audiofile("output.wav")
162
- #elif audio_output_format == "mp3":
163
- # audio_clip.write_audiofile("output.mp3")
164
- #audio_clip.close()
165
- #video_clip.close()
166
- #for mp4remove in glob.glob("*.mp4"):
167
- # os.remove(mp4remove)
168
- single_zip_name = "only_audio.zip"
169
- audio_files = glob.glob("*.wav") if audio_output_format == "wav" else glob.glob("*.mp3")
170
- with zipfile.ZipFile(single_zip_name, 'w') as zip_file:
171
- for audio_file in audio_files:
172
- zip_file.write(audio_file, os.path.basename(audio_file))
173
- for outputwavremoval in glob.glob("*.wav"):
174
- if os.path.exists(outputwavremoval):
175
- os.remove(outputwavremoval)
176
- for outputmp3removal in glob.glob("*.mp3"):
177
- if os.path.exists(outputmp3removal):
178
- os.remove(outputmp3removal)
179
- #return f"Done! Download the zip file below! This only contains the audio file.\n\nYou have downloaded a video.", single_zip_name
180
- return "Done! Download the zip file below! This only contains the audio file.", single_zip_name
181
-
182
  def mp4_to_wav_or_mp3(mp4fileuploader, file_format):
183
  if mp4fileuploader == None:
184
  raise gr.Error("Input cannot be empty!")
@@ -259,50 +114,6 @@ def mvsep_download_separated_audio(hash_textbox):
259
  return json.dumps(urls, indent=4)
260
  except requests.exceptions.JSONDecodeError:
261
  return gr.Info("Nothing to download yet. Check back later.")
262
-
263
- def mvsep_yt_link_request(mvsep_key2, sep_dropdown2, yt_link):
264
- try:
265
- ydl_opts = {
266
- 'format': "mp3/bestaudio/best",
267
- 'postprocessors': [{
268
- 'key': 'FFmpegExtractAudio',
269
- 'preferredcodec': "mp3"
270
- }]
271
- }
272
- with yt_dlp.YoutubeDL(ydl_opts) as ydl:
273
- ydl.download(yt_link)
274
- except pytube.exceptions.RegexMatchError:
275
- raise gr.Error("URL not valid or is empty! Please fix the link or enter one!")
276
- except urllib.error.HTTPError as not_ok:
277
- raise gr.Error(f"Recieved {not_ok}")
278
- except pytube.exceptions.AgeRestrictedError:
279
- raise gr.Error("The video you inputted is age-restricted! Please try another link.")
280
- #video = yt.streams.get_highest_resolution()
281
- #video.download()
282
- #video_path = f"{video.default_filename}"
283
- #video_clip = VideoFileClip(video_path)
284
- #audio_clip = video_clip.audio
285
- #audio_clip.write_audiofile("output.mp3")
286
- #audio_clip.close()
287
- #video_clip.close()
288
- for rename in glob.glob("*.mp3"):
289
- if os.path.exists(rename):
290
- os.rename(rename, "output.mp3")
291
- for removalmp4 in glob.glob("*.mp4"):
292
- os.remove(removalmp4)
293
-
294
- url = "https://mvsep.com/api/separation/create"
295
- files = {
296
- "audiofile": open("output.mp3", 'rb')
297
- }
298
- data = {
299
- "api_token": mvsep_key2,
300
- "sep_type": sep_dropdown2
301
- }
302
- r = requests.post(url, files=files, data=data)
303
- json_format = r.json()
304
- hash_val = json_format['data']['hash']
305
- return f"Request sent successfully! Your hash is: {hash_val}\n\nUse the next tab to check the status of your request."
306
 
307
  def split_by_dur(file_upload, dur_to_cut):
308
  if file_upload == None:
@@ -322,6 +133,9 @@ with gr.Blocks(theme='sudeepshouche/minimalist', title="Global Dataset Maker") a
322
  gr.HTML(
323
  "<h1> Welcome to the Cafeteria (formally GDMGS)!</h1>"
324
  )
 
 
 
325
  gr.Markdown("## Duplicate this space if you want to make your own changes!")
326
  gr.HTML(
327
  """<p style="margin:5px auto;display: flex;justify-content: left;">
@@ -335,35 +149,6 @@ with gr.Blocks(theme='sudeepshouche/minimalist', title="Global Dataset Maker") a
335
  "<h2> This Space's storage is ephemeral, meaning all audio files are visible to you only. I do not have access to any of this, nor would I do anything with it anyway. </h2>"
336
  )
337
  with gr.Tabs():
338
- with gr.TabItem("Download Video"):
339
- with gr.Row():
340
- with gr.Column():
341
- with gr.Row():
342
- gr.Markdown("# Currently broken. Use Stacher in the meantime.")
343
- #url = gr.Textbox(label="URL")
344
- #download_as = gr.Radio(["wav", "mp3"], label="Audio format output", value="wav", info="What should the audio format be output as?")
345
- #use_ytdlp = gr.Checkbox(False, label="Use yt_dlp instead of pytube?", info="Sometimes Pytube refuses to download a video. If that happens, check this box to download using yt_dlp instead.")
346
- #convertion = gr.Button("Download", variant='primary')
347
- #convertion.click(
348
- # fn=download_video,
349
- # inputs=[url, download_as, use_ytdlp],
350
- # outputs=gr.Text(label="Output")
351
- #)
352
- with gr.TabItem("Split audio files"):
353
- with gr.Row():
354
- with gr.Column():
355
- with gr.Row():
356
- gr.Markdown("# Offline due to the download video section not working. If you have an audio file however, go to the 'Misc Tools' tab to split that instead.")
357
- #mindur = gr.Number(label="Min duration", minimum=1, maximum=10, value=1)
358
- #maxdur = gr.Number(label="Max duration", minimum=1, maximum=10, value=5)
359
- #name_for_split_files = gr.Textbox(label="Name for split files")
360
- #show_amount_of_files_and_file_dur = gr.Checkbox(False, label="Show total amount of files and duration?")
361
- #splitbtn = gr.Button("Split", variant='primary')
362
- #splitbtn.click(
363
- # split_audio_from_yt_video,
364
- # inputs=[mindur, maxdur, name_for_split_files, show_amount_of_files_and_file_dur],
365
- # outputs=[gr.Text(label="Output"), gr.File(label="Zipped files")]
366
- #)
367
  with gr.TabItem("Misc tools"):
368
  with gr.Tab("File splitter"):
369
  gr.Markdown("If you would rather split a single WAV or mp3 audio file, use this method instead.")
@@ -395,21 +180,6 @@ with gr.Blocks(theme='sudeepshouche/minimalist', title="Global Dataset Maker") a
395
  [file_upload, dur_to_cut],
396
  [gr.Text(label="Output"), gr.File(label="Trimmed audio")]
397
  )
398
-
399
- with gr.Tab("Audio only download"):
400
- gr.Markdown("If you want to download only the audio (to isolate bgm using UVR, etc), use this method, which will only extract audio and not split the audio.")
401
- gr.Markdown("# Currently broken. Use Stacher in the meantime.")
402
- #with gr.Row():
403
- # with gr.Column():
404
- # with gr.Row():
405
- # yt_video = gr.Textbox(label="URL")
406
- # audio_output_format = gr.Radio(["wav", "mp3"], value="wav", label="Download audio as:")
407
- # commence_download = gr.Button("Download", variant='primary')
408
- #commence_download.click(
409
- # download_video_as_audio_only,
410
- # [yt_video, audio_output_format],
411
- # [gr.Text(label="Output"), gr.File(label="Zipped audio file")]
412
- #)
413
  with gr.Tab("MP4 to mp3/wav converter"):
414
  gr.Markdown("If you have an mp4 file, you can convert it to mp3 or wav here. Only click the 'Remove file' button when done.")
415
  with gr.Row():
@@ -486,7 +256,7 @@ with gr.Blocks(theme='sudeepshouche/minimalist', title="Global Dataset Maker") a
486
  "45 - Bandit v2 (speech, music, effects)"
487
  ],
488
  max_choices=1,
489
- value="11 - Demucs3 Model B (vocals, drums, bass, other)",
490
  label="Model type:",
491
  interactive=True,
492
  type='index'
@@ -497,73 +267,6 @@ with gr.Blocks(theme='sudeepshouche/minimalist', title="Global Dataset Maker") a
497
  [mvsep_key, audio_file, sep_dropdown],
498
  [gr.Text(label="Output")]
499
  )
500
- with gr.Tab("Send Request via yt link"):
501
- gr.Markdown("## Currently broken. Use MVSEP's actual website in the meantime.")
502
- #with gr.Row():
503
- # with gr.Column():
504
- # with gr.Row():
505
- # mvsep_key2 = gr.Textbox(placeholder="Enter your MVSEP API key.", label="API key")
506
- # yt_link = gr.Textbox(label="YouTube link")
507
- # sep_dropdown2 = gr.Dropdown(
508
- # ["0 - spleeter (vocals, music)",
509
- # "1 - spleeter (vocals, drums, bass, other)",
510
- # "2 - spleeter (vocals, drums, bass, piano, other)",
511
- # "3 - unmix XL (vocals, drums, bass, other)",
512
- # "4 - unmix HQ (vocals, drums, bass, other)",
513
- # "5 - unmix SD (vocals, drums, bass, other)",
514
- # "6 - unmix SE (vocals, music)",
515
- # "7 - MDX A (vocals, drums, bass, other)",
516
- # "8 - MDX B (vocals, drums, bass, other)",
517
- # "9 - UVR HQ (vocals, music)",
518
- # "10 - Demucs3 Model A (vocals, drums, bass, other)",
519
- # "11 - Demucs3 Model B (vocals, drums, bass, other)",
520
- # "12 - MDX-B Karaoke (lead/back vocals)",
521
- # "13 - Demucs2 (vocals, drums, bass, other)",
522
- # "14 - Zero Shot (Query Based) (LQ)",
523
- # "15 - Danna sep (vocals, drums, bass, other)",
524
- # "16 - Byte Dance (vocals, drums, bass, other)",
525
- # "17 - UVRv5 Demucs (vocals, music)",
526
- # "18 - MVSep DNR (music, sfx, speech)",
527
- # "19 - MVSep Vocal Model (vocals, music)",
528
- # "20 - Demucs4 HT (vocals, drums, bass, other)",
529
- # "--------------------------------------------------------------------------------------------------",
530
- # "22 - FoxJoy Reverb Removal (other)",
531
- # "23 - MDX B (vocals, instrumental)",
532
- # "24 - MVSep Demucs4HT DNR (dialog, sfx, music)",
533
- # "25 - MDX23C (vocals, instrumental)",
534
- # "26 - Ensemble (vocals, instrumental) [PREMIUM ONLY]",
535
- # "27 - Demucs4 Vocals 2023 (vocals, instrumental)",
536
- # "28 - Ensemble (vocals, instrumental, bass, drums, other) [PREMIUM ONLY]",
537
- # "29 - MVSep Piano (piano, other)",
538
- # "30 - Ensemble All-In (vocals, bass, drums, piano, guitar, lead/back vocals, other) [PREMIUM ONLY]",
539
- # "31 - MVSep Guitar (guitar, other)",
540
- # "-------------------------------------------------------------------------------------------------",
541
- # "33 - Vit Large 23 (vocals, instrum)",
542
- # "34 - MVSep Crowd removal (crowd, other)",
543
- # "35 - MVSep MelBand Roformer (vocals, instrum)",
544
- # "36 - BandIt Plus (speech, music, effects)",
545
- # "37 - DrumSep (kick, snare, cymbals, toms)",
546
- # "38 - LarsNet (kick, snare, cymbals, toms, hihat)",
547
- # "39 - Whisper (extract text from audio)",
548
- # "40 - BS Roformer (vocals, instrumental)",
549
- # "41 - MVSep Bass (bass, other)",
550
- # "42 - MVSep MultiSpeaker (MDX23C)",
551
- # "43 - MVSEP Multichannel BS (vocals, inst)",
552
- # "44 - MVSep Drums (drums, other)",
553
- # "45 - Bandit v2 (speech, music, effects)"
554
- # ],
555
- # max_choices=1,
556
- # value="11 - Demucs3 Model B (vocals, drums, bass, other)",
557
- # label="Model type:",
558
- # interactive=True,
559
- # type='index'
560
- # )
561
- # send_req2 = gr.Button("Send request", variant='primary')
562
- # send_req2.click(
563
- # mvsep_yt_link_request,
564
- # [mvsep_key2, sep_dropdown2, yt_link],
565
- # [gr.Text(label="Output")]
566
- # )
567
  with gr.Tab("Get status of request"):
568
  with gr.Row():
569
  with gr.Column():
@@ -583,12 +286,7 @@ with gr.Blocks(theme='sudeepshouche/minimalist', title="Global Dataset Maker") a
583
  )
584
 
585
  with gr.TabItem("Changelog"):
 
586
  gr.Markdown("v0.99.9 - Added new tool: Split audio file by duration.")
587
- gr.Markdown("v0.99.8 - Added new MVSep models.")
588
- gr.Markdown("v0.99.7 - Temporarily fixed an issue causing a 400 error to happen whenever a youtube url was placed.")
589
- gr.Markdown("v0.99.6 - Added a yt link request method for MVSEP.")
590
- gr.Markdown("v0.99.5 - Added bug fixes and Dropdown instead of button for MVSEP.")
591
- gr.Markdown("v0.99.4 - Added a button to display the available models for MVSEP.")
592
- gr.Markdown("v0.99.3 - Added MVSEP in Misc Tools.")
593
 
594
  app.launch()
 
1
+ import gradio as gr, glob, os, auditok, zipfile, requests, json, traceback, tempfile
 
2
  from moviepy.editor import *
3
  from pydub import AudioSegment
4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
  def split_wav_or_mp3_file(audiofileuploader, mindur2, maxdur2, name_for_split_files2, strict):
6
  if audiofileuploader == None:
7
  raise gr.Error("Audio file cannot be empty!")
 
34
  os.remove(file2)
35
  return f"File split successfully!\nCheck below for zipped files.\nAmount created: {len(audio_files)}", zip_file_name2
36
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
  def mp4_to_wav_or_mp3(mp4fileuploader, file_format):
38
  if mp4fileuploader == None:
39
  raise gr.Error("Input cannot be empty!")
 
114
  return json.dumps(urls, indent=4)
115
  except requests.exceptions.JSONDecodeError:
116
  return gr.Info("Nothing to download yet. Check back later.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
117
 
118
  def split_by_dur(file_upload, dur_to_cut):
119
  if file_upload == None:
 
133
  gr.HTML(
134
  "<h1> Welcome to the Cafeteria (formally GDMGS)!</h1>"
135
  )
136
+ gr.HTML(
137
+ "<h2> Currently, no yt functions are working right now, so they have been deleted. Please use this tool to split an audio file, convert an mp4 file to mp3 or wav, or use mvsep."
138
+ )
139
  gr.Markdown("## Duplicate this space if you want to make your own changes!")
140
  gr.HTML(
141
  """<p style="margin:5px auto;display: flex;justify-content: left;">
 
149
  "<h2> This Space's storage is ephemeral, meaning all audio files are visible to you only. I do not have access to any of this, nor would I do anything with it anyway. </h2>"
150
  )
151
  with gr.Tabs():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
152
  with gr.TabItem("Misc tools"):
153
  with gr.Tab("File splitter"):
154
  gr.Markdown("If you would rather split a single WAV or mp3 audio file, use this method instead.")
 
180
  [file_upload, dur_to_cut],
181
  [gr.Text(label="Output"), gr.File(label="Trimmed audio")]
182
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
183
  with gr.Tab("MP4 to mp3/wav converter"):
184
  gr.Markdown("If you have an mp4 file, you can convert it to mp3 or wav here. Only click the 'Remove file' button when done.")
185
  with gr.Row():
 
256
  "45 - Bandit v2 (speech, music, effects)"
257
  ],
258
  max_choices=1,
259
+ value="45 - Bandit v2 (speech, music, effects)",
260
  label="Model type:",
261
  interactive=True,
262
  type='index'
 
267
  [mvsep_key, audio_file, sep_dropdown],
268
  [gr.Text(label="Output")]
269
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
270
  with gr.Tab("Get status of request"):
271
  with gr.Row():
272
  with gr.Column():
 
286
  )
287
 
288
  with gr.TabItem("Changelog"):
289
+ gr.Markdown("v1 - Not the most exciting v1 release. **Removed yt functions as they are no longer working.**")
290
  gr.Markdown("v0.99.9 - Added new tool: Split audio file by duration.")
 
 
 
 
 
 
291
 
292
  app.launch()