Skip to content

brown2020/generatemeai

Repository files navigation

Generate.me AI

Generate.me Logo

A powerful AI-powered image and video generation platform

FeaturesAI ModelsQuick StartArchitectureContributing

Next.js 16.1.1 React 19.2.3 TypeScript 5.9.3 Tailwind CSS 4.1.18 Firebase 12.7.0 Zustand 5.0.9 Vercel AI SDK 6.0.3 AGPL-3.0 License


Overview

Generate.me AI is a full-stack application that enables users to create custom images and videos using multiple AI providers. The platform supports various artistic styles, lighting conditions, color schemes, and advanced generation parameters. Users can either provide their own API keys or purchase credits to access generation features.

Built with modern React patterns, this project showcases best practices including:

  • React Server Components with Next.js 16 App Router
  • Zustand for efficient state management
  • Strategy Pattern for AI provider abstraction
  • Factory Pattern for option configuration
  • Custom Hooks for reusable logic
  • TypeScript strict mode throughout

Features

🎨 Image Generation

  • Multiple AI Models: Support for DALL-E, Stable Diffusion XL, Flux Schnell, Ideogram, and more
  • Style Customization: 20+ artistic styles from Renaissance to Contemporary Art
  • Advanced Parameters: Control lighting, color scheme, perspective, composition, medium, and mood
  • Image-to-Image: Use reference images to guide generation (supported models)
  • Prompt Enhancement: AI-powered prompt optimization using GPT-4
  • Voice Input: Speak your prompts with Web Speech API integration

🎬 Video Generation

  • Talking Avatars: Create talking head videos with D-ID
  • Video Animation: Transform images into videos with Runway ML
  • GIF Conversion: Convert videos to GIF format using FFmpeg
  • Audio Support: Add voiceovers to generated videos

👤 User Management

  • Firebase Authentication: Google Sign-In, email/password, and passwordless email links
  • Profile Management: Store and manage multiple API keys securely
  • Credit System: Pay-per-use credit system or bring your own API keys
  • Image History: Browse, search, and manage all generated content

💳 Payment Integration

  • Stripe Integration: Secure payment processing
  • Credit Purchases: Buy credits for generation usage
  • Transaction History: View all payment records

🔗 Social Features

  • Image Sharing: Share generated images publicly with optional password protection
  • Social Sharing: Share to Facebook, Twitter, LinkedIn, and Email
  • Tags & Categories: Organize and search generated content

Supported AI Models

Image Generation

Model Provider Features
DALL-E OpenAI Text-to-image, high quality
Stable Diffusion XL Fireworks AI Text-to-image, image-to-image
SD3-Turbo Stability AI Fast generation, text-to-image
Playground V2 Fireworks AI Aesthetic-focused generation
Playground V2.5 Fireworks AI Enhanced 1024px aesthetic output
Flux Schnell Replicate (Blackforest Labs) Fast, high-quality generation
Ideogram AI Ideogram Text rendering, typography

Video Generation

Model Provider Features
D-ID D-ID Talking avatars, lip sync, animations
Runway ML Runway Image-to-video animation

Additional Services

Service Provider Features
Background Removal Bria AI Remove image backgrounds
Prompt Optimization OpenAI GPT-4 Enhance prompts for better results
Tag Suggestions OpenAI GPT-4 AI-powered tag recommendations

Tech Stack

Core Framework

Package Version Description
Next.js 16.1.1 React framework with App Router & Turbopack
React 19.2.3 UI library with Server Components
TypeScript 5.9.3 Type-safe JavaScript

State Management

Package Version Description
Zustand 5.0.9 Lightweight state management

Styling & UI

Package Version Description
Tailwind CSS 4.1.18 Utility-first CSS framework
Framer Motion 12.23.26 Animation library
Lucide React 0.562.0 Icon library
React Icons 5.5.0 Additional icons
tailwind-merge 3.4.0 Merge Tailwind classes
clsx 2.1.1 Class name utility

Backend & Database

Package Version Description
Firebase 12.7.0 Authentication, Firestore, Storage
Firebase Admin 13.6.0 Server-side Firebase SDK
react-firebase-hooks 5.1.1 React hooks for Firebase

AI Integration

Package Version Description
Vercel AI SDK 6.0.3 AI SDK core
@ai-sdk/openai 3.0.1 OpenAI provider
@ai-sdk/rsc 2.0.3 React Server Components support
Replicate 1.4.0 Replicate API client

Payments

Package Version Description
Stripe 20.1.0 Payment processing
@stripe/react-stripe-js 5.4.1 React Stripe components
@stripe/stripe-js 8.6.0 Stripe.js

