Spaces:
Running
Running
Update src/apps/app.py
Browse files- src/apps/app.py +22 -21
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,10 +25,27 @@ from fastapi.security import OAuth2PasswordBearer
|
|
| 25 |
from jose import JWTError, jwt
|
| 26 |
import uuid
|
| 27 |
|
| 28 |
-
# Initialize Database
|
| 29 |
async def init_db():
|
| 30 |
async with engine.begin() as conn:
|
| 31 |
await conn.run_sync(Base.metadata.create_all)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
|
| 33 |
app = FastAPI(on_startup=[init_db])
|
| 34 |
|
|
@@ -378,8 +395,6 @@ async def advocatechatbot_page(request: Request):
|
|
| 378 |
async def womanchatbot_page(request: Request):
|
| 379 |
return templates.TemplateResponse("womanchatbot.html", {"request": request})
|
| 380 |
|
| 381 |
-
|
| 382 |
-
|
| 383 |
@app.get("/safetytips.html", response_class=HTMLResponse)
|
| 384 |
async def safetytips_page(request: Request):
|
| 385 |
return templates.TemplateResponse("safetytips.html", {"request": request})
|
|
@@ -405,23 +420,16 @@ async def stream_text_conversational(websocket: WebSocket, query: str, role: str
|
|
| 405 |
chat_limit = 10
|
| 406 |
temp_chat = {"user": "" ,"system":""}
|
| 407 |
temp_chat["user"] = query
|
| 408 |
-
# print(f"DEBUG: stream_text_conversational executing with role={role}")
|
| 409 |
model_response = ""
|
| 410 |
try:
|
| 411 |
-
|
| 412 |
-
completion = RAG(query, chat_history, role=role)
|
| 413 |
-
else:
|
| 414 |
-
completion = RAG(query, chat_history, role=role)
|
| 415 |
for chunk in completion:
|
| 416 |
if chunk.choices[0].delta.content is not None:
|
| 417 |
await websocket.send_text(chunk.choices[0].delta.content)
|
| 418 |
await asyncio.sleep(0.01)
|
| 419 |
model_response += chunk.choices[0].delta.content
|
| 420 |
|
| 421 |
-
# Signal completion to frontend
|
| 422 |
await websocket.send_text("[DONE]")
|
| 423 |
-
|
| 424 |
-
# print(model_response)
|
| 425 |
temp_chat['system']=model_response
|
| 426 |
chat_history.append(temp_chat)
|
| 427 |
if len(chat_history)>chat_limit:
|
|
@@ -436,8 +444,6 @@ async def stream_text_conversational(websocket: WebSocket, query: str, role: str
|
|
| 436 |
async def conversational_chat(websocket: WebSocket, role: Optional[str] = None):
|
| 437 |
await websocket.accept()
|
| 438 |
|
| 439 |
-
# --- STRICT ROLE ENFORCEMENT ---
|
| 440 |
-
# 1. Get role from Token/Cookie (Source of Truth)
|
| 441 |
token = websocket.cookies.get("access_token")
|
| 442 |
token_role = "General"
|
| 443 |
user_id = None
|
|
@@ -464,7 +470,6 @@ async def conversational_chat(websocket: WebSocket, role: Optional[str] = None):
|
|
| 464 |
await websocket.close()
|
| 465 |
return
|
| 466 |
|
| 467 |
-
# 2. Apply Logic based on Source of Truth
|
| 468 |
if token_role == "Admin":
|
| 469 |
if not role:
|
| 470 |
role = "Admin"
|
|
@@ -475,7 +480,6 @@ async def conversational_chat(websocket: WebSocket, role: Optional[str] = None):
|
|
| 475 |
try:
|
| 476 |
query = await websocket.receive_text()
|
| 477 |
|
| 478 |
-
# --- USAGE LIMIT CHECK ---
|
| 479 |
if token_role != "Admin" and question_count >= 2:
|
| 480 |
limit_message = (
|
| 481 |
"### Free usage limit reached\n\n"
|
|
@@ -490,14 +494,13 @@ async def conversational_chat(websocket: WebSocket, role: Optional[str] = None):
|
|
| 490 |
print(f"Query ({role}): {query}")
|
| 491 |
await stream_text_conversational(websocket, query, role=role)
|
| 492 |
|
| 493 |
-
# --- INCREMENT USAGE ---
|
| 494 |
if token_role != "Admin":
|
| 495 |
async for db in get_db():
|
| 496 |
result = await db.execute(select(User).where(User.id == user_id))
|
| 497 |
user_to_update = result.scalars().first()
|
| 498 |
if user_to_update:
|
| 499 |
user_to_update.question_count += 1
|
| 500 |
-
question_count = user_to_update.question_count
|
| 501 |
await db.commit()
|
| 502 |
break
|
| 503 |
|
|
@@ -512,9 +515,7 @@ async def conversational_chat(websocket: WebSocket, role: Optional[str] = None):
|
|
| 512 |
pass
|
| 513 |
break
|
| 514 |
|
| 515 |
-
|
| 516 |
# Run the application
|
| 517 |
if __name__ == "__main__":
|
| 518 |
-
print("Starting Law Bot Server...")
|
| 519 |
port = int(os.getenv("PORT", 8000))
|
| 520 |
-
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, AsyncSessionLocal
|
| 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 |
+
# Initialize Database and Create Default Admin
|
| 29 |
async def init_db():
|
| 30 |
async with engine.begin() as conn:
|
| 31 |
await conn.run_sync(Base.metadata.create_all)
|
| 32 |
+
|
| 33 |
+
# Ensure Admin exists
|
| 34 |
+
async with AsyncSessionLocal() as db:
|
| 35 |
+
result = await db.execute(select(User).where(User.username == "admin"))
|
| 36 |
+
admin_user = result.scalars().first()
|
| 37 |
+
|
| 38 |
+
if not admin_user:
|
| 39 |
+
print("Creating default admin user...")
|
| 40 |
+
new_admin = User(
|
| 41 |
+
username="admin",
|
| 42 |
+
email="admin@lawbot.ai",
|
| 43 |
+
hashed_password=get_password_hash("ADMin"),
|
| 44 |
+
role="Admin"
|
| 45 |
+
)
|
| 46 |
+
db.add(new_admin)
|
| 47 |
+
await db.commit()
|
| 48 |
+
print("Admin user created successfully.")
|
| 49 |
|
| 50 |
app = FastAPI(on_startup=[init_db])
|
| 51 |
|
|
|
|
| 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 |
chat_limit = 10
|
| 421 |
temp_chat = {"user": "" ,"system":""}
|
| 422 |
temp_chat["user"] = query
|
|
|
|
| 423 |
model_response = ""
|
| 424 |
try:
|
| 425 |
+
completion = RAG(query, chat_history, role=role)
|
|
|
|
|
|
|
|
|
|
| 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 |
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 |
await websocket.close()
|
| 471 |
return
|
| 472 |
|
|
|
|
| 473 |
if token_role == "Admin":
|
| 474 |
if not role:
|
| 475 |
role = "Admin"
|
|
|
|
| 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 |
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 |
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)
|