import gradio as gr import requests import os import json is_env_local = os.getenv("IS_ENV_LOCAL", "false") == "true" print(f"is_env_local: {is_env_local}") if is_env_local: with open("local_config.json") as f: config = json.load(f) PASSWORD = config["PASSWORD"] ELSA_API_TOKEN = config["ELSA_API_TOKEN"] else: PASSWORD = os.getenv("PASSWORD") ELSA_API_TOKEN = os.getenv("ELSA_API_TOKEN") def verify_password(password): if password == PASSWORD: return True else: raise gr.Error("密碼錯誤") def score_audio_plus(password, audio, api_plan, return_json): """ Call the ELSA 'score_audio_plus' endpoint with the provided audio file. """ if not audio: return "No audio file provided. Please upload an audio file." verify_password(password) url = "https://api.elsanow.io/api/v1/score_audio_plus" headers = { "Authorization": f"ELSA {ELSA_API_TOKEN}" } # Prepare files and data for POST request with open(audio, "rb") as f: files = { 'audio_file': (os.path.basename(audio), f, 'audio/wav') } data = { 'api_plan': api_plan, 'return_json': "true" if return_json else "false" } # Send POST request response = requests.post(url, files=files, data=data, headers=headers) if response.status_code == 200: # Successfully made the request return response.text else: # Error handling return f"Error: {response.status_code} - {response.text}" with gr.Blocks() as demo: with gr.Row(): password_input = gr.Textbox(label="Password", type="password") with gr.Tab("score_audio_plus"): with gr.Row(): with gr.Column(scale=2): audio_input = gr.Audio(sources=["microphone","upload"], type="filepath", max_length=60, label="語音輸入") api_plan_input = gr.Dropdown(choices=["basic", "premium"], label="API Plan", value="premium") return_json_input = gr.Checkbox(label="Return JSON", value=True) submit_button = gr.Button("Score Audio") with gr.Column(scale=1): output_text = gr.JSON(label="API Response") submit_button.click( fn=score_audio_plus, inputs=[password_input, audio_input, api_plan_input, return_json_input], outputs=output_text ) # Launch the interface demo.launch()