Media Processing

Package Version Description
Sharp 0.34.5 High-performance image processing
fluent-ffmpeg 2.1.3 FFmpeg wrapper
ffmpeg-static 5.2.0 Static FFmpeg binaries
dom-to-image 2.6.0 DOM to image conversion

UI Components

Package Version Description
React Modal 3.16.1 Accessible modal dialogs
React Select 5.8.1 Select input component
React Hot Toast 2.4.1 Toast notifications
React Spinners 0.17.0 Loading spinners
React Share 5.1.0 Social sharing buttons
react-textarea-autosize 8.5.3 Auto-resizing textarea
react-cookie-consent 9.0.0 Cookie consent banner

Utilities

Package Version Description
cookies-next 6.1.1 Cookie handling for Next.js
lodash 4.17.21 Utility functions
formdata-node 6.0.3 FormData implementation

Development

Package Version Description
ESLint 9.15.0 Code linting
PostCSS 8.4.47 CSS processing

Quick Start

Prerequisites

  • Node.js 20+ (recommended: use nvm)
  • Firebase Project with Firestore, Storage, and Authentication enabled
  • API Keys for at least one AI provider (OpenAI, Fireworks, or Replicate)

Installation

  1. Clone the repository

    git clone https://github.com/brown2020/generatemeai.git
    cd generatemeai
  2. Install dependencies

    npm install
  3. Configure environment variables

    cp .env.example .env.local

    Edit .env.local with your configuration (see Environment Variables).

  4. Set up Firebase

    • Create a Firebase project at console.firebase.google.com
    • Enable Authentication (Google, Email/Password, Email Link)
    • Create a Firestore database
    • Create a Storage bucket
    • Download your service account key for server-side operations

    Deploy security rules (recommended):

    • Firestore rules: firestore.rules
    • Storage rules: storage.rules

    With Firebase CLI installed/configured:

    firebase deploy --only firestore:rules,storage

Firebase Security Rules

