Vijish commited on
Commit
9c20444
1 Parent(s): 4e86785

Create handler.py

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