omarbajouk commited on
Commit
e4dcfbf
·
verified ·
1 Parent(s): fa26c75

Update src/capsule_builder.py

Browse files
Files changed (1) hide show
  1. src/capsule_builder.py +213 -78
src/capsule_builder.py CHANGED
@@ -1,92 +1,227 @@
1
- import os
2
- import json
3
- import time
4
- import shutil
5
- from .config import OUT_DIR, TMP_DIR
 
6
  from .graphics import make_background
7
- from .video_utils import write_srt
8
- from .tts_utils import create_tts_audio
9
- from .video_utils import write_video_with_fallback
10
 
11
  capsules = []
12
 
13
- def build_capsule(
14
- titre,
15
- sous_titre,
16
- texte_voix,
17
- texte_ecran,
18
- langue,
19
- voix_type,
20
- theme,
21
- image_fond,
22
- fond_mode,
23
- photo_mode,
24
- photo_pos,
25
- logo_path,
26
- logo_pos,
27
- video_presentateur=None,
28
- position_presentateur="bas-droite",
29
- plein=False
30
- ):
31
- print(f"[Capsule] Création de la capsule '{titre}'...")
32
 
 
33
  try:
34
- # ---- TTS ----
35
- audio_path, dur = create_tts_audio(texte_voix, langue, voix_type)
36
- print(f"[TTS] Audio généré ({dur:.2f}s): {audio_path}")
37
-
38
- # ---- Fond ----
39
- fond_path = make_background(
40
- titre=titre,
41
- sous_titre=sous_titre,
42
- texte_ecran=texte_ecran,
43
- theme=theme,
44
- logo_path=logo_path,
45
- logo_pos=logo_pos,
46
- image_fond=image_fond,
47
- fond_mode=fond_mode,
48
- photo_mode=photo_mode, # 🆕
49
- photo_pos=photo_pos # 🆕
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
  )
