tester343 commited on
Commit
8e724fa
·
verified ·
1 Parent(s): a0bf513

Update app_enhanced.py

Browse files
Files changed (1) hide show
  1. app_enhanced.py +1019 -221
app_enhanced.py CHANGED
@@ -4,140 +4,272 @@ import time
4
  import threading
5
  import json
6
  import traceback
 
 
 
7
  import shutil
8
  import cv2
 
9
  import numpy as np
10
  import srt
11
  from flask import Flask, jsonify, request, send_from_directory, send_file
12
 
13
  # ======================================================
14
- # 🚀 1. APP & GPU INITIALIZATION
15
  # ======================================================
16
- app = Flask(__name__)
17
-
18
  @spaces.GPU
19
  def gpu_warmup():
20
  import torch
21
- return torch.cuda.is_available()
 
22
 
23
  # ======================================================
24
- # 💾 2. STORAGE SETUP
25
  # ======================================================
26
- BASE_STORAGE_PATH = '/data' if os.path.exists('/data') else '.'
 
 
 
 
 
 
27
  BASE_USER_DIR = os.path.join(BASE_STORAGE_PATH, "userdata")
 
 
28
  os.makedirs(BASE_USER_DIR, exist_ok=True)
 
29
 
30
  # ======================================================
31
- # 🔧 3. UTILS (FIX FOR int64 ERROR)
32
  # ======================================================
33
- def sanitize_json(obj):
34
- if isinstance(obj, dict):
35
- return {k: sanitize_json(v) for k, v in obj.items()}
36
- elif isinstance(obj, list):
37
- return [sanitize_json(v) for v in obj]
38
- elif isinstance(obj, (np.int64, np.int32, np.int16)):
39
- return int(obj)
40
- elif isinstance(obj, (np.float64, np.float32, np.float16)):
41
- return float(obj)
42
- elif isinstance(obj, np.ndarray):
43
- return sanitize_json(obj.tolist())
44
- return obj
 
 
 
 
 
 
 
 
45
 
46
  # ======================================================
47
- # 🧠 4. CORE GPU GENERATOR
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
  # ======================================================
49
  @spaces.GPU(duration=300)
50
  def generate_comic_gpu(video_path, user_dir, frames_dir, metadata_path, target_pages):
 
 
 
 
 
51
  from backend.keyframes.keyframes import black_bar_crop
52
  from backend.simple_color_enhancer import SimpleColorEnhancer
 
53
  from backend.subtitles.subs_real import get_real_subtitles
54
  from backend.ai_bubble_placement import ai_bubble_placer
55
  from backend.ai_enhanced_core import face_detector
56
 
57
  cap = cv2.VideoCapture(video_path)
 
58
  fps = cap.get(cv2.CAP_PROP_FPS) or 25
59
  total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
60
  duration = total_frames / fps
61
  cap.release()
62
 
63
- # Get Subtitles
64
  user_srt = os.path.join(user_dir, 'subs.srt')
65
  try:
66
  get_real_subtitles(video_path)
67
- if os.path.exists('test1.srt'): shutil.move('test1.srt', user_srt)
 
68
  except:
69
- with open(user_srt, 'w') as f: f.write("1\n00:00:01,000 --> 00:00:05,000\nDialogue...\n")
70
-
71
  with open(user_srt, 'r', encoding='utf-8') as f:
72
  try: all_subs = list(srt.parse(f.read()))
73
  except: all_subs = []
74
 
75
- # 5-Panel logic
76
- panels_per_page = 5
77
- target_pages = int(target_pages)
78
- total_needed = target_pages * panels_per_page
79
-
80
- if not all_subs:
81
- times = np.linspace(1, max(1.1, duration-1), total_needed)
82
- moments = [{'text': '', 'start': t} for t in times]
83
- elif len(all_subs) <= total_needed:
84
- moments = [{'text': s.content, 'start': s.start.total_seconds()} for s in all_subs]
85
- while len(moments) < total_needed: moments.append({'text': '', 'start': duration/2})
86
- else:
87
- indices = np.linspace(0, len(all_subs) - 1, total_needed, dtype=int)
88
- moments = [{'text': all_subs[i].content, 'start': all_subs[i].start.total_seconds()} for i in indices]
89
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
  frame_metadata = {}
91
  cap = cv2.VideoCapture(video_path)
92
- frame_files = []
93
- for i, m in enumerate(moments):
94
- cap.set(cv2.CAP_PROP_POS_MSEC, m['start'] * 1000)
 
 
 
 
95
  ret, frame = cap.read()
96
  if ret:
97
- fname = f"frame_{i:04d}.png"
98
  p = os.path.join(frames_dir, fname)
99
  cv2.imwrite(p, frame)
100
- frame_metadata[fname] = {'dialogue': m['text'], 'time': m['start']}
101
- frame_files.append(fname)
 
 
102
  cap.release()
103
 
104
- with open(metadata_path, 'w') as f:
105
- json.dump(sanitize_json(frame_metadata), f)
106
-
107
  try: black_bar_crop()
108
  except: pass
109
 
110
  se = SimpleColorEnhancer()
111
- pages_data = []
112
- for p_idx in range(target_pages):
113
- p_p, p_b = [], []
114
- start = p_idx * 5
115
- for i in range(start, start + 5):
116
- if i >= len(frame_files): break
117
- f_name = frame_files[i]
118
- img_p = os.path.join(frames_dir, f_name)
119
- try: se.enhance_single(img_p, img_p)
120
- except: pass
121
-
122
- txt = frame_metadata[f_name]['dialogue']
123
- try:
124
- faces = face_detector.detect_faces(img_p)
125
- lip = face_detector.get_lip_position(img_p, faces[0]) if faces else (-1, -1)
126
- bx, by = ai_bubble_placer.place_bubble_ai(img_p, lip)
127
- item = {'dialog': txt, 'x': bx, 'y': by}
128
- except:
129
- item = {'dialog': txt, 'x': 50, 'y': 25}
 
 
 
 
 
 
 
 
 
 
130
 
131
- p_p.append({'image': f_name})
132
- p_b.append(item)
133
- pages_data.append({'panels': p_p, 'bubbles': p_b})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
134
 
135
- return sanitize_json(pages_data)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
136
 
137
  # ======================================================
138
- # 💻 5. BACKEND MANAGER
139
  # ======================================================
140
- class ComicGenerator:
141
  def __init__(self, sid):
142
  self.sid = sid
143
  self.user_dir = os.path.join(BASE_USER_DIR, sid)
@@ -149,198 +281,864 @@ class ComicGenerator:
149
  self.metadata_path = os.path.join(self.frames_dir, 'frame_metadata.json')
150
 
151
  def cleanup(self):
152
- if os.path.exists(self.user_dir): shutil.rmtree(self.user_dir)
 
153
  os.makedirs(self.frames_dir, exist_ok=True)
154
  os.makedirs(self.output_dir, exist_ok=True)
155
 
156
- def write_status(self, msg, prog):
157
- with open(os.path.join(self.output_dir, 'status.json'), 'w') as f:
158
- json.dump({'message': msg, 'progress': prog}, f)
159
-
160
  def run(self, target_pages):
161
  try:
162
- self.write_status("GPU Engine Active...", 20)
163
- data = generate_comic_gpu(self.video_path, self.user_dir, self.frames_dir, self.metadata_path, target_pages)
164
  with open(os.path.join(self.output_dir, 'pages.json'), 'w') as f:
165
- json.dump(data, f)
166
  self.write_status("Complete!", 100)
167
  except Exception as e:
 
168
  self.write_status(f"Error: {str(e)}", -1)
169
 
 
 
 
 
170
  # ======================================================
171
- # 🌐 6. UI HTML (MANUAL COORDINATES + 100% ZOOM)
172
  # ======================================================
