Spaces:
Runtime error
Runtime error
| from fastapi import FastAPI, Request | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from pathlib import Path | |
| import uvicorn | |
| import RAG_Solution_FIXED as rag # your existing RAG logic | |
| app = FastAPI(title="GuessBot API", description="RAG Chatbot API for WordPress integration") | |
| # Enable CORS for your WordPress frontend | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], # You can replace * with your site domain for security | |
| allow_credentials=True, | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| # --- Load RAG components once at startup --- | |
| print("--- Initializing RAG Model ---") | |
| data_dir = Path("./data") | |
| print("[1/4] Loading text files...") | |
| texts = rag.load_text_files(data_dir) | |
| print("β Texts loaded.") | |
| print("[2/4] Building text chunks...") | |
| docs = rag.build_chunks(texts) | |
| print("β Chunks ready.") | |
| print("[3/4] Building vector store...") | |
| vs = rag.build_vectorstore(docs) | |
| print("β Vector store built.") | |
| print("[4/4] Loading generative model...") | |
| generator = rag.make_generator() | |
| print("β Model ready.") | |
| print("π Model loading complete. API is now live.") | |
| # --- Routes --- | |
| async def root(): | |
| return {"message": "GuessBot API is running successfully!"} | |
| async def ask_question(request: Request): | |
| """Receives a question and returns an answer.""" | |
| data = await request.json() | |
| question = data.get("question", None) | |
| if not question: | |
| return {"error": "Missing question in request body"} | |
| try: | |
| answer, _, _ = rag.answer_question(vs, generator, question) | |
| return {"answer": answer.strip()} | |
| except Exception as e: | |
| return {"error": str(e)} | |
| # --- Entry point for local testing (ignored by HF Spaces) --- | |
| if __name__ == "__main__": | |
| uvicorn.run(app, host="0.0.0.0", port=7860) | |