# Copyright Jiaqi Liu # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import tempfile from typing import Literal from typing import Union import gradio as gr from openai import OpenAI server_name = os.getenv("SERVER_NAME", "0.0.0.0") def latin_replacement(text: str): with open("ancient-greek-phonemes.txt", "r") as mapping_file: mapping = dict( [(ancient_greek, latin) for ancient_greek, latin in [line.rstrip().split("->") for line in mapping_file.readlines()]] ) for key, value in mapping.items(): text = text.replace(key, value) return text def tts( openai_key: str, text: str, model: Union[str, Literal["tts-1", "tts-1-hd"]], voice: Literal["alloy", "echo", "fable", "onyx", "nova", "shimmer"], output_file_format: Literal["mp3", "opus", "aac", "flac"] = "mp3", speed: float = 1.0 ): if len(text) > 0: text = latin_replacement(text) try: client = OpenAI(api_key=openai_key) response = client.audio.speech.create( model=model, voice=voice, input=text, response_format=output_file_format, speed=speed ) except Exception as error: print(str(error)) raise gr.Error( "An error occurred while generating speech. Please check your API key and come back try again.") with tempfile.NamedTemporaryFile(suffix=".mp3", delete=False) as temp_file: temp_file.write(response.content) temp_file_path = temp_file.name return temp_file_path else: return "1-second-of-silence.mp3" with gr.Blocks() as app: gr.Markdown("#