173
  INDEX_HTML = '''
174
- <!DOCTYPE html><html lang="en">
175
- <head>
176
- <meta charset="UTF-8"><title>Elite Pro Comic Creator</title>
177
- <script src="https://cdnjs.cloudflare.com/ajax/libs/html-to-image/1.11.11/html-to-image.min.js"></script>
178
- <link href="https://fonts.googleapis.com/css2?family=Comic+Neue:wght@700&family=Lato:wght@400;900&display=swap" rel="stylesheet">
179
- <style>
180
- /* ⚡ GEOMETRIC PARALLEL COORDINATES ⚡ */
181
- :root {
182
- --w: 1000px;
183
- --h: 700px;
184
- --tierY: 350px;
185
- --gut: 5.25px;
186
-
187
- --r1-topX: 641.2px;
188
- --r1-botX: 588.2px;
189
-
190
- --r2L-topX: 284.2px;
191
- --r2L-botX: 314.2px;
192
-
193
- --r2R-topX: 618.2px;
194
- --r2R-botX: 678.2px;
195
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196
 
197
- body { background: #000; font-family: 'Lato', sans-serif; margin: 0; padding: 20px; color: white; }
198
- .setup-box { max-width: 450px; margin: 80px auto; background: white; padding: 40px; border-radius: 12px; color: black; text-align: center; }
199
-
200
- .comic-page {
201
- background: white; width: var(--w); height: var(--h); margin: 40px auto;
202
- border: 12px solid black; position: relative; overflow: hidden;
203
- display: block; box-shadow: 0 0 50px rgba(0,0,0,0.5);
204
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
205
 
206
- .panel { position: absolute; background: #000; overflow: hidden; cursor: pointer; border: 1px solid black; }
207
-
208
- /* ⚡ 100% ZOOM (NO SCALING) ⚡ */
209
- .panel img {
210
- width: 100%; height: 100%; object-fit: cover;
211
- position: absolute; top: 0; left: 0; pointer-events: none;
212
- }
 
 
 
213
 
214
- /* 📐 CLIPPING MATH 📐 */
215
- .p1 { top: 0; left: 0; width: 100%; height: var(--tierY); clip-path: polygon(0 0, calc(var(--r1-topX) - var(--gut)) 0, calc(var(--r1-botX) - var(--gut)) var(--tierY), 0 var(--tierY)); }
216
- .p2 { top: 0; left: 0; width: 100%; height: var(--tierY); clip-path: polygon(calc(var(--r1-topX) + var(--gut)) 0, var(--w) 0, var(--w) var(--tierY), calc(var(--r1-botX) + var(--gut)) var(--tierY)); }
217
-
218
- .p3 { top: calc(var(--tierY) + var(--gut)); left: 0; width: 100%; height: calc(var(--h) - var(--tierY)); clip-path: polygon(0 0, calc(var(--r2L-topX) - var(--gut)) 0, calc(var(--r2L-botX) - var(--gut)) 100%, 0 100%); }
219
- .p4 { top: calc(var(--tierY) + var(--gut)); left: 0; width: 100%; height: calc(var(--h) - var(--tierY)); clip-path: polygon(calc(var(--r2L-topX) + var(--gut)) 0, calc(var(--r2R-topX) - var(--gut)) 0, calc(var(--r2R-botX) - var(--gut)) 100%, calc(var(--r2L-botX) + var(--gut)) 100%); }
220
- .p5 { top: calc(var(--tierY) + var(--gut)); left: 0; width: 100%; height: calc(var(--h) - var(--tierY)); clip-path: polygon(calc(var(--r2R-topX) + var(--gut)) 0, var(--w) 0, var(--w) 100%, calc(var(--r2R-botX) + var(--gut)) 100%); }
 
 
 
 
 
221
 
222
- .bubble {
223
- position: absolute; background: white; border: 2.5px solid black; border-radius: 25px;
224
- padding: 10px 18px; font-family: 'Comic Neue'; font-weight: bold; font-size: 15px;
225
- color: black; min-width: 110px; text-align: center; cursor: move; z-index: 100;
226
- }
 
227
 
228
- .controls { position: fixed; bottom: 20px; right: 20px; background: #000; padding: 25px; border-radius: 12px; width: 240px; border: 2px solid #333; z-index: 2000; }
229
- button { width: 100%; padding: 12px; margin-top: 10px; cursor: pointer; font-weight: bold; border-radius: 6px; border: none; }
230
- .btn-gen { background: #00d2ff; color: black; }
231
- .hidden { display: none; }
232
- </style>
233
- </head>
234
- <body>
235
- <div id="u-zone" class="setup-box">
236
- <h1>🎬 Pro Comic Maker</h1>
237
- <p>100% Zoom Manual Template</p>
238
- <input type="file" id="vid" accept="video/mp4"><br><br>
239
- <label>Pages: </label><input type="number" id="pg" value="2" style="width:40px"><br><br>
240
- <button class="btn-gen" onclick="start()">🚀 GENERATE COMIC</button>
241
- <div id="loading" class="hidden"><p id="st">Status: Waiting...</p></div>
242
- </div>
243
 
244
- <div id="editor-zone" class="hidden">
245
- <div id="output"></div>
246
- <div class="controls">
247
- <button onclick="addB()" style="background:#2ecc71; color:white;">💬 Add Bubble</button>
248
- <button onclick="exportPNG()" style="background:#3498db; color:white;">📥 Download PNGs</button>
249
- <button onclick="location.reload()">🏠 Reset</button>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
250
  </div>
251
  </div>
252
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
253
  <script>
254
- let sid = 's' + Math.random().toString(36).substr(2,9);
255
- let selP = null;
256
-
257
- async function start() {
258
- const f = document.getElementById('vid').files[0];
259
- if(!f) return alert("Select a video!");
260
- document.getElementById('loading').classList.remove('hidden');
261
- const fd = new FormData(); fd.append('file', f); fd.append('pages', document.getElementById('pg').value);
262
- await fetch(`/uploader?sid=${sid}`, {method: 'POST', body: fd});
263
- const itv = setInterval(async () => {
264
- const r = await fetch(`/status?sid=${sid}`); const d = await r.json();
265
- document.getElementById('st').innerText = "Status: " + (d.message || "Working...");
266
- if(d.progress >= 100) { clearInterval(itv); load(); }
267
- }, 2000);
268
- }
269
-
270
- async function load() {
271
- const r = await fetch(`/output/${sid}/pages.json`); const pages = await r.json();
272
- document.getElementById('u-zone').classList.add('hidden');
273
- document.getElementById('editor-zone').classList.remove('hidden');
274
- const out = document.getElementById('output');
275
- pages.forEach(p => {
276
- const pgDiv = document.createElement('div'); pgDiv.className = 'comic-page';
277
- p.panels.forEach((pan, i) => {
278
- const pDiv = document.createElement('div'); pDiv.className = 'panel p' + (i+1);
279
- pDiv.onclick = (e) => { e.stopPropagation(); selP = pDiv; };
280
- const img = document.createElement('img'); img.src = `/frames/${sid}/${pan.image}`;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
281
  pDiv.appendChild(img);
282
- if(p.bubbles[i]) pDiv.appendChild(createB(p.bubbles[i].dialog, p.bubbles[i].x, p.bubbles[i].y));
283
- pgDiv.appendChild(pDiv);
284
  });
285
- out.appendChild(pgDiv);
 
 
286
  });
 
 
 
 
287
  }
288
-
289
- function createB(txt, x, y) {
290
- const b = document.createElement('div'); b.className = 'bubble';
291
- b.innerText = txt || '...'; b.style.left = x+'px'; b.style.top = y+'px';
292
- b.onmousedown = (e) => {
293
- e.stopPropagation();
294
- let ox = e.clientX - b.offsetLeft, oy = e.clientY - b.offsetTop;
295
- document.onmousemove = (ev) => { b.style.left=(ev.clientX-ox)+'px'; b.style.top=(ev.clientY-oy)+'px'; };
296
- document.onmouseup = () => { document.onmousemove = null; };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
297
  };
298
- b.ondblclick = () => { let n = prompt("Edit text:", b.innerText); if(n) b.innerText = n; };
 
299
  return b;
300
  }
301
-
302
- function addB() { if(selP) selP.appendChild(createB("Dialogue", 60, 60)); }
303
-
304
- async function exportPNG() {
305
- const pgs = document.querySelectorAll('.comic-page');
306
- for(let pg of pgs) {
307
- const url = await htmlToImage.toPng(pg, {pixelRatio: 2});
308
- const l = document.createElement('a'); l.download='Comic_Page.png'; l.href=url; l.click();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
309
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
310
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
311
  </script>
312
- </body></html>
313
- '''
314
 
315
- # ======================================================
316
- # ⚡ 7. FLASK ROUTES
317
- # ======================================================
318
  @app.route('/')
319
- def index(): return INDEX_HTML
 
320
 
321
  @app.route('/uploader', methods=['POST'])
322
- def uploader():
323
  sid = request.args.get('sid')
324
- mgr = ComicGenerator(sid)
325
- mgr.cleanup()
 
 
 
 
 
326
  f = request.files['file']
327
- f.save(mgr.video_path)
328
- threading.Thread(target=mgr.run, args=(request.form.get('pages', 2),)).start()
329
- return jsonify({'success': True})
 
 
 
 
 
330
 
331
  @app.route('/status')
332
- def status():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
333
  sid = request.args.get('sid')
334
- p = os.path.join(BASE_USER_DIR, sid, 'output', 'status.json')
335
- if os.path.exists(p): return send_file(p)
336
- return jsonify({'progress': 0})
337
 
338
- @app.route('/frames/<sid>/<path:f>')
339
- def get_frame(sid, f): return send_from_directory(os.path.join(BASE_USER_DIR, sid, 'frames'), f)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
340
 
341
- @app.route('/output/<sid>/<path:f>')
342
- def get_output(sid, f): return send_from_directory(os.path.join(BASE_USER_DIR, sid, 'output'), f)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
343
 
344
  if __name__ == '__main__':
345
- gpu_warmup()
 
346
  app.run(host='0.0.0.0', port=7860)
 
4
  import threading
5
  import json
6
  import traceback
7
+ import logging
8
+ import string
9
+ import random
10
  import shutil
11
  import cv2
12
+ import math
13
  import numpy as np
14
  import srt
15
  from flask import Flask, jsonify, request, send_from_directory, send_file
16
 
17
  # ======================================================
18
+ # 🚀 ZEROGPU CONFIGURATION
19
  # ======================================================
 
 
20
  @spaces.GPU
21
  def gpu_warmup():
22
  import torch
23
+ print(f"✅ ZeroGPU Warmup: CUDA Available: {torch.cuda.is_available()}")
24
+ return True
25
 
26
  # ======================================================
27
+ # 💾 PERSISTENT STORAGE CONFIGURATION
28
  # ======================================================
29
+ if os.path.exists('/data'):
30
+ BASE_STORAGE_PATH = '/data'
31
+ print("✅ Using Persistent Storage at /data")
32
+ else:
33
+ BASE_STORAGE_PATH = '.'
34
+ print("⚠️ Using Ephemeral/Local Storage")
35
+
36
  BASE_USER_DIR = os.path.join(BASE_STORAGE_PATH, "userdata")
37
+ SAVED_COMICS_DIR = os.path.join(BASE_STORAGE_PATH, "saved_comics")
38
+
39
  os.makedirs(BASE_USER_DIR, exist_ok=True)
40
+ os.makedirs(SAVED_COMICS_DIR, exist_ok=True)
41
 
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'
56
+ }
57
+
58
+ def panel(image=""):
59
+ return {'image': image}
60
+
61
+ class Page:
62
+ def __init__(self, panels, bubbles):
63
+ self.panels = panels
64
+ self.bubbles = bubbles
65
 