This repo includes production-ready Firebase rules that protect user-generated content by default:

  • Firestore (firestore.rules)

    • Private content: profiles/{uid}/covers/{id} is owner-only read/write.
    • Private user data: users/{uid}/** is owner-only read/write.
    • Public sharing: publicImages/{imageId} supports public get (no list) to avoid noisy permission errors when a doc is missing/unshared. Only the owner can create/update/delete (must have profiles/{auth.uid}/covers/{imageId}), and shared docs are enforced to be written with isSharable == true.
    • Note on “password protection”: passwords are stored in the public doc today; do not treat it as a secret.
  • Storage (storage.rules)

    • Private user uploads: generated/{uid}/* and image-references/{uid}/* are owner-only read/write (with basic image + size limits).
    • Public static assets: previews/** is public read.
    • Server-only artifacts: video-generation/* is denied for SDK access (served via signed URLs).
  1. Run the development server

    npm run dev

    Open http://localhost:3000 to view the application.

Production Build

npm run build
npm start

Environment Variables

Create a .env.local file in the root directory:

Firebase Configuration (Required)

# Firebase Client SDK
NEXT_PUBLIC_FIREBASE_APIKEY=your_api_key
NEXT_PUBLIC_FIREBASE_AUTHDOMAIN=your_project.firebaseapp.com
NEXT_PUBLIC_FIREBASE_PROJECTID=your_project_id
NEXT_PUBLIC_FIREBASE_STORAGEBUCKET=your_project.appspot.com
NEXT_PUBLIC_FIREBASE_MESSAGINGSENDERID=your_sender_id
NEXT_PUBLIC_FIREBASE_APPID=your_app_id
NEXT_PUBLIC_FIREBASE_MEASUREMENTID=G-XXXXXXXXXX

# Firebase Admin SDK (Server-side)
FIREBASE_TYPE=service_account
FIREBASE_PROJECT_ID=your_project_id
FIREBASE_PRIVATE_KEY_ID=your_private_key_id
FIREBASE_PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n"
FIREBASE_CLIENT_EMAIL=firebase-adminsdk-xxxxx@your_project.iam.gserviceaccount.com
FIREBASE_CLIENT_ID=your_client_id
FIREBASE_AUTH_URI=https://accounts.google.com/o/oauth2/auth
FIREBASE_TOKEN_URI=https://oauth2.googleapis.com/token
FIREBASE_AUTH_PROVIDER_X509_CERT_URL=https://www.googleapis.com/oauth2/v1/certs
FIREBASE_CLIENT_CERTS_URL=https://www.googleapis.com/robot/v1/metadata/x509/your_service_account

AI Provider API Keys (At least one required)

OPENAI_API_KEY=sk-...
FIREWORKS_API_KEY=fw_...
REPLICATE_API_TOKEN=r8_...
STABILITY_API_KEY=sk-...
IDEOGRAM_API_KEY=...
DID_API_KEY=...
RUNWAY_API_KEY=...
BRIA_API_KEY=...

Stripe Configuration (For payments)

STRIPE_SECRET_KEY=sk_...
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY=pk_...

Credit Configuration

NEXT_PUBLIC_CREDITS_PER_DALL_E_IMAGE=4
NEXT_PUBLIC_CREDITS_PER_STABLE_DIFFUSION_XL_IMAGE=4
NEXT_PUBLIC_CREDITS_PER_STABILITY_SD3_TURBO_IMAGE=4
NEXT_PUBLIC_CREDITS_PER_PLAYGROUND_V2_IMAGE=4
NEXT_PUBLIC_CREDITS_PER_PLAYGROUND_V2_5_IMAGE=4
NEXT_PUBLIC_CREDITS_PER_FLUX_SCHNELL=4
NEXT_PUBLIC_CREDITS_PER_D_ID=50
NEXT_PUBLIC_CREDITS_PER_RUNWAY=4
NEXT_PUBLIC_CREDITS_PER_IDEOGRAM=4
NEXT_PUBLIC_CREDITS_PER_BRIA_IMAGE=4
NEXT_PUBLIC_CREDITS_PER_CHATGPT=2

Application Settings

NEXT_PUBLIC_COOKIE_NAME=generateAuthToken
NEXT_PUBLIC_ENABLE_PREVIEW_MARKING=false

Project Structure

generatemeai/
├── public/                          # Static assets
│   ├── previews/                    # Model/style preview images
│   └── .well-known/                 # App association files
├── src/
│   ├── app/                         # Next.js App Router
│   │   ├── api/                     # API routes
│   │   ├── generate/                # Image generation page
│   │   ├── images/                  # Gallery & detail pages
│   │   │   └── [id]/                # Dynamic image page
│   │   ├── profile/                 # User profile
│   │   ├── payment-*/               # Payment flow
│   │   └── [legal pages]/           # About, Terms, Privacy, Support
│   │
│   ├── actions/                     # Server Actions
│   │   ├── generateImage.ts         # Image generation orchestration
│   │   ├── generateVideo.ts         # Video generation
│   │   ├── generateGif.ts           # GIF conversion
│   │   ├── suggestTags.ts           # AI tag suggestions (AI SDK)
│   │   ├── removeBackground.ts      # Background removal
│   │   └── paymentActions.ts        # Payment processing
│   │
│   ├── components/                  # React components
│   │   ├── auth/                    # Authentication components
│   │   │   └── AuthModal.tsx        # Extracted auth modal
│   │   ├── common/                  # Shared UI components
│   │   │   └── PaginatedGrid.tsx    # Generic paginated grid
│   │   ├── generation/              # Image generation UI
│   │   │   ├── ModelCard.tsx        # AI model selector card
│   │   │   ├── StyleCard.tsx        # Art style selector card
│   │   │   ├── SettingsSelector.tsx # Option selector component
│   │   │   ├── PreviewCard.tsx      # Preview image card
│   │   │   └── PreviewMarker.tsx    # Mark as preview feature
│   │   ├── image/                   # Image display components
│   │   │   ├── ImageViewer.tsx      # Main image display
│   │   │   ├── ImageActions.tsx     # Share, delete actions
│   │   │   ├── ImageMetadata.tsx    # Image metadata display
│   │   │   ├── TagManager.tsx       # Tag CRUD operations
│   │   │   ├── SocialShare.tsx      # Social sharing buttons
│   │   │   └── [modals]             # Password, color picker modals
│   │   ├── image-page/              # Image page logic (hooks)
│   │   │   ├── useImagePageData.ts  # Data fetching hook
│   │   │   └── useImagePageActions.ts # Actions hook
│   │   └── [page components]        # Full page components
│   │
│   ├── constants/                   # Configuration constants
│   │   ├── optionFactory.ts         # Factory for option sets
│   │   ├── colors.ts                # Color scheme options
│   │   ├── lightings.ts             # Lighting options
│   │   ├── perspectives.ts          # Perspective options
│   │   ├── compositions.ts          # Composition options
│   │   ├── mediums.ts               # Medium options
│   │   ├── moods.ts                 # Mood options
│   │   ├── artStyles.ts             # Art style definitions
│   │   └── models.ts                # AI model definitions
│   │
│   ├── firebase/                    # Firebase configuration
│   │   ├── firebaseClient.ts        # Client SDK initialization
│   │   ├── firebaseAdmin.ts         # Admin SDK initialization
│   │   └── paths.ts                 # Firestore path utilities
│   │
│   ├── hooks/                       # Custom React hooks
│   │   ├── useAuth.ts               # Authentication utilities
│   │   ├── useAuthLogic.ts          # Auth form logic
│   │   ├── useAuthToken.ts          # Token management
│   │   ├── useImageGenerator.ts     # Image generation logic
│   │   ├── useGenerationHistory.ts  # History management
│   │   ├── useNavigation.ts         # Navigation utilities
│   │   ├── usePreviewSaver.ts       # Preview saving logic
│   │   ├── useSpeechRecognition.ts  # Voice input
│   │   └── useUrlSync.ts            # URL parameter sync
│   │
│   ├── strategies/                  # AI provider strategies
│   │   ├── types.ts                 # Strategy interfaces
│   │   ├── index.ts                 # Strategy registry
│   │   ├── dalle.ts                 # OpenAI DALL-E
│   │   ├── fireworks.ts             # Fireworks AI (SD, Playground)
│   │   ├── replicate.ts             # Replicate (Flux)
│   │   ├── stability.ts             # Stability AI
│   │   └── ideogram.ts              # Ideogram AI
│   │
│   ├── types/                       # TypeScript definitions
│   │   ├── errors.ts                # Custom error types
│   │   ├── image.ts                 # Image data types
│   │   ├── model.ts                 # Model types
│   │   └── promptdata.ts            # Prompt data types
│   │
│   ├── utils/                       # Utility functions
│   │   ├── cn.ts                    # Class name utility
│   │   ├── credits.ts               # Credit calculations
│   │   ├── promptUtils.ts           # Prompt building
│   │   ├── promptOptimizer.ts       # AI prompt enhancement
│   │   ├── platform.ts              # Platform detection
│   │   └── imageUtils.ts            # Image utilities
│   │
│   └── zustand/                     # State management
│       ├── useAuthStore.ts          # Authentication state
│       ├── useProfileStore.ts       # User profile & credits
│       ├── useGenerationStore.ts    # Generation parameters
│       ├── usePaymentsStore.ts      # Payment history
│       └── useInitializeStores.ts   # Store initialization
│
├── .env.example                     # Example environment variables
├── next.config.mjs                  # Next.js configuration
├── tailwind.config.ts               # Tailwind CSS configuration
├── tsconfig.json                    # TypeScript configuration
└── package.json                     # Project dependencies

