Machine Learning pour prediction de match de Premier League Anglaise

Python ComfyUI API gestion d'API

Contexte du projet

Ce projet a été développé pour automatiser la création de vidéos destinées aux réseaux sociaux (TikTok, Instagram). En utilisant des modèles d'intelligence artificielle hébergés localement, l'objectif etant de générer rapidement des clips vidéo à partir d'un seul prompt textuel, sans dépendre de services cloud coûteux ou limités.

L'architecture repose sur un script Python qui demande a ollama de générer à la fois un script vocal et des prompts de scènes vidéo, puis utilise Hunyuan Video sur ComfyUI pour créer les clips, avant de les assembler et d'ajouter une voix off avec des sous-titres karaoké.

Extrait du Script d'Appel API

Afficher / masquer le code

#!/usr/bin/env python3
"""
Générateur de Reels/Shorts complet :
Ollama -> ComfyUI -> Concaténation -> TTS + Sous-titres karaoké mot-à-mot
"""

import os
import sys
import json
import time
import uuid
import asyncio
import requests
from pathlib import Path
from typing import Dict, List, Tuple
import subprocess
import torch
import gc



import edge_tts
from moviepy.editor import (
    VideoFileClip,
    TextClip,
    CompositeVideoClip,
    AudioFileClip,
    concatenate_videoclips,
)
from moviepy.video.fx import all as vfx
from soustitreollama import *


# ==========================================
# CONFIG GLOBALE
# ==========================================

# 1. Ollama
OLLAMA_MODEL = "gemma3:12b"
OLLAMA_BASE_URL = "http://localhost:11434"

# 2. ComfyUI
COMFY_SERVER = "127.0.0.1:8000"
COMFY_WORKFLOW_FILE = "workflow_api.json"
COMFY_OUTPUT_DIR = r"C:\Users\knipe\Documents\ComfyUI\output\video\hunyuan_video_1.5"
COMFY_PROMPT_NODE_ID = "44"

# 3. Vidéo / Audio / Fonts
TTS_VOICE = "en-US-EricNeural"
FONT_STYLE = r"C:\Code\py\reels\fullocal\reels-qui-marche-\the_bold_font\THEBOLDFONT-FREEVERSION.ttf"
if not os.path.exists(FONT_STYLE):
    FONT_STYLE = "Impact" if os.name == "nt" else "DejaVuSans-Bold"

# ==========================================
# PARTIE 1 : OLLAMA
# ==========================================