66
  # ======================================================
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):
75
+ chars = string.ascii_uppercase + string.digits
76
+ while True:
77
+ code = ''.join(random.choices(chars, k=length))
78
+ if not os.path.exists(os.path.join(SAVED_COMICS_DIR, code)):
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
101
  total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
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:
114
  try: all_subs = list(srt.parse(f.read()))
115
  except: all_subs = []
116
 
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
+ # UPDATED: 5 Panels per page for the new polygon layout
122
+ panels_per_page = 5
123
+ total_panels_needed = target_pages * panels_per_page
124
+
125
+ selected_moments = []
126
+ if not raw_moments:
127
+ times = np.linspace(1, duration-1, total_panels_needed)
128
+ for t in times: selected_moments.append({'text': '', 'start': t, 'end': t+1})
129
+ elif len(raw_moments) <= total_panels_needed:
130
+ selected_moments = raw_moments
131
+ else:
132
+ indices = np.linspace(0, len(raw_moments) - 1, total_panels_needed, dtype=int)
133
+ selected_moments = [raw_moments[i] for i in indices]
134
+
135
  frame_metadata = {}
136
  cap = cv2.VideoCapture(video_path)
137
+ count = 0
138
+ frame_files_ordered = []
139
+
140
+ for i, moment in enumerate(selected_moments):
141
+ mid = (moment['start'] + moment['end']) / 2
142
+ if mid > duration: mid = duration - 1
143
+ cap.set(cv2.CAP_PROP_POS_FRAMES, int(mid * fps))
144
  ret, frame = cap.read()
145
  if ret:
146
+ fname = f"frame_{count:04d}.png"
147
  p = os.path.join(frames_dir, fname)
148
  cv2.imwrite(p, frame)
149
+ os.sync()
150
+ frame_metadata[fname] = {'dialogue': moment['text'], 'time': mid}
151
+ frame_files_ordered.append(fname)
152
+ count += 1
153
  cap.release()
154
 
155
+ with open(metadata_path, 'w') as f: json.dump(frame_metadata, f, indent=2)
156
+
 
157
  try: black_bar_crop()
158
  except: pass
159
 
160
  se = SimpleColorEnhancer()
161
+ qe = QualityColorEnhancer()
162
+
163
+ for f in frame_files_ordered:
164
+ p = os.path.join(frames_dir, f)
165
+ try: se.enhance_single(p, p)
166
+ except: pass
167
+ try: qe.enhance_single(p, p)
168
+ except: pass
169
+
170
+ bubbles_list = []
171
+ for f in frame_files_ordered:
172
+ p = os.path.join(frames_dir, f)
173
+ dialogue = frame_metadata.get(f, {}).get('dialogue', '')
174
+
175
+ b_type = 'speech'
176
+ if '(' in dialogue and ')' in dialogue: b_type = 'narration'
177
+ elif '!' in dialogue and dialogue.isupper(): b_type = 'reaction'
178
+ elif '?' in dialogue: b_type = 'speech'
179
+
180
+ try:
181
+ faces = face_detector.detect_faces(p)
182
+ lip = face_detector.get_lip_position(p, faces[0]) if faces else (-1, -1)
183
+ # Adjust placement for new panel sizes?
184
+ # The AI placement is generic, we let the user adjust in UI
185
+ bx, by = ai_bubble_placer.place_bubble_ai(p, lip)
186
+ b = bubble(dialog=dialogue, bubble_offset_x=bx, bubble_offset_y=by, lip_x=lip[0], lip_y=lip[1], type=b_type)
187
+ bubbles_list.append(b)
188
+ except:
189
+ bubbles_list.append(bubble(dialog=dialogue, type=b_type))
190
 
191
+ pages = []
192
+ for i in range(target_pages):
193
+ start_idx = i * panels_per_page
194
+ end_idx = start_idx + panels_per_page
195
+ p_frames = frame_files_ordered[start_idx:end_idx]
196
+ p_bubbles = bubbles_list[start_idx:end_idx]
197
+ if p_frames:
198
+ pg_panels = [panel(image=f) for f in p_frames]
199
+ pages.append(Page(panels=pg_panels, bubbles=p_bubbles))
200
+
201
+ result = []
202
+ for pg in pages:
203
+ p_data = [p if isinstance(p, dict) else p.__dict__ for p in pg.panels]
204
+ b_data = [b if isinstance(b, dict) else b.__dict__ for b in pg.bubbles]
205
+ result.append({'panels': p_data, 'bubbles': b_data})
206
+
207
+ return result
208
 
209
+ @spaces.GPU
210
+ def regen_frame_gpu(video_path, frames_dir, metadata_path, fname, direction):
211
+ import cv2
212
+ import json
213
+ from backend.simple_color_enhancer import SimpleColorEnhancer
214
+
215
+ if not os.path.exists(metadata_path): return {"success": False, "message": "No metadata"}
216
+ with open(metadata_path, 'r') as f: meta = json.load(f)
217
+ if fname not in meta: return {"success": False, "message": "Frame not found"}
218
+
219
+ t = meta[fname]['time'] if isinstance(meta[fname], dict) else meta[fname]
220
+ cap = cv2.VideoCapture(video_path)
221
+ fps = cap.get(cv2.CAP_PROP_FPS) or 25
222
+ offset = (1.0/fps) * (1 if direction == 'forward' else -1)
223
+ new_t = max(0, t + offset)
224
+
225
+ cap.set(cv2.CAP_PROP_POS_MSEC, new_t * 1000)
226
+ ret, frame = cap.read()
227
+ cap.release()
228
+
229
+ if ret:
230
+ p = os.path.join(frames_dir, fname)
231
+ cv2.imwrite(p, frame)
232
+ os.sync()
233
+ try: SimpleColorEnhancer().enhance_single(p, p)
234
+ except: pass
235
+
236
+ if isinstance(meta[fname], dict): meta[fname]['time'] = new_t
237
+ else: meta[fname] = new_t
238
+ with open(metadata_path, 'w') as f: json.dump(meta, f, indent=2)
239
+ return {"success": True, "message": f"Adjusted to {new_t:.2f}s"}
240
+ return {"success": False, "message": "End of video"}
241
+
242
+ @spaces.GPU
243
+ def get_frame_at_ts_gpu(video_path, frames_dir, metadata_path, fname, ts):
244
+ import cv2
245
+ import json
246
+ from backend.simple_color_enhancer import SimpleColorEnhancer
247
+
248
+ cap = cv2.VideoCapture(video_path)
249
+ cap.set(cv2.CAP_PROP_POS_MSEC, float(ts) * 1000)
250
+ ret, frame = cap.read()
251
+ cap.release()
252
+
253
+ if ret:
254
+ p = os.path.join(frames_dir, fname)
255
+ cv2.imwrite(p, frame)
256
+ os.sync()
257
+ try: SimpleColorEnhancer().enhance_single(p, p)
258
+ except: pass
259
+
260
+ if os.path.exists(metadata_path):
261
+ with open(metadata_path, 'r') as f: meta = json.load(f)
262
+ if fname in meta:
263
+ if isinstance(meta[fname], dict): meta[fname]['time'] = float(ts)
264
+ else: meta[fname] = float(ts)
265
+ with open(metadata_path, 'w') as f: json.dump(meta, f, indent=2)
266
+ return {"success": True, "message": f"Jumped to {ts}s"}
267
+ return {"success": False, "message": "Invalid timestamp"}
268
 
269
  # ======================================================
270
+ # 💻 BACKEND CLASS
271
  # ======================================================
272
+ class EnhancedComicGenerator:
273
  def __init__(self, sid):
274
  self.sid = sid
275
  self.user_dir = os.path.join(BASE_USER_DIR, sid)
 
281
  self.metadata_path = os.path.join(self.frames_dir, 'frame_metadata.json')
282
 
283
  def cleanup(self):
284
+ if os.path.exists(self.frames_dir): shutil.rmtree(self.frames_dir)
285
+ if os.path.exists(self.output_dir): shutil.rmtree(self.output_dir)
286
  os.makedirs(self.frames_dir, exist_ok=True)
287
  os.makedirs(self.output_dir, exist_ok=True)
288
 
 
 
 
 
289
  def run(self, target_pages):
290
  try:
291
+ self.write_status("Waiting for GPU...", 5)
292
+ data = generate_comic_gpu(self.video_path, self.user_dir, self.frames_dir, self.metadata_path, int(target_pages))
293
  with open(os.path.join(self.output_dir, 'pages.json'), 'w') as f:
294
+ json.dump(data, f, indent=2)
295
  self.write_status("Complete!", 100)
296
  except Exception as e:
297
+ traceback.print_exc()
298
  self.write_status(f"Error: {str(e)}", -1)
299
 
300
+ def write_status(self, msg, prog):
301
+ with open(os.path.join(self.output_dir, 'status.json'), 'w') as f:
302
+ json.dump({'message': msg, 'progress': prog}, f)
303
+
304
  # ======================================================
305
+ # 🌐 ROUTES & FULL UI
306
  # ======================================================
