Spaces:
Sleeping
Sleeping
Upload myinfer_latest.py
Browse files27 unmodified lines282930313233343536373811 unmodified lines50515253545515 unmodified lines71727374757677787980818283848586878860 unmodified lines14915015115215315454 unmodified lines209210211212213214215215 unmodified lines4314324334344354364374384394404414424434444451 unmodified line44744844945045145245318 unmodified lines47247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750827 unmodified linesfrom multiprocessing import Process, SimpleQueue, set_start_method,get_contextfrom queue import Emptyfrom pydub import AudioSegmentimport ioapp = Flask(__name__)app.secret_key = 'smjain_6789'now_dir = os.getcwd()11 unmodified linesrequest_semaphore = Semaphore(MAX_CONCURRENT_REQUESTS)task_status_tracker = {}#set_start_method('spawn', force=True)from lib.infer_pack.models import (15 unmodified linesf0method_mode = ["pm", "harvest", "crepe"]f0method_info = "PM is fast, Harvest is good but extremely slow, and Crepe effect is good but requires GPU (Default: PM)"def hash_array(array):# Ensure the array is in a consistent byte formatarray_bytes = array.tobytes()# Create a hash object (using SHA256 for example)hash_obj = hashlib.sha256(array_bytes)# Get the hexadecimal digest of the arrayhash_hex = hash_obj.hexdigest()return hash_hexdef hash_array1(arr):arr_str = np.array2string(arr)return hashlib.md5(arr_str.encode()).hexdigest()if os.path.isfile("rmvpe.pt"):f0method_mode.insert(2, "rmvpe")60 unmodified linesexcept Exception as e:print(f"Error deleting {path}: {e}")@app.route('/status/<audio_id>', methods=['GET'])def get_status(audio_id):# Retrieve the task status using the unique ID54 unmodified linesaudio_length_minutes = len(audio) / 60000.0 # pydub returns length in millisecondsif audio_length_minutes > 5:return jsonify({"error": "Audio length exceeds 3 minutes"}), 400#created_files = []# Save the file to a temporary path215 unmodified linesprotect,f0_file=f0_file)hash_val = hash_array1(audio_opt)# Get the current thread's name or IDthread_name = threading.current_thread().nameprint(f"Thread {thread_name}: Hash {hash_val}")sample_and_print(audio_opt,thread_name)# Print the hash and thread informationif resample_sr >= 16000 and tgt_sr != resample_sr:tgt_sr = resample_srindex_info = (1 unmodified lineif os.path.exists(file_index)else "Index not used.")save_audio_with_thread_id(audio_opt,tgt_sr)print("writing to FS")#output_file_path = os.path.join("output", f"converted_audio_{sid}.wav") # Adjust path as needed# Assuming 'unique_id' is passed to convert_voice function along with 'sid'18 unmodified linesreturn info, (None, None)def save_audio_with_thread_id(audio_opt, tgt_sr,output_dir="output"):# Ensure the output directory existsos.makedirs(output_dir, exist_ok=True)# Get the current thread ID or namethread_id = threading.current_thread().name# Construct the filename using the thread IDfilename = f"audio_{thread_id}.wav"output_path = os.path.join(output_dir, filename)# Assuming the target sample rate is defined elsewhere; replace as necessary#tgt_sr = 16000 # Example sample rate, adjust according to your needs# Write the audio filesf.write(output_path, audio_opt, tgt_sr)print(f"Saved {output_path}")def sample_and_print(array, thread_name):# Ensure the array has more than 10 elements; otherwise, use the array lengthnum_samples = 10 if len(array) > 10 else len(array)# Calculate indices to sample; spread them evenly across the arrayindices = np.linspace(0, len(array) - 1, num=num_samples, dtype=int)# Sample elementssampled_elements = array[indices]# Print sampled elements with thread IDprint(f"Thread {thread_name}: Sampled Elements: {sampled_elements}")def get_vc(sid, to_return_protect0):27 unmodified lines2829303132333435363738394011 unmodified lines52535455565758596061626315 unmodified lines7980818283848586878889909192939460 unmodified lines15515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818954 unmodified lines244245246247248249250215 unmodified lines4664674684694704714724734744754764771 unmodified line47948048148248348448518 unmodified lines50450550650750850951027 unmodified linesfrom multiprocessing import Process, SimpleQueue, set_start_method,get_contextfrom queue import Emptyfrom pydub import AudioSegmentfrom flask_dance.contrib.google import make_google_blueprint, googleimport ioapp = Flask(__name__)app.secret_key = 'smjain_6789'now_dir = os.getcwd()11 unmodified linesrequest_semaphore = Semaphore(MAX_CONCURRENT_REQUESTS)task_status_tracker = {}os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1" # ONLY FOR TESTING, REMOVE IN PRODUCTIONos.environ["OAUTHLIB_RELAX_TOKEN_SCOPE"] = "1"app.config["GOOGLE_OAUTH_CLIENT_ID"] = "144930881143-n3e3ubers3vkq7jc9doe4iirasgimdt2.apps.googleusercontent.com"app.config["GOOGLE_OAUTH_CLIENT_SECRET"] = "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"google_blueprint = make_google_blueprint(scope=["profile", "email"])app.register_blueprint(google_blueprint, url_prefix="/login")#set_start_method('spawn', force=True)from lib.infer_pack.models import (15 unmodified linesf0method_mode = ["pm", "harvest", "crepe"]f0method_info = "PM is fast, Harvest is good but extremely slow, and Crepe effect is good but requires GPU (Default: PM)"@app.route("/")def index():# Check if user is logged inif google.authorized:return render_template("index.html", logged_in=True)else:return render_template("index.html", logged_in=False)if os.path.isfile("rmvpe.pt"):f0method_mode.insert(2, "rmvpe")60 unmodified linesexcept Exception as e:print(f"Error deleting {path}: {e}")@app.route("/create_song")def create_song():if not google.authorized:return redirect(url_for("google.login"))resp = google.get("/oauth2/v2/userinfo")assert resp.ok, resp.textemail = resp.json()["email"]user_info = resp.json()user_id = user_info.get("id")name = user_info.get("name")#if not user_exists(email):# user_data = {'user_id': user_id, 'user_name': name, 'email': email, 'model_created': 'No', 'time_used': '0','model_id':''}# add_user(user_data)#models = get_user_models(email)# Assuming we're interested in whether any model has been created#model_exists = len(models) > 0return render_template("ui.html", email=email)@app.route("/logout")def logout():# Clear the sessionsession.clear()#if "google_oauth_token" in session:# del session["google_oauth_token"]return redirect(url_for("index"))@app.route('/status/<audio_id>', methods=['GET'])def get_status(audio_id):# Retrieve the task status using the unique ID54 unmodified linesaudio_length_minutes = len(audio) / 60000.0 # pydub returns length in millisecondsif audio_length_minutes > 5:return jsonify({"error": "Audio length exceeds 5 minutes"}), 400#created_files = []# Save the file to a temporary path215 unmodified linesprotect,f0_file=f0_file)# Get the current thread's name or IDif resample_sr >= 16000 and tgt_sr != resample_sr:tgt_sr = resample_srindex_info = (1 unmodified lineif os.path.exists(file_index)else "Index not used.")print("writing to FS")#output_file_path = os.path.join("output", f"converted_audio_{sid}.wav") # Adjust path as needed# Assuming 'unique_id' is passed to convert_voice function along with 'sid'18 unmodified linesreturn info, (None, None)def get_vc(sid, to_return_protect0):
myinfer_latest.py+51-49