Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -4,30 +4,53 @@ os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
|
| 4 |
from dotenv import load_dotenv
|
| 5 |
load_dotenv()
|
| 6 |
|
| 7 |
-
from fastapi import FastAPI
|
| 8 |
from fastapi.middleware.cors import CORSMiddleware
|
| 9 |
from pydantic import BaseModel
|
| 10 |
from chatbot import generate_response
|
| 11 |
|
|
|
|
| 12 |
app = FastAPI(title="Aaple Sarkar Chatbot API")
|
| 13 |
|
| 14 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
app.add_middleware(
|
| 16 |
CORSMiddleware,
|
| 17 |
-
allow_origins=["*"],
|
| 18 |
allow_methods=["*"],
|
| 19 |
allow_headers=["*"],
|
| 20 |
)
|
| 21 |
|
|
|
|
| 22 |
class ChatRequest(BaseModel):
|
| 23 |
query: str
|
| 24 |
language: str = "en"
|
| 25 |
|
|
|
|
| 26 |
@app.get("/health")
|
| 27 |
def health():
|
| 28 |
return {"status": "ok"}
|
| 29 |
|
| 30 |
@app.post("/chat")
|
| 31 |
-
def chat(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
answer = generate_response(req.query, req.language)
|
| 33 |
-
return {"answer": answer}
|
|
|
|
| 4 |
from dotenv import load_dotenv
|
| 5 |
load_dotenv()
|
| 6 |
|
| 7 |
+
from fastapi import FastAPI, Header, HTTPException
|
| 8 |
from fastapi.middleware.cors import CORSMiddleware
|
| 9 |
from pydantic import BaseModel
|
| 10 |
from chatbot import generate_response
|
| 11 |
|
| 12 |
+
# ================= APP =================
|
| 13 |
app = FastAPI(title="Aaple Sarkar Chatbot API")
|
| 14 |
|
| 15 |
+
# ================= AUTH =================
|
| 16 |
+
def verify_api_key(x_api_key: str = Header(None)):
|
| 17 |
+
expected_key = os.getenv("CHATBOT_API_KEY")
|
| 18 |
+
|
| 19 |
+
if not expected_key:
|
| 20 |
+
raise HTTPException(
|
| 21 |
+
status_code=500,
|
| 22 |
+
detail="Server misconfiguration"
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
if x_api_key != expected_key:
|
| 26 |
+
raise HTTPException(
|
| 27 |
+
status_code=401,
|
| 28 |
+
detail="Unauthorized"
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
# ================= CORS =================
|
| 32 |
app.add_middleware(
|
| 33 |
CORSMiddleware,
|
| 34 |
+
allow_origins=["*"], # restrict later if needed
|
| 35 |
allow_methods=["*"],
|
| 36 |
allow_headers=["*"],
|
| 37 |
)
|
| 38 |
|
| 39 |
+
# ================= SCHEMAS =================
|
| 40 |
class ChatRequest(BaseModel):
|
| 41 |
query: str
|
| 42 |
language: str = "en"
|
| 43 |
|
| 44 |
+
# ================= ROUTES =================
|
| 45 |
@app.get("/health")
|
| 46 |
def health():
|
| 47 |
return {"status": "ok"}
|
| 48 |
|
| 49 |
@app.post("/chat")
|
| 50 |
+
def chat(
|
| 51 |
+
req: ChatRequest,
|
| 52 |
+
x_api_key: str = Header(None)
|
| 53 |
+
):
|
| 54 |
+
verify_api_key(x_api_key)
|
| 55 |
answer = generate_response(req.query, req.language)
|
| 56 |
+
return {"answer": answer}
|