File size: 10,580 Bytes
aa8be9d
 
 
5ac8480
 
 
 
05b7bf7
5ac8480
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4ed689f
5ac8480
 
 
 
 
05b7bf7
 
 
4ed689f
 
05b7bf7
3533cad
9be91cf
aa20744
 
348d98a
 
 
172d90f
348d98a
 
87ab0b1
 
 
05b7bf7
348d98a
 
b83aa84
 
 
8d36434
 
 
 
 
 
 
cb048b6
5ac8480
720f6f0
ccbeb90
5ac8480
 
 
 
 
 
 
 
 
 
 
ccbeb90
5ac8480
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
05b7bf7
11c87e1
 
 
 
 
9f86e86
 
05b7bf7
5ac8480
 
 
 
 
36b4dfb
 
5ac8480
ccbeb90
a4ce924
cfbf626
a4ce924
540b247
ccbeb90
36b4dfb
 
 
 
 
 
 
5ac8480
 
 
05b7bf7
11c87e1
9f86e86
 
5ac8480
 
e8ca5df
 
cfbf626
e8ca5df
 
9be91cf
3f18ac3
9be91cf
 
 
 
e8ca5df
 
 
 
6f7d11c
 
 
 
e8ca5df
1214561
cfbf626
e8ca5df
dcaf440
023f508
6f7d11c
 
9be91cf
6f7d11c
 
60db93f
e8ca5df
 
cfbf626
e8ca5df
 
023f508
 
 
6f7d11c
023f508
e8ca5df
60db93f
e8ca5df
 
1214561
cfbf626
 
e8ca5df
 
 
cfbf626
 
60db93f
e8ca5df
 
 
 
60db93f
6f7d11c
e8ca5df
 
 
cfbf626
 
 
 
 
6f7d11c
 
 
 
cfbf626
6f7d11c
 
e8ca5df
ebbd307
e8ca5df
5ac8480
 
 
 
 
 
 
 
 
 
9be91cf
 
5ac8480
 
 
 
 
b83aa84
5ac8480
 
 
 
 
 
 
 
 
3befee0
cfbf626
5ac8480
 
 
 
 
3befee0
5ac8480
11c87e1
 
 
b83aa84
 
 
 
 
 
 
 
 
 
 
3533cad
b83aa84
 
11c87e1
b83aa84
dcaf440
3befee0
b83aa84
 
 
 
11c87e1
5ac8480
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
05b7bf7
 
 
 
 
 
 
 
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
import torch
import torch.serialization        # the module that controls loading behaviour
from supar.config import Config
import supar.utils.data as _supar_data
import multiprocess as mp
from transformers import BertTokenizerFast


# Patch the tokenizer class directly
if not hasattr(BertTokenizerFast, 'split_special_tokens'):
    BertTokenizerFast.split_special_tokens = False

# Force supar's pool to inherit the patch by using fork start method
mp.set_start_method('fork', force=True)

"""
main.py โ€” Sebayhi FastAPI backend

Endpoints:
  GET  /              โ†’ serves the chat UI
  POST /chat/stream   โ†’ SSE streaming response

Intent is now determined by the frontend (user explicitly selects
"knowledge" or "i3rab" before typing). The backend receives it directly
in the request body โ€” no classifier needed.
"""
import re
import asyncio
from fastapi import FastAPI, Request
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse, StreamingResponse
from pydantic import BaseModel
from typing import Literal
from haystack_pipeline import *
from pymongo import MongoClient
import json
import os
import requests 
import uuid
from dotenv import load_dotenv
from datetime import datetime
from fastapi.middleware.cors import CORSMiddleware
load_dotenv()

try:
    connection_uri = os.getenv("MONGODB_URL")
    client = MongoClient(connection_uri, tls=True) # temp fix

except Exception as e:
    print("An error occured when trying to connect to the cluster: ", e)

db = client.get_database("Sebayhi_convos")
collection = db.get_collection("collection_0")

# retrieve docs from mongodb and stringify them

    

