uniq-backendd / api /app.py
salmafahmy's picture
update
6e104bf
Raw History Blame Contribute Delete
7.11 kB
import os
import uvicorn
from fastapi import FastAPI, BackgroundTasks
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from typing import List
# =========================
# ๐Ÿ“ฆ IMPORT SERVICES
# =========================
from services.intent_service import IntentService
from services.rag_service import RAGService
from services.academic_rag_service import AcademicRAGService
from services.gpa_service import GPAService
from core.memory_manager import MemoryService
from services.llm_service import LLMService
from services.recommendation_service import RecommendationService
from utils.course_matcher import CourseMatcherService
from core.orchestrator import OrchestratorService
from core.access_control import AccessControl
from database.mock_data import DataService
from data.load_pdfs import build_vectordb
from config import (
EMBEDDING_MODEL,
LLM_MODEL_NAME,
INTENT_LLM_MODEL_NAME,
CHROMA_DIR
)
# =========================
# ๐Ÿš€ APP CONFIGURATION
# =========================
app = FastAPI(title="UNIQ Backend API")
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# =========================
# โš™๏ธ SYSTEM INITIALIZATION
# =========================
data_service = DataService()
# โœ… ACCESS CONTROL
access_control = AccessControl(
data_service=data_service
)
llm_service = LLMService(
model_name=LLM_MODEL_NAME,
temperature=0
)
intent_llm_service = LLMService(
model_name=INTENT_LLM_MODEL_NAME,
temperature=0
)
gpa_service = GPAService()
memory_service = MemoryService(
llm=llm_service.llm
)
rag_service = RAGService(
model_name=EMBEDDING_MODEL
)
academic_rag_service = None
intent_service = IntentService(
intent_llm=intent_llm_service.llm,
llm_model=llm_service.llm,
intents=[
"course_rec",
"gpa_calc",
"gpa_plan",
"general_query"
]
)
course_matcher = CourseMatcherService(
courses_catalog=data_service.COURSES_CATALOG,
llm=llm_service.llm
)
recommendation_service = RecommendationService(
gpa_service=gpa_service,
matcher=course_matcher
)
# =========================
# ๐Ÿง  SAFE CHROMA CHECK
# =========================
def chroma_is_valid(path: str) -> bool:
"""
check ุญู‚ูŠู‚ูŠ ุนู„ู‰ ูˆุฌูˆุฏ ุจูŠุงู†ุงุช Chroma
"""
if not os.path.exists(path):
return False
try:
files = os.listdir(path)
except Exception:
return False
if len(files) == 0:
return False
# ุฃู‡ู… ู…ุคุดุฑ ุฅู† ุงู„ุฏุงุชุง ุงุชุจู†ุช ูุนู„ุงู‹
return any(
"chroma.sqlite3" in f or "index" in f
for f in files
)
# =========================
# ๐Ÿ—๏ธ AUTO BUILD LOGIC
# =========================
@app.on_event("startup")
def startup_event():
global academic_rag_service
print("\n==============================")
print("๐Ÿ”ฅ UNIQ SYSTEM STARTUP")
print("==============================")
# ๐Ÿ”ฅ ู†ูุณ ุงู„ุจุงุซ ุจุฏูˆู† ุฃูŠ ุชุบูŠูŠุฑ
if not chroma_is_valid(CHROMA_DIR):
print(
f"โš ๏ธ Chroma DB missing or invalid in: "
f"{CHROMA_DIR}"
)
print("๐Ÿ› ๏ธ Starting Vector DB build process...")
build_vectordb(force_rebuild=True)
print("โœ… Rebuild complete.")
else:
print(
f"โœ… Chroma DB found and valid at: "
f"{CHROMA_DIR}"
)
# =========================
# ๐Ÿ“š Academic RAG Init
# =========================
vectordb, ensemble_retriever = build_vectordb(
force_rebuild=False
)
# =========================
# ๐Ÿ“š Academic RAG Init
# =========================
academic_rag_service = AcademicRAGService(
llm_service=llm_service,
vectordb=vectordb,
ensemble_retriever=ensemble_retriever
)
# =========================
# ๐Ÿง  MAIN ORCHESTRATOR
# =========================
app.state.orchestrator = OrchestratorService(
intent_service=intent_service,
rag_service=rag_service,
academic_rag_service=academic_rag_service,
gpa_service=gpa_service,
memory_service=memory_service,
llm_service=llm_service,
course_matcher=course_matcher,
recommendation_service=recommendation_service,
ui_service=None,
data_service=data_service,
access_control=access_control
)
print("๐Ÿš€ UNIQ System is fully functional!")
print("==============================\n")
# =========================
# ๐Ÿ“ REQUEST MODELS
# =========================
class ChatRequest(BaseModel):
user_id: str
query: str
class GPAPlanRequest(BaseModel):
current_gpa: float
target_gpa: float
completed_hours: int
remaining_hours: int
class Subject(BaseModel):
credit_hours: int
grade: str
class GPACalcRequest(BaseModel):
subjects: List[Subject]
# =========================
# ๐Ÿ›ฃ๏ธ ENDPOINTS
# =========================
@app.get("/")
def health_check():
return {
"status": "online",
"system": "UNIQ AI Assistant"
}
@app.post("/chat")
async def chat(
req: ChatRequest,
background_tasks: BackgroundTasks
):
try:
answer, intent, confidence = (
app.state.orchestrator.generate_uniq_response(
user_id=req.user_id,
query=req.query
)
)
background_tasks.add_task(
memory_service.cleanup_sessions
)
return {
"answer": answer,
"intent": intent,
"confidence": round(confidence, 2)
}
except Exception as e:
import traceback
traceback.print_exc()
return {
"answer": "ุนุฐุฑุงู‹ุŒ ูˆุงุฌู‡ุช ู…ุดูƒู„ุฉ ุชู‚ู†ูŠุฉ ุจุณูŠุทุฉ.",
"intent": "error",
"error_detail": str(e)
}
@app.post("/calculate-gpa")
def api_calculate_gpa(req: GPACalcRequest):
try:
subjects = [
s.dict()
for s in req.subjects
]
result = gpa_service.calculate_gpa(subjects)
return {
"gpa": result
}
except Exception as e:
return {
"error": str(e)
}
@app.post("/plan-gpa")
def api_plan_gpa(req: GPAPlanRequest):
try:
rem_list = [3] * (req.remaining_hours // 3)
if req.remaining_hours % 3:
rem_list.append(
req.remaining_hours % 3
)
result = gpa_service.calculate_balanced_gpa(
current_gpa=req.current_gpa,
completed_hours=req.completed_hours,
remaining_hours_list=rem_list,
target_gpa=req.target_gpa
)
return result
except Exception as e:
return {
"error": str(e)
}
# =========================
# ๐Ÿƒ RUN SERVER
# =========================
if __name__ == "__main__":
uvicorn.run(
app,
host="0.0.0.0",
port=8000
)