basyx commited on
Commit
bb71ec1
·
verified ·
1 Parent(s): 82d8564

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +37 -37
app.py CHANGED
@@ -1,23 +1,20 @@
1
-
2
  import os
3
  import gradio as gr
4
  import tempfile
5
  import soundfile as sf
6
  from models import Tokenizer, Kokoro
 
 
 
7
 
8
- # Function to fetch available style vectors dynamically
9
-
10
 
11
  def get_style_vector_choices(directory="voices"):
12
  return [file for file in os.listdir(directory) if file.endswith(".pt")]
13
 
14
-
15
  def get_onnx_models(directory="weights"):
16
  return [file for file in os.listdir(directory) if file.endswith(".onnx")]
17
 
18
- # Function to perform TTS using your local model
19
-
20
-
21
  def local_tts(
22
  text: str,
23
  model_path: str,
@@ -29,9 +26,9 @@ def local_tts(
29
  try:
30
  tokenizer = Tokenizer()
31
  style_vector_path = os.path.join("voices", style_vector)
32
- model_path = os.path.join("weights", model_path)
33
 
34
- inference = Kokoro(model_path, style_vector_path, tokenizer=tokenizer, lang='en-us')
35
 
36
  audio, sample_rate = inference.generate_audio(text, speed=speed)
37
 
@@ -46,12 +43,9 @@ def local_tts(
46
  else:
47
  raise gr.Error("Input text cannot be empty.")
48
 
49
-
50
- # Get the list of available style vectors
51
  style_vector_choices = get_style_vector_choices()
52
  onnx_models_choices = get_onnx_models()
53
 
54
- # sample texts and their corresponding audio
55
  sample_outputs = [
56
  ("Educational Note", "Machine learning models rely on large datasets and complex algorithms to identify patterns and make predictions.", "assets/edu_note.wav"),
57
  ("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"),
@@ -64,45 +58,51 @@ example_texts = [
64
  ["Thank you for listening to this audio. It was generated by the Kokoro TTS model."]
65
  ]
66
 
67
- # Gradio Interface
 
68
  with gr.Blocks() as demo:
69
  gr.Markdown("## <center> Kokoro TTS ONNX Inference | [GitHub Link](https://github.com/yakhyo/kokoro-onnx) </center>")
70
-
71
- # Model-specific inputs
72
  with gr.Row(variant="panel"):
73
  model_path = gr.Dropdown(choices=onnx_models_choices, label="ONNX Model Path", value=onnx_models_choices[0])
74
  style_vector = gr.Dropdown(choices=style_vector_choices, label="Style Vector", value=style_vector_choices[0])
75
  output_file_format = gr.Dropdown(choices=["wav", "mp3"], label="Output Format", value="wav")
76
  speed = gr.Slider(minimum=0.5, maximum=2.0, value=1.0, step=0.1, label="Speed")
77
 
78
- # Text input and output
79
- text = gr.Textbox(
80
- label="Input Text",
81
- placeholder="Enter text to convert to speech."
82
- )
83
  btn = gr.Button("Generate Speech")
84
  output_audio = gr.Audio(label="Generated Audio", type="filepath")
85
 
86
- # Link inputs and outputs
87
- btn.click(
88
- fn=local_tts,
89
- inputs=[text, model_path, style_vector, output_file_format, speed],
90
- outputs=output_audio
91
- )
92
-
93
- # Add example texts
94
- gr.Examples(
95
- examples=example_texts,
96
- inputs=[text],
97
- label="Click an example to populate the input text"
98
- )
99
-
100
- # Add example texts and audios
101
  gr.Markdown("### Sample Texts and Audio")
102
  for topic, sample_text, sample_audio in sample_outputs:
103
  with gr.Row():
104
  gr.Textbox(value=sample_text, label=topic, interactive=False)
105
  gr.Audio(value=sample_audio, label="Example Audio", type="filepath", interactive=False)
106
 
107
- demo.launch(server_name="0.0.0.0")
108
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import os
2
  import gradio as gr
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
+ # --- EXISTING LOGIC (UNCHANGED) ---
 
11
 
12
  def get_style_vector_choices(directory="voices"):
13
  return [file for file in os.listdir(directory) if file.endswith(".pt")]
14
 
 
15
  def get_onnx_models(directory="weights"):
16
  return [file for file in os.listdir(directory) if file.endswith(".onnx")]
17
 
 
 
 
18
  def local_tts(
19
  text: str,
20
  model_path: str,
 
26
  try:
27
  tokenizer = Tokenizer()
28
  style_vector_path = os.path.join("voices", style_vector)
29
+ model_path_full = os.path.join("weights", model_path)
30
 
31
+ inference = Kokoro(model_path_full, style_vector_path, tokenizer=tokenizer, lang='en-us')
32
 
33
  audio, sample_rate = inference.generate_audio(text, speed=speed)
34
 
 
43
  else:
44
  raise gr.Error("Input text cannot be empty.")
45
 
 
 
46
  style_vector_choices = get_style_vector_choices()
47
  onnx_models_choices = get_onnx_models()
48
 
 
49
  sample_outputs = [
50
  ("Educational Note", "Machine learning models rely on large datasets and complex algorithms to identify patterns and make predictions.", "assets/edu_note.wav"),
51
  ("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"),
 
58
  ["Thank you for listening to this audio. It was generated by the Kokoro TTS model."]
59
  ]
60
 
61
+ # --- GRADIO INTERFACE (UNCHANGED) ---
62
+
63
  with gr.Blocks() as demo:
64
  gr.Markdown("## <center> Kokoro TTS ONNX Inference | [GitHub Link](https://github.com/yakhyo/kokoro-onnx) </center>")
 
 
65
  with gr.Row(variant="panel"):
66
  model_path = gr.Dropdown(choices=onnx_models_choices, label="ONNX Model Path", value=onnx_models_choices[0])
67
  style_vector = gr.Dropdown(choices=style_vector_choices, label="Style Vector", value=style_vector_choices[0])
68
  output_file_format = gr.Dropdown(choices=["wav", "mp3"], label="Output Format", value="wav")
69
  speed = gr.Slider(minimum=0.5, maximum=2.0, value=1.0, step=0.1, label="Speed")
70
 
71
+ text = gr.Textbox(label="Input Text", placeholder="Enter text to convert to speech.")
 
 
 
 
72
  btn = gr.Button("Generate Speech")
73
  output_audio = gr.Audio(label="Generated Audio", type="filepath")
74
 
75
+ btn.click(fn=local_tts, inputs=[text, model_path, style_vector, output_file_format, speed], outputs=output_audio)
76
+
77
+ gr.Examples(examples=example_texts, inputs=[text], label="Click an example to populate the input text")
 
 
 
 
 
 
 
 
 
 
 
 
78
  gr.Markdown("### Sample Texts and Audio")
79
  for topic, sample_text, sample_audio in sample_outputs:
80
  with gr.Row():
81
  gr.Textbox(value=sample_text, label=topic, interactive=False)
82
  gr.Audio(value=sample_audio, label="Example Audio", type="filepath", interactive=False)
83
 
84
+ # --- FASTAPI WRAPPER & STARTUP ---
85
+
86
+ app = FastAPI()
87
+
88
+ @app.post("/v1/audio/speech")
89
+ async def api_speech(request: Request):
90
+ """
91
+ OpenAI-compatible /v1/audio/speech endpoint for automation.
92
+ Expects JSON: {"input": "text", "voice": "voice_file.pt", "model": "model_file.onnx"}
93
+ """
94
+ data = await request.json()
95
+ input_text = data.get("input", "")
96
+ m_path = data.get("model", onnx_models_choices[0])
97
+ s_vec = data.get("voice", style_vector_choices[0])
98
+ spd = float(data.get("speed", 1.0))
99
+
100
+ file_path = local_tts(input_text, m_path, s_vec, speed=spd)
101
+ return FileResponse(file_path, media_type="audio/wav")
102
+
103
+ # Mount Gradio into the FastAPI app
104
+ app = gr.mount_gradio_app(app, demo, path="/")
105
+
106
+ if __name__ == "__main__":
107
+ # Runs on port 7860 as expected by the Dockerfile/Hugging Face
108
+ uvicorn.run(app, host="0.0.0.0", port=7860)