Architecture

Strategy Pattern for AI Providers

The application uses a Strategy Pattern to abstract different AI model integrations, making it easy to add new providers:

// src/strategies/types.ts
export interface StrategyContext {
  message: string;
  img: File | null;
  apiKey: string;
  useCredits: boolean;
}

export type GenerationStrategy = (
  context: StrategyContext
) => Promise<ArrayBuffer | Buffer>;

// src/strategies/index.ts
export const strategies: Record<string, GenerationStrategy> = {
  "dall-e": dalleStrategy,
  "stable-diffusion-xl": fireworksStrategy,
  "playground-v2": playgroundV2Strategy,
  "flux-schnell": replicateStrategy,
  // Add new providers here
};

Factory Pattern for Options

Option constants use a Factory Pattern for consistent behavior:

// src/constants/optionFactory.ts
export const createOptionSet = <T extends Option>(options: T[]) => {
  const optionsWithIds = withIds(options);
  return {
    options: optionsWithIds,
    getValueFromLabel: createLabelToValueMapper(),
    findByValue: createOptionFinder(optionsWithIds),
    findByLabel: createOptionFinderByLabel(optionsWithIds),
  };
};

// Usage in src/constants/colors.ts
export const {
  options: colors,
  getValueFromLabel: getColorFromLabel,
  findByValue: findColorByValue,
  findByLabel: findColorByLabel,
} = createOptionSet(colorOptions);

Custom Hooks Architecture

Hooks are organized by domain and responsibility:

Hook Purpose
useAuth Authentication state utilities
useAuthLogic Auth form state and handlers
useAuthToken JWT token management and refresh
useImageGenerator Orchestrates image generation
useGenerationHistory Saves generation to Firestore
useNavigation Shared navigation logic
usePreviewSaver Save images as previews
useSpeechRecognition Web Speech API integration
useUrlSync Sync state with URL parameters

Zustand Store Organization

// Stores are organized by domain
useAuthStore; // Authentication: uid, email, displayName
useProfileStore; // Profile: credits, API keys, preferences
useGenerationStore; // Generation: prompt, model, settings, result
usePaymentsStore; // Payments: history, processing state

