#!/usr/bin/env python3 """ Hockey Mind AI Chatbot - Fixed Gradio Interface for Hugging Face Spaces """ import gradio as gr import asyncio import os from dotenv import load_dotenv from OpenAPI_DB import agentic_hockey_chat # Load environment variables load_dotenv() # Global variable to track if resources are loaded resources_loaded = False async def chat_interface(user_role, user_team, user_prompt): """Interface function for Gradio""" global resources_loaded try: # Load resources on first use to save memory if not resources_loaded: try: from OpenAPI_DB import load_resources load_resources() resources_loaded = True except ImportError as import_err: return f"Import Error: {str(import_err)}. Please check if all required packages are installed.", "Unable to load ML models." # Call the main chat function result = await agentic_hockey_chat(user_role, user_team, user_prompt) # Format response for Gradio ai_response = result.get('ai_response', 'Sorry, no response generated.') recommendations = result.get('recommended_content_details', []) # Format recommendations as HTML rec_html = "" if recommendations: rec_html = "

🏒 Recommended Videos:

" return ai_response, rec_html except Exception as e: import traceback error_details = traceback.format_exc() return f"Error: {str(e)}\n\nDetails:\n{error_details}", "No recommendations available due to error." def sync_chat_interface(user_role, user_team, user_prompt): """Synchronous wrapper for Gradio""" return asyncio.run(chat_interface(user_role, user_team, user_prompt)) # Gradio Interface with gr.Blocks( title="🏒 Hockey Mind AI Chatbot", theme=gr.themes.Soft(), css=""" .gradio-container {max-width: 800px !important; margin: auto !important;} .main-header {text-align: center; margin-bottom: 2rem;} """ ) as demo: gr.HTML("""

🏒 Hockey Mind AI Chatbot

Get personalized hockey advice and video recommendations!

Optimized for field hockey coaching, training, and player development

""") with gr.Row(): with gr.Column(): user_role = gr.Dropdown( choices=["le Trainer", "le Coach", "Speler"], label="Your Role 👤", value="Coach" ) user_team = gr.Textbox( label="Team/Level 🏒", placeholder="e.g., U8C, Toronto Maple Leafs, Beginner", value="U10" ) user_prompt = gr.Textbox( label="Your Question ❓", placeholder="Ask about drills, techniques, strategies, rules...", lines=3 ) submit_btn = gr.Button("Get Hockey Advice 🚀", variant="primary", size="lg") with gr.Row(): ai_response = gr.Textbox( label="🤖 AI Response", lines=8, interactive=False ) with gr.Row(): recommendations = gr.HTML() # Examples section gr.HTML("

💡 Example Questions:

") examples = gr.Examples( examples=[ ["Coach", "U8C", "What are the best backhand shooting drills for young players?"], ["Player", "Intermediate", "How can I improve my penalty corner technique?"], ["le Coach", "U10", "Geef me oefeningen voor backhandschoten"], ["Parent", "Beginner", "What equipment does my child need to start playing hockey?"], ["Coach", "Advanced", "What are effective small-sided games for skill development?"], ], inputs=[user_role, user_team, user_prompt], outputs=[ai_response, recommendations], fn=sync_chat_interface, ) # Event handler submit_btn.click( fn=sync_chat_interface, inputs=[user_role, user_team, user_prompt], outputs=[ai_response, recommendations], api_name="chat" ) user_prompt.submit( fn=sync_chat_interface, inputs=[user_role, user_team, user_prompt], outputs=[ai_response, recommendations] ) # Footer gr.HTML("""

🏒 Hockey Mind AI - Powered by OpenRouter & Sentence Transformers

Supports English & Dutch | Built for field hockey community

""") # Launch configuration for Hugging Face Spaces if __name__ == "__main__": # Check if running on Hugging Face Spaces if os.getenv("SPACE_ID"): # Production mode on HF Spaces demo.launch( server_name="0.0.0.0", server_port=7860, share=False, show_error=True, quiet=False ) else: # Local development mode demo.launch( share=True, show_error=True )