Download src/modules/ai/ai.controller.js from moustafa7/gymco: direct link, hf CLI and curl.
- Browser
- Download file 15.4 kB
-
https://huggingface.co/spaces/moustafa7/gymco/resolve/main/src/modules/ai/ai.controller.js
- Command line
-
hf download hf://spaces/moustafa7/gymco/src/modules/ai/ai.controller.js
-
curl -L -o ai.controller.js https://huggingface.co/spaces/moustafa7/gymco/resolve/main/src/modules/ai/ai.controller.js
15.4 kB
| import Anthropic from '@anthropic-ai/sdk'; | |
| import { ApiError } from '../../common/errors/ApiError.js'; | |
| import { asyncHandler } from '../../common/middleware/asyncHandler.js'; | |
| import { created, ok } from '../../common/utils/response.js'; | |
| import { defaultExercises } from '../../common/constants/defaultExercises.js'; | |
| import { prisma } from '../../config/prisma.js'; | |
| const anthropic = new Anthropic({ | |
| apiKey: process.env.ANTHROPIC_API_KEY || process.env.GLM_API_KEY, | |
| }); | |
| const dayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']; | |
| const pickFallbackExercises = (library, startIndex, count) => { | |
| if (!library.length) return []; | |
| const result = []; | |
| for (let i = 0; i < count; i += 1) { | |
| result.push(library[(startIndex + i) % library.length]); | |
| } | |
| return result; | |
| }; | |
| const baseExerciseLibrary = () => defaultExercises.map((exercise) => ({ | |
| id: null, | |
| isGlobal: true, | |
| ...exercise, | |
| })); | |
| const getExerciseLibrary = async (gymId, take = 150) => { | |
| const library = await prisma.exercise.findMany({ | |
| where: { OR: [{ gymId }, { isGlobal: true }] }, | |
| orderBy: [{ isGlobal: 'desc' }, { name: 'asc' }], | |
| take, | |
| select: { id: true, name: true, nameAr: true, muscleGroup: true, equipment: true, isGlobal: true }, | |
| }); | |
| return library.length ? library : baseExerciseLibrary(); | |
| }; | |
| const fallbackWorkout = async (gymId, member, goals) => { | |
| const exercises = await getExerciseLibrary(gymId, 120); | |
| const exercisesPerDay = goals.level === 'advanced' ? 6 : goals.level === 'intermediate' ? 5 : 4; | |
| const days = Array.from({ length: goals.daysPerWeek }).map((_, dayIndex) => { | |
| const fallbackSet = pickFallbackExercises(exercises, dayIndex * exercisesPerDay, exercisesPerDay); | |
| return { | |
| dayNumber: dayIndex + 1, | |
| name: `${dayNames[dayIndex % 7]} Plan`, | |
| focus: fallbackSet[0]?.muscleGroup || 'general', | |
| isRestDay: false, | |
| exercises: fallbackSet.map((exercise) => ({ | |
| exerciseId: exercise.id, | |
| name: exercise.name, | |
| nameAr: exercise.nameAr || null, | |
| muscleGroup: exercise.muscleGroup || 'general', | |
| equipment: exercise.equipment || null, | |
| sets: goals.level === 'advanced' ? 4 : 3, | |
| reps: goals.primary === 'gain_muscle' ? '8-12' : '12-15', | |
| restSeconds: goals.primary === 'strength' ? 120 : 75, | |
| })), | |
| }; | |
| }); | |
| return { | |
| planName: `${member.fullName} Workout Plan`, | |
| description: 'تم توليد خطة تمرين عملية من مكتبة التمارين المتاحة مع مراعاة هدفك ومستواك.', | |
| durationWeeks: 8, | |
| totalExercises: days.reduce((sum, day) => sum + day.exercises.length, 0), | |
| days, | |
| }; | |
| }; | |
| const parseJsonFromText = (text) => { | |
| const trimmed = String(text || '').replace(/```json|```/gi, '').trim(); | |
| if (!trimmed) throw new Error('Model returned empty content'); | |
| try { | |
| return JSON.parse(trimmed); | |
| } catch { | |
| const match = trimmed.match(/\{[\s\S]*\}/); | |
| if (!match) throw new Error('Model did not return valid JSON'); | |
| return JSON.parse(match[0]); | |
| } | |
| }; | |
| const normalizePlan = (plan, goals, member, library) => { | |
| const daysPerWeek = Math.min(7, Math.max(1, Number(goals.daysPerWeek) || 3)); | |
| const exercisesPerDay = goals.level === 'advanced' ? 6 : goals.level === 'intermediate' ? 5 : 4; | |
| const safeDaysInput = Array.isArray(plan?.days) ? plan.days : []; | |
| const normalizedDays = Array.from({ length: daysPerWeek }).map((_, index) => { | |
| const modelDay = safeDaysInput[index] || {}; | |
| const modelExercises = Array.isArray(modelDay.exercises) ? modelDay.exercises : []; | |
| const fallbackSet = pickFallbackExercises(library, index * exercisesPerDay, exercisesPerDay); | |
| const normalizedExercises = (modelExercises.length ? modelExercises : fallbackSet).slice(0, exercisesPerDay).map((exercise, orderIndex) => { | |
| const source = exercise && typeof exercise === 'object' ? exercise : {}; | |
| const name = source.name || fallbackSet[orderIndex]?.name || `Exercise ${orderIndex + 1}`; | |
| const libraryMatch = library.find((item) => String(item.name || '').toLowerCase() === String(name).toLowerCase()); | |
| return { | |
| exerciseId: source.exerciseId || libraryMatch?.id || null, | |
| name, | |
| nameAr: source.nameAr || libraryMatch?.nameAr || null, | |
| muscleGroup: source.muscleGroup || libraryMatch?.muscleGroup || 'general', | |
| equipment: source.equipment || libraryMatch?.equipment || null, | |
| sets: Math.max(2, Math.min(6, Number(source.sets || (goals.level === 'advanced' ? 4 : 3)))), | |
| reps: String(source.reps || (goals.primary === 'gain_muscle' ? '8-12' : '12-15')), | |
| restSeconds: Math.max(30, Math.min(180, Number(source.restSeconds || 75))), | |
| notes: source.notes || null, | |
| }; | |
| }); | |
| return { | |
| dayNumber: index + 1, | |
| name: modelDay.name || `${dayNames[index % 7]} Plan`, | |
| focus: modelDay.focus || normalizedExercises[0]?.muscleGroup || 'general', | |
| isRestDay: Boolean(modelDay.isRestDay), | |
| exercises: normalizedExercises, | |
| }; | |
| }); | |
| return { | |
| planName: plan?.planName || `${member.fullName} Workout Plan`, | |
| description: plan?.description || 'AI generated plan optimized for this member goal and level.', | |
| durationWeeks: Math.max(4, Math.min(16, Number(plan?.durationWeeks || 8))), | |
| totalExercises: normalizedDays.reduce((sum, day) => sum + day.exercises.length, 0), | |
| days: normalizedDays, | |
| }; | |
| }; | |
| const generateWorkoutWithAI = async (member, goals, library) => { | |
| const prompt = ` | |
| Generate a realistic gym workout plan in strict JSON only. | |
| Member: | |
| - name: ${member.fullName} | |
| - gender: ${member.gender || 'unknown'} | |
| - weightKg: ${member.weight || 'unknown'} | |
| - heightCm: ${member.height || 'unknown'} | |
| - goal: ${goals.primary} | |
| - level: ${goals.level} | |
| - daysPerWeek: ${goals.daysPerWeek} | |
| - availableEquipment: ${goals.equipment.join(', ') || 'all'} | |
| Use these existing library exercises when possible: | |
| ${JSON.stringify(library.slice(0, 80))} | |
| Rules: | |
| 1) Return exactly ${goals.daysPerWeek} training days. | |
| 2) Each day must include 4 to 6 realistic exercises. | |
| 3) Every exercise must include sets and reps. | |
| 4) Prefer compound movements first, then accessory movements. | |
| 5) Keep names practical gym names, no fake exercises. | |
| Return JSON only with this shape: | |
| { | |
| "planName": "string", | |
| "description": "string", | |
| "durationWeeks": 8, | |
| "days": [ | |
| { | |
| "dayNumber": 1, | |
| "name": "string", | |
| "focus": "chest|back|legs|shoulders|arms|core|cardio|full_body|general", | |
| "isRestDay": false, | |
| "exercises": [ | |
| { | |
| "exerciseId": "optional uuid if known", | |
| "name": "string", | |
| "nameAr": "optional string", | |
| "muscleGroup": "string", | |
| "equipment": "optional string", | |
| "sets": 3, | |
| "reps": "10-12", | |
| "restSeconds": 75, | |
| "notes": "optional string" | |
| } | |
| ] | |
| } | |
| ] | |
| } | |
| `.trim(); | |
| const message = await anthropic.messages.create({ | |
| model: 'claude-sonnet-4-20250514', | |
| max_tokens: 4096, | |
| messages: [{ role: 'user', content: prompt }], | |
| }); | |
| const text = message.content[0].text; | |
| return parseJsonFromText(text); | |
| }; | |
| const canAccessMember = async (req, memberId) => { | |
| const member = await prisma.member.findFirst({ | |
| where: { | |
| id: memberId, | |
| gymId: req.gymId, | |
| deletedAt: null, | |
| ...(req.user.role === 'coach' ? { coachId: req.user.sub } : {}), | |
| ...(req.user.role === 'member' ? { id: req.user.memberId } : {}), | |
| }, | |
| }); | |
| if (!member) throw ApiError.notFound('Member not found'); | |
| return member; | |
| }; | |
| const generateWorkout = async (gymId, member, goals) => { | |
| const library = await getExerciseLibrary(gymId, 150); | |
| try { | |
| const raw = await generateWorkoutWithAI(member, goals, library); | |
| return normalizePlan(raw, goals, member, library); | |
| } catch { | |
| const fallback = await fallbackWorkout(gymId, member, goals); | |
| return normalizePlan(fallback, goals, member, library); | |
| } | |
| }; | |
| const workoutJobs = new Map(); | |
| const JOB_TTL_MS = 30 * 60 * 1000; | |
| const setJob = (id, value) => { | |
| workoutJobs.set(id, { ...value, _expires: Date.now() + JOB_TTL_MS }); | |
| for (const [k, v] of workoutJobs) { | |
| if (v._expires < Date.now()) workoutJobs.delete(k); | |
| } | |
| }; | |
| const getJob = (id) => { | |
| const job = workoutJobs.get(id); | |
| if (!job) return null; | |
| if (job._expires < Date.now()) { | |
| workoutJobs.delete(id); | |
| return null; | |
| } | |
| return { status: job.status, result: job.result, error: job.error }; | |
| }; | |
| export const aiController = { | |
| workoutPlan: asyncHandler(async (req, res) => { | |
| const member = await canAccessMember(req, req.body.memberId); | |
| const jobId = `workout_${Date.now()}_${Math.random().toString(36).slice(2)}`; | |
| setJob(jobId, { status: 'queued', result: null, error: null }); | |
| generateWorkout(req.gymId, member, req.body.goals) | |
| .then(async (planJson) => { | |
| const createdPlan = await prisma.$transaction(async (tx) => { | |
| const plan = await tx.workoutPlan.create({ | |
| data: { | |
| gymId: req.gymId, | |
| coachId: req.user.role === 'coach' ? req.user.sub : member.coachId || req.user.sub, | |
| memberId: member.id, | |
| name: planJson.planName, | |
| description: planJson.description, | |
| durationWeeks: planJson.durationWeeks || 8, | |
| startDate: new Date(), | |
| isTemplate: false, | |
| }, | |
| }); | |
| for (const day of planJson.days || []) { | |
| const workoutDay = await tx.workoutDay.create({ | |
| data: { | |
| planId: plan.id, | |
| dayNumber: day.dayNumber, | |
| name: day.name, | |
| focus: day.focus, | |
| isRestDay: Boolean(day.isRestDay), | |
| }, | |
| }); | |
| let order = 0; | |
| for (const item of day.exercises || []) { | |
| let exercise = null; | |
| if (item.exerciseId) { | |
| exercise = await tx.exercise.findFirst({ | |
| where: { id: item.exerciseId, gymId: req.gymId }, | |
| }) ?? await tx.exercise.findFirst({ | |
| where: { id: item.exerciseId, isGlobal: true }, | |
| }); | |
| } | |
| if (!exercise && item.name) { | |
| exercise = await tx.exercise.findFirst({ | |
| where: { name: item.name, gymId: req.gymId }, | |
| }) ?? await tx.exercise.findFirst({ | |
| where: { name: item.name, isGlobal: true }, | |
| }); | |
| } | |
| if (!exercise) { | |
| exercise = await tx.exercise.create({ | |
| data: { | |
| gymId: req.gymId, | |
| name: item.name, | |
| nameAr: item.nameAr, | |
| muscleGroup: item.muscleGroup || 'general', | |
| equipment: item.equipment, | |
| instructions: item.notes || null, | |
| }, | |
| }); | |
| } | |
| await tx.workoutExercise.create({ | |
| data: { | |
| dayId: workoutDay.id, | |
| exerciseId: exercise.id, | |
| sets: item.sets || 3, | |
| reps: item.reps || '10-12', | |
| restSeconds: item.restSeconds || 60, | |
| orderIndex: order, | |
| notes: item.notes || null, | |
| weight: item.weight || null, | |
| }, | |
| }); | |
| order += 1; | |
| } | |
| } | |
| await tx.aIRecommendation.create({ | |
| data: { | |
| gymId: req.gymId, | |
| memberId: member.id, | |
| type: 'workout', | |
| content: planJson, | |
| score: 1, | |
| }, | |
| }); | |
| return tx.workoutPlan.findFirst({ | |
| where: { id: plan.id, gymId: req.gymId }, | |
| include: { days: { include: { exercises: { include: { exercise: true } } } } }, | |
| }); | |
| }); | |
| setJob(jobId, { status: 'completed', result: createdPlan, error: null }); | |
| }) | |
| .catch((err) => { | |
| setJob(jobId, { status: 'failed', result: null, error: err.message }); | |
| }); | |
| created(res, { jobId, status: 'queued' }, 'Workout generation started'); | |
| }), | |
| workoutStatus: asyncHandler(async (req, res) => { | |
| const job = getJob(req.params.jobId); | |
| if (!job) throw ApiError.notFound('Job not found'); | |
| ok(res, job); | |
| }), | |
| nutritionPlan: asyncHandler(async (req, res) => { | |
| const member = await canAccessMember(req, req.params.memberId); | |
| const content = { | |
| goal: req.body.goal, | |
| dailyCalories: Math.round((member.weight || 75) * 32), | |
| macros: { protein: `${Math.round((member.weight || 75) * 1.8)}g`, carbs: '45%', fats: '25%' }, | |
| meals: [{ name: 'Balanced Meal', calories: 500, foods: ['Eggs', 'Oats', 'Fruit'] }], | |
| tips: ['Hydrate daily', 'Prioritize protein', 'Keep meal timing consistent'], | |
| }; | |
| created(res, await prisma.aIRecommendation.create({ data: { gymId: req.gymId, memberId: member.id, type: 'nutrition', content } }), 'Nutrition recommendation generated'); | |
| }), | |
| recommendations: asyncHandler(async (req, res) => { | |
| const memberId = req.user.role === 'member' ? req.user.memberId : req.params.memberId; | |
| await canAccessMember(req, memberId); | |
| ok(res, await prisma.aIRecommendation.findMany({ | |
| where: { gymId: req.gymId, memberId, OR: [{ expiresAt: null }, { expiresAt: { gt: new Date() } }] }, | |
| orderBy: { generatedAt: 'desc' }, | |
| })); | |
| }), | |
| feedback: asyncHandler(async (req, res) => { | |
| if (!req.user.memberId) throw ApiError.forbidden('Member profile is not linked to this account'); | |
| const recommendation = await prisma.aIRecommendation.findFirst({ | |
| where: { id: req.params.id, gymId: req.gymId, memberId: req.user.memberId }, | |
| }); | |
| if (!recommendation) throw ApiError.notFound('Recommendation not found'); | |
| ok(res, await prisma.aIRecommendation.update({ where: { id: recommendation.id }, data: { feedback: req.body.feedback } }), 'Feedback saved'); | |
| }), | |
| churnRisk: asyncHandler(async (req, res) => { | |
| const twoWeeksAgo = new Date(); | |
| twoWeeksAgo.setDate(twoWeeksAgo.getDate() - 14); | |
| const members = await prisma.member.findMany({ | |
| where: { | |
| gymId: req.gymId, | |
| deletedAt: null, | |
| status: 'active', | |
| subscriptions: { some: { status: 'active', endDate: { gt: new Date() }, deletedAt: null } }, | |
| attendance: { none: { checkIn: { gte: twoWeeksAgo }, deletedAt: null } }, | |
| }, | |
| }); | |
| ok(res, members.map((member) => ({ member, score: 0.9, reason: 'no_attendance_14_days' }))); | |
| }), | |
| analyzeGym: asyncHandler(async (req, res) => { | |
| const [members, payments, attendance] = await Promise.all([ | |
| prisma.member.count({ where: { gymId: req.gymId, deletedAt: null } }), | |
| prisma.payment.aggregate({ where: { gymId: req.gymId, deletedAt: null, status: 'success' }, _sum: { amount: true } }), | |
| prisma.attendance.count({ where: { gymId: req.gymId, deletedAt: null } }), | |
| ]); | |
| ok(res, { | |
| insights: [ | |
| `Total members: ${members}`, | |
| `Total successful revenue tracked: ${Number(payments._sum.amount || 0)} EGP`, | |
| `Attendance records: ${attendance}`, | |
| ], | |
| recommendations: ['Follow up with inactive members', 'Promote renewals before expiry', 'Review peak attendance days'], | |
| }); | |
| }), | |
| }; | |