307
  INDEX_HTML = '''
308
+ <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>🎬 Enhanced Comic Generator</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; }
309
+
310
+ #upload-container { display: flex; flex-direction:column; justify-content: center; align-items: center; min-height: 100vh; width: 100%; padding: 20px; }
311
+ .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; }
312
+
313
+ #editor-container { display: none; padding: 20px; width: 100%; box-sizing: border-box; padding-bottom: 100px; }
314
+
315
+ h1 { color: #2c3e50; margin-bottom: 20px; font-weight: 600; }
316
+ .file-input { display: none; }
317
+ .file-label { display: block; padding: 15px; background: #2c3e50; color: white; border-radius: 8px; cursor: pointer; font-weight: bold; margin-bottom: 10px; transition:0.2s; }
318
+ .file-label:hover { background: #34495e; }
319
+
320
+ .page-input-group { margin: 20px 0; text-align: left; }
321
+ .page-input-group label { font-weight: bold; font-size: 14px; display: block; margin-bottom: 5px; color: #333; }
322
+ .page-input-group input { width: 100%; padding: 12px; border: 2px solid #ddd; border-radius: 8px; font-size: 16px; box-sizing: border-box; }
323
+
324
+ .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; }
325
+ .submit-btn:hover { background: #d35400; }
326
+ .restore-btn { margin-top: 10px; background: #27ae60; color: white; padding: 12px; width: 100%; border: none; border-radius: 8px; cursor: pointer; font-weight: bold; }
327
+
328
+ .load-section { margin-top: 30px; padding-top: 20px; border-top: 2px solid #eee; }
329
+ .load-input-group { display: flex; gap: 10px; margin-top: 10px; }
330
+ .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; }
331
+ .load-input-group button { padding: 12px 20px; background: #3498db; color: white; border: none; border-radius: 8px; cursor: pointer; font-weight: bold; }
332
+
333
+ .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; }
334
+ @keyframes ball { 0%{background-position:0 50%} 100%{background-position:100px 50%} }
335
+
336
+ /* ========================================= */
337
+ /* 🎨 NEW POLYGON TEMPLATE LAYOUT CSS */
338
+ /* ========================================= */
339
+
340
+ /*
341
+ Total Width: 1000px
342
+ Tier Height: 350px
343
+ Gutter: 10px
344
+
345
+ Row 1 Y: 0 - 350
346
+ Row 2 Y: 360 - 710
347
+ Total Height: 710px
348
+ */
349
 
350
+ .comic-wrapper { max-width: 1050px; margin: 0 auto; }
351
+ .page-wrapper { margin: 30px auto; display: flex; flex-direction: column; align-items: center; }
352
+ .page-title { text-align: center; color: #333; margin-bottom: 10px; font-size: 18px; font-weight: bold; }
353
+
354
+ .comic-page {
355
+ background: white;
356
+ width: 1000px;
357
+ height: 710px;
358
+ box-shadow: 0 4px 10px rgba(0,0,0,0.1);
359
+ position: relative;
360
+ overflow: hidden;
361
+ border: none;
362
+ }
363
+
364
+ /* We use absolute positioning for panels with clip-path */
365
+ .panel {
366
+ position: absolute;
367
+ background: #eee;
368
+ cursor: pointer;
369
+ overflow: hidden;
370
+ border: none;
371
+ }
372
+
373
+ .panel.selected { filter: brightness(0.9) sepia(0.2); z-index: 5; }
374
+
375
+ .panel img {
376
+ width: 100%;
377
+ height: 100%;
378
+ object-fit: cover;
379
+ transition: transform 0.1s ease-out;
380
+ transform-origin: center center;
381
+ }
382
+ .panel img.pannable { cursor: grab; }
383
+ .panel img.panning { cursor: grabbing; }
384
 
385
+ /*
386
+ Coordinates Logic with 10px Gutter (approx +/- 5px from center lines)
387
+
388
+ Row 1 Divider: (635.2, 0) to (588.2, 350)
389
+ Row 2 Left Div: (293.2, 0) to (326.2, 350)
390
+ Row 2 Right Div: (617.2, 0) to (666.2, 350)
391
+
392
+ Row 1 Top: 0px. Row 1 Height: 350px.
393
+ Row 2 Top: 360px. Row 2 Height: 350px.
394
+ */
395
 
396
+ /* --- TIER 1 --- */
397
+ /* Panel 0 (Top Left) */
398
+ .panel-0 {
399
+ top: 0; left: 0; width: 1000px; height: 350px;
400
+ clip-path: polygon(0% 0%, 630.2px 0%, 583.2px 100%, 0% 100%);
401
+ }
402
+
403
+ /* Panel 1 (Top Right) */
404
+ .panel-1 {
405
+ top: 0; left: 0; width: 1000px; height: 350px;
406
+ clip-path: polygon(640.2px 0%, 1000px 0%, 1000px 100%, 593.2px 100%);
407
+ }
408
 
409
+ /* --- TIER 2 --- */
410
+ /* Panel 2 (Bottom Left) */
411
+ .panel-2 {
412
+ top: 360px; left: 0; width: 1000px; height: 350px;
413
+ clip-path: polygon(0% 0%, 288.2px 0%, 321.2px 100%, 0% 100%);
414
+ }
415
 
416
+ /* Panel 3 (Bottom Middle) */
417
+ .panel-3 {
418
+ top: 360px; left: 0; width: 1000px; height: 350px;
419
+ clip-path: polygon(298.2px 0%, 612.2px 0%, 661.2px 100%, 331.2px 100%);
420
+ }
 
 
 
 
 
 
 
 
 
 
421
 
422
+ /* Panel 4 (Bottom Right) */
423
+ .panel-4 {
424
+ top: 360px; left: 0; width: 1000px; height: 350px;
425
+ clip-path: polygon(622.2px 0%, 1000px 0%, 1000px 100%, 671.2px 100%);
426
+ }
427
+
428
+ /* SPEECH BUBBLES */
429
+ .speech-bubble {
430
+ position: absolute; display: flex; justify-content: center; align-items: center;
431
+ width: 150px; height: 80px; min-width: 50px; min-height: 30px; box-sizing: border-box;
432
+ z-index: 10; cursor: move; font-family: 'Comic Neue', cursive; font-weight: bold;
433
+ font-size: 13px; text-align: center;
434
+ overflow: visible;
435
+ line-height: 1.2;
436
+ --tail-pos: 50%;
437
+ }
438
+
439
+ .bubble-text {
440
+ padding: 0.5em;
441
+ word-wrap: break-word;
442
+ white-space: pre-wrap;
443
+ position: relative;
444
+ z-index: 5;
445
+ pointer-events: none;
446
+ user-select: none;
447
+ width: 100%;
448
+ height: 100%;
449
+ overflow: hidden;
450
+ display: flex;
451
+ align-items: center;
452
+ justify-content: center;
453
+ border-radius: inherit;
454
+ }
455
+
456
+ .speech-bubble.selected { outline: 2px dashed #4CAF50; z-index: 100; }
457
+ .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; }
458
+
459
+ /* SPEECH BUBBLE CSS (Tails) */
460
+ .speech-bubble.speech {
461
+ --b: 3em; --h: 1.8em; --t: 0.6; --p: var(--tail-pos, 50%); --r: 1.2em;
462
+ background: var(--bubble-fill-color, #4ECDC4);
463
+ color: var(--bubble-text-color, #fff);
464
+ padding: 0;
465
+ 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);
466
+ }
467
+ .speech-bubble.speech:before {
468
+ content: ""; position: absolute; width: var(--b); height: var(--h);
469
+ background: inherit; border-bottom-left-radius: 100%; pointer-events: none; z-index: 1;
470
+ -webkit-mask: radial-gradient(calc(var(--t)*100%) 105% at 100% 0,#0000 99%,#000 101%);
471
+ mask: radial-gradient(calc(var(--t)*100%) 105% at 100% 0,#0000 99%,#000 101%);
472
+ }
473
+
474
+ .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))); }
475
+ .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); }
476
+ .speech-bubble.speech.tail-left { border-radius: var(--r); }
477
+ .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; }
478
+ .speech-bubble.speech.tail-right { border-radius: var(--r); }
479
+ .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; }
480
+
481
+ .speech-bubble.thought { background: white; border: 2px dashed #555; color: #333; border-radius: 50%; }
482
+ .speech-bubble.thought::before { display:none; }
483
+ .thought-dot { position: absolute; background-color: white; border: 2px solid #555; border-radius: 50%; z-index: -1; }
484
+ .thought-dot-1 { width: 20px; height: 20px; }
485
+ .thought-dot-2 { width: 12px; height: 12px; }
486
+
487
+ .speech-bubble.thought.pos-bl .thought-dot-1 { left: 20px; bottom: -20px; }
488
+ .speech-bubble.thought.pos-bl .thought-dot-2 { left: 10px; bottom: -32px; }
489
+ .speech-bubble.thought.pos-br .thought-dot-1 { right: 20px; bottom: -20px; }
490
+ .speech-bubble.thought.pos-br .thought-dot-2 { right: 10px; bottom: -32px; }
491
+ .speech-bubble.thought.pos-tr .thought-dot-1 { right: 20px; top: -20px; }
492
+ .speech-bubble.thought.pos-tr .thought-dot-2 { right: 10px; top: -32px; }
493
+ .speech-bubble.thought.pos-tl .thought-dot-1 { left: 20px; top: -20px; }
494
+ .speech-bubble.thought.pos-tl .thought-dot-2 { left: 10px; top: -32px; }
495
+
496
+ .speech-bubble.reaction { background: #FFD700; border: 3px solid #E53935; color: #D32F2F; font-weight: 900; 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%); }
497
+ .speech-bubble.narration { background: #FAFAFA; border: 2px solid #BDBDBD; color: #424242; border-radius: 3px; }
498
+
499
+ .resize-handle { position: absolute; width: 10px; height: 10px; background: #2196F3; border: 1px solid white; border-radius: 50%; display: none; z-index: 11; }
500
+ .speech-bubble.selected .resize-handle { display: block; }
501
+ .resize-handle.se { bottom: -5px; right: -5px; cursor: se-resize; }
502
+ .resize-handle.sw { bottom: -5px; left: -5px; cursor: sw-resize; }
503
+ .resize-handle.ne { top: -5px; right: -5px; cursor: ne-resize; }
504
+ .resize-handle.nw { top: -5px; left: -5px; cursor: nw-resize; }
505
+
506
+ /* CONTROLS */
507
+ .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; }
508
+ .edit-controls h4 { margin: 0 0 10px 0; color: #4ECDC4; text-align: center; }
509
+ .control-group { margin-top: 10px; border-top: 1px solid #555; padding-top: 10px; }
510
+ .control-group label { font-size: 11px; font-weight: bold; display: block; margin-bottom: 3px; }
511
+ 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; }
512
+ .button-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 5px; }
513
+ .color-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 5px; }
514
+ .slider-container { display: flex; align-items: center; gap: 5px; margin-top: 5px; }
515
+ .slider-container label { min-width: 40px; font-size: 11px; }
516
+ .action-btn { background: #4CAF50; color: white; }
517
+ .reset-btn { background: #e74c3c; color: white; }
518
+ .secondary-btn { background: #f39c12; color: white; }
519
+ .export-btn { background: #2196F3; color: white; }
520
+ .save-btn { background: #9b59b6; color: white; }
521
+ .undo-btn { background: #7f8c8d; color: white; margin-bottom: 5px; }
522
+
523
+ /* MODAL */
524
+ .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; }
525
+ .modal-content { background: white; padding: 30px; border-radius: 12px; max-width: 400px; width: 90%; text-align: center; }
526
+ .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; }
527
+ .modal-content button { background: #3498db; color: white; border: none; padding: 12px 30px; border-radius: 8px; cursor: pointer; font-weight: bold; margin: 5px; }
528
+ </style>
529
+ </head> <body> <div id="upload-container"> <div class="upload-box"> <h1>🎬 Enhanced Comic Generator</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>
530
+ <div class="page-input-group">
531
+ <label>📚 Total Comic Pages:</label>
532
+ <input type="number" id="page-count" value="3" min="1" max="15" placeholder="e.g. 3 (Video will be divided evenly)">
533
+ <small style="color:#666; font-size:11px; display:block; margin-top:5px;">System calculates 5 panels per page (Polygon Layout).</small>
534
+ </div>
535
+
536
+ <button class="submit-btn" onclick="upload()">🚀 Generate Comic</button>
537
+ <button id="restore-draft-btn" class="restore-btn" style="display:none; margin-top:15px;" onclick="restoreDraft()">📂 Restore Unsaved Draft</button>
538
+
539
+ <div class="load-section">
540
+ <h3>📥 Load Saved Comic</h3>
541
+ <div class="load-input-group">
542
+ <input type="text" id="load-code-input" placeholder="SAVE CODE" maxlength="8" style="text-transform:uppercase;">
543
+ <button onclick="loadSavedComic()">Load</button>
544
+ </div>
545
+ </div>
546
+ <div class="loading-view" id="loading-view" style="display:none; margin-top:20px;">
547
+ <div class="loader" style="margin:0 auto;"></div>
548
+ <p id="status-text" style="margin-top:10px;">Starting...</p>
549
  </div>
550
  </div>
551
+ </div>
552
+ <div id="editor-container">
553
+ <div class="comic-wrapper" id="comic-container"></div>
554
+ <input type="file" id="image-uploader" style="display: none;" accept="image/*">
555
+ <div class="edit-controls">
556
+ <h4>✏️ Interactive Editor</h4>
557
+
558
+ <button onclick="undoLastAction()" class="undo-btn">↩️ Undo</button>
559
+
560
+ <div class="control-group">
561
+ <label>💾 Save & Load:</label>
562
+ <button onclick="saveComic()" class="save-btn">💾 Save Comic</button>
563
+ <div id="current-save-code" style="display:none; margin-top:5px; text-align:center;">
564
+ <span id="display-save-code" style="font-weight:bold; background:#eee; padding:2px 5px; border-radius:3px;"></span>
565
+ <button onclick="copyCode()" style="padding:2px; width:auto; font-size:10px;">Copy</button>
566
+ </div>
567
+ </div>
568
+
569
+ <div class="control-group">
570
+ <label>💬 Bubble Styling:</label>
571
+ <select id="bubble-type-select" onchange="changeBubbleType(this.value)" disabled>
572
+ <option value="speech">Speech</option>
573
+ <option value="thought">Thought</option>
574
+ <option value="reaction">Reaction (Shout)</option>
575
+ <option value="narration">Narration (Box)</option>
576
+ </select>
577
+ <select id="font-select" onchange="changeFont(this.value)" disabled>
578
+ <option value="'Comic Neue', cursive">Comic Neue</option>
579
+ <option value="'Bangers', cursive">Bangers</option>
580
+ <option value="'Gloria Hallelujah', cursive">Gloria</option>
581
+ <option value="'Lato', sans-serif">Lato</option>
582
+ </select>
583
+ <div class="color-grid">
584
+ <div><label>Text</label><input type="color" id="bubble-text-color" value="#ffffff" disabled></div>
585
+ <div><label>Fill</label><input type="color" id="bubble-fill-color" value="#4ECDC4" disabled></div>
586
+ </div>
587
+ <div class="button-grid">
588
+ <button onclick="addBubble()" class="action-btn">Add</button>
589
+ <button onclick="deleteBubble()" class="reset-btn">Delete</button>
590
+ </div>
591
+ </div>
592
+
593
+ <div class="control-group" id="tail-controls" style="display:none;">
594
+ <label>📐 Tail Adjustment:</label>
595
+ <button onclick="rotateTail()" class="secondary-btn">🔄 Rotate Side</button>
596
+ <div class="slider-container">
597
+ <label>Pos:</label>
598
+ <input type="range" id="tail-slider" min="10" max="90" value="50" oninput="slideTail(this.value)">
599
+ </div>
600
+ </div>
601
+
602
+ <div class="control-group">
603
+ <label>🖼️ Panel Tools:</label>
604
+ <button onclick="replacePanelImage()" class="action-btn">🖼️ Replace Image</button>
605
+ <div class="button-grid">
606
+ <button onclick="adjustFrame('backward')" class="secondary-btn" id="prev-btn">⬅️ Prev</button>
607
+ <button onclick="adjustFrame('forward')" class="action-btn" id="next-btn">Next ➡️</button>
608
+ </div>
609
+ <div class="timestamp-controls">
610
+ <input type="text" id="timestamp-input" placeholder="mm:ss or secs">
611
+ <button onclick="gotoTimestamp()" class="action-btn" id="go-btn">Go</button>
612
+ </div>
613
+ </div>
614
+
615
+ <div class="control-group">
616
+ <label>🔍 Zoom & Pan:</label>
617
+ <div class="button-grid">
618
+ <button onclick="resetPanelTransform()" class="secondary-btn">Reset</button>
619
+ <input type="range" id="zoom-slider" min="100" max="300" value="100" step="5" disabled oninput="handleZoom(this)">
620
+ </div>
621
+ </div>
622
+
623
+ <div class="control-group">
624
+ <button onclick="exportComic()" class="export-btn">📥 Export as PNG</button>
625
+ <button onclick="goBackToUpload()" class="reset-btn" style="margin-top:10px;">🏠 Home</button>
626
+ </div>
627
+ </div>
628
+ </div>
629
+ <div class="modal-overlay" id="save-modal">
630
+ <div class="modal-content">
631
+ <h2>✅ Comic Saved!</h2>
632
+ <div class="code" id="modal-save-code">XXXXXXXX</div>
633
+ <button onclick="copyModalCode()">📋 Copy Code</button>
634
+ <button class="close-btn" onclick="closeModal()">Close</button>
635
+ </div>
636
+ </div>
637
  <script>
638
+ 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);}); }
639
+ let sid = localStorage.getItem('comic_sid') || genUUID();
640
+ localStorage.setItem('comic_sid', sid);
641
+
642
+ let currentSaveCode = null;
643
+ let isProcessing = false;
644
+ let interval, selectedBubble = null, selectedPanel = null;
645
+ let isDragging = false, isResizing = false, isPanning = false;
646
+ let startX, startY, initX, initY, panStartX, panStartY, panStartTx, panStartTy;
647
+ let resizeHandle, originalWidth, originalHeight, originalMouseX, originalMouseY;
648
+ let currentlyEditing = null;
649
+
650
+ // UNDO SYSTEM
651
+ let historyStack = [];
652
+ let historyIndex = -1;
653
+ function addToHistory() {
654
+ if (historyIndex < historyStack.length - 1) {
655
+ historyStack = historyStack.slice(0, historyIndex + 1);
656
+ }
657
+ const state = JSON.stringify(getCurrentState());
658
+ if (historyStack.length > 0 && historyStack[historyStack.length - 1] === state) return;
659
+
660
+ historyStack.push(state);
661
+ historyIndex++;
662
+
663
+ if (historyStack.length > 30) {
664
+ historyStack.shift();
665
+ historyIndex--;
666
+ }
667
+ }
668
+ function undoLastAction() {
669
+ if (historyIndex > 0) {
670
+ historyIndex--;
671
+ const previousState = JSON.parse(historyStack[historyIndex]);
672
+ renderFromState(previousState);
673
+ saveDraft(false);
674
+ }
675
+ }
676
+
677
+ if(localStorage.getItem('comic_draft_'+sid)) document.getElementById('restore-draft-btn').style.display = 'block';
678
+
679
+ function showSaveModal(code) { document.getElementById('modal-save-code').textContent = code; document.getElementById('save-modal').style.display = 'flex'; }
680
+ function closeModal() { document.getElementById('save-modal').style.display = 'none'; }
681
+ function copyModalCode() { navigator.clipboard.writeText(document.getElementById('modal-save-code').textContent).then(() => alert('Code copied!')); }
682
+ function copyCode() { if(currentSaveCode) navigator.clipboard.writeText(currentSaveCode).then(() => alert('Code copied!')); }
683
+
684
+ function setProcessing(busy) {
685
+ isProcessing = busy;
686
+ const btns = ['prev-btn', 'next-btn', 'go-btn'];
687
+ btns.forEach(id => {
688
+ const el = document.getElementById(id);
689
+ if(el) { el.disabled = busy; el.style.opacity = busy ? '0.5' : '1'; el.innerText = busy ? '⏳' : el.getAttribute('data-txt') || el.innerText; }
690
+ });
691
+ }
692
+ async function saveComic() {
693
+ const state = getCurrentState();
694
+ if(!state || state.length === 0) { alert('No comic to save!'); return; }
695
+ try {
696
+ const r = await fetch(`/save_comic?sid=${sid}`, { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ pages: state, savedAt: new Date().toISOString() }) });
697
+ const d = await r.json();
698
+ 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); }
699
+ else { alert('Failed to save: ' + d.message); }
700
+ } catch(e) { console.error(e); alert('Error saving comic'); }
701
+ }
702
+
703
+ async function loadSavedComic() {
704
+ const code = document.getElementById('load-code-input').value.trim().toUpperCase();
705
+ if(!code || code.length < 4) { alert('Invalid code'); return; }
706
+ try {
707
+ const r = await fetch(`/load_comic/${code}`);
708
+ const d = await r.json();
709
+ if(d.success) { currentSaveCode = code; sid = d.originalSid || sid; localStorage.setItem('comic_sid', sid); renderFromState(d.pages); document.getElementById('upload-container').style.display = 'none'; document.getElementById('editor-container').style.display = 'block'; document.getElementById('display-save-code').textContent = code; document.getElementById('current-save-code').style.display = 'block'; saveDraft(true); }
710
+ else { alert('Load failed: ' + d.message); }
711
+ } catch(e) { console.error(e); alert('Error loading comic.'); }
712
+ }
713
+
714
+ function restoreDraft() {
715
+ try {
716
+ const state = JSON.parse(localStorage.getItem('comic_draft_'+sid));
717
+ if(state.saveCode) { currentSaveCode = state.saveCode; document.getElementById('display-save-code').textContent = state.saveCode; document.getElementById('current-save-code').style.display = 'block'; }
718
+ renderFromState(state.pages || state);
719
+ document.getElementById('upload-container').style.display = 'none';
720
+ document.getElementById('editor-container').style.display = 'block';
721
+ addToHistory();
722
+ } catch(e) { console.error(e); alert("Failed to restore."); }
723
+ }
724
+
725
+ function getCurrentState() {
726
+ const pages = [];
727
+ document.querySelectorAll('.comic-page').forEach(p => {
728
+ const panels = [];
729
+ p.querySelectorAll('.panel').forEach(pan => {
730
+ const img = pan.querySelector('img');
731
+ const bubbles = [];
732
+ pan.querySelectorAll('.speech-bubble').forEach(b => {
733
+ const textEl = b.querySelector('.bubble-text');
734
+ bubbles.push({
735
+ text: textEl ? textEl.textContent : '',
736
+ left: b.style.left, top: b.style.top, width: b.style.width, height: b.style.height,
737
+ classes: b.className.replace(' selected', ''),
738
+ type: b.dataset.type, font: b.style.fontFamily,
739
+ tailPos: b.style.getPropertyValue('--tail-pos'),
740
+ colors: { fill: b.style.getPropertyValue('--bubble-fill-color'), text: b.style.getPropertyValue('--bubble-text-color') }
741
+ });
742
+ });
743
+ panels.push({
744
+ src: img.src,
745
+ zoom: img.dataset.zoom, tx: img.dataset.translateX, ty: img.dataset.translateY,
746
+ bubbles: bubbles
747
+ });
748
+ });
749
+ pages.push({ panels: panels });
750
+ });
751
+ return pages;
752
+ }
753
+
754
+ function saveDraft(recordHistory = true) {
755
+ if(recordHistory) addToHistory();
756
+ localStorage.setItem('comic_draft_'+sid, JSON.stringify({ pages: getCurrentState(), saveCode: currentSaveCode, savedAt: new Date().toISOString() }));
757
+ }
758
+
759
+ function renderFromState(pagesData) {
760
+ const con = document.getElementById('comic-container'); con.innerHTML = '';
761
+ pagesData.forEach((page, pageIdx) => {
762
+ const pageWrapper = document.createElement('div'); pageWrapper.className = 'page-wrapper';
763
+ const pageTitle = document.createElement('h2'); pageTitle.className = 'page-title'; pageTitle.textContent = `Page ${pageIdx + 1}`;
764
+ pageWrapper.appendChild(pageTitle);
765
+
766
+ const div = document.createElement('div');
767
+ div.className = 'comic-page'; // Now 1000x710px
768
+
769
+ // Render 5 panels using specific layout classes
770
+ page.panels.forEach((pan, idx) => {
771
+ const pDiv = document.createElement('div');
772
+ // Cycle through 0-4 for layout positions if there are more panels, or just use idx
773
+ const posClass = `panel-${idx % 5}`;
774
+ pDiv.className = `panel ${posClass}`;
775
+
776
+ pDiv.onclick = (e) => { e.stopPropagation(); selectPanel(pDiv); };
777
+ const img = document.createElement('img');
778
+ img.src = pan.src.includes('?') ? pan.src : pan.src + `?sid=${sid}`;
779
+ img.dataset.zoom = pan.zoom || 100; img.dataset.translateX = pan.tx || 0; img.dataset.translateY = pan.ty || 0;
780
+ updateImageTransform(img);
781
+ img.onmousedown = (e) => startPan(e, img);
782
  pDiv.appendChild(img);
783
+ (pan.bubbles || []).forEach(bData => { pDiv.appendChild(createBubbleHTML(bData)); });
784
+ div.appendChild(pDiv);
785
  });
786
+
787
+ pageWrapper.appendChild(div);
788
+ con.appendChild(pageWrapper);
789
  });
790
+ selectedBubble = null;
791
+ selectedPanel = null;
792
+ document.getElementById('bubble-type-select').disabled = true;
793
+ document.getElementById('font-select').disabled = true;
794
  }
795
+
796
+ async function upload() {
797
+ const f = document.getElementById('file-upload').files[0];
798
+ const pCount = document.getElementById('page-count').value;
799
+ if(!f) return alert("Select a video");
800
+ sid = genUUID(); localStorage.setItem('comic_sid', sid); currentSaveCode = null;
801
+ document.querySelector('.upload-box').style.display='none';
802
+ document.getElementById('loading-view').style.display='flex';
803
+ const fd = new FormData(); fd.append('file', f); fd.append('target_pages', pCount);
804
+ const r = await fetch(`/uploader?sid=${sid}`, {method:'POST', body:fd});
805
+ if(r.ok) interval = setInterval(checkStatus, 2000);
806
+ else { alert("Upload failed"); location.reload(); }
807
+ }
808
+
809
+ async function checkStatus() {
810
+ try {
811
+ const r = await fetch(`/status?sid=${sid}`); const d = await r.json();
812
+ document.getElementById('status-text').innerText = d.message;
813
+ if(d.progress >= 100) { clearInterval(interval); document.getElementById('upload-container').style.display='none'; document.getElementById('editor-container').style.display='block'; loadNewComic(); }
814
+ else if (d.progress < 0) { clearInterval(interval); document.getElementById('status-text').textContent = "Error: " + d.message; document.querySelector('.loader').style.display = 'none'; }
815
+ } catch(e) {}
816
+ }
817
+
818
+ function loadNewComic() {
819
+ fetch(`/output/pages.json?sid=${sid}`).then(r=>r.json()).then(data => {
820
+ const cleanData = data.map((p, pi) => ({
821
+ panels: p.panels.map((pan, j) => ({
822
+ src: `/frames/${pan.image}?sid=${sid}`,
823
+ bubbles: (p.bubbles && p.bubbles[j] && p.bubbles[j].dialog) ? [{
824
+ text: p.bubbles[j].dialog,
825
+ left: (p.bubbles[j].bubble_offset_x || 50) + 'px',
826
+ top: (p.bubbles[j].bubble_offset_y || 20) + 'px',
827
+ type: (p.bubbles[j].type || 'speech'),
828
+ classes: `speech-bubble ${p.bubbles[j].type || 'speech'} tail-bottom`
829
+ }] : []
830
+ }))
831
+ }));
832
+ renderFromState(cleanData); saveDraft(true);
833
+ });
834
+ }
835
+
836
+ function createBubbleHTML(data) {
837
+ const b = document.createElement('div');
838
+ const type = data.type || 'speech';
839
+ b.className = data.classes || `speech-bubble ${type} tail-bottom`;
840
+ if (type === 'thought' && !b.className.includes('pos-')) b.className += ' pos-bl';
841
+
842
+ b.dataset.type = type;
843
+ b.style.left = data.left; b.style.top = data.top;
844
+ if(data.width) b.style.width = data.width; if(data.height) b.style.height = data.height;
845
+ if(data.font) b.style.fontFamily = data.font;
846
+ if(data.colors) { b.style.setProperty('--bubble-fill-color', data.colors.fill || '#4ECDC4'); b.style.setProperty('--bubble-text-color', data.colors.text || '#ffffff'); }
847
+ if(data.tailPos) b.style.setProperty('--tail-pos', data.tailPos);
848
+
849
+ const textSpan = document.createElement('span'); textSpan.className = 'bubble-text'; textSpan.textContent = data.text || ''; b.appendChild(textSpan);
850
+
851
+ 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); } }
852
+
853
+ ['nw', 'ne', 'sw', 'se'].forEach(dir => { const handle = document.createElement('div'); handle.className = `resize-handle ${dir}`; handle.onmousedown = (e) => startResize(e, dir); b.appendChild(handle); });
854
+
855
+ b.onmousedown = (e) => {
856
+ if(e.target.classList.contains('resize-handle')) return;
857
+ e.stopPropagation(); selectBubble(b); isDragging = true; startX = e.clientX; startY = e.clientY; initX = b.offsetLeft; initY = b.offsetTop;
858
  };
859
+ b.onclick = (e) => { e.stopPropagation(); };
860
+ b.ondblclick = (e) => { e.stopPropagation(); editBubbleText(b); };
861
  return b;
862
  }
863
+
864
+ function editBubbleText(bubble) {
865
+ if (currentlyEditing) return; currentlyEditing = bubble;
866
+ const textSpan = bubble.querySelector('.bubble-text'); const textarea = document.createElement('textarea');
867
+ textarea.value = textSpan.textContent; bubble.appendChild(textarea); textSpan.style.display = 'none'; textarea.focus();
868
+ const finishEditing = () => {
869
+ textSpan.textContent = textarea.value; textarea.remove(); textSpan.style.display = ''; currentlyEditing = null;
870
+ saveDraft(true);
871
+ };
872
+ textarea.addEventListener('blur', finishEditing, { once: true });
873
+ textarea.addEventListener('keydown', e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); textarea.blur(); } });
874
+ }
875
+
876
+ document.addEventListener('mousemove', (e) => {
877
+ if(isDragging && selectedBubble) { selectedBubble.style.left = (initX + e.clientX - startX) + 'px'; selectedBubble.style.top = (initY + e.clientY - startY) + 'px'; }
878
+ if(isResizing && selectedBubble) { resizeBubble(e); }
879
+ if(isPanning && selectedPanel) { panImage(e); }
880
+ });
881
+
882
+ document.addEventListener('mouseup', () => {
883
+ if(isDragging || isResizing || isPanning) {
884
+ saveDraft(true);
885
  }
886
+ isDragging = false; isResizing = false; isPanning = false;
887
+ });
888
+
889
+ function startResize(e, dir) { e.preventDefault(); e.stopPropagation(); isResizing = true; resizeHandle = dir; const rect = selectedBubble.getBoundingClientRect(); originalWidth = rect.width; originalHeight = rect.height; originalMouseX = e.clientX; originalMouseY = e.clientY; }
890
+ function resizeBubble(e) { if (!isResizing || !selectedBubble) return; const dx = e.clientX - originalMouseX; const dy = e.clientY - originalMouseY; if(resizeHandle.includes('e')) selectedBubble.style.width = (originalWidth + dx)+'px'; if(resizeHandle.includes('s')) selectedBubble.style.height = (originalHeight + dy)+'px'; }
891
+
892
+ function selectBubble(el) {
893
+ if(selectedBubble) selectedBubble.classList.remove('selected');
894
+ if(selectedPanel) { selectedPanel.classList.remove('selected'); selectedPanel = null; }
895
+ selectedBubble = el; el.classList.add('selected');
896
+ document.getElementById('bubble-type-select').disabled = false;
897
+ document.getElementById('font-select').disabled = false;
898
+ document.getElementById('bubble-text-color').disabled = false;
899
+ document.getElementById('bubble-fill-color').disabled = false;
900
+ document.getElementById('tail-controls').style.display = 'block';
901
+ document.getElementById('bubble-type-select').value = el.dataset.type || 'speech';
902
+ }
903
+
904
+ function selectPanel(el) {
905
+ if(selectedPanel) selectedPanel.classList.remove('selected');
906
+ if(selectedBubble) { selectedBubble.classList.remove('selected'); selectedBubble = null; }
907
+ selectedPanel = el; el.classList.add('selected');
908
+ document.getElementById('zoom-slider').disabled = false;
909
+ const img = el.querySelector('img');
910
+ document.getElementById('zoom-slider').value = img.dataset.zoom || 100;
911
+ document.getElementById('bubble-type-select').disabled = true;
912
+ document.getElementById('font-select').disabled = true;
913
+ document.getElementById('tail-controls').style.display = 'none';
914
+ }
915
+
916
+ function addBubble() {
917
+ if(!selectedPanel) return alert("Select a panel first");
918
+ const b = createBubbleHTML({ text: "Text", left: "50px", top: "30px", type: 'speech', classes: "speech-bubble speech tail-bottom" });
919
+ selectedPanel.appendChild(b); selectBubble(b); saveDraft(true);
920
  }
921
+
922
+ function deleteBubble() {
923
+ if(!selectedBubble) return alert("Select a bubble");
924
+ selectedBubble.remove(); selectedBubble=null; saveDraft(true);
925
+ }
926
+
927
+ function changeBubbleType(type) {
928
+ if(!selectedBubble) return;
929
+ selectedBubble.dataset.type = type;
930
+ selectedBubble.className = 'speech-bubble ' + type + ' selected';
931
+
932
+ if(type === 'thought') selectedBubble.classList.add('pos-bl');
933
+ else selectedBubble.classList.add('tail-bottom');
934
+
935
+ selectedBubble.querySelectorAll('.thought-dot').forEach(d=>d.remove());
936
+ if(type === 'thought') { for(let i=1; i<=2; i++){ const d = document.createElement('div'); d.className = `thought-dot thought-dot-${i}`; selectedBubble.appendChild(d); } }
937
+ saveDraft(true);
938
+ }
939
+
940
+ function changeFont(font) { if(!selectedBubble) return; selectedBubble.style.fontFamily = font; saveDraft(true); }
941
+
942
+ function rotateTail() {
943
+ if(!selectedBubble) return;
944
+ const type = selectedBubble.dataset.type;
945
+
946
+ if(type === 'speech') {
947
+ const positions = ['tail-bottom', 'tail-right', 'tail-top', 'tail-left'];
948
+ let current = 0;
949
+ positions.forEach((pos, i) => { if(selectedBubble.classList.contains(pos)) current = i; });
950
+ selectedBubble.classList.remove(positions[current]);
951
+ selectedBubble.classList.add(positions[(current + 1) % 4]);
952
+ }
953
+ else if (type === 'thought') {
954
+ const positions = ['pos-bl', 'pos-br', 'pos-tr', 'pos-tl'];
955
+ let current = 0;
956
+ positions.forEach((pos, i) => { if(selectedBubble.classList.contains(pos)) current = i; });
957
+ selectedBubble.classList.remove(positions[current]);
958
+ selectedBubble.classList.add(positions[(current + 1) % 4]);
959
+ }
960
+ saveDraft(true);
961
+ }
962
+
963
+ function slideTail(v) { if(selectedBubble) { selectedBubble.style.setProperty('--tail-pos', v+'%'); saveDraft(true); } }
964
+
965
+ document.getElementById('bubble-text-color').addEventListener('change', (e) => { if(selectedBubble) { selectedBubble.style.setProperty('--bubble-text-color', e.target.value); saveDraft(true); } });
966
+ document.getElementById('bubble-fill-color').addEventListener('change', (e) => { if(selectedBubble) { selectedBubble.style.setProperty('--bubble-fill-color', e.target.value); saveDraft(true); } });
967
+
968
+ function handleZoom(el) { if(!selectedPanel) return; const img = selectedPanel.querySelector('img'); img.dataset.zoom = el.value; updateImageTransform(img); }
969
+ document.getElementById('zoom-slider').addEventListener('change', () => saveDraft(true));
970
+ function startPan(e, img) { if(parseFloat(img.dataset.zoom || 100) <= 100) return; e.preventDefault(); isPanning = true; selectedPanel = img.closest('.panel'); panStartX = e.clientX; panStartY = e.clientY; panStartTx = parseFloat(img.dataset.translateX || 0); panStartTy = parseFloat(img.dataset.translateY || 0); img.classList.add('panning'); }
971
+ function panImage(e) { if(!isPanning || !selectedPanel) return; const img = selectedPanel.querySelector('img'); img.dataset.translateX = panStartTx + (e.clientX - panStartX); img.dataset.translateY = panStartTy + (e.clientY - panStartY); updateImageTransform(img); }
972
+ function updateImageTransform(img) { const z = (img.dataset.zoom || 100) / 100; const x = img.dataset.translateX || 0; const y = img.dataset.translateY || 0; img.style.transform = `translateX(${x}px) translateY(${y}px) scale(${z})`; img.classList.toggle('pannable', z > 1); }
973
+ function resetPanelTransform() { if(!selectedPanel) return alert("Select a panel"); const img = selectedPanel.querySelector('img'); img.dataset.zoom = 100; img.dataset.translateX = 0; img.dataset.translateY = 0; document.getElementById('zoom-slider').value = 100; updateImageTransform(img); saveDraft(true); }
974
+
975
+ function replacePanelImage() { if(!selectedPanel) return alert("Select a panel"); const inp = document.getElementById('image-uploader'); inp.onchange = async (e) => { const fd = new FormData(); fd.append('image', e.target.files[0]); const img = selectedPanel.querySelector('img'); const r = await fetch(`/replace_panel?sid=${sid}`, {method:'POST', body:fd}); const d = await r.json(); if(d.success) { img.src = `/frames/${d.new_filename}?sid=${sid}`; saveDraft(true); } inp.value = ''; }; inp.click(); }
976
+ async function adjustFrame(dir) { if(isProcessing) return; if(!selectedPanel) return alert("Select a panel"); const img = selectedPanel.querySelector('img'); let fname = img.src.split('/').pop().split('?')[0]; setProcessing(true); img.style.opacity = '0.5'; try { const r = await fetch(`/regenerate_frame?sid=${sid}`, { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({filename:fname, direction:dir}) }); const d = await r.json(); if(d.success) { img.src = `/frames/${fname}?sid=${sid}&t=${Date.now()}`; } else { alert('Error: ' + d.message); } } catch(e) { console.error(e); } img.style.opacity = '1'; setProcessing(false); saveDraft(true); }
977
+ async function gotoTimestamp() { if(isProcessing) return; if(!selectedPanel) return alert("Select a panel"); let v = document.getElementById('timestamp-input').value.trim(); if(!v) return; if(v.includes(':')) { let p = v.split(':'); v = parseInt(p[0]) * 60 + parseFloat(p[1]); } else { v = parseFloat(v); } if(isNaN(v)) return alert("Invalid time"); const img = selectedPanel.querySelector('img'); let fname = img.src.split('/').pop().split('?')[0]; setProcessing(true); img.style.opacity = '0.5'; try { const r = await fetch(`/goto_timestamp?sid=${sid}`, { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({filename:fname, timestamp:v}) }); const d = await r.json(); if(d.success) { img.src = `/frames/${fname}?sid=${sid}&t=${Date.now()}`; document.getElementById('timestamp-input').value = ''; } else { alert('Error: ' + d.message); } } catch(e) { console.error(e); } img.style.opacity = '1'; setProcessing(false); saveDraft(true); }
978
+
979
+ async function exportComic() {
980
+ const pgs = document.querySelectorAll('.comic-page');
981
+ if(pgs.length === 0) return alert("No pages found");
982
+
983
+ // Remove selection highlights
984
+ if(selectedBubble) selectedBubble.classList.remove('selected');
985
+ if(selectedPanel) selectedPanel.classList.remove('selected');
986
+ alert(`Exporting ${pgs.length} page(s)...`);
987
+
988
+ // --- 0% ERROR FIX ---
989
+ // 1. Lock specific pixel dimensions + 1px buffer to prevent word wrapping
990
+ const bubbles = document.querySelectorAll('.speech-bubble');
991
+ bubbles.forEach(b => {
992
+ const rect = b.getBoundingClientRect();
993
+ // Add slight buffer (1px) to width to handle sub-pixel rendering differences
994
+ // This prevents "just fitting" words from wrapping in the export
995
+ b.style.width = (rect.width + 1) + 'px';
996
+ b.style.height = rect.height + 'px';
997
+ b.style.display = 'flex';
998
+ b.style.alignItems = 'center';
999
+ b.style.justifyContent = 'center';
1000
+ });
1001
+
1002
+ for(let i = 0; i < pgs.length; i++) {
1003
+ try {
1004
+ const u = await htmlToImage.toPng(pgs[i], {
1005
+ pixelRatio: 2, // High quality
1006
+ style: { transform: 'none' }
1007
+ });
1008
+ const a = document.createElement('a');
1009
+ a.href = u;
1010
+ a.download = `Comic-Page-${i+1}.png`;
1011
+ a.click();
1012
+ } catch(err) {
1013
+ console.error(err);
1014
+ alert(`Failed to export page ${i+1}`);
1015
+ }
1016
+ }
1017
+ }
1018
+
1019
+ function goBackToUpload() { if(confirm('Go home? Unsaved changes will be lost.')) { document.getElementById('editor-container').style.display = 'none'; document.getElementById('upload-container').style.display = 'flex'; document.getElementById('loading-view').style.display = 'none'; } }
1020
  </script>
1021
+ </body> </html> '''
 