class ReelsGeneratorAPI:
    def __init__(self, model: str = OLLAMA_MODEL, base_url: str = OLLAMA_BASE_URL):
        self.model = model
        self.base_url = base_url
        self.api_url = f"{base_url}/api/generate"
        self.verify_ollama()

    def verify_ollama(self):
        try:
            response = requests.get(f"{self.base_url}/api/tags", timeout=5)
            if response.status_code == 200:
                print(f"✅ Ollama API détecté - Modèle: {self.model}")
            else:
                print("⚠️ Erreur avec l'API Ollama.")
                sys.exit(1)
        except Exception as e:
            print(f"❌ Erreur de connexion à Ollama: {e}")
            sys.exit(1)

    def call_ollama(self, prompt: str, max_tokens: int = 500) -> str:
        try:
            payload = {
                "model": self.model,
                "prompt": prompt,
                "stream": False,
                "options": {
                    "num_predict": max_tokens,
                    "temperature": 0.7,
                    "top_p": 0.9,
                },
            }
            response = requests.post(self.api_url, json=payload, timeout=120)
            return response.json().get("response", "").strip() if response.status_code == 200 else ""
        except Exception as e:
            return f"Erreur: {str(e)}"

    def unload_model(self):
        print(f"\n🧹 Vidage de la VRAM (Déchargement de {self.model})...")
        try:
            payload = {
                "model": self.model,
                "keep_alive": 0,
            }
            # petit hack : endpoint /api/generate avec keep_alive=0 force le déchargement
            requests.post(self.api_url, json=payload, timeout=10)
            time.sleep(2)
            print("✅ VRAM d'Ollama libérée avec succès !")
        except Exception as e:
            print(f"⚠️ Erreur lors du vidage de la VRAM: {e}")

    def generate_voiceover_script(self, topic: str) -> str:
        print("   🎙️ Écriture du script vocal...")
        prompt = f"""Act as an expert TikTok/Reels scriptwriter. Write a fast-paced, highly engaging 45-60 second voiceover script about: {topic}.

Structure:
Hook (0-3s): A pattern-interrupting, controversial, or highly relatable opening statement that forces viewers to stop scrolling.
Value/Story (30-40s): Fast, punchy sentences. Deliver immediate value or a compelling narrative. Use simple, conversational language with no fluff.
CTA (5-7s): A clear, low-friction Call to Action (e.g., "Save this for later," "Comment X for the link," or "Follow for part 2").

Tone: Energetic, authentic, and fast-paced.
Formatting: Answer ONLY with the script text. Do not include stage directions or notes.
"""
        return self.call_ollama(prompt, max_tokens=600)

    def generate_video_clips(self, topic: str) -> List[str]:
        print("   🎬 Génération des scènes...")
        prompt = f"""Act as a viral short-form video director. List exactly 10 high-retention visual scenes (roughly 3-6 seconds each) for a TikTok/Reel about: {topic}.

Requirements:
Scene 1 must be visually striking or involve rapid movement to match the hook.
Include quick cuts and dynamic actions (e.g., pointing, screen recordings, text on screen, B-roll with movement).
Keep descriptions concise and highly visual.

Format:
1. [Scene description]
2. [Scene description]
(Continue up to 8)

Answer ONLY with the numbered list. No introductions or explanations.
"""
        clips_raw = self.call_ollama(prompt, max_tokens=500)

        video_prompts = []
        for line in clips_raw.split("\n"):
            line = line.strip()
            if line and any(line.startswith(str(i)) for i in range(1, 10)):
                clean = line.lstrip("0123456789.-*)• ").strip()
                if len(clean) > 10:
                    video_prompts.append(
                        f"Professional 4K video: {clean}, cinematic lighting, smooth motion"
                    )

        if len(video_prompts) < 5:
            video_prompts = [f"4K video: Dynamic scene about {topic}"] * 8
        return video_prompts[:8]

    def generate_complete_reels(self, user_prompt: str) -> Dict:
        print(f"🎬 Génération du concept pour: '{user_prompt}'\n")
        voiceover = self.generate_voiceover_script(user_prompt)
        voiceover = voiceover.replace("\n", " ").strip()
        clips = self.generate_video_clips(user_prompt)
        return {
            "voiceover_script": voiceover,
            "video_clips": clips,
        }


# ==========================================
# PARTIE 2 : COMFYUI
# ==========================================

def clear_comfy_output_dir(folder_path):
    folder = Path(folder_path)
    if folder.exists():
        for f in folder.iterdir():
            if f.is_file() and f.suffix.lower() in {".mp4", ".avi", ".mov", ".mkv", ".webm"}:
                try:
                    f.unlink()
                except:
                    pass


def send_prompt_to_comfy(prompt_text: str) -> str:
    workflow_path = Path(COMFY_WORKFLOW_FILE)
    if not workflow_path.exists():
        raise SystemExit(f"Fichier API non trouvé: {COMFY_WORKFLOW_FILE}")

    prompt_graph = json.loads(workflow_path.read_text(encoding="utf-8"))

    if COMFY_PROMPT_NODE_ID not in prompt_graph:
        raise ValueError(f"Node {COMFY_PROMPT_NODE_ID} introuvable dans {COMFY_WORKFLOW_FILE}")

    if "inputs" not in prompt_graph[COMFY_PROMPT_NODE_ID]:
        prompt_graph[COMFY_PROMPT_NODE_ID]["inputs"] = {}
    prompt_graph[COMFY_PROMPT_NODE_ID]["inputs"]["text"] = prompt_text

    payload = {"prompt": prompt_graph, "client_id": str(uuid.uuid4())}
    r = requests.post(f"http://{COMFY_SERVER}/prompt", json=payload)
    r.raise_for_status()

    return r.json().get("prompt_id")


def wait_for_comfy_job(prompt_id: str):
    print(f"   ⏳ Attente de ComfyUI (ID: {prompt_id})...")
    while True:
        try:
            r = requests.get(f"http://{COMFY_SERVER}/history/{prompt_id}")
            if r.status_code == 200:
                history = r.json()
                if prompt_id in history:
                    print("   ✅ Clip généré !")
                    return
        except requests.exceptions.ConnectionError:
            pass
        time.sleep(3)


