PROPERT_AI / app.py
msa240's picture
changing app file
f75fd18
Raw
History Blame Contribute Delete
2.78 kB
import os
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse, Response
from pydantic import BaseModel
from src.chatbot import handle_query
from pathlib import Path
class ChatRequest(BaseModel):
query: str
class ChatResponse(BaseModel):
answer: str
cards: list = []
app = FastAPI(title="NoBrokerage Chatbot")
# CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Get the directory where app.py is located
BASE_DIR = Path(__file__).resolve().parent
frontend_path = BASE_DIR / "frontend"
@app.get("/")
async def root():
"""Serve the frontend HTML"""
html_file = frontend_path / "index.html"
if html_file.exists():
return FileResponse(html_file)
return {"error": "index.html not found", "path": str(html_file)}
@app.get("/style.css")
async def get_css():
"""Serve CSS file"""
css_file = frontend_path / "style.css"
if css_file.exists():
return FileResponse(css_file, media_type="text/css")
return {"error": "style.css not found"}
@app.get("/script.js")
async def get_js():
"""Serve JavaScript file with automatic API URL fix"""
js_file = frontend_path / "script.js"
if js_file.exists():
# Read the original file
with open(js_file, 'r', encoding='utf-8') as f:
content = f.read()
# Replace localhost URL with empty string for same-origin requests
content = content.replace(
'const API_BASE_URL = "http://localhost:8000";',
'const API_BASE_URL = "";'
)
# Return the modified JavaScript
return Response(content=content, media_type="application/javascript")
return {"error": "script.js not found"}
@app.get("/logo.png")
async def get_logo():
"""Serve logo image"""
logo_file = frontend_path / "logo.png"
if logo_file.exists():
return FileResponse(logo_file, media_type="image/png")
# Return a placeholder or error
return {"error": "logo.png not found"}
@app.post("/chat", response_model=ChatResponse)
def chat(request: ChatRequest):
"""Handle chat requests"""
result = handle_query(request.query)
return ChatResponse(answer=result.get("summary"), cards=result.get("cards", []))
@app.get("/health")
def health():
"""Health check endpoint"""
return {"status": "ok", "message": "✅ NoBrokerage running"}
# For Hugging Face Spaces
if __name__ == "__main__":
import uvicorn
port = int(os.environ.get("PORT", 7860))
uvicorn.run(app, host="0.0.0.0", port=port)