Spaces:
Running

File size: 8,311 Bytes
dc19c4a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from fastapi import FastAPI, Query , Depends , BackgroundTasks
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import StreamingResponse
import asyncio
import json
from datetime import datetime
import uvicorn
import pandas as pd
import duckdb
from apscheduler.schedulers.background import BackgroundScheduler
import redis
from fastapi import Security, HTTPException

from stats import format_code_run_data
from lessonsdata import  format_lessons_data
from dependencies import verify_jwt_token

import os
from dotenv import load_dotenv

# Load environment variables
load_dotenv()

# Configuration variables
API_KEY = os.getenv("API_KEY")
AWS_ACCESS_KEY_ID = os.getenv("AWS_ACCESS_KEY_ID")
AWS_SECRET_ACCESS_KEY = os.getenv("AWS_SECRET_ACCESS_KEY")
S3_ENDPOINT = os.getenv("S3_ENDPOINT")
S3_URL_STYLE = os.getenv("S3_URL_STYLE")
S3_USE_SSL = os.getenv("S3_USE_SSL", "true").lower() == "true"

REDIS_HOST = os.getenv("REDIS_HOST")
REDIS_PORT = int(os.getenv("REDIS_PORT", 6379))
REDIS_PASSWORD = os.getenv("REDIS_PASSWORD")
REDIS_SSL = os.getenv("REDIS_SSL", "true").lower() == "true"

CORS_ORIGIN = os.getenv("CORS_ORIGIN", "http://localhost:3000")


app = FastAPI()


#move them

async def background_update_code(user_id: str, con, r):
    try:
        # Get the formatted data
        data = format_code_run_data(user_id, con)

        # Update Redis with new data
        r.set(f"{user_id}-code", json.dumps(data))

        print(f"Code stats background task completed successfully for user {user_id}")
    except Exception as e:
        print(f"Error in code stats background task for user {user_id}: {str(e)}")
        # You might want to log this error or handle it in some way


async def background_update_lessons(user_id: str, con, r):
    try:
        # Get the formatted data
        data = format_lessons_data(user_id, con)
        data_dict = data.model_dump()  # Use .dict() for older Pydantic versions

        # Update Redis with new data
        r.set(f"{user_id}-lessons", json.dumps(data_dict))

        print(f"Lessons stats background task completed successfully for user {user_id}")
    except Exception as e:
        print(f"Error in lessons stats background task for user {user_id}: {str(e)}")
        # You might want to log this error or handle it in some way



# # Create scheduler instance
# scheduler = BackgroundScheduler()

# # Define your cron job function
# def cron_job():
#     print(f"Cron job executed at: {datetime.now()}")

# Create a global variable for the connection
con = None
r= None

@app.on_event("startup")
async def startup_event():
    global con, r

    # Initialize DuckDB connection
    con = duckdb.connect()

    # Load the S3 extension
    con.execute("INSTALL httpfs;")
    con.execute("LOAD httpfs;")

    # Configure S3 settings
    con.execute(f"""

        SET s3_endpoint='{S3_ENDPOINT}';

        SET s3_access_key_id='{AWS_ACCESS_KEY_ID}';

        SET s3_secret_access_key='{AWS_SECRET_ACCESS_KEY}';

        SET s3_url_style='{S3_URL_STYLE}';

        SET s3_use_ssl={str(S3_USE_SSL).lower()};

    """)

    # Initialize Redis connection
    r = redis.Redis(
        host=REDIS_HOST,
        port=REDIS_PORT,
        password=REDIS_PASSWORD,
        ssl=REDIS_SSL
    )

    # # Initialize default data
    # code_runs_data = {
    #     "total": 0,
    #     "avgExecutionTime": "0.0s",
    #     "overTime": []
    # }

    # lessons_data = {
    #     "completed": 0,
    #     "popular": []
    # }

    # # Set default data in Redis
    # default_user_id = "18eee92a-9c14-4484-b3c0-25d75a840d77"
    # r.set(f'{default_user_id}-code', json.dumps(code_runs_data))
    # r.set(f'{default_user_id}-lessons', json.dumps(lessons_data))