1022
 
 
 
 
1023
  @app.route('/')
1024
+ def index():
1025
+ return INDEX_HTML
1026
 
1027
  @app.route('/uploader', methods=['POST'])
1028
+ def upload():
1029
  sid = request.args.get('sid')
1030
+ if not sid: return jsonify({'success': False, 'message': 'Missing session ID'}), 400
1031
+ if 'file' not in request.files or not request.files['file'].filename:
1032
+ return jsonify({'success': False, 'message': 'No file selected'}), 400
1033
+
1034
+ # GET PAGE COUNT FROM FORM
1035
+ target_pages = request.form.get('target_pages', 3)
1036
+
1037
  f = request.files['file']
1038
+ gen = EnhancedComicGenerator(sid)
1039
+ gen.cleanup()
1040
+ f.save(gen.video_path)
1041
+ gen.write_status("Starting...", 5)
1042
+
1043
+ # Run in thread
1044
+ threading.Thread(target=gen.run, args=(target_pages,)).start()
1045
+ return jsonify({'success': True, 'message': 'Generation started.'})
1046
 
1047
  @app.route('/status')
1048
+ def get_status():
1049
+ sid = request.args.get('sid')
1050
+ path = os.path.join(BASE_USER_DIR, sid, 'output', 'status.json')
1051
+ if os.path.exists(path): return send_file(path)
1052
+ return jsonify({'progress': 0, 'message': "Waiting..."})
1053
+
1054
+ @app.route('/output/<path:filename>')
1055
+ def get_output(filename):
1056
+ sid = request.args.get('sid')
1057
+ return send_from_directory(os.path.join(BASE_USER_DIR, sid, 'output'), filename)
1058
+
1059
+ @app.route('/frames/<path:filename>')
1060
+ def get_frame(filename):
1061
+ sid = request.args.get('sid')
1062
+ return send_from_directory(os.path.join(BASE_USER_DIR, sid, 'frames'), filename)
1063
+
1064
+ @app.route('/regenerate_frame', methods=['POST'])
1065
+ def regen():
1066
+ sid = request.args.get('sid')
1067
+ d = request.get_json()
1068
+ gen = EnhancedComicGenerator(sid)
1069
+ return jsonify(regen_frame_gpu(gen.video_path, gen.frames_dir, gen.metadata_path, d['filename'], d['direction']))
1070
+
1071
+ @app.route('/goto_timestamp', methods=['POST'])
1072
+ def go_time():
1073
  sid = request.args.get('sid')
