Spaces:
Sleeping
Sleeping
Create main.py
Browse files
main.py
ADDED
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# main.py
|
2 |
+
|
3 |
+
from fastapi import FastAPI, HTTPException
|
4 |
+
from fastapi.middleware.cors import CORSMiddleware
|
5 |
+
from uuid import uuid4
|
6 |
+
|
7 |
+
from models import InitChatRequest, ChatRequest, EndSessionRequest
|
8 |
+
from rag_chain import build_chain
|
9 |
+
|
10 |
+
app = FastAPI()
|
11 |
+
|
12 |
+
# CORS setup
|
13 |
+
app.add_middleware(
|
14 |
+
CORSMiddleware,
|
15 |
+
allow_origins=["*"],
|
16 |
+
allow_credentials=True,
|
17 |
+
allow_methods=["*"],
|
18 |
+
allow_headers=["*"],
|
19 |
+
)
|
20 |
+
|
21 |
+
# In-memory session storage
|
22 |
+
chat_sessions = {}
|
23 |
+
|
24 |
+
@app.post("/init")
|
25 |
+
def initialize_chat(req: InitChatRequest):
|
26 |
+
try:
|
27 |
+
session_id = str(uuid4())
|
28 |
+
qa_chain = build_chain(req.video_id)
|
29 |
+
chat_sessions[session_id] = qa_chain
|
30 |
+
return {"message": "Chat session started", "session_id": session_id}
|
31 |
+
except Exception as e:
|
32 |
+
raise HTTPException(status_code=500, detail=str(e))
|
33 |
+
|
34 |
+
|
35 |
+
@app.post("/chat")
|
36 |
+
def chat(req: ChatRequest):
|
37 |
+
session_id = req.session_id
|
38 |
+
if session_id not in chat_sessions:
|
39 |
+
raise HTTPException(status_code=404, detail="Invalid session ID. Initialize session first.")
|
40 |
+
|
41 |
+
try:
|
42 |
+
qa_chain = chat_sessions[session_id]
|
43 |
+
result = qa_chain.invoke({"query": req.query})
|
44 |
+
|
45 |
+
return {
|
46 |
+
"answer": result["result"],
|
47 |
+
"sources": [doc.page_content for doc in result["source_documents"]]
|
48 |
+
}
|
49 |
+
except Exception as e:
|
50 |
+
raise HTTPException(status_code=500, detail=str(e))
|
51 |
+
|
52 |
+
|
53 |
+
@app.post("/end")
|
54 |
+
def end_chat_session(req: EndSessionRequest):
|
55 |
+
session_id = req.session_id
|
56 |
+
if session_id in chat_sessions:
|
57 |
+
del chat_sessions[session_id]
|
58 |
+
return {"message": f"Session {session_id} ended successfully."}
|
59 |
+
else:
|
60 |
+
raise HTTPException(status_code=404, detail="Session ID not found.")
|