from fastapi import FastAPI, WebSocket, WebSocketDisconnect from routes.index import router import websockets from ai.emotion import emotion_model app = FastAPI() @app.get("/") def read_root(): return {"message": "Hello, FastAPI!"} # To run: uvicorn main:app --reload # pymongo from pymongo.mongo_client import MongoClient uri = "mongodb+srv://gowdaman:gowdaman@cluster0.z5dooqf.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0" client = MongoClient(uri) db = client["ai-saas"] emotion = db["emotion"] sentiment = db["sentiments"] # emotion detection import base64 import json from bson.objectid import ObjectId from bson import ObjectId @app.websocket("/emotion") async def websocket_emotion(websocket: WebSocket): await websocket.accept() course_id = None try: while True: data = await websocket.receive_text() msg = json.loads(data) image_b64 = msg.get("image") course_id = msg.get("course_id") # Get the courseId from the message if not image_b64: await websocket.send_text("No image data received") continue image_bytes = base64.b64decode(image_b64) label, face = emotion_model.predict_from_frame_bytes(image_bytes) await websocket.send_text(str(label)) except WebSocketDisconnect: # Do not call await websocket.close() here pass finally: print(f"WebSocket connection closed for user with course ID {course_id}") # Convert course_id to ObjectId if it's a string try: course_obj_id = ObjectId(course_id) # course_obj_id = course_id # fallback if already ObjectId or invalid emotion_data = emotion.find_one({"course_id": course_obj_id}) total_len = len(emotion_data['emotion']) print(emotion_data['emotion'].count(0)) # negetive print(emotion_data['emotion'].count(1)) # positive #positive percentage positive_percentage = round((emotion_data['emotion'].count(1)/total_len)*100,2) negative_percentage = round((emotion_data['emotion'].count(0)/total_len)*100,2) print(positive_percentage) print(negative_percentage) sentiment.update_one( {"course_id": course_obj_id}, { "$set": { "expression_positive_score": positive_percentage, "expression_negetive_score": negative_percentage, } }, ) except Exception: pass app.include_router(router) # if __name__ == "__main__": # import uvicorn # uvicorn.run("main:app", host="0.0.0.0", port=7000, reload=True)