Spaces:
Runtime error
Runtime error
| import gradio as gr | |
| from Modules import Agent_HCP | |
| import Modules | |
| import ast | |
| import pandas as pd | |
| import csv | |
| import re | |
| import os | |
| def chat_interface(query: str): | |
| if not query: | |
| return "", "" | |
| result, memory = Agent_HCP.get_response(query) | |
| # Formatage de l'historique pour affichage | |
| formatted_history = "" | |
| for message in memory.messages: | |
| if message.type == "human": | |
| formatted_history += ( | |
| f"<div style='text-align: right; margin: 10px 0; background-color: white; padding: 5px; border-radius: 5px; max-width: 60%; margin-left: auto;'>" | |
| f"<strong>User:</strong> {message.content}</div>" | |
| ) | |
| else: | |
| formatted_history += ( | |
| f"<div style='text-align: left; margin: 10px 0; background-color: lightgray; padding: 5px; border-radius: 5px; max-width: 60%;'>" | |
| f"<strong>ChatBot:</strong> {message.content}</div>" | |
| ) | |
| Modules.PARSED_LOGS=Agent_HCP.save_sql_query_input_output_steps(result) | |
| # Retourne l'historique formaté et la réponse | |
| return formatted_history, "" | |
| # Fonction pour réinitialiser l'historique | |
| def clear_history(): | |
| Agent_HCP.clear_memory() | |
| return "", "" | |
| # Fonction pour colorer les lignes en alternance | |
| def color_rows(val): | |
| # Appliquer une couleur différente pour chaque ligne (alternée) | |
| return ['background-color: #f0f0f0' if i % 2 == 0 else 'background-color: #ffffff' for i in range(len(val))] | |
| # Fonction pour lire le CSV et afficher seulement deux colonnes du DataFrame | |
| def display_dataframe(): | |
| # Lire le fichier CSV dans un DataFrame | |
| df = pd.read_csv(Modules.FILE_HISTORY, header=None, names=['INPUT', 'SQL_QUERY', 'SQL_RESULT', 'OUTPUT', "STEPS"], quoting=csv.QUOTE_MINIMAL) | |
| # Sélectionner seulement les colonnes 'INPUT', 'SQL_QUERY', 'SQL_RESULT', 'OUTPUT' | |
| df_selected = df[['INPUT', 'SQL_QUERY', 'SQL_RESULT', 'OUTPUT']].sort_index(ascending=False) | |
| # Appliquer le style au DataFrame | |
| styled_df = df_selected.style.apply(color_rows, axis=0) | |
| html_table = styled_df.to_html() | |
| return html_table | |
| def get_action_details(index): | |
| log = Modules.PARSED_LOGS[index] | |
| return ( | |
| f"<div style='color: #007BFF;'><strong>Action:</strong> {index+1}</div><br>" | |
| f"<div style='color: #28A745;'><strong>Question:</strong> {log['Question']}</div><br>" | |
| f"<div style='color: #FFC107;'><strong>Thought:</strong> {log['Thought']}</div><br>" | |
| f"<div style='color: #17A2B8;'><strong>Action:</strong> {log['Action']}</div><br>" | |
| f"<div style='color: #DC3545;'><strong>Action Input:</strong> {log['Action Input']}</div><br>" | |
| f"<div style='color: #6C757D;'><strong>Result:</strong> {log['Result']}</div>" | |
| ) | |
| # Fonction pour rafraîchir les données et créer les nouveaux boutons | |
| def fn_action_buttons(): | |
| markdown_text = gr.Markdown(f"# Visualisation des actions de l'agent\n\nIl y a {len(Modules.PARSED_LOGS)} actions.") | |
| # Vérifier s'il y a des logs à afficher | |
| if len(Modules.PARSED_LOGS) > 0: | |
| # Créer les boutons pour chaque action disponible | |
| action_buttons = [gr.Button(f"Action {i + 1}", visible=True) for i in range(len(Modules.PARSED_LOGS))] | |
| else: | |
| # Si aucune action n'est disponible, on affiche un bouton placeholder caché | |
| action_buttons = [gr.Button(visible=False)] | |
| # Compléter avec des placeholders si nécessaire | |
| while len(action_buttons) < Modules.MAX_ACTIONS: | |
| action_buttons.append(gr.Button(visible=False)) # Ajouter des boutons cachés | |
| return [markdown_text, *action_buttons] | |
| # Interface Gradio | |
| with gr.Blocks() as demo: | |
| with gr.Tabs(): | |
| with gr.TabItem("Chat"): | |
| with gr.Row(): | |
| with gr.Column(scale=1, min_width=200): | |
| gr.Markdown(""" | |
| ### Description de l'outil : | |
| - Posez vos questions sur les données de recensement de 2014 au Maroc. | |
| - Cette base de données contient seulement 50.000 personnes. | |
| """) | |
| with gr.Column(scale=4): | |
| gr.Markdown("# Parlez avec les données de HCP") | |
| chat_history = gr.HTML("") | |
| user_input = gr.Textbox(placeholder="Enter text here…", label="Your input") | |
| run_btn = gr.Button("Run") | |
| clear_btn = gr.Button("Clear History") | |
| user_input.submit(chat_interface, inputs=user_input, outputs=[chat_history, user_input]) | |
| run_btn.click(chat_interface, inputs=user_input, outputs=[chat_history, user_input]) | |
| clear_btn.click(clear_history, outputs=[chat_history, user_input]) | |
| with gr.Row() : | |
| # Ajout d'exemples | |
| gr.Examples( | |
| examples=["Combien y-a-t-il de personnes recensées ?", "Quel est le le nombre de femmes ?",\ | |
| "Combien de ménages sont dirigés par des femmes dans la province d'Al Hoceïma ?"], | |
| inputs=user_input | |
| ) | |
| with gr.TabItem("Evaluation"): | |
| gr.Markdown("# SQL EVALUATION") | |
| # Ajouter un tableau pour afficher le DataFrame dans cet onglet | |
| refresh_button = gr.Button("Rafraîchir la table") | |
| # Afficher le DataFrame | |
| html_output = gr.HTML(display_dataframe()) | |
| # Rafraîchir les données à chaque clic sur le bouton | |
| refresh_button.click(fn=display_dataframe, inputs=[], outputs=html_output) | |
| # Fonction qui rafraîchit les données et retourne le texte Markdown mis à jour | |
| with gr.TabItem("Suivi"): | |
| # Affichage du nombre d'actions et bouton de rafraîchissement | |
| info_text = gr.Markdown(f"# Visualisation des actions de l'agent\n\nIl y a {len(Modules.PARSED_LOGS)} actions.") | |
| with gr.Row(): | |
| refresh_button = gr.Button("Rafraîchir les actions") | |
| # Créer les boutons d'action initiaux | |
| with gr.Row(): | |
| # Créer les boutons pour chaque action disponible | |
| output_buttons = [gr.Button(f"Action {i + 1}", visible=False) for i in range(Modules.MAX_ACTIONS)] | |
| # Zone pour afficher les détails de l'action sélectionnée | |
| details_output = gr.Markdown("") | |
| # Lier les boutons d'action à la fonction pour afficher les détails | |
| for i, button in enumerate(output_buttons): | |
| button.click(get_action_details, inputs=[gr.Number(i, visible=False)], outputs=details_output) | |
| # Action du bouton de rafraîchissement | |
| refresh_button.click( | |
| fn_action_buttons, # Fonction appelée lors du clic | |
| outputs=[info_text] + output_buttons # Mise à jour des éléments Markdown et boutons | |
| ) | |
| with gr.TabItem("V1-Graph"): | |
| info_graph = gr.Markdown(f"# La version1 est un agent graph.") | |
| def afficher_image(): | |
| # Remplacez le chemin par votre image | |
| image_path = os.path.abspath("Output/graph.jpeg") | |
| return image_path | |
| gr.Image(afficher_image()) | |
| with gr.TabItem("V2-Graph-RAG"): | |
| info_graph = gr.Markdown(f"# Dans la version2, RAG est intégré au graph.") | |
| def afficher_image_graph(): | |
| # Remplacez le chemin par votre image | |
| image_path = os.path.abspath("Output/graph_rag.jpeg") | |
| return image_path | |
| gr.Image(afficher_image_graph()) | |
| demo.launch(share=False) | |
| #demo.launch(share=True, auth=("username", "password")) | |