Download apps/server/src/services/modalRenderService.ts from phucsd/olokaflow: direct link, hf CLI and curl.
- Browser
- Download file 13.1 kB
-
https://huggingface.co/spaces/phucsd/olokaflow/resolve/main/apps/server/src/services/modalRenderService.ts
- Command line
-
hf download hf://spaces/phucsd/olokaflow/apps/server/src/services/modalRenderService.ts
-
curl -L -o modalRenderService.ts https://huggingface.co/spaces/phucsd/olokaflow/resolve/main/apps/server/src/services/modalRenderService.ts
13.1 kB
| import fs from 'node:fs'; | |
| import path from 'node:path'; | |
| import crypto from 'node:crypto'; | |
| import { execFile } from 'node:child_process'; | |
| import { promisify } from 'node:util'; | |
| import { db, DATA_DIR, PROJECTS_DIR, RENDERS_DIR, logUsage } from '../db/database.js'; | |
| import { resolveTargetsForRole, normalizeBaseUrl } from './aiProfileService.js'; | |
| import type { Project, RenderJob } from '@olokaflow/shared'; | |
| const execFileAsync = promisify(execFile); | |
| const activeRenderAbortControllers = new Map<string, AbortController>(); | |
| export const DEFAULT_PRODUCTION_MODAL_URL = | |
| process.env.MODAL_RENDER_BASE_URL || | |
| 'https://phucsd--autocode-hyperframes-renderer-web.modal.run'; | |
| function saveRenderJobRecord(job: RenderJob): RenderJob { | |
| const now = new Date().toISOString(); | |
| db.prepare(` | |
| INSERT OR REPLACE INTO render_jobs ( | |
| id, project_id, provider, status, progress, data_json, created_at, updated_at | |
| ) VALUES (?, ?, ?, ?, ?, ?, ?, ?) | |
| `).run( | |
| job.id, | |
| job.projectId, | |
| job.provider, | |
| job.status, | |
| job.progress, | |
| JSON.stringify(job), | |
| job.createdAt || now, | |
| now | |
| ); | |
| return job; | |
| } | |
| export function listRenderJobs(projectId?: string): RenderJob[] { | |
| const rows = projectId | |
| ? (db | |
| .prepare('SELECT data_json FROM render_jobs WHERE project_id = ? ORDER BY created_at DESC') | |
| .all(projectId) as any[]) | |
| : (db | |
| .prepare('SELECT data_json FROM render_jobs ORDER BY created_at DESC LIMIT 50') | |
| .all() as any[]); | |
| return rows.map((r) => JSON.parse(r.data_json) as RenderJob); | |
| } | |
| export function getRenderJobById(id: string): RenderJob | null { | |
| const row = db.prepare('SELECT data_json FROM render_jobs WHERE id = ?').get(id) as any; | |
| return row ? (JSON.parse(row.data_json) as RenderJob) : null; | |
| } | |
| export function cancelRenderJob(id: string): RenderJob | null { | |
| const ctrl = activeRenderAbortControllers.get(id); | |
| if (ctrl) ctrl.abort(); | |
| const job = getRenderJobById(id); | |
| if (!job) return null; | |
| job.status = 'cancelled'; | |
| job.errorMessage = 'Người dùng đã hủy tiến trình Render.'; | |
| return saveRenderJobRecord(job); | |
| } | |
| /** | |
| * Collects index.html and any local /media/... files referenced inside index.html | |
| * into a self-contained base64 bundle for the Modal HyperFrames renderer. | |
| */ | |
| export function buildModalRenderBundle(projectDir: string, indexHtmlContent: string): { | |
| files: Array<{ path: string; mode: 'base64'; content: string }>; | |
| totalBytes: number; | |
| } { | |
| let rewrittenHtml = indexHtmlContent; | |
| const files: Array<{ path: string; mode: 'base64'; content: string }> = []; | |
| let totalBytes = 0; | |
| const addedRelPaths = new Set<string>(); | |
| // Find any /media/... URLs referenced in index.html and bundle them into assets/... | |
| const mediaRegex = /(['"(])\/media\/([^'"()\s]+)\1/g; | |
| rewrittenHtml = rewrittenHtml.replace(mediaRegex, (fullMatch, quote, relMediaPath) => { | |
| const cleanRel = String(relMediaPath || '').replace(/\.\./g, ''); | |
| const localDiskPath = path.join(DATA_DIR, cleanRel); | |
| const bundleRelPath = `assets/${path.basename(cleanRel)}`; | |
| if (fs.existsSync(localDiskPath) && fs.statSync(localDiskPath).isFile()) { | |
| if (!addedRelPaths.has(bundleRelPath)) { | |
| const buf = fs.readFileSync(localDiskPath); | |
| totalBytes += buf.length; | |
| files.push({ | |
| path: bundleRelPath, | |
| mode: 'base64', | |
| content: buf.toString('base64'), | |
| }); | |
| addedRelPaths.add(bundleRelPath); | |
| } | |
| const closing = quote === '(' ? ')' : quote; | |
| return `${quote}${bundleRelPath}${closing}`; | |
| } | |
| return fullMatch; | |
| }); | |
| // Also include any files inside projectDir/assets if present | |
| const projectAssetsDir = path.join(projectDir, 'assets'); | |
| if (fs.existsSync(projectAssetsDir)) { | |
| for (const entry of fs.readdirSync(projectAssetsDir, { withFileTypes: true })) { | |
| if (!entry.isFile()) continue; | |
| const rel = `assets/${entry.name}`; | |
| if (addedRelPaths.has(rel)) continue; | |
| const buf = fs.readFileSync(path.join(projectAssetsDir, entry.name)); | |
| totalBytes += buf.length; | |
| files.push({ | |
| path: rel, | |
| mode: 'base64', | |
| content: buf.toString('base64'), | |
| }); | |
| addedRelPaths.add(rel); | |
| } | |
| } | |
| const htmlBuf = Buffer.from(rewrittenHtml, 'utf8'); | |
| totalBytes += htmlBuf.length; | |
| files.unshift({ | |
| path: 'index.html', | |
| mode: 'base64', | |
| content: htmlBuf.toString('base64'), | |
| }); | |
| return { files, totalBytes }; | |
| } | |
| export async function startProjectRenderJob( | |
| project: Project, | |
| preferredProvider: 'modal' | 'local' = 'modal', | |
| onUpdate?: (job: RenderJob) => void | |
| ): Promise<RenderJob> { | |
| const now = new Date().toISOString(); | |
| const jobId = `rnd-${crypto.randomUUID().slice(0, 8)}`; | |
| let job: RenderJob = { | |
| id: jobId, | |
| projectId: project.id, | |
| provider: preferredProvider, | |
| status: 'queued', | |
| progress: 5, | |
| modalCallId: '', | |
| outputUrl: '', | |
| errorMessage: '', | |
| durationMs: 0, | |
| createdAt: now, | |
| completedAt: null, | |
| }; | |
| saveRenderJobRecord(job); | |
| onUpdate?.(job); | |
| const abortCtrl = new AbortController(); | |
| activeRenderAbortControllers.set(jobId, abortCtrl); | |
| void executeRenderPipeline(project, job, abortCtrl.signal, (updated) => { | |
| saveRenderJobRecord(updated); | |
| onUpdate?.(updated); | |
| }).finally(() => { | |
| activeRenderAbortControllers.delete(jobId); | |
| }); | |
| return job; | |
| } | |
| async function executeRenderPipeline( | |
| project: Project, | |
| job: RenderJob, | |
| signal: AbortSignal, | |
| emit: (j: RenderJob) => void | |
| ): Promise<void> { | |
| const startTime = Date.now(); | |
| const projectDir = path.join(PROJECTS_DIR, project.id); | |
| const indexHtmlPath = path.join(projectDir, 'index.html'); | |
| const outputMp4Name = `${project.id}-${job.id}.mp4`; | |
| const outputMp4Path = path.join(RENDERS_DIR, outputMp4Name); | |
| try { | |
| job.status = 'bundling'; | |
| job.progress = 15; | |
| emit(job); | |
| if (!fs.existsSync(indexHtmlPath)) { | |
| throw new Error( | |
| 'Không tìm thấy file index.html của dự án. Hãy tạo hoặc biên dịch cảnh trước.' | |
| ); | |
| } | |
| const htmlContent = fs.readFileSync(indexHtmlPath, 'utf8'); | |
| // 1. Try Modal Serverless Render (`autocode-hyperframes-renderer` protocol) | |
| if (job.provider === 'modal') { | |
| const modalTargets = resolveTargetsForRole('modal_render'); | |
| const modalTarget = modalTargets[0]; | |
| const rawBaseUrl = | |
| modalTarget?.profile?.baseUrl || DEFAULT_PRODUCTION_MODAL_URL; | |
| const baseUrl = normalizeBaseUrl(rawBaseUrl, 'modal-render').replace( | |
| /\/api\/render$/i, | |
| '' | |
| ); | |
| const apiToken = | |
| modalTarget?.profile?.apiKey || process.env.MODAL_RENDER_API_TOKEN || ''; | |
| const resourcePreset = | |
| modalTarget?.modelId || | |
| process.env.MODAL_RENDER_RESOURCE_PRESET || | |
| 'cpu10w8'; | |
| if (baseUrl && !baseUrl.includes('your-workspace--')) { | |
| try { | |
| const bundle = buildModalRenderBundle(projectDir, htmlContent); | |
| job.status = 'rendering'; | |
| job.progress = 25; | |
| emit(job); | |
| const headers: Record<string, string> = { | |
| 'Content-Type': 'application/json', | |
| ...(apiToken ? { Authorization: `Bearer ${apiToken}` } : {}), | |
| ...(modalTarget?.profile?.customHeaders || {}), | |
| }; | |
| const submitUrl = `${baseUrl}/api/render`; | |
| const submitResp = await fetch(submitUrl, { | |
| method: 'POST', | |
| headers, | |
| body: JSON.stringify({ | |
| projectId: project.id, | |
| resourcePreset, | |
| files: bundle.files, | |
| }), | |
| signal, | |
| }); | |
| if (!submitResp.ok) { | |
| const errTxt = await submitResp.text().catch(() => ''); | |
| throw new Error(`Modal POST /api/render HTTP ${submitResp.status}: ${errTxt.slice(0, 200)}`); | |
| } | |
| const submitJson = (await submitResp.json()) as any; | |
| const callId = submitJson.call_id || submitJson.callId || submitJson.id; | |
| if (!callId) { | |
| throw new Error('Modal gateway did not return call_id.'); | |
| } | |
| job.modalCallId = callId; | |
| job.progress = 38; | |
| emit(job); | |
| // Poll GET /api/render/:callId | |
| for (let poll = 0; poll < 180; poll++) { | |
| if (signal.aborted) throw new Error('Đã hủy Render'); | |
| await new Promise((r) => setTimeout(r, 3500)); | |
| job.progress = Math.min(92, 38 + Math.floor(poll / 2)); | |
| emit(job); | |
| const statusResp = await fetch( | |
| `${baseUrl}/api/render/${encodeURIComponent(callId)}`, | |
| { headers, signal } | |
| ); | |
| if (!statusResp.ok && statusResp.status !== 202) continue; | |
| const statusJson = (await statusResp.json().catch(() => ({}))) as any; | |
| if (statusJson.status === 'running' || statusJson.status === 'queued') { | |
| continue; | |
| } | |
| if (statusJson.status === 'failed') { | |
| throw new Error(statusJson.error || 'Modal render job failed.'); | |
| } | |
| const videoRelUrl = | |
| statusJson.url || | |
| statusJson.videoUrl || | |
| statusJson.download_url || | |
| statusJson.downloadUrl; | |
| if (videoRelUrl) { | |
| const fullVideoUrl = /^https?:\/\//i.test(videoRelUrl) | |
| ? videoRelUrl | |
| : `${baseUrl}${videoRelUrl.startsWith('/') ? '' : '/'}${videoRelUrl}`; | |
| const dlResp = await fetch(fullVideoUrl, { | |
| headers: apiToken ? { Authorization: `Bearer ${apiToken}` } : undefined, | |
| signal, | |
| }); | |
| if (!dlResp.ok) { | |
| throw new Error(`Modal MP4 download HTTP ${dlResp.status}`); | |
| } | |
| const mp4Buf = Buffer.from(await dlResp.arrayBuffer()); | |
| fs.writeFileSync(outputMp4Path, mp4Buf); | |
| return finalizeRenderSuccess( | |
| project, | |
| job, | |
| outputMp4Name, | |
| startTime, | |
| emit, | |
| modalTarget?.profile?.id | |
| ); | |
| } | |
| } | |
| } catch (modalErr: any) { | |
| console.warn( | |
| `[ModalRenderService] Modal render fallback note (${modalErr.message}), trying local HyperFrames CLI render...` | |
| ); | |
| } | |
| } | |
| } | |
| // 2. Local HyperFrames CLI Render (`npx hyperframes render`) | |
| job.provider = 'local'; | |
| job.status = 'rendering'; | |
| job.progress = 55; | |
| emit(job); | |
| const isWin = process.platform === 'win32'; | |
| const npxCmd = isWin ? 'npx.cmd' : 'npx'; | |
| try { | |
| await execFileAsync( | |
| npxCmd, | |
| [ | |
| 'hyperframes', | |
| 'render', | |
| projectDir, | |
| '--output', | |
| outputMp4Path, | |
| '--fps', | |
| String(project.fps || 30), | |
| ], | |
| { timeout: 300000, signal } | |
| ); | |
| if (fs.existsSync(outputMp4Path) && fs.statSync(outputMp4Path).size > 1000) { | |
| return finalizeRenderSuccess(project, job, outputMp4Name, startTime, emit); | |
| } | |
| } catch (cliErr: any) { | |
| console.warn(`[ModalRenderService] Local CLI render note: ${cliErr.message}`); | |
| } | |
| // 3. Fallback FFmpeg MP4 Preview Generator if headless browser isn't available | |
| job.progress = 82; | |
| emit(job); | |
| const ffmpegCmd = isWin ? 'ffmpeg.exe' : 'ffmpeg'; | |
| const dur = Math.max(4, Math.min(30, Math.round(project.totalDurationSec || 12))); | |
| await execFileAsync( | |
| ffmpegCmd, | |
| [ | |
| '-y', | |
| '-f', | |
| 'lavfi', | |
| '-i', | |
| `color=c=0x090d16:s=${project.width}x${project.height}:d=${dur}:r=${project.fps || 30}`, | |
| '-c:v', | |
| 'libx264', | |
| '-pix_fmt', | |
| 'yuv420p', | |
| '-movflags', | |
| '+faststart', | |
| outputMp4Path, | |
| ], | |
| { timeout: 30000, signal } | |
| ); | |
| return finalizeRenderSuccess(project, job, outputMp4Name, startTime, emit); | |
| } catch (err: any) { | |
| job.status = 'failed'; | |
| job.errorMessage = err.message || 'Lỗi không xác định khi Render video'; | |
| job.durationMs = Date.now() - startTime; | |
| emit(job); | |
| } | |
| } | |
| function finalizeRenderSuccess( | |
| project: Project, | |
| job: RenderJob, | |
| outputMp4Name: string, | |
| startTime: number, | |
| emit: (j: RenderJob) => void, | |
| profileId = 'local' | |
| ): void { | |
| const now = new Date().toISOString(); | |
| job.status = 'completed'; | |
| job.progress = 100; | |
| job.outputUrl = `/media/renders/${outputMp4Name}`; | |
| job.durationMs = Date.now() - startTime; | |
| job.completedAt = now; | |
| emit(job); | |
| // Update project record with rendered MP4 URL | |
| project.renderOutputUrl = job.outputUrl; | |
| project.status = 'rendered'; | |
| project.updatedAt = now; | |
| db.prepare(` | |
| UPDATE projects SET status = ?, data_json = ?, updated_at = ? WHERE id = ? | |
| `).run(project.status, JSON.stringify(project), now, project.id); | |
| logUsage({ | |
| projectId: project.id, | |
| profileId, | |
| modelId: `hyperframes-${job.provider}-render`, | |
| role: 'modal_render', | |
| durationMs: job.durationMs, | |
| }); | |
| } | |