# ==========================================
# PARTIE 3 : CONCATÉNATION MOVIEPY
# ==========================================

def concatenate_videos(video_folder_path, output_filename, delete_originals=True):
    folder = Path(video_folder_path)
    if not folder.exists():
        raise FileNotFoundError(f"Le dossier '{video_folder_path}' n'existe pas.")

    video_extensions = {".mp4", ".avi", ".mov", ".mkv", ".webm"}
    video_files = sorted(
        [f for f in folder.iterdir() if f.is_file() and f.suffix.lower() in video_extensions]
    )

    if not video_files:
        raise Exception("Aucune vidéo trouvée pour la concaténation.")

    print(f"\nConcaténation de {len(video_files)} clips...")
    clips = [VideoFileClip(str(vf)) for vf in video_files]

    final_clip = concatenate_videoclips(clips, method="compose")
    final_clip.write_videofile(
        output_filename,
        codec="libx264",
        audio_codec="aac",
        fps=24,
        logger=None,
    )

    final_clip.close()
    for clip in clips:
        clip.close()

    if delete_originals:
        for vf in video_files:
            try:
                vf.unlink()
            except:
                pass


# ==========================================
# PARTIE 4 : TTS + SOUS-TITRES KARAOKÉ
# ==========================================

async def tts_with_word_boundaries(text: str, out_audio: str) -> List[Dict]:
    """
    Utilise edge-tts en mode streaming pour récupérer :
    - un fichier audio MP3,
    - une liste de boundaries : [{ "word": str, "start": float, "end": float }, ...]
    """
    communicate = edge_tts.Communicate(text, TTS_VOICE)

    # edge-tts retourne des "chunks" d'audio + métadonnées type WordBoundary. [web:19][web:27]
    boundaries = []
    audio_bytes = bytearray()
    current_time = 0.0

    async for chunk in communicate.stream():
        if chunk["type"] == "audio":
            audio_bytes.extend(chunk["data"])
            current_time = chunk["offset"] / 10_000_000  # ticks (100ns) -> secondes
        elif chunk["type"] == "WordBoundary":
            # chunk["offset"] est le début du mot, chunk["duration"] la durée du mot
            start = chunk["offset"] / 10_000_000
            end = (chunk["offset"] + chunk["duration"]) / 10_000_000
            word = chunk.get("text", "").strip()
            if word:
                boundaries.append(
                    {"word": word, "start": float(start), "end": float(end)}
                )

    # Sauvegarder l'audio
    with open(out_audio, "wb") as f:
        f.write(audio_bytes)

    return boundaries


def obtenir_duree_audio(audio_file: str) -> float:
    try:
        audioclip = AudioFileClip(audio_file)
        duration = audioclip.duration
        audioclip.close()
        return duration
    except Exception as e:
        print(f"Erreur durée audio : {e}")
        return 0.0



# ==========================================
# MAIN
# ==========================================

def main():
    print("=" * 70)
    print("🚀 GÉNÉRATEUR AUTOMATIQUE DE REELS (Ollama -> ComfyUI -> MoviePy)")
    print("=" * 70)

    user_prompt = input("\n📝 Votre sujet (ex: comment être confiant ?) : ").strip()
    if not user_prompt:
        user_prompt = "comment être confiant ?"

    # 1. Ollama
    generator = ReelsGeneratorAPI()
    reels_data = generator.generate_complete_reels(user_prompt)
    clips_prompts = reels_data["video_clips"]
    voiceover_script = reels_data["voiceover_script"]

    # Décharger le modèle pour libérer la VRAM
    generator.unload_model()
    gc.collect()
    torch.cuda.empty_cache()

    subprocess.run(["ollama", "stop", "gemma3:12b"], capture_output=True)

    # 2. ComfyUI
    print("\n🧹 Nettoyage de l'ancien dossier de sortie ComfyUI...")
    clear_comfy_output_dir(COMFY_OUTPUT_DIR)

    print(f"\n🖥️ Lancement de {len(clips_prompts)} générations vidéo sur ComfyUI...")
    prompt_ids = []
    for idx, clip_prompt in enumerate(clips_prompts):
        print(f"Génération clip {idx+1}/8")

        pid = send_prompt_to_comfy(f"Video clip {idx+1}: {clip_prompt}")
        wait_for_comfy_job(pid)

        time.sleep(2)

    for pid in prompt_ids:
        wait_for_comfy_job(pid)

    # 3. Concaténation des vidéos
    combined_video_path = "temp_combined.mp4"
    concatenate_videos(COMFY_OUTPUT_DIR, combined_video_path, delete_originals=True)

    # 4. TTS + sous-titres karaoké
    final_output = f"REEL_FINAL_{uuid.uuid4().hex[:6]}.mp4"
    creer_video_sous_titree_karaoke(combined_video_path, voiceover_script, final_output)

    # Nettoyage
    if os.path.exists(combined_video_path):
        os.remove(combined_video_path)

    print("\n" + "=" * 70)
    print(f"🎉 VIDÉO TERMINÉE ET SAUVEGARDÉE : {os.path.abspath(final_output)}")
    print("=" * 70)


