File size: 7,112 Bytes
68efe87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6e104bf
68efe87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6e104bf
 
 
 
 
 
68efe87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6e104bf
 
68efe87
 
 
 
 
 
 
 
 
6e104bf
 
68efe87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6e104bf
 
 
 
 
 
 
 
68efe87
 
 
 
6e104bf
 
 
68efe87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6b339c5
68efe87
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
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
    )