myn0908's picture
handle api key for save cost limit api
77ed5d2
raw
history blame
3.32 kB
import gradio as gr
from translator import ServerTranslator
from LanguageTranslator.utils.constants import set_api_key, stop_api_key
import json
def apply_api_key(api_key):
api_key = set_api_key(api_key=api_key)
return f'Successfully set {api_key}'
def clear_all(input_json, input_text, input_dest_lang, translated_text_json, translted_text_text):
return None, "", "", "", ""
def translate_text_json(input_json):
# Translation code for JSON input
try:
json_file_path = input_json.name
with open(json_file_path, 'r') as f:
file_content = f.read()
json_input = json.loads(file_content)
translation = ServerTranslator.language_translator(inputs_data=json_input).translate()
translate_text = translation['text']
return translate_text
except Exception as e:
translate_text = f"Error: {str(e)}"
return translate_text
def translate_text_text(input_text, input_dest_lang):
# Translation code for text input
try:
translation = ServerTranslator.language_translator(text=input_text, dest_language=input_dest_lang).translate()
translate_text = translation['text']
return translate_text
except Exception as e:
translate_text = f"Error: {str(e)}"
return translate_text
with gr.Blocks() as demo:
with gr.Column():
gr.Markdown("# Translator For Upload JSON file")
translated_text_json = gr.Textbox(label="Result Translate Text")
input_json = gr.File(label="Upload JSON file")
submit_json = gr.Button("Submit Json")
submit_json.click(
translate_text_json,
[input_json], # Pass all three inputs
[translated_text_json]
)
with gr.Column():
gr.Markdown("# Translator For Input Text and Destination Language")
translated_text_text = gr.Textbox(label="Result Translate Text")
input_dest_lang = gr.Textbox(placeholder='Example input: vi', label="Destination Language")
input_text = gr.Textbox(placeholder='Example inputs: I love you, I love you than myself',
label="Enter Text")
submit_text = gr.Button("Submit Text")
submit_text.click(
translate_text_text,
[input_text, input_dest_lang], # Pass all three inputs
[translated_text_text]
)
clear = gr.Button("Clear")
clear.click(
clear_all,
[input_json, input_text, input_dest_lang, translated_text_json, translated_text_text],
[input_json, input_text, input_dest_lang, translated_text_json, translated_text_text]
)
with gr.Row():
with gr.Column():
status = gr.Textbox(label='API KEY STATUS')
api_key_set = gr.Textbox(label='Set your OPENAI API KEY')
api_key_set_button = gr.Button("Set API key")
api_key_set_button.click(
apply_api_key,
[api_key_set],
[status]
)
with gr.Column():
status_2 = gr.Textbox(label='STOP API KEY STATUS')
stop_api_button = gr.Button('Stop API key')
stop_api_button.click(
stop_api_key,
[],
[status_2])
demo.launch(share=True)