if __name__ == "__main__":
    main()

                

Extrait du Script des sous titres

Afficher / masquer le code

import os
import sys
import time
import json
import asyncio
from typing import Dict, List
import moviepy.video.fx.all as vfx
import requests
import edge_tts
from moviepy.editor import (
    VideoFileClip,
    TextClip,
    CompositeVideoClip,
    AudioFileClip,
    concatenate_audioclips,
)

# ================== CONFIG OLLAMA ==================

OLLAMA_MODEL = "gemma3:12b"          # adapte si besoin 
OLLAMA_BASE_URL = "http://localhost:11434"


class OllamaClient:
    def __init__(self, model: str = OLLAMA_MODEL, base_url: str = OLLAMA_BASE_URL):
        self.model = model
        self.base_url = base_url.rstrip("/")
        self.api_url = f"{self.base_url}/api/generate"
        self.verify_ollama()

    def verify_ollama(self):
        try:
            response = requests.get(f"{self.base_url}/api/tags", timeout=5)
            if response.status_code == 200:
                print(f"✅ Ollama API détecté - Modèle: {self.model}")
            else:
                print("⚠️ Erreur avec l'API Ollama.")
                sys.exit(1)
        except Exception as e:
            print(f"❌ Erreur de connexion à Ollama: {e}")
            sys.exit(1)

    def call_ollama(self, prompt: str, max_tokens: int = 500) -> str:
        try:
            payload = {
                "model": self.model,
                "prompt": prompt,
                "stream": False,
                "options": {
                    "num_predict": max_tokens,
                    "temperature": 0.1,  # plus basse pour du JSON fiable
                    "top_p": 0.9,
                },
            }
            response = requests.post(self.api_url, json=payload, timeout=120)
            if response.status_code == 200:
                return response.json().get("response", "").strip()
            else:
                print("⚠️ Ollama a renvoyé un status code non 200:", response.status_code)
                return ""
        except Exception as e:
            print(f"⚠️ Erreur lors de l'appel à Ollama: {e}")
            return ""


# ================== CONFIG TTS / MOVIEPY ==================

TTS_VOICE = "en-GB-MaisieNeural"
FONT_STYLE = r"C:\Code\py\reels\fullocal\reels-qui-marche-\the_bold_font\THEBOLDFONT-FREEVERSION.ttf"
if not os.path.exists(FONT_STYLE):
    FONT_STYLE = "Impact" if os.name == "nt" else "DejaVuSans-Bold"
def _strip_markdown_fences(raw: str) -> str:
    """
    Enlève les ```json ... ``` éventuels autour de la réponse d'Ollama.
    """
    raw = raw.strip()
    if raw.startswith("```"):
        # enlève la première ligne ``` ou ```json
        lines = raw.splitlines()
        # supprime la première ligne
        lines = lines[1:]
        # si la dernière ligne est ``` on la retire aussi
        if lines and lines[-1].strip().startswith("```"):
            lines = lines[:-1]
        raw = "\n".join(lines).strip()
    return raw  

