A gamified speech training application with AI-powered analysis and progress tracking, now integrated with Neon DB for secure user data management.
- 🎯 Access Key Authentication: Secure authentication using access keys from external applications
- 🗄️ Neon DB Integration: PostgreSQL database for user progress, sessions, and statistics
- 🎮 Gamified Learning: Progressive levels with rewards and achievements
- 🤖 AI Speech Analysis: AssemblyAI integration for speech transcription and analysis
- 🎤 VAPI Interviews: AI-powered mock interviews for advanced training
- 📊 Progress Tracking: Comprehensive analytics and performance metrics
git clone <repository-url>
cd speech-game
npm install- Go to Neon Console
- Create a new project
- Copy the connection string from your project dashboard
- Update
.env.localwith your Neon database URL:
NEON_DATABASE_URL=postgresql://username:password@hostname/database?sslmode=requireExecute the database migration to set up all tables:
node database/schema/migrate.jsThis will create all necessary tables:
users- User accounts with access keysuser_progress- Level completion trackinguser_sessions- Session time and activity trackinguser_stats- Auto-updating aggregated user statistics and performance metrics (via database triggers)
The user_stats table is automatically maintained through PostgreSQL triggers:
- Real-time Updates: Statistics update immediately when users complete levels
- Calculated Metrics: Averages, totals, and performance indicators are computed automatically
- Performance Optimized: Analytics queries use pre-calculated cached data instead of expensive real-time calculations
- Fallback Calculations: If cached stats are unavailable, real-time calculations from progress data ensure accuracy
Update your .env.local file with all required API keys:
# Neon Database Connection String
NEON_DATABASE_URL=your_neon_database_url_here
# AssemblyAI API Key for speech analysis
ASSEMBLYAI_API_KEY=your_assemblyai_api_key
# VAPI API Key for interview functionality
NEXT_PUBLIC_VAPI_API_KEY=your_vapi_api_keyIf you want to pre-populate the database with authorized users, you can add access keys:
# Interactive mode - add access keys one by one
npm run db:add-key
# List existing access keys
npm run db:list-keysTEST-ACCESS-KEY => test-key The script will prompt you to enter access keys for authorized users. Each access key represents one user account in the system.
npm run devid- Primary keyaccess_key- Unique access key for authenticationcreated_at- Account creation timestamplast_active- Last activity timestampis_active- Account status
user_id- Foreign key to userslevel_id- Level number completedsuccess- Whether level was passedscore- Numerical score (0-100)transcription- Speech transcription textaccuracy- Speech accuracy percentagefluency- Speech fluency scorewords_per_minute- Speaking speedcoins_earned- Coins awardedxp_earned- XP awarded
user_id- Foreign key to userssession_start- Session start timesession_end- Session end time (nullable)total_time_seconds- Session durationlevels_attempted- Levels attempted in sessionlevels_completed- Levels completed in sessiontotal_coins_earned- Coins earned in sessiontotal_xp_earned- XP earned in session
user_id- Foreign key to users (unique)total_coins- Total coins accumulatedtotal_xp- Total XP earnedcurrent_level- Current user levelcurrent_streak- Current completion streakbest_streak- Best completion streaktotal_sessions- Total sessions playedaverage_score- Average level scoreaverage_accuracy- Average speech accuracyaverage_fluency- Average speech fluency
POST /api/auth/validate- Validate access key and create session
GET /api/user/data- Get user statistics and progress
POST /api/progress- Save level completionGET /api/progress- Get progress data
POST /api/session- Start/end user sessions (with unique session keys)
GET /api/analytics- Comprehensive user analytics and performance data with pagination- Query parameters:
recentActivityLimit,sessionLimit,includeTrends
- Query parameters:
The application uses access key-based authentication:
- Users enter their access key on the login screen
- The key is validated against the database
- Valid keys create or retrieve user accounts
- All subsequent requests include the access key in headers/cookies
Access keys are bound to users in external applications and provide the only authorization mechanism.
The application implements comprehensive session-based tracking:
- Session Creation: When a user presses "Start Challenge", a unique session key is generated
- Activity Mapping: All speech analysis, progress saves, and user interactions are linked to the active session
- Session Completion: Sessions are automatically ended when users complete challenges
- Unique Session Keys: Each session has a unique identifier (
session_[timestamp]_[random]) - Activity Linking: All progress records include the session key for grouping
- Session Statistics: Track time spent, levels attempted, coins earned, etc.
user_sessions (session_key) → user_progress (session_key)
- Detailed Analytics: Track user behavior patterns within sessions
- Performance Insights: Analyze session effectiveness and improvement trends
- Activity Grouping: Group related activities for better data analysis
- Session Recovery: Maintain context across page refreshes and navigation
You can manage access keys using the provided scripts:
# Add new access keys interactively
npm run db:add-key
# View existing access keys
npm run db:list-keysFeatures:
- ✅ Checks for duplicate access keys
- 🔄 Can reactivate deactivated users
- 📊 Shows database statistics
- 🎯 Batch entry support
Example Usage:
$ node database/add-access-key.js
🔄 Connecting to Neon DB...
✅ Connected to database
📊 Database Status:
Total Users: 0
Active Users: 0
🔑 Access Key Management Tool
=============================
Enter the access key to add (or "quit" to exit): abc123def456
✅ Access key added successfully!
User ID: 1
Created: 2024-01-15T10:30:00.000Z
Access Key: abc123def456
Add another access key? (Y/n): n
👋 Goodbye!Users can access detailed analytics by clicking the 📊 ANALYTICS button in the main game interface. The analytics dashboard provides:
- Real-time Performance Metrics: Average scores, accuracy, fluency, and speaking speed
- Progress Tracking: Total levels completed, coins earned, and XP accumulated
- Session Analysis: Detailed breakdown of performance by session
- Recent Activity: Last 10 speech attempts with full transcription and metrics
- Historical Trends: Performance improvement over time
The /api/analytics endpoint provides comprehensive speech performance analytics using cached statistics from the user_stats table:
- Total levels completed and current level
- Total coins and XP earned
- Current and best streaks
- Total sessions and time spent
- Average score, accuracy, fluency, and words per minute
- Historical trends and improvement tracking
- Level-by-level breakdown with detailed statistics
- Session-by-session performance breakdown (configurable limit)
- Activity grouping by session keys
- Session effectiveness analysis
- Time-based session patterns
- Configurable number of recent level attempts with full analysis data
- Transcription text, accuracy scores, fluency ratings
- Duration and performance metrics
- Session context for each activity
- Daily progress tracking for the last 30 days
- Performance improvement over time (first half vs second half comparison)
- Session-based analytics for detailed insights
- Comprehensive speech therapy progress monitoring
- Score, accuracy, and fluency improvement metrics
Available database scripts:
# Run initial migration (creates all tables)
npm run db:migrate
# Run session key migration (adds session tracking to existing databases)
npm run db:migrate-sessions
# Add access keys for users
npm run db:add-key
# View existing access keys
npm run db:list-keys
# Get analytics for a user (replace YOUR_ACCESS_KEY)
npm run db:analyticsTo reset the database completely:
# Drop all tables and rerun migration
node database/schema/migrate.jsThe application includes comprehensive error handling and fallbacks for database connectivity issues.
Ensure all environment variables are set in your deployment environment:
NEON_DATABASE_URLASSEMBLYAI_API_KEYNEXT_PUBLIC_VAPI_API_KEY
- Access keys are stored securely in HTTP-only cookies
- All database queries use parameterized statements
- User data is isolated by access key validation
- No sensitive information is exposed in client-side code
- Verify
NEON_DATABASE_URLis correctly set - Ensure your Neon project is active
- Check database firewall settings
- Access keys must be validated before use
- Check browser console for authentication errors
- Verify cookie settings for cross-origin requests
- Ensure PostgreSQL extensions are available
- Check database permissions
- Verify connection string format
- Fork the repository
- Create a feature branch
- Make your changes
- Test database operations
- Submit a pull request
[Your License Here]