Error Handling

Custom error types provide consistent error handling:

// src/types/errors.ts
export class AppError extends Error {
  constructor(message: string, code: string, statusCode: number) { ... }
}

export class InsufficientCreditsError extends AppError { ... }
export class AuthenticationError extends AppError { ... }
export class ValidationError extends AppError { ... }
export class ExternalApiError extends AppError { ... }

Firebase Path Utilities

Centralized Firestore paths prevent typos and enable refactoring:

// src/firebase/paths.ts
export const FirestorePaths = {
  userProfile: (uid: string) => `users/${uid}/profile/userData`,
  profileCover: (uid: string, coverId: string) =>
    `profiles/${uid}/covers/${coverId}`,
  publicImage: (id: string) => `publicImages/${id}`,
  // ...
} as const;

Usage

Image Generation

  1. Navigate to the Generate page
  2. Enter a text prompt describing your desired image
  3. Select an AI model from the available options
  4. Optionally customize:
    • Artistic style (Renaissance, Impressionism, etc.)
    • Color scheme (Warm, Cool, Vibrant, etc.)
    • Lighting (Golden Hour, Dramatic, Soft, etc.)
    • Perspective, composition, medium, and mood
  5. Click Generate Image
  6. View, download, or share your generated image

Video Generation

  1. Generate or upload a base image
  2. Open the image detail page
  3. Click Create Video
  4. Choose between:
    • Talking Avatar (D-ID): Add speech to your image
    • Animation (Runway ML): Add motion to your image
  5. Configure audio/script options
  6. Generate and download your video

Profile Management

  • API Keys: Add your own keys for each AI provider
  • Credits: Purchase credits or use your own API keys
  • Toggle Mode: Switch between credits and API key usage
  • Delete Account: Remove all data and generated content

Scripts

# Development with Turbopack (fast refresh)
npm run dev

# Production build
npm run build

# Start production server
npm start

# Run ESLint
npm run lint

Contributing

Contributions are welcome! Please follow these steps:

  1. Fork the repository
  2. Create a feature branch
    git checkout -b feature/amazing-feature
  3. Commit your changes
    git commit -m 'Add amazing feature'
  4. Push to the branch
    git push origin feature/amazing-feature
  5. Open a Pull Request

Development Guidelines

  • Follow existing code patterns and architecture
  • Use TypeScript strict mode - avoid any types
  • Use the Factory Pattern for new option sets
  • Use the Strategy Pattern for new AI providers
  • Create custom hooks for reusable logic
  • Write meaningful commit messages

Code Style

Area Convention
Components Functional components with hooks
State Zustand for global, useState for local
Styling Tailwind CSS utility classes
Types Explicit types, use custom error types
Paths Use FirestorePaths utility
Options Use createOptionSet factory

Adding a New AI Provider

  1. Create a new strategy in src/strategies/
  2. Implement the GenerationStrategy interface
  3. Register in src/strategies/index.ts
  4. Add model to src/constants/models.ts
  5. Add credit configuration to src/utils/credits.ts
  6. Update environment variables

Deployment

Vercel (Recommended)

  1. Connect your GitHub repository to Vercel
  2. Configure environment variables in the Vercel dashboard
  3. Deploy with automatic CI/CD

Other Platforms

The application can be deployed to any platform supporting Next.js:

  • AWS Amplify
  • Google Cloud Run
  • Railway
  • Render

Requirements:

  • Node.js 20+
  • Server-side rendering support
  • Environment variables
  • FFmpeg binary (for video processing)

Troubleshooting

Common Issues

Firebase Authentication Errors

  • Ensure all Firebase config values are correct
  • Check that authentication methods are enabled in Firebase Console
  • Verify the authorized domains include your deployment URL

API Rate Limits

  • AI providers have rate limits; implement retry logic for production
  • Consider using credits to distribute load across providers

Video Processing Fails

  • Ensure FFmpeg is available in your environment
  • Check that ffmpeg-static is properly installed

Images Not Loading

  • If you're using Firebase Storage SDK reads, ensure rules allow the reads you expect.
  • This app primarily serves generated media via signed URLs (Admin SDK), so Storage rules typically won't block rendering.
  • Check that next.config.mjs includes all required image domains.

Build Errors

  • Run npm run lint to check for TypeScript errors
  • Ensure all environment variables are set

License

This project is licensed under the GNU Affero General Public License v3.0. See the LICENSE.md file for details.


Support


Acknowledgments


Made with ❤️ by Ignite Channel

About

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 3

  •  
  •  
  •