Guessbot / app.py
Mihirsingh1101's picture
Update app.py
db3c55e verified
raw
history blame
1.81 kB
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 ---
@app.get("/")
async def root():
return {"message": "GuessBot API is running successfully!"}
@app.post("/ask")
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)