Vijish commited on
Commit
540a60c
·
verified ·
1 Parent(s): f19ea80

Upload handler (3).py

Browse files
Files changed (1) hide show
  1. handler (3).py +85 -0
handler (3).py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pydantic import BaseModel
2
+ from environs import Env
3
+ from typing import List, Dict, Any
4
+ import os
5
+ 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):
12
+ self.model_dir = model_dir
13
+
14
+ def __call__(self, data: Dict[str, Any]) -> Dict[str, Any]:
15
+ try:
16
+ # Clone the repository
17
+ repo_url = "https://huggingface.co/mazalaai/TTS_Mongolian.git"
18
+ os.system(f"git clone {repo_url}")
19
+
20
+ # Change directory to the cloned repository
21
+ repo_dir = "TTS_Mongolian"
22
+ os.chdir(repo_dir)
23
+
24
+ # Import the voice_processing module and functions
25
+ from voice_processing import tts, get_model_names, voice_mapping, get_unique_filename
26
+
27
+ if "inputs" in data:
28
+ # Check if data is in Hugging Face JSON format
29
+ return self.process_hf_input(data)
30
+ else:
31
+ return self.process_json_input(data)
32
+
33
+ except ValueError as e:
34
+ return {"error": str(e)}
35
+ except Exception as e:
36
+ return {"error": str(e)}
37
+
38
+ def process_json_input(self, json_data):
39
+ if all(key in json_data for key in ["model_name", "tts_text", "selected_voice", "slang_rate", "use_uploaded_voice"]):
40
+ model_name = json_data["model_name"]
41
+ tts_text = json_data["tts_text"]
42
+ selected_voice = json_data["selected_voice"]
43
+ slang_rate = json_data["slang_rate"]
44
+ use_uploaded_voice = json_data["use_uploaded_voice"]
45
+ voice_upload_file = json_data.get("voice_upload_file", None)
46
+
47
+ edge_tts_voice = voice_mapping.get(selected_voice)
48
+ if not edge_tts_voice:
49
+ raise ValueError(f"Invalid voice '{selected_voice}'.")
50
+
51
+ info, edge_tts_output_path, tts_output_data, edge_output_file = tts(
52
+ model_name, tts_text, edge_tts_voice, slang_rate, use_uploaded_voice, voice_upload_file
53
+ )
54
+
55
+ if edge_output_file and os.path.exists(edge_output_file):
56
+ os.remove(edge_output_file)
57
+
58
+ _, audio_output = tts_output_data
59
+ audio_file_path = self.save_audio_data_to_file(audio_output) if isinstance(audio_output, np.ndarray) else audio_output
60
+
61
+ try:
62
+ with open(audio_file_path, 'rb') as file:
63
+ audio_bytes = file.read()
64
+ audio_data_uri = f"data:audio/wav;base64,{base64.b64encode(audio_bytes).decode('utf-8')}"
65
+ except Exception as e:
66
+ raise Exception(f"Failed to read audio file: {e}")
67
+ finally:
68
+ if os.path.exists(audio_file_path):
69
+ os.remove(audio_file_path)
70
+
71
+ return {"info": info, "audio_data_uri": audio_data_uri}
72
+ else:
73
+ raise ValueError("Invalid JSON structure.")
74
+
75
+ def process_hf_input(self, hf_data):
76
+ if "inputs" in hf_data:
77
+ actual_data = hf_data["inputs"]
78
+ return self.process_json_input(actual_data)
79
+ else:
80
+ return {"error": "Invalid Hugging Face JSON structure."}
81
+
82
+ def save_audio_data_to_file(self, audio_data, sample_rate=40000):
83
+ file_path = get_unique_filename('wav')
84
+ wavfile.write(file_path, sample_rate, audio_data)
85
+ return file_path