51
- print(f"[Capsule] ✅ Fond chargé: {fond_path}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
 
53
- # ---- Sous-titres ----
54
- srt_path = write_srt(texte_voix, dur, base_name=titre)
55
 
56
- # ---- Fusion vidéo ----
57
- out_base = os.path.join(OUT_DIR, f"{titre.replace(' ', '_')}")
58
- out_path = write_video_with_fallback(
59
- final_clip=None, # le clip est créé ailleurs (selon ta logique existante)
60
- out_path_base=out_base
 
 
 
 
 
 
 
 
 
 
 
 
61
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
 
63
- # ---- Enregistrer capsule ----
64
- capsule_data = {
65
- "file": out_path,
66
- "title": titre,
67
- "langue": langue,
68
- "voice": voix_type,
69
- "theme": theme,
70
- "duration": round(dur, 1),
71
- "inputs": {
72
- "image_fond": image_fond,
73
- "logo": logo_path,
74
- "video_presentateur": video_presentateur
75
- },
76
- "texte_voix": texte_voix,
77
- "texte_ecran": texte_ecran,
78
- "photo_mode": photo_mode,
79
- "photo_pos": photo_pos
80
- }
81
- capsules.append(capsule_data)
82
-
83
- manifest_path = os.path.join(OUT_DIR, "manifest.json")
84
- with open(manifest_path, "w", encoding="utf-8") as f:
85
- json.dump({"capsules": capsules}, f, ensure_ascii=False, indent=2)
86
-
87
- print(f"[Capsule] ✅ Capsule '{titre}' ajoutée ({len(capsules)} total)")
88
- return out_path
89
 
 
 
 
90
  except Exception as e:
91
- print(f"[Capsule] ❌ Erreur création capsule : {e}")
92
  return None
 
1
+ import os, json, uuid, gc, traceback
2
+ from moviepy.editor import ImageClip, AudioFileClip, CompositeVideoClip
3
+ from moviepy.video.VideoClip import ColorClip
4
+
5
+ from .config import OUT_DIR, TMP_DIR, MANIFEST_PATH, W, H
6
+ from .tts_utils import tts_edge, tts_gtts, normalize_audio_to_wav
7
  from .graphics import make_background
8
+ from .video_utils import prepare_video_presentateur, write_srt, write_video_with_fallback, safe_name
 
 
9
 
10
  capsules = []
11
 
12
+ # Load manifest on import
13
+ if os.path.exists(MANIFEST_PATH):
14
+ try:
15
+ data = json.load(open(MANIFEST_PATH, "r", encoding="utf-8"))
16
+ if isinstance(data, dict) and "capsules" in data:
17
+ capsules.extend(data["capsules"])
18
+ except Exception:
19
+ pass
20
+
21
+ def _save_manifest():
22
+ with open(MANIFEST_PATH, "w", encoding="utf-8") as f:
23
+ json.dump({"capsules": capsules}, f, ensure_ascii=False, indent=2)
24
+
25
+ def build_capsule(titre, sous_titre, texte_voix, texte_ecran, theme,
26
+ image_fond=None, logo_path=None, logo_pos="haut-gauche",
27
+ fond_mode="plein écran",
28
+ video_presentateur=None, voix_type="Féminine",
29
+ position_presentateur="bottom-right", plein=False,
30
+ moteur_voix="Edge-TTS (recommandé)", langue="fr", speaker=None):
31
 
32
+ # 1) TTS
33
  try:
34
+ audio_mp = tts_edge(texte_voix, voice=speaker or ("fr-FR-DeniseNeural" if langue == "fr" else "nl-NL-MaaikeNeural"))
35
+ except Exception as e:
36
+ print(f"[Capsule] Erreur TTS Edge ({e}), fallback gTTS.")
37
+ audio_mp = tts_gtts(texte_voix, lang=langue)
38
+
39
+ audio_wav = audio_mp
40
+ if not audio_mp.lower().endswith(".wav"):
41
+ try:
42
+ audio_wav = normalize_audio_to_wav(audio_mp)
43
+ except Exception as e:
44
+ print(f"[Audio] Normalisation échouée ({e}), on garde {audio_mp}")
45
+
46
+ # 2) Fond
47
+ print("[Capsule] Génération du fond...")
48
+ fond_path = make_background(titre, sous_titre, texte_ecran, theme,
49
+ logo_path, logo_pos, image_fond, fond_mode)
50
+ if fond_path is None:
51
+ print("[Capsule] ❌ fond_path est None, création d'urgence")
52
+ from PIL import Image
53
+ try:
54
+ emergency_bg = Image.new("RGB", (W, H), (0, 82, 147))
55
+ fond_path = os.path.join(TMP_DIR, f"emergency_{uuid.uuid4().hex[:6]}.png")
56
+ emergency_bg.save(fond_path)
57
+ print(f"[Capsule] ✅ Fond d'urgence créé: {fond_path}")
58
+ except Exception as e:
59
+ print(f"[Capsule] ❌ Impossible de créer le fond d'urgence: {e}")
60
+ fond_path = None
61
+
62
+ # 3) Composition MoviePy
63
+ audio = AudioFileClip(audio_wav)
64
+ dur = float(audio.duration or 5.0)
65
+ target_fps = 25
66
+ clips = []
67
+
68
+ if fond_path and os.path.exists(fond_path):
69
+ try:
70
+ bg = ImageClip(fond_path).set_duration(dur)
71
+ clips.append(bg)
72
+ print(f"[Capsule] ✅ Fond chargé: {fond_path}")
73
+ except Exception as e:
74
+ print(f"[Capsule] ❌ Erreur ImageClip, fallback ColorClip: {e}")
75
+ bg = ColorClip(size=(W, H), color=(0, 82, 147)).set_duration(dur)
76
+ clips.append(bg)
77
+ else:
78
+ print("[Capsule] ❌ Aucun fond valide, utilisation ColorClip")
79
+ bg = ColorClip(size=(W, H), color=(0, 82, 147)).set_duration(dur)
80
+ clips.append(bg)
81
+
82
+ if video_presentateur and os.path.exists(video_presentateur):
83
+ print(f"[Capsule] Vidéo présentateur trouvée: {video_presentateur}")
84
+ v_presentateur = prepare_video_presentateur(
85
+ video_presentateur, dur, position_presentateur, plein
86
  )
87
+ if v_presentateur:
88
+ print(f"[Capsule] ✅ Vidéo présentateur ajoutée")
89
+ clips.append(v_presentateur)
90
+ else:
91
+ print(f"[Capsule] ❌ Échec préparation vidéo présentateur")
92
+ else:
93
+ print(f"[Capsule] Aucune vidéo présentateur: {video_presentateur}")
94
+
95
+ final = CompositeVideoClip(clips).set_audio(audio.set_fps(44100))
96
+ name = safe_name(f"{titre}_{langue}")
97
+ out_base = os.path.join(OUT_DIR, name)
98
+ out = write_video_with_fallback(final, out_base, fps=target_fps)
99
+
100
+ srt_path = write_srt(texte_voix, dur)
101
+ capsules.append({
102
+ "file": out,
103
+ "title": titre,
104
+ "langue": langue,
105
+ "voice": speaker or voix_type,
106
+ "theme": theme,
107
+ "duration": round(dur, 1),
108
+ "inputs": {"image_fond": image_fond, "logo": logo_path, "video_presentateur": video_presentateur},
109
+ "texte_voix": texte_voix,
110
+ "texte_ecran": texte_ecran
111
+ })
112
+ _save_manifest()
113
+
114
+ try:
115
+ audio.close()
116
+ final.close()
117
+ bg.close()
118
+ if 'v_presentateur' in locals() and v_presentateur is not None:
119
+ v_presentateur.close()
120
+ if os.path.exists(audio_mp):
121
+ os.remove(audio_mp)
122
+ if audio_wav != audio_mp and os.path.exists(audio_wav):
123
+ os.remove(audio_wav)
124
+ except Exception as e:
125
+ print(f"[Clean] Erreur nettoyage: {e}")
126
+ gc.collect()
127
 
128
+ return out, f"✅ Capsule {langue.upper()} créée ({dur:.1f}s, voix {speaker or voix_type})", srt_path
 
129
 
130
+ def table_capsules():
131
+ import os
132
+ return [[i+1, c["title"], c.get("langue","fr").upper(),
133
+ f"{c['duration']}s", c["theme"], c["voice"], os.path.basename(c["file"])]
134
+ for i, c in enumerate(capsules)]
135
+
136
+ def assemble_final():
137
+ if not capsules:
138
+ return None, "❌ Aucune capsule."
139
+ from moviepy.editor import VideoFileClip
140
+ from moviepy.video.compositing.concatenate import concatenate_videoclips
141
+ clips = [VideoFileClip(c["file"]) for c in capsules]
142
+ try:
143
+ out = write_video_with_fallback(
144
+ concatenate_videoclips(clips, method="compose"),
145
+ os.path.join(OUT_DIR, "VIDEO_COMPLETE"),
146
+ fps=25,
147
  )
148
+ return out, f"🎉 Vidéo finale prête ({len(capsules)} capsules)."
149
+ finally:
150
+ for c in clips:
151
+ try: c.close()
152
+ except: pass
153
+
154
+ def supprimer_capsule(index):
155
+ try:
156
+ idx = int(index) - 1
157
+ if 0 <= idx < len(capsules):
158
+ fichier = capsules[idx]["file"]
159
+ if os.path.exists(fichier):
160
+ os.remove(fichier)
161
+ del capsules[idx]
162
+ _save_manifest()
163
+ return f"🗑 Capsule supprimée : {fichier}", table_capsules()
164
+ else:
165
+ return "⚠️ Index invalide.", table_capsules()
166
+ except Exception as e:
167
+ return f"❌ Erreur lors de la suppression : {e}", table_capsules()
168
+
169
+ def deplacer_capsule(index, direction):
170
+ try:
171
+ idx = int(index) - 1
172
+ if direction == "up" and idx > 0:
173
+ capsules[idx - 1], capsules[idx] = capsules[idx], capsules[idx - 1]
174
+ elif direction == "down" and idx < len(capsules) - 1:
175
+ capsules[idx + 1], capsules[idx] = capsules[idx], capsules[idx + 1]
176
+ _save_manifest()
177
+ return f"🔁 Capsule déplacée {direction}.", table_capsules()
178
+ except Exception as e:
179
+ return f"❌ Erreur de déplacement : {e}", table_capsules()
180
+
181
+
182
+ import shutil, time
183
+
184
+ def export_project_zip():
185
+ """Crée un ZIP complet pour toutes les capsules (vidéos, srt, inputs, params, manifest)."""
186
+ try:
187
+ zip_root = os.path.join(TMP_DIR, f"zip_export_{int(time.time())}")
188
+ os.makedirs(zip_root, exist_ok=True)
189
+ # Manifest global
190
+ manifest = {"capsules": capsules}
191
+ with open(os.path.join(zip_root, "manifest.json"), "w", encoding="utf-8") as f:
192
+ json.dump(manifest, f, ensure_ascii=False, indent=2)
193
+
194
+ # Par capsule
195
+ for i, cap in enumerate(capsules, 1):
196
+ cap_dir = os.path.join(zip_root, f"capsule_{i}")
197
+ os.makedirs(os.path.join(cap_dir, "inputs"), exist_ok=True)
198
+
199
+ # copy video + srt if exists
200
+ for key in ["file"]:
201
+ path = cap.get(key)
202
+ if path and os.path.exists(path):
203
+ shutil.copy2(path, os.path.join(cap_dir, os.path.basename(path)))
204
+ # try to find srt next to file if not stored
205
+ if cap.get("file"):
206
+ base = os.path.splitext(os.path.basename(cap["file"]))[0]
207
+ # srt names are not strictly tied; we copy any srt in OUT_DIR too
208
+ for f in os.listdir(OUT_DIR):
209
+ if f.lower().endswith(".srt"):
210
+ shutil.copy2(os.path.join(OUT_DIR, f), os.path.join(cap_dir, f))
211
+
212
+ # inputs
213
+ for k in ["image_fond", "logo", "video_presentateur"]:
214
+ p = cap.get("inputs", {}).get(k) if cap.get("inputs") else None
215
+ if p and os.path.exists(p):
216
+ shutil.copy2(p, os.path.join(cap_dir, "inputs", os.path.basename(p)))
217
 
218
+ # params.json per capsule
219
+ with open(os.path.join(cap_dir, "params.json"), "w", encoding="utf-8") as pf:
220
+ json.dump(cap, pf, ensure_ascii=False, indent=2)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
221
 
222
+ # zip
223
+ zip_path = shutil.make_archive(os.path.join(TMP_DIR, f"capsules_export_{int(time.time())}"), "zip", zip_root)
224
+ return zip_path
225
  except Exception as e:
226
+ print(f"[Export] ❌ Erreur ZIP : {e}")
227
  return None