# app.py (Smart detection for HF Spaces deployment) import os import sys # Add path for imports sys.path.append(os.path.join(os.path.dirname(__file__))) def is_huggingface_space(): """Detect if running on Hugging Face Spaces""" return os.getenv("SPACE_ID") is not None def ensure_database_ready(): """Only rebuild database on HF Spaces""" if is_huggingface_space(): print("🔄 HF Spaces detected - ensuring database is ready...") # Check if database exists and has content vector_db_path = "./vector_db" needs_setup = False if not os.path.exists(vector_db_path): print("📄 Vector database not found, setting up...") needs_setup = True else: try: from app.dutch_chatbot.vector_store import VectorStore vs = VectorStore() vs.create_collection() info = vs.get_collection_info() if info.get('document_count', 0) == 0: print("📄 Vector database empty, rebuilding...") needs_setup = True else: print(f"✅ Vector database ready with {info.get('document_count')} documents") except Exception as e: print(f"📄 Vector database error, rebuilding... ({e})") needs_setup = True if needs_setup: print("📄 Processing PDF documents...") from app.dutch_chatbot.document_processor import DocumentProcessor from app.dutch_chatbot.vector_store import VectorStore processor = DocumentProcessor() chunks = processor.process_all_pdfs() if chunks: print("💾 Storing in vector database...") vector_store = VectorStore() vector_store.create_collection() vector_store.add_documents(chunks) print(f"✅ Database ready with {len(chunks)} chunks!") else: print("❌ No documents found to process") else: print("✅ Local environment detected - using existing database") # Import your existing gradio app components from app.interfaces.gradio_app import create_chatbot_interface from app.dutch_chatbot.config import Config import logging def main(): """Main function to launch the Gradio app.""" config = Config() print("🧬 Starting DUTCH Test Assistant...") print("=" * 50) try: # Validate configuration config.validate() # Only rebuild database on HF Spaces ensure_database_ready() # Use your existing interface demo = create_chatbot_interface() # Launch with environment-appropriate settings launch_config = { "server_name": "0.0.0.0", "server_port": 7860, "show_error": True, "share": False, "debug": config.DEBUG } # Only add auth for local non-debug mode if not is_huggingface_space() and not config.DEBUG: launch_config["auth"] = ("admin", "dutchtest123") print(f"🚀 Launching on: http://localhost:7860") print(f"📝 Debug mode: {config.DEBUG}") print(f"🌐 Environment: {'Hugging Face Spaces' if is_huggingface_space() else 'Local'}") demo.launch(**launch_config) except Exception as e: logging.error(f"Failed to launch app: {e}") print(f"❌ Error: {e}") print("\nTroubleshooting:") print("1. Make sure you've run: uv run python scripts/setup_vector_db.py") print("2. Check your .env file has ANTHROPIC_API_KEY set") print("3. Ensure PDF documents are in knowledge_base/pdfs/") if __name__ == "__main__": main()