Edurag_beta / ui /chatbot_tab.py
Nugh75's picture
Creazione function e database_hundling
b2638ec
raw
history blame
3.2 kB
# ui/chatbot_tab.py
import gradio as gr
from app.functions.database_handling import list_databases
from utils.helpers import extract_text_from_files
from app.llm_handling import answer_question
def create_chatbot_tab():
"""Crea il tab 'Chatbot' dell'interfaccia Gradio."""
def chat_upload_and_respond(files, chat_history, db_name):
"""Gestisce il caricamento dei file e aggiorna la chat con il contenuto."""
if chat_history is None:
chat_history = []
text = extract_text_from_files(files)
chat_history.append({
"role": "assistant",
"content": f"πŸ“„ Contenuto dei documenti caricati:\n{text}"
})
return chat_history
def respond(message, chat_history, db_name):
"""Genera una risposta alla domanda dell'utente e aggiorna la chat."""
if chat_history is None:
chat_history = []
new_messages = answer_question(message, db_name)
chat_history.extend(new_messages)
return "", chat_history
def clear_chat():
"""Pulisce la cronologia della chat."""
return [], []
# Ottieni la lista aggiornata dei database
databases = list_databases()
with gr.Tab("Chatbot"):
with gr.Row():
with gr.Column(scale=2):
# Dropdown per selezionare il database
db_name_chat = gr.Dropdown(
choices=databases,
label="Seleziona Database",
value="default_db"
)
# Componente Chatbot
chatbot = gr.Chatbot(label="Conversazione", type="messages")
# Input per la domanda
question_input = gr.Textbox(
label="Fai una domanda",
placeholder="Scrivi qui la tua domanda...",
lines=2
)
# Bottoni per azioni
with gr.Row():
ask_button = gr.Button("Invia")
clear_button = gr.Button("Pulisci Chat")
# Upload file con dimensioni ridotte
with gr.Row():
file_input = gr.File(
label="Carica PDF/Docx/TXT per la conversazione",
file_types=[".pdf", ".docx", ".txt"],
file_count="multiple",
height="100px",
scale=3
)
upload_button = gr.Button("Carica Documenti", scale=1)
# Stato della chat
chat_state = gr.State([])
# Eventi per i bottoni
upload_button.click(
fn=chat_upload_and_respond,
inputs=[file_input, chat_state, db_name_chat],
outputs=chatbot
)
ask_button.click(
fn=respond,
inputs=[question_input, chat_state, db_name_chat],
outputs=[question_input, chatbot]
)
clear_button.click(
fn=clear_chat,
outputs=[chatbot, chat_state]
)
return