tester343 commited on
Commit
7e7f5c0
·
verified ·
1 Parent(s): 3eaaa39

Update app_enhanced.py

Browse files
Files changed (1) hide show
  1. app_enhanced.py +1163 -63
app_enhanced.py CHANGED
@@ -118,7 +118,6 @@ def generate_comic_gpu(video_path, user_dir, frames_dir, metadata_path, target_p
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
- # 5 Panels for the specific template requested
122
  panels_per_page = 5
123
  total_panels_needed = target_pages * panels_per_page
124
 
@@ -177,7 +176,7 @@ def generate_comic_gpu(video_path, user_dir, frames_dir, metadata_path, target_p
177
  elif '!' in dialogue and dialogue.isupper(): b_type = 'reaction'
178
  elif '?' in dialogue: b_type = 'speech'
179
 
180
- # Default placement; user will adjust in UI
181
  b = bubble(dialog=dialogue, bubble_offset_x=50, bubble_offset_y=50, type=b_type)
182
  bubbles_list.append(b)
183
 
@@ -340,20 +339,23 @@ INDEX_HTML = '''
340
  height: 710px;
341
  box-shadow: 0 4px 10px rgba(0,0,0,0.1);
342
  position: relative;
343
- /* Overflow visible so bubbles can pop out slightly if needed, but panels clip images */
344
  z-index: 1;
345
  }
346
 
347
- /* BUBBLES are direct children of comic-page now, so they float above everything */
348
  .speech-bubble {
349
  position: absolute; display: flex; justify-content: center; align-items: center;
350
- width: 150px; height: 80px; min-width: 50px; min-height: 30px; box-sizing: border-box;
351
- z-index: 200; /* High z-index to stay above panels */
 
 
 
 
352
  cursor: move; font-family: 'Comic Neue', cursive; font-weight: bold;
353
  font-size: 13px; text-align: center;
354
- overflow: visible;
355
  line-height: 1.2;
356
  --tail-pos: 50%;
 
357
  }
358
 
359
  .panel {
@@ -366,13 +368,12 @@ INDEX_HTML = '''
366
  }
367
  .panel.selected { filter: brightness(0.9) sepia(0.2); outline: 3px solid #2196F3; z-index: 15; }
368
 
369
- /* OBJECT FIT COVER FIX:
370
- Images fill their defined bounding box, maintaining aspect ratio.
371
- */
372
  .panel img {
373
  width: 100%;
374
  height: 100%;
375
  object-fit: cover;
 
376
  transition: transform 0.1s ease-out;
377
  transform-origin: center center;
378
  }
@@ -381,74 +382,37 @@ INDEX_HTML = '''
381
 
382
  /*
383
  CALCULATED COORDINATES WITH 10PX GUTTER
384
- Total W: 1000, Row Height: 350. Gutter Y: 10px (350-360).
385
  */
386
 
387
  /* --- TIER 1 (Y: 0 - 350) --- */
388
-
389
- /* Panel 0 (Top Left)
390
- Line: (635.2, 0) to (588.2, 350).
391
- Minus 5px for gutter.
392
- TR: 630.2, BR: 583.2.
393
- */
394
  .panel-0 {
395
  top: 0; left: 0; width: 631px; height: 350px;
396
  clip-path: polygon(0% 0%, 630.2px 0%, 583.2px 100%, 0% 100%);
397
  }
398
-
399
- /* Panel 1 (Top Right)
400
- Line: (635.2, 0) to (588.2, 350).
401
- Plus 5px for gutter.
402
- TL: 640.2, BL: 593.2.
403
- Bounding Box: Starts at X=593. Width = 1000-593 = 407.
404
- Poly Relative: TL(47.2, 0), BL(0.2, 350).
405
- */
406
  .panel-1 {
407
  top: 0; left: 593px; width: 407px; height: 350px;
408
  clip-path: polygon(47.2px 0%, 100% 0%, 100% 100%, 0.2px 100%);
409
  }
410
 
411
  /* --- TIER 2 (Y: 360 - 710) --- */
412
-
413
- /* Panel 2 (Bottom Left)
414
- Line Left: (293.2, 0) to (326.2, 350).
415
- Minus 5px.
416
- TR: 288.2, BR: 321.2.
417
- Box Height: 350px. Top: 360px.
418
- */
419
  .panel-2 {
420
  top: 360px; left: 0; width: 322px; height: 350px;
421
  clip-path: polygon(0% 0%, 288.2px 0%, 321.2px 100%, 0% 100%);
422
  }
423
-
424
- /* Panel 3 (Bottom Middle)
425
- Line Left (+5px): TL 298.2, BL 331.2.
426
- Line Right (-5px): (617.2,0)->(666.2,350). TR 612.2, BR 661.2.
427
- Box Start: 298px. Width: 662 - 298 = 364px.
428
- Poly Relative:
429
- TL: 0.2, BL: 33.2
430
- TR: 314.2, BR: 363.2
431
- */
432
  .panel-3 {
433
  top: 360px; left: 298px; width: 364px; height: 350px;
434
  clip-path: polygon(0.2px 0%, 314.2px 0%, 363.2px 100%, 33.2px 100%);
435
  }
436
-
437
- /* Panel 4 (Bottom Right)
438
- Line Right (+5px): TL 622.2, BL 671.2.
439
- Box Start: 622px. Width: 378px.
440
- Poly Relative: TL 0.2, BL 49.2.
441
- */
442
  .panel-4 {
443
  top: 360px; left: 622px; width: 378px; height: 350px;
444
  clip-path: polygon(0.2px 0%, 100% 0%, 100% 100%, 49.2px 100%);
445
  }
446
 
447
- /* ... Bubbles CSS continued ... */
448
-
449
  .bubble-text {
450
  padding: 0.5em;
451
- word-wrap: break-word;
 
 
452
  white-space: pre-wrap;
453
  position: relative;
454
  z-index: 5;
@@ -456,7 +420,6 @@ INDEX_HTML = '''
456
  user-select: none;
457
  width: 100%;
458
  height: 100%;
459
- overflow: hidden;
460
  display: flex;
461
  align-items: center;
462
  justify-content: center;
@@ -732,7 +695,6 @@ INDEX_HTML = '''
732
  }
733
 
734
  // UPDATED STATE RETRIEVAL
735
- // Bubbles are now children of comic-page, not panels.
736
  function getCurrentState() {
737
  const pages = [];
738
  document.querySelectorAll('.comic-page').forEach(p => {
@@ -896,7 +858,8 @@ INDEX_HTML = '''
896
 
897
  b.dataset.type = type;
898
  b.style.left = data.left; b.style.top = data.top;
899
- if(data.width) b.style.width = data.width; if(data.height) b.style.height = data.height;
 
900
  if(data.font) b.style.fontFamily = data.font;
901
  if(data.colors) { b.style.setProperty('--bubble-fill-color', data.colors.fill || '#4ECDC4'); b.style.setProperty('--bubble-text-color', data.colors.text || '#ffffff'); }
902
  if(data.tailPos) b.style.setProperty('--tail-pos', data.tailPos);
@@ -1041,16 +1004,1153 @@ INDEX_HTML = '''
1041
  if(selectedPanel) selectedPanel.classList.remove('selected');
1042
  alert(`Exporting ${pgs.length} page(s)...`);
1043
 
1044
- // --- 0% ERROR FIX ---
1045
- const bubbles = document.querySelectorAll('.speech-bubble');
1046
- bubbles.forEach(b => {
1047
- const rect = b.getBoundingClientRect();
1048
- b.style.width = (rect.width + 1) + 'px';
1049
- b.style.height = rect.height + 'px';
1050
- b.style.display = 'flex';
1051
- b.style.alignItems = 'center';
1052
- b.style.justifyContent = 'center';
1053
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1054
 
1055
  for(let i = 0; i < pgs.length; i++) {
1056
  try {
 
118
  raw_moments = [{'text': s.content, 'start': s.start.total_seconds(), 'end': s.end.total_seconds()} for s in valid_subs]
119
 
120
  if target_pages <= 0: target_pages = 1
 
121
  panels_per_page = 5
122
  total_panels_needed = target_pages * panels_per_page
123
 
 
176
  elif '!' in dialogue and dialogue.isupper(): b_type = 'reaction'
177
  elif '?' in dialogue: b_type = 'speech'
178
 
179
+ # Default offset
180
  b = bubble(dialog=dialogue, bubble_offset_x=50, bubble_offset_y=50, type=b_type)
181
  bubbles_list.append(b)
182
 
 
339
  height: 710px;
340
  box-shadow: 0 4px 10px rgba(0,0,0,0.1);
341
  position: relative;
 
342
  z-index: 1;
343
  }
344
 
345
+ /* SPEECH BUBBLES - SIBLINGS to panels (higher z-index) */
346
  .speech-bubble {
347
  position: absolute; display: flex; justify-content: center; align-items: center;
348
+ /* AUTO SIZING FIX: Min dims but grow with text */
349
+ width: auto; height: auto;
350
+ min-width: 80px; min-height: 50px;
351
+ max-width: 250px;
352
+ box-sizing: border-box;
353
+ z-index: 200;
354
  cursor: move; font-family: 'Comic Neue', cursive; font-weight: bold;
355
  font-size: 13px; text-align: center;
 
356
  line-height: 1.2;
357
  --tail-pos: 50%;
358
+ padding: 5px; /* Room for text */
359
  }
360
 
361
  .panel {
 
368
  }
369
  .panel.selected { filter: brightness(0.9) sepia(0.2); outline: 3px solid #2196F3; z-index: 15; }
370
 
371
+ /* OBJECT FIT FIX: Focus on Center Top (Faces) and Cover */
 
 
372
  .panel img {
373
  width: 100%;
374
  height: 100%;
375
  object-fit: cover;
376
+ object-position: center 20%; /* Prioritize upper center for faces */
377
  transition: transform 0.1s ease-out;
378
  transform-origin: center center;
379
  }
 
382
 
383
  /*
384
  CALCULATED COORDINATES WITH 10PX GUTTER
 
385
  */
386
 
387
  /* --- TIER 1 (Y: 0 - 350) --- */
 
 
 
 
 
 
388
  .panel-0 {
389
  top: 0; left: 0; width: 631px; height: 350px;
390
  clip-path: polygon(0% 0%, 630.2px 0%, 583.2px 100%, 0% 100%);
391
  }
 
 
 
 
 
 
 
 
392
  .panel-1 {
393
  top: 0; left: 593px; width: 407px; height: 350px;
394
  clip-path: polygon(47.2px 0%, 100% 0%, 100% 100%, 0.2px 100%);
395
  }
396
 
397
  /* --- TIER 2 (Y: 360 - 710) --- */
 
 
 
 
 
 
 
398
  .panel-2 {
399
  top: 360px; left: 0; width: 322px; height: 350px;
400
  clip-path: polygon(0% 0%, 288.2px 0%, 321.2px 100%, 0% 100%);
401
  }
 
 
 
 
 
 
 
 
 
402
  .panel-3 {
403
  top: 360px; left: 298px; width: 364px; height: 350px;
404
  clip-path: polygon(0.2px 0%, 314.2px 0%, 363.2px 100%, 33.2px 100%);
405
  }
 
 
 
 
 
 
406
  .panel-4 {
407
  top: 360px; left: 622px; width: 378px; height: 350px;
408
  clip-path: polygon(0.2px 0%, 100% 0%, 100% 100%, 49.2px 100%);
409
  }
410
 
 
 
411
  .bubble-text {
412
  padding: 0.5em;
413
+ /* TEXT OVERFLOW FIX */
414
+ overflow-wrap: break-word;
415
+ word-wrap: break-word;
416
  white-space: pre-wrap;
417
  position: relative;
418
  z-index: 5;
 
420
  user-select: none;
421
  width: 100%;
422
  height: 100%;
 
423
  display: flex;
424
  align-items: center;
425
  justify-content: center;
 
695
  }
696
 
697
  // UPDATED STATE RETRIEVAL
 
698
  function getCurrentState() {
699
  const pages = [];
700
  document.querySelectorAll('.comic-page').forEach(p => {
 
858
 
859
  b.dataset.type = type;
860
  b.style.left = data.left; b.style.top = data.top;
861
+ // Allow auto width/height if not explicitly set (or remove fixed dims if present)
862
+ // We set basic styles but let CSS handle content sizing
863
  if(data.font) b.style.fontFamily = data.font;
864
  if(data.colors) { b.style.setProperty('--bubble-fill-color', data.colors.fill || '#4ECDC4'); b.style.setProperty('--bubble-text-color', data.colors.text || '#ffffff'); }
865
  if(data.tailPos) b.style.setProperty('--tail-pos', data.tailPos);
 
1004
  if(selectedPanel) selectedPanel.classList.remove('selected');
1005
  alert(`Exporting ${pgs.length} page(s)...`);
1006
 
1007
+ for(let i = 0; i < pgs.length; i++) {
1008
+ try {
1009
+ const u = await htmlToImage.toPng(pgs[i], {
1010
+ pixelRatio: 2, // High quality
1011
+ style: { transform: 'none' }
1012
+ });
1013
+ const a = document.createElement('a');
1014
+ a.href = u;
1015
+ a.download = `Comic-Page-${i+1}.png`;
1016
+ a.click();
1017
+ } catch(err) {
1018
+ console.error(err);
1019
+ alert(`Failed to export page ${i+1}`);
1020
+ }
1021
+ }
1022
+ }
1023
+
1024
+ 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'; } }
1025
+ </script>
1026
+ </body> </html> '''
1027
+
1028
+ @app.route('/')
1029
+ def index():
1030
+ return INDEX_HTML
1031
+
1032
+ @app.route('/uploader', methods=['POST'])
1033
+ def upload():
1034
+ sid = request.args.get('sid')
1035
+ if not sid: return jsonify({'success': False, 'message': 'Missing session ID'}), 400
1036
+ if 'file' not in request.files or not request.files['file'].filename:
1037
+ return jsonify({'success': False, 'message': 'No file selected'}), 400
1038
+
1039
+ # GET PAGE COUNT FROM FORM
1040
+ target_pages = request.form.get('target_pages', 3)
1041
+
1042
+ f = request.files['file']
1043
+ gen = EnhancedComicGenerator(sid)
1044
+ gen.cleanup()
1045
+ f.save(gen.video_path)
1046
+ gen.write_status("Starting...", 5)
1047
+
1048
+ # Run in thread
1049
+ threading.Thread(target=gen.run, args=(target_pages,)).start()
1050
+ return jsonify({'success': True, 'message': 'Generation started.'})
1051
+
1052
+ @app.route('/status')
1053
+ def get_status():
1054
+ sid = request.args.get('sid')
1055
+ path = os.path.join(BASE_USER_DIR, sid, 'output', 'status.json')
1056
+ if os.path.exists(path): return send_file(path)
1057
+ return jsonify({'progress': 0, 'message': "Waiting..."})
1058
+
1059
+ @app.route('/output/<path:filename>')
1060
+ def get_output(filename):
1061
+ sid = request.args.get('sid')
1062
+ return send_from_directory(os.path.join(BASE_USER_DIR, sid, 'output'), filename)
1063
+
1064
+ @app.route('/frames/<path:filename>')
1065
+ def get_frame(filename):
1066
+ sid = request.args.get('sid')
1067
+ return send_from_directory(os.path.join(BASE_USER_DIR, sid, 'frames'), filename)
1068
+
1069
+ @app.route('/regenerate_frame', methods=['POST'])
1070
+ def regen():
1071
+ sid = request.args.get('sid')
1072
+ d = request.get_json()
1073
+ gen = EnhancedComicGenerator(sid)
1074
+ return jsonify(regen_frame_gpu(gen.video_path, gen.frames_dir, gen.metadata_path, d['filename'], d['direction']))
1075
+
1076
+ @app.route('/goto_timestamp', methods=['POST'])
1077
+ def go_time():
1078
+ sid = request.args.get('sid')
1079
+ d = request.get_json()
1080
+ gen = EnhancedComicGenerator(sid)
1081
+ return jsonify(get_frame_at_ts_gpu(gen.video_path, gen.frames_dir, gen.metadata_path, d['filename'], float(d['timestamp'])))
1082
+
1083
+ @app.route('/replace_panel', methods=['POST'])
1084
+ def rep_panel():
1085
+ sid = request.args.get('sid')
1086
+ if 'image' not in request.files: return jsonify({'success': False, 'error': 'No image'})
1087
+ f = request.files['image']
1088
+ frames_dir = os.path.join(BASE_USER_DIR, sid, 'frames')
1089
+ os.makedirs(frames_dir, exist_ok=True)
1090
+ fname = f"replaced_{int(time.time() * 1000)}.png"
1091
+ f.save(os.path.join(frames_dir, fname))
1092
+ return jsonify({'success': True, 'new_filename': fname})
1093
+
1094
+ @app.route('/save_comic', methods=['POST'])
1095
+ def save_comic():
1096
+ sid = request.args.get('sid')
1097
+ try:
1098
+ data = request.get_json()
1099
+ save_code = generate_save_code()
1100
+ save_dir = os.path.join(SAVED_COMICS_DIR, save_code)
1101
+ os.makedirs(save_dir, exist_ok=True)
1102
+
1103
+ user_frames_dir = os.path.join(BASE_USER_DIR, sid, 'frames')
1104
+ saved_frames_dir = os.path.join(save_dir, 'frames')
1105
+
1106
+ if os.path.exists(user_frames_dir):
1107
+ if os.path.exists(saved_frames_dir): shutil.rmtree(saved_frames_dir)
1108
+ shutil.copytree(user_frames_dir, saved_frames_dir)
1109
+
1110
+ save_data = {
1111
+ 'code': save_code,
1112
+ 'originalSid': sid,
1113
+ 'pages': data.get('pages', []),
1114
+ 'savedAt': data.get('savedAt', time.strftime('%Y-%m-%d %H:%M:%S'))
1115
+ }
1116
+ with open(os.path.join(save_dir, 'comic_state.json'), 'w') as f: json.dump(save_data, f, indent=2)
1117
+ return jsonify({'success': True, 'code': save_code})
1118
+ except Exception as e:
1119
+ traceback.print_exc()
1120
+ return jsonify({'success': False, 'message': str(e)})
1121
+
1122
+ @app.route('/load_comic/<code>')
1123
+ def load_comic(code):
1124
+ code = code.upper()
1125
+ save_dir = os.path.join(SAVED_COMICS_DIR, code)
1126
+ state_file = os.path.join(save_dir, 'comic_state.json')
1127
+
1128
+ if not os.path.exists(state_file): return jsonify({'success': False, 'message': 'Save code not found'})
1129
+
1130
+ try:
1131
+ with open(state_file, 'r') as f: save_data = json.load(f)
1132
+ original_sid = save_data.get('originalSid')
1133
+ saved_frames_dir = os.path.join(save_dir, 'frames')
1134
+ if original_sid and os.path.exists(saved_frames_dir):
1135
+ user_frames_dir = os.path.join(BASE_USER_DIR, original_sid, 'frames')
1136
+ os.makedirs(user_frames_dir, exist_ok=True)
1137
+ for fname in os.listdir(saved_frames_dir):
1138
+ src = os.path.join(saved_frames_dir, fname)
1139
+ dst = os.path.join(user_frames_dir, fname)
1140
+ if not os.path.exists(dst): shutil.copy2(src, dst)
1141
+ return jsonify({ 'success': True, 'pages': save_data.get('pages', []), 'originalSid': original_sid, 'savedAt': save_data.get('savedAt') })
1142
+ except Exception as e:
1143
+ traceback.print_exc()
1144
+ return jsonify({'success': False, 'message': str(e)})
1145
+
1146
+ if __name__ == '__main__':
1147
+ try: gpu_warmup()
1148
+ except: pass
1149
+ app.run(host='0.0.0.0', port=7860)import spaces # <--- CRITICAL: MUST BE THE FIRST IMPORT
1150
+ import os
1151
+ import time
1152
+ import threading
1153
+ import json
1154
+ import traceback
1155
+ import logging
1156
+ import string
1157
+ import random
1158
+ import shutil
1159
+ import cv2
1160
+ import math
1161
+ import numpy as np
1162
+ import srt
1163
+ from flask import Flask, jsonify, request, send_from_directory, send_file
1164
+
1165
+ # ======================================================
1166
+ # 🚀 ZEROGPU CONFIGURATION
1167
+ # ======================================================
1168
+ @spaces.GPU
1169
+ def gpu_warmup():
1170
+ import torch
1171
+ print(f"✅ ZeroGPU Warmup: CUDA Available: {torch.cuda.is_available()}")
1172
+ return True
1173
+
1174
+ # ======================================================
1175
+ # 💾 PERSISTENT STORAGE CONFIGURATION
1176
+ # ======================================================
1177
+ if os.path.exists('/data'):
1178
+ BASE_STORAGE_PATH = '/data'
1179
+ print("✅ Using Persistent Storage at /data")
1180
+ else:
1181
+ BASE_STORAGE_PATH = '.'
1182
+ print("⚠️ Using Ephemeral/Local Storage")
1183
+
1184
+ BASE_USER_DIR = os.path.join(BASE_STORAGE_PATH, "userdata")
1185
+ SAVED_COMICS_DIR = os.path.join(BASE_STORAGE_PATH, "saved_comics")
1186
+
1187
+ os.makedirs(BASE_USER_DIR, exist_ok=True)
1188
+ os.makedirs(SAVED_COMICS_DIR, exist_ok=True)
1189
+
1190
+ # ======================================================
1191
+ # 🧱 DATA CLASSES
1192
+ # ======================================================
1193
+ def bubble(dialog="", bubble_offset_x=50, bubble_offset_y=20, lip_x=-1, lip_y=-1, emotion='normal', type='speech'):
1194
+ return {
1195
+ 'dialog': dialog,
1196
+ 'bubble_offset_x': int(bubble_offset_x),
1197
+ 'bubble_offset_y': int(bubble_offset_y),
1198
+ 'lip_x': int(lip_x),
1199
+ 'lip_y': int(lip_y),
1200
+ 'emotion': emotion,
1201
+ 'type': type,
1202
+ 'tail_pos': '50%',
1203
+ 'classes': f'speech-bubble {type} tail-bottom'
1204
+ }
1205
+
1206
+ def panel(image=""):
1207
+ return {'image': image}
1208
+
1209
+ class Page:
1210
+ def __init__(self, panels, bubbles):
1211
+ self.panels = panels
1212
+ self.bubbles = bubbles
1213
+
1214
+ # ======================================================
1215
+ # 🔧 APP CONFIG
1216
+ # ======================================================
1217
+ logging.basicConfig(level=logging.INFO)
1218
+ logger = logging.getLogger(__name__)
1219
+
1220
+ app = Flask(__name__)
1221
+
1222
+ def generate_save_code(length=8):
1223
+ chars = string.ascii_uppercase + string.digits
1224
+ while True:
1225
+ code = ''.join(random.choices(chars, k=length))
1226
+ if not os.path.exists(os.path.join(SAVED_COMICS_DIR, code)):
1227
+ return code
1228
+
1229
+ # ======================================================
1230
+ # 🧠 GLOBAL GPU FUNCTIONS
1231
+ # ======================================================
1232
+ @spaces.GPU(duration=300)
1233
+ def generate_comic_gpu(video_path, user_dir, frames_dir, metadata_path, target_pages):
1234
+ print(f"🚀 GPU Task Started: {video_path} | Pages: {target_pages}")
1235
+
1236
+ import cv2
1237
+ import srt
1238
+ import numpy as np
1239
+ from backend.keyframes.keyframes import black_bar_crop
1240
+ from backend.simple_color_enhancer import SimpleColorEnhancer
1241
+ from backend.quality_color_enhancer import QualityColorEnhancer
1242
+ from backend.subtitles.subs_real import get_real_subtitles
1243
+ from backend.ai_bubble_placement import ai_bubble_placer
1244
+ from backend.ai_enhanced_core import face_detector
1245
+
1246
+ cap = cv2.VideoCapture(video_path)
1247
+ if not cap.isOpened(): raise Exception("Cannot open video")
1248
+ fps = cap.get(cv2.CAP_PROP_FPS) or 25
1249
+ total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
1250
+ duration = total_frames / fps
1251
+ cap.release()
1252
+
1253
+ user_srt = os.path.join(user_dir, 'subs.srt')
1254
+ try:
1255
+ get_real_subtitles(video_path)
1256
+ if os.path.exists('test1.srt'):
1257
+ shutil.move('test1.srt', user_srt)
1258
+ except:
1259
+ with open(user_srt, 'w') as f: f.write("1\n00:00:01,000 --> 00:00:04,000\n...\n")
1260
+
1261
+ with open(user_srt, 'r', encoding='utf-8') as f:
1262
+ try: all_subs = list(srt.parse(f.read()))
1263
+ except: all_subs = []
1264
+
1265
+ valid_subs = [s for s in all_subs if s.content.strip()]
1266
+ raw_moments = [{'text': s.content, 'start': s.start.total_seconds(), 'end': s.end.total_seconds()} for s in valid_subs]
1267
+
1268
+ if target_pages <= 0: target_pages = 1
1269
+ panels_per_page = 5
1270
+ total_panels_needed = target_pages * panels_per_page
1271
+
1272
+ selected_moments = []
1273
+ if not raw_moments:
1274
+ times = np.linspace(1, duration-1, total_panels_needed)
1275
+ for t in times: selected_moments.append({'text': '', 'start': t, 'end': t+1})
1276
+ elif len(raw_moments) <= total_panels_needed:
1277
+ selected_moments = raw_moments
1278
+ else:
1279
+ indices = np.linspace(0, len(raw_moments) - 1, total_panels_needed, dtype=int)
1280
+ selected_moments = [raw_moments[i] for i in indices]
1281
+
1282
+ frame_metadata = {}
1283
+ cap = cv2.VideoCapture(video_path)
1284
+ count = 0
1285
+ frame_files_ordered = []
1286
+
1287
+ for i, moment in enumerate(selected_moments):
1288
+ mid = (moment['start'] + moment['end']) / 2
1289
+ if mid > duration: mid = duration - 1
1290
+ cap.set(cv2.CAP_PROP_POS_FRAMES, int(mid * fps))
1291
+ ret, frame = cap.read()
1292
+ if ret:
1293
+ fname = f"frame_{count:04d}.png"
1294
+ p = os.path.join(frames_dir, fname)
1295
+ cv2.imwrite(p, frame)
1296
+ os.sync()
1297
+ frame_metadata[fname] = {'dialogue': moment['text'], 'time': mid}
1298
+ frame_files_ordered.append(fname)
1299
+ count += 1
1300
+ cap.release()
1301
+
1302
+ with open(metadata_path, 'w') as f: json.dump(frame_metadata, f, indent=2)
1303
+
1304
+ try: black_bar_crop()
1305
+ except: pass
1306
+
1307
+ se = SimpleColorEnhancer()
1308
+ qe = QualityColorEnhancer()
1309
+
1310
+ for f in frame_files_ordered:
1311
+ p = os.path.join(frames_dir, f)
1312
+ try: se.enhance_single(p, p)
1313
+ except: pass
1314
+ try: qe.enhance_single(p, p)
1315
+ except: pass
1316
+
1317
+ bubbles_list = []
1318
+ for f in frame_files_ordered:
1319
+ p = os.path.join(frames_dir, f)
1320
+ dialogue = frame_metadata.get(f, {}).get('dialogue', '')
1321
+
1322
+ b_type = 'speech'
1323
+ if '(' in dialogue and ')' in dialogue: b_type = 'narration'
1324
+ elif '!' in dialogue and dialogue.isupper(): b_type = 'reaction'
1325
+ elif '?' in dialogue: b_type = 'speech'
1326
+
1327
+ # Default offset
1328
+ b = bubble(dialog=dialogue, bubble_offset_x=50, bubble_offset_y=50, type=b_type)
1329
+ bubbles_list.append(b)
1330
+
1331
+ pages = []
1332
+ for i in range(target_pages):
1333
+ start_idx = i * panels_per_page
1334
+ end_idx = start_idx + panels_per_page
1335
+ p_frames = frame_files_ordered[start_idx:end_idx]
1336
+ p_bubbles = bubbles_list[start_idx:end_idx]
1337
+ if p_frames:
1338
+ pg_panels = [panel(image=f) for f in p_frames]
1339
+ pages.append(Page(panels=pg_panels, bubbles=p_bubbles))
1340
+
1341
+ result = []
1342
+ for pg in pages:
1343
+ p_data = [p if isinstance(p, dict) else p.__dict__ for p in pg.panels]
1344
+ b_data = [b if isinstance(b, dict) else b.__dict__ for b in pg.bubbles]
1345
+ result.append({'panels': p_data, 'bubbles': b_data})
1346
+
1347
+ return result
1348
+
1349
+ @spaces.GPU
1350
+ def regen_frame_gpu(video_path, frames_dir, metadata_path, fname, direction):
1351
+ import cv2
1352
+ import json
1353
+ from backend.simple_color_enhancer import SimpleColorEnhancer
1354
+
1355
+ if not os.path.exists(metadata_path): return {"success": False, "message": "No metadata"}
1356
+ with open(metadata_path, 'r') as f: meta = json.load(f)
1357
+ if fname not in meta: return {"success": False, "message": "Frame not found"}
1358
+
1359
+ t = meta[fname]['time'] if isinstance(meta[fname], dict) else meta[fname]
1360
+ cap = cv2.VideoCapture(video_path)
1361
+ fps = cap.get(cv2.CAP_PROP_FPS) or 25
1362
+ offset = (1.0/fps) * (1 if direction == 'forward' else -1)
1363
+ new_t = max(0, t + offset)
1364
+
1365
+ cap.set(cv2.CAP_PROP_POS_MSEC, new_t * 1000)
1366
+ ret, frame = cap.read()
1367
+ cap.release()
1368
+
1369
+ if ret:
1370
+ p = os.path.join(frames_dir, fname)
1371
+ cv2.imwrite(p, frame)
1372
+ os.sync()
1373
+ try: SimpleColorEnhancer().enhance_single(p, p)
1374
+ except: pass
1375
+
1376
+ if isinstance(meta[fname], dict): meta[fname]['time'] = new_t
1377
+ else: meta[fname] = new_t
1378
+ with open(metadata_path, 'w') as f: json.dump(meta, f, indent=2)
1379
+ return {"success": True, "message": f"Adjusted to {new_t:.2f}s"}
1380
+ return {"success": False, "message": "End of video"}
1381
+
1382
+ @spaces.GPU
1383
+ def get_frame_at_ts_gpu(video_path, frames_dir, metadata_path, fname, ts):
1384
+ import cv2
1385
+ import json
1386
+ from backend.simple_color_enhancer import SimpleColorEnhancer
1387
+
1388
+ cap = cv2.VideoCapture(video_path)
1389
+ cap.set(cv2.CAP_PROP_POS_MSEC, float(ts) * 1000)
1390
+ ret, frame = cap.read()
1391
+ cap.release()
1392
+
1393
+ if ret:
1394
+ p = os.path.join(frames_dir, fname)
1395
+ cv2.imwrite(p, frame)
1396
+ os.sync()
1397
+ try: SimpleColorEnhancer().enhance_single(p, p)
1398
+ except: pass
1399
+
1400
+ if os.path.exists(metadata_path):
1401
+ with open(metadata_path, 'r') as f: meta = json.load(f)
1402
+ if fname in meta:
1403
+ if isinstance(meta[fname], dict): meta[fname]['time'] = float(ts)
1404
+ else: meta[fname] = float(ts)
1405
+ with open(metadata_path, 'w') as f: json.dump(meta, f, indent=2)
1406
+ return {"success": True, "message": f"Jumped to {ts}s"}
1407
+ return {"success": False, "message": "Invalid timestamp"}
1408
+
1409
+ # ======================================================
1410
+ # 💻 BACKEND CLASS
1411
+ # ======================================================
1412
+ class EnhancedComicGenerator:
1413
+ def __init__(self, sid):
1414
+ self.sid = sid
1415
+ self.user_dir = os.path.join(BASE_USER_DIR, sid)
1416
+ self.video_path = os.path.join(self.user_dir, 'uploaded.mp4')
1417
+ self.frames_dir = os.path.join(self.user_dir, 'frames')
1418
+ self.output_dir = os.path.join(self.user_dir, 'output')
1419
+ os.makedirs(self.frames_dir, exist_ok=True)
1420
+ os.makedirs(self.output_dir, exist_ok=True)
1421
+ self.metadata_path = os.path.join(self.frames_dir, 'frame_metadata.json')
1422
+
1423
+ def cleanup(self):
1424
+ if os.path.exists(self.frames_dir): shutil.rmtree(self.frames_dir)
1425
+ if os.path.exists(self.output_dir): shutil.rmtree(self.output_dir)
1426
+ os.makedirs(self.frames_dir, exist_ok=True)
1427
+ os.makedirs(self.output_dir, exist_ok=True)
1428
+
1429
+ def run(self, target_pages):
1430
+ try:
1431
+ self.write_status("Waiting for GPU...", 5)
1432
+ data = generate_comic_gpu(self.video_path, self.user_dir, self.frames_dir, self.metadata_path, int(target_pages))
1433
+ with open(os.path.join(self.output_dir, 'pages.json'), 'w') as f:
1434
+ json.dump(data, f, indent=2)
1435
+ self.write_status("Complete!", 100)
1436
+ except Exception as e:
1437
+ traceback.print_exc()
1438
+ self.write_status(f"Error: {str(e)}", -1)
1439
+
1440
+ def write_status(self, msg, prog):
1441
+ with open(os.path.join(self.output_dir, 'status.json'), 'w') as f:
1442
+ json.dump({'message': msg, 'progress': prog}, f)
1443
+
1444
+ # ======================================================
1445
+ # 🌐 ROUTES & FULL UI
1446
+ # ======================================================
1447
+ INDEX_HTML = '''
1448
+ <!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; }
1449
+
1450
+ #upload-container { display: flex; flex-direction:column; justify-content: center; align-items: center; min-height: 100vh; width: 100%; padding: 20px; }
1451
+ .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; }
1452
+
1453
+ #editor-container { display: none; padding: 20px; width: 100%; box-sizing: border-box; padding-bottom: 100px; }
1454
+
1455
+ h1 { color: #2c3e50; margin-bottom: 20px; font-weight: 600; }
1456
+ .file-input { display: none; }
1457
+ .file-label { display: block; padding: 15px; background: #2c3e50; color: white; border-radius: 8px; cursor: pointer; font-weight: bold; margin-bottom: 10px; transition:0.2s; }
1458
+ .file-label:hover { background: #34495e; }
1459
+
1460
+ .page-input-group { margin: 20px 0; text-align: left; }
1461
+ .page-input-group label { font-weight: bold; font-size: 14px; display: block; margin-bottom: 5px; color: #333; }
1462
+ .page-input-group input { width: 100%; padding: 12px; border: 2px solid #ddd; border-radius: 8px; font-size: 16px; box-sizing: border-box; }
1463
+
1464
+ .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; }
1465
+ .submit-btn:hover { background: #d35400; }
1466
+ .restore-btn { margin-top: 10px; background: #27ae60; color: white; padding: 12px; width: 100%; border: none; border-radius: 8px; cursor: pointer; font-weight: bold; }
1467
+
1468
+ .load-section { margin-top: 30px; padding-top: 20px; border-top: 2px solid #eee; }
1469
+ .load-input-group { display: flex; gap: 10px; margin-top: 10px; }
1470
+ .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; }
1471
+ .load-input-group button { padding: 12px 20px; background: #3498db; color: white; border: none; border-radius: 8px; cursor: pointer; font-weight: bold; }
1472
+
1473
+ .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; }
1474
+ @keyframes ball { 0%{background-position:0 50%} 100%{background-position:100px 50%} }
1475
+
1476
+ /* ========================================= */
1477
+ /* 🎨 POLYGON TEMPLATE LAYOUT CSS (FIXED) */
1478
+ /* ========================================= */
1479
+
1480
+ .comic-wrapper { max-width: 1050px; margin: 0 auto; }
1481
+ .page-wrapper { margin: 30px auto; display: flex; flex-direction: column; align-items: center; }
1482
+ .page-title { text-align: center; color: #333; margin-bottom: 10px; font-size: 18px; font-weight: bold; }
1483
+
1484
+ .comic-page {
1485
+ background: white;
1486
+ width: 1000px;
1487
+ height: 710px;
1488
+ box-shadow: 0 4px 10px rgba(0,0,0,0.1);
1489
+ position: relative;
1490
+ z-index: 1;
1491
+ }
1492
+
1493
+ /* SPEECH BUBBLES - SIBLINGS to panels (higher z-index) */
1494
+ .speech-bubble {
1495
+ position: absolute; display: flex; justify-content: center; align-items: center;
1496
+ /* AUTO SIZING FIX: Min dims but grow with text */
1497
+ width: auto; height: auto;
1498
+ min-width: 80px; min-height: 50px;
1499
+ max-width: 250px;
1500
+ box-sizing: border-box;
1501
+ z-index: 200;
1502
+ cursor: move; font-family: 'Comic Neue', cursive; font-weight: bold;
1503
+ font-size: 13px; text-align: center;
1504
+ line-height: 1.2;
1505
+ --tail-pos: 50%;
1506
+ padding: 5px; /* Room for text */
1507
+ }
1508
+
1509
+ .panel {
1510
+ position: absolute;
1511
+ background: #eee;
1512
+ cursor: pointer;
1513
+ overflow: hidden;
1514
+ z-index: 10;
1515
+ border: none;
1516
+ }
1517
+ .panel.selected { filter: brightness(0.9) sepia(0.2); outline: 3px solid #2196F3; z-index: 15; }
1518
+
1519
+ /* OBJECT FIT FIX: Focus on Center Top (Faces) and Cover */
1520
+ .panel img {
1521
+ width: 100%;
1522
+ height: 100%;
1523
+ object-fit: cover;
1524
+ object-position: center 20%; /* Prioritize upper center for faces */
1525
+ transition: transform 0.1s ease-out;
1526
+ transform-origin: center center;
1527
+ }
1528
+ .panel img.pannable { cursor: grab; }
1529
+ .panel img.panning { cursor: grabbing; }
1530
+
1531
+ /*
1532
+ CALCULATED COORDINATES WITH 10PX GUTTER
1533
+ */
1534
+
1535
+ /* --- TIER 1 (Y: 0 - 350) --- */
1536
+ .panel-0 {
1537
+ top: 0; left: 0; width: 631px; height: 350px;
1538
+ clip-path: polygon(0% 0%, 630.2px 0%, 583.2px 100%, 0% 100%);
1539
+ }
1540
+ .panel-1 {
1541
+ top: 0; left: 593px; width: 407px; height: 350px;
1542
+ clip-path: polygon(47.2px 0%, 100% 0%, 100% 100%, 0.2px 100%);
1543
+ }
1544
+
1545
+ /* --- TIER 2 (Y: 360 - 710) --- */
1546
+ .panel-2 {
1547
+ top: 360px; left: 0; width: 322px; height: 350px;
1548
+ clip-path: polygon(0% 0%, 288.2px 0%, 321.2px 100%, 0% 100%);
1549
+ }
1550
+ .panel-3 {
1551
+ top: 360px; left: 298px; width: 364px; height: 350px;
1552
+ clip-path: polygon(0.2px 0%, 314.2px 0%, 363.2px 100%, 33.2px 100%);
1553
+ }
1554
+ .panel-4 {
1555
+ top: 360px; left: 622px; width: 378px; height: 350px;
1556
+ clip-path: polygon(0.2px 0%, 100% 0%, 100% 100%, 49.2px 100%);
1557
+ }
1558
+
1559
+ .bubble-text {
1560
+ padding: 0.5em;
1561
+ /* TEXT OVERFLOW FIX */
1562
+ overflow-wrap: break-word;
1563
+ word-wrap: break-word;
1564
+ white-space: pre-wrap;
1565
+ position: relative;
1566
+ z-index: 5;
1567
+ pointer-events: none;
1568
+ user-select: none;
1569
+ width: 100%;
1570
+ height: 100%;
1571
+ display: flex;
1572
+ align-items: center;
1573
+ justify-content: center;
1574
+ border-radius: inherit;
1575
+ }
1576
+
1577
+ .speech-bubble.selected { outline: 2px dashed #4CAF50; z-index: 201; }
1578
+ .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; }
1579
+
1580
+ .speech-bubble.speech {
1581
+ --b: 3em; --h: 1.8em; --t: 0.6; --p: var(--tail-pos, 50%); --r: 1.2em;
1582
+ background: var(--bubble-fill-color, #4ECDC4);
1583
+ color: var(--bubble-text-color, #fff);
1584
+ padding: 0;
1585
+ 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);
1586
+ }
1587
+ .speech-bubble.speech:before {
1588
+ content: ""; position: absolute; width: var(--b); height: var(--h);
1589
+ background: inherit; border-bottom-left-radius: 100%; pointer-events: none; z-index: 1;
1590
+ -webkit-mask: radial-gradient(calc(var(--t)*100%) 105% at 100% 0,#0000 99%,#000 101%);
1591
+ mask: radial-gradient(calc(var(--t)*100%) 105% at 100% 0,#0000 99%,#000 101%);
1592
+ }
1593
+
1594
+ .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))); }
1595
+ .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); }
1596
+ .speech-bubble.speech.tail-left { border-radius: var(--r); }
1597
+ .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; }
1598
+ .speech-bubble.speech.tail-right { border-radius: var(--r); }
1599
+ .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; }
1600
+
1601
+ .speech-bubble.thought { background: white; border: 2px dashed #555; color: #333; border-radius: 50%; }
1602
+ .speech-bubble.thought::before { display:none; }
1603
+ .thought-dot { position: absolute; background-color: white; border: 2px solid #555; border-radius: 50%; z-index: -1; }
1604
+ .thought-dot-1 { width: 20px; height: 20px; }
1605
+ .thought-dot-2 { width: 12px; height: 12px; }
1606
+
1607
+ .speech-bubble.thought.pos-bl .thought-dot-1 { left: 20px; bottom: -20px; }
1608
+ .speech-bubble.thought.pos-bl .thought-dot-2 { left: 10px; bottom: -32px; }
1609
+ .speech-bubble.thought.pos-br .thought-dot-1 { right: 20px; bottom: -20px; }
1610
+ .speech-bubble.thought.pos-br .thought-dot-2 { right: 10px; bottom: -32px; }
1611
+ .speech-bubble.thought.pos-tr .thought-dot-1 { right: 20px; top: -20px; }
1612
+ .speech-bubble.thought.pos-tr .thought-dot-2 { right: 10px; top: -32px; }
1613
+ .speech-bubble.thought.pos-tl .thought-dot-1 { left: 20px; top: -20px; }
1614
+ .speech-bubble.thought.pos-tl .thought-dot-2 { left: 10px; top: -32px; }
1615
+
1616
+ .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%); }
1617
+ .speech-bubble.narration { background: #FAFAFA; border: 2px solid #BDBDBD; color: #424242; border-radius: 3px; }
1618
+
1619
+ .resize-handle { position: absolute; width: 10px; height: 10px; background: #2196F3; border: 1px solid white; border-radius: 50%; display: none; z-index: 11; }
1620
+ .speech-bubble.selected .resize-handle { display: block; }
1621
+ .resize-handle.se { bottom: -5px; right: -5px; cursor: se-resize; }
1622
+ .resize-handle.sw { bottom: -5px; left: -5px; cursor: sw-resize; }
1623
+ .resize-handle.ne { top: -5px; right: -5px; cursor: ne-resize; }
1624
+ .resize-handle.nw { top: -5px; left: -5px; cursor: nw-resize; }
1625
+
1626
+ /* CONTROLS */
1627
+ .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; }
1628
+ .edit-controls h4 { margin: 0 0 10px 0; color: #4ECDC4; text-align: center; }
1629
+ .control-group { margin-top: 10px; border-top: 1px solid #555; padding-top: 10px; }
1630
+ .control-group label { font-size: 11px; font-weight: bold; display: block; margin-bottom: 3px; }
1631
+ 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; }
1632
+ .button-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 5px; }
1633
+ .color-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 5px; }
1634
+ .slider-container { display: flex; align-items: center; gap: 5px; margin-top: 5px; }
1635
+ .slider-container label { min-width: 40px; font-size: 11px; }
1636
+ .action-btn { background: #4CAF50; color: white; }
1637
+ .reset-btn { background: #e74c3c; color: white; }
1638
+ .secondary-btn { background: #f39c12; color: white; }
1639
+ .export-btn { background: #2196F3; color: white; }
1640
+ .save-btn { background: #9b59b6; color: white; }
1641
+ .undo-btn { background: #7f8c8d; color: white; margin-bottom: 5px; }
1642
+
1643
+ /* MODAL */
1644
+ .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; }
1645
+ .modal-content { background: white; padding: 30px; border-radius: 12px; max-width: 400px; width: 90%; text-align: center; }
1646
+ .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; }
1647
+ .modal-content button { background: #3498db; color: white; border: none; padding: 12px 30px; border-radius: 8px; cursor: pointer; font-weight: bold; margin: 5px; }
1648
+ </style>
1649
+ </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>
1650
+ <div class="page-input-group">
1651
+ <label>📚 Total Comic Pages:</label>
1652
+ <input type="number" id="page-count" value="3" min="1" max="15" placeholder="e.g. 3 (Video will be divided evenly)">
1653
+ <small style="color:#666; font-size:11px; display:block; margin-top:5px;">System calculates 5 panels per page (Polygon Layout).</small>
1654
+ </div>
1655
+
1656
+ <button class="submit-btn" onclick="upload()">🚀 Generate Comic</button>
1657
+ <button id="restore-draft-btn" class="restore-btn" style="display:none; margin-top:15px;" onclick="restoreDraft()">📂 Restore Unsaved Draft</button>
1658
+
1659
+ <div class="load-section">
1660
+ <h3>📥 Load Saved Comic</h3>
1661
+ <div class="load-input-group">
1662
+ <input type="text" id="load-code-input" placeholder="SAVE CODE" maxlength="8" style="text-transform:uppercase;">
1663
+ <button onclick="loadSavedComic()">Load</button>
1664
+ </div>
1665
+ </div>
1666
+ <div class="loading-view" id="loading-view" style="display:none; margin-top:20px;">
1667
+ <div class="loader" style="margin:0 auto;"></div>
1668
+ <p id="status-text" style="margin-top:10px;">Starting...</p>
1669
+ </div>
1670
+ </div>
1671
+ </div>
1672
+ <div id="editor-container">
1673
+ <div class="comic-wrapper" id="comic-container"></div>
1674
+ <input type="file" id="image-uploader" style="display: none;" accept="image/*">
1675
+ <div class="edit-controls">
1676
+ <h4>✏️ Interactive Editor</h4>
1677
+
1678
+ <button onclick="undoLastAction()" class="undo-btn">↩️ Undo</button>
1679
+
1680
+ <div class="control-group">
1681
+ <label>💾 Save & Load:</label>
1682
+ <button onclick="saveComic()" class="save-btn">💾 Save Comic</button>
1683
+ <div id="current-save-code" style="display:none; margin-top:5px; text-align:center;">
1684
+ <span id="display-save-code" style="font-weight:bold; background:#eee; padding:2px 5px; border-radius:3px;"></span>
1685
+ <button onclick="copyCode()" style="padding:2px; width:auto; font-size:10px;">Copy</button>
1686
+ </div>
1687
+ </div>
1688
+
1689
+ <div class="control-group">
1690
+ <label>💬 Bubble Styling:</label>
1691
+ <select id="bubble-type-select" onchange="changeBubbleType(this.value)" disabled>
1692
+ <option value="speech">Speech</option>
1693
+ <option value="thought">Thought</option>
1694
+ <option value="reaction">Reaction (Shout)</option>
1695
+ <option value="narration">Narration (Box)</option>
1696
+ </select>
1697
+ <select id="font-select" onchange="changeFont(this.value)" disabled>
1698
+ <option value="'Comic Neue', cursive">Comic Neue</option>
1699
+ <option value="'Bangers', cursive">Bangers</option>
1700
+ <option value="'Gloria Hallelujah', cursive">Gloria</option>
1701
+ <option value="'Lato', sans-serif">Lato</option>
1702
+ </select>
1703
+ <div class="color-grid">
1704
+ <div><label>Text</label><input type="color" id="bubble-text-color" value="#ffffff" disabled></div>
1705
+ <div><label>Fill</label><input type="color" id="bubble-fill-color" value="#4ECDC4" disabled></div>
1706
+ </div>
1707
+ <div class="button-grid">
1708
+ <button onclick="addBubble()" class="action-btn">Add</button>
1709
+ <button onclick="deleteBubble()" class="reset-btn">Delete</button>
1710
+ </div>
1711
+ </div>
1712
+
1713
+ <div class="control-group" id="tail-controls" style="display:none;">
1714
+ <label>📐 Tail Adjustment:</label>
1715
+ <button onclick="rotateTail()" class="secondary-btn">🔄 Rotate Side</button>
1716
+ <div class="slider-container">
1717
+ <label>Pos:</label>
1718
+ <input type="range" id="tail-slider" min="10" max="90" value="50" oninput="slideTail(this.value)">
1719
+ </div>
1720
+ </div>
1721
+
1722
+ <div class="control-group">
1723
+ <label>🖼️ Panel Tools:</label>
1724
+ <button onclick="replacePanelImage()" class="action-btn">🖼️ Replace Image</button>
1725
+ <div class="button-grid">
1726
+ <button onclick="adjustFrame('backward')" class="secondary-btn" id="prev-btn">⬅️ Prev</button>
1727
+ <button onclick="adjustFrame('forward')" class="action-btn" id="next-btn">Next ➡️</button>
1728
+ </div>
1729
+ <div class="timestamp-controls">
1730
+ <input type="text" id="timestamp-input" placeholder="mm:ss or secs">
1731
+ <button onclick="gotoTimestamp()" class="action-btn" id="go-btn">Go</button>
1732
+ </div>
1733
+ </div>
1734
+
1735
+ <div class="control-group">
1736
+ <label>🔍 Zoom & Pan:</label>
1737
+ <div class="button-grid">
1738
+ <button onclick="resetPanelTransform()" class="secondary-btn">Reset</button>
1739
+ <input type="range" id="zoom-slider" min="100" max="300" value="100" step="5" disabled oninput="handleZoom(this)">
1740
+ </div>
1741
+ </div>
1742
+
1743
+ <div class="control-group">
1744
+ <button onclick="exportComic()" class="export-btn">📥 Export as PNG</button>
1745
+ <button onclick="goBackToUpload()" class="reset-btn" style="margin-top:10px;">🏠 Home</button>
1746
+ </div>
1747
+ </div>
1748
+ </div>
1749
+ <div class="modal-overlay" id="save-modal">
1750
+ <div class="modal-content">
1751
+ <h2>✅ Comic Saved!</h2>
1752
+ <div class="code" id="modal-save-code">XXXXXXXX</div>
1753
+ <button onclick="copyModalCode()">📋 Copy Code</button>
1754
+ <button class="close-btn" onclick="closeModal()">Close</button>
1755
+ </div>
1756
+ </div>
1757
+ <script>
1758
+ 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);}); }
1759
+ let sid = localStorage.getItem('comic_sid') || genUUID();
1760
+ localStorage.setItem('comic_sid', sid);
1761
+
1762
+ let currentSaveCode = null;
1763
+ let isProcessing = false;
1764
+ let interval, selectedBubble = null, selectedPanel = null;
1765
+ let isDragging = false, isResizing = false, isPanning = false;
1766
+ let startX, startY, initX, initY, panStartX, panStartY, panStartTx, panStartTy;
1767
+ let resizeHandle, originalWidth, originalHeight, originalMouseX, originalMouseY;
1768
+ let currentlyEditing = null;
1769
+
1770
+ // UNDO SYSTEM
1771
+ let historyStack = [];
1772
+ let historyIndex = -1;
1773
+ function addToHistory() {
1774
+ if (historyIndex < historyStack.length - 1) {
1775
+ historyStack = historyStack.slice(0, historyIndex + 1);
1776
+ }
1777
+ const state = JSON.stringify(getCurrentState());
1778
+ if (historyStack.length > 0 && historyStack[historyStack.length - 1] === state) return;
1779
+
1780
+ historyStack.push(state);
1781
+ historyIndex++;
1782
+
1783
+ if (historyStack.length > 30) {
1784
+ historyStack.shift();
1785
+ historyIndex--;
1786
+ }
1787
+ }
1788
+ function undoLastAction() {
1789
+ if (historyIndex > 0) {
1790
+ historyIndex--;
1791
+ const previousState = JSON.parse(historyStack[historyIndex]);
1792
+ renderFromState(previousState);
1793
+ saveDraft(false);
1794
+ }
1795
+ }
1796
+
1797
+ if(localStorage.getItem('comic_draft_'+sid)) document.getElementById('restore-draft-btn').style.display = 'block';
1798
+
1799
+ function showSaveModal(code) { document.getElementById('modal-save-code').textContent = code; document.getElementById('save-modal').style.display = 'flex'; }
1800
+ function closeModal() { document.getElementById('save-modal').style.display = 'none'; }
1801
+ function copyModalCode() { navigator.clipboard.writeText(document.getElementById('modal-save-code').textContent).then(() => alert('Code copied!')); }
1802
+ function copyCode() { if(currentSaveCode) navigator.clipboard.writeText(currentSaveCode).then(() => alert('Code copied!')); }
1803
+
1804
+ function setProcessing(busy) {
1805
+ isProcessing = busy;
1806
+ const btns = ['prev-btn', 'next-btn', 'go-btn'];
1807
+ btns.forEach(id => {
1808
+ const el = document.getElementById(id);
1809
+ if(el) { el.disabled = busy; el.style.opacity = busy ? '0.5' : '1'; el.innerText = busy ? '⏳' : el.getAttribute('data-txt') || el.innerText; }
1810
+ });
1811
+ }
1812
+ async function saveComic() {
1813
+ const state = getCurrentState();
1814
+ if(!state || state.length === 0) { alert('No comic to save!'); return; }
1815
+ try {
1816
+ const r = await fetch(`/save_comic?sid=${sid}`, { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({ pages: state, savedAt: new Date().toISOString() }) });
1817
+ const d = await r.json();
1818
+ 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); }
1819
+ else { alert('Failed to save: ' + d.message); }
1820
+ } catch(e) { console.error(e); alert('Error saving comic'); }
1821
+ }
1822
+
1823
+ async function loadSavedComic() {
1824
+ const code = document.getElementById('load-code-input').value.trim().toUpperCase();
1825
+ if(!code || code.length < 4) { alert('Invalid code'); return; }
1826
+ try {
1827
+ const r = await fetch(`/load_comic/${code}`);
1828
+ const d = await r.json();
1829
+ 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); }
1830
+ else { alert('Load failed: ' + d.message); }
1831
+ } catch(e) { console.error(e); alert('Error loading comic.'); }
1832
+ }
1833
+
1834
+ function restoreDraft() {
1835
+ try {
1836
+ const state = JSON.parse(localStorage.getItem('comic_draft_'+sid));
1837
+ if(state.saveCode) { currentSaveCode = state.saveCode; document.getElementById('display-save-code').textContent = state.saveCode; document.getElementById('current-save-code').style.display = 'block'; }
1838
+ renderFromState(state.pages || state);
1839
+ document.getElementById('upload-container').style.display = 'none';
1840
+ document.getElementById('editor-container').style.display = 'block';
1841
+ addToHistory();
1842
+ } catch(e) { console.error(e); alert("Failed to restore."); }
1843
+ }
1844
+
1845
+ // UPDATED STATE RETRIEVAL
1846
+ function getCurrentState() {
1847
+ const pages = [];
1848
+ document.querySelectorAll('.comic-page').forEach(p => {
1849
+ const panels = [];
1850
+ const bubbles = []; // Page-level bubbles
1851
+
1852
+ p.querySelectorAll('.panel').forEach(pan => {
1853
+ const img = pan.querySelector('img');
1854
+ panels.push({
1855
+ src: img.src,
1856
+ zoom: img.dataset.zoom, tx: img.dataset.translateX, ty: img.dataset.translateY,
1857
+ bubbles: [] // Legacy structure kept empty
1858
+ });
1859
+ });
1860
+
1861
+ p.querySelectorAll('.speech-bubble').forEach(b => {
1862
+ const textEl = b.querySelector('.bubble-text');
1863
+ bubbles.push({
1864
+ text: textEl ? textEl.textContent : '',
1865
+ left: b.style.left, top: b.style.top, width: b.style.width, height: b.style.height,
1866
+ classes: b.className.replace(' selected', ''),
1867
+ type: b.dataset.type, font: b.style.fontFamily,
1868
+ tailPos: b.style.getPropertyValue('--tail-pos'),
1869
+ colors: { fill: b.style.getPropertyValue('--bubble-fill-color'), text: b.style.getPropertyValue('--bubble-text-color') }
1870
+ });
1871
+ });
1872
+
1873
+ pages.push({ panels: panels, pageBubbles: bubbles });
1874
+ });
1875
+ return pages;
1876
+ }
1877
+
1878
+ function saveDraft(recordHistory = true) {
1879
+ if(recordHistory) addToHistory();
1880
+ localStorage.setItem('comic_draft_'+sid, JSON.stringify({ pages: getCurrentState(), saveCode: currentSaveCode, savedAt: new Date().toISOString() }));
1881
+ }
1882
+
1883
+ function renderFromState(pagesData) {
1884
+ const con = document.getElementById('comic-container'); con.innerHTML = '';
1885
+ pagesData.forEach((page, pageIdx) => {
1886
+ const pageWrapper = document.createElement('div'); pageWrapper.className = 'page-wrapper';
1887
+ const pageTitle = document.createElement('h2'); pageTitle.className = 'page-title'; pageTitle.textContent = `Page ${pageIdx + 1}`;
1888
+ pageWrapper.appendChild(pageTitle);
1889
+
1890
+ const div = document.createElement('div');
1891
+ div.className = 'comic-page';
1892
+
1893
+ // 1. Render Panels
1894
+ page.panels.forEach((pan, idx) => {
1895
+ const pDiv = document.createElement('div');
1896
+ const posClass = `panel-${idx % 5}`;
1897
+ pDiv.className = `panel ${posClass}`;
1898
+
1899
+ pDiv.onclick = (e) => { e.stopPropagation(); selectPanel(pDiv); };
1900
+ const img = document.createElement('img');
1901
+ img.src = pan.src.includes('?') ? pan.src : pan.src + `?sid=${sid}`;
1902
+ img.dataset.zoom = pan.zoom || 100; img.dataset.translateX = pan.tx || 0; img.dataset.translateY = pan.ty || 0;
1903
+ updateImageTransform(img);
1904
+ img.onmousedown = (e) => startPan(e, img);
1905
+ pDiv.appendChild(img);
1906
+
1907
+ // Legacy support for old saves
1908
+ (pan.bubbles || []).forEach(bData => {
1909
+ const b = createBubbleHTML(bData);
1910
+ div.appendChild(b);
1911
+ });
1912
+
1913
+ div.appendChild(pDiv);
1914
+ });
1915
+
1916
+ // 2. Render Page-Level Bubbles
1917
+ if(page.pageBubbles) {
1918
+ page.pageBubbles.forEach(bData => {
1919
+ div.appendChild(createBubbleHTML(bData));
1920
+ });
1921
+ }
1922
+
1923
+ // Bind click to deselect
1924
+ div.onclick = (e) => {
1925
+ if(e.target === div) {
1926
+ if(selectedBubble) selectedBubble.classList.remove('selected'); selectedBubble = null;
1927
+ if(selectedPanel) selectedPanel.classList.remove('selected'); selectedPanel = null;
1928
+ }
1929
+ }
1930
+
1931
+ pageWrapper.appendChild(div);
1932
+ con.appendChild(pageWrapper);
1933
+ });
1934
+ selectedBubble = null;
1935
+ selectedPanel = null;
1936
+ document.getElementById('bubble-type-select').disabled = true;
1937
+ document.getElementById('font-select').disabled = true;
1938
+ }
1939
+
1940
+ async function upload() {
1941
+ const f = document.getElementById('file-upload').files[0];
1942
+ const pCount = document.getElementById('page-count').value;
1943
+ if(!f) return alert("Select a video");
1944
+ sid = genUUID(); localStorage.setItem('comic_sid', sid); currentSaveCode = null;
1945
+ document.querySelector('.upload-box').style.display='none';
1946
+ document.getElementById('loading-view').style.display='flex';
1947
+ const fd = new FormData(); fd.append('file', f); fd.append('target_pages', pCount);
1948
+ const r = await fetch(`/uploader?sid=${sid}`, {method:'POST', body:fd});
1949
+ if(r.ok) interval = setInterval(checkStatus, 2000);
1950
+ else { alert("Upload failed"); location.reload(); }
1951
+ }
1952
+
1953
+ async function checkStatus() {
1954
+ try {
1955
+ const r = await fetch(`/status?sid=${sid}`); const d = await r.json();
1956
+ document.getElementById('status-text').innerText = d.message;
1957
+ if(d.progress >= 100) { clearInterval(interval); document.getElementById('upload-container').style.display='none'; document.getElementById('editor-container').style.display='block'; loadNewComic(); }
1958
+ else if (d.progress < 0) { clearInterval(interval); document.getElementById('status-text').textContent = "Error: " + d.message; document.querySelector('.loader').style.display = 'none'; }
1959
+ } catch(e) {}
1960
+ }
1961
+
1962
+ function loadNewComic() {
1963
+ fetch(`/output/pages.json?sid=${sid}`).then(r=>r.json()).then(data => {
1964
+ // Convert Backend Data (Bubbles in Panels) to Frontend Data (Page Bubbles)
1965
+ const cleanData = data.map((p, pi) => {
1966
+ const panels = [];
1967
+ const pageBubbles = [];
1968
+
1969
+ // Panel Geometry for Default Bubble Placement
1970
+ const panelCenters = [
1971
+ {x: 315, y: 175}, // 0
1972
+ {x: 790, y: 175}, // 1
1973
+ {x: 160, y: 535}, // 2
1974
+ {x: 480, y: 535}, // 3
1975
+ {x: 800, y: 535} // 4
1976
+ ];
1977
+
1978
+ p.panels.forEach((pan, j) => {
1979
+ panels.push({
1980
+ src: `/frames/${pan.image}?sid=${sid}`,
1981
+ bubbles: []
1982
+ });
1983
+
1984
+ if(p.bubbles && p.bubbles[j] && p.bubbles[j].dialog) {
1985
+ const center = panelCenters[j % 5] || {x:500, y:350};
1986
+ pageBubbles.push({
1987
+ text: p.bubbles[j].dialog,
1988
+ left: (center.x - 75) + 'px',
1989
+ top: (center.y - 40) + 'px',
1990
+ type: (p.bubbles[j].type || 'speech'),
1991
+ classes: `speech-bubble ${p.bubbles[j].type || 'speech'} tail-bottom`
1992
+ });
1993
+ }
1994
+ });
1995
+ return { panels: panels, pageBubbles: pageBubbles };
1996
+ });
1997
+ renderFromState(cleanData); saveDraft(true);
1998
+ });
1999
+ }
2000
+
2001
+ function createBubbleHTML(data) {
2002
+ const b = document.createElement('div');
2003
+ const type = data.type || 'speech';
2004
+ b.className = data.classes || `speech-bubble ${type} tail-bottom`;
2005
+ if (type === 'thought' && !b.className.includes('pos-')) b.className += ' pos-bl';
2006
+
2007
+ b.dataset.type = type;
2008
+ b.style.left = data.left; b.style.top = data.top;
2009
+ // Allow auto width/height if not explicitly set (or remove fixed dims if present)
2010
+ // We set basic styles but let CSS handle content sizing
2011
+ if(data.font) b.style.fontFamily = data.font;
2012
+ if(data.colors) { b.style.setProperty('--bubble-fill-color', data.colors.fill || '#4ECDC4'); b.style.setProperty('--bubble-text-color', data.colors.text || '#ffffff'); }
2013
+ if(data.tailPos) b.style.setProperty('--tail-pos', data.tailPos);
2014
+
2015
+ const textSpan = document.createElement('span'); textSpan.className = 'bubble-text'; textSpan.textContent = data.text || ''; b.appendChild(textSpan);
2016
+
2017
+ 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); } }
2018
+
2019
+ ['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); });
2020
+
2021
+ b.onmousedown = (e) => {
2022
+ if(e.target.classList.contains('resize-handle')) return;
2023
+ e.stopPropagation(); selectBubble(b); isDragging = true; startX = e.clientX; startY = e.clientY; initX = b.offsetLeft; initY = b.offsetTop;
2024
+ };
2025
+ b.onclick = (e) => { e.stopPropagation(); };
2026
+ b.ondblclick = (e) => { e.stopPropagation(); editBubbleText(b); };
2027
+ return b;
2028
+ }
2029
+
2030
+ function editBubbleText(bubble) {
2031
+ if (currentlyEditing) return; currentlyEditing = bubble;
2032
+ const textSpan = bubble.querySelector('.bubble-text'); const textarea = document.createElement('textarea');
2033
+ textarea.value = textSpan.textContent; bubble.appendChild(textarea); textSpan.style.display = 'none'; textarea.focus();
2034
+ const finishEditing = () => {
2035
+ textSpan.textContent = textarea.value; textarea.remove(); textSpan.style.display = ''; currentlyEditing = null;
2036
+ saveDraft(true);
2037
+ };
2038
+ textarea.addEventListener('blur', finishEditing, { once: true });
2039
+ textarea.addEventListener('keydown', e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); textarea.blur(); } });
2040
+ }
2041
+
2042
+ document.addEventListener('mousemove', (e) => {
2043
+ if(isDragging && selectedBubble) { selectedBubble.style.left = (initX + e.clientX - startX) + 'px'; selectedBubble.style.top = (initY + e.clientY - startY) + 'px'; }
2044
+ if(isResizing && selectedBubble) { resizeBubble(e); }
2045
+ if(isPanning && selectedPanel) { panImage(e); }
2046
+ });
2047
+
2048
+ document.addEventListener('mouseup', () => {
2049
+ if(isDragging || isResizing || isPanning) {
2050
+ saveDraft(true);
2051
+ }
2052
+ isDragging = false; isResizing = false; isPanning = false;
2053
+ });
2054
+
2055
+ 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; }
2056
+ 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'; }
2057
+
2058
+ function selectBubble(el) {
2059
+ if(selectedBubble) selectedBubble.classList.remove('selected');
2060
+ if(selectedPanel) { selectedPanel.classList.remove('selected'); selectedPanel = null; }
2061
+ selectedBubble = el; el.classList.add('selected');
2062
+ document.getElementById('bubble-type-select').disabled = false;
2063
+ document.getElementById('font-select').disabled = false;
2064
+ document.getElementById('bubble-text-color').disabled = false;
2065
+ document.getElementById('bubble-fill-color').disabled = false;
2066
+ document.getElementById('tail-controls').style.display = 'block';
2067
+ document.getElementById('bubble-type-select').value = el.dataset.type || 'speech';
2068
+ }
2069
+
2070
+ function selectPanel(el) {
2071
+ if(selectedPanel) selectedPanel.classList.remove('selected');
2072
+ if(selectedBubble) { selectedBubble.classList.remove('selected'); selectedBubble = null; }
2073
+ selectedPanel = el; el.classList.add('selected');
2074
+ document.getElementById('zoom-slider').disabled = false;
2075
+ const img = el.querySelector('img');
2076
+ document.getElementById('zoom-slider').value = img.dataset.zoom || 100;
2077
+ document.getElementById('bubble-type-select').disabled = true;
2078
+ document.getElementById('font-select').disabled = true;
2079
+ document.getElementById('tail-controls').style.display = 'none';
2080
+ }
2081
+
2082
+ function addBubble() {
2083
+ if(!selectedPanel) return alert("Select a panel to define which page to add to.");
2084
+ const pageDiv = selectedPanel.parentElement;
2085
+ const b = createBubbleHTML({ text: "Text", left: "50px", top: "50px", type: 'speech', classes: "speech-bubble speech tail-bottom" });
2086
+ pageDiv.appendChild(b); selectBubble(b); saveDraft(true);
2087
+ }
2088
+
2089
+ function deleteBubble() {
2090
+ if(!selectedBubble) return alert("Select a bubble");
2091
+ selectedBubble.remove(); selectedBubble=null; saveDraft(true);
2092
+ }
2093
+
2094
+ function changeBubbleType(type) {
2095
+ if(!selectedBubble) return;
2096
+ selectedBubble.dataset.type = type;
2097
+ selectedBubble.className = 'speech-bubble ' + type + ' selected';
2098
+
2099
+ if(type === 'thought') selectedBubble.classList.add('pos-bl');
2100
+ else selectedBubble.classList.add('tail-bottom');
2101
+
2102
+ selectedBubble.querySelectorAll('.thought-dot').forEach(d=>d.remove());
2103
+ 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); } }
2104
+ saveDraft(true);
2105
+ }
2106
+
2107
+ function changeFont(font) { if(!selectedBubble) return; selectedBubble.style.fontFamily = font; saveDraft(true); }
2108
+
2109
+ function rotateTail() {
2110
+ if(!selectedBubble) return;
2111
+ const type = selectedBubble.dataset.type;
2112
+
2113
+ if(type === 'speech') {
2114
+ const positions = ['tail-bottom', 'tail-right', 'tail-top', 'tail-left'];
2115
+ let current = 0;
2116
+ positions.forEach((pos, i) => { if(selectedBubble.classList.contains(pos)) current = i; });
2117
+ selectedBubble.classList.remove(positions[current]);
2118
+ selectedBubble.classList.add(positions[(current + 1) % 4]);
2119
+ }
2120
+ else if (type === 'thought') {
2121
+ const positions = ['pos-bl', 'pos-br', 'pos-tr', 'pos-tl'];
2122
+ let current = 0;
2123
+ positions.forEach((pos, i) => { if(selectedBubble.classList.contains(pos)) current = i; });
2124
+ selectedBubble.classList.remove(positions[current]);
2125
+ selectedBubble.classList.add(positions[(current + 1) % 4]);
2126
+ }
2127
+ saveDraft(true);
2128
+ }
2129
+
2130
+ function slideTail(v) { if(selectedBubble) { selectedBubble.style.setProperty('--tail-pos', v+'%'); saveDraft(true); } }
2131
+
2132
+ document.getElementById('bubble-text-color').addEventListener('change', (e) => { if(selectedBubble) { selectedBubble.style.setProperty('--bubble-text-color', e.target.value); saveDraft(true); } });
2133
+ document.getElementById('bubble-fill-color').addEventListener('change', (e) => { if(selectedBubble) { selectedBubble.style.setProperty('--bubble-fill-color', e.target.value); saveDraft(true); } });
2134
+
2135
+ function handleZoom(el) { if(!selectedPanel) return; const img = selectedPanel.querySelector('img'); img.dataset.zoom = el.value; updateImageTransform(img); }
2136
+ document.getElementById('zoom-slider').addEventListener('change', () => saveDraft(true));
2137
+ 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'); }
2138
+ 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); }
2139
+ 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); }
2140
+ 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); }
2141
+
2142
+ 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(); }
2143
+ 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); }
2144
+ 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); }
2145
+
2146
+ async function exportComic() {
2147
+ const pgs = document.querySelectorAll('.comic-page');
2148
+ if(pgs.length === 0) return alert("No pages found");
2149
+
2150
+ // Remove selection highlights
2151
+ if(selectedBubble) selectedBubble.classList.remove('selected');
2152
+ if(selectedPanel) selectedPanel.classList.remove('selected');
2153
+ alert(`Exporting ${pgs.length} page(s)...`);
2154
 
2155
  for(let i = 0; i < pgs.length; i++) {
2156
  try {