mirror of
https://github.com/R0m1k3/Socialflow.git
synced 2026-10-16 03:39:15 +02:00
feat(reels): voix Gemini complète, sous-titres mot à mot et rendu de qualité
Service ffmpeg-api réécrit (ffmpeg-service/app/) : - Appels FFmpeg asynchrones : le service ne se fige plus pendant un rendu - Vidéo récupérée par téléchargement (GET /files/…) au lieu de base64 en JSON - Vraies erreurs HTTP ; échec explicite si la voix demandée est impossible - 30 voix Gemini + ton de lecture (dynamique, chaleureux, promo, calme), clé en en-tête, modèle configurable avec repli - Edge TTS 7 (minutage des mots restauré), secours en voix françaises - Voix traitée : filtre, compression, niveau constant ; musique bouclée et baissée automatiquement sous la voix ; mix final à -14 LUFS - Sous-titres calés mot à mot (Whisper pour Gemini et la voix d'origine, à la place de ffsubsync), style Montserrat, placés hors des boutons Reels - Vidéo : plus de retouche luminosité forcée, scaling lanczos, HDR iPhone converti, BT.709, AAC 48 kHz 192k ; la vidéo s'allonge si la voix dépasse - Grand logo de fin affiché après la voix ; FFmpeg 7.0.2 épinglé, polices et modèle Whisper intégrés à l'image ; tests pytest et ruff Application : - Sélecteur de voix partagé (4 pages) : moteur, 30 voix, ton, écoute - Reel images : minutage réel des mots, interrupteur voix respecté - sync-info ne génère plus de voix à chaque frappe (estimation locale) - Stabilisation désactivée par défaut, route /reels/preview inutilisée retirée - Log « [ReelQueue] Worker démarré » pour vérifier la version déployée Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018Ze4bs7tpF1KGWUk6ZZSZ4
This commit is contained in:
47 files changed
+2206
-2285
No files matched your search
@@ -6,11 +6,10 @@
|
||||
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
import * as musicMetadata from "music-metadata";
|
||||
import { bundle } from "@remotion/bundler";
|
||||
import { renderMedia, selectComposition } from "@remotion/renderer";
|
||||
import { imagesReelParamsSchema, type ImagesReelResult } from "@shared/reel";
|
||||
import { ffmpegService } from "../ffmpeg";
|
||||
import { ffmpegService, type TimedWord } from "../ffmpeg";
|
||||
import { generateVideoThumbnail } from "../thumbnail";
|
||||
import type { JobContext } from "./queue";
|
||||
import { resolveGeminiApiKey, resolveLogoPath } from "./assets";
|
||||
@@ -88,43 +87,31 @@ export function stripForTTS(text: string): string {
|
||||
.trim();
|
||||
}
|
||||
|
||||
/** Nombre de syllabes d'un mot français (groupes de voyelles). */
|
||||
function countSyllablesFr(word: string): number {
|
||||
const clean = word.replace(/[^a-zàâéèêëîïôùûüç]/gi, "").toLowerCase();
|
||||
if (!clean) return 1;
|
||||
return Math.max(1, clean.match(/[aeiouyàâéèêëîïôùûü]+/gi)?.length ?? 1);
|
||||
const EDGE_PUNCT = /^[.,!?;:…«»"'()\[\]]+|[.,!?;:…«»"'()\[\]]+$/g;
|
||||
|
||||
export interface WordTiming {
|
||||
word: string;
|
||||
startFrame: number;
|
||||
endFrame: number;
|
||||
}
|
||||
|
||||
const PUNCT_ONLY = /^[.,!?;:…\-—«»"''()\[\]]+$/;
|
||||
const EDGE_PUNCT = /^[.,!?;:…«»"''()\[\]]+|[.,!?;:…«»"''()\[\]]+$/g;
|
||||
|
||||
/**
|
||||
* Timings des mots prononcés (en images), répartis au prorata des syllabes.
|
||||
* Estimation provisoire : remplacée par les vrais timings de la voix au lot
|
||||
* « voix et sous-titres ».
|
||||
* Convertit le minutage réel des mots (en secondes, fourni par la voix) en
|
||||
* images. Chaque mot reste affiché jusqu'au début du suivant : pas de trou
|
||||
* pendant les respirations.
|
||||
*/
|
||||
export function computeWordTimings(
|
||||
displayText: string,
|
||||
audioDurationSeconds: number,
|
||||
fps: number,
|
||||
startFrame: number,
|
||||
): Array<{ word: string; startFrame: number; endFrame: number }> {
|
||||
const spokenWords = stripForTTS(displayText)
|
||||
.split(/\s+/)
|
||||
.filter((w) => w && !PUNCT_ONLY.test(w));
|
||||
if (spokenWords.length === 0) return [];
|
||||
|
||||
const cleanWords = spokenWords.map((w) => w.replace(EDGE_PUNCT, "") || w);
|
||||
const syllables = cleanWords.map(countSyllablesFr);
|
||||
const totalSyllables = syllables.reduce((a, b) => a + b, 0);
|
||||
const totalFrames = audioDurationSeconds * fps;
|
||||
|
||||
let currentFrame = startFrame;
|
||||
return cleanWords.map((word, i) => {
|
||||
const wordStart = currentFrame;
|
||||
currentFrame += Math.round((syllables[i] / totalSyllables) * totalFrames);
|
||||
return { word, startFrame: wordStart, endFrame: currentFrame };
|
||||
});
|
||||
export function toWordTimings(words: TimedWord[], fps: number): WordTiming[] {
|
||||
const timings = words
|
||||
.map((w) => ({ word: w.text.replace(EDGE_PUNCT, "") || w.text, start: w.start, end: w.end }))
|
||||
.filter((w) => w.word.trim());
|
||||
return timings.map((w, i) => ({
|
||||
word: w.word,
|
||||
startFrame: Math.round(w.start * fps),
|
||||
endFrame: Math.max(
|
||||
Math.round(w.start * fps) + 1,
|
||||
Math.round((i + 1 < timings.length ? timings[i + 1].start : w.end) * fps),
|
||||
),
|
||||
}));
|
||||
}
|
||||
|
||||
export async function runImagesReelJob({ job, progress }: JobContext): Promise<ImagesReelResult> {
|
||||
@@ -141,32 +128,27 @@ export async function runImagesReelJob({ job, progress }: JobContext): Promise<I
|
||||
|
||||
// --- Voix ---
|
||||
let audioUrl: string | undefined;
|
||||
let wordTimings: ReturnType<typeof computeWordTimings> | undefined;
|
||||
let wordTimings: WordTiming[] | undefined;
|
||||
let audioDuration = 0;
|
||||
|
||||
const ttsText = overlayText ? stripForTTS(overlayText) : "";
|
||||
if (overlayText && ttsText) {
|
||||
if (params.ttsEnabled && overlayText && ttsText) {
|
||||
await progress(15, "voice");
|
||||
const geminiApiKey = await resolveGeminiApiKey(params.ttsEngine);
|
||||
const tts = await ffmpegService.previewTTS(ttsText, params.ttsVoice, params.ttsEngine, geminiApiKey);
|
||||
if (!tts.success || !tts.audioBase64) {
|
||||
throw new Error(`La voix n'a pas pu être générée : ${tts.error ?? "réponse vide"}`);
|
||||
}
|
||||
const voice = await ffmpegService.previewVoice(ttsText, {
|
||||
voice: params.ttsVoice,
|
||||
engine: params.ttsEngine,
|
||||
style: params.ttsStyle,
|
||||
geminiApiKey: await resolveGeminiApiKey(params.ttsEngine),
|
||||
});
|
||||
for (const warning of voice.warnings) console.warn(`⚠️ [Reels] ${warning}`);
|
||||
|
||||
const audioFilename = `tts-${job.id}.mp3`;
|
||||
const audioPath = path.join(REMOTION_TEMP_DIR, audioFilename);
|
||||
const audioBuffer = Buffer.from(tts.audioBase64, "base64");
|
||||
await fs.promises.writeFile(audioPath, audioBuffer);
|
||||
await fs.promises.writeFile(audioPath, voice.audio);
|
||||
jobTempFiles.push(audioPath);
|
||||
audioUrl = localHttpUrl(`/uploads/temp/${audioFilename}`);
|
||||
|
||||
try {
|
||||
audioDuration = (await musicMetadata.parseFile(audioPath)).format.duration ?? 0;
|
||||
} catch {
|
||||
audioDuration = audioBuffer.length / 16000; // estimation à 128 kb/s
|
||||
}
|
||||
audioDuration = Math.max(audioDuration, ttsText.split(/\s+/).length * 0.35);
|
||||
wordTimings = computeWordTimings(overlayText, audioDuration, FPS, 0);
|
||||
audioDuration = voice.duration;
|
||||
wordTimings = toWordTimings(voice.words, FPS);
|
||||
}
|
||||
|
||||
// --- Durée : 25 à 30 s ---
|
||||
|
||||
@@ -94,6 +94,7 @@ export async function startReelWorker(): Promise<void> {
|
||||
console.error("❌ [ReelQueue] Récupération des jobs orphelins impossible :", error);
|
||||
}
|
||||
|
||||
console.log(`🎬 [ReelQueue] Worker démarré (traitements : ${Array.from(handlers.keys()).join(", ")})`);
|
||||
pollTimer = setInterval(kick, POLL_INTERVAL_MS);
|
||||
pollTimer.unref();
|
||||
kick();
|
||||
|
||||
@@ -30,14 +30,14 @@ export async function runVideoReelJob({ job, progress }: JobContext) {
|
||||
|
||||
await progress(15, "render");
|
||||
const startedAt = Date.now();
|
||||
const rendered = await ffmpegService.processReelFromUrl(resolveInternalUrl(media.originalUrl), {
|
||||
const rendered = await ffmpegService.renderReel(resolveInternalUrl(media.originalUrl), {
|
||||
text: params.overlayText,
|
||||
musicUrl,
|
||||
ttsEnabled: params.ttsEnabled,
|
||||
ttsVoice: params.ttsVoice,
|
||||
ttsEngine: params.ttsEngine,
|
||||
ttsStyle: params.ttsStyle,
|
||||
geminiApiKey,
|
||||
wordDuration: params.wordDuration,
|
||||
fontSize: params.fontSize,
|
||||
musicVolume: params.musicVolume,
|
||||
drawText: params.drawText,
|
||||
@@ -46,18 +46,10 @@ export async function runVideoReelJob({ job, progress }: JobContext) {
|
||||
storeName: params.storeName,
|
||||
enableEndingEffect: params.enableEndingEffect,
|
||||
});
|
||||
console.log(`⏱️ [Reels] FFmpeg : ${((Date.now() - startedAt) / 1000).toFixed(1)} s`);
|
||||
|
||||
if (!rendered.success || !rendered.videoBase64) {
|
||||
throw new Error(rendered.error || "Erreur de traitement vidéo FFmpeg");
|
||||
}
|
||||
if (rendered.ttsError) {
|
||||
// Voix demandée mais absente : ne jamais publier un Reel muet sans le dire
|
||||
throw new Error(`La voix n'a pas pu être générée : ${rendered.ttsError}`);
|
||||
}
|
||||
console.log(`⏱️ [Reels] Rendu : ${((Date.now() - startedAt) / 1000).toFixed(1)} s, vidéo de ${rendered.duration.toFixed(1)} s`);
|
||||
|
||||
await progress(65, "store");
|
||||
const videoBuffer = Buffer.from(rendered.videoBase64, "base64");
|
||||
const videoBuffer = rendered.video;
|
||||
const processedMedia = await storeRenderedVideo(job.userId, videoBuffer, `reel-${Date.now()}.mp4`);
|
||||
await storage.updatePostMedia(postId, [processedMedia.id]);
|
||||
|
||||
|
||||
Reference in new issue
Block a user