# modify this function later
#def retrieve_docs(session_id: str):
#    #session_id = request.state.session_id
#    docs = list(collection.find({
#        "session_id": session_id
#    }))
#
#    return json.dumps(docs, indent=2, default=str)
    


def run_query(message: str, intent: str, session_id: str) -> str:
    """
    Routes the user message to the appropriate Haystack pipeline
    based on the intent selected in the UI.
 
    Args:
        message: raw Arabic text from the user
        intent:  "knowledge" | "i3rab"
 
    Returns:
        LLM reply as a string
    """
    #session_id = request.state.session_id
    match intent:
        case "i3rab":
            # Strip any leading instruction words so the parser gets
            # only the sentence: "ุฃุนุฑุจ: ุฐู‡ุจ ุงู„ุทุงู„ุจ" โ†’ "ุฐู‡ุจ ุงู„ุทุงู„ุจ"
            sentence = re.sub(
                r"^(ุฃุนุฑุจ|ุงุนุฑุจ|ุญู„ู„|ุฅุนุฑุงุจ|ุงุนุฑุงุจ)\s*[:\-]?\s*",
                "",
                message.strip()
            )
            #i3rab_pipeline.run({"parser": {"sentence": sentence}})

            parser_output = get_camel_parser_output(sentence)

            if parser_output:
                print("\n--- ุชู… ุงุณุชุฎุฑุงุฌ ุงู„ุจูŠุงู†ุงุช ุจู†ุฌุงุญุŒ ุฌุงุฑูŠ ุงู„ู…ุนุงู„ุฌุฉ... ---")
                final_tags_meaning = get_parsed_lines(parser_output)
                print("\n--- tags description. ---")
                print(final_tags_meaning)
                print("\n--- ุชู… ุชูุณูŠุฑ ุงู„ูˆุณูˆู… ุจู†ุฌุงุญ ---")
                print("\n--- ุฌุงุฑูŠ ุชูˆู„ูŠุฏ ุงู„ุฅุนุฑุงุจ... ---")
                result = i3rab_final_output(final_tags_meaning)
                print("\n=== ุงู„ู†ุชูŠุฌุฉ ุงู„ู†ู‡ุงุฆูŠุฉ ===")
                print(result)

                # test to see to insert/update msgs into mongodb docs
                #query_filter = {"role": "ai-assistant"}
                #update_operation = {"$push": {
                #    "message": result
                #}}
                #result_mongodb = collection.update_one(query_filter, update_operation)
                return result


            else:
                err_msg = "ูุดู„ ุงู„ู…ุญู„ู„ ููŠ ุงุณุชุฎุฑุงุฌ ุจูŠุงู†ุงุช."
                print(err_msg)
                return err_msg

        
        
        case "knowledge":

            chat_docs = collection.find_one({
                "_id": session_id
            })
            msg_history = json.dumps(chat_docs["messages"][-5:], indent=2, default=str)
            
            result = knowledge_pipeline.run({
                "text_embedder": {"text": message},
                "prompt_builder": {
                    "question": message,
                    "history": msg_history
                },
            })
 
            replies = result.get("llm", {}).get("replies", [])
            if replies:
                # test to see to insert/update msgs into mongodb docs
                
                return replies[0].text if hasattr(replies[0], "text") else str(replies[0])
            
            return "[ู„ู… ูŠุชู… ุงู„ุญุตูˆู„ ุนู„ู‰ ุฅุฌุงุจุฉ]"

# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

app = FastAPI(title="Sebayhi", description="Arabic Grammar Education Tutor")
app.mount("/static", StaticFiles(directory="static"), name="static")

