tester343 commited on
Commit
1d1f9a5
·
verified ·
1 Parent(s): 24655fa

Update app_enhanced.py

Browse files
Files changed (1) hide show
  1. app_enhanced.py +532 -142
app_enhanced.py CHANGED
@@ -24,7 +24,7 @@ def gpu_warmup():
24
  return True
25
 
26
  # ======================================================
27
- # 💾 STORAGE SETUP
28
  # ======================================================
29
  if os.path.exists('/data'):
30
  BASE_STORAGE_PATH = '/data'
@@ -39,7 +39,11 @@ SAVED_COMICS_DIR = os.path.join(BASE_STORAGE_PATH, "saved_comics")
39
  os.makedirs(BASE_USER_DIR, exist_ok=True)
40
  os.makedirs(SAVED_COMICS_DIR, exist_ok=True)
41
 
 
 
 
42
  app = Flask(__name__)
 
43
  app.config['MAX_CONTENT_LENGTH'] = 500 * 1024 * 1024
44
 
45
  def generate_save_code(length=8):
@@ -52,14 +56,11 @@ def generate_save_code(length=8):
52
  # ======================================================
53
  # 🧱 DATA CLASSES
54
  # ======================================================
55
- def bubble(dialog="", x=50, y=20, type='speech'):
 
56
  classes = f"speech-bubble {type}"
57
- if type == 'speech':
58
- classes += " tail-bottom"
59
- elif type == 'thought':
60
- classes += " tail-bottom" # Allow thought bubbles to rotate too
61
- elif type == 'reaction':
62
- classes += " tail-bottom"
63
 
