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)