tester343 commited on
Commit
ab42df8
·
verified ·
1 Parent(s): 339134a

Update app_enhanced.py

Browse files
Files changed (1) hide show
  1. app_enhanced.py +226 -98
app_enhanced.py CHANGED
@@ -24,16 +24,20 @@ def gpu_warmup():
24
  return True
25
 
26
  # ======================================================
27
- # 🧱 DATA CLASSES (Local Definition)
28
  # ======================================================
29
- def bubble(dialog="", bubble_offset_x=50, bubble_offset_y=20, lip_x=-1, lip_y=-1, emotion='normal'):
 
30
  return {
31
  'dialog': dialog,
32
  'bubble_offset_x': int(bubble_offset_x),
33
  'bubble_offset_y': int(bubble_offset_y),
34
  'lip_x': int(lip_x),
35
  'lip_y': int(lip_y),
36
- 'emotion': emotion
 
 
 
37
  }
38
 
39
  def panel(image=""):
@@ -45,7 +49,7 @@ class Page:
45
  self.bubbles = bubbles
46
 
47
  # ======================================================
48
- # 🔧 APP SETUP
49
  # ======================================================
50
  logging.basicConfig(level=logging.INFO)
51
  logger = logging.getLogger(__name__)
@@ -65,13 +69,14 @@ def generate_save_code(length=8):
65
  return code
66
 
67
  # ======================================================
68
- # 🧠 GLOBAL GPU FUNCTIONS
69
  # ======================================================
70
 
71
- @spaces.GPU(duration=240)
72
  def generate_comic_gpu(video_path, user_dir, frames_dir, metadata_path, target_pages):
73
  print(f"🚀 GPU Task Started: {video_path} | Target Pages: {target_pages}")
74
 
 
75
  import cv2
76
  import srt
77
  import math
