Skip to content

AI-driven YouTube video generator that creates viral content automatically - from script to upload in minutes. Modern SaaS platform built with Laravel, Vue.js, n8n and Docker, featuring intelligent automation and seamless YouTube integration.

set up the docker-compose, n8n workflows

Mohamed El aassalc7d5cdb62b73
diff --git a/DOCKER-README.md b/DOCKER-README.md
new file mode 100644
index 0000000..cbb8179
--- /dev/null
+++ b/DOCKER-README.md
@@ -0,0 +1,364 @@
+# YouTube Video Generator - Docker Setup
+
+## 🚀 Quick Start with Docker
+
+This setup provides a complete containerized environment for the YouTube Video Generator application with n8n automation.
+
+### Prerequisites
+
+- Docker Desktop installed
+- Docker Compose installed
+- At least 4GB RAM available
+- Ports 8000, 5678, 3306, 6379 available
+
+### 🏗️ Architecture
+
+```
+┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
+│ Laravel App │ │ n8n │ │ MySQL │
+│ (Port 8000) │◄──►│ (Port 5678) │◄──►│ (Port 3306) │
+└─────────────────┘ └─────────────────┘ └─────────────────┘
+ │ │ │
+ └───────────────────────┼───────────────────────┘
+ │
+ ┌─────────────────┐
+ │ Redis │
+ │ (Port 6379) │
+ └─────────────────┘
+```
+
+### 🔧 Services
+
+| Service | Description | Port | Credentials |
+|---------|-------------|------|-------------|
+| **app** | Laravel Application | 8000 | - |
+| **webserver** | Nginx Web Server | 80 | - |
+| **db** | MySQL Database | 3306 | root/secret |
+| **redis** | Redis Cache & Queues | 6379 | - |
+| **queue** | Laravel Queue Worker | - | - |
+| **n8n** | Automation Platform | 5678 | admin/n8npassword |
+| **ffmpeg** | Video Processing | - | - |
+
+## 🚀 Getting Started
+
+### Windows Users:
+```bash
+./start.bat
+```
+
+### Linux/Mac Users:
+```bash
+chmod +x start.sh
+./start.sh
+```
+
+### Manual Setup:
+```bash
+# 1. Copy environment file
+cp .env.docker .env
+
+# 2. Build containers
+docker-compose build --no-cache
+
+# 3. Start services
+docker-compose up -d
+
+# 4. Wait for database (30 seconds)
+sleep 30
+
+# 5. Run migrations
+docker-compose exec app php artisan migrate:fresh --seed
+
+# 6. Generate app key
+docker-compose exec app php artisan key:generate
+
+# 7. Clear caches
+docker-compose exec app php artisan config:cache
+docker-compose exec app php artisan route:cache
+
+# 8. Set permissions
+docker-compose exec app chmod -R 777 storage bootstrap/cache
+```
+
+## 🌐 Access Points
+
+- **Laravel Application**: http://localhost:8000
+- **n8n Workflows**: http://localhost:5678
+- **MySQL Database**: localhost:3306
+- **Redis**: localhost:6379
+
+## 🔐 Default Credentials
+
+### n8n Dashboard
+- **URL**: http://localhost:5678
+- **Username**: admin
+- **Password**: n8npassword
+
+### MySQL Database
+- **Host**: localhost
+- **Port**: 3306
+- **Database**: ytVideoGen
+- **Username**: root
+- **Password**: secret
+
+## 🤖 n8n Workflows
+
+The application includes 3 pre-configured workflows:
+
+### 1. Video Generation Workflow
+**File**: `docker/n8n/workflows/video-generation.json`
+
+**Flow**:
+1. Receives webhook with video topic
+2. Generates script using OpenAI GPT-4
+3. Fetches relevant visuals from Pexels
+4. Creates voiceover using ElevenLabs TTS
+5. Assembles video using FFmpeg
+6. Updates video status in database
+
+**Webhook URL**: `http://localhost:5678/webhook/video-generation`
+
+### 2. YouTube Upload Workflow
+**File**: `docker/n8n/workflows/youtube-upload.json`
+
+**Flow**:
+1. Receives upload request
+2. Gets video details from database
+3. Uploads to YouTube using API
+4. Updates upload status
+
+**Webhook URL**: `http://localhost:5678/webhook/youtube-upload`
+
+### 3. Autopilot Workflow
+**File**: `docker/n8n/workflows/autopilot.json`
+
+**Flow**:
+1. Runs daily via cron schedule
+2. Gets scheduled video topics
+3. Triggers video generation for each
+4. Waits for processing completion
+5. Automatically uploads to YouTube
+
+## 🔑 API Keys Configuration
+
+### Required API Keys
+
+1. **OpenAI API Key**
+ - Sign up at: https://platform.openai.com/
+ - Add to n8n credentials as "OpenAI API"
+
+2. **ElevenLabs API Key**
+ - Sign up at: https://elevenlabs.io/
+ - Add to n8n credentials as "ElevenLabs API"
+
+3. **Pexels API Key**
+ - Sign up at: https://www.pexels.com/api/
+ - Add to n8n credentials as "Pexels API"
+
+4. **Google OAuth & YouTube API**
+ - Already configured in `.env.docker`
+ - Update with your actual credentials
+
+### Adding API Keys to n8n
+
+1. Visit http://localhost:5678
+2. Login with admin/n8npassword
+3. Go to Settings → Credentials
+4. Add new credentials for each service
+5. Import the workflow files
+6. Update credential references in workflows
+
+## 📁 Project Structure
+
+```
+project/
+├── docker/
+│ ├── nginx/ # Nginx configuration
+│ ├── php/ # PHP configuration
+│ └── n8n/
+│ └── workflows/ # n8n workflow definitions
+├── docker-compose.yml # Docker services configuration
+├── Dockerfile # Laravel app container
+├── .env.docker # Environment variables for Docker
+├── start.sh # Linux/Mac startup script
+└── start.bat # Windows startup script
+```
+
+## 🔧 Development Commands
+
+### Container Management
+```bash
+# Start all services
+docker-compose up -d
+
+# Stop all services
+docker-compose down
+
+# View logs
+docker-compose logs -f app
+docker-compose logs -f n8n
+
+# Restart specific service
+docker-compose restart app
+```
+
+### Laravel Commands
+```bash
+# Run artisan commands
+docker-compose exec app php artisan migrate
+docker-compose exec app php artisan queue:work
+docker-compose exec app php artisan cache:clear
+
+# Access container shell
+docker-compose exec app bash
+```
+
+### Database Operations
+```bash
+# Access MySQL
+docker-compose exec db mysql -u root -p
+
+# Backup database
+docker-compose exec db mysqldump -u root -p ytVideoGen > backup.sql
+
+# Restore database
+docker-compose exec -T db mysql -u root -p ytVideoGen < backup.sql
+```
+
+## 🐛 Troubleshooting
+
+### Common Issues
+
+1. **Port Already in Use**
+ ```bash
+ # Check what's using the port
+ netstat -tulpn | grep :8000
+
+ # Kill process or change port in docker-compose.yml
+ ```
+
+2. **Database Connection Failed**
+ ```bash
+ # Wait longer for database to initialize
+ sleep 60
+
+ # Check database logs
+ docker-compose logs db
+ ```
+
+3. **Permission Denied**
+ ```bash
+ # Fix permissions
+ docker-compose exec app chmod -R 777 storage bootstrap/cache
+ ```
+
+4. **n8n Workflows Not Working**
+ - Check API keys are properly configured
+ - Verify webhook URLs are accessible
+ - Check n8n logs: `docker-compose logs n8n`
+
+### Reset Everything
+```bash
+# Stop and remove everything
+docker-compose down -v
+docker system prune -a
+
+# Start fresh
+./start.bat # or ./start.sh
+```
+
+## 📊 Monitoring
+
+### Health Checks
+```bash
+# Check all containers status
+docker-compose ps
+
+# Check resource usage
+docker stats
+
+# Test application
+curl http://localhost:8000
+curl http://localhost:5678
+```
+
+### Logs
+```bash
+# View all logs
+docker-compose logs -f
+
+# View specific service logs
+docker-compose logs -f app
+docker-compose logs -f n8n
+docker-compose logs -f queue
+```
+
+## 🔄 Updates
+
+### Update Application
+```bash
+# Pull latest changes
+git pull
+
+# Rebuild containers
+docker-compose build --no-cache
+
+# Restart services
+docker-compose up -d
+```
+
+### Update Dependencies
+```bash
+# Update PHP dependencies
+docker-compose exec app composer update
+
+# Update Node dependencies
+docker-compose exec app npm update
+```
+
+## 🚀 Production Deployment
+
+For production deployment:
+
+1. Update `.env.docker` with production values
+2. Set `APP_ENV=production` and `APP_DEBUG=false`
+3. Configure proper domain names
+4. Set up SSL certificates
+5. Use external database and Redis services
+6. Configure proper backup strategies
+7. Set up monitoring and alerting
+
+## 📋 Testing the Complete Workflow
+
+1. **Access Application**: http://localhost:8000
+2. **Login**: Use demo login or Google OAuth
+3. **Create Video**: Go to dashboard, create new video
+4. **Test n8n**: Check http://localhost:5678 for workflow execution
+5. **Monitor Progress**: Watch logs and database for updates
+6. **Verify Output**: Check generated videos and YouTube uploads
+
+## 💡 Performance Optimization
+
+### Resource Allocation
+- Increase memory limits in `docker-compose.yml`
+- Add more queue workers for parallel processing
+- Use SSD storage for better I/O performance
+
+### Scaling
+- Use Docker Swarm or Kubernetes for horizontal scaling
+- Separate video processing to dedicated servers
+- Implement CDN for video storage and delivery
+
+## 🆘 Support
+
+If you encounter issues:
+
+1. Check logs: `docker-compose logs -f`
+2. Verify all services are running: `docker-compose ps`
+3. Test individual components
+4. Check API keys and credentials
+5. Review n8n workflow configurations
+
+---
+
+**Happy Video Generating! 🎬**
diff --git a/Dockerfile b/Dockerfile
index 5b4e6cc..ac612c6 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -1,4 +1,4 @@
-FROM php:8.2-fpm
+FROM php:8.2
# Install system dependencies
RUN apt-get update && apt-get install -y \
@@ -13,7 +13,12 @@ RUN apt-get update && apt-get install -y \
npm \
ffmpeg \
python3 \
- python3-pip
+ python3-pip \
+ && rm -rf /var/lib/apt/lists/*
+
+# Install Python dependencies for video processing
+COPY scripts/requirements.txt /tmp/requirements.txt
+RUN pip3 install -r /tmp/requirements.txt
# Clear cache
RUN apt-get clean && rm -rf /var/lib/apt/lists/*
@@ -31,7 +36,12 @@ RUN pip3 install gTTS pydub
WORKDIR /var/www/html
# Copy application files
-COPY . .
+# Copy application code
+COPY . /var/www
+
+# Copy Python scripts to accessible location
+COPY scripts/ /app/scripts/
+RUN chmod +x /app/scripts/*.py
# Install PHP dependencies
RUN composer install --no-dev --optimize-autoloader
diff --git a/FREE_SERVICES_GUIDE.md b/FREE_SERVICES_GUIDE.md
new file mode 100644
index 0000000..0dd8e6a
--- /dev/null
+++ b/FREE_SERVICES_GUIDE.md
@@ -0,0 +1,175 @@
+# YouTube Video Generator - Free Services Setup Guide
+
+## Overview
+This YouTube Video Generator SaaS uses completely **FREE** services to create videos automatically:
+
+- **Google Gemini**: Free AI script generation (1M tokens/day)
+- **Pixabay**: Free stock videos (5000 requests/hour)
+- **Unsplash**: Free stock images (50 requests/hour for demo)
+- **gTTS**: Free Google Text-to-Speech (unlimited)
+- **FFmpeg**: Free video processing (open source)
+
+## Quick Start with Docker
+
+### 1. Get Free API Keys
+
+**Gemini API (Free):**
+- Visit: https://makersuite.google.com/app/apikey
+- Sign in with Google account
+- Click "Create API key"
+- Copy the key
+
+**Pixabay API (Free):**
+- Visit: https://pixabay.com/api/docs/
+- Create account and verify email
+- Copy your API key from account settings
+
+**Unsplash API (Free for Development):**
+- Visit: https://unsplash.com/developers
+- Create developer account
+- Create new app
+- Copy Access Key
+
+### 2. Configure Environment
+
+Create `.env` file in project root:
+```bash
+# Database
+DB_CONNECTION=mysql
+DB_HOST=db
+DB_PORT=3306
+DB_DATABASE=youtube_generator
+DB_USERNAME=laravel_user
+DB_PASSWORD=secure_password
+
+# Laravel
+APP_NAME="YouTube Generator"
+APP_ENV=local
+APP_KEY=base64:YOUR_APP_KEY_HERE
+APP_DEBUG=true
+APP_URL=http://localhost:8000
+
+# API Keys (FREE)
+GEMINI_API_KEY=your_gemini_api_key_here
+PIXABAY_API_KEY=your_pixabay_api_key_here
+UNSPLASH_ACCESS_KEY=your_unsplash_access_key_here
+
+# Redis
+REDIS_HOST=redis
+REDIS_PASSWORD=null
+REDIS_PORT=6379
+
+# N8n
+N8N_BASIC_AUTH_ACTIVE=true
+N8N_BASIC_AUTH_USER=admin
+N8N_BASIC_AUTH_PASSWORD=password123
+```
+
+### 3. Update N8n Workflow Keys
+
+Edit `docker/n8n/workflows/video-generation.json` and replace:
+```javascript
+gemini_api_key: "YOUR_GEMINI_API_KEY"
+pixabay_api_key: "YOUR_PIXABAY_API_KEY"
+unsplash_access_key: "YOUR_UNSPLASH_ACCESS_KEY"
+```
+
+### 4. Start the Application
+
+```bash
+# Build and start all services
+docker-compose up --build
+
+# In separate terminal - run database migrations
+docker-compose exec app php artisan migrate
+
+# Generate application key
+docker-compose exec app php artisan key:generate
+```
+
+### 5. Access the Application
+
+- **Main App**: http://localhost:8000
+- **N8n Workflows**: http://localhost:5678 (admin/password123)
+
+## How It Works
+
+### Free Video Generation Process:
+
+1. **Script Generation**: Gemini AI creates engaging YouTube scripts
+2. **Media Collection**: Pixabay provides background videos, Unsplash provides images
+3. **Voice Creation**: gTTS converts script to natural speech audio
+4. **Video Assembly**: FFmpeg combines media, audio, and effects
+5. **YouTube Upload**: Automated upload via Google API
+
+### Cost Breakdown (FREE for Development):
+
+- **Gemini**: 1 million tokens/day free (≈500 video scripts)
+- **Pixabay**: 5000 API requests/hour free (≈200 videos/hour)
+- **Unsplash**: 50 requests/hour free (≈50 image sets/hour)
+- **gTTS**: Unlimited free text-to-speech
+- **FFmpeg**: Open source, completely free
+- **Hosting**: Your own Docker containers
+
+## Production Scaling
+
+For production with millions of videos:
+
+1. **Gemini Pro**: $0.50 per 1M tokens (very affordable)
+2. **Pixabay Pro**: $9.99/month for unlimited requests
+3. **Unsplash+**: $10/month for 10,000 requests
+4. **ElevenLabs**: Premium TTS if needed
+5. **Cloud Storage**: AWS S3 for video storage
+
+## API Endpoints
+
+The Laravel application provides these API endpoints for n8n:
+
+- `POST /api/videos/{id}/status` - Update video generation status
+- `POST /api/videos/{id}/youtube` - Update YouTube upload status
+- `GET /api/autopilot/topics` - Get next topic for autopilot
+- `POST /api/autopilot/complete` - Mark autopilot video complete
+
+## Demo Features
+
+- **Demo Login**: Skip OAuth setup during development
+- **Manual Topics**: Test video generation with custom topics
+- **Progress Tracking**: Real-time status updates
+- **Autopilot Mode**: Fully automated video creation
+
+## Free Service Limits
+
+During development (1 month period):
+
+- **Videos per day**: ~200-500 depending on complexity
+- **API costs**: $0 (all free tiers)
+- **Storage**: Local Docker volumes (free)
+- **Bandwidth**: Your server only
+
+Perfect for:
+- MVP development
+- Testing and validation
+- Demo presentations
+- Small-scale content creation
+
+## Troubleshooting
+
+**If videos fail to generate:**
+1. Check API keys in n8n workflow
+2. Verify Python dependencies: `docker-compose exec app pip3 list`
+3. Check n8n logs: `docker-compose logs n8n`
+4. Test FFmpeg: `docker-compose exec app ffmpeg -version`
+
+**If workflows don't trigger:**
+1. Import workflows manually in n8n interface
+2. Activate workflows in n8n
+3. Check webhook URLs match Laravel routes
+
+## Next Steps
+
+1. Test demo login and video generation
+2. Configure your actual API keys
+3. Import and activate n8n workflows
+4. Generate your first automated video!
+
+The system is designed to be **completely free** for development and testing, making it perfect for building your MVP before scaling to production.
diff --git a/app/Http/Controllers/Api/N8nController.php b/app/Http/Controllers/Api/N8nController.php
new file mode 100644
index 0000000..7d65745
--- /dev/null
+++ b/app/Http/Controllers/Api/N8nController.php
@@ -0,0 +1,341 @@
+<?php
+
+namespace App\Http\Controllers\Api;
+
+use App\Http\Controllers\Controller;
+use App\Models\Video;
+use App\Models\User;
+use Illuminate\Http\Request;
+use Illuminate\Http\JsonResponse;
+use Illuminate\Support\Facades\Http;
+use Illuminate\Support\Facades\Log;
+
+class N8nController extends Controller
+{
+ /**
+ * Generate script using Gemini AI
+ */
+ public function generateScript(Request $request, $videoId): JsonResponse
+ {
+ try {
+ $video = Video::findOrFail($videoId);
+
+ $prompt = "Create an engaging YouTube script about: {$request->topic}. Target duration: {$request->duration} minutes. Include: 1) Catchy intro hook, 2) Clear structure with 3-5 main points, 3) Engaging examples and stories, 4) Strong conclusion with call-to-action. Write in conversational, enthusiastic tone. Make it informative yet entertaining.";
+
+ $response = Http::timeout(30)->post('https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent', [
+ 'contents' => [
+ [
+ 'parts' => [
+ ['text' => $prompt]
+ ]
+ ]
+ ]
+ ], [
+ 'key' => config('services.gemini.api_key')
+ ]);
+
+ if ($response->successful()) {
+ $script = $response->json()['candidates'][0]['content']['parts'][0]['text'];
+
+ $video->update([
+ 'script' => $script,
+ 'status' => 'script_generated'
+ ]);
+
+ return response()->json([
+ 'success' => true,
+ 'script' => $script,
+ 'video_id' => $videoId
+ ]);
+ }
+
+ throw new \Exception('Failed to generate script');
+
+ } catch (\Exception $e) {
+ Log::error('Script generation failed', ['error' => $e->getMessage(), 'video_id' => $videoId]);
+
+ return response()->json([
+ 'success' => false,
+ 'message' => 'Failed to generate script',
+ 'error' => $e->getMessage()
+ ], 500);
+ }
+ }
+
+ /**
+ * Fetch media from Pixabay and Unsplash
+ */
+ public function fetchMedia(Request $request, $videoId): JsonResponse
+ {
+ try {
+ $video = Video::findOrFail($videoId);
+ $topic = $request->topic;
+ $mediaList = [];
+
+ // Fetch videos from Pixabay
+ $pixabayResponse = Http::get('https://pixabay.com/api/videos/', [
+ 'key' => config('services.pixabay.api_key'),
+ 'q' => str_replace(' ', '+', $topic),
+ 'video_type' => 'film',
+ 'category' => 'backgrounds',
+ 'min_duration' => 20,
+ 'per_page' => 8,
+ 'safesearch' => 'true'
+ ]);
+
+ if ($pixabayResponse->successful()) {
+ $videos = $pixabayResponse->json()['hits'] ?? [];
+ foreach (array_slice($videos, 0, 3) as $video) {
+ $videoUrl = $video['videos']['medium']['url'] ?? $video['videos']['small']['url'] ?? null;
+ if ($videoUrl) {
+ $mediaList[] = [
+ 'type' => 'video',
+ 'url' => $videoUrl,
+ 'duration' => $video['duration'] ?? 30
+ ];
+ }
+ }
+ }
+
+ // Fetch images from Unsplash
+ $unsplashResponse = Http::withHeaders([
+ 'Authorization' => 'Client-ID ' . config('services.unsplash.access_key')
+ ])->get('https://api.unsplash.com/search/photos', [
+ 'query' => $topic,
+ 'per_page' => 10,
+ 'orientation' => 'landscape'
+ ]);
+
+ if ($unsplashResponse->successful()) {
+ $images = $unsplashResponse->json()['results'] ?? [];
+ foreach (array_slice($images, 0, 5) as $image) {
+ if ($image['urls']['regular']) {
+ $mediaList[] = [
+ 'type' => 'image',
+ 'url' => $image['urls']['regular']
+ ];
+ }
+ }
+ }
+
+ $video->update([
+ 'status' => 'media_fetched'
+ ]);
+
+ return response()->json([
+ 'success' => true,
+ 'media_list' => $mediaList,
+ 'video_id' => $videoId
+ ]);
+
+ } catch (\Exception $e) {
+ Log::error('Media fetch failed', ['error' => $e->getMessage(), 'video_id' => $videoId]);
+
+ return response()->json([
+ 'success' => false,
+ 'message' => 'Failed to fetch media',
+ 'error' => $e->getMessage()
+ ], 500);
+ }
+ }
+
+ /**
+ * Upload video to YouTube using user's OAuth token
+ */
+ public function uploadToYoutube(Request $request, $videoId): JsonResponse
+ {
+ try {
+ $video = Video::with('user')->findOrFail($videoId);
+
+ // Check if user has YouTube OAuth token
+ if (!$video->user->youtube_access_token) {
+ return response()->json([
+ 'success' => false,
+ 'message' => 'User has not connected YouTube account'
+ ], 400);
+ }
+
+ // Refresh token if needed
+ if ($video->user->youtube_token_expires_at && $video->user->youtube_token_expires_at->isPast()) {
+ $this->refreshYouTubeToken($video->user);
+ }
+
+ // Upload to YouTube
+ $youtubeResponse = Http::withHeaders([
+ 'Authorization' => 'Bearer ' . $video->user->youtube_access_token,
+ 'Content-Type' => 'application/json'
+ ])->post('https://www.googleapis.com/upload/youtube/v3/videos?part=snippet,status&uploadType=resumable', [
+ 'snippet' => [
+ 'title' => $video->title ?: ($request->topic . ' - AI Generated Video'),
+ 'description' => $video->description ?: "This video was automatically generated using AI.\n\nScript generated by Google Gemini AI\nMedia from Pixabay and Unsplash\nVoiceover by Google Text-to-Speech\n\n#AI #{$request->topic} #AutoGenerated",
+ 'tags' => explode(',', $video->tags ?: 'AI,Automated,Technology'),
+ 'categoryId' => '28'
+ ],
+ 'status' => [
+ 'privacyStatus' => 'public'
+ ]
+ ]);
+
+ if ($youtubeResponse->successful()) {
+ $youtubeVideoId = $youtubeResponse->json()['id'];
+ $youtubeUrl = "https://www.youtube.com/watch?v={$youtubeVideoId}";
+
+ $video->update([
+ 'youtube_video_id' => $youtubeVideoId,
+ 'youtube_url' => $youtubeUrl,
+ 'status' => 'uploaded'
+ ]);
+
+ return response()->json([
+ 'success' => true,
+ 'youtube_video_id' => $youtubeVideoId,
+ 'youtube_url' => $youtubeUrl
+ ]);
+ }
+
+ throw new \Exception('YouTube upload failed');
+
+ } catch (\Exception $e) {
+ Log::error('YouTube upload failed', ['error' => $e->getMessage(), 'video_id' => $videoId]);
+
+ return response()->json([
+ 'success' => false,
+ 'message' => 'Failed to upload to YouTube',
+ 'error' => $e->getMessage()
+ ], 500);
+ }
+ }
+
+ /**
+ * Refresh YouTube OAuth token
+ */
+ private function refreshYouTubeToken(User $user): void
+ {
+ $response = Http::post('https://oauth2.googleapis.com/token', [
+ 'client_id' => config('services.google.client_id'),
+ 'client_secret' => config('services.google.client_secret'),
+ 'refresh_token' => $user->youtube_refresh_token,
+ 'grant_type' => 'refresh_token'
+ ]);
+
+ if ($response->successful()) {
+ $data = $response->json();
+ $user->update([
+ 'youtube_access_token' => $data['access_token'],
+ 'youtube_token_expires_at' => now()->addSeconds($data['expires_in'])
+ ]);
+ }
+ }
+ /**
+ * Get video details for n8n workflow
+ */
+ public function getVideoDetails(Request $request, $videoId): JsonResponse
+ {
+ $video = Video::with('user')->findOrFail($videoId);
+
+ return response()->json([
+ 'id' => $video->id,
+ 'title' => $video->title,
+ 'description' => $video->description,
+ 'tags' => explode(',', $video->tags ?? ''),
+ 'script' => $video->script,
+ 'status' => $video->status,
+ 'user_id' => $video->user_id,
+ 'api_token' => $video->user->createToken('n8n-api')->plainTextToken
+ ]);
+ }
+
+ /**
+ * Update video status from n8n
+ */
+ public function updateVideoStatus(Request $request, $videoId): JsonResponse
+ {
+ $video = Video::findOrFail($videoId);
+
+ $video->update([
+ 'status' => $request->status,
+ 'file_path' => $request->file_path,
+ 'script' => $request->script ?? $video->script,
+ ]);
+
+ return response()->json([
+ 'success' => true,
+ 'message' => 'Video status updated',
+ 'video' => $video
+ ]);
+ }
+
+ /**
+ * Mark video as uploaded to YouTube
+ */
+ public function markAsUploaded(Request $request, $videoId): JsonResponse
+ {
+ $video = Video::findOrFail($videoId);
+
+ $video->update([
+ 'status' => 'uploaded',
+ 'youtube_video_id' => $request->youtube_video_id,
+ 'youtube_url' => $request->youtube_url,
+ 'uploaded_at' => now()
+ ]);
+
+ return response()->json([
+ 'success' => true,
+ 'message' => 'Video marked as uploaded',
+ 'video' => $video
+ ]);
+ }
+
+ /**
+ * Get scheduled topics for autopilot
+ */
+ public function getScheduledTopics(Request $request): JsonResponse
+ {
+ // Get videos that are scheduled for today and haven't been processed
+ $scheduledVideos = Video::where('status', 'scheduled')
+ ->whereDate('scheduled_at', today())
+ ->with('user')
+ ->get();
+
+ $topics = $scheduledVideos->map(function ($video) {
+ return [
+ 'video_id' => $video->id,
+ 'topic' => $video->title,
+ 'duration' => $video->duration ?? 5,
+ 'api_token' => $video->user->createToken('autopilot-api')->plainTextToken,
+ 'youtube_access_token' => $video->user->google_access_token,
+ 'youtube_api_key' => config('services.google.api_key')
+ ];
+ });
+
+ return response()->json($topics);
+ }
+
+ /**
+ * Create a new video request from n8n
+ */
+ public function createVideoRequest(Request $request): JsonResponse
+ {
+ $request->validate([
+ 'user_id' => 'required|exists:users,id',
+ 'title' => 'required|string|max:255',
+ 'description' => 'nullable|string',
+ 'duration' => 'nullable|integer|min:1|max:60'
+ ]);
+
+ $video = Video::create([
+ 'user_id' => $request->user_id,
+ 'title' => $request->title,
+ 'description' => $request->description,
+ 'duration' => $request->duration ?? 5,
+ 'status' => 'processing',
+ 'created_at' => now()
+ ]);
+
+ return response()->json([
+ 'success' => true,
+ 'video_id' => $video->id,
+ 'message' => 'Video request created'
+ ], 201);
+ }
+}
diff --git a/app/Models/User.php b/app/Models/User.php
index 3d03f5f..ce31013 100644
--- a/app/Models/User.php
+++ b/app/Models/User.php
@@ -28,6 +28,9 @@ class User extends Authenticatable
'google_token_expires_at',
'google_scopes',
'avatar_url',
+ 'youtube_access_token',
+ 'youtube_refresh_token',
+ 'youtube_token_expires_at',
'subscription_plan',
'monthly_video_quota',
'videos_generated_this_month',
diff --git a/config/services.php b/config/services.php
index e95e4c0..2f52417 100644
--- a/config/services.php
+++ b/config/services.php
@@ -41,4 +41,17 @@ return [
'redirect' => env('GOOGLE_REDIRECT_URI'),
],
+ // Free AI/Media Service APIs
+ 'gemini' => [
+ 'api_key' => env('GEMINI_API_KEY'),
+ ],
+
+ 'pixabay' => [
+ 'api_key' => env('PIXABAY_API_KEY'),
+ ],
+
+ 'unsplash' => [
+ 'access_key' => env('UNSPLASH_ACCESS_KEY'),
+ ],
+
];
diff --git a/database/migrations/2024_01_02_000000_add_youtube_oauth_to_users_table.php b/database/migrations/2024_01_02_000000_add_youtube_oauth_to_users_table.php
new file mode 100644
index 0000000..2e307b4
--- /dev/null
+++ b/database/migrations/2024_01_02_000000_add_youtube_oauth_to_users_table.php
@@ -0,0 +1,34 @@
+<?php
+
+use Illuminate\Database\Migrations\Migration;
+use Illuminate\Database\Schema\Blueprint;
+use Illuminate\Support\Facades\Schema;
+
+return new class extends Migration
+{
+ /**
+ * Run the migrations.
+ */
+ public function up(): void
+ {
+ Schema::table('users', function (Blueprint $table) {
+ $table->text('youtube_access_token')->nullable()->after('google_scopes');
+ $table->text('youtube_refresh_token')->nullable()->after('youtube_access_token');
+ $table->timestamp('youtube_token_expires_at')->nullable()->after('youtube_refresh_token');
+ });
+ }
+
+ /**
+ * Reverse the migrations.
+ */
+ public function down(): void
+ {
+ Schema::table('users', function (Blueprint $table) {
+ $table->dropColumn([
+ 'youtube_access_token',
+ 'youtube_refresh_token',
+ 'youtube_token_expires_at'
+ ]);
+ });
+ }
+};
diff --git a/docker-compose.yml b/docker-compose.yml
index 2dabe40..8722c74 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -1,84 +1,146 @@
-version: '3.8'
-
services:
+ # Laravel Application
app:
build:
context: .
dockerfile: Dockerfile
- ports:
- - "8000:8000"
+ container_name: youtube_generator_app
+ restart: unless-stopped
+ working_dir: /var/www
volumes:
- - .:/var/www/html
- - ./storage:/var/www/html/storage
+ - ./:/var/www
+ - ./docker/php/local.ini:/usr/local/etc/php/conf.d/local.ini
+ networks:
+ - youtube_generator
+ depends_on:
+ - db
+ - redis
environment:
- APP_ENV=local
- APP_DEBUG=true
- - DB_HOST=mysql
- - DB_DATABASE=youtube_generator
+ - DB_CONNECTION=mysql
+ - DB_HOST=db
+ - DB_PORT=3306
+ - DB_DATABASE=ytVideoGen
- DB_USERNAME=root
- DB_PASSWORD=secret
- REDIS_HOST=redis
- depends_on:
- - mysql
- - redis
+ - REDIS_PASSWORD=null
+ - REDIS_PORT=6379
+ - QUEUE_CONNECTION=redis
+
+ # Nginx Web Server
+ webserver:
+ image: nginx:alpine
+ container_name: youtube_generator_webserver
+ restart: unless-stopped
+ ports:
+ - "8000:80"
+ volumes:
+ - ./:/var/www
+ - ./docker/nginx:/etc/nginx/conf.d
networks:
- - youtube-generator
+ - youtube_generator
+ depends_on:
+ - app
- mysql:
+ # MySQL Database
+ db:
image: mysql:8.0
+ container_name: youtube_generator_db
+ restart: unless-stopped
ports:
- "3306:3306"
environment:
- - MYSQL_ROOT_PASSWORD=secret
- - MYSQL_DATABASE=youtube_generator
+ MYSQL_DATABASE: ytVideoGen
+ MYSQL_ROOT_PASSWORD: secret
+ MYSQL_PASSWORD: secret
+ MYSQL_USER: sail
+ SERVICE_TAGS: dev
+ SERVICE_NAME: mysql
volumes:
- - mysql_data:/var/lib/mysql
+ - dbdata:/var/lib/mysql
+ - ./docker/mysql/init:/docker-entrypoint-initdb.d
networks:
- - youtube-generator
+ - youtube_generator
+ # Redis for Caching and Queues
redis:
- image: redis:7-alpine
+ image: redis:7.0-alpine
+ container_name: youtube_generator_redis
+ restart: unless-stopped
ports:
- "6379:6379"
networks:
- - youtube-generator
+ - youtube_generator
+
+ # Laravel Queue Worker
+ queue:
+ build:
+ context: .
+ dockerfile: Dockerfile
+ container_name: youtube_generator_queue
+ restart: unless-stopped
+ working_dir: /var/www
+ volumes:
+ - ./:/var/www
+ networks:
+ - youtube_generator
+ depends_on:
+ - db
+ - redis
+ command: php artisan queue:work --sleep=3 --tries=3 --max-time=3600
+ environment:
+ - APP_ENV=local
+ - DB_CONNECTION=mysql
+ - DB_HOST=db
+ - DB_PORT=3306
+ - DB_DATABASE=ytVideoGen
+ - DB_USERNAME=root
+ - DB_PASSWORD=secret
+ - REDIS_HOST=redis
+ - QUEUE_CONNECTION=redis
+ # n8n Automation Platform
n8n:
image: n8nio/n8n:latest
+ container_name: youtube_generator_n8n
+ restart: unless-stopped
ports:
- "5678:5678"
environment:
- N8N_BASIC_AUTH_ACTIVE=true
- N8N_BASIC_AUTH_USER=admin
- - N8N_BASIC_AUTH_PASSWORD=admin123
- - WEBHOOK_URL=http://localhost:5678
- - N8N_PROTOCOL=http
+ - N8N_BASIC_AUTH_PASSWORD=n8npassword
- N8N_HOST=localhost
- N8N_PORT=5678
+ - N8N_PROTOCOL=http
+ - WEBHOOK_URL=http://localhost:5678/
+ - GENERIC_TIMEZONE=UTC
volumes:
- n8n_data:/home/node/.n8n
- - ./n8n/workflows:/home/node/.n8n/workflows
+ - ./docker/n8n/workflows:/home/node/.n8n/workflows
networks:
- - youtube-generator
-
- # Optional: phpMyAdmin for database management
- phpmyadmin:
- image: phpmyadmin/phpmyadmin
- ports:
- - "8080:80"
- environment:
- - PMA_HOST=mysql
- - PMA_USER=root
- - PMA_PASSWORD=secret
+ - youtube_generator
depends_on:
- - mysql
- networks:
- - youtube-generator
+ - db
+ - redis
-volumes:
- mysql_data:
- n8n_data:
+ # FFmpeg for Video Processing
+ ffmpeg:
+ image: jrottenberg/ffmpeg:4.4-alpine
+ container_name: youtube_generator_ffmpeg
+ volumes:
+ - ./storage/app/videos:/videos
+ networks:
+ - youtube_generator
networks:
- youtube-generator:
+ youtube_generator:
driver: bridge
+
+volumes:
+ dbdata:
+ driver: local
+ n8n_data:
+ driver: local
diff --git a/docker/n8n/workflows/autopilot.json b/docker/n8n/workflows/autopilot.json
new file mode 100644
index 0000000..196f39c
--- /dev/null
+++ b/docker/n8n/workflows/autopilot.json
@@ -0,0 +1,229 @@
+{
+ "name": "Autopilot Video Generation",
+ "nodes": [
+ {
+ "parameters": {
+ "rule": {
+ "interval": [
+ {
+ "field": "hours",
+ "hoursInterval": 24
+ }
+ ]
+ }
+ },
+ "id": "schedule-trigger",
+ "name": "Daily Schedule",
+ "type": "n8n-nodes-base.cron",
+ "typeVersion": 1,
+ "position": [
+ 240,
+ 300
+ ]
+ },
+ {
+ "parameters": {
+ "url": "http://app:8000/api/autopilot/topics",
+ "sendHeaders": true,
+ "headerParameters": {
+ "parameters": [
+ {
+ "name": "Authorization",
+ "value": "Bearer autopilot-api-key"
+ }
+ ]
+ }
+ },
+ "id": "get-scheduled-topics",
+ "name": "Get Scheduled Topics",
+ "type": "n8n-nodes-base.httpRequest",
+ "typeVersion": 4.1,
+ "position": [
+ 460,
+ 300
+ ]
+ },
+ {
+ "parameters": {
+ "batchSize": 1,
+ "options": {}
+ },
+ "id": "process-each-topic",
+ "name": "Process Each Topic",
+ "type": "n8n-nodes-base.splitInBatches",
+ "typeVersion": 3,
+ "position": [
+ 680,
+ 300
+ ]
+ },
+ {
+ "parameters": {
+ "url": "http://localhost:5678/webhook/video-generation",
+ "sendHeaders": true,
+ "headerParameters": {
+ "parameters": [
+ {
+ "name": "Content-Type",
+ "value": "application/json"
+ }
+ ]
+ },
+ "sendBody": true,
+ "bodyParameters": {
+ "parameters": [
+ {
+ "name": "topic",
+ "value": "={{ $json.topic }}"
+ },
+ {
+ "name": "duration",
+ "value": "={{ $json.duration }}"
+ },
+ {
+ "name": "video_id",
+ "value": "={{ $json.video_id }}"
+ },
+ {
+ "name": "api_token",
+ "value": "={{ $json.api_token }}"
+ },
+ {
+ "name": "voice_id",
+ "value": "pNInz6obpgDQGcFmaJgB"
+ }
+ ]
+ }
+ },
+ "id": "trigger-video-generation",
+ "name": "Trigger Video Generation",
+ "type": "n8n-nodes-base.httpRequest",
+ "typeVersion": 4.1,
+ "position": [
+ 900,
+ 300
+ ]
+ },
+ {
+ "parameters": {
+ "amount": 300,
+ "unit": "seconds"
+ },
+ "id": "wait-for-processing",
+ "name": "Wait for Processing",
+ "type": "n8n-nodes-base.wait",
+ "typeVersion": 1,
+ "position": [
+ 1120,
+ 300
+ ]
+ },
+ {
+ "parameters": {
+ "url": "http://localhost:5678/webhook/youtube-upload",
+ "sendHeaders": true,
+ "headerParameters": {
+ "parameters": [
+ {
+ "name": "Content-Type",
+ "value": "application/json"
+ }
+ ]
+ },
+ "sendBody": true,
+ "bodyParameters": {
+ "parameters": [
+ {
+ "name": "video_id",
+ "value": "={{ $json.video_id }}"
+ },
+ {
+ "name": "api_token",
+ "value": "={{ $json.api_token }}"
+ },
+ {
+ "name": "youtube_access_token",
+ "value": "={{ $json.youtube_access_token }}"
+ },
+ {
+ "name": "youtube_api_key",
+ "value": "={{ $json.youtube_api_key }}"
+ }
+ ]
+ }
+ },
+ "id": "trigger-youtube-upload",
+ "name": "Trigger YouTube Upload",
+ "type": "n8n-nodes-base.httpRequest",
+ "typeVersion": 4.1,
+ "position": [
+ 1340,
+ 300
+ ]
+ }
+ ],
+ "connections": {
+ "Daily Schedule": {
+ "main": [
+ [
+ {
+ "node": "Get Scheduled Topics",
+ "type": "main",
+ "index": 0
+ }
+ ]
+ ]
+ },
+ "Get Scheduled Topics": {
+ "main": [
+ [
+ {
+ "node": "Process Each Topic",
+ "type": "main",
+ "index": 0
+ }
+ ]
+ ]
+ },
+ "Process Each Topic": {
+ "main": [
+ [
+ {
+ "node": "Trigger Video Generation",
+ "type": "main",
+ "index": 0
+ }
+ ]
+ ]
+ },
+ "Trigger Video Generation": {
+ "main": [
+ [
+ {
+ "node": "Wait for Processing",
+ "type": "main",
+ "index": 0
+ }
+ ]
+ ]
+ },
+ "Wait for Processing": {
+ "main": [
+ [
+ {
+ "node": "Trigger YouTube Upload",
+ "type": "main",
+ "index": 0
+ }
+ ]
+ ]
+ }
+ },
+ "active": true,
+ "settings": {
+ "timezone": "UTC"
+ },
+ "createdAt": "2025-01-01T00:00:00.000Z",
+ "updatedAt": "2025-01-01T00:00:00.000Z",
+ "id": "3"
+}
diff --git a/docker/n8n/workflows/complete-video-generator.json b/docker/n8n/workflows/complete-video-generator.json
new file mode 100644
index 0000000..9dd4079
--- /dev/null
+++ b/docker/n8n/workflows/complete-video-generator.json
@@ -0,0 +1,685 @@
+{
+ "name": "Complete YouTube Video Generator (All-in-One)",
+ "nodes": [
+ {
+ "parameters": {
+ "httpMethod": "POST",
+ "path": "generate-complete-video",
+ "responseMode": "responseNode",
+ "options": {}
+ },
+ "id": "webhook-start",
+ "name": "Start Video Generation",
+ "type": "n8n-nodes-base.webhook",
+ "typeVersion": 1,
+ "position": [240, 300],
+ "webhookId": "complete-video-webhook"
+ },
+ {
+ "parameters": {
+ "jsCode": "// Setup workflow data - NO API keys stored here!\nreturn {\n json: {\n // Input data from webhook\n topic: $input.item.json.topic || 'Technology Trends',\n duration: $input.item.json.duration || 5,\n user_id: $input.item.json.user_id,\n video_id: $input.item.json.video_id || Date.now().toString(),\n \n // Laravel API token for authentication\n api_token: $input.item.json.api_token || \"default-token\",\n \n // Laravel base URL\n laravel_url: \"http://app:8000\"\n }\n};"
+ },
+ "id": "setup-config",
+ "name": "Setup Configuration",
+ "type": "n8n-nodes-base.code",
+ "typeVersion": 2,
+ "position": [460, 300]
+ },
+ {
+ "parameters": {
+ "url": "http://app:8000/api/videos/{{ $json.video_id }}/status",
+ "sendHeaders": true,
+ "headerParameters": {
+ "parameters": [
+ {
+ "name": "Authorization",
+ "value": "Bearer {{ $json.api_token }}"
+ },
+ {
+ "name": "Content-Type",
+ "value": "application/json"
+ }
+ ]
+ },
+ "sendBody": true,
+ "bodyParameters": {
+ "parameters": [
+ {
+ "name": "status",
+ "value": "generating_script"
+ },
+ {
+ "name": "progress",
+ "value": 10
+ }
+ ]
+ },
+ "options": {
+ "timeout": 10000
+ }
+ },
+ "id": "update-status-script",
+ "name": "Update Status: Generating Script",
+ "type": "n8n-nodes-base.httpRequest",
+ "typeVersion": 4.1,
+ "position": [680, 300]
+ },
+ {
+ "parameters": {
+ "url": "http://app:8000/api/videos/{{ $('Setup Configuration').item.json.video_id }}/generate-script",
+ "sendHeaders": true,
+ "headerParameters": {
+ "parameters": [
+ {
+ "name": "Authorization",
+ "value": "Bearer {{ $('Setup Configuration').item.json.api_token }}"
+ },
+ {
+ "name": "Content-Type",
+ "value": "application/json"
+ }
+ ]
+ },
+ "sendBody": true,
+ "bodyParameters": {
+ "parameters": [
+ {
+ "name": "topic",
+ "value": "{{ $('Setup Configuration').item.json.topic }}"
+ },
+ {
+ "name": "duration",
+ "value": "{{ $('Setup Configuration').item.json.duration }}"
+ },
+ {
+ "name": "user_id",
+ "value": "{{ $('Setup Configuration').item.json.user_id }}"
+ }
+ ]
+ },
+ "options": {
+ "timeout": 30000
+ }
+ },
+ "id": "generate-script",
+ "name": "Generate Script via Laravel",
+ "type": "n8n-nodes-base.httpRequest",
+ "typeVersion": 4.1,
+ "position": [900, 300]
+ },
+ {
+ "parameters": {
+ "url": "http://app:8000/api/videos/{{ $('Setup Configuration').item.json.video_id }}/status",
+ "sendHeaders": true,
+ "headerParameters": {
+ "parameters": [
+ {
+ "name": "Authorization",
+ "value": "Bearer {{ $('Setup Configuration').item.json.api_token }}"
+ },
+ {
+ "name": "Content-Type",
+ "value": "application/json"
+ }
+ ]
+ },
+ "sendBody": true,
+ "bodyParameters": {
+ "parameters": [
+ {
+ "name": "status",
+ "value": "fetching_media"
+ },
+ {
+ "name": "progress",
+ "value": 30
+ },
+ {
+ "name": "script",
+ "value": "{{ $json.script }}"
+ }
+ ]
+ }
+ },
+ "id": "update-status-media",
+ "name": "Update Status: Fetching Media",
+ "type": "n8n-nodes-base.httpRequest",
+ "typeVersion": 4.1,
+ "position": [1120, 300]
+ },
+ {
+ "parameters": {
+ "url": "http://app:8000/api/videos/{{ $('Setup Configuration').item.json.video_id }}/fetch-media",
+ "sendHeaders": true,
+ "headerParameters": {
+ "parameters": [
+ {
+ "name": "Authorization",
+ "value": "Bearer {{ $('Setup Configuration').item.json.api_token }}"
+ },
+ {
+ "name": "Content-Type",
+ "value": "application/json"
+ }
+ ]
+ },
+ "sendBody": true,
+ "bodyParameters": {
+ "parameters": [
+ {
+ "name": "topic",
+ "value": "{{ $('Setup Configuration').item.json.topic }}"
+ },
+ {
+ "name": "user_id",
+ "value": "{{ $('Setup Configuration').item.json.user_id }}"
+ }
+ ]
+ }
+ },
+ "id": "fetch-media",
+ "name": "Fetch Media via Laravel",
+ "type": "n8n-nodes-base.httpRequest",
+ "typeVersion": 4.1,
+ "position": [1340, 300]
+ },
+ {
+ "parameters": {
+ "url": "http://app:8000/api/videos/{{ $('Setup Configuration').item.json.video_id }}/status",
+ "sendHeaders": true,
+ "headerParameters": {
+ "parameters": [
+ {
+ "name": "Authorization",
+ "value": "Bearer {{ $('Setup Configuration').item.json.api_token }}"
+ },
+ {
+ "name": "Content-Type",
+ "value": "application/json"
+ }
+ ]
+ },
+ "sendBody": true,
+ "bodyParameters": {
+ "parameters": [
+ {
+ "name": "status",
+ "value": "creating_voiceover"
+ },
+ {
+ "name": "progress",
+ "value": 50
+ }
+ ]
+ }
+ },
+ "id": "update-status-voice",
+ "name": "Update Status: Creating Voiceover",
+ "type": "n8n-nodes-base.httpRequest",
+ "typeVersion": 4.1,
+ "position": [1560, 300]
+ },
+ {
+ "parameters": {
+ "command": "python3",
+ "parameters": "/app/scripts/gtts_client.py \"{{ $('Generate Script via Laravel').item.json.script }}\" \"/tmp/voiceover_{{ $('Setup Configuration').item.json.video_id }}.mp3\" \"en\" \"false\""
+ },
+ "id": "create-voiceover",
+ "name": "Create Voiceover with gTTS",
+ "type": "n8n-nodes-base.executeCommand",
+ "typeVersion": 1,
+ "position": [1780, 300]
+ },
+ {
+ "parameters": {
+ "url": "http://app:8000/api/videos/{{ $('Setup Configuration').item.json.video_id }}/status",
+ "sendHeaders": true,
+ "headerParameters": {
+ "parameters": [
+ {
+ "name": "Authorization",
+ "value": "Bearer {{ $('Setup Configuration').item.json.api_token }}"
+ },
+ {
+ "name": "Content-Type",
+ "value": "application/json"
+ }
+ ]
+ },
+ "sendBody": true,
+ "bodyParameters": {
+ "parameters": [
+ {
+ "name": "status",
+ "value": "assembling_video"
+ },
+ {
+ "name": "progress",
+ "value": 70
+ }
+ ]
+ }
+ },
+ "id": "update-status-assembly",
+ "name": "Update Status: Assembling Video",
+ "type": "n8n-nodes-base.httpRequest",
+ "typeVersion": 4.1,
+ "position": [2000, 300]
+ },
+ {
+ "parameters": {
+ "jsCode": "// Prepare data for video assembly\nconst videoId = $('Setup Configuration').item.json.video_id;\nconst mediaList = $('Fetch Media via Laravel').item.json.media_list || [];\n\n// Create assembly data\nconst assemblyData = {\n video_id: videoId,\n media_list: mediaList,\n voiceover_path: `/tmp/voiceover_${videoId}.mp3`\n};\n\nreturn {\n json: {\n assembly_data: JSON.stringify(assemblyData),\n video_id: videoId\n }\n};"
+ },
+ "id": "prepare-assembly",
+ "name": "Prepare Video Assembly Data",
+ "type": "n8n-nodes-base.code",
+ "typeVersion": 2,
+ "position": [2220, 300]
+ },
+ {
+ "parameters": {
+ "command": "python3",
+ "parameters": "/app/scripts/create_video.py '{{ $json.assembly_data }}'"
+ },
+ "id": "assemble-video",
+ "name": "Assemble Final Video",
+ "type": "n8n-nodes-base.executeCommand",
+ "typeVersion": 1,
+ "position": [2440, 300]
+ },
+ {
+ "parameters": {
+ "conditions": {
+ "options": {
+ "caseSensitive": true,
+ "leftValue": "",
+ "typeValidation": "strict"
+ },
+ "conditions": [
+ {
+ "leftValue": "={{ $('Setup Configuration').item.json.youtube_access_token }}",
+ "rightValue": "",
+ "operator": {
+ "type": "string",
+ "operation": "notEmpty"
+ }
+ }
+ ],
+ "combinator": "and"
+ },
+ "options": {}
+ },
+ "id": "check-youtube-auth",
+ "name": "Check YouTube Auth",
+ "type": "n8n-nodes-base.if",
+ "typeVersion": 2,
+ "position": [2660, 300]
+ },
+ {
+ "parameters": {
+ "url": "http://app:8000/api/videos/{{ $('Setup Configuration').item.json.video_id }}/status",
+ "sendHeaders": true,
+ "headerParameters": {
+ "parameters": [
+ {
+ "name": "Authorization",
+ "value": "Bearer {{ $('Setup Configuration').item.json.api_token }}"
+ },
+ {
+ "name": "Content-Type",
+ "value": "application/json"
+ }
+ ]
+ },
+ "sendBody": true,
+ "bodyParameters": {
+ "parameters": [
+ {
+ "name": "status",
+ "value": "uploading_youtube"
+ },
+ {
+ "name": "progress",
+ "value": 90
+ }
+ ]
+ }
+ },
+ "id": "update-status-upload",
+ "name": "Update Status: Uploading",
+ "type": "n8n-nodes-base.httpRequest",
+ "typeVersion": 4.1,
+ "position": [2880, 200]
+ },
+ {
+ "parameters": {
+ "url": "https://www.googleapis.com/upload/youtube/v3/videos?part=snippet,status&uploadType=resumable",
+ "sendHeaders": true,
+ "headerParameters": {
+ "parameters": [
+ {
+ "name": "Authorization",
+ "value": "Bearer {{ $('Setup Configuration').item.json.youtube_access_token }}"
+ },
+ {
+ "name": "Content-Type",
+ "value": "application/json"
+ }
+ ]
+ },
+ "sendBody": true,
+ "bodyParameters": {
+ "parameters": [
+ {
+ "name": "snippet",
+ "value": {
+ "title": "{{ $('Setup Configuration').item.json.topic }} - AI Generated Video",
+ "description": "This video was automatically generated using AI.\\n\\nScript generated by Google Gemini AI\\nMedia from Pixabay and Unsplash\\nVoiceover by Google Text-to-Speech\\n\\n#AI #{{ $('Setup Configuration').item.json.topic.replace(' ', '') }} #AutoGenerated",
+ "tags": ["AI", "{{ $('Setup Configuration').item.json.topic }}", "Automated", "Technology"],
+ "categoryId": "28"
+ }
+ },
+ {
+ "name": "status",
+ "value": {
+ "privacyStatus": "public"
+ }
+ }
+ ]
+ }
+ },
+ "id": "upload-youtube",
+ "name": "Upload to YouTube",
+ "type": "n8n-nodes-base.httpRequest",
+ "typeVersion": 4.1,
+ "position": [3100, 200]
+ },
+ {
+ "parameters": {
+ "url": "http://app:8000/api/videos/{{ $('Setup Configuration').item.json.video_id }}/youtube-uploaded",
+ "sendHeaders": true,
+ "headerParameters": {
+ "parameters": [
+ {
+ "name": "Authorization",
+ "value": "Bearer {{ $('Setup Configuration').item.json.api_token }}"
+ },
+ {
+ "name": "Content-Type",
+ "value": "application/json"
+ }
+ ]
+ },
+ "sendBody": true,
+ "bodyParameters": {
+ "parameters": [
+ {
+ "name": "youtube_video_id",
+ "value": "={{ $json.id }}"
+ },
+ {
+ "name": "youtube_url",
+ "value": "=https://www.youtube.com/watch?v={{ $json.id }}"
+ },
+ {
+ "name": "status",
+ "value": "completed"
+ },
+ {
+ "name": "progress",
+ "value": 100
+ }
+ ]
+ }
+ },
+ "id": "update-youtube-success",
+ "name": "Update YouTube Success",
+ "type": "n8n-nodes-base.httpRequest",
+ "typeVersion": 4.1,
+ "position": [3320, 200]
+ },
+ {
+ "parameters": {
+ "url": "http://app:8000/api/videos/{{ $('Setup Configuration').item.json.video_id }}/status",
+ "sendHeaders": true,
+ "headerParameters": {
+ "parameters": [
+ {
+ "name": "Authorization",
+ "value": "Bearer {{ $('Setup Configuration').item.json.api_token }}"
+ },
+ {
+ "name": "Content-Type",
+ "value": "application/json"
+ }
+ ]
+ },
+ "sendBody": true,
+ "bodyParameters": {
+ "parameters": [
+ {
+ "name": "status",
+ "value": "completed"
+ },
+ {
+ "name": "progress",
+ "value": 100
+ },
+ {
+ "name": "file_path",
+ "value": "/tmp/final_video_{{ $('Setup Configuration').item.json.video_id }}.mp4"
+ }
+ ]
+ }
+ },
+ "id": "update-completed",
+ "name": "Update Status: Completed",
+ "type": "n8n-nodes-base.httpRequest",
+ "typeVersion": 4.1,
+ "position": [2880, 400]
+ },
+ {
+ "parameters": {
+ "respondWith": "json",
+ "responseBody": "={{ \n $('Check YouTube Auth').item.json && $('Upload to YouTube') ? \n {\n \"success\": true,\n \"message\": \"Video generated and uploaded to YouTube successfully!\",\n \"video_id\": $('Setup Configuration').item.json.video_id,\n \"youtube_url\": \"https://www.youtube.com/watch?v=\" + $('Upload to YouTube').item.json.id,\n \"local_path\": \"/tmp/final_video_\" + $('Setup Configuration').item.json.video_id + \".mp4\"\n } : \n {\n \"success\": true,\n \"message\": \"Video generated successfully! (No YouTube upload - missing auth)\",\n \"video_id\": $('Setup Configuration').item.json.video_id,\n \"local_path\": \"/tmp/final_video_\" + $('Setup Configuration').item.json.video_id + \".mp4\",\n \"note\": \"Provide youtube_access_token to enable YouTube upload\"\n }\n}}"
+ },
+ "id": "final-response",
+ "name": "Final Response",
+ "type": "n8n-nodes-base.respondToWebhook",
+ "typeVersion": 1,
+ "position": [3540, 300]
+ }
+ ],
+ "connections": {
+ "Start Video Generation": {
+ "main": [
+ [
+ {
+ "node": "Setup Configuration",
+ "type": "main",
+ "index": 0
+ }
+ ]
+ ]
+ },
+ "Setup Configuration": {
+ "main": [
+ [
+ {
+ "node": "Update Status: Generating Script",
+ "type": "main",
+ "index": 0
+ }
+ ]
+ ]
+ },
+ "Update Status: Generating Script": {
+ "main": [
+ [
+ {
+ "node": "Generate Script via Laravel",
+ "type": "main",
+ "index": 0
+ }
+ ]
+ ]
+ },
+ "Generate Script via Laravel": {
+ "main": [
+ [
+ {
+ "node": "Update Status: Fetching Media",
+ "type": "main",
+ "index": 0
+ }
+ ]
+ ]
+ },
+ "Update Status: Fetching Media": {
+ "main": [
+ [
+ {
+ "node": "Fetch Media via Laravel",
+ "type": "main",
+ "index": 0
+ }
+ ]
+ ]
+ },
+ "Fetch Media via Laravel": {
+ "main": [
+ [
+ {
+ "node": "Update Status: Creating Voiceover",
+ "type": "main",
+ "index": 0
+ }
+ ]
+ ]
+ },
+ "Update Status: Creating Voiceover": {
+ "main": [
+ [
+ {
+ "node": "Create Voiceover with gTTS",
+ "type": "main",
+ "index": 0
+ }
+ ]
+ ]
+ },
+ "Create Voiceover with gTTS": {
+ "main": [
+ [
+ {
+ "node": "Update Status: Assembling Video",
+ "type": "main",
+ "index": 0
+ }
+ ]
+ ]
+ },
+ "Update Status: Assembling Video": {
+ "main": [
+ [
+ {
+ "node": "Prepare Video Assembly Data",
+ "type": "main",
+ "index": 0
+ }
+ ]
+ ]
+ },
+ "Prepare Video Assembly Data": {
+ "main": [
+ [
+ {
+ "node": "Assemble Final Video",
+ "type": "main",
+ "index": 0
+ }
+ ]
+ ]
+ },
+ "Assemble Final Video": {
+ "main": [
+ [
+ {
+ "node": "Check YouTube Auth",
+ "type": "main",
+ "index": 0
+ }
+ ]
+ ]
+ },
+ "Check YouTube Auth": {
+ "main": [
+ [
+ {
+ "node": "Update Status: Uploading",
+ "type": "main",
+ "index": 0
+ }
+ ],
+ [
+ {
+ "node": "Update Status: Completed",
+ "type": "main",
+ "index": 0
+ }
+ ]
+ ]
+ },
+ "Update Status: Uploading": {
+ "main": [
+ [
+ {
+ "node": "Upload to YouTube",
+ "type": "main",
+ "index": 0
+ }
+ ]
+ ]
+ },
+ "Upload to YouTube": {
+ "main": [
+ [
+ {
+ "node": "Update YouTube Success",
+ "type": "main",
+ "index": 0
+ }
+ ]
+ ]
+ },
+ "Update YouTube Success": {
+ "main": [
+ [
+ {
+ "node": "Final Response",
+ "type": "main",
+ "index": 0
+ }
+ ]
+ ]
+ },
+ "Update Status: Completed": {
+ "main": [
+ [
+ {
+ "node": "Final Response",
+ "type": "main",
+ "index": 0
+ }
+ ]
+ ]
+ }
+ },
+ "active": true,
+ "settings": {
+ "timezone": "UTC"
+ },
+ "createdAt": "2025-01-01T00:00:00.000Z",
+ "updatedAt": "2025-01-01T00:00:00.000Z",
+ "id": "complete-workflow"
+}
diff --git a/docker/n8n/workflows/video-generation.json b/docker/n8n/workflows/video-generation.json
new file mode 100644
index 0000000..28482b4
--- /dev/null
+++ b/docker/n8n/workflows/video-generation.json
@@ -0,0 +1,351 @@
+{
+ "name": "YouTube Video Generator (Free Services)",
+ "nodes": [
+ {
+ "parameters": {
+ "httpMethod": "POST",
+ "path": "video-generation",
+ "responseMode": "responseNode",
+ "options": {}
+ },
+ "id": "webhook-start",
+ "name": "Webhook Start",
+ "type": "n8n-nodes-base.webhook",
+ "typeVersion": 1,
+ "position": [
+ 240,
+ 300
+ ],
+ "webhookId": "video-generation-webhook"
+ },
+ {
+ "parameters": {
+ "url": "=https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent",
+ "sendQuery": true,
+ "queryParameters": {
+ "parameters": [
+ {
+ "name": "key",
+ "value": "={{ $('Set API Keys').item.json.gemini_api_key }}"
+ }
+ ]
+ },
+ "sendHeaders": true,
+ "headerParameters": {
+ "parameters": [
+ {
+ "name": "Content-Type",
+ "value": "application/json"
+ }
+ ]
+ },
+ "sendBody": true,
+ "bodyParameters": {
+ "parameters": [
+ {
+ "name": "contents",
+ "value": "=[{\"parts\": [{\"text\": \"Create a YouTube script about: {{ $json.topic }}. Length: {{ $json.duration }} minutes. Include an engaging intro, main content with 3-5 key points, and a strong conclusion with call-to-action. Make it informative and engaging.\"}]}]"
+ }
+ ]
+ },
+ "options": {}
+ },
+ "id": "generate-script-gemini",
+ "name": "Generate Script with Gemini",
+ "type": "n8n-nodes-base.httpRequest",
+ "typeVersion": 4.1,
+ "position": [
+ 500,
+ 300
+ ]
+ },
+ {
+ "parameters": {
+ "url": "=https://pixabay.com/api/videos/",
+ "sendQuery": true,
+ "queryParameters": {
+ "parameters": [
+ {
+ "name": "key",
+ "value": "={{ $('Set API Keys').item.json.pixabay_api_key }}"
+ },
+ {
+ "name": "q",
+ "value": "={{ $json.topic.replace(' ', '+') }}"
+ },
+ {
+ "name": "video_type",
+ "value": "film"
+ },
+ {
+ "name": "category",
+ "value": "backgrounds"
+ },
+ {
+ "name": "min_duration",
+ "value": "20"
+ },
+ {
+ "name": "per_page",
+ "value": "10"
+ }
+ ]
+ },
+ "options": {}
+ },
+ "id": "fetch-videos-pixabay",
+ "name": "Fetch Videos from Pixabay",
+ "type": "n8n-nodes-base.httpRequest",
+ "typeVersion": 4.1,
+ "position": [
+ 720,
+ 300
+ ]
+ },
+ {
+ "parameters": {
+ "url": "=https://unsplash.com/napi/search/photos",
+ "sendQuery": true,
+ "queryParameters": {
+ "parameters": [
+ {
+ "name": "query",
+ "value": "={{ $json.topic }}"
+ },
+ {
+ "name": "per_page",
+ "value": "10"
+ },
+ {
+ "name": "orientation",
+ "value": "landscape"
+ }
+ ]
+ },
+ "sendHeaders": true,
+ "headerParameters": {
+ "parameters": [
+ {
+ "name": "Authorization",
+ "value": "=Client-ID {{ $('Set API Keys').item.json.unsplash_access_key }}"
+ }
+ ]
+ },
+ "options": {}
+ },
+ "id": "fetch-images-unsplash",
+ "name": "Fetch Images from Unsplash",
+ "type": "n8n-nodes-base.httpRequest",
+ "typeVersion": 4.1,
+ "position": [
+ 720,
+ 420
+ ]
+ },
+ {
+ "parameters": {
+ "command": "=python3 -c \"import gtts; import os; tts = gtts.gTTS(text='{{ $('Generate Script with Gemini').item.json.candidates[0].content.parts[0].text.replace('\\n', ' ').replace('\\'', '\\\\\\'\\'') }}', lang='en', slow=False); tts.save('/tmp/voiceover_{{ $json.video_id }}.mp3'); print('Voiceover generated successfully')\""
+ },
+ "id": "generate-voiceover-gtts",
+ "name": "Generate Voiceover with gTTS",
+ "type": "n8n-nodes-base.executeCommand",
+ "typeVersion": 1,
+ "position": [
+ 940,
+ 300
+ ]
+ },
+ {
+ "parameters": {
+ "jsCode": "// Create video script for FFmpeg\nconst script = $('Generate Script with Gemini').item.json.candidates[0].content.parts[0].text;\nconst videoId = $json.video_id;\n\n// Get media assets\nconst pixabayVideos = $('Fetch Videos from Pixabay').item.json.hits || [];\nconst unsplashImages = $('Fetch Images from Unsplash').item.json.results || [];\n\n// Create media list for video assembly\nlet mediaList = [];\nlet totalDuration = 0;\nconst targetDuration = parseInt($json.duration) * 60; // Convert to seconds\n\n// Add videos first\npixabayVideos.forEach((video, index) => {\n if (totalDuration < targetDuration && video.videos && video.videos.medium) {\n mediaList.push({\n type: 'video',\n url: video.videos.medium.url,\n duration: Math.min(video.duration, 10) // Max 10 seconds per clip\n });\n totalDuration += Math.min(video.duration, 10);\n }\n});\n\n// Fill remaining time with images (3 seconds each)\nunsplashImages.forEach((image, index) => {\n if (totalDuration < targetDuration) {\n mediaList.push({\n type: 'image',\n url: image.urls.regular,\n duration: 3\n });\n totalDuration += 3;\n }\n});\n\nreturn {\n json: {\n script: script,\n video_id: videoId,\n media_list: mediaList,\n total_duration: totalDuration,\n voiceover_path: `/tmp/voiceover_${videoId}.mp3`\n }\n};"
+ },
+ "id": "prepare-video-data",
+ "name": "Prepare Video Assembly Data",
+ "type": "n8n-nodes-base.code",
+ "typeVersion": 2,
+ "position": [
+ 1160,
+ 300
+ ]
+ },
+ {
+ "parameters": {
+ "command": "=python3 /var/www/scripts/create_video.py '{{ JSON.stringify($json) }}'"
+ },
+ "id": "assemble-video-python",
+ "name": "Assemble Video with Python",
+ "type": "n8n-nodes-base.executeCommand",
+ "typeVersion": 1,
+ "position": [
+ 1380,
+ 300
+ ]
+ },
+ {
+ "parameters": {
+ "url": "=http://app:8000/api/videos/{{ $json.video_id }}/update",
+ "sendHeaders": true,
+ "headerParameters": {
+ "parameters": [
+ {
+ "name": "Authorization",
+ "value": "=Bearer {{ $json.api_token }}"
+ },
+ {
+ "name": "Content-Type",
+ "value": "application/json"
+ }
+ ]
+ },
+ "sendBody": true,
+ "bodyParameters": {
+ "parameters": [
+ {
+ "name": "status",
+ "value": "completed"
+ },
+ {
+ "name": "file_path",
+ "value": "=/tmp/final_video_{{ $json.video_id }}.mp4"
+ },
+ {
+ "name": "script",
+ "value": "={{ $('Generate Script with Gemini').item.json.candidates[0].content.parts[0].text }}"
+ }
+ ]
+ }
+ },
+ "id": "update-video-status",
+ "name": "Update Video Status",
+ "type": "n8n-nodes-base.httpRequest",
+ "typeVersion": 4.1,
+ "position": [
+ 1600,
+ 300
+ ]
+ },
+ {
+ "parameters": {
+ "respondWith": "json",
+ "responseBody": "={{ { \"success\": true, \"message\": \"Video generation completed\", \"video_id\": $json.video_id, \"file_path\": \"/tmp/final_video_\" + $json.video_id + \".mp4\" } }}"
+ },
+ "id": "webhook-response",
+ "name": "Webhook Response",
+ "type": "n8n-nodes-base.respondToWebhook",
+ "typeVersion": 1,
+ "position": [
+ 1820,
+ 300
+ ]
+ },
+ {
+ "parameters": {
+ "jsCode": "// Set up API keys - You'll need to configure these in n8n\nreturn {\n json: {\n gemini_api_key: \"YOUR_GEMINI_API_KEY\", // Free: https://makersuite.google.com/app/apikey\n pixabay_api_key: \"YOUR_PIXABAY_API_KEY\", // Free: https://pixabay.com/api/docs/\n unsplash_access_key: \"YOUR_UNSPLASH_ACCESS_KEY\" // Free: https://unsplash.com/developers\n }\n};"
+ },
+ "id": "set-api-keys",
+ "name": "Set API Keys",
+ "type": "n8n-nodes-base.code",
+ "typeVersion": 2,
+ "position": [
+ 240,
+ 420
+ ]
+ }
+ ],
+ "connections": {
+ "Webhook Start": {
+ "main": [
+ [
+ {
+ "node": "Generate Script with Gemini",
+ "type": "main",
+ "index": 0
+ },
+ {
+ "node": "Set API Keys",
+ "type": "main",
+ "index": 0
+ }
+ ]
+ ]
+ },
+ "Generate Script with Gemini": {
+ "main": [
+ [
+ {
+ "node": "Fetch Videos from Pixabay",
+ "type": "main",
+ "index": 0
+ },
+ {
+ "node": "Fetch Images from Unsplash",
+ "type": "main",
+ "index": 0
+ }
+ ]
+ ]
+ },
+ "Fetch Videos from Pixabay": {
+ "main": [
+ [
+ {
+ "node": "Generate Voiceover with gTTS",
+ "type": "main",
+ "index": 0
+ }
+ ]
+ ]
+ },
+ "Generate Voiceover with gTTS": {
+ "main": [
+ [
+ {
+ "node": "Prepare Video Assembly Data",
+ "type": "main",
+ "index": 0
+ }
+ ]
+ ]
+ },
+ "Prepare Video Assembly Data": {
+ "main": [
+ [
+ {
+ "node": "Assemble Video with Python",
+ "type": "main",
+ "index": 0
+ }
+ ]
+ ]
+ },
+ "Assemble Video with Python": {
+ "main": [
+ [
+ {
+ "node": "Update Video Status",
+ "type": "main",
+ "index": 0
+ }
+ ]
+ ]
+ },
+ "Update Video Status": {
+ "main": [
+ [
+ {
+ "node": "Webhook Response",
+ "type": "main",
+ "index": 0
+ }
+ ]
+ ]
+ }
+ },
+ "active": true,
+ "settings": {
+ "timezone": "UTC"
+ },
+ "createdAt": "2025-01-01T00:00:00.000Z",
+ "updatedAt": "2025-01-01T00:00:00.000Z",
+ "id": "1"
+}
diff --git a/docker/n8n/workflows/youtube-upload.json b/docker/n8n/workflows/youtube-upload.json
new file mode 100644
index 0000000..37b7fa8
--- /dev/null
+++ b/docker/n8n/workflows/youtube-upload.json
@@ -0,0 +1,213 @@
+{
+ "name": "YouTube Video Upload",
+ "nodes": [
+ {
+ "parameters": {
+ "httpMethod": "POST",
+ "path": "youtube-upload",
+ "responseMode": "responseNode",
+ "options": {}
+ },
+ "id": "webhook-upload-start",
+ "name": "Upload Webhook",
+ "type": "n8n-nodes-base.webhook",
+ "typeVersion": 1,
+ "position": [
+ 240,
+ 300
+ ],
+ "webhookId": "youtube-upload-webhook"
+ },
+ {
+ "parameters": {
+ "url": "=http://app:8000/api/videos/{{ $json.video_id }}/details",
+ "sendHeaders": true,
+ "headerParameters": {
+ "parameters": [
+ {
+ "name": "Authorization",
+ "value": "=Bearer {{ $json.api_token }}"
+ }
+ ]
+ }
+ },
+ "id": "get-video-details",
+ "name": "Get Video Details",
+ "type": "n8n-nodes-base.httpRequest",
+ "typeVersion": 4.1,
+ "position": [
+ 460,
+ 300
+ ]
+ },
+ {
+ "parameters": {
+ "url": "=https://www.googleapis.com/upload/youtube/v3/videos",
+ "sendQuery": true,
+ "queryParameters": {
+ "parameters": [
+ {
+ "name": "part",
+ "value": "snippet,status"
+ },
+ {
+ "name": "key",
+ "value": "={{ $json.youtube_api_key }}"
+ }
+ ]
+ },
+ "sendHeaders": true,
+ "headerParameters": {
+ "parameters": [
+ {
+ "name": "Authorization",
+ "value": "=Bearer {{ $json.youtube_access_token }}"
+ },
+ {
+ "name": "Content-Type",
+ "value": "application/json"
+ }
+ ]
+ },
+ "sendBody": true,
+ "bodyParameters": {
+ "parameters": [
+ {
+ "name": "snippet",
+ "value": {
+ "title": "={{ $('Get Video Details').item.json.title }}",
+ "description": "={{ $('Get Video Details').item.json.description }}",
+ "tags": "={{ $('Get Video Details').item.json.tags }}",
+ "categoryId": "22"
+ }
+ },
+ {
+ "name": "status",
+ "value": {
+ "privacyStatus": "public"
+ }
+ }
+ ]
+ }
+ },
+ "id": "upload-to-youtube",
+ "name": "Upload to YouTube",
+ "type": "n8n-nodes-base.httpRequest",
+ "typeVersion": 4.1,
+ "position": [
+ 680,
+ 300
+ ]
+ },
+ {
+ "parameters": {
+ "url": "=http://app:8000/api/videos/{{ $json.video_id }}/youtube-uploaded",
+ "sendHeaders": true,
+ "headerParameters": {
+ "parameters": [
+ {
+ "name": "Authorization",
+ "value": "=Bearer {{ $json.api_token }}"
+ },
+ {
+ "name": "Content-Type",
+ "value": "application/json"
+ }
+ ]
+ },
+ "sendBody": true,
+ "bodyParameters": {
+ "parameters": [
+ {
+ "name": "youtube_video_id",
+ "value": "={{ $('Upload to YouTube').item.json.id }}"
+ },
+ {
+ "name": "youtube_url",
+ "value": "=https://www.youtube.com/watch?v={{ $('Upload to YouTube').item.json.id }}"
+ },
+ {
+ "name": "status",
+ "value": "uploaded"
+ }
+ ]
+ }
+ },
+ "id": "update-upload-status",
+ "name": "Update Upload Status",
+ "type": "n8n-nodes-base.httpRequest",
+ "typeVersion": 4.1,
+ "position": [
+ 900,
+ 300
+ ]
+ },
+ {
+ "parameters": {
+ "respondWith": "json",
+ "responseBody": "={{ { \"success\": true, \"message\": \"Video uploaded to YouTube\", \"youtube_url\": \"https://www.youtube.com/watch?v=\" + $('Upload to YouTube').item.json.id } }}"
+ },
+ "id": "upload-response",
+ "name": "Upload Response",
+ "type": "n8n-nodes-base.respondToWebhook",
+ "typeVersion": 1,
+ "position": [
+ 1120,
+ 300
+ ]
+ }
+ ],
+ "connections": {
+ "Upload Webhook": {
+ "main": [
+ [
+ {
+ "node": "Get Video Details",
+ "type": "main",
+ "index": 0
+ }
+ ]
+ ]
+ },
+ "Get Video Details": {
+ "main": [
+ [
+ {
+ "node": "Upload to YouTube",
+ "type": "main",
+ "index": 0
+ }
+ ]
+ ]
+ },
+ "Upload to YouTube": {
+ "main": [
+ [
+ {
+ "node": "Update Upload Status",
+ "type": "main",
+ "index": 0
+ }
+ ]
+ ]
+ },
+ "Update Upload Status": {
+ "main": [
+ [
+ {
+ "node": "Upload Response",
+ "type": "main",
+ "index": 0
+ }
+ ]
+ ]
+ }
+ },
+ "active": true,
+ "settings": {
+ "timezone": "UTC"
+ },
+ "createdAt": "2025-01-01T00:00:00.000Z",
+ "updatedAt": "2025-01-01T00:00:00.000Z",
+ "id": "2"
+}
diff --git a/docker/nginx/app.conf b/docker/nginx/app.conf
new file mode 100644
index 0000000..f397fbd
--- /dev/null
+++ b/docker/nginx/app.conf
@@ -0,0 +1,20 @@
+server {
+ listen 80;
+ index index.php index.html;
+ error_log /var/log/nginx/error.log;
+ access_log /var/log/nginx/access.log;
+ root /var/www/public;
+ location ~ \.php$ {
+ try_files $uri =404;
+ fastcgi_split_path_info ^(.+\.php)(/.+)$;
+ fastcgi_pass app:9000;
+ fastcgi_index index.php;
+ include fastcgi_params;
+ fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
+ fastcgi_param PATH_INFO $fastcgi_path_info;
+ }
+ location / {
+ try_files $uri $uri/ /index.php?$query_string;
+ gzip_static on;
+ }
+}
diff --git a/docker/php/local.ini b/docker/php/local.ini
new file mode 100644
index 0000000..80b31a7
--- /dev/null
+++ b/docker/php/local.ini
@@ -0,0 +1,5 @@
+upload_max_filesize=100M
+post_max_size=100M
+memory_limit=512M
+max_execution_time=300
+max_input_time=300
diff --git a/routes/api.php b/routes/api.php
new file mode 100644
index 0000000..0d4a6b2
--- /dev/null
+++ b/routes/api.php
@@ -0,0 +1,31 @@
+<?php
+
+use App\Http\Controllers\Api\N8nController;
+use Illuminate\Http\Request;
+use Illuminate\Support\Facades\Route;
+
+/*
+|--------------------------------------------------------------------------
+| API Routes
+|--------------------------------------------------------------------------
+*/
+
+Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
+ return $request->user();
+});
+
+// n8n Integration Routes
+Route::prefix('videos')->group(function () {
+ Route::get('{video}/details', [N8nController::class, 'getVideoDetails']);
+ Route::post('{video}/status', [N8nController::class, 'updateVideoStatus']);
+ Route::post('{video}/generate-script', [N8nController::class, 'generateScript']);
+ Route::post('{video}/fetch-media', [N8nController::class, 'fetchMedia']);
+ Route::post('{video}/upload-youtube', [N8nController::class, 'uploadToYoutube']);
+ Route::post('{video}/youtube-uploaded', [N8nController::class, 'markAsUploaded']);
+});
+
+Route::prefix('autopilot')->group(function () {
+ Route::get('topics', [N8nController::class, 'getScheduledTopics']);
+});
+
+Route::post('video-requests', [N8nController::class, 'createVideoRequest']);
diff --git a/scripts/create_video.py b/scripts/create_video.py
new file mode 100644
index 0000000..e389f4e
--- /dev/null
+++ b/scripts/create_video.py
@@ -0,0 +1,178 @@
+#!/usr/bin/env python3
+"""
+Video Assembly Script for YouTube Video Generator
+Uses free services: gTTS, FFmpeg, Pixabay, Unsplash
+"""
+
+import json
+import sys
+import os
+import requests
+import subprocess
+from pathlib import Path
+import tempfile
+import logging
+
+# Set up logging
+logging.basicConfig(level=logging.INFO)
+logger = logging.getLogger(__name__)
+
+def download_file(url, local_path):
+ """Download file from URL to local path"""
+ try:
+ response = requests.get(url, stream=True, timeout=30)
+ response.raise_for_status()
+
+ with open(local_path, 'wb') as f:
+ for chunk in response.iter_content(chunk_size=8192):
+ f.write(chunk)
+
+ logger.info(f"Downloaded: {local_path}")
+ return True
+ except Exception as e:
+ logger.error(f"Failed to download {url}: {e}")
+ return False
+
+def create_video_from_images(image_paths, output_path, duration_per_image=3):
+ """Create video from images using FFmpeg"""
+ try:
+ # Create input file list for FFmpeg
+ with tempfile.NamedTemporaryFile(mode='w', suffix='.txt', delete=False) as f:
+ for img_path in image_paths:
+ f.write(f"file '{img_path}'\n")
+ f.write(f"duration {duration_per_image}\n")
+ # Add last image again for proper ending
+ if image_paths:
+ f.write(f"file '{image_paths[-1]}'\n")
+ input_list_path = f.name
+
+ # FFmpeg command to create video from images
+ cmd = [
+ 'ffmpeg', '-y', # Overwrite output file
+ '-f', 'concat',
+ '-safe', '0',
+ '-i', input_list_path,
+ '-vf', 'scale=1920:1080:force_original_aspect_ratio=decrease,pad=1920:1080:(ow-iw)/2:(oh-ih)/2',
+ '-r', '30', # Frame rate
+ '-c:v', 'libx264',
+ '-pix_fmt', 'yuv420p',
+ output_path
+ ]
+
+ result = subprocess.run(cmd, capture_output=True, text=True)
+
+ # Clean up
+ os.unlink(input_list_path)
+
+ if result.returncode == 0:
+ logger.info(f"Video created: {output_path}")
+ return True
+ else:
+ logger.error(f"FFmpeg error: {result.stderr}")
+ return False
+
+ except Exception as e:
+ logger.error(f"Error creating video from images: {e}")
+ return False
+
+def add_audio_to_video(video_path, audio_path, output_path):
+ """Add audio to video using FFmpeg"""
+ try:
+ cmd = [
+ 'ffmpeg', '-y',
+ '-i', video_path,
+ '-i', audio_path,
+ '-c:v', 'copy',
+ '-c:a', 'aac',
+ '-shortest', # End when shortest stream ends
+ output_path
+ ]
+
+ result = subprocess.run(cmd, capture_output=True, text=True)
+
+ if result.returncode == 0:
+ logger.info(f"Audio added to video: {output_path}")
+ return True
+ else:
+ logger.error(f"FFmpeg audio error: {result.stderr}")
+ return False
+
+ except Exception as e:
+ logger.error(f"Error adding audio to video: {e}")
+ return False
+
+def main():
+ if len(sys.argv) != 2:
+ logger.error("Usage: python3 create_video.py '<json_data>'")
+ sys.exit(1)
+
+ try:
+ # Parse input data
+ data = json.loads(sys.argv[1])
+ video_id = data['video_id']
+ media_list = data['media_list']
+ voiceover_path = data['voiceover_path']
+
+ logger.info(f"Creating video {video_id} with {len(media_list)} media items")
+
+ # Create temp directory for this video
+ temp_dir = Path(f"/tmp/video_{video_id}")
+ temp_dir.mkdir(exist_ok=True)
+
+ # Download media files
+ image_paths = []
+ video_paths = []
+
+ for i, media in enumerate(media_list):
+ if media['type'] == 'image':
+ local_path = temp_dir / f"image_{i}.jpg"
+ if download_file(media['url'], local_path):
+ image_paths.append(str(local_path))
+ elif media['type'] == 'video':
+ local_path = temp_dir / f"video_{i}.mp4"
+ if download_file(media['url'], local_path):
+ video_paths.append(str(local_path))
+
+ # Create video from images if we have any
+ if image_paths:
+ images_video_path = temp_dir / "images_video.mp4"
+ if create_video_from_images(image_paths, str(images_video_path)):
+ video_paths.append(str(images_video_path))
+
+ # For now, use the first video or images video
+ if video_paths:
+ base_video_path = video_paths[0]
+ else:
+ logger.error("No media available for video creation")
+ sys.exit(1)
+
+ # Add voiceover if available
+ final_video_path = f"/tmp/final_video_{video_id}.mp4"
+
+ if os.path.exists(voiceover_path):
+ if add_audio_to_video(base_video_path, voiceover_path, final_video_path):
+ logger.info(f"Video completed: {final_video_path}")
+ else:
+ # Fallback: copy base video
+ import shutil
+ shutil.copy2(base_video_path, final_video_path)
+ logger.info(f"Video completed (no audio): {final_video_path}")
+ else:
+ # No voiceover, just copy the base video
+ import shutil
+ shutil.copy2(base_video_path, final_video_path)
+ logger.info(f"Video completed (no voiceover): {final_video_path}")
+
+ # Clean up temp directory
+ import shutil
+ shutil.rmtree(temp_dir, ignore_errors=True)
+
+ logger.info("Video assembly completed successfully")
+ print(f"SUCCESS: {final_video_path}")
+
+ except Exception as e:
+ logger.error(f"Error in main: {e}")
+ sys.exit(1)
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/gtts_client.py b/scripts/gtts_client.py
new file mode 100644
index 0000000..3bf6508
--- /dev/null
+++ b/scripts/gtts_client.py
@@ -0,0 +1,48 @@
+#!/usr/bin/env python3
+"""
+Google Text-to-Speech (gTTS) Client for YouTube Video Generator
+Completely free TTS service with good quality
+"""
+
+from gtts import gTTS
+import sys
+import os
+import logging
+
+logging.basicConfig(level=logging.INFO)
+logger = logging.getLogger(__name__)
+
+def create_speech(text, output_path, language='en', slow=False):
+ """Create speech audio file from text using gTTS"""
+ try:
+ # Create gTTS object
+ tts = gTTS(text=text, lang=language, slow=slow)
+
+ # Save to file
+ tts.save(output_path)
+
+ logger.info(f"Speech created: {output_path}")
+ return True
+
+ except Exception as e:
+ logger.error(f"Error creating speech: {e}")
+ return False
+
+def main():
+ if len(sys.argv) < 3:
+ logger.error("Usage: python3 gtts_client.py '<text>' <output_path> [language] [slow]")
+ sys.exit(1)
+
+ text = sys.argv[1]
+ output_path = sys.argv[2]
+ language = sys.argv[3] if len(sys.argv) > 3 else 'en'
+ slow = sys.argv[4].lower() == 'true' if len(sys.argv) > 4 else False
+
+ if create_speech(text, output_path, language, slow):
+ print(f"SUCCESS: {output_path}")
+ else:
+ print("ERROR: Failed to create speech")
+ sys.exit(1)
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/install_dependencies.sh b/scripts/install_dependencies.sh
new file mode 100644
index 0000000..01d8f4e
--- /dev/null
+++ b/scripts/install_dependencies.sh
@@ -0,0 +1,26 @@
+#!/bin/bash
+"""
+Installation script for Python dependencies
+Run this in your Docker container or local environment
+"""
+
+# Install Python packages
+pip3 install -r requirements.txt
+
+# Verify installations
+echo "Verifying installations..."
+python3 -c "import gtts; print('gTTS installed successfully')"
+python3 -c "import requests; print('Requests installed successfully')"
+
+echo "All Python dependencies installed successfully!"
+echo ""
+echo "Available scripts:"
+echo "- create_video.py: Main video assembly script"
+echo "- pixabay_client.py: Pixabay API client for videos/images"
+echo "- unsplash_client.py: Unsplash API client for images"
+echo "- gtts_client.py: Google Text-to-Speech client"
+echo ""
+echo "Usage examples:"
+echo "python3 gtts_client.py 'Hello world' /tmp/speech.mp3"
+echo "python3 pixabay_client.py YOUR_API_KEY 'nature' video"
+echo "python3 unsplash_client.py YOUR_ACCESS_KEY 'landscape'"
diff --git a/scripts/pixabay_client.py b/scripts/pixabay_client.py
new file mode 100644
index 0000000..31737fd
--- /dev/null
+++ b/scripts/pixabay_client.py
@@ -0,0 +1,111 @@
+#!/usr/bin/env python3
+"""
+Pixabay API Client for YouTube Video Generator
+Free API with 5000 requests/hour limit
+"""
+
+import requests
+import json
+import sys
+import logging
+
+logging.basicConfig(level=logging.INFO)
+logger = logging.getLogger(__name__)
+
+class PixabayClient:
+ def __init__(self, api_key):
+ self.api_key = api_key
+ self.base_url = "https://pixabay.com/api"
+
+ def search_videos(self, query, per_page=10, video_type="film"):
+ """Search for videos on Pixabay"""
+ params = {
+ 'key': self.api_key,
+ 'q': query,
+ 'video_type': video_type,
+ 'category': 'backgrounds',
+ 'per_page': per_page,
+ 'safesearch': 'true',
+ 'order': 'popular'
+ }
+
+ try:
+ response = requests.get(f"{self.base_url}/videos/", params=params)
+ response.raise_for_status()
+ return response.json()
+ except Exception as e:
+ logger.error(f"Pixabay video search error: {e}")
+ return {"hits": []}
+
+ def search_images(self, query, per_page=10, image_type="photo"):
+ """Search for images on Pixabay"""
+ params = {
+ 'key': self.api_key,
+ 'q': query,
+ 'image_type': image_type,
+ 'category': 'backgrounds',
+ 'per_page': per_page,
+ 'safesearch': 'true',
+ 'order': 'popular',
+ 'min_width': 1920,
+ 'min_height': 1080
+ }
+
+ try:
+ response = requests.get(f"{self.base_url}/", params=params)
+ response.raise_for_status()
+ return response.json()
+ except Exception as e:
+ logger.error(f"Pixabay image search error: {e}")
+ return {"hits": []}
+
+def main():
+ if len(sys.argv) != 4:
+ logger.error("Usage: python3 pixabay_client.py <api_key> <query> <media_type>")
+ sys.exit(1)
+
+ api_key = sys.argv[1]
+ query = sys.argv[2]
+ media_type = sys.argv[3] # 'video' or 'image'
+
+ client = PixabayClient(api_key)
+
+ if media_type == 'video':
+ results = client.search_videos(query, per_page=5)
+ media_list = []
+
+ for hit in results.get('hits', []):
+ # Get medium quality video URL
+ video_url = hit.get('videos', {}).get('medium', {}).get('url')
+ if video_url:
+ media_list.append({
+ 'type': 'video',
+ 'url': video_url,
+ 'title': hit.get('tags', 'Video'),
+ 'duration': hit.get('duration', 10)
+ })
+
+ print(json.dumps(media_list))
+
+ elif media_type == 'image':
+ results = client.search_images(query, per_page=8)
+ media_list = []
+
+ for hit in results.get('hits', []):
+ # Get large image URL
+ image_url = hit.get('largeImageURL') or hit.get('webformatURL')
+ if image_url:
+ media_list.append({
+ 'type': 'image',
+ 'url': image_url,
+ 'title': hit.get('tags', 'Image')
+ })
+
+ print(json.dumps(media_list))
+
+ else:
+ logger.error("Media type must be 'video' or 'image'")
+ sys.exit(1)
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/requirements.txt b/scripts/requirements.txt
new file mode 100644
index 0000000..1df69b2
--- /dev/null
+++ b/scripts/requirements.txt
@@ -0,0 +1,23 @@
+#!/usr/bin/env python3
+"""
+Requirements file for Python scripts
+Install these packages in your Python environment or Docker container
+"""
+
+# For text-to-speech with gTTS
+gtts==2.5.1
+
+# For HTTP requests
+requests==2.31.0
+
+# For JSON processing (built-in, no install needed)
+# json
+
+# For system operations (built-in, no install needed)
+# os
+# sys
+# subprocess
+# pathlib
+# tempfile
+# logging
+# shutil
diff --git a/scripts/unsplash_client.py b/scripts/unsplash_client.py
new file mode 100644
index 0000000..77e3b5f
--- /dev/null
+++ b/scripts/unsplash_client.py
@@ -0,0 +1,73 @@
+#!/usr/bin/env python3
+"""
+Unsplash API Client for YouTube Video Generator
+Free API with 50 requests/hour limit for demo/development
+"""
+
+import requests
+import json
+import sys
+import logging
+
+logging.basicConfig(level=logging.INFO)
+logger = logging.getLogger(__name__)
+
+class UnsplashClient:
+ def __init__(self, access_key):
+ self.access_key = access_key
+ self.base_url = "https://api.unsplash.com"
+ self.headers = {
+ 'Authorization': f'Client-ID {access_key}',
+ 'Accept-Version': 'v1'
+ }
+
+ def search_photos(self, query, per_page=10, orientation="landscape"):
+ """Search for photos on Unsplash"""
+ params = {
+ 'query': query,
+ 'per_page': per_page,
+ 'orientation': orientation,
+ 'order_by': 'relevant',
+ 'content_filter': 'high'
+ }
+
+ try:
+ response = requests.get(
+ f"{self.base_url}/search/photos",
+ headers=self.headers,
+ params=params
+ )
+ response.raise_for_status()
+ return response.json()
+ except Exception as e:
+ logger.error(f"Unsplash search error: {e}")
+ return {"results": []}
+
+def main():
+ if len(sys.argv) != 3:
+ logger.error("Usage: python3 unsplash_client.py <access_key> <query>")
+ sys.exit(1)
+
+ access_key = sys.argv[1]
+ query = sys.argv[2]
+
+ client = UnsplashClient(access_key)
+ results = client.search_photos(query, per_page=8)
+
+ media_list = []
+
+ for photo in results.get('results', []):
+ # Get regular size image URL (suitable for 1920x1080)
+ image_url = photo.get('urls', {}).get('regular')
+ if image_url:
+ media_list.append({
+ 'type': 'image',
+ 'url': image_url,
+ 'title': photo.get('alt_description') or photo.get('description') or 'Unsplash Image',
+ 'credit': f"Photo by {photo.get('user', {}).get('name', 'Unknown')} on Unsplash"
+ })
+
+ print(json.dumps(media_list))
+
+if __name__ == "__main__":
+ main()
diff --git a/start.bat b/start.bat
new file mode 100644
index 0000000..2b950b5
--- /dev/null
+++ b/start.bat
@@ -0,0 +1,53 @@
+@echo off
+echo 🚀 Starting YouTube Video Generator Application...
+
+:: Copy environment file
+copy .env.docker .env
+
+:: Build and start containers
+echo 📦 Building Docker containers...
+docker-compose build --no-cache
+
+echo 🔧 Starting services...
+docker-compose up -d
+
+:: Wait for database to be ready
+echo ⏳ Waiting for database to be ready...
+timeout /t 30 /nobreak
+
+:: Run database migrations
+echo 🗄️ Running database migrations...
+docker-compose exec app php artisan migrate:fresh --seed
+
+:: Generate application key
+echo 🔑 Generating application key...
+docker-compose exec app php artisan key:generate
+
+:: Clear caches
+echo 🧹 Clearing caches...
+docker-compose exec app php artisan config:cache
+docker-compose exec app php artisan route:cache
+
+:: Set permissions
+echo 📂 Setting permissions...
+docker-compose exec app chmod -R 777 storage bootstrap/cache
+
+echo ✅ Setup complete!
+echo.
+echo 🌐 Application URLs:
+echo - Laravel App: http://localhost:8000
+echo - n8n Workflows: http://localhost:5678
+echo - MySQL: localhost:3306
+echo - Redis: localhost:6379
+echo.
+echo 🔐 n8n Login:
+echo - Username: admin
+echo - Password: n8npassword
+echo.
+echo 📋 Next Steps:
+echo 1. Visit http://localhost:8000 to access the application
+echo 2. Visit http://localhost:5678 to configure n8n workflows
+echo 3. Import the workflow files from docker/n8n/workflows/
+echo 4. Configure API keys in n8n for OpenAI, ElevenLabs, and Pexels
+
+pause
diff --git a/start.sh b/start.sh
new file mode 100644
index 0000000..86e5c69
--- /dev/null
+++ b/start.sh
@@ -0,0 +1,52 @@
+#!/bin/bash
+
+echo "🚀 Starting YouTube Video Generator Application..."
+
+# Copy environment file
+cp .env.docker .env
+
+# Build and start containers
+echo "📦 Building Docker containers..."
+docker-compose build --no-cache
+
+echo "🔧 Starting services..."
+docker-compose up -d
+
+# Wait for database to be ready
+echo "⏳ Waiting for database to be ready..."
+sleep 30
+
+# Run database migrations
+echo "🗄️ Running database migrations..."
+docker-compose exec app php artisan migrate:fresh --seed
+
+# Generate application key
+echo "🔑 Generating application key..."
+docker-compose exec app php artisan key:generate
+
+# Clear caches
+echo "🧹 Clearing caches..."
+docker-compose exec app php artisan config:cache
+docker-compose exec app php artisan route:cache
+
+# Set permissions
+echo "📂 Setting permissions..."
+docker-compose exec app chmod -R 777 storage bootstrap/cache
+
+echo "✅ Setup complete!"
+echo ""
+echo "🌐 Application URLs:"
+echo " - Laravel App: http://localhost:8000"
+echo " - n8n Workflows: http://localhost:5678"
+echo " - MySQL: localhost:3306"
+echo " - Redis: localhost:6379"
+echo ""
+echo "🔐 n8n Login:"
+echo " - Username: admin"
+echo " - Password: n8npassword"
+echo ""
+echo "📋 Next Steps:"
+echo " 1. Visit http://localhost:8000 to access the application"
+echo " 2. Visit http://localhost:5678 to configure n8n workflows"
+echo " 3. Import the workflow files from docker/n8n/workflows/"
+echo " 4. Configure API keys in n8n for OpenAI, ElevenLabs, and Pexels"