tester343 commited on
Commit
396b6f1
·
verified ·
1 Parent(s): 811b65f

Update app_enhanced.py

Browse files
Files changed (1) hide show
  1. app_enhanced.py +192 -431
app_enhanced.py CHANGED
@@ -24,7 +24,7 @@ def gpu_warmup():
24
  return True
25
 
26
  # ======================================================
27
- # 💾 PERSISTENT STORAGE CONFIGURATION
28
  # ======================================================
29
  if os.path.exists('/data'):
30
  BASE_STORAGE_PATH = '/data'
@@ -42,14 +42,11 @@ os.makedirs(SAVED_COMICS_DIR, exist_ok=True)
42
  # ======================================================
43
  # 🧱 DATA CLASSES
44
  # ======================================================
45
- def bubble(dialog="", bubble_offset_x=50, bubble_offset_y=20, lip_x=-1, lip_y=-1, emotion='normal', type='speech'):
46
  return {
47
  'dialog': dialog,
48
  'bubble_offset_x': int(bubble_offset_x),
49
  'bubble_offset_y': int(bubble_offset_y),
50
- 'lip_x': int(lip_x),
51
- 'lip_y': int(lip_y),
52
- 'emotion': emotion,
53
  'type': type,
54
  'tail_pos': '50%',
55
  'classes': f'speech-bubble {type} tail-bottom'
@@ -67,8 +64,6 @@ class Page:
67
  # 🔧 APP CONFIG
68
  # ======================================================
69
  logging.basicConfig(level=logging.INFO)
70
- logger = logging.getLogger(__name__)
71
-
72
  app = Flask(__name__)
73
 
74
  def generate_save_code(length=8):
@@ -79,22 +74,17 @@ def generate_save_code(length=8):
79
  return code
80
 
81
  # ======================================================
82
- # 🧠 GLOBAL GPU FUNCTIONS
83
  # ======================================================
84
- @spaces.GPU(duration=300)
85
  def generate_comic_gpu(video_path, user_dir, frames_dir, metadata_path, target_pages):
86
- print(f"🚀 GPU Task Started: {video_path} | Pages: {target_pages}")
87
 
88
  import cv2
89
  import srt
90
  import numpy as np
91
- from backend.keyframes.keyframes import black_bar_crop
92
- from backend.simple_color_enhancer import SimpleColorEnhancer
93
- from backend.quality_color_enhancer import QualityColorEnhancer
94
- from backend.subtitles.subs_real import get_real_subtitles
95
- from backend.ai_bubble_placement import ai_bubble_placer
96
- from backend.ai_enhanced_core import face_detector
97
-
98
  cap = cv2.VideoCapture(video_path)
99
  if not cap.isOpened(): raise Exception("Cannot open video")
100
  fps = cap.get(cv2.CAP_PROP_FPS) or 25
@@ -102,12 +92,10 @@ def generate_comic_gpu(video_path, user_dir, frames_dir, metadata_path, target_p
102
  duration = total_frames / fps
103
  cap.release()
104
 
 
105
  user_srt = os.path.join(user_dir, 'subs.srt')
106
- try:
107
- get_real_subtitles(video_path)
108
- if os.path.exists('test1.srt'):
109
- shutil.move('test1.srt', user_srt)
110
- except:
111
  with open(user_srt, 'w') as f: f.write("1\n00:00:01,000 --> 00:00:04,000\n...\n")
112
 
113
  with open(user_srt, 'r', encoding='utf-8') as f:
@@ -117,13 +105,14 @@ def generate_comic_gpu(video_path, user_dir, frames_dir, metadata_path, target_p
117
  valid_subs = [s for s in all_subs if s.content.strip()]
118
  raw_moments = [{'text': s.content, 'start': s.start.total_seconds(), 'end': s.end.total_seconds()} for s in valid_subs]
119
 
 
120
  if target_pages <= 0: target_pages = 1
121
  panels_per_page = 4
122
  total_panels_needed = target_pages * panels_per_page
123
 
124
  selected_moments = []
125
  if not raw_moments:
126
- times = np.linspace(1, duration-1, total_panels_needed)
127
  for t in times: selected_moments.append({'text': '', 'start': t, 'end': t+1})
128
  elif len(raw_moments) <= total_panels_needed:
129
  selected_moments = raw_moments
@@ -131,6 +120,7 @@ def generate_comic_gpu(video_path, user_dir, frames_dir, metadata_path, target_p
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
  frame_metadata = {}
135
  cap = cv2.VideoCapture(video_path)
136
  count = 0
@@ -138,60 +128,40 @@ def generate_comic_gpu(video_path, user_dir, frames_dir, metadata_path, target_p
138
 
139
  for i, moment in enumerate(selected_moments):
140
  mid = (moment['start'] + moment['end']) / 2
141
- if mid > duration: mid = duration - 1
142
- cap.set(cv2.CAP_PROP_POS_FRAMES, int(mid * fps))
143
  ret, frame = cap.read()
 
144
  if ret:
145
  # ------------------------------------------------
146
- # 🎯 CRITICAL: RESIZE TO 400x600 (TEMPLATE SPEC)
 
147
  # ------------------------------------------------
148
- frame = cv2.resize(frame, (400, 600))
149
 
150
  fname = f"frame_{count:04d}.png"
151
  p = os.path.join(frames_dir, fname)
152
  cv2.imwrite(p, frame)
153
- os.sync()
154
  frame_metadata[fname] = {'dialogue': moment['text'], 'time': mid}
155
  frame_files_ordered.append(fname)
156
  count += 1
 
157
  cap.release()
158
-
159
  with open(metadata_path, 'w') as f: json.dump(frame_metadata, f, indent=2)
160
 
161
- try: black_bar_crop()
162
- except: pass
163
-
164
- se = SimpleColorEnhancer()
165
- qe = QualityColorEnhancer()
166
-
167
- for f in frame_files_ordered:
168
- p = os.path.join(frames_dir, f)
169
- try: se.enhance_single(p, p)
170
- except: pass
171
- try: qe.enhance_single(p, p)
172
- except: pass
173
-
174
  bubbles_list = []
175
  for f in frame_files_ordered:
176
- p = os.path.join(frames_dir, f)
177
  dialogue = frame_metadata.get(f, {}).get('dialogue', '')
178
-
179
  b_type = 'speech'
180
- if '(' in dialogue and ')' in dialogue: b_type = 'narration'
181
- elif '!' in dialogue and dialogue.isupper(): b_type = 'reaction'
182
- elif '?' in dialogue: b_type = 'speech'
183
 
184
- try:
185
- # AI Placement still runs to find initial coordinates
186
- # Note: Coordinates might need scaling in frontend if original frame wasn't 400x600
187
- faces = face_detector.detect_faces(p)
188
- lip = face_detector.get_lip_position(p, faces[0]) if faces else (-1, -1)
189
- bx, by = ai_bubble_placer.place_bubble_ai(p, lip)
190
- b = bubble(dialog=dialogue, bubble_offset_x=bx, bubble_offset_y=by, lip_x=lip[0], lip_y=lip[1], type=b_type)
191
- bubbles_list.append(b)
192
- except:
193
- bubbles_list.append(bubble(dialog=dialogue, type=b_type))
194
 
 
195
  pages = []
196
  for i in range(target_pages):
197
  start_idx = i * 4
@@ -199,11 +169,10 @@ def generate_comic_gpu(video_path, user_dir, frames_dir, metadata_path, target_p
199
  p_frames = frame_files_ordered[start_idx:end_idx]
200
  p_bubbles = bubbles_list[start_idx:end_idx]
201
 
202
- # Ensure 4 panels per page for the template
203
  while len(p_frames) < 4:
204
- # Create empty placeholder if run out of frames
205
  fname = f"empty_{i}_{len(p_frames)}.png"
206
- img = np.zeros((600, 400, 3), dtype=np.uint8); img[:] = (50,50,50)
207
  cv2.imwrite(os.path.join(frames_dir, fname), img)
208
  p_frames.append(fname)
209
  p_bubbles.append(bubble(dialog="", type='speech'))
@@ -212,6 +181,7 @@ def generate_comic_gpu(video_path, user_dir, frames_dir, metadata_path, target_p
212
  pg_panels = [panel(image=f) for f in p_frames]
213
  pages.append(Page(panels=pg_panels, bubbles=p_bubbles))
214
 
 
215
  result = []
216
  for pg in pages:
217
  p_data = [p if isinstance(p, dict) else p.__dict__ for p in pg.panels]
@@ -224,7 +194,6 @@ def generate_comic_gpu(video_path, user_dir, frames_dir, metadata_path, target_p
224
  def regen_frame_gpu(video_path, frames_dir, metadata_path, fname, direction):
225
  import cv2
226
  import json
227
- from backend.simple_color_enhancer import SimpleColorEnhancer
228
 
229
  if not os.path.exists(metadata_path): return {"success": False, "message": "No metadata"}
230
  with open(metadata_path, 'r') as f: meta = json.load(f)
@@ -233,7 +202,7 @@ def regen_frame_gpu(video_path, frames_dir, metadata_path, fname, direction):
233
  t = meta[fname]['time'] if isinstance(meta[fname], dict) else meta[fname]
234
  cap = cv2.VideoCapture(video_path)
235
  fps = cap.get(cv2.CAP_PROP_FPS) or 25
236
- offset = (1.0/fps) * (1 if direction == 'forward' else -1)
237
  new_t = max(0, t + offset)
238
 
239
  cap.set(cv2.CAP_PROP_POS_MSEC, new_t * 1000)
@@ -241,24 +210,20 @@ def regen_frame_gpu(video_path, frames_dir, metadata_path, fname, direction):
241
  cap.release()
242
 
243
  if ret:
244
- frame = cv2.resize(frame, (400, 600)) # Force resize
245
  p = os.path.join(frames_dir, fname)
246
  cv2.imwrite(p, frame)
247
- os.sync()
248
- try: SimpleColorEnhancer().enhance_single(p, p)
249
- except: pass
250
 
251
  if isinstance(meta[fname], dict): meta[fname]['time'] = new_t
252
  else: meta[fname] = new_t
253
  with open(metadata_path, 'w') as f: json.dump(meta, f, indent=2)
254
- return {"success": True, "message": f"Adjusted to {new_t:.2f}s"}
255
  return {"success": False, "message": "End of video"}
256
 
257
  @spaces.GPU
258
  def get_frame_at_ts_gpu(video_path, frames_dir, metadata_path, fname, ts):
259
  import cv2
260
  import json
261
- from backend.simple_color_enhancer import SimpleColorEnhancer
262
 
263
  cap = cv2.VideoCapture(video_path)
264
  cap.set(cv2.CAP_PROP_POS_MSEC, float(ts) * 1000)
@@ -266,12 +231,9 @@ def get_frame_at_ts_gpu(video_path, frames_dir, metadata_path, fname, ts):
266
  cap.release()
267
 
268
  if ret:
269
- frame = cv2.resize(frame, (400, 600)) # Force resize
270
  p = os.path.join(frames_dir, fname)
271
  cv2.imwrite(p, frame)
272
- os.sync()
273
- try: SimpleColorEnhancer().enhance_single(p, p)
274
- except: pass
275
 
276
  if os.path.exists(metadata_path):
277
  with open(metadata_path, 'r') as f: meta = json.load(f)
@@ -321,30 +283,24 @@ class EnhancedComicGenerator:
321
  # 🌐 ROUTES & FULL UI
322
  # ======================================================
323
  INDEX_HTML = '''
324
- <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Enhanced Hidden Panel Comic</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/html-to-image/1.11.11/html-to-image.min.js"></script> <link href="https://fonts.googleapis.com/css2?family=Bangers&family=Comic+Neue:wght@700&family=Gloria+Hallelujah&family=Lato&display=swap" rel="stylesheet"> <style> * { box-sizing: border-box; } body { background-color: #fdf6e3; font-family: 'Lato', sans-serif; color: #3d3d3d; margin: 0; min-height: 100vh; }
325
 
326
  #upload-container { display: flex; flex-direction:column; justify-content: center; align-items: center; min-height: 100vh; width: 100%; padding: 20px; }
327
- .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; }
328
 
329
  #editor-container { display: none; padding: 20px; width: 100%; box-sizing: border-box; padding-bottom: 100px; }
330
 
331
- h1 { color: #2c3e50; margin-bottom: 20px; font-weight: 600; }
332
  .file-input { display: none; }
333
- .file-label { display: block; padding: 15px; background: #2c3e50; color: white; border-radius: 8px; cursor: pointer; font-weight: bold; margin-bottom: 10px; transition:0.2s; }
334
- .file-label:hover { background: #34495e; }
335
 
336
  .page-input-group { margin: 20px 0; text-align: left; }
337
- .page-input-group label { font-weight: bold; font-size: 14px; display: block; margin-bottom: 5px; color: #333; }
338
- .page-input-group input { width: 100%; padding: 12px; border: 2px solid #ddd; border-radius: 8px; font-size: 16px; box-sizing: border-box; }
339
-
340
- .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; }
341
- .submit-btn:hover { background: #d35400; }
342
- .restore-btn { margin-top: 10px; background: #27ae60; color: white; padding: 12px; width: 100%; border: none; border-radius: 8px; cursor: pointer; font-weight: bold; }
343
 
344
- .load-section { margin-top: 30px; padding-top: 20px; border-top: 2px solid #eee; }
345
- .load-input-group { display: flex; gap: 10px; margin-top: 10px; }
346
- .load-input-group input { flex: 1; padding: 12px; border: 2px solid #ddd; border-radius: 8px; font-size: 16px; text-transform: uppercase; letter-spacing: 2px; text-align: center; }
347
- .load-input-group button { padding: 12px 20px; background: #3498db; color: white; border: none; border-radius: 8px; cursor: pointer; font-weight: bold; }
348
 
349
  .loader { width: 120px; height: 20px; background: radial-gradient(circle 10px, #e67e22 100%, transparent 0); background-size: 20px 20px; animation: ball 1s infinite linear; margin: 20px auto; }
350
  @keyframes ball { 0%{background-position:0 50%} 100%{background-position:100px 50%} }
@@ -352,13 +308,13 @@ INDEX_HTML = '''
352
  /* === 400x600 COMIC LAYOUT === */
353
  .comic-wrapper { max-width: 1000px; margin: 0 auto; }
354
  .page-wrapper { margin: 30px auto; display: flex; flex-direction: column; align-items: center; }
355
- .page-title { text-align: center; color: #333; margin-bottom: 10px; font-size: 18px; font-weight: bold; }
356
 
357
  .comic-page {
358
  width: 400px;
359
  height: 600px;
360
  background: white;
361
- box-shadow: 0 4px 20px rgba(0,0,0,0.15);
362
  position: relative;
363
  overflow: hidden;
364
  border: 4px solid #000;
@@ -379,15 +335,17 @@ INDEX_HTML = '''
379
 
380
  .panel {
381
  position: absolute; top: 0; left: 0; width: 100%; height: 100%;
382
- overflow: hidden; background: #222; cursor: pointer;
383
  }
384
 
385
  .panel img {
386
  width: 100%; height: 100%;
387
- object-fit: cover;
388
  transform-origin: center;
389
- transition: transform 0.1s ease-out;
 
390
  }
 
391
  .panel.selected { outline: 3px solid #2196F3; z-index: 5; }
392
 
393
  /* === CLIP PATHS === */
@@ -398,13 +356,13 @@ INDEX_HTML = '''
398
 
399
  /* === HANDLES === */
400
  .handle {
401
- position: absolute; width: 20px; height: 20px;
402
  border: 2px solid white; border-radius: 50%;
403
  transform: translate(-50%, -50%);
404
  z-index: 101; cursor: ew-resize;
405
  box-shadow: 0 2px 4px rgba(0,0,0,0.8);
406
  }
407
- .handle:hover { transform: translate(-50%, -50%) scale(1.3); }
408
 
409
  .h-t1 { background: #3498db; left: var(--t1); top: 0%; margin-top: 12px; }
410
  .h-t2 { background: #3498db; left: var(--t2); top: 50%; margin-top: -12px; }
@@ -416,220 +374,145 @@ INDEX_HTML = '''
416
  position: absolute; display: flex; justify-content: center; align-items: center;
417
  width: 150px; height: 80px; min-width: 50px; min-height: 30px; box-sizing: border-box;
418
  z-index: 10; cursor: move; font-family: 'Comic Neue', cursive; font-weight: bold;
419
- font-size: 13px; text-align: center;
420
  overflow: visible; line-height: 1.2; --tail-pos: 50%;
421
  }
422
- .bubble-text { padding: 0.5em; word-wrap: break-word; white-space: pre-wrap; position: relative; z-index: 5; pointer-events: none; user-select: none; width: 100%; height: 100%; overflow: hidden; display: flex; align-items: center; justify-content: center; border-radius: inherit; }
423
  .speech-bubble.selected { outline: 2px dashed #4CAF50; z-index: 100; }
424
- .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; white-space: pre-wrap; }
425
 
426
  .speech-bubble.speech {
427
- --b: 3em; --h: 1.8em; --t: 0.6; --p: var(--tail-pos, 50%); --r: 1.2em;
428
- background: var(--bubble-fill-color, #4ECDC4); color: var(--bubble-text-color, #fff); padding: 0;
429
- 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);
430
  }
431
- .speech-bubble.speech:before {
432
- content: ""; position: absolute; width: var(--b); height: var(--h);
433
- background: inherit; border-bottom-left-radius: 100%; pointer-events: none; z-index: 1;
434
- -webkit-mask: radial-gradient(calc(var(--t)*100%) 105% at 100% 0,#0000 99%,#000 101%);
435
- mask: radial-gradient(calc(var(--t)*100%) 105% at 100% 0,#0000 99%,#000 101%);
436
  }
437
 
438
- .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))); }
439
- .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); }
440
- .speech-bubble.speech.tail-left { border-radius: var(--r); }
441
- .speech-bubble.speech.tail-left:before { right: 100%; top: clamp(0%, calc(var(--p) - (1 - var(--t)) * var(--b) / 2), calc(100% - (1 - var(--t)) * var(--b))); transform: rotate(90deg); transform-origin: top right; }
442
- .speech-bubble.speech.tail-right { border-radius: var(--r); }
443
- .speech-bubble.speech.tail-right:before { left: 100%; top: clamp(0%, calc(var(--p) - (1 - var(--t)) * var(--b) / 2), calc(100% - (1 - var(--t)) * var(--b))); transform: rotate(-90deg); transform-origin: top left; }
444
- .speech-bubble.thought { background: white; border: 2px dashed #555; color: #333; border-radius: 50%; }
445
- .speech-bubble.thought::before { display:none; }
446
- .thought-dot { position: absolute; background-color: white; border: 2px solid #555; border-radius: 50%; z-index: -1; }
447
- .thought-dot-1 { width: 20px; height: 20px; } .thought-dot-2 { width: 12px; height: 12px; }
448
- .speech-bubble.thought.pos-bl .thought-dot-1 { left: 20px; bottom: -20px; } .speech-bubble.thought.pos-bl .thought-dot-2 { left: 10px; bottom: -32px; }
449
-
450
- .resize-handle { position: absolute; width: 10px; height: 10px; background: #2196F3; border: 1px solid white; border-radius: 50%; display: none; z-index: 11; }
451
- .speech-bubble.selected .resize-handle { display: block; }
452
- .resize-handle.se { bottom: -5px; right: -5px; cursor: se-resize; }
453
-
454
  /* CONTROLS */
455
  .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; }
456
  .edit-controls h4 { margin: 0 0 10px 0; color: #4ECDC4; text-align: center; }
457
  .control-group { margin-top: 10px; border-top: 1px solid #555; padding-top: 10px; }
458
  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; }
459
  .button-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 5px; }
460
- .color-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 5px; }
461
  .action-btn { background: #4CAF50; color: white; }
462
  .reset-btn { background: #e74c3c; color: white; }
463
  .secondary-btn { background: #f39c12; color: white; }
464
- .export-btn { background: #2196F3; color: white; }
465
- .save-btn { background: #9b59b6; color: white; }
466
 
467
- .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; }
468
- .modal-content { background: white; padding: 30px; border-radius: 12px; max-width: 400px; width: 90%; text-align: center; }
469
- .modal-content .code { font-size: 32px; font-weight: bold; letter-spacing: 4px; background: #f0f0f0; padding: 15px 25px; border-radius: 8px; display: inline-block; margin: 15px 0; font-family: monospace; user-select: all; }
470
  </style>
471
- </head> <body> <div id="upload-container"> <div class="upload-box"> <h1>🎬 Enhanced Hidden Panel Comic</h1> <input type="file" id="file-upload" class="file-input" onchange="document.getElementById('fn').innerText=this.files[0].name"> <label for="file-upload" class="file-label">📁 Choose Video File</label> <span id="fn" style="margin-bottom:10px; display:block; color:#666;">No file selected</span>
 
 
 
 
 
 
 
 
472
  <div class="page-input-group">
473
- <label>📚 Total Pages (4 Panels/Page):</label>
474
  <input type="number" id="page-count" value="4" min="1" max="15">
475
  </div>
476
- <button class="submit-btn" onclick="upload()">🚀 Generate Comic</button>
477
- <button id="restore-draft-btn" class="restore-btn" style="display:none;" onclick="restoreDraft()">📂 Restore Unsaved Draft</button>
478
 
479
- <div class="load-section">
480
- <h3>📥 Load Saved Comic</h3>
481
- <div class="load-input-group">
482
- <input type="text" id="load-code-input" placeholder="SAVE CODE" maxlength="8">
483
- <button onclick="loadSavedComic()">Load</button>
484
- </div>
485
- </div>
486
  <div class="loading-view" id="loading-view" style="display:none; margin-top:20px;">
487
  <div class="loader" style="margin:0 auto;"></div>
488
  <p id="status-text" style="margin-top:10px;">Starting...</p>
489
  </div>
490
  </div>
491
  </div>
 
492
  <div id="editor-container">
493
- <div style="text-align:center; padding:10px; background:#e74c3c; color:white; font-weight:bold; margin-bottom:20px; border-radius:5px;">👉 Drag Blue/Green dots from RIGHT to LEFT to reveal 4 panels!</div>
494
  <div class="comic-wrapper" id="comic-container"></div>
495
- <input type="file" id="image-uploader" style="display: none;" accept="image/*">
496
  <div class="edit-controls">
497
  <h4>✏️ Editor</h4>
498
- <button onclick="undoLastAction()" style="background:#7f8c8d; color:white;">↩️ Undo</button>
499
-
500
- <div class="control-group">
501
- <label>💾 Save & Load:</label>
502
- <button onclick="saveComic()" class="save-btn">💾 Save Comic</button>
503
- <div id="current-save-code" style="display:none; margin-top:5px; text-align:center;">
504
- <span id="display-save-code" style="font-weight:bold; background:#eee; padding:2px 5px; border-radius:3px;"></span>
505
- <button onclick="copyCode()" style="padding:2px; width:auto; font-size:10px;">Copy</button>
506
- </div>
507
- </div>
508
 
509
  <div class="control-group">
510
- <label>💬 Bubble Styling:</label>
511
- <select id="bubble-type-select" onchange="changeBubbleType(this.value)" disabled>
512
- <option value="speech">Speech</option>
513
- <option value="thought">Thought</option>
514
- <option value="reaction">Reaction</option>
515
- <option value="narration">Narration</option>
516
- </select>
517
- <div class="color-grid">
518
- <div><label>Text</label><input type="color" id="bubble-text-color" value="#ffffff" disabled></div>
519
- <div><label>Fill</label><input type="color" id="bubble-fill-color" value="#4ECDC4" disabled></div>
520
- </div>
521
  <div class="button-grid">
522
- <button onclick="addBubble()" class="action-btn">Add</button>
523
  <button onclick="deleteBubble()" class="reset-btn">Delete</button>
524
  </div>
525
  </div>
526
 
527
- <div class="control-group" id="tail-controls" style="display:none;">
528
- <label>📐 Tail Adjustment:</label>
529
- <button onclick="rotateTail()" class="secondary-btn">🔄 Rotate Side</button>
530
- <input type="range" id="tail-slider" min="10" max="90" value="50" oninput="slideTail(this.value)">
531
- </div>
532
-
533
  <div class="control-group">
534
- <label>🖼️ Panel Tools:</label>
535
- <button onclick="replacePanelImage()" class="action-btn">Replace Img</button>
536
  <div class="button-grid">
537
- <button onclick="adjustFrame('backward')" class="secondary-btn" id="prev-btn">⬅️ Prev</button>
538
- <button onclick="adjustFrame('forward')" class="action-btn" id="next-btn">Next ➡️</button>
539
  </div>
540
- <input type="text" id="timestamp-input" placeholder="mm:ss">
541
- <button onclick="gotoTimestamp()" class="action-btn" id="go-btn">Go</button>
542
  </div>
543
 
544
  <div class="control-group">
545
- <label>🔍 Zoom & Pan:</label>
546
- <input type="range" id="zoom-slider" min="100" max="300" value="100" step="5" disabled oninput="handleZoom(this)">
547
- <button onclick="resetPanelTransform()" class="secondary-btn">Reset</button>
548
  </div>
549
 
550
  <div class="control-group">
551
- <button onclick="exportComic()" class="export-btn">📥 Export PNG</button>
552
- <button onclick="goBackToUpload()" class="reset-btn" style="margin-top:10px;">🏠 Home</button>
553
  </div>
554
  </div>
555
  </div>
556
- <div class="modal-overlay" id="save-modal">
557
- <div class="modal-content">
558
- <h2>✅ Saved!</h2>
559
- <div class="code" id="modal-save-code"></div>
560
- <button onclick="copyModalCode()">Copy</button>
561
- <button onclick="closeModal()">Close</button>
562
- </div>
563
- </div>
564
  <script>
565
  function genUUID(){ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g,c=>{var r=Math.random()*16|0,v=c=='x'?r:(r&0x3|0x8);return v.toString(16);}); }
566
  let sid = localStorage.getItem('comic_sid') || genUUID();
567
  localStorage.setItem('comic_sid', sid);
568
- let currentSaveCode = null, isProcessing = false, interval, selectedBubble = null, selectedPanel = null;
569
  let dragType = null, activeObj = null, dragStart = {x:0, y:0};
570
- let historyStack = [], historyIndex = -1;
571
-
572
- // HISTORY
573
- function addToHistory() {
574
- if (historyIndex < historyStack.length - 1) historyStack = historyStack.slice(0, historyIndex + 1);
575
- const state = JSON.stringify(getCurrentState());
576
- if (historyStack.length > 0 && historyStack[historyStack.length - 1] === state) return;
577
- historyStack.push(state); historyIndex++;
578
- if (historyStack.length > 30) { historyStack.shift(); historyIndex--; }
579
- }
580
- function undoLastAction() {
581
- if (historyIndex > 0) {
582
- historyIndex--;
583
- renderFromState(JSON.parse(historyStack[historyIndex]));
584
- saveDraft(false);
585
- }
586
- }
587
- if(localStorage.getItem('comic_draft_'+sid)) document.getElementById('restore-draft-btn').style.display = 'block';
588
-
589
- function showSaveModal(code) { document.getElementById('modal-save-code').textContent = code; document.getElementById('save-modal').style.display = 'flex'; }
590
- function closeModal() { document.getElementById('save-modal').style.display = 'none'; }
591
- function copyModalCode() { navigator.clipboard.writeText(document.getElementById('modal-save-code').textContent); }
592
- function copyCode() { if(currentSaveCode) navigator.clipboard.writeText(currentSaveCode); }
593
-
594
- function setProcessing(busy) {
595
- isProcessing = busy;
596
- const btns = ['prev-btn', 'next-btn', 'go-btn'];
597
- btns.forEach(id => { const el = document.getElementById(id); if(el) { el.disabled = busy; el.style.opacity = busy?'0.5':'1'; } });
598
- }
599
 
600
  // STATE MANAGEMENT
601
  function getCurrentState() {
602
- const pages = [];
603
- document.querySelectorAll('.comic-page').forEach(p => {
604
- const grid = p.querySelector('.comic-grid');
605
- const panels = [];
606
- grid.querySelectorAll('.panel').forEach(pan => {
607
- const img = pan.querySelector('img');
608
- panels.push({ src: img.src, zoom: img.dataset.zoom, tx: img.dataset.translateX, ty: img.dataset.translateY });
609
- });
610
- const bubbles = [];
611
- grid.querySelectorAll('.speech-bubble').forEach(b => {
612
- bubbles.push({
613
- text: b.querySelector('.bubble-text').textContent, left: b.style.left, top: b.style.top, width: b.style.width, height: b.style.height,
614
- type: b.dataset.type, colors: { fill: b.style.getPropertyValue('--bubble-fill-color'), text: b.style.getPropertyValue('--bubble-text-color') },
615
- tailPos: b.style.getPropertyValue('--tail-pos')
616
- });
617
- });
618
- // Save Grid Variables for Hidden Layout state
619
- const styles = getComputedStyle(grid);
620
- pages.push({
621
- panels: panels, bubbles: bubbles,
622
- layout: { t1: grid.style.getPropertyValue('--t1') || '100%', t2: grid.style.getPropertyValue('--t2') || '100%', b1: grid.style.getPropertyValue('--b1') || '100%', b2: grid.style.getPropertyValue('--b2') || '100%' }
623
- });
624
- });
625
- return pages;
626
  }
627
 
628
- function saveDraft(recordHistory = true) {
629
- if(recordHistory) addToHistory();
630
- localStorage.setItem('comic_draft_'+sid, JSON.stringify({ pages: getCurrentState(), saveCode: currentSaveCode }));
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
631
  }
632
 
 
 
 
 
 
 
 
 
 
 
 
 
633
  function renderFromState(pagesData) {
634
  const con = document.getElementById('comic-container'); con.innerHTML = '';
635
  pagesData.forEach((page, pageIdx) => {
@@ -638,36 +521,36 @@ INDEX_HTML = '''
638
  const div = document.createElement('div'); div.className = 'comic-page';
639
  const grid = document.createElement('div'); grid.className = 'comic-grid';
640
 
641
- // Restore Layout vars
642
- if(page.layout) {
643
- grid.style.setProperty('--t1', page.layout.t1); grid.style.setProperty('--t2', page.layout.t2);
644
- grid.style.setProperty('--b1', page.layout.b1); grid.style.setProperty('--b2', page.layout.b2);
645
- }
646
-
647
  // Panels
648
  page.panels.forEach(pan => {
649
  const pDiv = document.createElement('div'); pDiv.className = 'panel';
650
  const img = document.createElement('img');
651
  img.src = pan.src.includes('?') ? pan.src : pan.src + `?sid=${sid}`;
652
- img.dataset.zoom = pan.zoom || 100; img.dataset.translateX = pan.tx || 0; img.dataset.translateY = pan.ty || 0;
653
- updateImageTransform(img);
654
- pDiv.appendChild(img);
655
 
656
- // Panel Interaction
657
- pDiv.onmousedown = (e) => { e.stopPropagation(); selectPanel(pDiv); dragType = 'pan'; activeObj = img; dragStart = {x:e.clientX, y:e.clientY}; };
 
 
 
 
 
 
 
 
658
  grid.appendChild(pDiv);
659
  });
660
 
661
- // Bubbles (Appended to Grid, not Panel, to avoid clipping)
662
- (page.bubbles || []).forEach(bData => { grid.appendChild(createBubbleHTML(bData)); });
663
-
664
  // Handles
665
  grid.append(createHandle('h-t1', grid, 't1')); grid.append(createHandle('h-t2', grid, 't2'));
666
  grid.append(createHandle('h-b1', grid, 'b1')); grid.append(createHandle('h-b2', grid, 'b2'));
667
 
 
 
 
668
  div.appendChild(grid); pageWrapper.appendChild(div); con.appendChild(pageWrapper);
669
  });
670
- selectedBubble = null; selectedPanel = null;
671
  }
672
 
673
  function createHandle(cls, grid, varName) {
@@ -676,56 +559,14 @@ INDEX_HTML = '''
676
  return h;
677
  }
678
 
679
- async function upload() {
680
- const f = document.getElementById('file-upload').files[0];
681
- const pCount = document.getElementById('page-count').value;
682
- if(!f) return alert("Select video");
683
- sid = genUUID(); localStorage.setItem('comic_sid', sid);
684
- document.querySelector('.upload-box').style.display='none'; document.getElementById('loading-view').style.display='flex';
685
- const fd = new FormData(); fd.append('file', f); fd.append('target_pages', pCount);
686
- const r = await fetch(`/uploader?sid=${sid}`, {method:'POST', body:fd});
687
- if(r.ok) interval = setInterval(checkStatus, 2000);
688
- else { alert("Upload failed"); location.reload(); }
689
- }
690
-
691
- async function checkStatus() {
692
- try {
693
- const r = await fetch(`/status?sid=${sid}`); const d = await r.json();
694
- document.getElementById('status-text').innerText = d.message;
695
- if(d.progress >= 100) { clearInterval(interval); document.getElementById('upload-container').style.display='none'; document.getElementById('editor-container').style.display='block'; loadNewComic(); }
696
- } catch(e) {}
697
- }
698
-
699
- function loadNewComic() {
700
- fetch(`/output/pages.json?sid=${sid}`).then(r=>r.json()).then(data => {
701
- const cleanData = data.map(p => ({
702
- panels: p.panels.map(pan => ({ src: `/frames/${pan.image}?sid=${sid}` })),
703
- bubbles: p.bubbles.map(b => ({
704
- text: b.dialog, left: (b.bubble_offset_x||50)+'px', top: (b.bubble_offset_y||20)+'px', type: b.type||'speech',
705
- tailPos: '50%'
706
- }))
707
- }));
708
- renderFromState(cleanData); saveDraft(true);
709
- });
710
- }
711
-
712
  function createBubbleHTML(data) {
713
  const b = document.createElement('div');
714
- const type = data.type || 'speech';
715
- b.className = `speech-bubble ${type} tail-bottom`;
716
- if (type === 'thought') b.classList.add('pos-bl');
717
- b.dataset.type = type;
718
  b.style.left = data.left; b.style.top = data.top;
719
- if(data.width) b.style.width = data.width; if(data.height) b.style.height = data.height;
720
- if(data.colors) { b.style.setProperty('--bubble-fill-color', data.colors.fill); b.style.setProperty('--bubble-text-color', data.colors.text); }
721
- if(data.tailPos) b.style.setProperty('--tail-pos', data.tailPos);
722
 
723
- const textSpan = document.createElement('span'); textSpan.className = 'bubble-text'; textSpan.textContent = data.text || ''; b.appendChild(textSpan);
724
- if(type === 'thought') { for(let i=1; i<=2; i++){ const d = document.createElement('div'); d.className = `thought-dot thought-dot-${i}`; b.appendChild(d); } }
725
- ['se'].forEach(dir => { const h = document.createElement('div'); h.className = `resize-handle ${dir}`; h.onmousedown = (e) => startResize(e, b); b.appendChild(h); });
726
 
727
  b.onmousedown = (e) => {
728
- if(e.target.classList.contains('resize-handle')) return;
729
  e.stopPropagation(); selectBubble(b); dragType = 'bubble'; activeObj = b; dragStart = {x: e.clientX, y: e.clientY};
730
  };
731
  b.ondblclick = (e) => { e.stopPropagation(); editBubbleText(b); };
@@ -733,14 +574,11 @@ INDEX_HTML = '''
733
  }
734
 
735
  function editBubbleText(bubble) {
736
- const textSpan = bubble.querySelector('.bubble-text'); const textarea = document.createElement('textarea');
737
- textarea.value = textSpan.textContent; bubble.appendChild(textarea); textSpan.style.display = 'none'; textarea.focus();
738
- const finish = () => { textSpan.textContent = textarea.value; textarea.remove(); textSpan.style.display = ''; saveDraft(true); };
739
- textarea.addEventListener('blur', finish, { once: true });
740
  }
741
 
742
- function startResize(e, b) { e.preventDefault(); e.stopPropagation(); dragType = 'resize'; activeObj = { b:b, w: b.getBoundingClientRect().width, h: b.getBoundingClientRect().height, mx: e.clientX, my: e.clientY }; }
743
-
744
  // GLOBAL INTERACTION
745
  document.addEventListener('mousemove', (e) => {
746
  if(!dragType) return;
@@ -753,8 +591,13 @@ INDEX_HTML = '''
753
  else if(dragType === 'pan') {
754
  const dx = e.clientX - dragStart.x; const dy = e.clientY - dragStart.y;
755
  const img = activeObj;
756
- img.dataset.translateX = (parseFloat(img.dataset.translateX)||0) + dx;
757
- img.dataset.translateY = (parseFloat(img.dataset.translateY)||0) + dy;
 
 
 
 
 
758
  updateImageTransform(img);
759
  dragStart = {x: e.clientX, y: e.clientY};
760
  }
@@ -763,83 +606,58 @@ INDEX_HTML = '''
763
  activeObj.style.left = (e.clientX - rect.left - (activeObj.offsetWidth/2)) + 'px';
764
  activeObj.style.top = (e.clientY - rect.top - (activeObj.offsetHeight/2)) + 'px';
765
  }
766
- else if(dragType === 'resize') {
767
- const dx = e.clientX - activeObj.mx; const dy = e.clientY - activeObj.my;
768
- activeObj.b.style.width = (activeObj.w + dx)+'px'; activeObj.b.style.height = (activeObj.h + dy)+'px';
769
- }
770
  });
771
 
772
- document.addEventListener('mouseup', () => { if(dragType) saveDraft(true); dragType = null; activeObj = null; });
 
 
 
773
 
774
  // HELPERS
775
- function selectBubble(el) {
776
- if(selectedBubble) selectedBubble.classList.remove('selected'); selectedBubble = el; el.classList.add('selected');
777
- document.getElementById('bubble-type-select').disabled = false; document.getElementById('bubble-text-color').disabled = false; document.getElementById('bubble-fill-color').disabled = false;
778
- document.getElementById('tail-controls').style.display = 'block';
 
 
779
  }
780
- function selectPanel(el) { if(selectedPanel) selectedPanel.classList.remove('selected'); selectedPanel = el; el.classList.add('selected'); document.getElementById('zoom-slider').disabled = false; document.getElementById('zoom-slider').value = el.querySelector('img').dataset.zoom || 100; }
781
  function addBubble() {
782
- const grid = document.querySelector('.comic-grid'); // Add to first grid found if none selected, or selected panel's parent
783
- const target = selectedPanel ? selectedPanel.parentElement : grid;
784
- if(target) { const b = createBubbleHTML({ text: "Text", left: "50%", top: "50%" }); target.appendChild(b); selectBubble(b); saveDraft(true); }
 
 
 
 
 
 
 
 
785
  }
786
- function deleteBubble() { if(selectedBubble) { selectedBubble.remove(); selectedBubble=null; saveDraft(true); } }
787
- function changeBubbleType(t) { if(selectedBubble) { selectedBubble.dataset.type = t; selectedBubble.className=`speech-bubble ${t} selected tail-bottom`; saveDraft(true); } }
788
- function rotateTail() { if(selectedBubble) { /* Simplified rotation logic */ selectedBubble.classList.toggle('tail-top'); saveDraft(true); } }
789
- function slideTail(v) { if(selectedBubble) { selectedBubble.style.setProperty('--tail-pos', v+'%'); saveDraft(true); } }
790
- document.getElementById('bubble-text-color').addEventListener('change', (e) => { if(selectedBubble) { selectedBubble.style.setProperty('--bubble-text-color', e.target.value); saveDraft(true); } });
791
- document.getElementById('bubble-fill-color').addEventListener('change', (e) => { if(selectedBubble) { selectedBubble.style.setProperty('--bubble-fill-color', e.target.value); saveDraft(true); } });
792
- function handleZoom(el) { if(selectedPanel) { const img = selectedPanel.querySelector('img'); img.dataset.zoom = el.value; updateImageTransform(img); } }
793
- function updateImageTransform(img) { const z = (img.dataset.zoom||100)/100, x = img.dataset.translateX||0, y = img.dataset.translateY||0; img.style.transform = `translateX(${x}px) translateY(${y}px) scale(${z})`; }
794
- function resetPanelTransform() { if(selectedPanel) { const img = selectedPanel.querySelector('img'); img.dataset.zoom=100; img.dataset.translateX=0; img.dataset.translateY=0; updateImageTransform(img); } }
795
-
796
- // BACKEND ACTIONS
797
- function replacePanelImage() {
798
- if(!selectedPanel) return alert("Select a panel");
799
- const inp = document.getElementById('image-uploader');
800
- inp.onchange = async (e) => {
801
- const fd = new FormData(); fd.append('image', e.target.files[0]);
802
- const r = await fetch(`/replace_panel?sid=${sid}`, {method:'POST', body:fd});
803
- const d = await r.json();
804
- if(d.success) { selectedPanel.querySelector('img').src = `/frames/${d.new_filename}?sid=${sid}`; saveDraft(true); }
805
- inp.value = '';
806
- };
807
- inp.click();
808
  }
 
 
 
 
 
 
 
 
 
809
  async function adjustFrame(dir) {
810
- if(isProcessing || !selectedPanel) return;
811
- const img = selectedPanel.querySelector('img'); let fname = img.src.split('/').pop().split('?')[0]; setProcessing(true); img.style.opacity='0.5';
 
812
  const r = await fetch(`/regenerate_frame?sid=${sid}`, { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({filename:fname, direction:dir}) });
813
  const d = await r.json();
814
  if(d.success) img.src = `/frames/${fname}?sid=${sid}&t=${Date.now()}`;
815
- img.style.opacity='1'; setProcessing(false); saveDraft(true);
816
- }
817
- async function gotoTimestamp() {
818
- if(isProcessing || !selectedPanel) return;
819
- let v = document.getElementById('timestamp-input').value.trim();
820
- if(v.includes(':')) { let p=v.split(':'); v=parseInt(p[0])*60+parseFloat(p[1]); } else v=parseFloat(v);
821
- if(isNaN(v)) return;
822
- const img = selectedPanel.querySelector('img'); let fname = img.src.split('/').pop().split('?')[0]; setProcessing(true);
823
- const r = await fetch(`/goto_timestamp?sid=${sid}`, { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({filename:fname, timestamp:v}) });
824
- const d = await r.json();
825
- if(d.success) img.src = `/frames/${fname}?sid=${sid}&t=${Date.now()}`;
826
- setProcessing(false); saveDraft(true);
827
  }
828
 
829
- async function saveComic() {
830
- const r = await fetch(`/save_comic?sid=${sid}`, { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({ pages: getCurrentState() }) });
831
- const d = await r.json();
832
- if(d.success) { currentSaveCode = d.code; document.getElementById('display-save-code').textContent = d.code; document.getElementById('current-save-code').style.display='block'; showSaveModal(d.code); saveDraft(false); }
833
- }
834
- async function loadSavedComic() {
835
- const code = document.getElementById('load-code-input').value.trim();
836
- const r = await fetch(`/load_comic/${code}`); const d = await r.json();
837
- if(d.success) { sid = d.originalSid; localStorage.setItem('comic_sid', sid); renderFromState(d.pages); document.getElementById('upload-container').style.display='none'; document.getElementById('editor-container').style.display='block'; currentSaveCode=code; document.getElementById('display-save-code').textContent=code; document.getElementById('current-save-code').style.display='block'; saveDraft(true); }
838
- }
839
- function restoreDraft() {
840
- const state = JSON.parse(localStorage.getItem('comic_draft_'+sid));
841
- if(state) { renderFromState(state.pages); if(state.saveCode) { currentSaveCode=state.saveCode; document.getElementById('display-save-code').textContent=state.saveCode; document.getElementById('current-save-code').style.display='block'; } document.getElementById('upload-container').style.display='none'; document.getElementById('editor-container').style.display='block'; addToHistory(); }
842
- }
843
  async function exportComic() {
844
  const pgs = document.querySelectorAll('.comic-page');
845
  for(let i=0; i<pgs.length; i++) {
@@ -847,7 +665,6 @@ INDEX_HTML = '''
847
  const a = document.createElement('a'); a.href=u; a.download=`Page-${i+1}.png`; a.click();
848
  }
849
  }
850
- function goBackToUpload() { if(confirm("Unsaved changes lost. Go back?")) location.reload(); }
851
  </script>
852
  </body> </html> '''
853
 
@@ -895,62 +712,6 @@ def regen():
895
  gen = EnhancedComicGenerator(sid)
896
  return jsonify(regen_frame_gpu(gen.video_path, gen.frames_dir, gen.metadata_path, d['filename'], d['direction']))
897
 
898
- @app.route('/goto_timestamp', methods=['POST'])
899
- def go_time():
900
- sid = request.args.get('sid')
901
- d = request.get_json()
902
- gen = EnhancedComicGenerator(sid)
903
- return jsonify(get_frame_at_ts_gpu(gen.video_path, gen.frames_dir, gen.metadata_path, d['filename'], float(d['timestamp'])))
904
-
905
- @app.route('/replace_panel', methods=['POST'])
906
- def rep_panel():
907
- sid = request.args.get('sid')
908
- if 'image' not in request.files: return jsonify({'success': False})
909
- f = request.files['image']
910
- frames_dir = os.path.join(BASE_USER_DIR, sid, 'frames')
911
- fname = f"replaced_{int(time.time()*1000)}.png"
912
- f.save(os.path.join(frames_dir, fname))
913
- return jsonify({'success': True, 'new_filename': fname})
914
-
915
- @app.route('/save_comic', methods=['POST'])
916
- def save_comic():
917
- sid = request.args.get('sid')
918
- try:
919
- data = request.get_json()
920
- save_code = generate_save_code()
921
- save_dir = os.path.join(SAVED_COMICS_DIR, save_code)
922
- os.makedirs(save_dir, exist_ok=True)
923
-
924
- user_frames = os.path.join(BASE_USER_DIR, sid, 'frames')
925
- saved_frames = os.path.join(save_dir, 'frames')
926
- if os.path.exists(user_frames):
927
- if os.path.exists(saved_frames): shutil.rmtree(saved_frames)
928
- shutil.copytree(user_frames, saved_frames)
929
-
930
- save_data = { 'code': save_code, 'originalSid': sid, 'pages': data.get('pages', []), 'savedAt': time.strftime('%Y-%m-%d %H:%M:%S') }
931
- with open(os.path.join(save_dir, 'comic_state.json'), 'w') as f: json.dump(save_data, f)
932
- return jsonify({'success': True, 'code': save_code})
933
- except Exception as e: return jsonify({'success': False, 'message': str(e)})
934
-
935
- @app.route('/load_comic/<code>')
936
- def load_comic(code):
937
- code = code.upper()
938
- save_dir = os.path.join(SAVED_COMICS_DIR, code)
939
- if not os.path.exists(save_dir): return jsonify({'success': False, 'message': 'Code not found'})
940
- try:
941
- with open(os.path.join(save_dir, 'comic_state.json'), 'r') as f: data = json.load(f)
942
- # Restore frames
943
- orig_sid = data.get('originalSid')
944
- if orig_sid:
945
- user_frames = os.path.join(BASE_USER_DIR, orig_sid, 'frames')
946
- saved_frames = os.path.join(save_dir, 'frames')
947
- os.makedirs(user_frames, exist_ok=True)
948
- if os.path.exists(saved_frames):
949
- for fn in os.listdir(saved_frames):
950
- shutil.copy2(os.path.join(saved_frames, fn), os.path.join(user_frames, fn))
951
- return jsonify({'success': True, 'pages': data['pages'], 'originalSid': orig_sid})
952
- except Exception as e: return jsonify({'success': False, 'message': str(e)})
953
-
954
  if __name__ == '__main__':
955
  try: gpu_warmup()
956
  except: pass
 
24
  return True
25
 
26
  # ======================================================
27
+ # 💾 PERSISTENT STORAGE
28
  # ======================================================
29
  if os.path.exists('/data'):
30
  BASE_STORAGE_PATH = '/data'
 
42
  # ======================================================
43
  # 🧱 DATA CLASSES
44
  # ======================================================
45
+ def bubble(dialog="", bubble_offset_x=50, bubble_offset_y=50, type='speech'):
46
  return {
47
  'dialog': dialog,
48
  'bubble_offset_x': int(bubble_offset_x),
49
  'bubble_offset_y': int(bubble_offset_y),
 
 
 
50
  'type': type,
51
  'tail_pos': '50%',
52
  'classes': f'speech-bubble {type} tail-bottom'
 
64
  # 🔧 APP CONFIG
65
  # ======================================================
66
  logging.basicConfig(level=logging.INFO)
 
 
67
  app = Flask(__name__)
68
 
69
  def generate_save_code(length=8):
 
74
  return code
75
 
76
  # ======================================================
77
+ # 🧠 GPU FUNCTIONS (OPTIMIZED FOR SPEED)
78
  # ======================================================
79
+ @spaces.GPU(duration=120)
80
  def generate_comic_gpu(video_path, user_dir, frames_dir, metadata_path, target_pages):
81
+ print(f"🚀 Fast Generation Started: {video_path}")
82
 
83
  import cv2
84
  import srt
85
  import numpy as np
86
+
87
+ # 1. Video Setup
 
 
 
 
 
88
  cap = cv2.VideoCapture(video_path)
89
  if not cap.isOpened(): raise Exception("Cannot open video")
90
  fps = cap.get(cv2.CAP_PROP_FPS) or 25
 
92
  duration = total_frames / fps
93
  cap.release()
94
 
95
+ # 2. Subtitle Processing
96
  user_srt = os.path.join(user_dir, 'subs.srt')
97
+ if not os.path.exists(user_srt):
98
+ # Create dummy SRT if missing to avoid crashes
 
 
 
99
  with open(user_srt, 'w') as f: f.write("1\n00:00:01,000 --> 00:00:04,000\n...\n")
100
 
101
  with open(user_srt, 'r', encoding='utf-8') as f:
 
105
  valid_subs = [s for s in all_subs if s.content.strip()]
106
  raw_moments = [{'text': s.content, 'start': s.start.total_seconds(), 'end': s.end.total_seconds()} for s in valid_subs]
107
 
108
+ # 3. Time Selection
109
  if target_pages <= 0: target_pages = 1
110
  panels_per_page = 4
111
  total_panels_needed = target_pages * panels_per_page
112
 
113
  selected_moments = []
114
  if not raw_moments:
115
+ times = np.linspace(1, max(1, duration-1), total_panels_needed)
116
  for t in times: selected_moments.append({'text': '', 'start': t, 'end': t+1})
117
  elif len(raw_moments) <= total_panels_needed:
118
  selected_moments = raw_moments
 
120
  indices = np.linspace(0, len(raw_moments) - 1, total_panels_needed, dtype=int)
121
  selected_moments = [raw_moments[i] for i in indices]
122
 
123
+ # 4. Fast Extraction Loop
124
  frame_metadata = {}
125
  cap = cv2.VideoCapture(video_path)
126
  count = 0
 
128
 
129
  for i, moment in enumerate(selected_moments):
130
  mid = (moment['start'] + moment['end']) / 2
131
+ if mid > duration: mid = duration - 0.5
132
+ cap.set(cv2.CAP_PROP_POS_MSEC, mid * 1000)
133
  ret, frame = cap.read()
134
+
135
  if ret:
136
  # ------------------------------------------------
137
+ # OPTIMIZATION: 16:9 RESIZE ONLY (NO AI)
138
+ # 1280x720 preserves the "Wide Space"
139
  # ------------------------------------------------
140
+ frame = cv2.resize(frame, (1280, 720))
141
 
142
  fname = f"frame_{count:04d}.png"
143
  p = os.path.join(frames_dir, fname)
144
  cv2.imwrite(p, frame)
145
+
146
  frame_metadata[fname] = {'dialogue': moment['text'], 'time': mid}
147
  frame_files_ordered.append(fname)
148
  count += 1
149
+
150
  cap.release()
 
151
  with open(metadata_path, 'w') as f: json.dump(frame_metadata, f, indent=2)
152
 
153
+ # 5. Fast Bubble Creation (Skipped Face Detect for Speed)
 
 
 
 
 
 
 
 
 
 
 
 
154
  bubbles_list = []
155
  for f in frame_files_ordered:
 
156
  dialogue = frame_metadata.get(f, {}).get('dialogue', '')
 
157
  b_type = 'speech'
158
+ if '(' in dialogue: b_type = 'narration'
159
+ elif '!' in dialogue: b_type = 'reaction'
 
160
 
161
+ # Default to Center (50, 50) to save processing time
162
+ bubbles_list.append(bubble(dialog=dialogue, bubble_offset_x=50, bubble_offset_y=50, type=b_type))
 
 
 
 
 
 
 
 
163
 
164
+ # 6. Pagination
165
  pages = []
166
  for i in range(target_pages):
167
  start_idx = i * 4
 
169
  p_frames = frame_files_ordered[start_idx:end_idx]
170
  p_bubbles = bubbles_list[start_idx:end_idx]
171
 
172
+ # Pad with empty frames if needed
173
  while len(p_frames) < 4:
 
174
  fname = f"empty_{i}_{len(p_frames)}.png"
175
+ img = np.zeros((720, 1280, 3), dtype=np.uint8); img[:] = (40,40,40)
176
  cv2.imwrite(os.path.join(frames_dir, fname), img)
177
  p_frames.append(fname)
178
  p_bubbles.append(bubble(dialog="", type='speech'))
 
181
  pg_panels = [panel(image=f) for f in p_frames]
182
  pages.append(Page(panels=pg_panels, bubbles=p_bubbles))
183
 
184
+ # 7. Convert to Dict
185
  result = []
186
  for pg in pages:
187
  p_data = [p if isinstance(p, dict) else p.__dict__ for p in pg.panels]
 
194
  def regen_frame_gpu(video_path, frames_dir, metadata_path, fname, direction):
195
  import cv2
196
  import json
 
197
 
198
  if not os.path.exists(metadata_path): return {"success": False, "message": "No metadata"}
199
  with open(metadata_path, 'r') as f: meta = json.load(f)
 
202
  t = meta[fname]['time'] if isinstance(meta[fname], dict) else meta[fname]
203
  cap = cv2.VideoCapture(video_path)
204
  fps = cap.get(cv2.CAP_PROP_FPS) or 25
205
+ offset = (1.0/fps) * (1 if direction == 'forward' else -1) # 1 Frame jump
206
  new_t = max(0, t + offset)
207
 
208
  cap.set(cv2.CAP_PROP_POS_MSEC, new_t * 1000)
 
210
  cap.release()
211
 
212
  if ret:
213
+ frame = cv2.resize(frame, (1280, 720)) # Keep 16:9
214
  p = os.path.join(frames_dir, fname)
215
  cv2.imwrite(p, frame)
 
 
 
216
 
217
  if isinstance(meta[fname], dict): meta[fname]['time'] = new_t
218
  else: meta[fname] = new_t
219
  with open(metadata_path, 'w') as f: json.dump(meta, f, indent=2)
220
+ return {"success": True, "message": f"Time: {new_t:.2f}s"}
221
  return {"success": False, "message": "End of video"}
222
 
223
  @spaces.GPU
224
  def get_frame_at_ts_gpu(video_path, frames_dir, metadata_path, fname, ts):
225
  import cv2
226
  import json
 
227
 
228
  cap = cv2.VideoCapture(video_path)
229
  cap.set(cv2.CAP_PROP_POS_MSEC, float(ts) * 1000)
 
231
  cap.release()
232
 
233
  if ret:
234
+ frame = cv2.resize(frame, (1280, 720)) # Keep 16:9
235
  p = os.path.join(frames_dir, fname)
236
  cv2.imwrite(p, frame)
 
 
 
237
 
238
  if os.path.exists(metadata_path):
239
  with open(metadata_path, 'r') as f: meta = json.load(f)
 
283
  # 🌐 ROUTES & FULL UI
284
  # ======================================================
285
  INDEX_HTML = '''
286
+ <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Fast Comic Gen (16:9)</title> <script src="https://cdnjs.cloudflare.com/ajax/libs/html-to-image/1.11.11/html-to-image.min.js"></script> <link href="https://fonts.googleapis.com/css2?family=Bangers&family=Comic+Neue:wght@700&display=swap" rel="stylesheet"> <style> * { box-sizing: border-box; } body { background-color: #222; font-family: 'Lato', sans-serif; color: #eee; margin: 0; min-height: 100vh; }
287
 
288
  #upload-container { display: flex; flex-direction:column; justify-content: center; align-items: center; min-height: 100vh; width: 100%; padding: 20px; }
289
+ .upload-box { max-width: 500px; width: 100%; padding: 40px; background: #333; border-radius: 12px; box-shadow: 0 8px 30px rgba(0,0,0,0.5); text-align: center; }
290
 
291
  #editor-container { display: none; padding: 20px; width: 100%; box-sizing: border-box; padding-bottom: 100px; }
292
 
293
+ h1 { color: #fff; margin-bottom: 20px; font-weight: 600; }
294
  .file-input { display: none; }
295
+ .file-label { display: block; padding: 15px; background: #e74c3c; color: white; border-radius: 8px; cursor: pointer; font-weight: bold; margin-bottom: 10px; transition:0.2s; }
296
+ .file-label:hover { background: #c0392b; }
297
 
298
  .page-input-group { margin: 20px 0; text-align: left; }
299
+ .page-input-group label { font-weight: bold; font-size: 14px; display: block; margin-bottom: 5px; color: #ccc; }
300
+ .page-input-group input { width: 100%; padding: 12px; border: 2px solid #555; background: #222; color: white; border-radius: 8px; font-size: 16px; box-sizing: border-box; }
 
 
 
 
301
 
302
+ .submit-btn { width: 100%; padding: 15px; background: #3498db; color: white; border: none; border-radius: 8px; font-size: 18px; font-weight: bold; cursor: pointer; transition: 0.2s; }
303
+ .submit-btn:hover { background: #2980b9; }
 
 
304
 
305
  .loader { width: 120px; height: 20px; background: radial-gradient(circle 10px, #e67e22 100%, transparent 0); background-size: 20px 20px; animation: ball 1s infinite linear; margin: 20px auto; }
306
  @keyframes ball { 0%{background-position:0 50%} 100%{background-position:100px 50%} }
 
308
  /* === 400x600 COMIC LAYOUT === */
309
  .comic-wrapper { max-width: 1000px; margin: 0 auto; }
310
  .page-wrapper { margin: 30px auto; display: flex; flex-direction: column; align-items: center; }
311
+ .page-title { text-align: center; color: #eee; margin-bottom: 10px; font-size: 18px; font-weight: bold; }
312
 
313
  .comic-page {
314
  width: 400px;
315
  height: 600px;
316
  background: white;
317
+ box-shadow: 0 4px 20px rgba(0,0,0,0.5);
318
  position: relative;
319
  overflow: hidden;
320
  border: 4px solid #000;
 
335
 
336
  .panel {
337
  position: absolute; top: 0; left: 0; width: 100%; height: 100%;
338
+ overflow: hidden; background: #1a1a1a; cursor: grab;
339
  }
340
 
341
  .panel img {
342
  width: 100%; height: 100%;
343
+ object-fit: cover; /* Key for 16:9 in Portrait */
344
  transform-origin: center;
345
+ transition: transform 0.05s ease-out; /* Faster response */
346
+ display: block;
347
  }
348
+ .panel img.panning { cursor: grabbing; transition: none; }
349
  .panel.selected { outline: 3px solid #2196F3; z-index: 5; }
350
 
351
  /* === CLIP PATHS === */
 
356
 
357
  /* === HANDLES === */
358
  .handle {
359
+ position: absolute; width: 22px; height: 22px;
360
  border: 2px solid white; border-radius: 50%;
361
  transform: translate(-50%, -50%);
362
  z-index: 101; cursor: ew-resize;
363
  box-shadow: 0 2px 4px rgba(0,0,0,0.8);
364
  }
365
+ .handle:hover { transform: scale(1.3); }
366
 
367
  .h-t1 { background: #3498db; left: var(--t1); top: 0%; margin-top: 12px; }
368
  .h-t2 { background: #3498db; left: var(--t2); top: 50%; margin-top: -12px; }
 
374
  position: absolute; display: flex; justify-content: center; align-items: center;
375
  width: 150px; height: 80px; min-width: 50px; min-height: 30px; box-sizing: border-box;
376
  z-index: 10; cursor: move; font-family: 'Comic Neue', cursive; font-weight: bold;
377
+ font-size: 14px; text-align: center;
378
  overflow: visible; line-height: 1.2; --tail-pos: 50%;
379
  }
380
+ .bubble-text { padding: 0.5em; width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; overflow: hidden; white-space: pre-wrap; pointer-events: none; }
381
  .speech-bubble.selected { outline: 2px dashed #4CAF50; z-index: 100; }
 
382
 
383
  .speech-bubble.speech {
384
+ background: #fff; color: #000; border: 2px solid #000;
385
+ border-radius: 50%; /* Oval default */
 
386
  }
387
+ .speech-bubble.speech::after {
388
+ content: ''; position: absolute; bottom: -10px; left: var(--tail-pos);
389
+ border: 10px solid transparent; border-top-color: #000; border-bottom: 0; margin-left: -10px;
 
 
390
  }
391
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
392
  /* CONTROLS */
393
  .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; }
394
  .edit-controls h4 { margin: 0 0 10px 0; color: #4ECDC4; text-align: center; }
395
  .control-group { margin-top: 10px; border-top: 1px solid #555; padding-top: 10px; }
396
  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; }
397
  .button-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 5px; }
 
398
  .action-btn { background: #4CAF50; color: white; }
399
  .reset-btn { background: #e74c3c; color: white; }
400
  .secondary-btn { background: #f39c12; color: white; }
 
 
401
 
402
+ .tip {
403
+ text-align:center; padding:10px; background:#e74c3c; color:white; font-weight:bold; margin-bottom:20px; border-radius:5px;
404
+ }
405
  </style>
406
+ </head> <body>
407
+
408
+ <div id="upload-container">
409
+ <div class="upload-box">
410
+ <h1>⚡ Fast 16:9 Comic Gen</h1>
411
+ <input type="file" id="file-upload" class="file-input" onchange="document.getElementById('fn').innerText=this.files[0].name">
412
+ <label for="file-upload" class="file-label">📁 Choose Video</label>
413
+ <span id="fn" style="margin-bottom:10px; display:block; color:#aaa;">No file selected</span>
414
+
415
  <div class="page-input-group">
416
+ <label>📚 Total Pages:</label>
417
  <input type="number" id="page-count" value="4" min="1" max="15">
418
  </div>
 
 
419
 
420
+ <button class="submit-btn" onclick="upload()">🚀 Generate Fast</button>
421
+
 
 
 
 
 
422
  <div class="loading-view" id="loading-view" style="display:none; margin-top:20px;">
423
  <div class="loader" style="margin:0 auto;"></div>
424
  <p id="status-text" style="margin-top:10px;">Starting...</p>
425
  </div>
426
  </div>
427
  </div>
428
+
429
  <div id="editor-container">
430
+ <div class="tip">👉 Drag Blue/Green dots from the RIGHT edge to reveal hidden panels!</div>
431
  <div class="comic-wrapper" id="comic-container"></div>
432
+
433
  <div class="edit-controls">
434
  <h4>✏️ Editor</h4>
 
 
 
 
 
 
 
 
 
 
435
 
436
  <div class="control-group">
437
+ <label>💬 Bubbles:</label>
 
 
 
 
 
 
 
 
 
 
438
  <div class="button-grid">
439
+ <button onclick="addBubble()" class="action-btn">Add Text</button>
440
  <button onclick="deleteBubble()" class="reset-btn">Delete</button>
441
  </div>
442
  </div>
443
 
 
 
 
 
 
 
444
  <div class="control-group">
445
+ <label>🖼️ Image Control:</label>
 
446
  <div class="button-grid">
447
+ <button onclick="adjustFrame('backward')" class="secondary-btn">⬅️ Frame</button>
448
+ <button onclick="adjustFrame('forward')" class="action-btn">Frame ➡️</button>
449
  </div>
 
 
450
  </div>
451
 
452
  <div class="control-group">
453
+ <label>🔍 Zoom/Pan:</label>
454
+ <input type="range" id="zoom-slider" min="100" max="300" value="100" step="5" oninput="handleZoom(this)" disabled>
455
+ <button onclick="resetPanelTransform()" class="secondary-btn">Reset View</button>
456
  </div>
457
 
458
  <div class="control-group">
459
+ <button onclick="exportComic()" class="action-btn" style="background:#3498db;">📥 Export PNG</button>
460
+ <button onclick="location.reload()" class="reset-btn" style="margin-top:10px;">🏠 Start Over</button>
461
  </div>
462
  </div>
463
  </div>
464
+
 
 
 
 
 
 
 
465
  <script>
466
  function genUUID(){ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g,c=>{var r=Math.random()*16|0,v=c=='x'?r:(r&0x3|0x8);return v.toString(16);}); }
467
  let sid = localStorage.getItem('comic_sid') || genUUID();
468
  localStorage.setItem('comic_sid', sid);
469
+ let interval, selectedBubble = null, selectedPanel = null;
470
  let dragType = null, activeObj = null, dragStart = {x:0, y:0};
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
471
 
472
  // STATE MANAGEMENT
473
  function getCurrentState() {
474
+ // Simple state grabber for saves (not fully implemented in this fast version, but structure is here)
475
+ return {};
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
476
  }
477
 
478
+ async function upload() {
479
+ const f = document.getElementById('file-upload').files[0];
480
+ const pCount = document.getElementById('page-count').value;
481
+ if(!f) return alert("Select video");
482
+
483
+ sid = genUUID(); localStorage.setItem('comic_sid', sid);
484
+ document.querySelector('.upload-box').style.display='none';
485
+ document.getElementById('loading-view').style.display='flex';
486
+
487
+ const fd = new FormData();
488
+ fd.append('file', f);
489
+ fd.append('target_pages', pCount);
490
+
491
+ const r = await fetch(`/uploader?sid=${sid}`, {method:'POST', body:fd});
492
+ if(r.ok) interval = setInterval(checkStatus, 1500); // Faster polling
493
+ else { alert("Upload failed"); location.reload(); }
494
+ }
495
+
496
+ async function checkStatus() {
497
+ try {
498
+ const r = await fetch(`/status?sid=${sid}`); const d = await r.json();
499
+ document.getElementById('status-text').innerText = d.message;
500
+ if(d.progress >= 100) { clearInterval(interval); document.getElementById('upload-container').style.display='none'; document.getElementById('editor-container').style.display='block'; loadNewComic(); }
501
+ } catch(e) {}
502
  }
503
 
504
+ function loadNewComic() {
505
+ fetch(`/output/pages.json?sid=${sid}`).then(r=>r.json()).then(data => {
506
+ const cleanData = data.map(p => ({
507
+ panels: p.panels.map(pan => ({ src: `/frames/${pan.image}?sid=${sid}` })),
508
+ bubbles: p.bubbles.map(b => ({
509
+ text: b.dialog, left: (b.bubble_offset_x||50)+'px', top: (b.bubble_offset_y||20)+'px'
510
+ }))
511
+ }));
512
+ renderFromState(cleanData);
513
+ });
514
+ }
515
+
516
  function renderFromState(pagesData) {
517
  const con = document.getElementById('comic-container'); con.innerHTML = '';
518
  pagesData.forEach((page, pageIdx) => {
 
521
  const div = document.createElement('div'); div.className = 'comic-page';
522
  const grid = document.createElement('div'); grid.className = 'comic-grid';
523
 
 
 
 
 
 
 
524
  // Panels
525
  page.panels.forEach(pan => {
526
  const pDiv = document.createElement('div'); pDiv.className = 'panel';
527
  const img = document.createElement('img');
528
  img.src = pan.src.includes('?') ? pan.src : pan.src + `?sid=${sid}`;
529
+ // Init transform data
530
+ img.dataset.zoom = 100; img.dataset.translateX = 0; img.dataset.translateY = 0;
 
531
 
532
+ // Pan Interaction
533
+ img.onmousedown = (e) => {
534
+ e.preventDefault(); e.stopPropagation();
535
+ selectPanel(pDiv);
536
+ dragType = 'pan'; activeObj = img;
537
+ dragStart = {x:e.clientX, y:e.clientY};
538
+ img.classList.add('panning');
539
+ };
540
+
541
+ pDiv.appendChild(img);
542
  grid.appendChild(pDiv);
543
  });
544
 
 
 
 
545
  // Handles
546
  grid.append(createHandle('h-t1', grid, 't1')); grid.append(createHandle('h-t2', grid, 't2'));
547
  grid.append(createHandle('h-b1', grid, 'b1')); grid.append(createHandle('h-b2', grid, 'b2'));
548
 
549
+ // Bubbles (Appended to Grid)
550
+ (page.bubbles || []).forEach(bData => { grid.appendChild(createBubbleHTML(bData)); });
551
+
552
  div.appendChild(grid); pageWrapper.appendChild(div); con.appendChild(pageWrapper);
553
  });
 
554
  }
555
 
556
  function createHandle(cls, grid, varName) {
 
559
  return h;
560
  }
561
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
562
  function createBubbleHTML(data) {
563
  const b = document.createElement('div');
564
+ b.className = `speech-bubble speech`;
 
 
 
565
  b.style.left = data.left; b.style.top = data.top;
 
 
 
566
 
567
+ const textSpan = document.createElement('span'); textSpan.className = 'bubble-text'; textSpan.textContent = data.text || 'Text'; b.appendChild(textSpan);
 
 
568
 
569
  b.onmousedown = (e) => {
 
570
  e.stopPropagation(); selectBubble(b); dragType = 'bubble'; activeObj = b; dragStart = {x: e.clientX, y: e.clientY};
571
  };
572
  b.ondblclick = (e) => { e.stopPropagation(); editBubbleText(b); };
 
574
  }
575
 
576
  function editBubbleText(bubble) {
577
+ const textSpan = bubble.querySelector('.bubble-text');
578
+ const newText = prompt("Edit Text:", textSpan.textContent);
579
+ if(newText !== null) textSpan.textContent = newText;
 
580
  }
581
 
 
 
582
  // GLOBAL INTERACTION
583
  document.addEventListener('mousemove', (e) => {
584
  if(!dragType) return;
 
591
  else if(dragType === 'pan') {
592
  const dx = e.clientX - dragStart.x; const dy = e.clientY - dragStart.y;
593
  const img = activeObj;
594
+ // Get current vals
595
+ let cx = parseFloat(img.dataset.translateX);
596
+ let cy = parseFloat(img.dataset.translateY);
597
+
598
+ img.dataset.translateX = cx + dx;
599
+ img.dataset.translateY = cy + dy;
600
+
601
  updateImageTransform(img);
602
  dragStart = {x: e.clientX, y: e.clientY};
603
  }
 
606
  activeObj.style.left = (e.clientX - rect.left - (activeObj.offsetWidth/2)) + 'px';
607
  activeObj.style.top = (e.clientY - rect.top - (activeObj.offsetHeight/2)) + 'px';
608
  }
 
 
 
 
609
  });
610
 
611
+ document.addEventListener('mouseup', () => {
612
+ if(activeObj && activeObj.classList) activeObj.classList.remove('panning');
613
+ dragType = null; activeObj = null;
614
+ });
615
 
616
  // HELPERS
617
+ function selectBubble(el) { if(selectedBubble) selectedBubble.classList.remove('selected'); selectedBubble = el; el.classList.add('selected'); }
618
+ function selectPanel(el) {
619
+ if(selectedPanel) selectedPanel.classList.remove('selected');
620
+ selectedPanel = el; el.classList.add('selected');
621
+ document.getElementById('zoom-slider').disabled = false;
622
+ document.getElementById('zoom-slider').value = el.querySelector('img').dataset.zoom;
623
  }
624
+
625
  function addBubble() {
626
+ const grid = document.querySelector('.comic-grid');
627
+ if(grid) { const b = createBubbleHTML({ text: "Text", left: "50%", top: "50%" }); grid.appendChild(b); selectBubble(b); }
628
+ }
629
+ function deleteBubble() { if(selectedBubble) { selectedBubble.remove(); selectedBubble=null; } }
630
+
631
+ function handleZoom(el) {
632
+ if(selectedPanel) {
633
+ const img = selectedPanel.querySelector('img');
634
+ img.dataset.zoom = el.value;
635
+ updateImageTransform(img);
636
+ }
637
  }
638
+ function updateImageTransform(img) {
639
+ const z = (img.dataset.zoom||100)/100, x = img.dataset.translateX||0, y = img.dataset.translateY||0;
640
+ img.style.transform = `translateX(${x}px) translateY(${y}px) scale(${z})`;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
641
  }
642
+ function resetPanelTransform() {
643
+ if(selectedPanel) {
644
+ const img = selectedPanel.querySelector('img');
645
+ img.dataset.zoom=100; img.dataset.translateX=0; img.dataset.translateY=0;
646
+ updateImageTransform(img);
647
+ document.getElementById('zoom-slider').value = 100;
648
+ }
649
+ }
650
+
651
  async function adjustFrame(dir) {
652
+ if(!selectedPanel) return alert("Click a panel first");
653
+ const img = selectedPanel.querySelector('img'); let fname = img.src.split('/').pop().split('?')[0];
654
+ img.style.opacity='0.5';
655
  const r = await fetch(`/regenerate_frame?sid=${sid}`, { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({filename:fname, direction:dir}) });
656
  const d = await r.json();
657
  if(d.success) img.src = `/frames/${fname}?sid=${sid}&t=${Date.now()}`;
658
+ img.style.opacity='1';
 
 
 
 
 
 
 
 
 
 
 
659
  }
660
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
661
  async function exportComic() {
662
  const pgs = document.querySelectorAll('.comic-page');
663
  for(let i=0; i<pgs.length; i++) {
 
665
  const a = document.createElement('a'); a.href=u; a.download=`Page-${i+1}.png`; a.click();
666
  }
667
  }
 
668
  </script>
669
  </body> </html> '''
670
 
 
712
  gen = EnhancedComicGenerator(sid)
713
  return jsonify(regen_frame_gpu(gen.video_path, gen.frames_dir, gen.metadata_path, d['filename'], d['direction']))
714
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
715
  if __name__ == '__main__':
716
  try: gpu_warmup()
717
  except: pass