1074
+ d = request.get_json()
1075
+ gen = EnhancedComicGenerator(sid)
1076
+ return jsonify(get_frame_at_ts_gpu(gen.video_path, gen.frames_dir, gen.metadata_path, d['filename'], float(d['timestamp'])))
1077
 
1078
+ @app.route('/replace_panel', methods=['POST'])
1079
+ def rep_panel():
1080
+ sid = request.args.get('sid')
1081
+ if 'image' not in request.files: return jsonify({'success': False, 'error': 'No image'})
1082
+ f = request.files['image']
1083
+ frames_dir = os.path.join(BASE_USER_DIR, sid, 'frames')
1084
+ os.makedirs(frames_dir, exist_ok=True)
1085
+ fname = f"replaced_{int(time.time() * 1000)}.png"
1086
+ f.save(os.path.join(frames_dir, fname))
1087
+ return jsonify({'success': True, 'new_filename': fname})
1088
+
1089
+ @app.route('/save_comic', methods=['POST'])
1090
+ def save_comic():
1091
+ sid = request.args.get('sid')
1092
+ try:
1093
+ data = request.get_json()
1094
+ save_code = generate_save_code()
1095
+ save_dir = os.path.join(SAVED_COMICS_DIR, save_code)
1096
+ os.makedirs(save_dir, exist_ok=True)
1097
+
1098
+ user_frames_dir = os.path.join(BASE_USER_DIR, sid, 'frames')
1099
+ saved_frames_dir = os.path.join(save_dir, 'frames')
1100
+
1101
+ if os.path.exists(user_frames_dir):
1102
+ if os.path.exists(saved_frames_dir): shutil.rmtree(saved_frames_dir)
1103
+ shutil.copytree(user_frames_dir, saved_frames_dir)
1104
+
1105
+ save_data = {
1106
+ 'code': save_code,
1107
+ 'originalSid': sid,
1108
+ 'pages': data.get('pages', []),
1109
+ 'savedAt': data.get('savedAt', time.strftime('%Y-%m-%d %H:%M:%S'))
1110
+ }
1111
+ with open(os.path.join(save_dir, 'comic_state.json'), 'w') as f: json.dump(save_data, f, indent=2)
1112
+ return jsonify({'success': True, 'code': save_code})
1113
+ except Exception as e:
1114
+ traceback.print_exc()
1115
+ return jsonify({'success': False, 'message': str(e)})
1116
 