app.add_middleware(
    CORSMiddleware,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"]
)
# fastapi middleware here --> cookies / session generation logic
@app.middleware("http")
async def user_session_management(request: Request, call_next):
    
    print("\n==============================")
    print("REQUEST:", request.method, request.url.path)
    print("INCOMING COOKIES:", request.cookies)

    session_id = request.cookies.get("session_id")
    print("COOKIE:", session_id)
    session = None

    # this if statement is not running OR session_id is never saved and found on mongodb
    if session_id:
        print("COOKIE SESSION ID:", session_id)

        retrieved_session = collection.find_one({"_id": session_id})
        print("MONGO FOUND:", retrieved_session is not None)

        print("FOUND SESSION:", session_id is not None)
        if retrieved_session:
            collection.update_one(
                {"_id": session_id},
                {"$set": {"last_active": datetime.utcnow()}}
            )
            #session = retrieved_session
            session_id = retrieved_session["_id"]
        else:
            print("COOKIE EXISTS BUT SESSION DOES NOT")
            session_id = None
    
    if session_id is None:
        try:
            session_id = str(uuid.uuid4())
            print("CREATING NEW SESSION:", session_id)
            session = {
                "_id": session_id,
                "created_at": datetime.utcnow(),
                "last_active": datetime.utcnow(),
                "messages": []
            }
            usr_doc = collection.insert_one(session)
            

        except Exception as e:
            print("An error occured when trying to generate a session id / create new session: ", e) 
    
    request.state.session_id = session_id
    print("FINAL REQUEST SESSION:", request.state.session_id)
    # forward request to actual endpoint and get the response
    response = await call_next(request)

    
    response.set_cookie(
        key="session_id",
        value=session_id,
        max_age=60*60*24*7,
        httponly=True,
        samesite="lax",
        secure=True,
        path="/"
    )
    print("SETTING COOKIE:", session_id)
    print("==============================\n")
    return response
    

# โ”€โ”€ Request model โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

class ChatRequest(BaseModel):
    message: str
    intent: Literal["knowledge", "i3rab"]   # sent explicitly by the frontend


# โ”€โ”€ Routes โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

@app.get("/")
async def serve_ui():
    
    return FileResponse("static/index.html")



@app.post("/chat/stream")
async def chat_stream(req: ChatRequest, request: Request):
    """
    SSE streaming endpoint.
    Runs the pipeline in a thread (blocking I/O), then streams
    the reply word-by-word to the frontend.
 
    Chunk protocol:
      data: <token>\n\n   โ€” text to append
      data: [DONE]\n\n    โ€” end of stream
    """
    

    async def token_generator():
        # Run the blocking pipeline call in a thread pool so FastAPI
        # stays non-blocking for other concurrent requests
        loop = asyncio.get_event_loop()
        full_reply = await loop.run_in_executor(
            None, run_query, req.message, req.intent, request.state.session_id
        )
        # via mongodb api, insert the msgs and replies  into the docs
        # then in haystack_pipeline.py retrieve the docs and inject them into the prompt
        
        # append 
        #query_filter1 = {"role": "user"}
        #query_filter2 = {"role": "ai-assistant"}
        #
        #update_operation1 = {"$push": {
        #    "message": req.message
        #}}
#
        #update_operation2 = {"$push": {
        #    "message": full_reply
        #}}
        
        #user_msgs = collection.update_one(query_filter1, update_operation1)
        #ai_msgs = collection.update_one(query_filter2, update_operation2)

        
        all_msgs = collection.update_one(
            {"_id": request.state.session_id},
            {"$push": {
                "messages": {"$each": [req.message, full_reply]}
            }}
        )
        
        for word in full_reply.split(" "):
            yield f"data: {word} \n\n"
            await asyncio.sleep(0.02)
 
        yield "data: [DONE]\n\n"
 
    return StreamingResponse(
        token_generator(),
        media_type="text/event-stream",
        headers={
            "Cache-Control": "no-cache",
            "X-Accel-Buffering": "no",
        },
    )
 
# โ”€โ”€ Entry point โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€

if __name__ == "__main__":
    import uvicorn
    uvicorn.run("main:app", host="0.0.0.0", port=7860, reload=True)


'''
mongodb methods;
- insertOne, insertMany()
- find(), sort(), limit()
- include document body as a parameter or part of it within a method
- updateOne(), updateMany()
-$set, $unset for updating documents with key value pairs
'''