feat: implement FastAPI service for video processing with TTS, synchronized subtitles, and stabilization.

This commit is contained in:
Michael committed 2026-03-03 12:08:28 +01:00
1 parent 4e189e7797
commit b4e48a1f0e
4 files changed
+314 -216

No files matched your search

+182 -178
View File
@@ -18,7 +18,7 @@ export default function CalendarView() {
const [editDialogOpen, setEditDialogOpen] = useState(false); const [editDialogOpen, setEditDialogOpen] = useState(false);
const [selectedPost, setSelectedPost] = useState<any>(null); const [selectedPost, setSelectedPost] = useState<any>(null);
const [previewModalOpen, setPreviewModalOpen] = useState(false); const [previewModalOpen, setPreviewModalOpen] = useState(false);
const [previewData, setPreviewData] = useState<{ postText: string; mediaIds: string[]; allMedia: Media[] }>({ postText: '', mediaIds: [], allMedia: [] }); const [previewData, setPreviewData] = useState<{ postText: string; mediaIds: string[]; allMedia: Media[]; generationStatus?: string; generationProgress?: number }>({ postText: '', mediaIds: [], allMedia: [] });
const { toast } = useToast(); const { toast } = useToast();
const isDesktop = useMediaQuery("(min-width: 768px)"); const isDesktop = useMediaQuery("(min-width: 768px)");
@@ -28,7 +28,7 @@ export default function CalendarView() {
}); });
const deletePostMutation = useMutation({ const deletePostMutation = useMutation({
mutationFn: (postId: string) => mutationFn: (postId: string) =>
apiRequest('DELETE', `/api/scheduled-posts/${postId}`, {}), apiRequest('DELETE', `/api/scheduled-posts/${postId}`, {}),
onSuccess: () => { onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['/api/scheduled-posts'] }); queryClient.invalidateQueries({ queryKey: ['/api/scheduled-posts'] });
@@ -61,26 +61,28 @@ export default function CalendarView() {
const handlePreviewPost = async (scheduledPost: any, e?: React.MouseEvent) => { const handlePreviewPost = async (scheduledPost: any, e?: React.MouseEvent) => {
if (e) e.stopPropagation(); if (e) e.stopPropagation();
try { try {
const response = await fetch(`/api/posts/${scheduledPost.postId}`, { const response = await fetch(`/api/posts/${scheduledPost.postId}`, {
credentials: "include", credentials: "include",
}); });
if (!response.ok) { if (!response.ok) {
throw new Error("Failed to fetch post"); throw new Error("Failed to fetch post");
} }
const postWithMedia = await response.json(); const postWithMedia = await response.json();
const mediaIds = postWithMedia.media?.map((m: Media) => m.id) || []; const mediaIds = postWithMedia.media?.map((m: Media) => m.id) || [];
const allMedia = postWithMedia.media || []; const allMedia = postWithMedia.media || [];
setPreviewData({ setPreviewData({
postText: postWithMedia.post.content || '', postText: postWithMedia.post.content || '',
mediaIds: mediaIds, mediaIds: mediaIds,
allMedia: allMedia, allMedia: allMedia,
generationStatus: postWithMedia.post.generationStatus,
generationProgress: postWithMedia.post.generationProgress,
}); });
setPreviewModalOpen(true); setPreviewModalOpen(true);
} catch (error) { } catch (error) {
toast({ toast({
@@ -111,11 +113,11 @@ export default function CalendarView() {
return (scheduledPosts || []).filter(post => { return (scheduledPosts || []).filter(post => {
if (!post.scheduledAt) return false; if (!post.scheduledAt) return false;
const postDate = new Date(post.scheduledAt); const postDate = new Date(post.scheduledAt);
// Compare using local date components to avoid timezone issues // Compare using local date components to avoid timezone issues
return postDate.getFullYear() === date.getFullYear() && return postDate.getFullYear() === date.getFullYear() &&
postDate.getMonth() === date.getMonth() && postDate.getMonth() === date.getMonth() &&
postDate.getDate() === date.getDate(); postDate.getDate() === date.getDate();
}); });
}; };
@@ -181,9 +183,9 @@ export default function CalendarView() {
</div> </div>
</div> </div>
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">
<Button <Button
variant="outline" variant="outline"
size="sm" size="sm"
onClick={goToPreviousMonth} onClick={goToPreviousMonth}
className="rounded-xl" className="rounded-xl"
data-testid="button-prev-month" data-testid="button-prev-month"
@@ -194,9 +196,9 @@ export default function CalendarView() {
<span className="text-sm font-semibold text-foreground min-w-[140px] text-center px-4 py-2 bg-muted/30 rounded-xl"> <span className="text-sm font-semibold text-foreground min-w-[140px] text-center px-4 py-2 bg-muted/30 rounded-xl">
{monthNames[currentDate.getMonth()]} {currentDate.getFullYear()} {monthNames[currentDate.getMonth()]} {currentDate.getFullYear()}
</span> </span>
<Button <Button
variant="outline" variant="outline"
size="sm" size="sm"
onClick={goToNextMonth} onClick={goToNextMonth}
className="rounded-xl" className="rounded-xl"
data-testid="button-next-month" data-testid="button-next-month"
@@ -219,192 +221,192 @@ export default function CalendarView() {
</div> </div>
<div className="grid grid-cols-7 gap-2"> <div className="grid grid-cols-7 gap-2">
{days.map((day, index) => ( {days.map((day, index) => (
<div <div
key={index} key={index}
className={` className={`
bg-card border border-border/50 rounded-xl p-4 min-h-[140px] transition-all hover:shadow-md bg-card border border-border/50 rounded-xl p-4 min-h-[140px] transition-all hover:shadow-md
${isToday(day.date) ? "ring-2 ring-primary shadow-lg" : ""} ${isToday(day.date) ? "ring-2 ring-primary shadow-lg" : ""}
${!day.isCurrentMonth ? "opacity-40" : ""} ${!day.isCurrentMonth ? "opacity-40" : ""}
`} `}
data-testid={`calendar-day-${index}`} data-testid={`calendar-day-${index}`}
> >
<div className="flex items-center justify-between mb-3"> <div className="flex items-center justify-between mb-3">
<span <span
className={` className={`
text-sm font-semibold text-sm font-semibold
${!day.isCurrentMonth ? "text-muted-foreground" : "text-foreground"} ${!day.isCurrentMonth ? "text-muted-foreground" : "text-foreground"}
${isToday(day.date) ? "text-primary" : ""} ${isToday(day.date) ? "text-primary" : ""}
`} `}
> >
{day.date.getDate()} {day.date.getDate()}
</span>
{isToday(day.date) && (
<span className="text-[10px] bg-gradient-to-r from-primary to-secondary text-white px-2 py-0.5 rounded-full font-semibold">
Aujourd'hui
</span> </span>
)} {isToday(day.date) && (
</div> <span className="text-[10px] bg-gradient-to-r from-primary to-secondary text-white px-2 py-0.5 rounded-full font-semibold">
Aujourd'hui
{(() => { </span>
if (!day.isCurrentMonth) return null; )}
const postsForDay = getPostsForDate(day.date); </div>
if (postsForDay.length === 0) return null;
{(() => {
return ( if (!day.isCurrentMonth) return null;
<div className="space-y-2"> const postsForDay = getPostsForDate(day.date);
{postsForDay.slice(0, 2).map((post: any, idx) => { if (postsForDay.length === 0) return null;
const time = post.scheduledAt ? new Date(post.scheduledAt).toLocaleTimeString('fr-FR', { hour: '2-digit', minute: '2-digit' }) : '';
const isPending = !post.publishedAt; return (
const isPublished = !!post.publishedAt; <div className="space-y-2">
const pageName = post.page?.pageName || 'Page inconnue'; {postsForDay.slice(0, 2).map((post: any, idx) => {
const platform = post.page?.platform || 'facebook'; const time = post.scheduledAt ? new Date(post.scheduledAt).toLocaleTimeString('fr-FR', { hour: '2-digit', minute: '2-digit' }) : '';
const PlatformIcon = platform === 'instagram' ? SiInstagram : SiFacebook; const isPending = !post.publishedAt;
const isPublished = !!post.publishedAt;
return ( const pageName = post.page?.pageName || 'Page inconnue';
<div const platform = post.page?.platform || 'facebook';
key={idx} const PlatformIcon = platform === 'instagram' ? SiInstagram : SiFacebook;
className={`
return (
<div
key={idx}
className={`
px-3 py-2 rounded-lg text-xs transition-all font-medium shadow-sm group relative px-3 py-2 rounded-lg text-xs transition-all font-medium shadow-sm group relative
${isPending ? 'bg-blue-500/20 text-blue-600 hover:bg-blue-500/30' : ''} ${isPending ? 'bg-blue-500/20 text-blue-600 hover:bg-blue-500/30' : ''}
${isPublished ? 'bg-green-500/20 text-green-600 hover:bg-green-500/30' : ''} ${isPublished ? 'bg-green-500/20 text-green-600 hover:bg-green-500/30' : ''}
`} `}
data-testid={`calendar-post-${post.id}`} data-testid={`calendar-post-${post.id}`}
> >
<div className="flex items-start justify-between gap-2"> <div className="flex items-start justify-between gap-2">
<div className="flex-1 min-w-0"> <div className="flex-1 min-w-0">
<div className="flex items-center gap-1 font-semibold"> <div className="flex items-center gap-1 font-semibold">
{getPostTypeIcon(post.postType)} {getPostTypeIcon(post.postType)}
<span>{time}</span> <span>{time}</span>
</div>
<div className="flex items-center gap-1 truncate opacity-90">
<PlatformIcon className="w-3 h-3 flex-shrink-0" />
<span className="truncate">{pageName}</span>
</div>
</div> </div>
<div className="flex items-center gap-1 truncate opacity-90"> <div className="flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
<PlatformIcon className="w-3 h-3 flex-shrink-0" /> <button
<span className="truncate">{pageName}</span> onClick={(e) => handlePreviewPost(post, e)}
className={`p-1 rounded ${isPending ? 'hover:bg-blue-500/20' : 'hover:bg-green-500/20'}`}
data-testid={`button-preview-post-${post.id}`}
title="Prévisualiser"
>
<Eye className={`w-3 h-3 ${isPending ? 'text-blue-500' : 'text-green-500'}`} />
</button>
{isPending && (
<>
<button
onClick={(e) => handleEditPost(post, e)}
className="p-1 hover:bg-blue-500/20 rounded"
data-testid={`button-edit-post-${post.id}`}
title="Modifier"
>
<Edit className="w-3 h-3 text-blue-500" />
</button>
<button
onClick={(e) => handleDeletePost(post.id, e)}
className="p-1 hover:bg-red-500/20 rounded"
data-testid={`button-delete-post-${post.id}`}
title="Supprimer"
>
<Trash2 className="w-3 h-3 text-red-500" />
</button>
</>
)}
</div> </div>
</div> </div>
<div className="flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
<button
onClick={(e) => handlePreviewPost(post, e)}
className={`p-1 rounded ${isPending ? 'hover:bg-blue-500/20' : 'hover:bg-green-500/20'}`}
data-testid={`button-preview-post-${post.id}`}
title="Prévisualiser"
>
<Eye className={`w-3 h-3 ${isPending ? 'text-blue-500' : 'text-green-500'}`} />
</button>
{isPending && (
<>
<button
onClick={(e) => handleEditPost(post, e)}
className="p-1 hover:bg-blue-500/20 rounded"
data-testid={`button-edit-post-${post.id}`}
title="Modifier"
>
<Edit className="w-3 h-3 text-blue-500" />
</button>
<button
onClick={(e) => handleDeletePost(post.id, e)}
className="p-1 hover:bg-red-500/20 rounded"
data-testid={`button-delete-post-${post.id}`}
title="Supprimer"
>
<Trash2 className="w-3 h-3 text-red-500" />
</button>
</>
)}
</div>
</div> </div>
</div> );
); })}
})} {postsForDay.length > 2 && (
{postsForDay.length > 2 && ( <Popover>
<Popover> <PopoverTrigger asChild>
<PopoverTrigger asChild> <button
<button className="w-full text-left text-[11px] text-primary hover:text-primary/80 pl-2 font-medium transition-colors flex items-center gap-1"
className="w-full text-left text-[11px] text-primary hover:text-primary/80 pl-2 font-medium transition-colors flex items-center gap-1" data-testid="button-show-more-posts"
data-testid="button-show-more-posts" >
> <MoreHorizontal className="w-3 h-3" />
<MoreHorizontal className="w-3 h-3" /> +{postsForDay.length - 2} autre(s)
+{postsForDay.length - 2} autre(s) </button>
</button> </PopoverTrigger>
</PopoverTrigger> <PopoverContent className="w-80 p-3" align="start">
<PopoverContent className="w-80 p-3" align="start"> <div className="space-y-2">
<div className="space-y-2"> <h4 className="font-semibold text-sm mb-3">
<h4 className="font-semibold text-sm mb-3"> Tous les posts du {day.date.getDate()} {monthNames[day.date.getMonth()]}
Tous les posts du {day.date.getDate()} {monthNames[day.date.getMonth()]} </h4>
</h4> {postsForDay.slice(2).map((post: any, idx) => {
{postsForDay.slice(2).map((post: any, idx) => { const time = post.scheduledAt ? new Date(post.scheduledAt).toLocaleTimeString('fr-FR', { hour: '2-digit', minute: '2-digit' }) : '';
const time = post.scheduledAt ? new Date(post.scheduledAt).toLocaleTimeString('fr-FR', { hour: '2-digit', minute: '2-digit' }) : ''; const isPending = !post.publishedAt;
const isPending = !post.publishedAt; const isPublished = !!post.publishedAt;
const isPublished = !!post.publishedAt; const pageName = post.page?.pageName || 'Page inconnue';
const pageName = post.page?.pageName || 'Page inconnue'; const platform = post.page?.platform || 'facebook';
const platform = post.page?.platform || 'facebook'; const PlatformIcon = platform === 'instagram' ? SiInstagram : SiFacebook;
const PlatformIcon = platform === 'instagram' ? SiInstagram : SiFacebook;
return (
return ( <div
<div key={idx}
key={idx} className={`
className={`
px-3 py-2 rounded-lg text-xs transition-all font-medium shadow-sm group relative px-3 py-2 rounded-lg text-xs transition-all font-medium shadow-sm group relative
${isPending ? 'bg-blue-500/20 text-blue-600 hover:bg-blue-500/30' : ''} ${isPending ? 'bg-blue-500/20 text-blue-600 hover:bg-blue-500/30' : ''}
${isPublished ? 'bg-green-500/20 text-green-600 hover:bg-green-500/30' : ''} ${isPublished ? 'bg-green-500/20 text-green-600 hover:bg-green-500/30' : ''}
`} `}
data-testid={`popover-post-${post.id}`} data-testid={`popover-post-${post.id}`}
> >
<div className="flex items-start justify-between gap-2"> <div className="flex items-start justify-between gap-2">
<div className="flex-1 min-w-0"> <div className="flex-1 min-w-0">
<div className="flex items-center gap-1 font-semibold"> <div className="flex items-center gap-1 font-semibold">
{getPostTypeIcon(post.postType)} {getPostTypeIcon(post.postType)}
<span>{time}</span> <span>{time}</span>
</div>
<div className="flex items-center gap-1 truncate opacity-90">
<PlatformIcon className="w-3 h-3 flex-shrink-0" />
<span className="truncate">{pageName}</span>
</div>
</div> </div>
<div className="flex items-center gap-1 truncate opacity-90"> <div className="flex gap-1">
<PlatformIcon className="w-3 h-3 flex-shrink-0" /> <button
<span className="truncate">{pageName}</span> onClick={(e) => handlePreviewPost(post, e)}
className={`p-1 rounded ${isPending ? 'hover:bg-blue-500/20' : 'hover:bg-green-500/20'}`}
data-testid={`button-preview-popover-post-${post.id}`}
title="Prévisualiser"
>
<Eye className={`w-3 h-3 ${isPending ? 'text-blue-500' : 'text-green-500'}`} />
</button>
{isPending && (
<>
<button
onClick={(e) => handleEditPost(post, e)}
className="p-1 hover:bg-blue-500/20 rounded"
data-testid={`button-edit-popover-post-${post.id}`}
title="Modifier"
>
<Edit className="w-3 h-3 text-blue-500" />
</button>
<button
onClick={(e) => handleDeletePost(post.id, e)}
className="p-1 hover:bg-red-500/20 rounded"
data-testid={`button-delete-popover-post-${post.id}`}
title="Supprimer"
>
<Trash2 className="w-3 h-3 text-red-500" />
</button>
</>
)}
</div> </div>
</div> </div>
<div className="flex gap-1">
<button
onClick={(e) => handlePreviewPost(post, e)}
className={`p-1 rounded ${isPending ? 'hover:bg-blue-500/20' : 'hover:bg-green-500/20'}`}
data-testid={`button-preview-popover-post-${post.id}`}
title="Prévisualiser"
>
<Eye className={`w-3 h-3 ${isPending ? 'text-blue-500' : 'text-green-500'}`} />
</button>
{isPending && (
<>
<button
onClick={(e) => handleEditPost(post, e)}
className="p-1 hover:bg-blue-500/20 rounded"
data-testid={`button-edit-popover-post-${post.id}`}
title="Modifier"
>
<Edit className="w-3 h-3 text-blue-500" />
</button>
<button
onClick={(e) => handleDeletePost(post.id, e)}
className="p-1 hover:bg-red-500/20 rounded"
data-testid={`button-delete-popover-post-${post.id}`}
title="Supprimer"
>
<Trash2 className="w-3 h-3 text-red-500" />
</button>
</>
)}
</div>
</div> </div>
</div> );
); })}
})} </div>
</div> </PopoverContent>
</PopoverContent> </Popover>
</Popover> )}
)} </div>
</div> );
); })()}
})()} </div>
</div> ))}
))} </div>
</div>
<div className="mt-8 flex items-center justify-center gap-8 flex-wrap"> <div className="mt-8 flex items-center justify-center gap-8 flex-wrap">
<div className="flex items-center gap-3"> <div className="flex items-center gap-3">
@@ -438,9 +440,11 @@ export default function CalendarView() {
postText={previewData.postText} postText={previewData.postText}
selectedMedia={previewData.mediaIds} selectedMedia={previewData.mediaIds}
mediaList={previewData.allMedia} mediaList={previewData.allMedia}
onPublish={() => {}} onPublish={() => { }}
isPublishing={false} isPublishing={false}
readOnly={true} readOnly={true}
generationStatus={previewData.generationStatus}
generationProgress={previewData.generationProgress}
/> />
</div> </div>
); );
+89 -32
View File
@@ -2,7 +2,7 @@ import { useState, useEffect, useRef } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '@/components/ui/dialog'; import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { ChevronLeft, ChevronRight, Send, Facebook, Instagram, Heart, MessageCircle, Share2, Bookmark } from 'lucide-react'; import { ChevronLeft, ChevronRight, Send, Facebook, Instagram, Heart, MessageCircle, Share2, Bookmark, Loader2, Video } from 'lucide-react';
import type { Media } from '@shared/schema'; import type { Media } from '@shared/schema';
import { removeHashtags } from '@shared/emoji'; import { removeHashtags } from '@shared/emoji';
import { EmojiText } from '@/components/emoji-text'; import { EmojiText } from '@/components/emoji-text';
@@ -16,6 +16,8 @@ interface PreviewModalProps {
onPublish: () => void; onPublish: () => void;
isPublishing: boolean; isPublishing: boolean;
readOnly?: boolean; readOnly?: boolean;
generationStatus?: string;
generationProgress?: number;
} }
type PreviewFormat = 'facebook-feed' | 'facebook-story' | 'instagram-feed' | 'instagram-story'; type PreviewFormat = 'facebook-feed' | 'facebook-story' | 'instagram-feed' | 'instagram-story';
@@ -28,7 +30,9 @@ export function PreviewModal({
mediaList, mediaList,
onPublish, onPublish,
isPublishing, isPublishing,
readOnly = false readOnly = false,
generationStatus,
generationProgress
}: PreviewModalProps) { }: PreviewModalProps) {
const [previewFormat, setPreviewFormat] = useState<PreviewFormat>('facebook-feed'); const [previewFormat, setPreviewFormat] = useState<PreviewFormat>('facebook-feed');
const [currentPhotoIndex, setCurrentPhotoIndex] = useState(0); const [currentPhotoIndex, setCurrentPhotoIndex] = useState(0);
@@ -68,7 +72,7 @@ export function PreviewModal({
const renderMedia = (media: Media, className: string = "w-full h-auto") => { const renderMedia = (media: Media, className: string = "w-full h-auto") => {
const url = getMediaUrl(media); const url = getMediaUrl(media);
if (media.type === 'video') { if (media.type === 'video') {
return ( return (
<video <video
@@ -80,7 +84,7 @@ export function PreviewModal({
/> />
); );
} }
return ( return (
<img <img
src={url} src={url}
@@ -110,6 +114,25 @@ export function PreviewModal({
</div> </div>
)} )}
{/* Is Generating Status Overlay */}
{orderedMedia.length === 0 && (generationStatus === 'processing' || generationStatus === 'pending') && (
<div className="relative bg-black aspect-video flex flex-col items-center justify-center text-white">
<Loader2 className="w-10 h-10 animate-spin text-primary mb-4" />
<h3 className="text-lg font-semibold">Génération vidéo en cours...</h3>
<p className="text-sm text-gray-300 mt-2 text-center px-4">
FFmpeg assemble votre vidéo. <br /> Elle s'affichera ici une fois terminée.
</p>
{generationProgress !== undefined && (
<div className="w-64 h-2 bg-gray-800 rounded-full mt-4 overflow-hidden">
<div
className="h-full bg-primary transition-all duration-500 ease-out"
style={{ width: `${generationProgress}%` }}
/>
</div>
)}
</div>
)}
{/* Media Carousel */} {/* Media Carousel */}
{orderedMedia.length > 0 && ( {orderedMedia.length > 0 && (
<div className="relative bg-black"> <div className="relative bg-black">
@@ -135,9 +158,8 @@ export function PreviewModal({
<button <button
key={idx} key={idx}
onClick={() => goToPhoto(idx)} onClick={() => goToPhoto(idx)}
className={`w-2 h-2 rounded-full transition-colors ${ className={`w-2 h-2 rounded-full transition-colors ${idx === currentPhotoIndex ? 'bg-white' : 'bg-white/50'
idx === currentPhotoIndex ? 'bg-white' : 'bg-white/50' }`}
}`}
data-testid={`button-photo-indicator-${idx}`} data-testid={`button-photo-indicator-${idx}`}
/> />
))} ))}
@@ -168,6 +190,23 @@ export function PreviewModal({
</div> </div>
</div> </div>
{/* Is Generating Status Overlay */}
{orderedMedia.length === 0 && (generationStatus === 'processing' || generationStatus === 'pending') && (
<div className="relative bg-black aspect-square flex flex-col items-center justify-center text-white">
<Loader2 className="w-10 h-10 animate-spin text-primary mb-4" />
<h3 className="text-lg font-semibold">Génération en cours...</h3>
<p className="text-sm text-gray-300 mt-2">Veuillez patienter.</p>
{generationProgress !== undefined && (
<div className="w-48 h-2 bg-gray-800 rounded-full mt-4 overflow-hidden">
<div
className="h-full bg-primary transition-all duration-500 ease-out"
style={{ width: `${generationProgress}%` }}
/>
</div>
)}
</div>
)}
{/* Media Carousel */} {/* Media Carousel */}
{orderedMedia.length > 0 && ( {orderedMedia.length > 0 && (
<div className="relative bg-black aspect-square"> <div className="relative bg-black aspect-square">
@@ -193,9 +232,8 @@ export function PreviewModal({
<button <button
key={idx} key={idx}
onClick={() => goToPhoto(idx)} onClick={() => goToPhoto(idx)}
className={`h-1 flex-1 transition-colors rounded ${ className={`h-1 flex-1 transition-colors rounded ${idx === currentPhotoIndex ? 'bg-white' : 'bg-white/50'
idx === currentPhotoIndex ? 'bg-white' : 'bg-white/50' }`}
}`}
style={{ width: '40px' }} style={{ width: '40px' }}
data-testid={`button-photo-indicator-${idx}`} data-testid={`button-photo-indicator-${idx}`}
/> />
@@ -239,12 +277,12 @@ export function PreviewModal({
for (const word of words) { for (const word of words) {
const testLine = currentLine ? `${currentLine} ${word}` : word; const testLine = currentLine ? `${currentLine} ${word}` : word;
const metrics = ctx.measureText(testLine); const metrics = ctx.measureText(testLine);
if (metrics.width > maxWidth && currentLine) { if (metrics.width > maxWidth && currentLine) {
// Current line would exceed width, push it and start new line // Current line would exceed width, push it and start new line
lines.push(currentLine); lines.push(currentLine);
currentLine = word; currentLine = word;
// Check if the word itself is too long for a single line // Check if the word itself is too long for a single line
const wordMetrics = ctx.measureText(word); const wordMetrics = ctx.measureText(word);
if (wordMetrics.width > maxWidth) { if (wordMetrics.width > maxWidth) {
@@ -266,7 +304,7 @@ export function PreviewModal({
currentLine = testLine; currentLine = testLine;
} }
} }
if (currentLine) { if (currentLine) {
lines.push(currentLine); lines.push(currentLine);
} }
@@ -280,12 +318,12 @@ export function PreviewModal({
const breakLongWord = (ctx: CanvasRenderingContext2D, word: string, maxWidth: number): string[] => { const breakLongWord = (ctx: CanvasRenderingContext2D, word: string, maxWidth: number): string[] => {
const chunks: string[] = []; const chunks: string[] = [];
let currentChunk = ''; let currentChunk = '';
for (let i = 0; i < word.length; i++) { for (let i = 0; i < word.length; i++) {
const char = word[i]; const char = word[i];
const testChunk = currentChunk + char; const testChunk = currentChunk + char;
const metrics = ctx.measureText(testChunk); const metrics = ctx.measureText(testChunk);
if (metrics.width > maxWidth && currentChunk) { if (metrics.width > maxWidth && currentChunk) {
chunks.push(currentChunk); chunks.push(currentChunk);
currentChunk = char; currentChunk = char;
@@ -293,11 +331,11 @@ export function PreviewModal({
currentChunk = testChunk; currentChunk = testChunk;
} }
} }
if (currentChunk) { if (currentChunk) {
chunks.push(currentChunk); chunks.push(currentChunk);
} }
return chunks.length > 0 ? chunks : [word]; return chunks.length > 0 ? chunks : [word];
}; };
@@ -305,31 +343,31 @@ export function PreviewModal({
const MIN_FONT_SIZE = 12; const MIN_FONT_SIZE = 12;
const MAX_FONT_SIZE = 72; const MAX_FONT_SIZE = 72;
const LINE_HEIGHT_MULTIPLIER = 1.2; const LINE_HEIGHT_MULTIPLIER = 1.2;
let fontSize = MAX_FONT_SIZE; let fontSize = MAX_FONT_SIZE;
let lines: string[] = []; let lines: string[] = [];
let totalTextHeight = 0; let totalTextHeight = 0;
while (fontSize >= MIN_FONT_SIZE) { while (fontSize >= MIN_FONT_SIZE) {
lines = wrapText(text, containerWidth, fontSize); lines = wrapText(text, containerWidth, fontSize);
const lineHeight = fontSize * LINE_HEIGHT_MULTIPLIER; const lineHeight = fontSize * LINE_HEIGHT_MULTIPLIER;
totalTextHeight = lines.length * lineHeight; totalTextHeight = lines.length * lineHeight;
if (totalTextHeight <= containerHeight) { if (totalTextHeight <= containerHeight) {
break; break;
} }
fontSize -= 2; fontSize -= 2;
} }
let isTruncated = false; let isTruncated = false;
if (fontSize < MIN_FONT_SIZE) { if (fontSize < MIN_FONT_SIZE) {
fontSize = MIN_FONT_SIZE; fontSize = MIN_FONT_SIZE;
lines = wrapText(text, containerWidth, fontSize); lines = wrapText(text, containerWidth, fontSize);
const lineHeight = fontSize * LINE_HEIGHT_MULTIPLIER; const lineHeight = fontSize * LINE_HEIGHT_MULTIPLIER;
totalTextHeight = lines.length * lineHeight; totalTextHeight = lines.length * lineHeight;
const maxLines = Math.floor(containerHeight / lineHeight); const maxLines = Math.floor(containerHeight / lineHeight);
if (lines.length > maxLines) { if (lines.length > maxLines) {
lines = lines.slice(0, maxLines); lines = lines.slice(0, maxLines);
@@ -348,12 +386,12 @@ export function PreviewModal({
const STORY_HEIGHT = 640; const STORY_HEIGHT = 640;
const TEXT_BOX_HEIGHT_RATIO = 0.25; const TEXT_BOX_HEIGHT_RATIO = 0.25;
const PADDING = 16; const PADDING = 16;
const textBoxHeight = STORY_HEIGHT * TEXT_BOX_HEIGHT_RATIO; const textBoxHeight = STORY_HEIGHT * TEXT_BOX_HEIGHT_RATIO;
const maxTextWidth = STORY_WIDTH - (PADDING * 2); const maxTextWidth = STORY_WIDTH - (PADDING * 2);
const maxTextHeight = textBoxHeight - (PADDING * 2); const maxTextHeight = textBoxHeight - (PADDING * 2);
const { fontSize, lines } = postText const { fontSize, lines } = postText
? calculateAdaptiveFontSize(postText, maxTextWidth, maxTextHeight) ? calculateAdaptiveFontSize(postText, maxTextWidth, maxTextHeight)
: { fontSize: 24, lines: [] }; : { fontSize: 24, lines: [] };
@@ -375,6 +413,26 @@ export function PreviewModal({
</div> </div>
</div> </div>
{/* Is Generating Status Overlay */}
{orderedMedia.length === 0 && (generationStatus === 'processing' || generationStatus === 'pending') && (
<div className="relative w-full h-full flex flex-col items-center justify-center text-white bg-black">
<Loader2 className="w-12 h-12 animate-spin text-primary mb-6" />
<h3 className="text-2xl font-semibold px-8 text-center drop-shadow-md">Création de votre Reel...</h3>
<p className="text-base text-gray-300 mt-4 text-center px-10 drop-shadow-md">
Montage vidéo en cours via FFmpeg. Le résultat apparaîtra ici lorsqu'il sera prêt (environ 1-2 min).
</p>
{generationProgress !== undefined && (
<div className="w-64 h-3 bg-gray-800 rounded-full mt-8 overflow-hidden shadow-inner">
<div
className="h-full bg-primary transition-all duration-500 ease-out"
style={{ width: `${generationProgress}%` }}
/>
</div>
)}
<div className="mt-2 text-primary font-medium">{generationProgress || 0}%</div>
</div>
)}
{/* Media */} {/* Media */}
{orderedMedia.length > 0 && ( {orderedMedia.length > 0 && (
<div className="relative w-full h-full"> <div className="relative w-full h-full">
@@ -386,9 +444,8 @@ export function PreviewModal({
<button <button
key={idx} key={idx}
onClick={() => goToPhoto(idx)} onClick={() => goToPhoto(idx)}
className={`h-1 flex-1 transition-colors rounded-full ${ className={`h-1 flex-1 transition-colors rounded-full ${idx === currentPhotoIndex ? 'bg-white' : 'bg-white/50'
idx === currentPhotoIndex ? 'bg-white' : 'bg-white/50' }`}
}`}
data-testid={`button-photo-indicator-${idx}`} data-testid={`button-photo-indicator-${idx}`}
/> />
))} ))}
@@ -409,17 +466,17 @@ export function PreviewModal({
</button> </button>
</> </>
)} )}
{/* Text overlay box - matching exact server rendering */} {/* Text overlay box - matching exact server rendering */}
{postText && ( {postText && (
<div <div
className="absolute bottom-0 left-0 right-0 flex items-center justify-center z-10" className="absolute bottom-0 left-0 right-0 flex items-center justify-center z-10"
style={{ height: `${TEXT_BOX_HEIGHT_RATIO * 100}%` }} style={{ height: `${TEXT_BOX_HEIGHT_RATIO * 100}%` }}
> >
<div className="absolute inset-0 bg-black/60" /> <div className="absolute inset-0 bg-black/60" />
<div <div
className="relative text-white text-center font-bold leading-tight" className="relative text-white text-center font-bold leading-tight"
style={{ style={{
fontSize: `${fontSize}px`, fontSize: `${fontSize}px`,
padding: `${PADDING}px`, padding: `${PADDING}px`,
lineHeight: '1.2' lineHeight: '1.2'
+5 -1
View File
@@ -20,7 +20,7 @@ type ScheduledPostWithRelations = ScheduledPost & {
export default function History() { export default function History() {
const [sidebarOpen, setSidebarOpen] = useState(false); const [sidebarOpen, setSidebarOpen] = useState(false);
const [previewModalOpen, setPreviewModalOpen] = useState(false); const [previewModalOpen, setPreviewModalOpen] = useState(false);
const [previewData, setPreviewData] = useState<{ postText: string; mediaIds: string[]; allMedia: Media[] }>({ postText: '', mediaIds: [], allMedia: [] }); const [previewData, setPreviewData] = useState<{ postText: string; mediaIds: string[]; allMedia: Media[]; generationStatus?: string; generationProgress?: number }>({ postText: '', mediaIds: [], allMedia: [] });
const { toast } = useToast(); const { toast } = useToast();
const { data: scheduledPosts = [], isLoading } = useQuery<ScheduledPostWithRelations[]>({ const { data: scheduledPosts = [], isLoading } = useQuery<ScheduledPostWithRelations[]>({
@@ -52,6 +52,8 @@ export default function History() {
postText: postWithMedia.post.content || '', postText: postWithMedia.post.content || '',
mediaIds: mediaIds, mediaIds: mediaIds,
allMedia: allMedia, allMedia: allMedia,
generationStatus: postWithMedia.post.generationStatus,
generationProgress: postWithMedia.post.generationProgress,
}); });
setPreviewModalOpen(true); setPreviewModalOpen(true);
@@ -241,6 +243,8 @@ export default function History() {
onPublish={() => { }} onPublish={() => { }}
isPublishing={false} isPublishing={false}
readOnly={true} readOnly={true}
generationStatus={previewData.generationStatus}
generationProgress={previewData.generationProgress}
/> />
</main> </main>
</div> </div>
+38 -5
View File
@@ -572,6 +572,30 @@ async def process_reel(request: ReelRequest, x_api_key: str = Header(None)):
else: else:
raise HTTPException(status_code=400, detail="No video source provided") raise HTTPException(status_code=400, detail="No video source provided")
# --- Get Video Duration for Fade Out ---
try:
video_dur_cmd = [
"ffprobe",
"-v",
"error",
"-show_entries",
"format=duration",
"-of",
"default=noprint_wrappers=1:nokey=1",
str(input_video_path),
]
dur_proc = subprocess.run(video_dur_cmd, stdout=subprocess.PIPE, text=True)
video_duration = float(dur_proc.stdout.strip() or 0)
except Exception as e:
print(f"⚠️ Could not measure original video duration: {e}")
video_duration = 30.0 # Fallback
fade_duration = 2.0
fade_start = max(0, video_duration - fade_duration)
print(
f"🎬 Video Duration: {video_duration:.2f}s | Fade Out Start: {fade_start:.2f}s"
)
# 2. Download Music (if present) # 2. Download Music (if present)
has_music = False has_music = False
if request.music_url: if request.music_url:
@@ -798,6 +822,9 @@ async def process_reel(request: ReelRequest, x_api_key: str = Header(None)):
fc_parts.append(f"[{watermark_idx}:v]scale=200:-1[wm]") fc_parts.append(f"[{watermark_idx}:v]scale=200:-1[wm]")
v_chain += "[v_pre_wm];[v_pre_wm][wm]overlay=W-w-20:H-h-20" v_chain += "[v_pre_wm];[v_pre_wm][wm]overlay=W-w-20:H-h-20"
# Add Video Fade Out
v_chain += f",fade=t=out:st={fade_start}:d={fade_duration}"
# End of video chain # End of video chain
v_chain += "[vout]" v_chain += "[vout]"
fc_parts.append(v_chain) fc_parts.append(v_chain)
@@ -835,15 +862,20 @@ async def process_reel(request: ReelRequest, x_api_key: str = Header(None)):
# Mix # Mix
if inputs_for_mix > 0: if inputs_for_mix > 0:
fc_parts.append( fc_parts.append(
f"{audio_mix_str}amix=inputs={inputs_for_mix}:duration=first:dropout_transition=2:normalize=0[aout]" f"{audio_mix_str}amix=inputs={inputs_for_mix}:duration=first:dropout_transition=2:normalize=0[amixout]"
)
fc_parts.append(
f"[amixout]afade=t=out:st={fade_start}:d={fade_duration}[aout]"
) )
audio_mapped = True audio_mapped = True
else: else:
# No external audio added # No external audio added
if has_original_audio: if has_original_audio:
# Just pass through original audio # Add audio fade out to original audio
# We can map 0:a directly, no filter needed for audio fc_parts.append(
audio_mapped = False f"[0:a]afade=t=out:st={fade_start}:d={fade_duration}[aout]"
)
audio_mapped = True
else: else:
# No audio at all # No audio at all
audio_mapped = False audio_mapped = False
@@ -859,7 +891,8 @@ async def process_reel(request: ReelRequest, x_api_key: str = Header(None)):
elif has_original_audio: elif has_original_audio:
cmd.extend(["-map", "0:a"]) # Map original audio directly cmd.extend(["-map", "0:a"]) # Map original audio directly
cmd.extend(["-shortest"]) # Cut EXACTLY at video length (better than -shortest which can cause issues with amix)
cmd.extend(["-t", str(video_duration)])
# Quality settings # Quality settings
cmd.extend( cmd.extend(