log-analyzer / app.py
Hashintha's picture
Update app.py
585f6e4
from response_parser import *
import gradio as gr
import os
def initialization(state_dict: Dict) -> None:
if not os.path.exists('cache'):
os.mkdir('cache')
if state_dict["bot_backend"] is None:
state_dict["bot_backend"] = BotBackend()
if 'OPENAI_API_KEY' in os.environ:
del os.environ['OPENAI_API_KEY']
def get_bot_backend(state_dict: Dict) -> BotBackend:
return state_dict["bot_backend"]
def add_text(state_dict: Dict, history: List, text: str) -> Tuple[List, Dict]:
bot_backend = get_bot_backend(state_dict)
bot_backend.add_text_message(user_text=text)
history = history + [(text, None)]
return history, gr.update(value="", interactive=False)
def bot(state_dict: Dict, history: List) -> List:
bot_backend = get_bot_backend(state_dict)
while bot_backend.finish_reason in ('new_input', 'function_call'):
if history[-1][0] is None:
history.append(
[None, ""]
)
else:
history[-1][1] = ""
response = chat_completion(bot_backend=bot_backend)
for chunk in response:
history, weather_exit = parse_response(
chunk=chunk,
history=history,
bot_backend=bot_backend
)
yield history
if weather_exit:
exit(-1)
yield history
if __name__ == '__main__':
config = get_config()
with gr.Blocks(theme=gr.themes.Base()) as block:
"""
Reference: https://www.gradio.app/guides/creating-a-chatbot-fast
"""
# UI components
state = gr.State(value={"bot_backend": None})
with gr.Tab("Chat"):
chatbot = gr.Chatbot([], elem_id="chatbot", label="Log-Analyzer v 1.0", height=450)
with gr.Row():
with gr.Column(scale=0.85):
text_box = gr.Textbox(
show_label=False,
placeholder="Enter text and press enter, or upload a file",
container=False
)
with gr.Row(equal_height=True):
with gr.Column(scale=0.15, min_width=0):
undo_file_button = gr.Button(value="↩️Undo upload file", interactive=False)
with gr.Tab("Files"):
file_output = gr.Files()
# Components function binding
txt_msg = text_box.submit(add_text, [state, chatbot, text_box], [chatbot, text_box], queue=False).then(
bot, [state, chatbot], chatbot
)
block.load(fn=initialization, inputs=[state])
block.queue()
block.launch(inbrowser=True)