Vijish commited on
Commit
6fb0feb
1 Parent(s): cc82b93

Update handler.py

Browse files
Files changed (1) hide show
  1. handler.py +58 -20
handler.py CHANGED
@@ -6,6 +6,50 @@ import base64
6
  import numpy as np
7
  import librosa
8
  from scipy.io import wavfile
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
  class EndpointHandler:
11
  def __init__(self, model_dir=None):
@@ -13,25 +57,10 @@ class EndpointHandler:
13
 
14
  def __call__(self, data: Dict[str, Any]) -> Dict[str, Any]:
15
  try:
16
- # Extract the actual input data from the "inputs" field
17
- if "inputs" in data:
18
- json_data = data["inputs"]
19
  else:
20
- json_data = data
21
-
22
- # Clone the repository if it's not already cloned
23
- repo_dir = "TTS_Mongolian"
24
- if not os.path.exists(repo_dir):
25
- repo_url = "https://huggingface.co/mazalaai/TTS_Mongolian.git"
26
- os.system(f"git clone {repo_url}")
27
-
28
- # Change directory to the repository
29
- os.chdir(repo_dir)
30
-
31
- # Import the voice_processing module and functions
32
- from voice_processing import tts, get_model_names, voice_mapping, get_unique_filename
33
-
34
- return self.process_json_input(json_data)
35
  except ValueError as e:
36
  return {"error": str(e)}
37
  except Exception as e:
@@ -50,13 +79,15 @@ class EndpointHandler:
50
  if not edge_tts_voice:
51
  raise ValueError(f"Invalid voice '{selected_voice}'.")
52
 
53
- info, edge_tts_output_path, tts_output_data, edge_output_file = tts(
54
  model_name, tts_text, edge_tts_voice, slang_rate, use_uploaded_voice, voice_upload_file
55
- )
 
56
  if edge_output_file and os.path.exists(edge_output_file):
57
  os.remove(edge_output_file)
58
 
59
  _, audio_output = tts_output_data
 
60
  audio_file_path = self.save_audio_data_to_file(audio_output) if isinstance(audio_output, np.ndarray) else audio_output
61
 
62
  try:
@@ -73,6 +104,13 @@ class EndpointHandler:
73
  else:
74
  raise ValueError("Invalid JSON structure.")
75
 
 
 
 
 
 
 
 
76
  def save_audio_data_to_file(self, audio_data, sample_rate=40000):
77
  file_path = get_unique_filename('wav')
78
  wavfile.write(file_path, sample_rate, audio_data)
 
6
  import numpy as np
7
  import librosa
8
  from scipy.io import wavfile
