A production-ready Next.js application for AI-powered jewelry virtual try-on with advanced mask generation and error handling.
- Dual Try-On Modes:
- Jewelry + Prompt: Generate model wearing jewelry from text description
- Jewelry + Person: Apply jewelry to existing person photos
- Production-Level Mask Generation: Intelligent mask creation for different jewelry types
- Advanced Error Handling: Comprehensive error tracking and logging
- Performance Monitoring: Built-in performance metrics and timing
- TypeScript: Full type safety throughout the application
- Next.js 15: Modern React framework with App Router
- Sharp: High-performance image processing
- Fal.ai Integration: AI-powered image generation and inpainting
- Production Error Handling: Structured error classes and logging
- Responsive Design: Mobile-first UI with Tailwind CSS
src/
├── app/
│ ├── api/tryon/ # API endpoint with production error handling
│ ├── globals.css # Global styles
│ ├── layout.tsx # Root layout
│ └── page.tsx # Main UI with dual interface
├── lib/
│ ├── errorHandling.ts # Production error handling system
│ ├── maskGenerator.ts # Advanced mask generation
│ └── productionMaskGenerator.ts # Jewelry-specific mask creation
└── components/ # Reusable UI components
- Clone the repository:
git clone <repository-url>
cd image-editing- Install dependencies:
npm install- Set up environment variables:
Create a
.env.localfile with:
FAL_API_KEY=your_fal_api_key_here
OPENAI_API_KEY=your_openai_key_here # Optional for enhanced features
GOOGLE_VISION_API_KEY=your_google_vision_key # Optional for face detection- Run the development server:
npm run devThe application includes a sophisticated mask generation system:
// Jewelry-specific mask strategies
const JEWELRY_CONFIGS = {
necklace: { regionY: 0.4, regionHeight: 0.4, regionWidth: 0.6 },
earrings: { regionY: 0.2, regionHeight: 0.3, regionWidth: 0.8 },
bracelet: { regionY: 0.6, regionHeight: 0.3, regionWidth: 0.4 },
ring: { regionY: 0.7, regionHeight: 0.2, regionWidth: 0.3 }
};Features:
- Jewelry-type specific masking
- Gaussian blur for soft edges
- Fallback mechanisms for robustness
- Performance optimization with Sharp
Production-ready error handling with:
// Custom error classes
class JewelryTryOnError extends Error
class ImageProcessingError extends JewelryTryOnError
class MaskGenerationError extends JewelryTryOnError
class AIServiceError extends JewelryTryOnError
class ValidationError extends JewelryTryOnErrorFeatures:
- Structured error types
- Context-aware error logging
- External service integration ready
- Performance monitoring
Built-in performance tracking:
// Measure API response times
PerformanceMonitor.measureAsync('total_request', async () => {
// Request processing
});
// Track mask generation performance
PerformanceMonitor.measureAsync('mask_generation', async () => {
// Mask generation
});Comprehensive logging system:
const errorHandler = ErrorHandler.getInstance();
// Structured logging
errorHandler.logInfo('Request received', {
hasJewelry: true,
hasPerson: false,
promptLength: 45
});
// Error tracking with context
errorHandler.handleError(error, {
endpoint: '/api/tryon',
userId: 'user123',
timestamp: new Date()
});Request Format: multipart/form-data
Fields:
jewelry(File, required): Jewelry imageprompt(string, required): Description for generationperson(File, optional): Person image for try-on
Response:
{
"success": true,
"image": "https://generated-image-url.com/image.jpg"
}Error Response:
{
"error": "Failed to process jewelry try-on",
"details": "Specific error message",
"code": "ERROR_CODE"
}1. Generate Model with Jewelry:
const formData = new FormData();
formData.append('jewelry', jewelryFile);
formData.append('prompt', 'Beautiful Indian model wearing this necklace');
const response = await fetch('/api/tryon', {
method: 'POST',
body: formData
});2. Apply Jewelry to Person:
const formData = new FormData();
formData.append('jewelry', jewelryFile);
formData.append('person', personFile);
formData.append('prompt', 'Add this jewelry to the person');
const response = await fetch('/api/tryon', {
method: 'POST',
body: formData
});| Variable | Description | Required |
|---|---|---|
FAL_API_KEY |
Fal.ai API key for image generation | Yes |
OPENAI_API_KEY |
OpenAI API key for enhanced features | No |
GOOGLE_VISION_API_KEY |
Google Vision API for face detection | No |
NODE_ENV |
Environment (development/production) | Auto |
The system supports different jewelry types with optimized masking:
- Necklace: Neck/chest area masking
- Earrings: Ear area masking
- Bracelet: Wrist area masking
- Ring: Hand/finger area masking
# Build for production
npm run build
# Start production server
npm start- Error Monitoring: Integrate with Sentry or similar service
- Logging: Set up centralized logging (DataDog, LogRocket)
- Performance: Monitor API response times and image processing
- Scaling: Consider image processing queue for high traffic
- Caching: Implement Redis for frequently used masks
- Security: Add rate limiting and input validation
The application is ready for production monitoring:
// In production, integrate with:
// - Sentry for error tracking
// - DataDog for logging
// - LogRocket for session replay
// - Custom analytics endpoint- TypeScript: Full type safety
- ESLint: Code linting with strict rules
- Prettier: Code formatting
- Husky: Git hooks for quality checks
# Run linting
npm run lint
# Build check
npm run build
# Type checking
npm run type-check- Fork the repository
- Create feature branch (
git checkout -b feature/amazing-feature) - Commit changes (
git commit -m 'Add amazing feature') - Push to branch (
git push origin feature/amazing-feature) - Open Pull Request
Input Images → Validation → Mask Generation → AI Processing → Output
↓ ↓ ↓ ↓ ↓
Error Check → Type Check → Smart Mask → Fal.ai API → URL Response
Error Occurs → Error Classification → Context Addition → Logging → Response
↓ ↓ ↓ ↓ ↓
Exception → Custom Error Class → Add Metadata → Log/Monitor → User Response
- Mask Generation: ~200-500ms
- AI Processing: ~5-15 seconds (depends on Fal.ai)
- Total Request: ~6-20 seconds
- Memory Usage: ~50-100MB per request
This project is licensed under the MIT License - see the LICENSE file for details.
For support and questions:
- Create an issue in the repository
- Check the documentation
- Review error logs for debugging
Note: This is a production-ready implementation with comprehensive error handling, performance monitoring, and scalability considerations. The mask generation system uses geometric approximation as a fallback, but can be enhanced with real face detection APIs for improved accuracy.