64
  return {
65
  'dialog': dialog,
@@ -75,13 +76,8 @@ def bubble(dialog="", x=50, y=20, type='speech'):
75
  def panel(image="", time=0.0):
76
  return {'image': image, 'time': time}
77
 
78
- class Page:
79
- def __init__(self, panels, bubbles):
80
- self.panels = panels
81
- self.bubbles = bubbles
82
-
83
  # ======================================================
84
- # 🧠 GPU GENERATION
85
  # ======================================================
86
  @spaces.GPU(duration=300)
87
  def generate_comic_gpu(video_path, user_dir, frames_dir, metadata_path, target_pages):
@@ -91,61 +87,80 @@ def generate_comic_gpu(video_path, user_dir, frames_dir, metadata_path, target_p
91
  import numpy as np
92
  from backend.subtitles.subs_real import get_real_subtitles
93
 
 
94
  cap = cv2.VideoCapture(video_path)
95
- if not cap.isOpened(): raise Exception("Cannot open video")
 
 
96
  fps = cap.get(cv2.CAP_PROP_FPS) or 25
97
  total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
98
  duration = total_frames / fps
99
  cap.release()
100
 
101
- # Subtitles
102
  user_srt = os.path.join(user_dir, 'subs.srt')
103
  try:
 
104
  get_real_subtitles(video_path)
105
  if os.path.exists('test1.srt'):
106
  shutil.move('test1.srt', user_srt)
107
  elif not os.path.exists(user_srt):
108
- with open(user_srt, 'w') as f: f.write("1\n00:00:01,000 --> 00:00:04,000\n...\n")
109
- except:
110
- with open(user_srt, 'w') as f: f.write("1\n00:00:01,000 --> 00:00:04,000\n...\n")
 
 
 
111
 
112
  with open(user_srt, 'r', encoding='utf-8') as f:
113
- try: all_subs = list(srt.parse(f.read()))
114
- except: all_subs = []
 
 
115
 
116
- valid_subs = [s for s in all_subs if s.content.strip()]
117
  if valid_subs:
118
  raw_moments = [{'text': s.content.strip(), 'start': s.start.total_seconds(), 'end': s.end.total_seconds()} for s in valid_subs]
119
  else:
120
  raw_moments = []
121
 
122
- # 4 Panels Per Page
123
  panels_per_page = 4
124
  total_panels_needed = int(target_pages) * panels_per_page
125
 
126
  selected_moments = []
127
  if not raw_moments:
 
128
  times = np.linspace(1, max(1, duration-1), total_panels_needed)
129
- for t in times: selected_moments.append({'text': '', 'start': t, 'end': t+1})
 
130
  elif len(raw_moments) <= total_panels_needed:
 
131
  selected_moments = raw_moments
 
 
 
132
  else:
 
133
  indices = np.linspace(0, len(raw_moments) - 1, total_panels_needed, dtype=int)
134
  selected_moments = [raw_moments[i] for i in indices]
135
 
 
136
  frame_metadata = {}
137
  cap = cv2.VideoCapture(video_path)
138
  count = 0
139
  frame_files_ordered = []
140
- frame_times = []
141
 
142
  for i, moment in enumerate(selected_moments):
143
  mid = (moment['start'] + moment['end']) / 2
144
  cap.set(cv2.CAP_PROP_POS_MSEC, mid * 1000)
145
  ret, frame = cap.read()
 
146
  if ret:
147
- # 🎯 EXTRACT 1920x1080 (Full HD 16:9)
148
- # This ensures high quality. Frontend handles fitting into 864x1080.
 
149
  frame = cv2.resize(frame, (1920, 1080))
150
 
151
  fname = f"frame_{count:04d}.png"
@@ -156,29 +171,35 @@ def generate_comic_gpu(video_path, user_dir, frames_dir, metadata_path, target_p
156
  frame_files_ordered.append(fname)
157
  frame_times.append(mid)
158
  count += 1
 
159
  cap.release()
160
-
161
- with open(metadata_path, 'w') as f: json.dump(frame_metadata, f, indent=2)
162
 
 
163
  bubbles_list = []
164
  for i, f in enumerate(frame_files_ordered):
165
  dialogue = frame_metadata.get(f, {}).get('dialogue', '')
 
 
166
  b_type = 'speech'
167
- if '(' in dialogue: b_type = 'narration'
168
- elif '!' in dialogue: b_type = 'reaction'
169
- elif '?' in dialogue: b_type = 'speech'
 
170
 
171
- # Smart Positioning for 864x1080
172
- # Panels are roughly 430x540
173
  pos_idx = i % 4
174
- if pos_idx == 0: bx, by = 150, 50
175
- elif pos_idx == 1: bx, by = 580, 50
176
- elif pos_idx == 2: bx, by = 150, 600
177
- elif pos_idx == 3: bx, by = 580, 600
178
  else: bx, by = 50, 50
179
-
180
  bubbles_list.append(bubble(dialog=dialogue, x=bx, y=by, type=b_type))
181
 
 
182
  pages = []
183
  for i in range(int(target_pages)):
184
  start_idx = i * 4
@@ -187,34 +208,37 @@ def generate_comic_gpu(video_path, user_dir, frames_dir, metadata_path, target_p
187
  p_times = frame_times[start_idx:end_idx]
188
  p_bubbles = bubbles_list[start_idx:end_idx]
189
 
 
190
  while len(p_frames) < 4:
191
  fname = f"empty_{i}_{len(p_frames)}.png"
192
- img = np.zeros((1080, 1920, 3), dtype=np.uint8); img[:] = (30,30,30)
 
193
  cv2.imwrite(os.path.join(frames_dir, fname), img)
194
  p_frames.append(fname)
195
  p_times.append(0.0)
196
  p_bubbles.append(bubble(dialog="", x=-999, y=-999, type='speech'))
197
 
198
  if p_frames:
199
- # Pass image AND timestamp to frontend
200
- pg_panels = [panel(image=p_frames[j], time=p_times[j]) for j in range(len(p_frames))]
201
- pages.append(Page(panels=pg_panels, bubbles=p_bubbles))
202
-
203
- # Convert to Dict
204
- result = []
205
- for pg in pages:
206
- p_data = [p if isinstance(p, dict) else p.__dict__ for p in pg.panels]
207
- b_data = [b if isinstance(b, dict) else b.__dict__ for b in pg.bubbles]
208
- result.append({'panels': p_data, 'bubbles': b_data})
209
 
210
- return result
211
 
212
  @spaces.GPU
213
  def regen_frame_gpu(video_path, frames_dir, metadata_path, fname, direction):
 
214
  import cv2
215
  import json
216
- if not os.path.exists(metadata_path): return {"success": False, "message": "No metadata"}
217
- with open(metadata_path, 'r') as f: meta = json.load(f)
 
 
 
 
218
 
219
  t = meta[fname]['time'] if isinstance(meta[fname], dict) else meta[fname]
220
  cap = cv2.VideoCapture(video_path)
@@ -227,16 +251,23 @@ def regen_frame_gpu(video_path, frames_dir, metadata_path, fname, direction):
227
  cap.release()
228
 
229
  if ret:
230
- frame = cv2.resize(frame, (1920, 1080))
231
  cv2.imwrite(os.path.join(frames_dir, fname), frame)
232
- if isinstance(meta[fname], dict): meta[fname]['time'] = new_t
233
- else: meta[fname] = new_t
234
- with open(metadata_path, 'w') as f: json.dump(meta, f, indent=2)
 
 
 
 
 
 
235
  return {"success": True, "message": f"Time: {new_t:.2f}s", "new_time": new_t}
236
- return {"success": False}
237
 
238
  @spaces.GPU
239
  def get_frame_at_ts_gpu(video_path, frames_dir, metadata_path, fname, ts):
 
240
  import cv2
241
  import json
242
  cap = cv2.VideoCapture(video_path)
@@ -245,15 +276,21 @@ def get_frame_at_ts_gpu(video_path, frames_dir, metadata_path, fname, ts):
245
  cap.release()
246
 
247
  if ret:
248
- frame = cv2.resize(frame, (1920, 1080))
249
  cv2.imwrite(os.path.join(frames_dir, fname), frame)
 
250
  if os.path.exists(metadata_path):
251
- with open(metadata_path, 'r') as f: meta = json.load(f)
 
252
  if fname in meta:
253
- if isinstance(meta[fname], dict): meta[fname]['time'] = float(ts)
254
- else: meta[fname] = float(ts)
255
- with open(metadata_path, 'w') as f: json.dump(meta, f, indent=2)
256
- return {"success": True, "message": f"Jumped to {ts}s", "new_time": ts}
 
 
 
 
257
  return {"success": False, "message": "Invalid timestamp"}
258
 
259
  # ======================================================
@@ -271,8 +308,10 @@ class EnhancedComicGenerator:
271
  self.metadata_path = os.path.join(self.frames_dir, 'frame_metadata.json')
272
 
273
  def cleanup(self):
274
- if os.path.exists(self.frames_dir): shutil.rmtree(self.frames_dir)
275
- if os.path.exists(self.output_dir): shutil.rmtree(self.output_dir)
 
 
276
  os.makedirs(self.frames_dir, exist_ok=True)
277
  os.makedirs(self.output_dir, exist_ok=True)
278
 
@@ -292,19 +331,23 @@ class EnhancedComicGenerator:
292
  json.dump({'message': msg, 'progress': prog}, f)
293
 
294
  # ======================================================
295
- # 🌐 FRONTEND
296
  # ======================================================
297
  INDEX_HTML = '''
298
- <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>864x1080 Comic Gen</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: #2c3e50; font-family: 'Lato', sans-serif; color: #eee; margin: 0; min-height: 100vh; }
299
 
300
  #upload-container { display: flex; flex-direction:column; justify-content: center; align-items: center; min-height: 100vh; width: 100%; padding: 20px; }
301
  .upload-box { max-width: 500px; width: 100%; padding: 40px; background: #34495e; border-radius: 12px; box-shadow: 0 10px 30px rgba(0,0,0,0.5); text-align: center; }
302
 
303
- #editor-container { display: none; padding: 20px; width: 100%; box-sizing: border-box; padding-bottom: 150px; flex-direction: column; align-items: center; }
 
 
 
304
 
305
  h1 { color: #fff; margin-bottom: 20px; }
306
  .file-input { display: none; }
307
  .file-label { display: block; padding: 15px; background: #e67e22; color: white; border-radius: 8px; cursor: pointer; font-weight: bold; margin-bottom: 10px; transition:0.2s; }
 
308
 
309
  .page-input-group { margin: 20px 0; text-align: left; }
310
  .page-input-group label { font-weight: bold; font-size: 14px; display: block; margin-bottom: 5px; color: #ccc; }
@@ -314,36 +357,37 @@ INDEX_HTML = '''
314
  .loader { width: 100px; height: 10px; background: #e67e22; margin: 20px auto; animation: load 1s infinite alternate; }
315
  @keyframes load { from { width: 20px; } to { width: 100px; } }
316
 
317
- /* === 864x1080 PAGE LAYOUT === */
318
- .comic-wrapper { max-width: 1000px; margin: 0 auto; display: flex; flex-direction: column; align-items: center; gap: 40px; }
319
- .page-wrapper { display: flex; flex-direction: column; align-items: center; }
320
- .page-title { text-align: center; color: #eee; margin-bottom: 10px; font-size: 20px; font-weight: bold; }
 
 
321
 
322
- /* 🎯 864x1080 + 5px White Border */
323
  .comic-page {
324
  width: 864px;
325
  height: 1080px;
326
  background: white;
327
  box-shadow: 0 5px 30px rgba(0,0,0,0.6);
328
  position: relative; overflow: hidden;
329
- border: 5px solid #ffffff;
330
  flex-shrink: 0;
331
  }
332
 
333
- /* 🎯 White Gap between panels */
334
  .comic-grid {
335
  width: 100%; height: 100%; position: relative;
336
- background: #ffffff; /* White lines */
337
  --y: 50%; --t1: 100%; --t2: 100%; --b1: 100%; --b2: 100%;
338
- --gap: 5px;
339
  }
340
 
341
  .panel { position: absolute; top: 0; left: 0; width: 100%; height: 100%; overflow: hidden; background: #1a1a1a; cursor: grab; }
342
 
343
- /* 🎯 NO CUT: Object Fit Contain = Show Whole Image */
344
  .panel img {
345
  width: 100%; height: 100%;
346
- object-fit: contain; /* Ensures 16:9 fits in 4:5 without cutting. Zoom to fill. */
 
347
  transform-origin: center;
348
  transition: transform 0.05s ease-out;
349
  display: block;
@@ -357,34 +401,56 @@ INDEX_HTML = '''
357
  .panel:nth-child(3) { clip-path: polygon(0 calc(var(--y) + var(--gap)), calc(var(--b1) - var(--gap)) calc(var(--y) + var(--gap)), calc(var(--b2) - var(--gap)) 100%, 0 100%); z-index: 1; }
358
  .panel:nth-child(4) { clip-path: polygon(calc(var(--b1) + var(--gap)) calc(var(--y) + var(--gap)), 100% calc(var(--y) + var(--gap)), 100% 100%, calc(var(--b2) + var(--gap)) 100%); z-index: 1; }
359
 
 
360
  .handle { position: absolute; width: 26px; height: 26px; border: 3px solid white; border-radius: 50%; transform: translate(-50%, -50%); z-index: 101; cursor: ew-resize; box-shadow: 0 2px 5px rgba(0,0,0,0.8); }
361
- .h-t1 { background: #3498db; left: var(--t1); top: 0%; margin-top: 15px; } .h-t2 { background: #3498db; left: var(--t2); top: 50%; margin-top: -15px; }
362
- .h-b1 { background: #2ecc71; left: var(--b1); top: 50%; margin-top: 15px; } .h-b2 { background: #2ecc71; left: var(--b2); top: 100%; margin-top: -15px; }
 
 
363
 
364
- /* BUBBLES */
365
- .speech-bubble { position: absolute; display: flex; justify-content: center; align-items: center; min-width: 60px; min-height: 40px; z-index: 10; cursor: move; font-weight: bold; text-align: center; overflow: visible; line-height: 1.2; --tail-pos: 50%; }
366
- .bubble-text { padding: 0.8em; width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; border-radius: inherit; pointer-events: none; }
 
 
 
 
 
 
 
 
 
367
  .speech-bubble.selected { outline: 2px dashed #4CAF50; z-index: 100; }
368
 
369
- /* SPEECH */
370
- .speech-bubble.speech { --b: 3em; --h: 1.8em; --t: 0.6; --p: var(--tail-pos, 50%); --r: 1.2em; background: var(--bubble-fill, #fff); color: var(--bubble-text, #000); padding: 0; 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); }
371
- .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%); }
 
 
 
 
 
 
 
 
 
 
372
  .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))); }
373
  .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); }
374
  .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; }
375
  .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; }
376
 
377
- /* THOUGHT - FIXED */
378
  .speech-bubble.thought { background: var(--bubble-fill, #fff); color: var(--bubble-text, #000); border: 2px dashed #555; border-radius: 50%; }
379
  .speech-bubble.thought::before { display:none; }
380
  .thought-dot { position: absolute; background-color: var(--bubble-fill, #fff); border: 2px solid #555; border-radius: 50%; z-index: -1; }
381
  .thought-dot-1 { width: 15px; height: 15px; } .thought-dot-2 { width: 10px; height: 10px; }
382
- /* Rotatable Thought Tail */
383
- .speech-bubble.thought.tail-bottom .thought-dot-1 { bottom: -20px; left: 20px; } .speech-bubble.thought.tail-bottom .thought-dot-2 { bottom: -32px; left: 10px; }
384
- .speech-bubble.thought.tail-top .thought-dot-1 { top: -20px; left: 20px; } .speech-bubble.thought.tail-top .thought-dot-2 { top: -32px; left: 10px; }
385
- .speech-bubble.thought.tail-right .thought-dot-1 { right: -20px; bottom: 20px; } .speech-bubble.thought.tail-right .thought-dot-2 { right: -32px; bottom: 10px; }
386
- .speech-bubble.thought.tail-left .thought-dot-1 { left: -20px; bottom: 20px; } .speech-bubble.thought.tail-left .thought-dot-2 { left: -32px; bottom: 10px; }
387
-
388
  .speech-bubble.reaction { background: #FFD700; border: 3px solid #E53935; color: #D32F2F; font-family: 'Bangers'; text-transform: uppercase; 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%); }
389
  .speech-bubble.narration { background: #eee; border: 2px solid #000; color: #000; border-radius: 0; font-family: 'Lato'; bottom: 10px; left: 50%; transform: translateX(-50%); width: 80% !important; height: auto !important; }
390
 
@@ -403,47 +469,194 @@ INDEX_HTML = '''
403
  .reset-btn { background: #c0392b; color: white; }
404
  .secondary-btn { background: #f39c12; color: white; }
405
  .save-btn { background: #8e44ad; color: white; }
 
406
  .tip { text-align:center; padding:10px; background:#e74c3c; color:white; font-weight:bold; margin-bottom:20px; border-radius:5px; }
 
 
 
407
  </style>
408
  </head> <body>
409
 
410
  <div id="upload-container">
411
  <div class="upload-box">
412
- <h1>⚡ 864x1080 Comic</h1>
413
  <input type="file" id="file-upload" class="file-input" onchange="document.getElementById('fn').innerText=this.files[0].name">
414
  <label for="file-upload" class="file-label">📁 Choose Video</label>
415
  <span id="fn" style="margin-bottom:10px; display:block; color:#aaa;">No file selected</span>
416
- <div class="page-input-group"> <label>📚 Total Pages:</label> <input type="number" id="page-count" value="4" min="1" max="15"> </div>
 
 
 
 
 
417
  <button class="submit-btn" onclick="upload()">🚀 Generate</button>
 
 
 
 
 
 
 
 
 
 
418
  </div>
419
  </div>
420
 
421
  <div id="editor-container">
422
  <div class="tip">👉 Drag Right-Side Dots to reveal 4 panels! | 📜 Scroll to Zoom/Pan</div>
423
  <div class="comic-wrapper" id="comic-container"></div>
 
 
424
  <div class="edit-controls">
425
  <h4>✏️ Editor</h4>
426
- <div class="control-group"> <button onclick="saveComic()" class="save-btn">💾 Save</button> </div>
427
  <div class="control-group">
428
- <label>💬 Bubbles:</label>
429
- <select id="bubble-type" onchange="updateBubbleType()"> <option value="speech">Speech 💬</option> <option value="thought">Thought 💭</option> <option value="reaction">Reaction 💥</option> <option value="narration">Narration ⬜</option> </select>
430
- <div class="button-grid"> <button onclick="addBubble()" class="action-btn">Add</button> <button onclick="deleteBubble()" class="reset-btn">Delete</button> </div>
431
- <div id="tail-controls"> <button onclick="rotateTail()" class="secondary-btn" style="margin-top:5px;">🔄 Rotate Tail</button> </div>
432
  </div>
433
- <div class="control-group">
434
- <label>🖼️ Time Frame (s):</label>
435
- <input type="text" id="timestamp-input" placeholder="Click panel to see time">
436
- <button onclick="gotoTimestamp()" class="action-btn">Go</button>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
437
  </div>
438
- <div class="control-group"> <button onclick="exportComic()" class="action-btn" style="background:#3498db;">📥 Export PNG</button> <button onclick="location.reload()" class="reset-btn" style="margin-top:10px;">🏠 Home</button> </div>
 
 
 
 
 
 
 
439
  </div>
440
  </div>
441
 
442
  <script>
443
  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);}); }
444
  let sid = localStorage.getItem('comic_sid') || genUUID();
445
- let selectedBubble = null, selectedPanel = null;
 
446
  let dragType = null, activeObj = null, dragStart = {x:0, y:0};
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
447
 
448
  async function upload() {
449
  const f = document.getElementById('file-upload').files[0];
@@ -451,15 +664,18 @@ INDEX_HTML = '''
451
  if(!f) return alert("Select video");
452
  sid = genUUID(); localStorage.setItem('comic_sid', sid);
453
  document.querySelector('.upload-box').style.display='none';
 
454
  const fd = new FormData(); fd.append('file', f); fd.append('target_pages', pCount); fd.append('sid', sid);
455
  const r = await fetch(`/uploader?sid=${sid}`, {method:'POST', body:fd});
456
- if(r.ok) setInterval(checkStatus, 1500);
 
457
  }
458
 
459
  async function checkStatus() {
460
  try {
461
  const r = await fetch(`/status?sid=${sid}`); const d = await r.json();
462
- if(d.progress >= 100) { document.getElementById('upload-container').style.display='none'; document.getElementById('editor-container').style.display='flex'; loadNewComic(); }
 
463
  } catch(e) {}
464
  }
465
 
@@ -468,45 +684,77 @@ INDEX_HTML = '''
468
  const data = await r.json();
469
  const cleanData = data.map(p => ({
470
  panels: p.panels.map(pan => ({ src: `/frames/${pan.image}?sid=${sid}`, time: pan.time })),
471
- bubbles: p.bubbles.map(b => ({ text: b.dialog, left: (b.bubble_offset_x||50)+'px', top: (b.bubble_offset_y||20)+'px', type: b.type, tailPos: b.tail_pos }))
 
 
 
472
  }));
473
  renderFromState(cleanData);
 
474
  }
475
 
476
  function renderFromState(pagesData) {
477
  const con = document.getElementById('comic-container'); con.innerHTML = '';
478
  pagesData.forEach((page, pageIdx) => {
 
 
479
  const div = document.createElement('div'); div.className = 'comic-page';
480
  const grid = document.createElement('div'); grid.className = 'comic-grid';
 
481
  page.panels.forEach((pan, idx) => {
482
  const pDiv = document.createElement('div'); pDiv.className = 'panel';
483
  const img = document.createElement('img');
484
  img.src = pan.src.includes('?') ? pan.src : pan.src + `?sid=${sid}`;
485
  img.dataset.zoom = 100; img.dataset.translateX = 0; img.dataset.translateY = 0;
486
- img.dataset.time = pan.time.toFixed(2); // Store Time
487
 
488
  img.onmousedown = (e) => { e.preventDefault(); e.stopPropagation(); selectPanel(pDiv); dragType = 'pan'; activeObj = img; dragStart = {x:e.clientX, y:e.clientY}; img.classList.add('panning'); };
489
- img.onwheel = (e) => { e.preventDefault(); let zoom = parseFloat(img.dataset.zoom); zoom += e.deltaY * -0.1; zoom = Math.min(Math.max(20, zoom), 300); img.dataset.zoom = zoom; updateImageTransform(img); };
 
490
  pDiv.appendChild(img); grid.appendChild(pDiv);
491
  });
 
492
  grid.append(createHandle('h-t1', grid, 't1'), createHandle('h-t2', grid, 't2'), createHandle('h-b1', grid, 'b1'), createHandle('h-b2', grid, 'b2'));
493
- if(page.bubbles) { page.bubbles.forEach((bData) => { if(bData.text) grid.appendChild(createBubbleHTML(bData)); }); }
494
- div.appendChild(grid); con.appendChild(div);
 
 
 
 
 
 
 
 
 
495
  });
496
  }
497
 
498
- function createHandle(cls, grid, varName) { let h = document.createElement('div'); h.className = `handle ${cls}`; h.onmousedown = (e) => { e.stopPropagation(); dragType = 'handle'; activeObj = { grid: grid, var: varName }; }; return h; }
 
 
 
 
499
 
500
  function createBubbleHTML(data) {
501
  const b = document.createElement('div');
502
  const type = data.type || 'speech';
 
503
  let className = `speech-bubble ${type}`;
504
- if(type === 'speech') className += ' tail-bottom';
505
- else if(type === 'thought') className += ' tail-bottom'; // Use tail logic for position
 
 
 
506
  b.className = className;
507
 
508
  b.dataset.type = type;
509
  b.style.left = data.left; b.style.top = data.top;
 
 
 
 
 
 
510
  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); } }
511
 
512
  const textSpan = document.createElement('span'); textSpan.className = 'bubble-text'; textSpan.textContent = data.text || 'Text'; b.appendChild(textSpan);
@@ -522,7 +770,7 @@ INDEX_HTML = '''
522
  function editBubbleText(bubble) {
523
  const textSpan = bubble.querySelector('.bubble-text');
524
  const newText = prompt("Edit Text:", textSpan.textContent);
525
- if(newText !== null) textSpan.textContent = newText;
526
  }
527
 
528
  document.addEventListener('mousemove', (e) => {
@@ -548,26 +796,38 @@ INDEX_HTML = '''
548
  }
549
  });
550
 
551
- document.addEventListener('mouseup', () => { if(activeObj && activeObj.classList) activeObj.classList.remove('panning'); dragType = null; activeObj = null; });
 
 
 
 
552
 
553
  function selectBubble(el) {
554
- if(selectedBubble) selectedBubble.classList.remove('selected'); selectedBubble = el; el.classList.add('selected');
 
555
  document.getElementById('bubble-type').value = el.dataset.type;
556
- document.getElementById('tail-controls').style.display = (el.dataset.type === 'speech' || el.dataset.type === 'thought') ? 'block' : 'none';
 
 
 
557
  }
558
 
559
  function selectPanel(el) {
560
  if(selectedPanel) selectedPanel.classList.remove('selected');
561
  selectedPanel = el; el.classList.add('selected');
562
- // 🎯 POPULATE TIME BOX
563
  const img = el.querySelector('img');
564
- if(img && img.dataset.time) {
565
- document.getElementById('timestamp-input').value = img.dataset.time;
566
- }
 
567
  }
568
 
569
- function addBubble() { const grid = document.querySelector('.comic-grid'); if(grid) { const b = createBubbleHTML({ text: "Text", left: "50%", top: "50%" }); grid.appendChild(b); selectBubble(b); } }
570
- function deleteBubble() { if(selectedBubble) { selectedBubble.remove(); selectedBubble=null; } }
 
 
 
571
 
572
  function updateBubbleType() {
573
  if(!selectedBubble) return;
@@ -576,36 +836,84 @@ INDEX_HTML = '''
576
  const data = {
577
  text: oldB.querySelector('.bubble-text').textContent,
578
  left: oldB.style.left, top: oldB.style.top, width: oldB.style.width, height: oldB.style.height,
579
- type: type
 
 
580
  };
581
  const newB = createBubbleHTML(data);
582
  oldB.parentElement.replaceChild(newB, oldB);
583
- selectBubble(newB);
 
 
 
 
 
 
 
584
  }
585
 
586
- // 🎯 ROTATE FOR ALL TYPES
 
 
587
  function rotateTail() {
588
  if(!selectedBubble) return;
 
589
  const positions = ['tail-bottom', 'tail-right', 'tail-top', 'tail-left'];
590
  let current = positions.find(p => selectedBubble.classList.contains(p)) || 'tail-bottom';
591
  selectedBubble.classList.remove(current);
592
  let next = positions[(positions.indexOf(current)+1)%4];
593
  selectedBubble.classList.add(next);
 
594
  }
595
 
 
596
  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})`; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
597
 
598
  async function gotoTimestamp() {
599
  if(!selectedPanel) return alert("Select a panel");
600
  let v = document.getElementById('timestamp-input').value.trim();
601
  if(!v) return;
602
  const img = selectedPanel.querySelector('img'); let fname = img.src.split('/').pop().split('?')[0];
 
603
  const r = await fetch(`/goto_timestamp?sid=${sid}`, { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({filename:fname, timestamp:v}) });
604
  const d = await r.json();
605
- if(d.success) {
606
- img.src = `/frames/${fname}?sid=${sid}&t=${Date.now()}`;
607
- img.dataset.time = d.new_time; // Update local time
608
  }
 
609
  }
610
 
611
  async function exportComic() {
@@ -615,17 +923,42 @@ INDEX_HTML = '''
615
  const a = document.createElement('a'); a.href=u; a.download=`Page-${i+1}.png`; a.click();
616
  }
617
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
618
  </script>
619
  </body> </html> '''
620
 
621
  @app.route('/')
622
- def index(): return INDEX_HTML
 
623
 
624
  @app.route('/uploader', methods=['POST'])
625
  def upload():
626
- sid = request.args.get('sid'); f = request.files.get('file'); pages = request.form.get('target_pages', 4)
627
- gen = EnhancedComicGenerator(sid); gen.cleanup(); f.save(gen.video_path)
628
- threading.Thread(target=gen.run, args=(pages,)).start()
 
 
 
 
 
 
 
 
 
 
629
  return jsonify({'success': True})
630
 
631
  @app.route('/status')
@@ -636,15 +969,72 @@ def get_status():
636
  return jsonify({'progress': 0, 'message': "Waiting..."})
637
 
638
  @app.route('/output/<path:filename>')
639
- def get_output(filename): return send_from_directory(os.path.join(BASE_USER_DIR, request.args.get('sid'), 'output'), filename)
 
 
 
640
  @app.route('/frames/<path:filename>')
641
- def get_frame(filename): return send_from_directory(os.path.join(BASE_USER_DIR, request.args.get('sid'), 'frames'), filename)
 
 
 
 
 
 
 
 
 
642
 
643
  @app.route('/goto_timestamp', methods=['POST'])
644
  def go_time():
645
- sid = request.args.get('sid'); d = request.get_json()
 
646
  gen = EnhancedComicGenerator(sid)
647
- return jsonify(gen.get_frame_at_timestamp(d['filename'], float(d['timestamp'])))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
648
 
649
  if __name__ == '__main__':
650
  try: gpu_warmup()
 
24
  return True
25
 
26
  # ======================================================
27
+ # 💾 PERSISTENT STORAGE CONFIGURATION
28
  # ======================================================
29
  if os.path.exists('/data'):
30
  BASE_STORAGE_PATH = '/data'
 
39
  os.makedirs(BASE_USER_DIR, exist_ok=True)
40
  os.makedirs(SAVED_COMICS_DIR, exist_ok=True)
41
 
42
+ # ======================================================
43
+ # 🔧 APP CONFIG
44
+ # ======================================================
45
  app = Flask(__name__)
46
+ # Allow large uploads (500MB)
47
  app.config['MAX_CONTENT_LENGTH'] = 500 * 1024 * 1024
48
 
49
  def generate_save_code(length=8):
 
56
  # ======================================================
57
  # 🧱 DATA CLASSES
58
  # ======================================================
59
+ def bubble(dialog="", x=50, y=50, type='speech'):
60
+ # Default styling logic
61
  classes = f"speech-bubble {type}"
62
+ # Default orientation
63
+ classes += " tail-bottom"
 
 
 
 
64
 
65
  return {
66
  'dialog': dialog,
 
76
  def panel(image="", time=0.0):
77
  return {'image': image, 'time': time}
78
 
 
 
 
 
 
79
  # ======================================================
80
+ # 🧠 GPU GENERATION (ROBUST)
81
  # ======================================================
82
  @spaces.GPU(duration=300)
83
  def generate_comic_gpu(video_path, user_dir, frames_dir, metadata_path, target_pages):
 
87
  import numpy as np
88
  from backend.subtitles.subs_real import get_real_subtitles
89
 
90
+ # 1. Video Setup
91
  cap = cv2.VideoCapture(video_path)
92
+ if not cap.isOpened():
93
+ raise Exception("Cannot open video")
94
+
95
  fps = cap.get(cv2.CAP_PROP_FPS) or 25
96
  total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
97
  duration = total_frames / fps
98
  cap.release()
99
 
100
+ # 2. Subtitle Extraction (Robust)
101
  user_srt = os.path.join(user_dir, 'subs.srt')
102
  try:
103
+ print("🎙️ Extracting subtitles...")
104
  get_real_subtitles(video_path)
105
  if os.path.exists('test1.srt'):
106
  shutil.move('test1.srt', user_srt)
107
  elif not os.path.exists(user_srt):
108
+ with open(user_srt, 'w') as f:
109
+ f.write("1\n00:00:01,000 --> 00:00:04,000\n...\n")
110
+ except Exception as e:
111
+ print(f"⚠️ Subtitle error: {e}")
112
+ with open(user_srt, 'w') as f:
113
+ f.write("1\n00:00:01,000 --> 00:00:04,000\n...\n")
114
 
115
  with open(user_srt, 'r', encoding='utf-8') as f:
116
+ try:
117
+ all_subs = list(srt.parse(f.read()))
118
+ except:
119
+ all_subs = []
120
 
121
+ valid_subs = [s for s in all_subs if s.content and s.content.strip()]
122
  if valid_subs:
123
  raw_moments = [{'text': s.content.strip(), 'start': s.start.total_seconds(), 'end': s.end.total_seconds()} for s in valid_subs]
124
  else:
125
  raw_moments = []
126
 
127
+ # 3. Calculate Frames (4 Panels Per Page)
128
  panels_per_page = 4
129
  total_panels_needed = int(target_pages) * panels_per_page
130
 
131
  selected_moments = []
132
  if not raw_moments:
133
+ # If no text, split evenly by time
134
  times = np.linspace(1, max(1, duration-1), total_panels_needed)
135
+ for t in times:
136
+ selected_moments.append({'text': '', 'start': t, 'end': t+1})
137
  elif len(raw_moments) <= total_panels_needed:
138
+ # If fewer lines than panels, use all lines
139
  selected_moments = raw_moments
140
+ # Pad remaining if needed
141
+ while len(selected_moments) < total_panels_needed:
142
+ selected_moments.append({'text': '', 'start': duration-1, 'end': duration})
143
  else:
144
+ # If more lines than panels, sample them evenly
145
  indices = np.linspace(0, len(raw_moments) - 1, total_panels_needed, dtype=int)
146
  selected_moments = [raw_moments[i] for i in indices]
147
 
148
+ # 4. Extract Frames (High Quality)
149
  frame_metadata = {}
150
  cap = cv2.VideoCapture(video_path)
151
  count = 0
152
  frame_files_ordered = []
153
+ frame_times = [] # Keep track of timestamps for frontend
154
 
155
  for i, moment in enumerate(selected_moments):
156
  mid = (moment['start'] + moment['end']) / 2
157
  cap.set(cv2.CAP_PROP_POS_MSEC, mid * 1000)
158
  ret, frame = cap.read()
159
+
160
  if ret:
161
+ # 🎯 EXTRACT AT 1920x1080 (HD 16:9)
162
+ # We do NOT crop here. We send the full image to frontend.
163
+ # Frontend uses object-fit: contain to show full image (0% cut).
164
  frame = cv2.resize(frame, (1920, 1080))
165
 
166
  fname = f"frame_{count:04d}.png"
 
171
  frame_files_ordered.append(fname)
172
  frame_times.append(mid)
173
  count += 1
174
+
175
  cap.release()
176
+ with open(metadata_path, 'w') as f:
177
+ json.dump(frame_metadata, f, indent=2)
178
 
179
+ # 5. Generate Bubbles
180
  bubbles_list = []
181
  for i, f in enumerate(frame_files_ordered):
182
  dialogue = frame_metadata.get(f, {}).get('dialogue', '')
183
+
184
+ # Bubble Type Logic
185
  b_type = 'speech'
186
+ if '(' in dialogue:
187
+ b_type = 'narration'
188
+ elif '!' in dialogue and len(dialogue) < 15:
189
+ b_type = 'reaction'
190
 
191
+ # 1 Bubble Per Panel Logic
192
+ # Position them roughly in the center of their respective quadrant
193
  pos_idx = i % 4
194
+ if pos_idx == 0: bx, by = 150, 80 # Top Left
195
+ elif pos_idx == 1: bx, by = 600, 80 # Top Right
196
+ elif pos_idx == 2: bx, by = 150, 600 # Bottom Left
197
+ elif pos_idx == 3: bx, by = 600, 600 # Bottom Right
198
  else: bx, by = 50, 50
199
+
200
  bubbles_list.append(bubble(dialog=dialogue, x=bx, y=by, type=b_type))
201
 
202
+ # 6. Organize Pages
203
  pages = []
204
  for i in range(int(target_pages)):
205
  start_idx = i * 4
 
208
  p_times = frame_times[start_idx:end_idx]
209
  p_bubbles = bubbles_list[start_idx:end_idx]
210
 
211
+ # Pad empty pages if needed
212
  while len(p_frames) < 4:
213
  fname = f"empty_{i}_{len(p_frames)}.png"
214
+ img = np.zeros((1080, 1920, 3), dtype=np.uint8)
215
+ img[:] = (30,30,30) # Dark grey background
216
  cv2.imwrite(os.path.join(frames_dir, fname), img)
217
  p_frames.append(fname)
218
  p_times.append(0.0)
219
  p_bubbles.append(bubble(dialog="", x=-999, y=-999, type='speech'))
220
 
221
  if p_frames:
222
+ # Create Page Object
223
+ pg_panels = []
224
+ for j in range(len(p_frames)):
225
+ pg_panels.append({'image': p_frames[j], 'time': p_times[j]})
226
+
227
+ pages.append({'panels': pg_panels, 'bubbles': p_bubbles})
 
 
 
 
228
 
229
+ return pages
230
 
231
  @spaces.GPU
232
  def regen_frame_gpu(video_path, frames_dir, metadata_path, fname, direction):
233
+ """Adjust frame forward/backward by 1 frame"""
234
  import cv2
235
  import json
236
+
237
+ if not os.path.exists(metadata_path):
238
+ return {"success": False, "message": "No metadata"}
239
+
240
+ with open(metadata_path, 'r') as f:
241
+ meta = json.load(f)
242
 
243
  t = meta[fname]['time'] if isinstance(meta[fname], dict) else meta[fname]
244
  cap = cv2.VideoCapture(video_path)
 
251
  cap.release()
252
 
253
  if ret:
254
+ frame = cv2.resize(frame, (1920, 1080)) # Keep HD
255
  cv2.imwrite(os.path.join(frames_dir, fname), frame)
256
+
257
+ if isinstance(meta[fname], dict):
258
+ meta[fname]['time'] = new_t
259
+ else:
260
+ meta[fname] = new_t
261
+
262
+ with open(metadata_path, 'w') as f:
263
+ json.dump(meta, f, indent=2)
264
+
265
  return {"success": True, "message": f"Time: {new_t:.2f}s", "new_time": new_t}
266
+ return {"success": False, "message": "End of video"}
267
 
268
  @spaces.GPU
269
  def get_frame_at_ts_gpu(video_path, frames_dir, metadata_path, fname, ts):
270
+ """Jump to specific timestamp"""
271
  import cv2
272
  import json
273
  cap = cv2.VideoCapture(video_path)
 
276
  cap.release()
277
 
278
  if ret:
279
+ frame = cv2.resize(frame, (1920, 1080)) # Keep HD
280
  cv2.imwrite(os.path.join(frames_dir, fname), frame)
281
+
282
  if os.path.exists(metadata_path):
283
+ with open(metadata_path, 'r') as f:
284
+ meta = json.load(f)
285
  if fname in meta:
286
+ if isinstance(meta[fname], dict):
287
+ meta[fname]['time'] = float(ts)
288
+ else:
289
+ meta[fname] = float(ts)
290
+ with open(metadata_path, 'w') as f:
291
+ json.dump(meta, f, indent=2)
292
+
293
+ return {"success": True, "message": f"Jumped to {ts}s", "new_time": float(ts)}
294
  return {"success": False, "message": "Invalid timestamp"}
295
 
296
  # ======================================================
 
308
  self.metadata_path = os.path.join(self.frames_dir, 'frame_metadata.json')
309
 
310
  def cleanup(self):
311
+ if os.path.exists(self.frames_dir):
312
+ shutil.rmtree(self.frames_dir)
313
+ if os.path.exists(self.output_dir):
314
+ shutil.rmtree(self.output_dir)
315
  os.makedirs(self.frames_dir, exist_ok=True)
316
  os.makedirs(self.output_dir, exist_ok=True)
317
 
 
331
  json.dump({'message': msg, 'progress': prog}, f)
332
 
333
  # ======================================================
334
+ # 🌐 ROUTES & FRONTEND
335
  # ======================================================
336
  INDEX_HTML = '''
337
+ <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>864x1080 Robust 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: #2c3e50; font-family: 'Lato', sans-serif; color: #eee; margin: 0; min-height: 100vh; }
338
 
339
  #upload-container { display: flex; flex-direction:column; justify-content: center; align-items: center; min-height: 100vh; width: 100%; padding: 20px; }
340
  .upload-box { max-width: 500px; width: 100%; padding: 40px; background: #34495e; border-radius: 12px; box-shadow: 0 10px 30px rgba(0,0,0,0.5); text-align: center; }
341
 
342
+ #editor-container {
343
+ display: none; padding: 20px; width: 100%; box-sizing: border-box;
344
+ padding-bottom: 150px; flex-direction: column; align-items: center;
345
+ }
346
 
347
  h1 { color: #fff; margin-bottom: 20px; }
348
  .file-input { display: none; }
349
  .file-label { display: block; padding: 15px; background: #e67e22; color: white; border-radius: 8px; cursor: pointer; font-weight: bold; margin-bottom: 10px; transition:0.2s; }
350
+ .file-label:hover { background: #d35400; }
351
 
352
  .page-input-group { margin: 20px 0; text-align: left; }
353
  .page-input-group label { font-weight: bold; font-size: 14px; display: block; margin-bottom: 5px; color: #ccc; }
 
357
  .loader { width: 100px; height: 10px; background: #e67e22; margin: 20px auto; animation: load 1s infinite alternate; }
358
  @keyframes load { from { width: 20px; } to { width: 100px; } }
359
 
360
+ /* === 864x1080 LAYOUT + 5px WHITE BORDER === */
361
+ .comic-wrapper {
362
+ max-width: 1000px; margin: 0 auto;
363
+ display: flex; flex-direction: column; align-items: center;
364
+ gap: 40px; width: 100%;
365
+ }
366
 
 
367
  .comic-page {
368
  width: 864px;
369
  height: 1080px;
370
  background: white;
371
  box-shadow: 0 5px 30px rgba(0,0,0,0.6);
372
  position: relative; overflow: hidden;
373
+ border: 5px solid #ffffff; /* Page Border */
374
  flex-shrink: 0;
375
  }
376
 
 
377
  .comic-grid {
378
  width: 100%; height: 100%; position: relative;
379
+ background: #ffffff; /* White background creates gaps */
380
  --y: 50%; --t1: 100%; --t2: 100%; --b1: 100%; --b2: 100%;
381
+ --gap: 5px; /* 5px Gap */
382
  }
383
 
384
  .panel { position: absolute; top: 0; left: 0; width: 100%; height: 100%; overflow: hidden; background: #1a1a1a; cursor: grab; }
385
 
386
+ /* === IMAGE NO CUT (Object Fit Contain) === */
387
  .panel img {
388
  width: 100%; height: 100%;
389
+ object-fit: contain; /* Prevents cutting */
390
+ background: #000; /* Letterbox fill */
391
  transform-origin: center;
392
  transition: transform 0.05s ease-out;
393
  display: block;
 
401
  .panel:nth-child(3) { clip-path: polygon(0 calc(var(--y) + var(--gap)), calc(var(--b1) - var(--gap)) calc(var(--y) + var(--gap)), calc(var(--b2) - var(--gap)) 100%, 0 100%); z-index: 1; }
402
  .panel:nth-child(4) { clip-path: polygon(calc(var(--b1) + var(--gap)) calc(var(--y) + var(--gap)), 100% calc(var(--y) + var(--gap)), 100% 100%, calc(var(--b2) + var(--gap)) 100%); z-index: 1; }
403
 
404
+ /* Handles */
405
  .handle { position: absolute; width: 26px; height: 26px; border: 3px solid white; border-radius: 50%; transform: translate(-50%, -50%); z-index: 101; cursor: ew-resize; box-shadow: 0 2px 5px rgba(0,0,0,0.8); }
406
+ .h-t1 { background: #3498db; left: var(--t1); top: 0%; margin-top: 15px; }
407
+ .h-t2 { background: #3498db; left: var(--t2); top: 50%; margin-top: -15px; }
408
+ .h-b1 { background: #2ecc71; left: var(--b1); top: 50%; margin-top: 15px; }
409
+ .h-b2 { background: #2ecc71; left: var(--b2); top: 100%; margin-top: -15px; }
410
 
411
+ /* === BUBBLES === */
412
+ .speech-bubble {
413
+ position: absolute; display: flex; justify-content: center; align-items: center;
414
+ min-width: 60px; min-height: 40px; box-sizing: border-box;
415
+ z-index: 10; cursor: move; font-weight: bold; text-align: center;
416
+ overflow: visible; line-height: 1.2; --tail-pos: 50%;
417
+ }
418
+ .bubble-text {
419
+ padding: 0.8em; word-wrap: break-word; white-space: pre-wrap;
420
+ width: 100%; height: 100%; display: flex; align-items: center; justify-content: center;
421
+ border-radius: inherit; pointer-events: none;
422
+ }
423
  .speech-bubble.selected { outline: 2px dashed #4CAF50; z-index: 100; }
424
 
425
+ /* --- BUBBLE TYPES & ROTATION SUPPORT --- */
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, #fff); color: var(--bubble-text, #000); 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
+ /* Rotate Logic */
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: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); }
440
  .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; }
441
  .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; }
442
 
443
+ /* Thought Bubble with Rotating Dots */
444
  .speech-bubble.thought { background: var(--bubble-fill, #fff); color: var(--bubble-text, #000); border: 2px dashed #555; border-radius: 50%; }
445
  .speech-bubble.thought::before { display:none; }
446
  .thought-dot { position: absolute; background-color: var(--bubble-fill, #fff); border: 2px solid #555; border-radius: 50%; z-index: -1; }
447
  .thought-dot-1 { width: 15px; height: 15px; } .thought-dot-2 { width: 10px; height: 10px; }
448
+ /* Positions */
449
+ .speech-bubble.thought.tail-bottom .thought-dot-1 { bottom: -18px; left: 20%; } .speech-bubble.thought.tail-bottom .thought-dot-2 { bottom: -30px; left: 15%; }
450
+ .speech-bubble.thought.tail-top .thought-dot-1 { top: -18px; right: 20%; } .speech-bubble.thought.tail-top .thought-dot-2 { top: -30px; right: 15%; }
451
+ .speech-bubble.thought.tail-left .thought-dot-1 { left: -18px; top: 40%; } .speech-bubble.thought.tail-left .thought-dot-2 { left: -30px; top: 35%; }
452
+ .speech-bubble.thought.tail-right .thought-dot-1 { right: -18px; bottom: 40%; } .speech-bubble.thought.tail-right .thought-dot-2 { right: -30px; bottom: 35%; }
453
+
454
  .speech-bubble.reaction { background: #FFD700; border: 3px solid #E53935; color: #D32F2F; font-family: 'Bangers'; text-transform: uppercase; 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%); }
455
  .speech-bubble.narration { background: #eee; border: 2px solid #000; color: #000; border-radius: 0; font-family: 'Lato'; bottom: 10px; left: 50%; transform: translateX(-50%); width: 80% !important; height: auto !important; }
456
 
 
469
  .reset-btn { background: #c0392b; color: white; }
470
  .secondary-btn { background: #f39c12; color: white; }
471
  .save-btn { background: #8e44ad; color: white; }
472
+
473
  .tip { text-align:center; padding:10px; background:#e74c3c; color:white; font-weight:bold; margin-bottom:20px; border-radius:5px; }
474
+ .modal-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.8); display: none; justify-content: center; align-items: center; z-index: 2000; }
475
+ .modal-content { background: white; padding: 30px; border-radius: 12px; width: 90%; max-width: 400px; text-align: center; color: #333; }
476
+ .code { font-size: 24px; font-weight: bold; letter-spacing: 3px; background: #eee; padding: 10px; margin: 15px 0; display: inline-block; font-family: monospace; }
477
  </style>
478
  </head> <body>
479
 
480
  <div id="upload-container">
481
  <div class="upload-box">
482
+ <h1>⚡ 864x1080 Robust Comic</h1>
483
  <input type="file" id="file-upload" class="file-input" onchange="document.getElementById('fn').innerText=this.files[0].name">
484
  <label for="file-upload" class="file-label">📁 Choose Video</label>
485
  <span id="fn" style="margin-bottom:10px; display:block; color:#aaa;">No file selected</span>
486
+
487
+ <div class="page-input-group">
488
+ <label>📚 Total Pages:</label>
489
+ <input type="number" id="page-count" value="4" min="1" max="15">
490
+ </div>
491
+
492
  <button class="submit-btn" onclick="upload()">🚀 Generate</button>
493
+ <button id="restore-draft-btn" class="reset-btn" style="display:none; margin-top:10px;" onclick="restoreDraft()">📂 Restore Draft</button>
494
+
495
+ <div style="margin-top:20px; border-top:1px solid #555; padding-top:10px;">
496
+ <input type="text" id="load-code" placeholder="ENTER SAVE CODE" style="width:70%; display:inline-block;">
497
+ <button onclick="loadComic()" style="width:25%; display:inline-block; background:#9b59b6; color:white;">Load</button>
498
+ </div>
499
+ <div class="loading-view" id="loading-view" style="display:none; margin-top:20px;">
500
+ <div class="loader"></div>
501
+ <p id="status-text" style="margin-top:10px;">Analyzing Video...</p>
502
+ </div>
503
  </div>
504
  </div>
505
 
506
  <div id="editor-container">
507
  <div class="tip">👉 Drag Right-Side Dots to reveal 4 panels! | 📜 Scroll to Zoom/Pan</div>
508
  <div class="comic-wrapper" id="comic-container"></div>
509
+ <input type="file" id="image-uploader" style="display: none;" accept="image/*">
510
+
511
  <div class="edit-controls">
512
  <h4>✏️ Editor</h4>
513
+
514
  <div class="control-group">
515
+ <button onclick="undo()" style="background:#7f8c8d; color:white;">↩️ Undo</button>
516
+ <button onclick="saveComic()" class="save-btn">💾 Save Comic</button>
 
 
517
  </div>
518
+
519
+ <div class="control-group">
520
+ <label>💬 Bubble Styling:</label>
521
+ <select id="bubble-type" onchange="updateBubbleType()">
522
+ <option value="speech">Speech 💬</option>
523
+ <option value="thought">Thought 💭</option>
524
+ <option value="reaction">Reaction 💥</option>
525
+ <option value="narration">Narration ⬜</option>
526
+ </select>
527
+ <select id="font-select" onchange="updateFont()">
528
+ <option value="'Comic Neue', cursive">Comic Neue</option>
529
+ <option value="'Bangers', cursive">Bangers</option>
530
+ <option value="'Gloria Hallelujah', cursive">Handwritten</option>
531
+ <option value="'Lato', sans-serif">Modern</option>
532
+ </select>
533
+ <div class="color-grid">
534
+ <input type="color" id="bub-fill" value="#ffffff" onchange="updateColors()" title="Fill">
535
+ <input type="color" id="bub-text" value="#000000" onchange="updateColors()" title="Text">
536
+ </div>
537
+ <div class="button-grid">
538
+ <button onclick="addBubble()" class="action-btn">Add</button>
539
+ <button onclick="deleteBubble()" class="reset-btn">Delete</button>
540
+ </div>
541
+ <div id="tail-controls">
542
+ <button onclick="rotateTail()" class="secondary-btn" style="margin-top:5px;">🔄 Rotate Tail</button>
543
+ <input type="range" min="10" max="90" value="50" oninput="slideTail(this.value)" title="Tail Pos">
544
+ </div>
545
+ </div>
546
+
547
+ <div class="control-group">
548
+ <label>🖼️ Image & Time:</label>
549
+ <div class="button-grid">
550
+ <button onclick="adjustFrame('backward')" class="secondary-btn">⬅️ Frame</button>
551
+ <button onclick="adjustFrame('forward')" class="action-btn">Frame ➡️</button>
552
+ </div>
553
+ <div class="timestamp-controls">
554
+ <input type="text" id="timestamp-input" placeholder="Click panel for time" style="margin-top:5px; width:60%;">
555
+ <button onclick="gotoTimestamp()" class="action-btn" style="width:30%;">Go</button>
556
+ </div>
557
+ <button onclick="replaceImage()" class="action-btn" style="margin-top:5px;">Replace Image</button>
558
+ </div>
559
+
560
+ <div class="control-group">
561
+ <label>🔍 Zoom (Scroll Wheel):</label>
562
+ <input type="range" id="zoom-slider" min="20" max="300" value="100" step="5" oninput="handleZoom(this.value)" disabled>
563
+ <button onclick="resetPanelTransform()" class="secondary-btn">Reset View</button>
564
+ </div>
565
+
566
+ <div class="control-group">
567
+ <button onclick="exportComic()" class="action-btn" style="background:#3498db;">📥 Export PNG</button>
568
+ <button onclick="location.reload()" class="reset-btn" style="margin-top:10px;">🏠 Home</button>
569
  </div>
570
+ </div>
571
+ </div>
572
+
573
+ <div class="modal-overlay" id="save-modal">
574
+ <div class="modal-content">
575
+ <h2>✅ Comic Saved!</h2>
576
+ <div class="code" id="modal-code">XXXX</div>
577
+ <button onclick="closeModal()">Close</button>
578
  </div>
579
  </div>
580
 
581
  <script>
582
  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);}); }
583
  let sid = localStorage.getItem('comic_sid') || genUUID();
584
+ localStorage.setItem('comic_sid', sid);
585
+ let interval, selectedBubble = null, selectedPanel = null;
586
  let dragType = null, activeObj = null, dragStart = {x:0, y:0};
587
+ let historyStack = [];
588
+
589
+ function saveState() {
590
+ const state = [];
591
+ document.querySelectorAll('.comic-page').forEach(pg => {
592
+ const grid = pg.querySelector('.comic-grid');
593
+ const 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%' };
594
+ const bubbles = [];
595
+ grid.querySelectorAll('.speech-bubble').forEach(b => {
596
+ bubbles.push({
597
+ text: b.querySelector('.bubble-text').textContent,
598
+ left: b.style.left, top: b.style.top, width: b.style.width, height: b.style.height,
599
+ type: b.dataset.type, font: b.style.fontFamily,
600
+ colors: { fill: b.style.getPropertyValue('--bubble-fill'), text: b.style.getPropertyValue('--bubble-text') },
601
+ tailPos: b.style.getPropertyValue('--tail-pos'),
602
+ classes: b.className
603
+ });
604
+ });
605
+ const panels = [];
606
+ grid.querySelectorAll('.panel').forEach(pan => {
607
+ const img = pan.querySelector('img');
608
+ const srcParts = img.src.split('frames/');
609
+ const fname = srcParts.length > 1 ? srcParts[1].split('?')[0] : '';
610
+ panels.push({ image: fname, time: img.dataset.time, zoom: img.dataset.zoom, tx: img.dataset.translateX, ty: img.dataset.translateY });
611
+ });
612
+ state.push({ layout, bubbles, panels });
613
+ });
614
+ historyStack.push(JSON.stringify(state));
615
+ if(historyStack.length > 20) historyStack.shift();
616
+ localStorage.setItem('comic_draft_'+sid, JSON.stringify(state));
617
+ }
618
+
619
+ function undo() {
620
+ if(historyStack.length > 1) {
621
+ historyStack.pop();
622
+ const prev = JSON.parse(historyStack[historyStack.length-1]);
623
+ restoreFromState(prev);
624
+ }
625
+ }
626
+
627
+ function restoreFromState(stateData) {
628
+ if(!stateData) return;
629
+ const pages = document.querySelectorAll('.comic-page');
630
+ stateData.forEach((pgData, i) => {
631
+ if(i >= pages.length) return;
632
+ const grid = pages[i].querySelector('.comic-grid');
633
+ if(pgData.layout) {
634
+ grid.style.setProperty('--t1', pgData.layout.t1); grid.style.setProperty('--t2', pgData.layout.t2);
635
+ grid.style.setProperty('--b1', pgData.layout.b1); grid.style.setProperty('--b2', pgData.layout.b2);
636
+ }
637
+ grid.querySelectorAll('.speech-bubble').forEach(b=>b.remove());
638
+ pgData.bubbles.forEach(bData => { const b = createBubbleHTML(bData); grid.appendChild(b); });
639
+ const panels = grid.querySelectorAll('.panel');
640
+ pgData.panels.forEach((pData, pi) => {
641
+ if(pi < panels.length) {
642
+ const img = panels[pi].querySelector('img');
643
+ img.dataset.zoom = pData.zoom; img.dataset.translateX = pData.tx; img.dataset.translateY = pData.ty;
644
+ img.dataset.time = pData.time;
645
+ if(pData.image) img.src = `/frames/${pData.image}?sid=${sid}`;
646
+ updateImageTransform(img);
647
+ }
648
+ });
649
+ });
650
+ }
651
+
652
+ if(localStorage.getItem('comic_draft_'+sid)) document.getElementById('restore-draft-btn').style.display='inline-block';
653
+ function restoreDraft() {
654
+ document.getElementById('upload-container').style.display='none';
655
+ document.getElementById('editor-container').style.display='flex';
656
+ loadNewComic().then(() => {
657
+ setTimeout(() => restoreFromState(JSON.parse(localStorage.getItem('comic_draft_'+sid))), 500);
658
+ });
659
+ }
660
 
661
  async function upload() {
662
  const f = document.getElementById('file-upload').files[0];
 
664
  if(!f) return alert("Select video");
665
  sid = genUUID(); localStorage.setItem('comic_sid', sid);
666
  document.querySelector('.upload-box').style.display='none';
667
+ document.getElementById('loading-view').style.display='flex';
668
  const fd = new FormData(); fd.append('file', f); fd.append('target_pages', pCount); fd.append('sid', sid);
669
  const r = await fetch(`/uploader?sid=${sid}`, {method:'POST', body:fd});
670
+ if(r.ok) interval = setInterval(checkStatus, 1500);
671
+ else { const d = await r.json(); alert("Upload failed: " + d.message); location.reload(); }
672
  }
673
 
674
  async function checkStatus() {
675
  try {
676
  const r = await fetch(`/status?sid=${sid}`); const d = await r.json();
677
+ document.getElementById('status-text').innerText = d.message;
678
+ if(d.progress >= 100) { clearInterval(interval); document.getElementById('upload-container').style.display='none'; document.getElementById('editor-container').style.display='flex'; loadNewComic(); }
679
  } catch(e) {}
680
  }
681
 
 
684
  const data = await r.json();
685
  const cleanData = data.map(p => ({
686
  panels: p.panels.map(pan => ({ src: `/frames/${pan.image}?sid=${sid}`, time: pan.time })),
687
+ bubbles: p.bubbles.map(b => ({
688
+ text: b.dialog, left: (b.bubble_offset_x||50)+'px', top: (b.bubble_offset_y||20)+'px', type: b.type,
689
+ colors: b.colors, font: b.font, classes: b.classes, tailPos: b.tail_pos
690
+ }))
691
  }));
692
  renderFromState(cleanData);
693
+ saveState();
694
  }
695
 
696
  function renderFromState(pagesData) {
697
  const con = document.getElementById('comic-container'); con.innerHTML = '';
698
  pagesData.forEach((page, pageIdx) => {
699
+ const pageWrapper = document.createElement('div'); pageWrapper.className = 'page-wrapper';
700
+ pageWrapper.innerHTML = `<h2 class="page-title">Page ${pageIdx + 1}</h2>`;
701
  const div = document.createElement('div'); div.className = 'comic-page';
702
  const grid = document.createElement('div'); grid.className = 'comic-grid';
703
+
704
  page.panels.forEach((pan, idx) => {
705
  const pDiv = document.createElement('div'); pDiv.className = 'panel';
706
  const img = document.createElement('img');
707
  img.src = pan.src.includes('?') ? pan.src : pan.src + `?sid=${sid}`;
708
  img.dataset.zoom = 100; img.dataset.translateX = 0; img.dataset.translateY = 0;
709
+ img.dataset.time = pan.time.toFixed(2);
710
 
711
  img.onmousedown = (e) => { e.preventDefault(); e.stopPropagation(); selectPanel(pDiv); dragType = 'pan'; activeObj = img; dragStart = {x:e.clientX, y:e.clientY}; img.classList.add('panning'); };
712
+ img.onwheel = (e) => { e.preventDefault(); let zoom = parseFloat(img.dataset.zoom); zoom += e.deltaY * -0.1; zoom = Math.min(Math.max(20, zoom), 300); img.dataset.zoom = zoom; updateImageTransform(img); if(selectedPanel === pDiv) document.getElementById('zoom-slider').value = zoom; saveState(); };
713
+
714
  pDiv.appendChild(img); grid.appendChild(pDiv);
715
  });
716
+
717
  grid.append(createHandle('h-t1', grid, 't1'), createHandle('h-t2', grid, 't2'), createHandle('h-b1', grid, 'b1'), createHandle('h-b2', grid, 'b2'));
718
+
719
+ if(page.bubbles) {
720
+ page.bubbles.forEach((bData, bIdx) => {
721
+ if(bData.text) {
722
+ const b = createBubbleHTML(bData);
723
+ grid.appendChild(b);
724
+ }
725
+ });
726
+ }
727
+
728
+ div.appendChild(grid); pageWrapper.appendChild(div); con.appendChild(pageWrapper);
729
  });
730
  }
731
 
732
+ function createHandle(cls, grid, varName) {
733
+ let h = document.createElement('div'); h.className = `handle ${cls}`;
734
+ h.onmousedown = (e) => { e.stopPropagation(); dragType = 'handle'; activeObj = { grid: grid, var: varName }; };
735
+ return h;
736
+ }
737
 
738
  function createBubbleHTML(data) {
739
  const b = document.createElement('div');
740
  const type = data.type || 'speech';
741
+
742
  let className = `speech-bubble ${type}`;
743
+ if(type === 'speech' || type === 'thought' || type === 'reaction') {
744
+ // Keep existing tail if present, else default
745
+ if(data.classes && data.classes.includes('tail-')) className = data.classes;
746
+ else className += ' tail-bottom';
747
+ }
748
  b.className = className;
749
 
750
  b.dataset.type = type;
751
  b.style.left = data.left; b.style.top = data.top;
752
+ if(data.width) b.style.width = data.width;
753
+ if(data.height) b.style.height = data.height;
754
+ if(data.font) b.style.fontFamily = data.font;
755
+ if(data.colors) { b.style.setProperty('--bubble-fill', data.colors.fill); b.style.setProperty('--bubble-text', data.colors.text); }
756
+ if(data.tailPos) b.style.setProperty('--tail-pos', data.tailPos);
757
+
758
  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); } }
759
 
760
  const textSpan = document.createElement('span'); textSpan.className = 'bubble-text'; textSpan.textContent = data.text || 'Text'; b.appendChild(textSpan);
 
770
  function editBubbleText(bubble) {
771
  const textSpan = bubble.querySelector('.bubble-text');
772
  const newText = prompt("Edit Text:", textSpan.textContent);
773
+ if(newText !== null) { textSpan.textContent = newText; saveState(); }
774
  }
775
 
776
  document.addEventListener('mousemove', (e) => {
 
796
  }
797
  });
798
 
799
+ document.addEventListener('mouseup', () => {
800
+ if(activeObj && activeObj.classList) activeObj.classList.remove('panning');
801
+ if(dragType) saveState();
802
+ dragType = null; activeObj = null;
803
+ });
804
 
805
  function selectBubble(el) {
806
+ if(selectedBubble) selectedBubble.classList.remove('selected');
807
+ selectedBubble = el; el.classList.add('selected');
808
  document.getElementById('bubble-type').value = el.dataset.type;
809
+ document.getElementById('font-select').value = el.style.fontFamily || "'Comic Neue', cursive";
810
+
811
+ const showTail = (el.dataset.type === 'speech' || el.dataset.type === 'thought' || el.dataset.type === 'reaction');
812
+ document.getElementById('tail-controls').style.display = showTail ? 'block' : 'none';
813
  }
814
 
815
  function selectPanel(el) {
816
  if(selectedPanel) selectedPanel.classList.remove('selected');
817
  selectedPanel = el; el.classList.add('selected');
818
+ document.getElementById('zoom-slider').disabled = false;
819
  const img = el.querySelector('img');
820
+ document.getElementById('zoom-slider').value = img.dataset.zoom || 100;
821
+
822
+ // Populate Time
823
+ if(img.dataset.time) document.getElementById('timestamp-input').value = img.dataset.time;
824
  }
825
 
826
+ function addBubble() {
827
+ const grid = document.querySelector('.comic-grid');
828
+ if(grid) { const b = createBubbleHTML({ text: "Text", left: "50%", top: "50%", type: "speech" }); grid.appendChild(b); selectBubble(b); saveState(); }
829
+ }
830
+ function deleteBubble() { if(selectedBubble) { selectedBubble.remove(); selectedBubble=null; saveState(); } }
831
 
832
  function updateBubbleType() {
833
  if(!selectedBubble) return;
 
836
  const data = {
837
  text: oldB.querySelector('.bubble-text').textContent,
838
  left: oldB.style.left, top: oldB.style.top, width: oldB.style.width, height: oldB.style.height,
839
+ type: type, font: oldB.style.fontFamily,
840
+ colors: { fill: oldB.style.getPropertyValue('--bubble-fill'), text: oldB.style.getPropertyValue('--bubble-text') },
841
+ tailPos: oldB.style.getPropertyValue('--tail-pos')
842
  };
843
  const newB = createBubbleHTML(data);
844
  oldB.parentElement.replaceChild(newB, oldB);
845
+ selectBubble(newB); saveState();
846
+ }
847
+
848
+ function updateColors() {
849
+ if(!selectedBubble) return;
850
+ selectedBubble.style.setProperty('--bubble-fill', document.getElementById('bub-fill').value);
851
+ selectedBubble.style.setProperty('--bubble-text', document.getElementById('bub-text').value);
852
+ saveState();
853
  }
854
 
855
+ function updateFont() { if(selectedBubble) { selectedBubble.style.fontFamily = document.getElementById('font-select').value; saveState(); } }
856
+ function slideTail(val) { if(selectedBubble) { selectedBubble.style.setProperty('--tail-pos', val+'%'); saveState(); } }
857
+
858
  function rotateTail() {
859
  if(!selectedBubble) return;
860
+ const type = selectedBubble.dataset.type;
861
  const positions = ['tail-bottom', 'tail-right', 'tail-top', 'tail-left'];
862
  let current = positions.find(p => selectedBubble.classList.contains(p)) || 'tail-bottom';
863
  selectedBubble.classList.remove(current);
864
  let next = positions[(positions.indexOf(current)+1)%4];
865
  selectedBubble.classList.add(next);
866
+ saveState();
867
  }
868
 
869
+ function handleZoom(val) { if(selectedPanel) { const img = selectedPanel.querySelector('img'); img.dataset.zoom = val; updateImageTransform(img); saveState(); } }
870
  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})`; }
871
+ function resetPanelTransform() { if(selectedPanel) { const img = selectedPanel.querySelector('img'); img.dataset.zoom=100; img.dataset.translateX=0; img.dataset.translateY=0; updateImageTransform(img); document.getElementById('zoom-slider').value=100; saveState(); } }
872
+
873
+ function replaceImage() {
874
+ if(!selectedPanel) return alert("Select a panel");
875
+ const inp = document.getElementById('image-uploader');
876
+ inp.onchange = async (e) => {
877
+ const fd = new FormData(); fd.append('image', e.target.files[0]);
878
+ const r = await fetch(`/replace_panel?sid=${sid}`, {method:'POST', body:fd});
879
+ const d = await r.json();
880
+ if(d.success) {
881
+ const img = selectedPanel.querySelector('img');
882
+ img.src = `/frames/${d.new_filename}?sid=${sid}`;
883
+ saveState();
884
+ }
885
+ inp.value = '';
886
+ };
887
+ inp.click();
888
+ }
889
+
890
+ async function adjustFrame(dir) {
891
+ if(!selectedPanel) return alert("Click a panel first");
892
+ const img = selectedPanel.querySelector('img'); let fname = img.src.split('/').pop().split('?')[0];
893
+ img.style.opacity='0.5';
894
+ const r = await fetch(`/regenerate_frame?sid=${sid}`, { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({filename:fname, direction:dir}) });
895
+ const d = await r.json();
896
+ if(d.success) {
897
+ img.src = `/frames/${fname}?sid=${sid}&t=${Date.now()}`;
898
+ img.dataset.time = d.new_time.toFixed(2);
899
+ document.getElementById('timestamp-input').value = d.new_time.toFixed(2);
900
+ }
901
+ img.style.opacity='1'; saveState();
902
+ }
903
 
904
  async function gotoTimestamp() {
905
  if(!selectedPanel) return alert("Select a panel");
906
  let v = document.getElementById('timestamp-input').value.trim();
907
  if(!v) return;
908
  const img = selectedPanel.querySelector('img'); let fname = img.src.split('/').pop().split('?')[0];
909
+ img.style.opacity = '0.5';
910
  const r = await fetch(`/goto_timestamp?sid=${sid}`, { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({filename:fname, timestamp:v}) });
911
  const d = await r.json();
912
+ if(d.success) {
913
+ img.src = `/frames/${fname}?sid=${sid}&t=${Date.now()}`;
914
+ img.dataset.time = d.new_time.toFixed(2);
915
  }
916
+ img.style.opacity = '1'; saveState();
917
  }
918
 
919
  async function exportComic() {
 
923
  const a = document.createElement('a'); a.href=u; a.download=`Page-${i+1}.png`; a.click();
924
  }
925
  }
926
+
927
+ async function saveComic() {
928
+ const r = await fetch(`/save_comic?sid=${sid}`, {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({pages:getCurrentState()})});
929
+ const d = await r.json();
930
+ if(d.success) { document.getElementById('modal-code').innerText=d.code; document.getElementById('save-modal').style.display='flex'; }
931
+ }
932
+ async function loadComic() {
933
+ const code = document.getElementById('load-code').value;
934
+ const r = await fetch(`/load_comic/${code}`);
935
+ const d = await r.json();
936
+ if(d.success) { sid=d.originalSid; localStorage.setItem('comic_sid', sid); restoreFromState(d.pages); document.getElementById('upload-container').style.display='none'; document.getElementById('editor-container').style.display='flex'; }
937
+ else alert(d.message);
938
+ }
939
+ function closeModal() { document.getElementById('save-modal').style.display='none'; }
940
  </script>
941
  </body> </html> '''
942
 
943
  @app.route('/')
944
+ def index():
945
+ return INDEX_HTML
946
 
947
  @app.route('/uploader', methods=['POST'])
948
  def upload():
949
+ sid = request.args.get('sid')
950
+ if not sid: return jsonify({'success': False, 'message': 'Missing session ID'}), 400
951
+
952
+ file = request.files.get('file')
953
+ if not file or file.filename == '': return jsonify({'success': False, 'message': 'No file uploaded'}), 400
954
+
955
+ target_pages = request.form.get('target_pages', 4)
956
+ gen = EnhancedComicGenerator(sid)
957
+ gen.cleanup()
958
+ file.save(gen.video_path)
959
+ gen.write_status("Starting...", 5)
960
+
961
+ threading.Thread(target=gen.run, args=(target_pages,)).start()
962
  return jsonify({'success': True})
963
 
964
  @app.route('/status')
 
969
  return jsonify({'progress': 0, 'message': "Waiting..."})
970
 
971
  @app.route('/output/<path:filename>')
972
+ def get_output(filename):
973
+ sid = request.args.get('sid')
974
+ return send_from_directory(os.path.join(BASE_USER_DIR, sid, 'output'), filename)
975
+
976
  @app.route('/frames/<path:filename>')
977
+ def get_frame(filename):
978
+ sid = request.args.get('sid')
979
+ return send_from_directory(os.path.join(BASE_USER_DIR, sid, 'frames'), filename)
980
+
981
+ @app.route('/regenerate_frame', methods=['POST'])
982
+ def regen():
983
+ sid = request.args.get('sid')
984
+ d = request.get_json()
985
+ gen = EnhancedComicGenerator(sid)
986
+ return jsonify(regen_frame_gpu(gen.video_path, gen.frames_dir, gen.metadata_path, d['filename'], d['direction']))
987
 
988
  @app.route('/goto_timestamp', methods=['POST'])
989
  def go_time():
990
+ sid = request.args.get('sid')
991
+ d = request.get_json()
992
  gen = EnhancedComicGenerator(sid)
993
+ return jsonify(get_frame_at_ts_gpu(gen.video_path, gen.frames_dir, gen.metadata_path, d['filename'], float(d['timestamp'])))
994
+
995
+ @app.route('/replace_panel', methods=['POST'])
996
+ def rep_panel():
997
+ sid = request.args.get('sid')
998
+ f = request.files['image']
999
+ frames_dir = os.path.join(BASE_USER_DIR, sid, 'frames')
1000
+ os.makedirs(frames_dir, exist_ok=True)
1001
+ fname = f"replaced_{int(time.time() * 1000)}.png"
1002
+ f.save(os.path.join(frames_dir, fname))
1003
+ return jsonify({'success': True, 'new_filename': fname})
1004
+
1005
+ @app.route('/save_comic', methods=['POST'])
1006
+ def save_comic():
1007
+ sid = request.args.get('sid')
1008
+ try:
1009
+ data = request.get_json()
1010
+ save_code = generate_save_code()
1011
+ save_dir = os.path.join(SAVED_COMICS_DIR, save_code)
1012
+ os.makedirs(save_dir, exist_ok=True)
1013
+ user_frames_dir = os.path.join(BASE_USER_DIR, sid, 'frames')
1014
+ saved_frames_dir = os.path.join(save_dir, 'frames')
1015
+ if os.path.exists(user_frames_dir):
1016
+ if os.path.exists(saved_frames_dir): shutil.rmtree(saved_frames_dir)
1017
+ shutil.copytree(user_frames_dir, saved_frames_dir)
1018
+ with open(os.path.join(save_dir, 'comic_state.json'), 'w') as f:
1019
+ json.dump({'originalSid': sid, 'pages': data['pages'], 'savedAt': time.time()}, f)
1020
+ return jsonify({'success': True, 'code': save_code})
1021
+ except Exception as e: return jsonify({'success': False, 'message': str(e)})
1022
+
1023
+ @app.route('/load_comic/<code>')
1024
+ def load_comic(code):
1025
+ code = code.upper()
1026
+ save_dir = os.path.join(SAVED_COMICS_DIR, code)
1027
+ if not os.path.exists(save_dir): return jsonify({'success': False, 'message': 'Code not found'})
1028
+ try:
1029
+ with open(os.path.join(save_dir, 'comic_state.json'), 'r') as f: data = json.load(f)
1030
+ orig_sid = data['originalSid']
1031
+ saved_frames = os.path.join(save_dir, 'frames')
1032
+ user_frames = os.path.join(BASE_USER_DIR, orig_sid, 'frames')
1033
+ os.makedirs(user_frames, exist_ok=True)
1034
+ for fn in os.listdir(saved_frames):
1035
+ shutil.copy2(os.path.join(saved_frames, fn), os.path.join(user_frames, fn))
1036
+ return jsonify({'success': True, 'originalSid': orig_sid, 'pages': data['pages']})
1037
+ except Exception as e: return jsonify({'success': False, 'message': str(e)})
1038
 
1039
  if __name__ == '__main__':
1040
  try: gpu_warmup()