9
+ import asyncio
10
+ import zipfile
11
+ import requests
12
+
13
+
14
+ def download_and_extract_files():
15
+ files_to_download = [
16
+ ("config.py", "https://www.dropbox.com/scl/fi/3vnj2myor659x5xyteu6u/config.py?rlkey=h7z6mp7denazoqwtr5hj0g70n&st=2vop5eid&dl=1"),
17
+ ("hubert_base.pt", "https://www.dropbox.com/scl/fi/g7oohuwfzlnrbd8zic6gj/hubert_base.pt?rlkey=ddeyqex1morsm54azyakmd62e&st=s7p2ocr3&dl=1"),
18
+ ("lib.zip", "https://www.dropbox.com/scl/fi/ia6p6cf5xvcbi78dmkbbz/lib.zip?rlkey=k3chc1nlaswsqdo7slqco56wi&st=re40dqki&dl=1"),
19
+ ("rmvpe.pt", "https://www.dropbox.com/scl/fi/7pl7u6fvydwgtz19n8nzx/rmvpe.pt?rlkey=tnbxmarogivbw3qy34hgy7r7q&st=69iglyfn&dl=1"),
20
+ ("rmvpe.py", "https://www.dropbox.com/scl/fi/i2shk4otwyg4ns8yod5h1/rmvpe.py?rlkey=l7313htdh1ihylb6bx91el0lv&st=mrz8advb&dl=1"),
21
+ ("vc_infer_pipeline.py", "https://www.dropbox.com/scl/fi/k0hbva7vujhbmzg2l0l2g/vc_infer_pipeline.py?rlkey=5leclgbjiv6ukjywnftscnwe8&st=fj6sgnq4&dl=1"),
22
+ ("voice_processing.py", "https://www.dropbox.com/scl/fi/z6gyjaymlgwinst05bb43/voice_processing.py?rlkey=0qlcfv6g9db2uzaq3xvv6k43s&st=gg63oppb&dl=1"),
23
+ ("weights.zip", "https://www.dropbox.com/scl/fi/tr5a04wlow5go8cv3d6qp/weights.zip?rlkey=qvpwax97nn5a4iv79g76lcbz2&st=5ueb2gva&dl=1")
24
+ ]
25
+
26
+ for file_name, url in files_to_download:
27
+ if not os.path.exists(file_name):
28
+ response = requests.get(url)
29
+ with open(file_name, "wb") as file:
30
+ file.write(response.content)
31
+
32
+ if file_name.endswith(".zip"):
33
+ with zipfile.ZipFile(file_name, "r") as zip_ref:
34
+ extract_to = os.path.splitext(file_name)[0]
35
+ for member in zip_ref.namelist():
36
+ # Extract files into the target directory without the first part of the path
37
+ member_path = os.path.join(extract_to, *member.split('/')[1:])
38
+ if member.endswith('/'):
39
+ os.makedirs(member_path, exist_ok=True)
40
+ else:
41
+ os.makedirs(os.path.dirname(member_path), exist_ok=True)
42
+ with open(member_path, 'wb') as f:
43
+ f.write(zip_ref.read(member))
44
+
45
+ # Optionally, remove the zip file after extraction
46
+ os.remove(file_name)
47
+
48
+ # Run the function
49
+ download_and_extract_files()
50
+
51
+ from voice_processing import tts, get_model_names, voice_mapping, get_unique_filename
52
+
53
 
54
  class EndpointHandler:
55
  def __init__(self, model_dir=None):
 
57
 
58
  def __call__(self, data: Dict[str, Any]) -> Dict[str, Any]:
59
  try:
60
+ if "inputs" in data: # Check if data is in Hugging Face JSON format
61
+ return self.process_hf_input(data)
 
62
  else:
63
+ return self.process_json_input(data)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
  except ValueError as e:
65
  return {"error": str(e)}
66
  except Exception as e:
 
79
  if not edge_tts_voice:
80
  raise ValueError(f"Invalid voice '{selected_voice}'.")
81
 
82
+ info, edge_tts_output_path, tts_output_data, edge_output_file = asyncio.run(tts(
83
  model_name, tts_text, edge_tts_voice, slang_rate, use_uploaded_voice, voice_upload_file
84
+ ))
85
+
86
  if edge_output_file and os.path.exists(edge_output_file):
87
  os.remove(edge_output_file)
88
 
89
  _, audio_output = tts_output_data
90
+
91
  audio_file_path = self.save_audio_data_to_file(audio_output) if isinstance(audio_output, np.ndarray) else audio_output
92
 
93
  try:
 
104
  else:
105
  raise ValueError("Invalid JSON structure.")
106
 
107
+ def process_hf_input(self, hf_data):
108
+ if "inputs" in hf_data:
109
+ actual_data = hf_data["inputs"]
110
+ return self.process_json_input(actual_data)
111
+ else:
112
+ return {"error": "Invalid Hugging Face JSON structure."}
113
+
114
  def save_audio_data_to_file(self, audio_data, sample_rate=40000):
115
  file_path = get_unique_filename('wav')
116
  wavfile.write(file_path, sample_rate, audio_data)