def decouper_texte_avec_ollama(texte: str, client: OllamaClient) -> List[str]:
    """
    Utilise Ollama pour découper le texte en groupes de 2–5 mots.
    Gère le cas où Ollama renvoie du JSON dans un bloc ```json ... ```.
    """
    print(f"🤖 Appel à Ollama ({client.model}) pour structurer les sous-titres...")

    prompt = (
        "Splits the following text into small groups of words for video subtitles."

"Each group must be a complete sentence or the splits need to be logical and natural for a english speaker like a professional tik tok video ."

"Keeps the original text EXACTLY, only changing the split points."

"Returns STRICTLY and ONLY a flat JSON array of strings,"

"with no other text or comments. Example of expected format:"

"[\"group 1\", \"group 2\", \"group 3\"].\n\n"
f"Text: {texte}"
    )

    raw = client.call_ollama(prompt, max_tokens=600)
    if not raw:
        print("⚠️ Réponse vide d'Ollama, fallback mot par mot.")
        return texte.split()

    # >>> nettoie les ```json ... ``` avant json.loads
    cleaned = _strip_markdown_fences(raw)

    try:
        chunks = json.loads(cleaned)

        # Si le modèle renvoie un dict, essayer d'en extraire la liste
        if isinstance(chunks, dict):
            for val in chunks.values():
                if isinstance(val, list):
                    chunks = val
                    break

        if isinstance(chunks, list) and chunks:
            chunks = [str(c).strip() for c in chunks if str(c).strip()]
            print(f"✅ Ollama a renvoyé {len(chunks)} segments.")
            return chunks
        else:
            print("⚠️ JSON renvoyé par Ollama non exploitable, fallback mot par mot.")
            return texte.split()

    except Exception as e:
        print(f"⚠️ Erreur de parsing JSON de la réponse Ollama: {e}")
        print("Réponse brute reçue (début) :", raw[:200])
        return texte.split()

async def tts_via_ollama_chunks(texte: str, out_audio: str, client: OllamaClient) -> List[Dict]:
    """
    Utilise les segments générés par Ollama.
    Un segment = un appel edge-tts => plus rapide que mot par mot.
    """
    chunks = decouper_texte_avec_ollama(texte, client)
    print(f"✅ Texte découpé en {len(chunks)} sous-titres par Ollama.")

    boundaries = []
    audioclips = []
    current_time = 0.0

    print("🎙️ Génération de l'audio via edge-tts (par chunk)...")
    for i, chunk_text in enumerate(chunks):
        chunk_text = str(chunk_text).strip()
        if not chunk_text:
            continue

        temp_file = f"temp_chunk_{i}.mp3"
        communicate = edge_tts.Communicate(chunk_text, TTS_VOICE)
        await communicate.save(temp_file)

        clip = AudioFileClip(temp_file)
        audioclips.append(clip)
        duration = clip.duration

        boundaries.append(
            {
                "word": chunk_text,
                "start": float(current_time),
                "end": float(current_time + duration),
            }
        )
        current_time += duration

    if audioclips:
        final_audio = concatenate_audioclips(audioclips)
        final_audio.write_audiofile(out_audio, logger=None)
    else:
        print("⚠️ Aucun audio n'a pu être généré.")

    for clip in audioclips:
        clip.close()
    for i in range(len(chunks)):
        temp_file = f"temp_chunk_{i}.mp3"
        if os.path.exists(temp_file):
            os.remove(temp_file)

    return boundaries


def obtenir_duree_audio(audio_file: str) -> float:
    try:
        audioclip = AudioFileClip(audio_file)
        duration = audioclip.duration
        audioclip.close()
        return duration
    except Exception as e:
        print(f"Erreur durée audio : {e}")
        return 0.0


