Spaces:
Running
Running
Upload app.py
Browse files- src/apps/app.py +24 -6
src/apps/app.py
CHANGED
|
@@ -16,7 +16,7 @@ from sqlalchemy.future import select
|
|
| 16 |
from pydantic import BaseModel, EmailStr
|
| 17 |
|
| 18 |
from utils.main import RAG
|
| 19 |
-
from database import engine, Base, get_db
|
| 20 |
from models import User
|
| 21 |
from auth import get_password_hash, verify_password, create_access_token, ACCESS_TOKEN_EXPIRE_MINUTES, ALGORITHM, SECRET_KEY
|
| 22 |
from email_utils import send_reset_email
|
|
@@ -25,6 +25,8 @@ from fastapi.security import OAuth2PasswordBearer
|
|
| 25 |
from jose import JWTError, jwt
|
| 26 |
import uuid
|
| 27 |
|
|
|
|
|
|
|
| 28 |
# Initialize Database and Create Default Admin
|
| 29 |
async def init_db():
|
| 30 |
async with engine.begin() as conn:
|
|
@@ -338,11 +340,11 @@ async def reset_password_page(request: Request):
|
|
| 338 |
# Home and Role Selection
|
| 339 |
@app.get("/", response_class=HTMLResponse)
|
| 340 |
async def role_selection(request: Request):
|
| 341 |
-
return templates.TemplateResponse("roleselection.html", {"request": request})
|
| 342 |
|
| 343 |
@app.get("/role", response_class=HTMLResponse)
|
| 344 |
async def roleselection_page(request: Request):
|
| 345 |
-
return templates.TemplateResponse("roleselection.html", {"request": request})
|
| 346 |
|
| 347 |
# Chatbot Pages
|
| 348 |
@app.get("/judgechatbot.html", response_class=HTMLResponse)
|
|
@@ -395,6 +397,8 @@ async def advocatechatbot_page(request: Request):
|
|
| 395 |
async def womanchatbot_page(request: Request):
|
| 396 |
return templates.TemplateResponse("womanchatbot.html", {"request": request})
|
| 397 |
|
|
|
|
|
|
|
| 398 |
@app.get("/safetytips.html", response_class=HTMLResponse)
|
| 399 |
async def safetytips_page(request: Request):
|
| 400 |
return templates.TemplateResponse("safetytips.html", {"request": request})
|
|
@@ -420,16 +424,23 @@ async def stream_text_conversational(websocket: WebSocket, query: str, role: str
|
|
| 420 |
chat_limit = 10
|
| 421 |
temp_chat = {"user": "" ,"system":""}
|
| 422 |
temp_chat["user"] = query
|
|
|
|
| 423 |
model_response = ""
|
| 424 |
try:
|
| 425 |
-
|
|
|
|
|
|
|
|
|
|
| 426 |
for chunk in completion:
|
| 427 |
if chunk.choices[0].delta.content is not None:
|
| 428 |
await websocket.send_text(chunk.choices[0].delta.content)
|
| 429 |
await asyncio.sleep(0.01)
|
| 430 |
model_response += chunk.choices[0].delta.content
|
| 431 |
|
|
|
|
| 432 |
await websocket.send_text("[DONE]")
|
|
|
|
|
|
|
| 433 |
temp_chat['system']=model_response
|
| 434 |
chat_history.append(temp_chat)
|
| 435 |
if len(chat_history)>chat_limit:
|
|
@@ -444,6 +455,8 @@ async def stream_text_conversational(websocket: WebSocket, query: str, role: str
|
|
| 444 |
async def conversational_chat(websocket: WebSocket, role: Optional[str] = None):
|
| 445 |
await websocket.accept()
|
| 446 |
|
|
|
|
|
|
|
| 447 |
token = websocket.cookies.get("access_token")
|
| 448 |
token_role = "General"
|
| 449 |
user_id = None
|
|
@@ -470,6 +483,7 @@ async def conversational_chat(websocket: WebSocket, role: Optional[str] = None):
|
|
| 470 |
await websocket.close()
|
| 471 |
return
|
| 472 |
|
|
|
|
| 473 |
if token_role == "Admin":
|
| 474 |
if not role:
|
| 475 |
role = "Admin"
|
|
@@ -480,6 +494,7 @@ async def conversational_chat(websocket: WebSocket, role: Optional[str] = None):
|
|
| 480 |
try:
|
| 481 |
query = await websocket.receive_text()
|
| 482 |
|
|
|
|
| 483 |
if token_role != "Admin" and question_count >= 2:
|
| 484 |
limit_message = (
|
| 485 |
"### Free usage limit reached\n\n"
|
|
@@ -494,13 +509,14 @@ async def conversational_chat(websocket: WebSocket, role: Optional[str] = None):
|
|
| 494 |
print(f"Query ({role}): {query}")
|
| 495 |
await stream_text_conversational(websocket, query, role=role)
|
| 496 |
|
|
|
|
| 497 |
if token_role != "Admin":
|
| 498 |
async for db in get_db():
|
| 499 |
result = await db.execute(select(User).where(User.id == user_id))
|
| 500 |
user_to_update = result.scalars().first()
|
| 501 |
if user_to_update:
|
| 502 |
user_to_update.question_count += 1
|
| 503 |
-
question_count = user_to_update.question_count
|
| 504 |
await db.commit()
|
| 505 |
break
|
| 506 |
|
|
@@ -515,7 +531,9 @@ async def conversational_chat(websocket: WebSocket, role: Optional[str] = None):
|
|
| 515 |
pass
|
| 516 |
break
|
| 517 |
|
|
|
|
| 518 |
# Run the application
|
| 519 |
if __name__ == "__main__":
|
|
|
|
| 520 |
port = int(os.getenv("PORT", 8000))
|
| 521 |
-
uvicorn.run(app, host="0.0.0.0", port=port)
|
|
|
|
| 16 |
from pydantic import BaseModel, EmailStr
|
| 17 |
|
| 18 |
from utils.main import RAG
|
| 19 |
+
from database import engine, Base, get_db
|
| 20 |
from models import User
|
| 21 |
from auth import get_password_hash, verify_password, create_access_token, ACCESS_TOKEN_EXPIRE_MINUTES, ALGORITHM, SECRET_KEY
|
| 22 |
from email_utils import send_reset_email
|
|
|
|
| 25 |
from jose import JWTError, jwt
|
| 26 |
import uuid
|
| 27 |
|
| 28 |
+
from database import engine, Base, get_db, AsyncSessionLocal
|
| 29 |
+
|
| 30 |
# Initialize Database and Create Default Admin
|
| 31 |
async def init_db():
|
| 32 |
async with engine.begin() as conn:
|
|
|
|
| 340 |
# Home and Role Selection
|
| 341 |
@app.get("/", response_class=HTMLResponse)
|
| 342 |
async def role_selection(request: Request):
|
| 343 |
+
return templates.TemplateResponse("roleselection.html", {"request": request, "show_roles": False})
|
| 344 |
|
| 345 |
@app.get("/role", response_class=HTMLResponse)
|
| 346 |
async def roleselection_page(request: Request):
|
| 347 |
+
return templates.TemplateResponse("roleselection.html", {"request": request, "show_roles": True})
|
| 348 |
|
| 349 |
# Chatbot Pages
|
| 350 |
@app.get("/judgechatbot.html", response_class=HTMLResponse)
|
|
|
|
| 397 |
async def womanchatbot_page(request: Request):
|
| 398 |
return templates.TemplateResponse("womanchatbot.html", {"request": request})
|
| 399 |
|
| 400 |
+
|
| 401 |
+
|
| 402 |
@app.get("/safetytips.html", response_class=HTMLResponse)
|
| 403 |
async def safetytips_page(request: Request):
|
| 404 |
return templates.TemplateResponse("safetytips.html", {"request": request})
|
|
|
|
| 424 |
chat_limit = 10
|
| 425 |
temp_chat = {"user": "" ,"system":""}
|
| 426 |
temp_chat["user"] = query
|
| 427 |
+
# print(f"DEBUG: stream_text_conversational executing with role={role}")
|
| 428 |
model_response = ""
|
| 429 |
try:
|
| 430 |
+
if role == "Citizen":
|
| 431 |
+
completion = RAG(query, chat_history, role=role)
|
| 432 |
+
else:
|
| 433 |
+
completion = RAG(query, chat_history, role=role)
|
| 434 |
for chunk in completion:
|
| 435 |
if chunk.choices[0].delta.content is not None:
|
| 436 |
await websocket.send_text(chunk.choices[0].delta.content)
|
| 437 |
await asyncio.sleep(0.01)
|
| 438 |
model_response += chunk.choices[0].delta.content
|
| 439 |
|
| 440 |
+
# Signal completion to frontend
|
| 441 |
await websocket.send_text("[DONE]")
|
| 442 |
+
|
| 443 |
+
# print(model_response)
|
| 444 |
temp_chat['system']=model_response
|
| 445 |
chat_history.append(temp_chat)
|
| 446 |
if len(chat_history)>chat_limit:
|
|
|
|
| 455 |
async def conversational_chat(websocket: WebSocket, role: Optional[str] = None):
|
| 456 |
await websocket.accept()
|
| 457 |
|
| 458 |
+
# --- STRICT ROLE ENFORCEMENT ---
|
| 459 |
+
# 1. Get role from Token/Cookie (Source of Truth)
|
| 460 |
token = websocket.cookies.get("access_token")
|
| 461 |
token_role = "General"
|
| 462 |
user_id = None
|
|
|
|
| 483 |
await websocket.close()
|
| 484 |
return
|
| 485 |
|
| 486 |
+
# 2. Apply Logic based on Source of Truth
|
| 487 |
if token_role == "Admin":
|
| 488 |
if not role:
|
| 489 |
role = "Admin"
|
|
|
|
| 494 |
try:
|
| 495 |
query = await websocket.receive_text()
|
| 496 |
|
| 497 |
+
# --- USAGE LIMIT CHECK ---
|
| 498 |
if token_role != "Admin" and question_count >= 2:
|
| 499 |
limit_message = (
|
| 500 |
"### Free usage limit reached\n\n"
|
|
|
|
| 509 |
print(f"Query ({role}): {query}")
|
| 510 |
await stream_text_conversational(websocket, query, role=role)
|
| 511 |
|
| 512 |
+
# --- INCREMENT USAGE ---
|
| 513 |
if token_role != "Admin":
|
| 514 |
async for db in get_db():
|
| 515 |
result = await db.execute(select(User).where(User.id == user_id))
|
| 516 |
user_to_update = result.scalars().first()
|
| 517 |
if user_to_update:
|
| 518 |
user_to_update.question_count += 1
|
| 519 |
+
question_count = user_to_update.question_count # Keep local sync
|
| 520 |
await db.commit()
|
| 521 |
break
|
| 522 |
|
|
|
|
| 531 |
pass
|
| 532 |
break
|
| 533 |
|
| 534 |
+
|
| 535 |
# Run the application
|
| 536 |
if __name__ == "__main__":
|
| 537 |
+
print("Starting Law Bot Server...")
|
| 538 |
port = int(os.getenv("PORT", 8000))
|
| 539 |
+
uvicorn.run(app, host="0.0.0.0", port=port)
|