| |
| import gradio as gr |
| import asyncio |
| import re |
|
|
| from client_agent import stream_agent_response_safe, get_current_chart, PLACEHOLDER_IMAGE |
|
|
| CUSTOM_CSS = """(seu css)""" |
|
|
| async def simulate_streaming_adaptive(full_text: str): |
| words = re.findall(r"\S+|\s+", full_text) |
| current = "" |
| for w in words: |
| current += w |
| if w.strip().endswith((".", "!", "?")): |
| await asyncio.sleep(0.12) |
| elif w.strip().endswith((",", ";", ":")): |
| await asyncio.sleep(0.06) |
| else: |
| await asyncio.sleep(0.02) |
| yield current |
|
|
| async def respond(message, history): |
| if not message or not message.strip(): |
| yield history, get_current_chart() |
| return |
|
|
| history = history + [gr.ChatMessage(role="user", content=message)] |
| history.append(gr.ChatMessage(role="assistant", content="")) |
|
|
| try: |
| full_response = await stream_agent_response_safe(message) |
| async for partial in simulate_streaming_adaptive(full_response): |
| history[-1] = gr.ChatMessage(role="assistant", content=partial) |
| yield history, get_current_chart() |
| yield history, get_current_chart() |
| except Exception as e: |
| history[-1] = gr.ChatMessage(role="assistant", content=f"⚠️ Error: {e}") |
| yield history, get_current_chart() |
|
|
| def refresh_chart(): |
| return get_current_chart() |
|
|
| if __name__ == "__main__": |
| with gr.Blocks(title="Barcelona Analytics Platform", css=CUSTOM_CSS) as demo: |
| gr.Markdown("# AI Data Analyst Agent for FC Barcelona") |
|
|
| with gr.Tabs(): |
| with gr.Tab("Analysis & Chat"): |
| chatbot = gr.Chatbot(type="messages", height=520, show_copy_button=True) |
| with gr.Row(): |
| msg = gr.Textbox(placeholder="Ask...", lines=2, scale=4, show_label=False) |
| submit_btn = gr.Button("Send", variant="primary", scale=1) |
|
|
| with gr.Tab("Data Visualization"): |
| chart_display = gr.Image( |
| value=PLACEHOLDER_IMAGE, |
| type="pil", |
| height=620, |
| show_download_button=True, |
| show_share_button=False, |
| show_label=False, |
| ) |
| refresh_btn = gr.Button("🔄 Refresh Visualization", variant="secondary") |
|
|
| submit_btn.click(fn=respond, inputs=[msg, chatbot], outputs=[chatbot, chart_display]).then( |
| lambda: "", None, [msg] |
| ) |
| msg.submit(fn=respond, inputs=[msg, chatbot], outputs=[chatbot, chart_display]).then( |
| lambda: "", None, [msg] |
| ) |
| refresh_btn.click(fn=refresh_chart, inputs=[], outputs=[chart_display]) |
|
|
| demo.launch(ssr_mode=False, share=False) |
|
|