def creer_video_sous_titree_karaoke(
    video_path: str,
    texte: str,
    output_path: str,
):
    audio_temp = "temp_audio.mp3"

    # client Ollama comme dans ton autre code
    client = OllamaClient()

    boundaries = asyncio.run(tts_via_ollama_chunks(texte, audio_temp, client))
    duree_audio = obtenir_duree_audio(audio_temp)

    if not boundaries:
        print("⚠️ Aucun boundary renvoyé, arrêt du traitement.")
        return

    print("📏 Alignement vidéo sur la durée de l'audio...")
    video_base = VideoFileClip(video_path)

    if video_base.duration < duree_audio:
        video_base = video_base.loop(duration=duree_audio)
    else:
        video_base = video_base.subclip(0, duree_audio)

    # on récupère la taille de la vidéo pour adapter la largeur max du texte
    video_w, video_h = video_base.size
    max_text_width = int(video_w * 0.8)  # 80% de la largeur vidéo

    audio_clip = AudioFileClip(audio_temp)
    video_base = video_base.set_audio(audio_clip)

    print("✍️ Création des sous-titres...")
    text_clips = []
    for i, item in enumerate(boundaries):
        word = item["word"]
        if not word.strip():
            continue

        start = float(item["start"])
        end = float(item["end"])
        if end <= start:
            continue

        text_color = "#FFD700"  # jaune
        txt_clip = (
            TextClip(
                word.strip(),
                fontsize=40,                # police plus petite
                color=text_color,
                font=FONT_STYLE,
                stroke_color="black",
                stroke_width=1,
                method="caption",           # wrap auto
                size=(max_text_width, None),# largeur = 80% de la vidéo, wrap si ça dépasse
                align="center",
            )
            # plus bas sur l'écran (80% de la hauteur)
            .set_position(("center", 0.8), relative=True)
            .set_start(start)
            .set_duration(end - start)
        )

        text_clips.append(txt_clip)

    print("🎥 Rendu final (encodage avec sous-titres)...")
    final_video = CompositeVideoClip([video_base] + text_clips)
    final_video = final_video.fx(vfx.speedx, factor=1.35)
    final_video.write_videofile(
        output_path,
        fps=24,
        codec="libx264",
        audio_codec="aac",
        threads=4,
        logger=None,
    )

    final_video.close()
    video_base.close()
    audio_clip.close()

    if os.path.exists(audio_temp):
        os.remove(audio_temp)

if __name__ == "__main__":
    creer_video_sous_titree_karaoke(
        video_path="temp_combined.mp4",
        texte=(
            "Stop following recipes word-for-word. Seriously, it is the number one "
            "reason your food tastes boring. Recipes teach you how to read, not how to cook. "
            "If you want to actually get better, you only need to master three basic concepts. "
            "First, acid. If your soup or sauce tastes flat, stop adding salt. "
            "Add a squeeze of lemon or a splash of vinegar to completely wake it up. "
            "Second, temperature control. Stop cooking absolutely everything on medium. "
            "Get your pans screaming hot for a proper crust, but drop the heat to low when "
            "you need to build flavor bases. Third, dry your proteins. Moisture is the enemy "
            "of a good sear. Pat your chicken or steak completely dry with a paper towel "
            "before it ever hits the pan. Learn these techniques, and you will start cooking "
            "on pure instinct. Save this video so you do not ruin dinner tonight, and follow "
            "me for more actual cooking secrets."
        ),
        output_path="output_video_karaoke.mp4",
    )

        

Workflow de Hunyuan Video sur ComfyUI

Afficher / masquer le code