1117
+ @app.route('/load_comic/<code>')
1118
+ def load_comic(code):
1119
+ code = code.upper()
1120
+ save_dir = os.path.join(SAVED_COMICS_DIR, code)
1121
+ state_file = os.path.join(save_dir, 'comic_state.json')
1122
+
1123
+ if not os.path.exists(state_file): return jsonify({'success': False, 'message': 'Save code not found'})
1124
+
1125
+ try:
1126
+ with open(state_file, 'r') as f: save_data = json.load(f)
1127
+ original_sid = save_data.get('originalSid')
1128
+ saved_frames_dir = os.path.join(save_dir, 'frames')
1129
+ if original_sid and os.path.exists(saved_frames_dir):
1130
+ user_frames_dir = os.path.join(BASE_USER_DIR, original_sid, 'frames')
1131
+ os.makedirs(user_frames_dir, exist_ok=True)
1132
+ for fname in os.listdir(saved_frames_dir):
1133
+ src = os.path.join(saved_frames_dir, fname)
1134
+ dst = os.path.join(user_frames_dir, fname)
1135
+ if not os.path.exists(dst): shutil.copy2(src, dst)
1136
+ return jsonify({ 'success': True, 'pages': save_data.get('pages', []), 'originalSid': original_sid, 'savedAt': save_data.get('savedAt') })
1137
+ except Exception as e:
1138
+ traceback.print_exc()
1139
+ return jsonify({'success': False, 'message': str(e)})
1140
 
1141
  if __name__ == '__main__':
1142
+ try: gpu_warmup()
1143
+ except: pass
1144
  app.run(host='0.0.0.0', port=7860)