@@ -91,100 +96,141 @@ def generate_comic_gpu(video_path, user_dir, frames_dir, metadata_path, target_p
91
  duration = total_frames / fps
92
  cap.release()
93
 
94
- # 2. Subtitles
95
  user_srt = os.path.join(user_dir, 'subs.srt')
96
  try:
 
97
  get_real_subtitles(video_path)
98
  if os.path.exists('test1.srt'):
99
  shutil.move('test1.srt', user_srt)
100
  except Exception as e:
101
- print(f"⚠️ Subtitle error: {e}")
102
- with open(user_srt, 'w') as f: f.write("1\n00:00:01,000 --> 00:00:04,000\nHello\n")
103
 
104
  with open(user_srt, 'r', encoding='utf-8') as f:
105
  all_subs = list(srt.parse(f.read()))
106
 
107
- key_moments = [{'index': s.index, 'text': s.content, 'start': s.start.total_seconds(), 'end': s.end.total_seconds()} for s in all_subs]
108
- key_moments.sort(key=lambda x: x['start'])
 
109
 
110
- # 3. Extract Frames (Limit max frames to keep it snappy)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
111
  frame_metadata = {}
112
  cap = cv2.VideoCapture(video_path)
113
  count = 0
114
- max_frames_to_extract = 40
 
 
115
 
116
- for i, moment in enumerate(key_moments[:max_frames_to_extract]):
117
  mid = (moment['start'] + moment['end']) / 2
118
  if mid > duration: continue
 
119
  cap.set(cv2.CAP_PROP_POS_FRAMES, int(mid * fps))
120
  ret, frame = cap.read()
121
  if ret:
122
  fname = f"frame_{count:04d}.png"
123
  p = os.path.join(frames_dir, fname)
124
  cv2.imwrite(p, frame)
125
- frame_metadata[fname] = {'dialogue': moment['text'], 'time': mid}
 
 
 
 
 
 
 
 
126
  count += 1
 
 
 
127
  cap.release()
128
 
129
- with open(metadata_path, 'w') as f: json.dump(frame_metadata, f)
130
 
131
- # 4. Enhance
132
  try: black_bar_crop()
133
  except: pass
134
 
135
  se = SimpleColorEnhancer()
136
  qe = QualityColorEnhancer()
137
- frame_files = sorted([f for f in os.listdir(frames_dir) if f.endswith('.png')])
138
 
139
- print(f"🎨 Enhancing {len(frame_files)} frames...")
140
- for f in frame_files:
141
  p = os.path.join(frames_dir, f)
142
- try: se.enhance_single(p, p)
143
  except: pass
144
- try: qe.enhance_single(p, p)
145
  except: pass
146
 
147
- # 5. Bubbles
148
- print("💬 Placing bubbles...")
149
  bubbles_list = []
150
- for f in frame_files:
 
151
  p = os.path.join(frames_dir, f)
152
  dialogue = frame_metadata.get(f, {}).get('dialogue', '')
 
 
 
 
 
 
 
153
  try:
154
  faces = face_detector.detect_faces(p)
155
  lip = face_detector.get_lip_position(p, faces[0]) if faces else (-1, -1)
156
  bx, by = ai_bubble_placer.place_bubble_ai(p, lip)
157
- bubbles_list.append(bubble(dialog=dialogue, bubble_offset_x=bx, bubble_offset_y=by, lip_x=lip[0], lip_y=lip[1]))
 
 
 
 
 
 
 
 
 
 
158
  except:
159
- bubbles_list.append(bubble(dialog=dialogue))
160
 
161
- # 6. Dynamic Layout Calculation
162
- print("📄 Generating layout...")
163
- total_panels = len(frame_files)
164
-
165
- # Calculate panels per page
166
- if target_pages <= 0: target_pages = 1
167
-
168
- # If we have 32 panels and user wants 4 pages -> 8 panels/page
169
- # If we have 32 panels and user wants 10 pages -> ~3 panels/page
170
- panels_per_page = math.ceil(total_panels / target_pages)
171
-
172
- print(f"📊 Layout: {total_panels} panels across {target_pages} pages (~{panels_per_page}/page)")
173
-
174
  pages = []
 
 
175
  for i in range(target_pages):
176
- start_idx = i * panels_per_page
177
- end_idx = start_idx + panels_per_page
178
 
179
- # Slicing safely
180
- page_frames = frame_files[start_idx:end_idx]
181
- page_bubbles = bubbles_list[start_idx:end_idx]
182
 
183
- if page_frames:
184
- pg_panels = [panel(image=f) for f in page_frames]
185
- pages.append(Page(panels=pg_panels, bubbles=page_bubbles))
186
 
187
- # Serialize Results
188
  result = []
189
  for pg in pages:
190
  p_data = [p if isinstance(p, dict) else p.__dict__ for p in pg.panels]
@@ -215,10 +261,8 @@ def regen_frame_gpu(video_path, frames_dir, metadata_path, fname, direction):
215
 
216
  if ret:
217
  p = os.path.join(frames_dir, fname)
218
- # Write then Flush to prevent libpng errors
219
  cv2.imwrite(p, frame)
220
- os.sync()
221
-
222
  try: SimpleColorEnhancer().enhance_single(p, p)
223
  except: pass
224
 
@@ -243,7 +287,6 @@ def get_frame_at_ts_gpu(video_path, frames_dir, metadata_path, fname, ts):
243
  p = os.path.join(frames_dir, fname)
244
  cv2.imwrite(p, frame)
245
  os.sync()
246
-
247
  try: SimpleColorEnhancer().enhance_single(p, p)
248
  except: pass
249
 
@@ -279,7 +322,6 @@ class EnhancedComicGenerator:
279
  def run(self, target_pages):
280
  try:
281
  self.write_status("Waiting for GPU...", 5)
282
- # Pass target_pages to GPU function
283
  data = generate_comic_gpu(self.video_path, self.user_dir, self.frames_dir, self.metadata_path, int(target_pages))
284
  with open(os.path.join(self.output_dir, 'pages.json'), 'w') as f:
285
  json.dump(data, f, indent=2)
@@ -293,7 +335,7 @@ class EnhancedComicGenerator:
293
  json.dump({'message': msg, 'progress': prog}, f)
294
 
295
  # ======================================================
296
- # 🌐 ROUTES
297
  # ======================================================
298
 
299
  INDEX_HTML = '''
@@ -302,18 +344,16 @@ INDEX_HTML = '''
302
  <head>
303
  <meta charset="UTF-8">
304
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
305
- <title>Movie to Comic Generator</title>
306
  <script src="https://cdnjs.cloudflare.com/ajax/libs/html-to-image/1.11.11/html-to-image.min.js"></script>
307
  <link href="https://fonts.googleapis.com/css2?family=Bangers&family=Comic+Neue:wght@700&family=Gloria+Hallelujah&family=Lato&display=swap" rel="stylesheet">
308
  <style>
309
  * { box-sizing: border-box; }
310
  body { background-color: #fdf6e3; font-family: 'Lato', sans-serif; color: #3d3d3d; margin: 0; min-height: 100vh; }
311
 
312
- /* UPLOAD SCREEN */
313
  #upload-container { display: flex; flex-direction:column; justify-content: center; align-items: center; min-height: 100vh; width: 100%; padding: 20px; }
314
  .upload-box { max-width: 500px; width: 100%; padding: 40px; background: white; border-radius: 12px; box-shadow: 0 8px 30px rgba(0,0,0,0.12); text-align: center; }
315
 
316
- /* EDITOR SCREEN */
317
  #editor-container { display: none; padding: 20px; width: 100%; box-sizing: border-box; padding-bottom: 100px; }
318
 
319
  h1 { color: #2c3e50; margin-bottom: 20px; font-weight: 600; }
@@ -321,10 +361,9 @@ INDEX_HTML = '''
321
  .file-label { display: block; padding: 15px; background: #2c3e50; color: white; border-radius: 8px; cursor: pointer; font-weight: bold; margin-bottom: 10px; transition:0.2s; }
322
  .file-label:hover { background: #34495e; }
323
 
324
- /* PAGE INPUT STYLES */
325
- .page-input-group { margin: 15px 0; text-align: left; }
326
  .page-input-group label { font-weight: bold; font-size: 14px; display: block; margin-bottom: 5px; color: #333; }
327
- .page-input-group input { width: 100%; padding: 10px; border: 2px solid #ddd; border-radius: 8px; font-size: 16px; }
328
 
329
  .submit-btn { width: 100%; padding: 15px; background: #e67e22; color: white; border: none; border-radius: 8px; font-size: 18px; font-weight: bold; cursor: pointer; transition: 0.2s; }
330
  .submit-btn:hover { background: #d35400; }
@@ -355,11 +394,12 @@ INDEX_HTML = '''
355
  .bubble-text { padding: 0.8em; word-wrap: break-word; position: relative; z-index: 5; }
356
  .speech-bubble.selected { outline: 2px dashed #4CAF50; z-index: 100; }
357
  .speech-bubble textarea { position: absolute; top:0; left:0; width:100%; height:100%; box-sizing:border-box; border:1px solid #4CAF50; background:rgba(255,255,255,0.95); text-align:center; padding:8px; z-index:102; resize:none; font: inherit; }
358
- .speech-bubble.speech { --b: 3em; --h: 1.8em; --t: 0.6; --p: var(--tail-pos, 50%); --r: 1.2em; --c: var(--bubble-fill-color, #4ECDC4); background: var(--c); color: var(--bubble-text-color, #fff); padding: 1em; position: absolute; border-radius: var(--r) var(--r) min(var(--r), calc(100% - var(--p) - (1 - var(--t)) * var(--b) / 2)) min(var(--r), calc(var(--p) - (1 - var(--t)) * var(--b) / 2)) / var(--r); }
359
- .speech-bubble.speech:before { content: ""; position: absolute; width: var(--b); height: var(--h); background: inherit; border-bottom-left-radius: 100%; pointer-events: none; z-index: 1; -webkit-mask: radial-gradient(calc(var(--t)*100%) 105% at 100% 0,#0000 99%,#000 101%); mask: radial-gradient(calc(var(--t)*100%) 105% at 100% 0,#0000 99%,#000 101%); }
360
- .speech-bubble.speech.tail-bottom:before { top: 100%; left: clamp(0%, calc(var(--p) - (1 - var(--t)) * var(--b) / 2), calc(100% - (1 - var(--t)) * var(--b))); }
361
- .speech-bubble.speech.tail-top { border-radius: min(var(--r), calc(var(--p) - (1 - var(--t)) * var(--b) / 2)) min(var(--r), calc(100% - var(--p) - (1 - var(--t)) * var(--b) / 2)) var(--r) var(--r) / var(--r); }
362
- .speech-bubble.speech.tail-top:before { bottom: 100%; left: clamp(0%, calc(var(--p) - (1 - var(--t)) * var(--b) / 2), calc(100% - (1 - var(--t)) * var(--b))); transform: scaleY(-1); }
 
363
 
364
  .resize-handle { position: absolute; width: 10px; height: 10px; background: #2196F3; border: 1px solid white; border-radius: 50%; display: none; z-index: 11; }
365
  .speech-bubble.selected .resize-handle { display: block; }
@@ -369,10 +409,12 @@ INDEX_HTML = '''
369
  .edit-controls { position: fixed; bottom: 20px; right: 20px; width: 260px; background: rgba(44, 62, 80, 0.95); color: white; padding: 15px; border-radius: 8px; box-shadow: 0 5px 15px rgba(0,0,0,0.3); z-index: 900; font-size: 13px; max-height: 90vh; overflow-y: auto; }
370
  .edit-controls h4 { margin: 0 0 10px 0; color: #4ECDC4; text-align: center; }
371
  .control-group { margin-top: 10px; border-top: 1px solid #555; padding-top: 10px; }
 
372
  button, input, select { width: 100%; margin-top: 5px; padding: 6px; border-radius: 4px; border: 1px solid #ddd; cursor: pointer; font-weight: bold; font-size: 12px; }
373
  .button-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 5px; }
 
374
  .action-btn { background: #4CAF50; color: white; }
375
- .action-btn:disabled { background: #555; cursor: not-allowed; opacity: 0.7; }
376
 
377
  /* MODAL */
378
  .modal-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.7); display: none; justify-content: center; align-items: center; z-index: 9999; }
@@ -383,14 +425,15 @@ INDEX_HTML = '''
383
  <body>
384
  <div id="upload-container">
385
  <div class="upload-box">
386
- <h1>🎬 Comic Generator</h1>
387
  <input type="file" id="file-upload" class="file-input" onchange="document.getElementById('fn').innerText=this.files[0].name">
388
  <label for="file-upload" class="file-label">📁 Choose Video File</label>
389
  <span id="fn" style="margin-bottom:10px; display:block; color:#666;">No file selected</span>
390
 
391
  <div class="page-input-group">
392
- <label>📚 Number of Pages:</label>
393
- <input type="number" id="page-count" value="4" min="1" max="10" placeholder="e.g. 4">
 
394
  </div>
395
 
396
  <button class="submit-btn" onclick="upload()">🚀 Generate Comic</button>
@@ -415,19 +458,40 @@ INDEX_HTML = '''
415
  <input type="file" id="image-uploader" style="display: none;" accept="image/*">
416
  <div class="edit-controls">
417
  <h4>✏️ Interactive Editor</h4>
 
418
  <div class="control-group">
419
  <label>💾 Save & Load:</label>
420
- <button onclick="saveComic()" class="save-btn">💾 Save Comic (Get Code)</button>
421
- <div id="current-save-code" style="display:none; margin-top:8px; padding:8px; background:#2ecc71; border-radius:4px; text-align:center;">
422
- <span id="display-save-code" style="font-size:18px; font-weight:bold; letter-spacing:2px;"></span>
423
- <button onclick="copyCode()" style="padding:4px 8px; margin-left:5px; font-size:10px;">📋 Copy</button>
424
  </div>
425
  </div>
 
426
  <div class="control-group">
427
- <label>💬 Bubble Tools:</label>
428
- <button onclick="addBubble()" class="action-btn">💬 Add Bubble</button>
429
- <button onclick="deleteBubble()" class="reset-btn">🗑️ Delete Bubble</button>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
430
  </div>
 
431
  <div class="control-group">
432
  <label>🖼️ Panel Tools:</label>
433
  <button onclick="replacePanelImage()" class="action-btn">🖼️ Replace Image</button>
@@ -440,14 +504,14 @@ INDEX_HTML = '''
440
  <button onclick="gotoTimestamp()" class="action-btn" id="go-btn">Go</button>
441
  </div>
442
  </div>
 
443
  <div class="control-group">
444
  <button onclick="exportComic()" class="export-btn">📥 Export as PNG</button>
445
- <button onclick="goBackToUpload()" class="reset-btn" style="margin-top:10px;">🏠 Back to Home</button>
446
  </div>
447
  </div>
448
  </div>
449
 
450
- <!-- MODAL -->
451
  <div class="modal-overlay" id="save-modal">
452
  <div class="modal-content">
453
  <h2>✅ Comic Saved!</h2>
@@ -463,11 +527,10 @@ INDEX_HTML = '''
463
  localStorage.setItem('comic_sid', sid);
464
 
465
  let currentSaveCode = null;
466
- let isProcessing = false; // Lock to prevent 429 errors
467
  let interval, selectedBubble = null, selectedPanel = null;
468
  let isDragging = false, isResizing = false;
469
- let startX, startY, initX, initY;
470
- let resizeHandle = '', originalWidth, originalHeight, originalX, originalY, originalMouseX, originalMouseY;
471
  let currentlyEditing = null;
472
 
473
  if(localStorage.getItem('comic_draft_'+sid)) document.getElementById('restore-draft-btn').style.display = 'block';
@@ -477,12 +540,13 @@ INDEX_HTML = '''
477
  function closeModal() { document.getElementById('save-modal').style.display = 'none'; }
478
  function copyModalCode() { navigator.clipboard.writeText(document.getElementById('modal-save-code').textContent).then(() => alert('Code copied!')); }
479
  function copyCode() { if(currentSaveCode) navigator.clipboard.writeText(currentSaveCode).then(() => alert('Code copied!')); }
 
480
  function setProcessing(busy) {
481
  isProcessing = busy;
482
  const btns = ['prev-btn', 'next-btn', 'go-btn'];
483
  btns.forEach(id => {
484
  const el = document.getElementById(id);
485
- if(el) { el.disabled = busy; el.style.opacity = busy ? '0.5' : '1'; }
486
  });
487
  }
488
 
@@ -528,7 +592,12 @@ INDEX_HTML = '''
528
  const bubbles = [];
529
  pan.querySelectorAll('.speech-bubble').forEach(b => {
530
  const textEl = b.querySelector('.bubble-text');
531
- bubbles.push({ text: textEl ? textEl.textContent : '', left: b.style.left, top: b.style.top, width: b.style.width, height: b.style.height, classes: b.className });
 
 
 
 
 
532
  });
533
  panels.push({ src: img.src, bubbles: bubbles });
534
  });
@@ -551,7 +620,6 @@ INDEX_HTML = '''
551
  const pDiv = document.createElement('div'); pDiv.className = 'panel';
552
  pDiv.onclick = (e) => { e.stopPropagation(); selectPanel(pDiv); };
553
  const img = document.createElement('img');
554
- // Add timestamp to src to force refresh
555
  img.src = pan.src.includes('?') ? pan.src : pan.src + `?sid=${sid}`;
556
  pDiv.appendChild(img);
557
  (pan.bubbles || []).forEach(bData => { pDiv.appendChild(createBubbleHTML(bData)); });
@@ -572,7 +640,7 @@ INDEX_HTML = '''
572
 
573
  const fd = new FormData();
574
  fd.append('file', f);
575
- fd.append('target_pages', pCount); // Send page count to backend
576
 
577
  const r = await fetch(`/uploader?sid=${sid}`, {method:'POST', body:fd});
578
  if(r.ok) interval = setInterval(checkStatus, 2000);
@@ -593,7 +661,7 @@ INDEX_HTML = '''
593
  const cleanData = data.map((p, pi) => ({
594
  panels: p.panels.map((pan, j) => ({
595
  src: `/frames/${pan.image}?sid=${sid}`,
596
- bubbles: (p.bubbles && p.bubbles[j] && p.bubbles[j].dialog) ? [{ text: p.bubbles[j].dialog, left: (p.bubbles[j].bubble_offset_x || 50) + 'px', top: (p.bubbles[j].bubble_offset_y || 20) + 'px', classes: 'speech-bubble speech tail-bottom' }] : []
597
  }))
598
  }));
599
  renderFromState(cleanData); saveDraft();
@@ -603,9 +671,19 @@ INDEX_HTML = '''
603
  // --- INTERACTIVE ELEMENTS ---
604
  function createBubbleHTML(data) {
605
  const b = document.createElement('div');
606
- b.className = data.classes || 'speech-bubble speech tail-bottom';
 
 
 
607
  b.style.left = data.left; b.style.top = data.top;
608
  if(data.width) b.style.width = data.width; if(data.height) b.style.height = data.height;
 
 
 
 
 
 
 
609
  const textSpan = document.createElement('span'); textSpan.className = 'bubble-text'; textSpan.textContent = data.text || ''; b.appendChild(textSpan);
610
  ['nw', 'ne', 'sw', 'se'].forEach(dir => { const handle = document.createElement('div'); handle.className = `resize-handle ${dir}`; handle.onmousedown = (e) => startResize(e, dir); b.appendChild(handle); });
611
  b.onmousedown = (e) => { if(e.target.classList.contains('resize-handle')) return; e.stopPropagation(); selectBubble(b); isDragging = true; startX = e.clientX; startY = e.clientY; initX = b.offsetLeft; initY = b.offsetTop; };
@@ -627,10 +705,59 @@ INDEX_HTML = '''
627
  function startResize(e, dir) { e.preventDefault(); e.stopPropagation(); isResizing = true; resizeHandle = dir; const rect = selectedBubble.getBoundingClientRect(); originalWidth = rect.width; originalHeight = rect.height; originalMouseX = e.clientX; originalMouseY = e.clientY; }
628
  function resizeBubble(e) { if (!isResizing || !selectedBubble) return; const dx = e.clientX - originalMouseX; const dy = e.clientY - originalMouseY; if(resizeHandle.includes('e')) selectedBubble.style.width = (originalWidth + dx)+'px'; if(resizeHandle.includes('s')) selectedBubble.style.height = (originalHeight + dy)+'px'; }
629
 
630
- function selectBubble(el) { if(selectedBubble) selectedBubble.classList.remove('selected'); if(selectedPanel) { selectedPanel.classList.remove('selected'); selectedPanel = null; } selectedBubble = el; el.classList.add('selected'); }
631
- function selectPanel(el) { if(selectedPanel) selectedPanel.classList.remove('selected'); if(selectedBubble) { selectedBubble.classList.remove('selected'); selectedBubble = null; } selectedPanel = el; el.classList.add('selected'); }
632
- function addBubble() { if(!selectedPanel) return alert("Select a panel first"); const b = createBubbleHTML({ text: "Text", left: "50px", top: "30px", classes: "speech-bubble speech tail-bottom" }); selectedPanel.appendChild(b); selectBubble(b); saveDraft(); }
633
- function deleteBubble() { if(!selectedBubble) return alert("Select a bubble"); selectedBubble.remove(); selectedBubble=null; saveDraft(); }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
634
 
635
  function replacePanelImage() {
636
  if(!selectedPanel) return alert("Select a panel");
@@ -647,12 +774,12 @@ INDEX_HTML = '''
647
  }
648
 
649
  async function adjustFrame(dir) {
650
- if(isProcessing) return; // LOCK
651
  if(!selectedPanel) return alert("Select a panel");
652
  const img = selectedPanel.querySelector('img');
653
  let fname = img.src.split('/').pop().split('?')[0];
654
 
655
- setProcessing(true); // ENABLE LOCK
656
  img.style.opacity = '0.5';
657
 
658
  try {
@@ -663,12 +790,12 @@ INDEX_HTML = '''
663
  } catch(e) { console.error(e); }
664
 
665
  img.style.opacity = '1';
666
- setProcessing(false); // RELEASE LOCK
667
  saveDraft();
668
  }
669
 
670
  async function gotoTimestamp() {
671
- if(isProcessing) return; // LOCK
672
  if(!selectedPanel) return alert("Select a panel");
673
  let v = document.getElementById('timestamp-input').value.trim();
674
  if(!v) return;
@@ -678,7 +805,7 @@ INDEX_HTML = '''
678
  const img = selectedPanel.querySelector('img');
679
  let fname = img.src.split('/').pop().split('?')[0];
680
 
681
- setProcessing(true); // ENABLE LOCK
682
  img.style.opacity = '0.5';
683
 
684
  try {
@@ -689,7 +816,7 @@ INDEX_HTML = '''
689
  } catch(e) { console.error(e); }
690
 
691
  img.style.opacity = '1';
692
- setProcessing(false); // RELEASE LOCK
693
  saveDraft();
694
  }
695
 
@@ -735,6 +862,7 @@ def upload():
735
  f.save(gen.video_path)
736
  gen.write_status("Starting...", 5)
737
 
 
738
  threading.Thread(target=gen.run, args=(target_pages,)).start()
739
  return jsonify({'success': True, 'message': 'Generation started.'})
740
 
 
24
  return True
25
 
26
  # ======================================================
27
+ # 🧱 DATA CLASSES (Robust Local Definitions)
28
  # ======================================================
29
+ def bubble(dialog="", bubble_offset_x=50, bubble_offset_y=20, lip_x=-1, lip_y=-1, emotion='normal', type='speech'):
30
+ # Returns a dictionary that matches the frontend expectations
31
  return {
32
  'dialog': dialog,
33
  'bubble_offset_x': int(bubble_offset_x),
34
  'bubble_offset_y': int(bubble_offset_y),
35
  'lip_x': int(lip_x),
36
  'lip_y': int(lip_y),
37
+ 'emotion': emotion,
38
+ 'type': type, # speech, thought, reaction, narration
39
+ 'tail_pos': 50,
40
+ 'tail_direction': 'bottom'
41
  }
42
 
43
  def panel(image=""):
 
49
  self.bubbles = bubbles
50
 
51
  # ======================================================
52
+ # 🔧 APP CONFIG
53
  # ======================================================
54
  logging.basicConfig(level=logging.INFO)
55
  logger = logging.getLogger(__name__)
 
69
  return code
70
 
71
  # ======================================================
72
+ # 🧠 GLOBAL GPU FUNCTIONS (THE ENGINE)
73
  # ======================================================
74
 
75
+ @spaces.GPU(duration=300) # Increased duration for longer videos
76
  def generate_comic_gpu(video_path, user_dir, frames_dir, metadata_path, target_pages):
77
  print(f"🚀 GPU Task Started: {video_path} | Target Pages: {target_pages}")
78
 
79
+ # --- Local Imports for GPU Context ---
80
  import cv2
81
  import srt
82
  import math
 
96
  duration = total_frames / fps
97
  cap.release()
98
 
99
+ # 2. Subtitles Generation
100
  user_srt = os.path.join(user_dir, 'subs.srt')
101
  try:
102
+ print("🎬 Extracting subtitles...")
103
  get_real_subtitles(video_path)
104
  if os.path.exists('test1.srt'):
105
  shutil.move('test1.srt', user_srt)
106
  except Exception as e:
107
+ print(f"⚠️ Subtitle error: {e}. Using fallback.")
108
+ with open(user_srt, 'w') as f: f.write("1\n00:00:01,000 --> 00:00:04,000\n...\n")
109
 
110
  with open(user_srt, 'r', encoding='utf-8') as f:
111
  all_subs = list(srt.parse(f.read()))
112
 
113
+ # 3. Smart Keyframe Selection (Equal Division Logic)
114
+ raw_moments = [{'index': s.index, 'text': s.content, 'start': s.start.total_seconds(), 'end': s.end.total_seconds()} for s in all_subs]
115
+ raw_moments.sort(key=lambda x: x['start'])
116
 
117
+ # LOGIC: 4 panels per page.
118
+ if target_pages <= 0: target_pages = 1
119
+ panels_per_page = 4
120
+ total_panels_needed = target_pages * panels_per_page
121
+
122
+ print(f"📊 Calculating: Needed {total_panels_needed} panels for {target_pages} pages.")
123
+
124
+ selected_moments = []
125
+ if len(raw_moments) <= total_panels_needed:
126
+ # If video is short/has few lines, take all
127
+ selected_moments = raw_moments
128
+ else:
129
+ # EVENLY DISTRIBUTE selection across the entire list
130
+ # This ensures the comic covers the beginning, middle, and end.
131
+ indices = np.linspace(0, len(raw_moments) - 1, total_panels_needed, dtype=int)
132
+ selected_moments = [raw_moments[i] for i in indices]
133
+
134
+ # 4. Extract Frames
135
  frame_metadata = {}
136
  cap = cv2.VideoCapture(video_path)
137
  count = 0
138
+ frame_files_ordered = []
139
+
140
+ print(f"📸 Extracting {len(selected_moments)} frames...")
141
 
142
+ for i, moment in enumerate(selected_moments):
143
  mid = (moment['start'] + moment['end']) / 2
144
  if mid > duration: continue
145
+
146
  cap.set(cv2.CAP_PROP_POS_FRAMES, int(mid * fps))
147
  ret, frame = cap.read()
148
  if ret:
149
  fname = f"frame_{count:04d}.png"
150
  p = os.path.join(frames_dir, fname)
151
  cv2.imwrite(p, frame)
152
+
153
+ # Save metadata
154
+ frame_metadata[fname] = {
155
+ 'dialogue': moment['text'],
156
+ 'time': mid,
157
+ 'start': moment['start'],
158
+ 'end': moment['end']
159
+ }
160
+ frame_files_ordered.append(fname)
161
  count += 1
162
+
163
+ # Sync to disk to prevent libpng errors on fast writes
164
+ os.sync()
165
  cap.release()
166
 
167
+ with open(metadata_path, 'w') as f: json.dump(frame_metadata, f, indent=2)
168
 
169
+ # 5. Image Enhancement
170
  try: black_bar_crop()
171
  except: pass
172
 
173
  se = SimpleColorEnhancer()
174
  qe = QualityColorEnhancer()
 
175
 
176
+ print("🎨 Enhancing images...")
177
+ for f in frame_files_ordered:
178
  p = os.path.join(frames_dir, f)
179
+ try: se.enhance_single(p, p) # Overwrite
180
  except: pass
181
+ try: qe.enhance_single(p, p) # Overwrite
182
  except: pass
183
 
184
+ # 6. Bubble Placement & Type Detection
185
+ print("💬 Analyzing faces and bubbles...")
186
  bubbles_list = []
187
+
188
+ for f in frame_files_ordered:
189
  p = os.path.join(frames_dir, f)
190
  dialogue = frame_metadata.get(f, {}).get('dialogue', '')
191
+
192
+ # Determine bubble type based on text content (Simple heuristic)
193
+ b_type = 'speech'
194
+ if '(' in dialogue and ')' in dialogue: b_type = 'narration' # (Sound effect)
195
+ elif '!' in dialogue and dialogue.isupper(): b_type = 'reaction' # SHOUTING
196
+ elif '?' in dialogue: b_type = 'speech'
197
+
198
  try:
199
  faces = face_detector.detect_faces(p)
200
  lip = face_detector.get_lip_position(p, faces[0]) if faces else (-1, -1)
201
  bx, by = ai_bubble_placer.place_bubble_ai(p, lip)
202
+
203
+ b = bubble(
204
+ dialog=dialogue,
205
+ bubble_offset_x=bx,
206
+ bubble_offset_y=by,
207
+ lip_x=lip[0],
208
+ lip_y=lip[1],
209
+ emotion='normal',
210
+ type=b_type
211
+ )
212
+ bubbles_list.append(b)
213
  except:
214
+ bubbles_list.append(bubble(dialog=dialogue, type=b_type))
215
 
216
+ # 7. Final Layout Construction
217
+ print("📄 Assembling pages...")
 
 
 
 
 
 
 
 
 
 
 
218
  pages = []
219
+
220
+ # We strictly use 4 panels per page for consistency based on user input
221
  for i in range(target_pages):
222
+ start_idx = i * 4
223
+ end_idx = start_idx + 4
224
 
225
+ # Get slice for this page
226
+ p_frames = frame_files_ordered[start_idx:end_idx]
227
+ p_bubbles = bubbles_list[start_idx:end_idx]
228
 
229
+ if p_frames:
230
+ pg_panels = [panel(image=f) for f in p_frames]
231
+ pages.append(Page(panels=pg_panels, bubbles=p_bubbles))
232
 
233
+ # Serialize
234
  result = []
235
  for pg in pages:
236
  p_data = [p if isinstance(p, dict) else p.__dict__ for p in pg.panels]
 
261
 
262
  if ret:
263
  p = os.path.join(frames_dir, fname)
 
264
  cv2.imwrite(p, frame)
265
+ os.sync()
 
266
  try: SimpleColorEnhancer().enhance_single(p, p)
267
  except: pass
268
 
 
287
  p = os.path.join(frames_dir, fname)
288
  cv2.imwrite(p, frame)
289
  os.sync()
 
290
  try: SimpleColorEnhancer().enhance_single(p, p)
291
  except: pass
292
 
 
322
  def run(self, target_pages):
323
  try:
324
  self.write_status("Waiting for GPU...", 5)
 
325
  data = generate_comic_gpu(self.video_path, self.user_dir, self.frames_dir, self.metadata_path, int(target_pages))
326
  with open(os.path.join(self.output_dir, 'pages.json'), 'w') as f:
327
  json.dump(data, f, indent=2)
 
335
  json.dump({'message': msg, 'progress': prog}, f)
336
 
337
  # ======================================================
338
+ # 🌐 ROUTES & HTML
339
  # ======================================================
340
 
341
  INDEX_HTML = '''
 
344
  <head>
345
  <meta charset="UTF-8">
346
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
347
+ <title>🎬 Enhanced Comic Generator</title>
348
  <script src="https://cdnjs.cloudflare.com/ajax/libs/html-to-image/1.11.11/html-to-image.min.js"></script>
349
  <link href="https://fonts.googleapis.com/css2?family=Bangers&family=Comic+Neue:wght@700&family=Gloria+Hallelujah&family=Lato&display=swap" rel="stylesheet">
350
  <style>
351
  * { box-sizing: border-box; }
352
  body { background-color: #fdf6e3; font-family: 'Lato', sans-serif; color: #3d3d3d; margin: 0; min-height: 100vh; }
353
 
 
354
  #upload-container { display: flex; flex-direction:column; justify-content: center; align-items: center; min-height: 100vh; width: 100%; padding: 20px; }
355
  .upload-box { max-width: 500px; width: 100%; padding: 40px; background: white; border-radius: 12px; box-shadow: 0 8px 30px rgba(0,0,0,0.12); text-align: center; }
356
 
 
357
  #editor-container { display: none; padding: 20px; width: 100%; box-sizing: border-box; padding-bottom: 100px; }
358
 
359
  h1 { color: #2c3e50; margin-bottom: 20px; font-weight: 600; }
 
361
  .file-label { display: block; padding: 15px; background: #2c3e50; color: white; border-radius: 8px; cursor: pointer; font-weight: bold; margin-bottom: 10px; transition:0.2s; }
362
  .file-label:hover { background: #34495e; }
363
 
364
+ .page-input-group { margin: 20px 0; text-align: left; }
 
365
  .page-input-group label { font-weight: bold; font-size: 14px; display: block; margin-bottom: 5px; color: #333; }
366
+ .page-input-group input { width: 100%; padding: 12px; border: 2px solid #ddd; border-radius: 8px; font-size: 16px; box-sizing: border-box; }
367
 
368
  .submit-btn { width: 100%; padding: 15px; background: #e67e22; color: white; border: none; border-radius: 8px; font-size: 18px; font-weight: bold; cursor: pointer; transition: 0.2s; }
369
  .submit-btn:hover { background: #d35400; }
 
394
  .bubble-text { padding: 0.8em; word-wrap: break-word; position: relative; z-index: 5; }
395
  .speech-bubble.selected { outline: 2px dashed #4CAF50; z-index: 100; }
396
  .speech-bubble textarea { position: absolute; top:0; left:0; width:100%; height:100%; box-sizing:border-box; border:1px solid #4CAF50; background:rgba(255,255,255,0.95); text-align:center; padding:8px; z-index:102; resize:none; font: inherit; }
397
+
398
+ /* BUBBLE STYLES */
399
+ .speech-bubble.speech { background: var(--bubble-fill-color, #4ECDC4); color: var(--bubble-text-color, #fff); border-radius: 20px; }
400
+ .speech-bubble.thought { background: white; border: 2px dashed #555; color: #333; border-radius: 50%; }
401
+ .speech-bubble.reaction { background: #FFD700; border: 3px solid #E53935; color: #D32F2F; clip-path: polygon(0% 25%, 17% 21%, 17% 0%, 31% 16%, 50% 4%, 69% 16%, 83% 0%, 83% 21%, 100% 25%, 85% 45%, 95% 62%, 82% 79%, 100% 97%, 79% 89%, 60% 98%, 46% 82%, 27% 95%, 15% 78%, 5% 62%, 15% 45%); }
402
+ .speech-bubble.narration { background: #FAFAFA; border: 2px solid #BDBDBD; color: #424242; border-radius: 3px; }
403
 
404
  .resize-handle { position: absolute; width: 10px; height: 10px; background: #2196F3; border: 1px solid white; border-radius: 50%; display: none; z-index: 11; }
405
  .speech-bubble.selected .resize-handle { display: block; }
 
409
  .edit-controls { position: fixed; bottom: 20px; right: 20px; width: 260px; background: rgba(44, 62, 80, 0.95); color: white; padding: 15px; border-radius: 8px; box-shadow: 0 5px 15px rgba(0,0,0,0.3); z-index: 900; font-size: 13px; max-height: 90vh; overflow-y: auto; }
410
  .edit-controls h4 { margin: 0 0 10px 0; color: #4ECDC4; text-align: center; }
411
  .control-group { margin-top: 10px; border-top: 1px solid #555; padding-top: 10px; }
412
+ .control-group label { font-size: 11px; font-weight: bold; display: block; margin-bottom: 3px; }
413
  button, input, select { width: 100%; margin-top: 5px; padding: 6px; border-radius: 4px; border: 1px solid #ddd; cursor: pointer; font-weight: bold; font-size: 12px; }
414
  .button-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 5px; }
415
+ .color-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 5px; }
416
  .action-btn { background: #4CAF50; color: white; }
417
+ .reset-btn { background: #e74c3c; color: white; }
418
 
419
  /* MODAL */
420
  .modal-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.7); display: none; justify-content: center; align-items: center; z-index: 9999; }
 
425
  <body>
426
  <div id="upload-container">
427
  <div class="upload-box">
428
+ <h1>🎬 Enhanced Comic Generator</h1>
429
  <input type="file" id="file-upload" class="file-input" onchange="document.getElementById('fn').innerText=this.files[0].name">
430
  <label for="file-upload" class="file-label">📁 Choose Video File</label>
431
  <span id="fn" style="margin-bottom:10px; display:block; color:#666;">No file selected</span>
432
 
433
  <div class="page-input-group">
434
+ <label>📚 Total Comic Pages:</label>
435
+ <input type="number" id="page-count" value="4" min="1" max="15" placeholder="e.g. 4 (Video will be divided evenly)">
436
+ <small style="color:#666; font-size:11px; display:block; margin-top:5px;">System calculates ~4 panels per page.</small>
437
  </div>
438
 
439
  <button class="submit-btn" onclick="upload()">🚀 Generate Comic</button>
 
458
  <input type="file" id="image-uploader" style="display: none;" accept="image/*">
459
  <div class="edit-controls">
460
  <h4>✏️ Interactive Editor</h4>
461
+
462
  <div class="control-group">
463
  <label>💾 Save & Load:</label>
464
+ <button onclick="saveComic()" class="save-btn">💾 Save Comic</button>
465
+ <div id="current-save-code" style="display:none; margin-top:5px; text-align:center;">
466
+ <span id="display-save-code" style="font-weight:bold; background:#eee; padding:2px 5px; border-radius:3px;"></span>
467
+ <button onclick="copyCode()" style="padding:2px; width:auto; font-size:10px;">Copy</button>
468
  </div>
469
  </div>
470
+
471
  <div class="control-group">
472
+ <label>💬 Bubble Styling:</label>
473
+ <select id="bubble-type-select" onchange="changeBubbleType(this.value)" disabled>
474
+ <option value="speech">Speech</option>
475
+ <option value="thought">Thought</option>
476
+ <option value="reaction">Reaction (Shout)</option>
477
+ <option value="narration">Narration (Box)</option>
478
+ </select>
479
+ <select id="font-select" onchange="changeFont(this.value)" disabled>
480
+ <option value="'Comic Neue', cursive">Comic Neue</option>
481
+ <option value="'Bangers', cursive">Bangers</option>
482
+ <option value="'Gloria Hallelujah', cursive">Gloria</option>
483
+ <option value="'Lato', sans-serif">Lato</option>
484
+ </select>
485
+ <div class="color-grid">
486
+ <div><label>Text</label><input type="color" id="bubble-text-color" value="#ffffff" disabled></div>
487
+ <div><label>Fill</label><input type="color" id="bubble-fill-color" value="#4ECDC4" disabled></div>
488
+ </div>
489
+ <div class="button-grid">
490
+ <button onclick="addBubble()" class="action-btn">Add</button>
491
+ <button onclick="deleteBubble()" class="reset-btn">Delete</button>
492
+ </div>
493
  </div>
494
+
495
  <div class="control-group">
496
  <label>🖼️ Panel Tools:</label>
497
  <button onclick="replacePanelImage()" class="action-btn">🖼️ Replace Image</button>
 
504
  <button onclick="gotoTimestamp()" class="action-btn" id="go-btn">Go</button>
505
  </div>
506
  </div>
507
+
508
  <div class="control-group">
509
  <button onclick="exportComic()" class="export-btn">📥 Export as PNG</button>
510
+ <button onclick="goBackToUpload()" class="reset-btn" style="margin-top:10px;">🏠 Home</button>
511
  </div>
512
  </div>
513
  </div>
514
 
 
515
  <div class="modal-overlay" id="save-modal">
516
  <div class="modal-content">
517
  <h2>✅ Comic Saved!</h2>
 
527
  localStorage.setItem('comic_sid', sid);
528
 
529
  let currentSaveCode = null;
530
+ let isProcessing = false; // Lock for ZeroGPU throttling
531
  let interval, selectedBubble = null, selectedPanel = null;
532
  let isDragging = false, isResizing = false;
533
+ let startX, startY, initX, initY, resizeHandle, originalWidth, originalHeight;
 
534
  let currentlyEditing = null;
535
 
536
  if(localStorage.getItem('comic_draft_'+sid)) document.getElementById('restore-draft-btn').style.display = 'block';
 
540
  function closeModal() { document.getElementById('save-modal').style.display = 'none'; }
541
  function copyModalCode() { navigator.clipboard.writeText(document.getElementById('modal-save-code').textContent).then(() => alert('Code copied!')); }
542
  function copyCode() { if(currentSaveCode) navigator.clipboard.writeText(currentSaveCode).then(() => alert('Code copied!')); }
543
+
544
  function setProcessing(busy) {
545
  isProcessing = busy;
546
  const btns = ['prev-btn', 'next-btn', 'go-btn'];
547
  btns.forEach(id => {
548
  const el = document.getElementById(id);
549
+ if(el) { el.disabled = busy; el.style.opacity = busy ? '0.5' : '1'; el.innerText = busy ? '⏳' : el.getAttribute('data-txt') || el.innerText; }
550
  });
551
  }
552
 
 
592
  const bubbles = [];
593
  pan.querySelectorAll('.speech-bubble').forEach(b => {
594
  const textEl = b.querySelector('.bubble-text');
595
+ bubbles.push({
596
+ text: textEl ? textEl.textContent : '',
597
+ left: b.style.left, top: b.style.top, width: b.style.width, height: b.style.height,
598
+ classes: b.className, type: b.dataset.type, font: b.style.fontFamily,
599
+ colors: { fill: b.style.getPropertyValue('--bubble-fill-color'), text: b.style.getPropertyValue('--bubble-text-color') }
600
+ });
601
  });
602
  panels.push({ src: img.src, bubbles: bubbles });
603
  });
 
620
  const pDiv = document.createElement('div'); pDiv.className = 'panel';
621
  pDiv.onclick = (e) => { e.stopPropagation(); selectPanel(pDiv); };
622
  const img = document.createElement('img');
 
623
  img.src = pan.src.includes('?') ? pan.src : pan.src + `?sid=${sid}`;
624
  pDiv.appendChild(img);
625
  (pan.bubbles || []).forEach(bData => { pDiv.appendChild(createBubbleHTML(bData)); });
 
640
 
641
  const fd = new FormData();
642
  fd.append('file', f);
643
+ fd.append('target_pages', pCount);
644
 
645
  const r = await fetch(`/uploader?sid=${sid}`, {method:'POST', body:fd});
646
  if(r.ok) interval = setInterval(checkStatus, 2000);
 
661
  const cleanData = data.map((p, pi) => ({
662
  panels: p.panels.map((pan, j) => ({
663
  src: `/frames/${pan.image}?sid=${sid}`,
664
+ bubbles: (p.bubbles && p.bubbles[j] && p.bubbles[j].dialog) ? [{ text: p.bubbles[j].dialog, left: (p.bubbles[j].bubble_offset_x || 50) + 'px', top: (p.bubbles[j].bubble_offset_y || 20) + 'px', type: (p.bubbles[j].type || 'speech') }] : []
665
  }))
666
  }));
667
  renderFromState(cleanData); saveDraft();
 
671
  // --- INTERACTIVE ELEMENTS ---
672
  function createBubbleHTML(data) {
673
  const b = document.createElement('div');
674
+ b.className = 'speech-bubble ' + (data.type || 'speech');
675
+ if(data.classes) b.className = data.classes;
676
+
677
+ b.dataset.type = data.type || 'speech';
678
  b.style.left = data.left; b.style.top = data.top;
679
  if(data.width) b.style.width = data.width; if(data.height) b.style.height = data.height;
680
+ if(data.font) b.style.fontFamily = data.font;
681
+
682
+ if(data.colors) {
683
+ b.style.setProperty('--bubble-fill-color', data.colors.fill || '#4ECDC4');
684
+ b.style.setProperty('--bubble-text-color', data.colors.text || '#ffffff');
685
+ }
686
+
687
  const textSpan = document.createElement('span'); textSpan.className = 'bubble-text'; textSpan.textContent = data.text || ''; b.appendChild(textSpan);
688
  ['nw', 'ne', 'sw', 'se'].forEach(dir => { const handle = document.createElement('div'); handle.className = `resize-handle ${dir}`; handle.onmousedown = (e) => startResize(e, dir); b.appendChild(handle); });
689
  b.onmousedown = (e) => { if(e.target.classList.contains('resize-handle')) return; e.stopPropagation(); selectBubble(b); isDragging = true; startX = e.clientX; startY = e.clientY; initX = b.offsetLeft; initY = b.offsetTop; };
 
705
  function startResize(e, dir) { e.preventDefault(); e.stopPropagation(); isResizing = true; resizeHandle = dir; const rect = selectedBubble.getBoundingClientRect(); originalWidth = rect.width; originalHeight = rect.height; originalMouseX = e.clientX; originalMouseY = e.clientY; }
706
  function resizeBubble(e) { if (!isResizing || !selectedBubble) return; const dx = e.clientX - originalMouseX; const dy = e.clientY - originalMouseY; if(resizeHandle.includes('e')) selectedBubble.style.width = (originalWidth + dx)+'px'; if(resizeHandle.includes('s')) selectedBubble.style.height = (originalHeight + dy)+'px'; }
707
 
708
+ function selectBubble(el) {
709
+ if(selectedBubble) selectedBubble.classList.remove('selected');
710
+ if(selectedPanel) { selectedPanel.classList.remove('selected'); selectedPanel = null; }
711
+ selectedBubble = el; el.classList.add('selected');
712
+
713
+ // Update controls
714
+ document.getElementById('bubble-type-select').disabled = false;
715
+ document.getElementById('font-select').disabled = false;
716
+ document.getElementById('bubble-text-color').disabled = false;
717
+ document.getElementById('bubble-fill-color').disabled = false;
718
+
719
+ document.getElementById('bubble-type-select').value = el.dataset.type || 'speech';
720
+ }
721
+
722
+ function selectPanel(el) {
723
+ if(selectedPanel) selectedPanel.classList.remove('selected');
724
+ if(selectedBubble) { selectedBubble.classList.remove('selected'); selectedBubble = null; }
725
+ selectedPanel = el; el.classList.add('selected');
726
+
727
+ document.getElementById('bubble-type-select').disabled = true;
728
+ document.getElementById('font-select').disabled = true;
729
+ }
730
+
731
+ function addBubble() {
732
+ if(!selectedPanel) return alert("Select a panel first");
733
+ const b = createBubbleHTML({ text: "Text", left: "50px", top: "30px", type: 'speech' });
734
+ selectedPanel.appendChild(b); selectBubble(b); saveDraft();
735
+ }
736
+
737
+ function deleteBubble() {
738
+ if(!selectedBubble) return alert("Select a bubble");
739
+ selectedBubble.remove(); selectedBubble=null; saveDraft();
740
+ }
741
+
742
+ function changeBubbleType(type) {
743
+ if(!selectedBubble) return;
744
+ selectedBubble.dataset.type = type;
745
+ selectedBubble.className = 'speech-bubble ' + type + ' selected';
746
+ saveDraft();
747
+ }
748
+
749
+ function changeFont(font) {
750
+ if(!selectedBubble) return;
751
+ selectedBubble.style.fontFamily = font;
752
+ saveDraft();
753
+ }
754
+
755
+ document.getElementById('bubble-text-color').addEventListener('input', (e) => {
756
+ if(selectedBubble) { selectedBubble.style.setProperty('--bubble-text-color', e.target.value); saveDraft(); }
757
+ });
758
+ document.getElementById('bubble-fill-color').addEventListener('input', (e) => {
759
+ if(selectedBubble) { selectedBubble.style.setProperty('--bubble-fill-color', e.target.value); saveDraft(); }
760
+ });
761
 
762
  function replacePanelImage() {
763
  if(!selectedPanel) return alert("Select a panel");
 
774
  }
775
 
776
  async function adjustFrame(dir) {
777
+ if(isProcessing) return;
778
  if(!selectedPanel) return alert("Select a panel");
779
  const img = selectedPanel.querySelector('img');
780
  let fname = img.src.split('/').pop().split('?')[0];
781
 
782
+ setProcessing(true);
783
  img.style.opacity = '0.5';
784
 
785
  try {
 
790
  } catch(e) { console.error(e); }
791
 
792
  img.style.opacity = '1';
793
+ setProcessing(false);
794
  saveDraft();
795
  }
796
 
797
  async function gotoTimestamp() {
798
+ if(isProcessing) return;
799
  if(!selectedPanel) return alert("Select a panel");
800
  let v = document.getElementById('timestamp-input').value.trim();
801
  if(!v) return;
 
805
  const img = selectedPanel.querySelector('img');
806
  let fname = img.src.split('/').pop().split('?')[0];
807
 
808
+ setProcessing(true);
809
  img.style.opacity = '0.5';
810
 
811
  try {
 
816
  } catch(e) { console.error(e); }
817
 
818
  img.style.opacity = '1';
819
+ setProcessing(false);
820
  saveDraft();
821
  }
822
 
 
862
  f.save(gen.video_path)
863
  gen.write_status("Starting...", 5)
864
 
865
+ # Run in thread
866
  threading.Thread(target=gen.run, args=(target_pages,)).start()
867
  return jsonify({'success': True, 'message': 'Generation started.'})
868