kabeerahmad's picture
Upload server.js
2755ad2 verified
Raw History Blame Contribute Delete
5.67 kB
import express from 'express';
import cors from 'cors';
import { bundle } from '@remotion/bundler';
import { renderMedia, selectComposition } from '@remotion/renderer';
import { readFile, mkdir, rm } from 'fs/promises';
import { tmpdir } from 'os';
import { join, dirname } from 'path';
import { randomUUID } from 'crypto';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const app = express();
const PORT = process.env.PORT || 7860;
app.use(cors());
app.use(express.json({ limit: '50mb' }));
// Health check
app.get('/', (req, res) => {
res.json({ status: 'ok', service: 'FacelessFlowAI Video Renderer' });
});
// Render endpoint
app.post('/render', async (req, res) => {
const { projectId, scenes, settings } = req.body;
if (!projectId || !scenes || !settings) {
return res.status(400).json({ error: 'Missing projectId, scenes, or settings' });
}
// Initialize Supabase Admin Client
const SUPABASE_URL = process.env.SUPABASE_URL;
const SUPABASE_SERVICE_ROLE_KEY = process.env.SUPABASE_SERVICE_ROLE_KEY;
if (!SUPABASE_URL || !SUPABASE_SERVICE_ROLE_KEY) {
console.error('[Config] Missing Supabase credentials');
return res.status(500).json({ error: 'Renderer configuration error' });
}
const { createClient } = await import('@supabase/supabase-js');
const supabase = createClient(SUPABASE_URL, SUPABASE_SERVICE_ROLE_KEY);
// 1. Respond immediately
res.json({ success: true, message: 'Rendering started in background' });
// 2. Start Background Process
(async () => {
try {
console.log(`[Render] Starting background render for project ${projectId}`);
const bundleLocation = await bundle({
entryPoint: join(__dirname, 'remotion', 'index.tsx'),
webpackOverride: (config) => config,
});
const composition = await selectComposition({
serveUrl: bundleLocation,
id: 'Main',
inputProps: { scenes, settings },
chromiumOptions: { executablePath: process.env.CHROME_BIN || '/usr/bin/chromium' },
});
const tempDir = join(tmpdir(), `remotion-${randomUUID()}`);
await mkdir(tempDir, { recursive: true });
const outputPath = join(tempDir, 'output.mp4');
const os = await import('os');
const cpuCount = os.cpus().length;
console.log(`[Render] Detected ${cpuCount} CPUs. Using all cores for rendering.`);
// HuggingFace Spaces (Free Tier) often reports host CPUs (e.g. 16) but enforces a 2-core limit.
// Remotion crashes if we request more threads than the system allows.
const safeConcurrency = Math.min(cpuCount, 2);
console.log(`[Render] Requesting concurrency: ${safeConcurrency} (Host has ${cpuCount})`);
await renderMedia({
composition,
serveUrl: bundleLocation,
codec: 'h264',
outputLocation: outputPath,
inputProps: { scenes, settings },
chromiumOptions: {
executablePath: process.env.CHROME_BIN || '/usr/bin/chromium',
enableMultiProcessRendering: true,
},
concurrency: safeConcurrency,
disallowParallelEncoding: false,
});
console.log(`[Render] Render complete. Uploading to Supabase...`);
const videoBuffer = await readFile(outputPath);
// Upload to Supabase Storage
const fileName = `${projectId}/video-${Date.now()}.mp4`;
const { data: uploadData, error: uploadError } = await supabase
.storage
.from('projects') // Assuming 'projects' bucket exists
.upload(fileName, videoBuffer, {
contentType: 'video/mp4',
upsert: true
});
if (uploadError) throw new Error(`Upload failed: ${uploadError.message}`);
// Get Public URL
const { data: { publicUrl } } = supabase
.storage
.from('projects')
.getPublicUrl(fileName);
console.log(`[Render] Uploaded to ${publicUrl}`);
// Update Project in DB
const { error: dbError } = await supabase
.from('projects')
.update({
status: 'done',
video_url: publicUrl
})
.eq('id', projectId);
if (dbError) throw new Error(`DB Update failed: ${dbError.message}`);
console.log(`[Render] Project ${projectId} updated successfully`);
// Cleanup
await rm(tempDir, { recursive: true, force: true });
} catch (error) {
console.error(`[Render] Background Error for ${projectId}:`, error);
// Optionally update project status to 'error' if you had that status
}
})();
});
app.listen(PORT, () => {
console.log(`🎬 FacelessFlowAI Renderer running on port ${PORT}`);
// Debug: Check for Secrets on Startup
console.log('--- Environment Check ---');
console.log('SUPABASE_URL exists:', !!process.env.SUPABASE_URL);
console.log('SUPABASE_SERVICE_ROLE_KEY exists:', !!process.env.SUPABASE_SERVICE_ROLE_KEY);
console.log('Available Keys (starts with SUPA):', Object.keys(process.env).filter(k => k.startsWith('SUPA')));
console.log('-------------------------');
});