@app.on_event("shutdown")
async def shutdown_event():
    global con
    if con:
        con.close()
    #need to stop the simply scheduler
    scheduler.shutdown()

# CORS middleware
app.add_middleware(
    CORSMiddleware,
    allow_origins=[CORS_ORIGIN],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)



async def generate_data(user_id: str):
    while True:

        # data = format_code_run_data(user_id,con)
        # code_runs_data = {
        #     "total": 120,
        #     "avgExecutionTime": "0.45s",
        #     "overTime": [
        #         {"date": "2023-10-01", "runs": 12},
        #         {"date": "2023-10-02", "runs": 18},
        #         {"date": "2023-10-03", "runs": 15},
        #         {"date": "2023-10-04", "runs": 20},
        #         {"date": "2023-10-05", "runs": 25},
        #     ]
        # }

        code_runs_data = json.loads(r.get(f"{user_id}-code"))

        print(f"The data is {code_runs_data} and the user is {user_id} ")
        yield f"data: {json.dumps(code_runs_data)}\n\n"
        await asyncio.sleep(5)

@app.get("/stream")
async def stream_data(user_id: str = Query(...),

    token_payload: dict = Depends(verify_jwt_token)):
    return StreamingResponse(
        generate_data(user_id),
        media_type="text/event-stream",
        headers={
            "Cache-Control": "no-cache",
            "Connection": "keep-alive",
        }
    )

async def generate_lessons_stats(user_id: str):
    while True:
        # data = format_lessons_data(user_id,con)
        # data_dict = data.model_dump()  # Use .dict() for older Pydantic versions
        # lessons_data = {
        #     "completed": 42,
        #     "popular": [
        #         {"lesson": "Hello, World!", "runs": 50},
        #         {"lesson": "Variables", "runs": 40},
        #         {"lesson": "Math Operations", "runs": 35},
        #     ]
        # }

        lessons_data = json.loads(r.get(f"{user_id}-lessons"))

        data_dict = lessons_data
        print(f"The data is  {data_dict} and user id id {user_id}")
        yield f"data: {json.dumps(data_dict)}\n\n"
        await asyncio.sleep(5)

@app.get("/lessonsstats")
async def stream_lesson_data(user_id: str = Query(...), token_payload: dict = Depends(verify_jwt_token)):
    return StreamingResponse(
        generate_lessons_stats(user_id),
        media_type="text/event-stream",
        headers={
            "Cache-Control": "no-cache",
            "Connection": "keep-alive",
        }
    )


@app.get("/update-lesson")
async def update_lesson_data(

    background_tasks: BackgroundTasks,

    token_payload: dict = Depends(verify_jwt_token)

):
    try:
        user_id = token_payload.get("sub")
        if not user_id:
            raise HTTPException(status_code=400, detail="User ID not found in token")

        background_tasks.add_task(
            background_update_lessons,
            user_id=user_id,
            con=con,
            r=r
        )

        return {
            "status": "success",
            "message": "Lessons stats update process started in background",
            "user_id": user_id
        }
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"Failed to start lessons stats background task: {str(e)}"
        )


@app.get("/update-code")
async def update_code_data(

    background_tasks: BackgroundTasks,

    token_payload: dict = Depends(verify_jwt_token)

):
    try:
        user_id = token_payload.get("sub")
        if not user_id:
            raise HTTPException(status_code=400, detail="User ID not found in token")

        background_tasks.add_task(
            background_update_code,
            user_id=user_id,
            con=con,
            r=r
        )

        return {
            "status": "success",
            "message": "Code stats update process started in background",
            "user_id": user_id
        }
    except Exception as e:
        raise HTTPException(
            status_code=500,
            detail=f"Failed to start code stats background task: {str(e)}"
        )


@app.get("/")
async def running():
    return {"Hello": f" MzLearningPython Report Generator "}

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)