{
  "8": {
    "inputs": {
      "tile_size": 256,
      "overlap": 32,
      "temporal_size": 32,
      "temporal_overlap": 4,
      "samples": [
        "127",
        0
      ],
      "vae": [
        "10",
        0
      ]
    },
    "class_type": "VAEDecodeTiled",
    "_meta": {
      "title": "VAE Decode (Tiled)"
    }
  },
  "10": {
    "inputs": {
      "vae_name": "hunyuanvideo15_vae_fp16.safetensors"
    },
    "class_type": "VAELoader",
    "_meta": {
      "title": "Charger VAE"
    }
  },
  "11": {
    "inputs": {
      "clip_name1": "qwen_2.5_vl_7b_fp8_scaled.safetensors",
      "clip_name2": "byt5_small_glyphxl_fp16.safetensors",
      "type": "hunyuan_video_15",
      "device": "default"
    },
    "class_type": "DualCLIPLoader",
    "_meta": {
      "title": "ChargeurDualCLIP"
    }
  },
  "12": {
    "inputs": {
      "unet_name": "hunyuanvideo1.5_720p_t2v_fp16.safetensors",
      "weight_dtype": "fp8_e4m3fn"
    },
    "class_type": "UNETLoader",
    "_meta": {
      "title": "Charger Modèle Diffusion"
    }
  },
  "44": {
    "inputs": {
      "text": "A paper airplane released from the top of a skyscraper, gliding through urban canyons, crossing traffic, flying over streets, spiraling upward between buildings. The camera follows the paper airplane's perspective, shooting cityscape in first-person POV, finally flying toward the sunset, disappearing in golden light. Creative camera movement, free perspective, dreamlike colors.",
      "clip": [
        "11",
        0
      ]
    },
    "class_type": "CLIPTextEncode",
    "_meta": {
      "title": "CLIP Text Encode (Positive Prompt)"
    }
  },
  "93": {
    "inputs": {
      "text": "",
      "clip": [
        "11",
        0
      ]
    },
    "class_type": "CLIPTextEncode",
    "_meta": {
      "title": "CLIP Text Encode (Negative Prompt)"
    }
  },
  "101": {
    "inputs": {
      "fps": 15,
      "images": [
        "8",
        0
      ]
    },
    "class_type": "CreateVideo",
    "_meta": {
      "title": "Créer une vidéo"
    }
  },
  "102": {
    "inputs": {
      "filename_prefix": "video/hunyuan_video_1.5/reel",
      "format": "auto",
      "codec": "h264",
      "video": [
        "101",
        0
      ]
    },
    "class_type": "SaveVideo",
    "_meta": {
      "title": "Enregistrer la vidéo"
    }
  },
  "124": {
    "inputs": {
      "width": 560,
      "height": 944,
      "length": 65,
      "batch_size": 1
    },
    "class_type": "EmptyHunyuanVideo15Latent",
    "_meta": {
      "title": "HunyuanVideo 1.5 latent vide"
    }
  },
  "127": {
    "inputs": {
      "noise": [
        "129",
        0
      ],
      "guider": [
        "131",
        0
      ],
      "sampler": [
        "130",
        0
      ],
      "sigmas": [
        "128",
        0
      ],
      "latent_image": [
        "124",
        0
      ]
    },
    "class_type": "SamplerCustomAdvanced",
    "_meta": {
      "title": "ÉchantillonneurPersonnaliséAvancé"
    }
  },
  "128": {
    "inputs": {
      "scheduler": "simple",
      "steps": 20,
      "denoise": 1,
      "model": [
        "12",
        0
      ]
    },
    "class_type": "BasicScheduler",
    "_meta": {
      "title": "PlanificateurBasique"
    }
  },
  "129": {
    "inputs": {
      "noise_seed": 887963123424675
    },
    "class_type": "RandomNoise",
    "_meta": {
      "title": "BruitAléatoire"
    }
  },
  "130": {
    "inputs": {
      "sampler_name": "euler"
    },
    "class_type": "KSamplerSelect",
    "_meta": {
      "title": "KSamplerSelect"
    }
  },
  "131": {
    "inputs": {
      "cfg": 6,
      "model": [
        "132",
        0
      ],
      "positive": [
        "44",
        0
      ],
      "negative": [
        "93",
        0
      ]
    },
    "class_type": "CFGGuider",
    "_meta": {
      "title": "GuideCFG"
    }
  },
  "132": {
    "inputs": {
      "shift": 7,
      "model": [
        "12",
        0
      ]
    },
    "class_type": "ModelSamplingSD3",
    "_meta": {
      "title": "ModèleÉchantillonnageSD3"
    }
  }
}
        

Comment l'utiliser

Besoin d'une carte graphique puissamte pour faire tourner le modèle de génération vidéo (ex: NVIDIA 4090 ou équivalent), 8gb de Vram, 32 gb de ram ( Le workflow est adapté pour tourner sur ma config, il faut peut-être ajuster les paramètres de génération dans comfyui pour les configs plus modestes). Pour utiliser ce projet vous avez besoin de ollama installé localement avec le modèle "gemma3:12b" (ou adaptez le nom du modèle dans le code), ainsi que ComfyUI avec le workflow de génération vidéo configuré comme montré ci-dessus.

Téléchargez Ollama ici
Téléchargez ComfyUI ici

Sur Comfyui, telecharger les modeles necesssaires (hunyuanvideo1.5_720p_t2v_fp16.safetensors, hunyuanvideo15_vae_fp16.safetensors, qwen_2.5_vl_7b_fp8_scaled.safetensors, byt5_small_glyphxl_fp16.safetensors) et configurez le workflow comme montré ci-dessus (le code JSON est disponible dans la section dédiée). Verifiez le code de vos host locaux ainsi que les chemins d'accès aux modèles dans le workflow correspondent à ceux de votre installation ComfyUI. Ensuite, lancez ollama, comfyui et le script Python. Il vous demandera d'entrer un sujet. Attendez et vous aurez une vidéo générée automatiquement avec un script vocal et des sous-titres karaoké. Le processus complet peut prendre jusqu'à plusieurs heures selon votre matériel.

Améliorations prévues

Exemple :

Prompt: How to make a good portfolio as an AI student ?