basyx commited on
Commit
ab6cce9
·
verified ·
1 Parent(s): 3d02d9a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +18 -82
app.py CHANGED
@@ -3,104 +3,40 @@ import gradio as gr
3
  import tempfile
4
  import soundfile as sf
5
  from models import Tokenizer, Kokoro
 
 
 
6
 
7
- # Function to fetch available style vectors dynamically
8
-
9
-
10
  def get_style_vector_choices(directory="voices"):
 
11
  return [file for file in os.listdir(directory) if file.endswith(".pt")]
12
 
13
-
14
  def get_onnx_models(directory="weights"):
 
15
  return [file for file in os.listdir(directory) if file.endswith(".onnx")]
16
 
17
- # Function to perform TTS using your local model
18
-
19
-
20
- def local_tts(
21
- text: str,
22
- model_path: str,
23
- style_vector: str,
24
- output_file_format: str = "wav",
25
- speed: float = 1.0
26
- ):
27
  if len(text) > 0:
28
  try:
29
  tokenizer = Tokenizer()
30
  style_vector_path = os.path.join("voices", style_vector)
31
- model_path = os.path.join("weights", model_path)
32
-
33
- inference = Kokoro(model_path, style_vector_path, tokenizer=tokenizer, lang='en-us')
34
 
 
35
  audio, sample_rate = inference.generate_audio(text, speed=speed)
36
 
37
  with tempfile.NamedTemporaryFile(suffix=f".{output_file_format}", delete=False) as temp_file:
38
  sf.write(temp_file.name, audio, sample_rate)
39
- temp_file_path = temp_file.name
40
-
41
- return temp_file_path
42
-
43
  except Exception as e:
44
- raise gr.Error(f"An error occurred during TTS inference: {str(e)}")
45
- else:
46
- raise gr.Error("Input text cannot be empty.")
47
-
48
-
49
- # Get the list of available style vectors
50
- style_vector_choices = get_style_vector_choices()
51
- onnx_models_choices = get_onnx_models()
52
-
53
- # sample texts and their corresponding audio
54
- sample_outputs = [
55
- ("Educational Note", "Machine learning models rely on large datasets and complex algorithms to identify patterns and make predictions.", "assets/edu_note.wav"),
56
- ("Fun Fact", "Did you know that honey never spoils? Archaeologists have found pots of honey in ancient Egyptian tombs that are over 3,000 years old and still edible!", "assets/fun_fact.wav"),
57
- ("Thanks", "Thank you for listening to this audio. It was generated by the Kokoro TTS model.", "assets/thanks.wav")
58
- ]
59
-
60
- example_texts = [
61
- ["Machine learning models rely on large datasets and complex algorithms to identify patterns and make predictions."],
62
- ["Did you know that honey never spoils? Archaeologists have found pots of honey in ancient Egyptian tombs that are over 3,000 years old and still edible!"],
63
- ["Thank you for listening to this audio. It was generated by the Kokoro TTS model."]
64
- ]
65
-
66
- # Gradio Interface
67
- with gr.Blocks() as demo:
68
- gr.Markdown("## <center> Kokoro TTS ONNX Inference | [GitHub Link](https://github.com/yakhyo/kokoro-onnx) </center>")
69
-
70
- # Model-specific inputs
71
- with gr.Row(variant="panel"):
72
- model_path = gr.Dropdown(choices=onnx_models_choices, label="ONNX Model Path", value=onnx_models_choices[0])
73
- style_vector = gr.Dropdown(choices=style_vector_choices, label="Style Vector", value=style_vector_choices[0])
74
- output_file_format = gr.Dropdown(choices=["wav", "mp3"], label="Output Format", value="wav")
75
- speed = gr.Slider(minimum=0.5, maximum=2.0, value=1.0, step=0.1, label="Speed")
76
-
77
- # Text input and output
78
- text = gr.Textbox(
79
- label="Input Text",
80
- placeholder="Enter text to convert to speech."
81
- )
82
- btn = gr.Button("Generate Speech")
83
- output_audio = gr.Audio(label="Generated Audio", type="filepath")
84
-
85
- # Link inputs and outputs
86
- btn.click(
87
- fn=local_tts,
88
- inputs=[text, model_path, style_vector, output_file_format, speed],
89
- outputs=output_audio
90
- )
91
-
92
- # Add example texts
93
- gr.Examples(
94
- examples=example_texts,
95
- inputs=[text],
96
- label="Click an example to populate the input text"
97
- )
98
 
99
- # Add example texts and audios
100
- gr.Markdown("### Sample Texts and Audio")
101
- for topic, sample_text, sample_audio in sample_outputs:
102
- with gr.Row():
103
- gr.Textbox(value=sample_text, label=topic, interactive=False)
104
- gr.Audio(value=sample_audio, label="Example Audio", type="filepath", interactive=False)
105
 
106
- demo.launch(server_name="0.0.0.0")
 
 
 
3
  import tempfile
4
  import soundfile as sf
5
  from models import Tokenizer, Kokoro
6
+ from fastapi import FastAPI, Request
7
+ from fastapi.responses import FileResponse
8
+ import uvicorn
9
 
10
+ # Initialize Kokoro components
 
 
11
  def get_style_vector_choices(directory="voices"):
12
+ if not os.path.exists(directory): return []
13
  return [file for file in os.listdir(directory) if file.endswith(".pt")]
14
 
 
15
  def get_onnx_models(directory="weights"):
16
+ if not os.path.exists(directory): return []
17
  return [file for file in os.listdir(directory) if file.endswith(".onnx")]
18
 
19
+ def local_tts(text: str, model_path: str, style_vector: str, output_file_format: str = "wav", speed: float = 1.0):
 
 
 
 
 
 
 
 
 
20
  if len(text) > 0:
21
  try:
22
  tokenizer = Tokenizer()
23
  style_vector_path = os.path.join("voices", style_vector)
24
+ model_full_path = os.path.join("weights", model_path)
 
 
25
 
26
+ inference = Kokoro(model_full_path, style_vector_path, tokenizer=tokenizer, lang='en-us')
27
  audio, sample_rate = inference.generate_audio(text, speed=speed)
28
 
29
  with tempfile.NamedTemporaryFile(suffix=f".{output_file_format}", delete=False) as temp_file:
30
  sf.write(temp_file.name, audio, sample_rate)
31
+ return temp_file.name
 
 
 
32
  except Exception as e:
33
+ print(f"Inference Error: {e}")
34
+ return None
35
+ return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
 
37
+ # --- FASTAPI SETUP ---
38
+ app = FastAPI(title="Basyx TTS Hub")
 
 
 
 
39
 
40
+ @app.post("/v1/audio/speech")
41
+ async def api_tts(request: Request):
42
+ data = await request.json()