diff --git a/Backend/.gitignore b/Backend/.gitignore new file mode 100644 index 00000000..b512c09d --- /dev/null +++ b/Backend/.gitignore @@ -0,0 +1 @@ +node_modules \ No newline at end of file diff --git a/Backend/arPoseLandmarks/downward_dog/downward_dog_landmarks.json b/Backend/arPoseLandmarks/downward_dog/downward_dog_landmarks.json new file mode 100644 index 00000000..cffb0e99 --- /dev/null +++ b/Backend/arPoseLandmarks/downward_dog/downward_dog_landmarks.json @@ -0,0 +1,42 @@ +[ + { + "name": "left_shoulder", + "x": 0.43475762009620667, + "y": 0.5846027731895447 + }, + { + "name": "right_shoulder", + "x": 0.4466809630393982, + "y": 0.5982203483581543 + }, + { + "name": "left_elbow", + "x": 0.3332710564136505, + "y": 0.7483700513839722 + }, + { + "name": "right_elbow", + "x": 0.34916260838508606, + "y": 0.7354578375816345 + }, + { + "name": "left_hip", + "x": 0.6648672223091125, + "y": 0.2121756225824356 + }, + { + "name": "right_hip", + "x": 0.6585555076599121, + "y": 0.2347366362810135 + }, + { + "name": "left_knee", + "x": 0.8213318586349487, + "y": 0.516678512096405 + }, + { + "name": "right_knee", + "x": 0.7963972687721252, + "y": 0.5197720527648926 + } +] \ No newline at end of file diff --git a/Backend/arPoseLandmarks/downward_dog/downward_dog_pose.jpg b/Backend/arPoseLandmarks/downward_dog/downward_dog_pose.jpg new file mode 100644 index 00000000..28bed08c Binary files /dev/null and b/Backend/arPoseLandmarks/downward_dog/downward_dog_pose.jpg differ diff --git a/Backend/arPoseLandmarks/extract_pose.py b/Backend/arPoseLandmarks/extract_pose.py new file mode 100644 index 00000000..031679cd --- /dev/null +++ b/Backend/arPoseLandmarks/extract_pose.py @@ -0,0 +1,89 @@ +import cv2 +import mediapipe as mp +import json +import os + +print("[INFO] Initializing MediaPipe Pose...") +mp_pose = mp.solutions.pose +pose = mp_pose.Pose( + static_image_mode=True, + model_complexity=1, + min_detection_confidence=0.5, + min_tracking_confidence=0.5 +) +mp_drawing = mp.solutions.drawing_utils + +# Update video path for Warrior II pose +video_path = "../../CeylonCare/CeylonCare/assets/videos/warrior_ii.mp4" # Relative path +output_image_path = "warrior_ii/warrior_ii.jpg" +output_json_path = "warrior_ii/warrior_ii_landmarks.json" + +# Create output directories if they don't exist +os.makedirs(os.path.dirname(output_image_path), exist_ok=True) +os.makedirs(os.path.dirname(output_json_path), exist_ok=True) + +if not os.path.exists(video_path): + print(f"[ERROR] Video file not found at: {video_path}") + print("[INFO] Ensure the video is in ../../CeylonCare/CeylonCare/assets/videos/") + exit() + +print("[INFO] Loading video...") +cap = cv2.VideoCapture(video_path) +if not cap.isOpened(): + print("[ERROR] Could not open video.") + exit() + +fps = cap.get(cv2.CAP_PROP_FPS) +total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) +print(f"[DEBUG] Video FPS: {fps}, Total Frames: {total_frames}") + +# Adjust target time based on when the Warrior II pose is held in the video +target_time = 5 # Adjust this based on your video +target_frame = int(fps * target_time) if int(fps * target_time) < total_frames else total_frames - 1 +print(f"[DEBUG] Targeting frame {target_frame} at {target_time} seconds") +cap.set(cv2.CAP_PROP_POS_FRAMES, target_frame) + +success, frame = cap.read() +if not success: + print("[ERROR] Failed to read frame.") + cap.release() + exit() + +print("[INFO] Processing frame for pose detection...") +rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) +results = pose.process(rgb_frame) + +if not results.pose_landmarks: + print("[ERROR] No pose detected.") + cv2.imwrite(output_image_path, frame) + print(f"[DEBUG] Frame saved as {output_image_path}") + cap.release() + exit() + +mp_drawing.draw_landmarks(frame, results.pose_landmarks, mp_pose.POSE_CONNECTIONS) +cv2.imwrite(output_image_path, frame) +print(f"[INFO] Frame saved as {output_image_path}") + +# Extract landmarks +landmarks = results.pose_landmarks.landmark +correct_pose = [ + {"name": "left_shoulder", "x": landmarks[11].x, "y": landmarks[11].y}, + {"name": "right_shoulder", "x": landmarks[12].x, "y": landmarks[12].y}, + {"name": "left_elbow", "x": landmarks[13].x, "y": landmarks[13].y}, + {"name": "right_elbow", "x": landmarks[14].x, "y": landmarks[14].y}, + {"name": "left_hip", "x": landmarks[23].x, "y": landmarks[23].y}, + {"name": "right_hip", "x": landmarks[24].x, "y": landmarks[24].y}, + {"name": "left_knee", "x": landmarks[25].x, "y": landmarks[25].y}, + {"name": "right_knee", "x": landmarks[26].x, "y": landmarks[26].y} +] +print("[DEBUG] Extracted landmarks:") +for landmark in correct_pose: + print(f"[DEBUG] {landmark['name']}: x={landmark['x']:.3f}, y={landmark['y']:.3f}") + +with open(output_json_path, 'w') as f: + json.dump(correct_pose, f, indent=2) +print(f"[INFO] Landmarks saved to {output_json_path}") + +cap.release() +pose.close() +print("[INFO] Script completed!") \ No newline at end of file diff --git a/Backend/arPoseLandmarks/triangle_pose/triangle_pose.jpg b/Backend/arPoseLandmarks/triangle_pose/triangle_pose.jpg new file mode 100644 index 00000000..f1d6b5e8 Binary files /dev/null and b/Backend/arPoseLandmarks/triangle_pose/triangle_pose.jpg differ diff --git a/Backend/arPoseLandmarks/triangle_pose/triangle_pose_landmarks.json b/Backend/arPoseLandmarks/triangle_pose/triangle_pose_landmarks.json new file mode 100644 index 00000000..9926b205 --- /dev/null +++ b/Backend/arPoseLandmarks/triangle_pose/triangle_pose_landmarks.json @@ -0,0 +1,42 @@ +[ + { + "name": "left_shoulder", + "x": 0.393909215927124, + "y": 0.5337827205657959 + }, + { + "name": "right_shoulder", + "x": 0.41303548216819763, + "y": 0.4024796485900879 + }, + { + "name": "left_elbow", + "x": 0.39781999588012695, + "y": 0.6615622043609619 + }, + { + "name": "right_elbow", + "x": 0.3966938853263855, + "y": 0.2836398184299469 + }, + { + "name": "left_hip", + "x": 0.50235915184021, + "y": 0.576718270778656 + }, + { + "name": "right_hip", + "x": 0.5291388630867004, + "y": 0.5406009554862976 + }, + { + "name": "left_knee", + "x": 0.4347962439060211, + "y": 0.7202959656715393 + }, + { + "name": "right_knee", + "x": 0.5943127870559692, + "y": 0.698548436164856 + } +] \ No newline at end of file diff --git a/Backend/arPoseLandmarks/warrior_ii/warrior_ii.jpg b/Backend/arPoseLandmarks/warrior_ii/warrior_ii.jpg new file mode 100644 index 00000000..6665e044 Binary files /dev/null and b/Backend/arPoseLandmarks/warrior_ii/warrior_ii.jpg differ diff --git a/Backend/arPoseLandmarks/warrior_ii/warrior_ii_landmarks.json b/Backend/arPoseLandmarks/warrior_ii/warrior_ii_landmarks.json new file mode 100644 index 00000000..69fda1dc --- /dev/null +++ b/Backend/arPoseLandmarks/warrior_ii/warrior_ii_landmarks.json @@ -0,0 +1,42 @@ +[ + { + "name": "left_shoulder", + "x": 0.5757824182510376, + "y": 0.30987370014190674 + }, + { + "name": "right_shoulder", + "x": 0.48430055379867554, + "y": 0.3139100670814514 + }, + { + "name": "left_elbow", + "x": 0.650972843170166, + "y": 0.32717323303222656 + }, + { + "name": "right_elbow", + "x": 0.40994828939437866, + "y": 0.3287721872329712 + }, + { + "name": "left_hip", + "x": 0.5621575117111206, + "y": 0.5378085374832153 + }, + { + "name": "right_hip", + "x": 0.5064576864242554, + "y": 0.5383180379867554 + }, + { + "name": "left_knee", + "x": 0.6146337985992432, + "y": 0.6881082057952881 + }, + { + "name": "right_knee", + "x": 0.44796282052993774, + "y": 0.6910121440887451 + } +] \ No newline at end of file diff --git a/Backend/ar_model/pose_service.py b/Backend/ar_model/pose_service.py new file mode 100644 index 00000000..deb38824 --- /dev/null +++ b/Backend/ar_model/pose_service.py @@ -0,0 +1,69 @@ +from flask import Flask, request, jsonify +import cv2 +import mediapipe as mp +import base64 +import numpy as np +import logging +import traceback + +# Set up logging for debugging and error tracking +logging.basicConfig(level=logging.DEBUG) +logger = logging.getLogger(__name__) + +app = Flask(__name__) +mp_pose = mp.solutions.pose + +# Initialize MediaPipe Pose model with higher confidence thresholds +pose = mp_pose.Pose(min_detection_confidence=0.7, min_tracking_confidence=0.7) + +@app.route('/process_frame', methods=['POST']) +def process_frame(): + try: + # Log incoming request + logger.info('[DEBUG] Received request to process frame') + + # Get JSON data from request + data = request.json + if not data or 'frame' not in data: + logger.error('[ERROR] Invalid request: Missing frame data') + return jsonify({'error': 'Missing frame data'}), 400 + + # Extract and log frame data + frame_base64 = data['frame'] + logger.debug('[DEBUG] Frame base64 length: %d', len(frame_base64)) + + # Decode base64 string to image + frame = base64.b64decode(frame_base64) + image = cv2.imdecode(np.frombuffer(frame, np.uint8), cv2.IMREAD_COLOR) + if image is None: + logger.error('[ERROR] Failed to decode image') + return jsonify({'error': 'Failed to decode image'}), 400 + + # Log image details + logger.debug('[DEBUG] Image decoded, shape: %s', image.shape) + + # Convert image to RGB for MediaPipe processing + image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) + results = pose.process(image_rgb) + + # Process pose detection results + if results.pose_landmarks: + landmarks = [ + {'name': f'landmark_{i}', 'x': lm.x, 'y': lm.y, 'z': lm.z} + for i, lm in enumerate(results.pose_landmarks.landmark) + ] + logger.info('[DEBUG] Pose landmarks detected: %d', len(landmarks)) + return jsonify({'landmarks': landmarks}) + else: + logger.warning('[WARN] No pose landmarks detected') + return jsonify({'landmarks': []}) + + except Exception as e: + # Log detailed error information + logger.error('[ERROR] Error processing frame: %s', str(e)) + logger.error('[ERROR] Traceback: %s', traceback.format_exc()) + return jsonify({'error': str(e)}), 500 + +if __name__ == '__main__': + logger.info('[INFO] Starting pose detection service on http://0.0.0.0:5002') + app.run(host='0.0.0.0', port=5002, debug=True) \ No newline at end of file diff --git a/Backend/controllers/arController.js b/Backend/controllers/arController.js index a730ca29..0334e87b 100644 --- a/Backend/controllers/arController.js +++ b/Backend/controllers/arController.js @@ -14,7 +14,7 @@ const getARRecommendations = async (req, res) => { console.log(`[DEBUG] Received request to fetch therapy for user: ${userId}`); try { - const response = await axios.get(`http://localhost:5000/healthData/${userId}`); + const response = await axios.get(`http://192.168.60.22:5000/healthData/${userId}`); console.log(`[DEBUG] Fetching health data for user: ${userId}, Response status: ${response.status}`); if (response.status !== 200) { @@ -24,7 +24,7 @@ const getARRecommendations = async (req, res) => { const userHealthData = response.data; console.log("[DEBUG] Fetched user health data:", JSON.stringify(userHealthData, null, 2)); - const flaskResponse = await axios.post("http://localhost:5001/predict", userHealthData); + const flaskResponse = await axios.post("http://192.168.60.22:5001/predict", userHealthData); console.log("[DEBUG] Flask API Full Response:", JSON.stringify(flaskResponse.data, null, 2)); diff --git a/Backend/controllers/chatController.js b/Backend/controllers/chatController.js index d3f9b1b1..41e740fc 100644 --- a/Backend/controllers/chatController.js +++ b/Backend/controllers/chatController.js @@ -33,7 +33,7 @@ const getChatRecommendation = async (req, res) => { console.log(`[DEBUG] User health condition: ${userHealthData.healthCondition || 'general'}`); // Send chat message and health condition to Flask app - const flaskResponse = await axios.post("http://localhost:5001/chat", { + const flaskResponse = await axios.post("http://192.168.60.22:5001/chat", { message: userInput, userId: userId, healthCondition: userHealthData.healthCondition || "general", diff --git a/Backend/controllers/riskAssessController.js b/Backend/controllers/riskAssessController.js new file mode 100644 index 00000000..0aeafb6b --- /dev/null +++ b/Backend/controllers/riskAssessController.js @@ -0,0 +1,366 @@ +const { doc, setDoc, getDoc, deleteDoc, collection, getDocs, query, where } = require("firebase/firestore"); +const { db } = require("../firebaseConfig"); + +// Get Risk Assessment Data by ID +const getRiskAssessmentById = async (req, res) => { + const { id } = req.params; + console.log("[DEBUG] Fetching risk assessment data by ID:", id); + + try { + const riskAssessRef = doc(db, "riskAssessments", id); + const riskAssessSnapshot = await getDoc(riskAssessRef); + + if (riskAssessSnapshot.exists()) { + console.log("[DEBUG] Risk assessment data found for ID:", id); + res.status(200).json(riskAssessSnapshot.data()); + } else { + console.log("[DEBUG] No risk assessment data found for ID:", id); + res.status(404).json({ error: "Risk assessment data not found" }); + } + } catch (error) { + console.error( + "[ERROR] Error fetching risk assessment data for ID:", + id, + error.message + ); + res.status(500).json({ error: "Failed to fetch risk assessment data" }); + } +}; + +// Get Risk Assessment Data by User ID +const getRiskAssessmentByUserId = async (req, res) => { + const { userId } = req.params; + console.log("[DEBUG] Fetching risk assessment data for user:", userId); + + try { + const riskAssessQuery = query( + collection(db, "riskAssessments"), + where("userId", "==", userId) + ); + const riskAssessSnapshot = await getDocs(riskAssessQuery); + + if (!riskAssessSnapshot.empty) { + const riskAssessments = []; + riskAssessSnapshot.forEach((doc) => { + riskAssessments.push({ + id: doc.id, + ...doc.data(), + }); + }); + console.log("[DEBUG] Risk assessment data found for user:", userId); + res.status(200).json(riskAssessments); + } else { + console.log("[DEBUG] No risk assessment data found for user:", userId); + res.status(200).json([]); // Return empty array for users with no assessments + } + } catch (error) { + console.error( + "[ERROR] Error fetching risk assessment data for user:", + userId, + error.message + ); + res.status(500).json({ error: "Failed to fetch risk assessment data" }); + } +}; + +// Get All Risk Assessments +const getAllRiskAssessments = async (req, res) => { + console.log("[DEBUG] Fetching all risk assessment data"); + + try { + const riskAssessSnapshot = await getDocs(collection(db, "riskAssessments")); + const riskAssessments = []; + + riskAssessSnapshot.forEach((doc) => { + riskAssessments.push({ + id: doc.id, + ...doc.data(), + }); + }); + + console.log("[DEBUG] Successfully fetched all risk assessment data"); + res.status(200).json(riskAssessments); + } catch (error) { + console.error( + "[ERROR] Error fetching all risk assessment data:", + error.message + ); + res.status(500).json({ error: "Failed to fetch risk assessment data" }); + } +}; + +// Create Risk Assessment +const createRiskAssessment = async (req, res) => { + console.log("[DEBUG] Creating new risk assessment"); + console.log("[DEBUG] Request Body:", req.body); + + try { + const { + userId, + username, + age, + weight, + height, + bmi, + gender, + heartDisease, + avgGlucoseLevel, + bloodGlucoseLevel, + hba1cLevel, + smokingStatus, + workType, + residenceType, + hypertension, + diabetes + } = req.body; + + if (!userId) { + return res.status(400).json({ error: "User ID is required" }); + } + + // Generate a unique ID for the risk assessment + const riskAssessId = `risk_${userId}_${Date.now()}`; + const riskAssessRef = doc(db, "riskAssessments", riskAssessId); + + // Calculate risk levels + let diabetesRiskLevel = "0"; + let hypertensionRiskLevel = "0"; + + // Diabetes risk calculation - only if diabetes is 0 (no diabetes) + if (diabetes === "0") { + let riskScore = 0; + + if (parseFloat(hba1cLevel) >= 6.5) { + diabetesRiskLevel = "high"; + } else if (parseFloat(hba1cLevel) >= 5.7) { + diabetesRiskLevel = "medium"; + } + + if (parseFloat(bloodGlucoseLevel) >= 7.0) { + diabetesRiskLevel = "high"; + } else if (parseFloat(bloodGlucoseLevel) >= 5.6) { + diabetesRiskLevel = "medium"; + } + + if (diabetesRiskLevel === "0") { + if (parseFloat(age) > 60) riskScore++; + if (hypertension === "1") riskScore++; + if (heartDisease === "1") riskScore++; + if (smokingStatus === "formerly smoked") riskScore++; + if (smokingStatus === "smokes") riskScore += 2; + if (parseFloat(bmi) > 25) riskScore += 2; + if (parseFloat(bmi) > 30) riskScore += 3; + + if (riskScore >= 5) diabetesRiskLevel = "high"; + else if (riskScore >= 3) diabetesRiskLevel = "medium"; + else if (riskScore > 0) diabetesRiskLevel = "low"; + } + } + + // Hypertension risk calculation - only if hypertension is 0 (no hypertension) + if (hypertension === "0") { + if (smokingStatus === "smokes") { + hypertensionRiskLevel = "high"; + } else if (parseFloat(age) > 65) { + hypertensionRiskLevel = "medium"; + } else if (heartDisease === "1") { + hypertensionRiskLevel = "high"; + } else if (hypertensionRiskLevel === "0" && (parseFloat(age) > 50 || parseFloat(bmi) > 30)) { + hypertensionRiskLevel = "low"; + } + } + + const data = { + userId, + username: username || "", + age: age || "", + weight: weight || "", + height: height || "", + bmi: bmi || "", + gender: gender || "", + heartDisease: heartDisease || "0", + avgGlucoseLevel: avgGlucoseLevel || "", + bloodGlucoseLevel: bloodGlucoseLevel || "", + hba1cLevel: hba1cLevel || "", + smokingStatus: smokingStatus || "never smoked", + workType: workType || "", + residenceType: residenceType || "", + hypertension: hypertension || "0", + diabetes: diabetes || "0", + diabetes_risk: diabetesRiskLevel, + hypertension_risk: hypertensionRiskLevel, + createdAt: new Date().toISOString(), + }; + + await setDoc(riskAssessRef, data); + console.log("[DEBUG] Risk assessment successfully created with ID:", riskAssessId); + + res.status(201).json({ + message: "Risk assessment created successfully", + id: riskAssessId, + data + }); + } catch (error) { + console.error( + "[ERROR] Error creating risk assessment:", + error.message + ); + res.status(500).json({ error: "Failed to create risk assessment" }); + } +} + +// Update Risk Assessment +const updateRiskAssessment = async (req, res) => { + const { id } = req.params; + console.log("[DEBUG] Updating risk assessment with ID:", id); + console.log("[DEBUG] Request Body:", req.body); + + try { + const riskAssessRef = doc(db, "riskAssessments", id); + const riskAssessSnapshot = await getDoc(riskAssessRef); + + if (!riskAssessSnapshot.exists()) { + console.log("[DEBUG] Risk assessment not found with ID:", id); + return res.status(404).json({ error: "Risk assessment not found" }); + } + + const { + username, + age, + weight, + height, + bmi, + gender, + heartDisease, + avgGlucoseLevel, + bloodGlucoseLevel, + hba1cLevel, + smokingStatus, + workType, + residenceType, + hypertension, + diabetes + } = req.body; + + // Calculate risk levels + let diabetesRiskLevel = "0"; + let hypertensionRiskLevel = "0"; + + // Diabetes risk calculation - only if diabetes is 0 (no diabetes) + if (diabetes === "0") { + let riskScore = 0; + + if (parseFloat(hba1cLevel) >= 6.5) { + diabetesRiskLevel = "high"; + } else if (parseFloat(hba1cLevel) >= 5.7) { + diabetesRiskLevel = "medium"; + } + + if (parseFloat(bloodGlucoseLevel) >= 7.0) { + diabetesRiskLevel = "high"; + } else if (parseFloat(bloodGlucoseLevel) >= 5.6) { + diabetesRiskLevel = "medium"; + } + + if (diabetesRiskLevel === "0") { + if (parseFloat(age) > 60) riskScore++; + if (hypertension === "1") riskScore++; + if (heartDisease === "1") riskScore++; + if (smokingStatus === "formerly smoked") riskScore++; + if (smokingStatus === "smokes") riskScore += 2; + if (parseFloat(bmi) > 25) riskScore += 2; + if (parseFloat(bmi) > 30) riskScore += 3; + + if (riskScore >= 5) diabetesRiskLevel = "high"; + else if (riskScore >= 3) diabetesRiskLevel = "medium"; + else if (riskScore > 0) diabetesRiskLevel = "low"; + } + } + + // Hypertension risk calculation - only if hypertension is 0 (no hypertension) + if (hypertension === "0") { + if (smokingStatus === "smokes") { + hypertensionRiskLevel = "high"; + } else if (parseFloat(age) > 65) { + hypertensionRiskLevel = "medium"; + } else if (heartDisease === "1") { + hypertensionRiskLevel = "high"; + } else if (hypertensionRiskLevel === "0" && (parseFloat(age) > 50 || parseFloat(bmi) > 30)) { + hypertensionRiskLevel = "low"; + } + } + + const data = { + username: username || riskAssessSnapshot.data().username, + age: age || riskAssessSnapshot.data().age, + weight: weight || riskAssessSnapshot.data().weight, + height: height || riskAssessSnapshot.data().height, + bmi: bmi || riskAssessSnapshot.data().bmi, + gender: gender || riskAssessSnapshot.data().gender, + heartDisease: heartDisease || riskAssessSnapshot.data().heartDisease, + avgGlucoseLevel: avgGlucoseLevel || riskAssessSnapshot.data().avgGlucoseLevel, + bloodGlucoseLevel: bloodGlucoseLevel || riskAssessSnapshot.data().bloodGlucoseLevel, + hba1cLevel: hba1cLevel || riskAssessSnapshot.data().hba1cLevel, + smokingStatus: smokingStatus || riskAssessSnapshot.data().smokingStatus, + workType: workType || riskAssessSnapshot.data().workType, + residenceType: residenceType || riskAssessSnapshot.data().residenceType, + hypertension: hypertension || riskAssessSnapshot.data().hypertension, + diabetes: diabetes || riskAssessSnapshot.data().diabetes || "0", + diabetes_risk: diabetesRiskLevel, + hypertension_risk: hypertensionRiskLevel, + updatedAt: new Date().toISOString(), + }; + + await setDoc(riskAssessRef, data, { merge: true }); + console.log("[DEBUG] Risk assessment successfully updated with ID:", id); + + res.status(200).json({ + message: "Risk assessment updated successfully", + data + }); + } catch (error) { + console.error( + "[ERROR] Error updating risk assessment:", + id, + error.message + ); + res.status(500).json({ error: "Failed to update risk assessment" }); + } +}; + +// Delete Risk Assessment +const deleteRiskAssessment = async (req, res) => { + const { id } = req.params; + console.log("[DEBUG] Deleting risk assessment with ID:", id); + + try { + const riskAssessRef = doc(db, "riskAssessments", id); + const riskAssessSnapshot = await getDoc(riskAssessRef); + + if (!riskAssessSnapshot.exists()) { + console.log("[DEBUG] Risk assessment not found with ID:", id); + return res.status(404).json({ error: "Risk assessment not found" }); + } + + await deleteDoc(riskAssessRef); + console.log("[DEBUG] Risk assessment successfully deleted with ID:", id); + + res.status(200).json({ message: "Risk assessment deleted successfully" }); + } catch (error) { + console.error( + "[ERROR] Error deleting risk assessment:", + id, + error.message + ); + res.status(500).json({ error: "Failed to delete risk assessment" }); + } +}; + +module.exports = { + getRiskAssessmentById, + getRiskAssessmentByUserId, + getAllRiskAssessments, + createRiskAssessment, + updateRiskAssessment, + deleteRiskAssessment, +}; diff --git a/Backend/index.js b/Backend/index.js index da9e2121..3b1dd5bc 100644 --- a/Backend/index.js +++ b/Backend/index.js @@ -17,6 +17,7 @@ const { } = require("./controllers/healthController"); const { getChatRecommendation } = require("./controllers/chatController"); const { getARRecommendations, getTherapyDetails } = require("./controllers/arController"); +const { getRiskAssessmentById, getRiskAssessmentByUserId, getAllRiskAssessments, createRiskAssessment, updateRiskAssessment, deleteRiskAssessment } = require("./controllers/riskAssessController"); const app = express(); app.use(cors({ origin: "*" })); @@ -43,9 +44,17 @@ app.get("/therapy_details/:therapyName", getTherapyDetails); // Chatbot Routes app.post('/healthChat/:userId', getChatRecommendation); +// Risk Assessment Routes +app.get("/riskassessment/:id", getRiskAssessmentById); +app.get("/riskassessment/user/:userId", getRiskAssessmentByUserId); +app.get("/riskassessments", getAllRiskAssessments); +app.post("/riskassessment", createRiskAssessment); +app.put("/riskassessment/:id", updateRiskAssessment); +app.delete("/riskassessment/:id", deleteRiskAssessment); + const PORT = 5000; app.listen(PORT, () => { - console.log(`[DEBUG] Backend server running at http://localhost:${PORT}`); + console.log(`[DEBUG] Backend server running at http://192.168.60.22:${PORT}`); console.log('[DEBUG] Registered routes:', app._router.stack .filter(r => r.route) .map(r => `${r.route.path} (${Object.keys(r.route.methods).join(', ')})`)); diff --git a/Backend/package.json b/Backend/package.json index 1d460adf..2e2b738f 100644 --- a/Backend/package.json +++ b/Backend/package.json @@ -3,6 +3,8 @@ "version": "1.0.0", "main": "index.js", "scripts": { + "start": "node index.js", + "dev": "nodemon index.js", "test": "echo \"Error: no test specified\" && exit 1" }, "author": "", diff --git a/CeylonCare/app/_layout.tsx b/CeylonCare/app/_layout.tsx index 55003862..29a19b46 100644 --- a/CeylonCare/app/_layout.tsx +++ b/CeylonCare/app/_layout.tsx @@ -16,6 +16,9 @@ import ChatScreen from "./pages/Chatbot_component/ChatScreen"; import TherapyRecommendations from "./pages/AR_component/TherapyRecommendations"; import TherapyDetails from "./pages/AR_component/TherapyDetails"; import ARAvatarScreen from "./pages/AR_component/ARAvatarScreen"; +import ViewHealthRisk from "./pages/HealthRisk/ViewHealthRisk"; +import AddHealthRisk from "./pages/HealthRisk/AddHealthRisk"; +import EditHealthRisk from "./pages/HealthRisk/EditHealthRisk"; const Stack = createStackNavigator(); @@ -99,6 +102,24 @@ const StackNavigator = () => { component={ChatScreen} options={{ headerShown: false }} /> + + + + + + ); }; diff --git a/CeylonCare/app/pages/AR_component/CameraTest.tsx b/CeylonCare/app/pages/AR_component/CameraTest.tsx new file mode 100644 index 00000000..9a4528e9 --- /dev/null +++ b/CeylonCare/app/pages/AR_component/CameraTest.tsx @@ -0,0 +1,69 @@ +import { CameraView, CameraType, useCameraPermissions } from 'expo-camera'; +import { useState } from 'react'; +import { Button, StyleSheet, Text, TouchableOpacity, View } from 'react-native'; + +export default function App() { + const [facing, setFacing] = useState('back'); + const [permission, requestPermission] = useCameraPermissions(); + + if (!permission) { + // Camera permissions are still loading. + return ; + } + + if (!permission.granted) { + // Camera permissions are not granted yet. + return ( + + We need your permission to show the camera +