Riko arudianshā commited on
Commit
dad5837
1 Parent(s): b4a2acd

Create main.py

Browse files
Files changed (1) hide show
  1. main.py +145 -0
main.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import gc
3
+ import hashlib
4
+ import json
5
+ import os
6
+ import shlex
7
+ import subprocess
8
+ from contextlib import suppress
9
+ from urllib.parse import urlparse, parse_qs
10
+
11
+ import gradio as gr
12
+ import librosa
13
+ import numpy as np
14
+ import soundfile as sf
15
+ import sox
16
+ import yt_dlp
17
+ from pedalboard import Pedalboard, Reverb, Compressor, HighpassFilter
18
+ from pedalboard.io import AudioFile
19
+ from pydub import AudioSegment
20
+
21
+
22
+ output_dir = os.path.join(BASE_DIR, 'song_output')
23
+
24
+
25
+ def get_youtube_video_id(url, ignore_playlist=True):
26
+ """
27
+ Examples:
28
+ http://youtu.be/SA2iWivDJiE
29
+ http://www.youtube.com/watch?v=_oPAwA_Udwc&feature=feedu
30
+ http://www.youtube.com/embed/SA2iWivDJiE
31
+ http://www.youtube.com/v/SA2iWivDJiE?version=3&hl=en_US
32
+ """
33
+ query = urlparse(url)
34
+ if query.hostname == 'youtu.be':
35
+ if query.path[1:] == 'watch':
36
+ return query.query[2:]
37
+ return query.path[1:]
38
+
39
+ if query.hostname in {'www.youtube.com', 'youtube.com', 'music.youtube.com'}:
40
+ if not ignore_playlist:
41
+ # use case: get playlist id not current video in playlist
42
+ with suppress(KeyError):
43
+ return parse_qs(query.query)['list'][0]
44
+ if query.path == '/watch':
45
+ return parse_qs(query.query)['v'][0]
46
+ if query.path[:7] == '/watch/':
47
+ return query.path.split('/')[1]
48
+ if query.path[:7] == '/embed/':
49
+ return query.path.split('/')[2]
50
+ if query.path[:3] == '/v/':
51
+ return query.path.split('/')[2]
52
+
53
+ # returns None for invalid YouTube url
54
+ return None
55
+
56
+
57
+ def yt_download(link):
58
+ ydl_opts = {
59
+ 'format': 'bestaudio',
60
+ 'outtmpl': '%(title)s',
61
+ 'nocheckcertificate': True,
62
+ 'ignoreerrors': True,
63
+ 'no_warnings': True,
64
+ 'quiet': True,
65
+ 'extractaudio': True,
66
+ 'postprocessors': [{'key': 'FFmpegExtractAudio', 'preferredcodec': 'mp3'}],
67
+ }
68
+ with yt_dlp.YoutubeDL(ydl_opts) as ydl:
69
+ result = ydl.extract_info(link, download=True)
70
+ download_path = ydl.prepare_filename(result, outtmpl='%(title)s.mp3')
71
+
72
+ return download_path
73
+
74
+
75
+ def raise_exception(error_msg, is_webui):
76
+ if is_webui:
77
+ raise gr.Error(error_msg)
78
+ else:
79
+ raise Exception(error_msg)
80
+
81
+
82
+
83
+ display_progress('[~] Applying audio effects to Vocals...', 0.8, is_webui, progress)
84
+ ai_vocals_mixed_path = add_audio_effects(ai_vocals_path, reverb_rm_size, reverb_wet, reverb_dry, reverb_damping)
85
+
86
+ if pitch_change_all != 0:
87
+ display_progress('[~] Applying overall pitch change', 0.85, is_webui, progress)
88
+ instrumentals_path = pitch_shift(instrumentals_path, pitch_change_all)
89
+ backup_vocals_path = pitch_shift(backup_vocals_path, pitch_change_all)
90
+
91
+ display_progress('[~] Combining AI Vocals and Instrumentals...', 0.9, is_webui, progress)
92
+ combine_audio([ai_vocals_mixed_path, backup_vocals_path, instrumentals_path], ai_cover_path, main_gain, backup_gain, inst_gain, output_format)
93
+
94
+ if not keep_files:
95
+ display_progress('[~] Removing intermediate audio files...', 0.95, is_webui, progress)
96
+ intermediate_files = [vocals_path, main_vocals_path, ai_vocals_mixed_path]
97
+ if pitch_change_all != 0:
98
+ intermediate_files += [instrumentals_path, backup_vocals_path]
99
+ for file in intermediate_files:
100
+ if file and os.path.exists(file):
101
+ os.remove(file)
102
+
103
+ return ai_cover_path
104
+
105
+ except Exception as e:
106
+ raise_exception(str(e), is_webui)
107
+
108
+
109
+ if __name__ == '__main__':
110
+ parser = argparse.ArgumentParser(description='Generate a AI cover song in the song_output/id directory.', add_help=True)
111
+ parser.add_argument('-i', '--song-input', type=str, required=True, help='Link to a YouTube video or the filepath to a local mp3/wav file to create an AI cover of')
112
+ parser.add_argument('-dir', '--rvc-dirname', type=str, required=True, help='Name of the folder in the rvc_models directory containing the RVC model file and optional index file to use')
113
+ parser.add_argument('-p', '--pitch-change', type=int, required=True, help='Change the pitch of AI Vocals only. Generally, use 1 for male to female and -1 for vice-versa. (Octaves)')
114
+ parser.add_argument('-k', '--keep-files', action=argparse.BooleanOptionalAction, help='Whether to keep all intermediate audio files generated in the song_output/id directory, e.g. Isolated Vocals/Instrumentals')
115
+ parser.add_argument('-ir', '--index-rate', type=float, default=0.5, help='A decimal number e.g. 0.5, used to reduce/resolve the timbre leakage problem. If set to 1, more biased towards the timbre quality of the training dataset')
116
+ parser.add_argument('-fr', '--filter-radius', type=int, default=3, help='A number between 0 and 7. If >=3: apply median filtering to the harvested pitch results. The value represents the filter radius and can reduce breathiness.')
117
+ parser.add_argument('-rms', '--rms-mix-rate', type=float, default=0.25, help="A decimal number e.g. 0.25. Control how much to use the original vocal's loudness (0) or a fixed loudness (1).")
118
+ parser.add_argument('-palgo', '--pitch-detection-algo', type=str, default='rmvpe', help='Best option is rmvpe (clarity in vocals), then mangio-crepe (smoother vocals).')
119
+ parser.add_argument('-hop', '--crepe-hop-length', type=int, default=128, help='If pitch detection algo is mangio-crepe, controls how often it checks for pitch changes in milliseconds. The higher the value, the faster the conversion and less risk of voice cracks, but there is less pitch accuracy. Recommended: 128.')
120
+ parser.add_argument('-pro', '--protect', type=float, default=0.33, help='A decimal number e.g. 0.33. Protect voiceless consonants and breath sounds to prevent artifacts such as tearing in electronic music. Set to 0.5 to disable. Decrease the value to increase protection, but it may reduce indexing accuracy.')
121
+ parser.add_argument('-mv', '--main-vol', type=int, default=0, help='Volume change for AI main vocals in decibels. Use -3 to decrease by 3 decibels and 3 to increase by 3 decibels')
122
+ parser.add_argument('-bv', '--backup-vol', type=int, default=0, help='Volume change for backup vocals in decibels')
123
+ parser.add_argument('-iv', '--inst-vol', type=int, default=0, help='Volume change for instrumentals in decibels')
124
+ parser.add_argument('-pall', '--pitch-change-all', type=int, default=0, help='Change the pitch/key of vocals and instrumentals. Changing this slightly reduces sound quality')
125
+ parser.add_argument('-rsize', '--reverb-size', type=float, default=0.15, help='Reverb room size between 0 and 1')
126
+ parser.add_argument('-rwet', '--reverb-wetness', type=float, default=0.2, help='Reverb wet level between 0 and 1')
127
+ parser.add_argument('-rdry', '--reverb-dryness', type=float, default=0.8, help='Reverb dry level between 0 and 1')
128
+ parser.add_argument('-rdamp', '--reverb-damping', type=float, default=0.7, help='Reverb damping between 0 and 1')
129
+ parser.add_argument('-oformat', '--output-format', type=str, default='mp3', help='Output format of audio file. mp3 for smaller file size, wav for best quality')
130
+ args = parser.parse_args()
131
+
132
+ rvc_dirname = args.rvc_dirname
133
+ if not os.path.exists(os.path.join(rvc_models_dir, rvc_dirname)):
134
+ raise Exception(f'The folder {os.path.join(rvc_models_dir, rvc_dirname)} does not exist.')
135
+
136
+ cover_path = song_cover_pipeline(args.song_input, rvc_dirname, args.pitch_change, args.keep_files,
137
+ main_gain=args.main_vol, backup_gain=args.backup_vol, inst_gain=args.inst_vol,
138
+ index_rate=args.index_rate, filter_radius=args.filter_radius,
139
+ rms_mix_rate=args.rms_mix_rate, f0_method=args.pitch_detection_algo,
140
+ crepe_hop_length=args.crepe_hop_length, protect=args.protect,
141
+ pitch_change_all=args.pitch_change_all,
142
+ reverb_rm_size=args.reverb_size, reverb_wet=args.reverb_wetness,
143
+ reverb_dry=args.reverb_dryness, reverb_damping=args.reverb_damping,
144
+ output_format=args.output_format)
145
+ print(f'[+] Cover generated at {cover_path}')