-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1262 lines (1012 loc) · 38.3 KB
/
app.py
File metadata and controls
1262 lines (1012 loc) · 38.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# ─────────────────────────────────────────────────────────────────────
# Copyright (c) 2025-2026 Thothica Private Limited, Delhi, India.
# All rights reserved. Proprietary and confidential.
# Unauthorized copying or distribution is strictly prohibited.
# ─────────────────────────────────────────────────────────────────────
"""
app.py - Flask web server for PDF Toolkit.
Run: python app.py
Then open http://127.0.0.1:5000 in your browser.
Thread safety: Flask runs with threaded=True. All fitz (PyMuPDF)
calls are serialised via editor.lock. Batch processing uses
subprocesses via _run_one.py (each with its own fitz instance).
"""
import fitz
import subprocess
import sys
import os
import json
import threading
import queue
import time
import gc
import webbrowser
from pathlib import Path
from collections import OrderedDict
from concurrent.futures import ThreadPoolExecutor, as_completed
from flask import (
Flask, render_template, request, jsonify,
Response, stream_with_context,
)
import license as lic
IS_FROZEN = getattr(sys, "frozen", False)
if IS_FROZEN:
BUNDLE_DIR = Path(sys.executable).parent
# PyInstaller puts data files in _internal/ (sys._MEIPASS)
_MEIPASS = Path(getattr(sys, "_MEIPASS", BUNDLE_DIR / "_internal"))
app = Flask(
__name__,
template_folder=str(_MEIPASS / "templates"),
static_folder=str(_MEIPASS / "static"),
)
HELPER = str(BUNDLE_DIR / "_run_one.exe")
SCRIPT_DIR = BUNDLE_DIR
else:
app = Flask(__name__)
SCRIPT_DIR = Path(__file__).parent
HELPER = str(SCRIPT_DIR / "_run_one.py")
app.config["TEMPLATES_AUTO_RELOAD"] = True
app.config["SEND_FILE_MAX_AGE_DEFAULT"] = 0
app.config["LICENSE_VALID"] = False
TIMEOUT = 300 # seconds per file
# ── Folder State ────────────────────────────────────────────────────
class FolderState:
def __init__(self):
self.lock = threading.Lock()
self.folder_path = None
self.files = [] # [{name, path, size, size_str}, ...]
self.processed = set() # filenames that have been saved/skipped
def load_folder(self, path):
with self.lock:
self.folder_path = path
self.processed = set()
self.files = []
p = Path(path)
for pdf in sorted(p.glob("*.pdf")):
sz = pdf.stat().st_size
self.files.append({
"name": pdf.name,
"path": str(pdf),
"size": sz,
"size_str": human_size(sz),
})
def remaining(self):
with self.lock:
return [f for f in self.files if f["name"] not in self.processed]
def mark_processed(self, name):
with self.lock:
self.processed.add(name)
def find_file(self, name):
with self.lock:
for f in self.files:
if f["name"] == name:
return f
return None
folder = FolderState()
# ── Batch Processing State ──────────────────────────────────────────
class BatchState:
def __init__(self):
self.running = False
self.cancelled = False
self.proc = None
self.log_queue = queue.Queue()
self.total = 0
self.current = 0
def reset(self):
self.running = False
self.cancelled = False
self.proc = None
self.total = 0
self.current = 0
# drain queue
while not self.log_queue.empty():
try:
self.log_queue.get_nowait()
except queue.Empty:
break
batch = BatchState()
# ── Page Editor State ────────────────────────────────────────────────
class EditorState:
def __init__(self):
self.lock = threading.Lock()
self.doc = None
self.path = None
self.modified = False
self.page_sizes = []
self.thumb_cache = OrderedDict()
self.cache_max = 200
self.generation = 0 # incremented on open/close/modify
def close(self):
if self.doc:
self.doc.close()
self.doc = None
self.path = None
self.modified = False
self.page_sizes = []
self.thumb_cache.clear()
self.generation += 1
fitz.TOOLS.store_shrink(100)
gc.collect()
def invalidate_cache(self):
self.thumb_cache.clear()
self.generation += 1
def get_thumb(self, page_idx, width=180):
key = (page_idx, width)
if key in self.thumb_cache:
self.thumb_cache.move_to_end(key)
return self.thumb_cache[key]
page = self.doc[page_idx]
zoom = width / page.rect.width
mat = fitz.Matrix(zoom, zoom)
pix = page.get_pixmap(matrix=mat, alpha=False)
img_bytes = pix.tobytes("jpeg", jpg_quality=65)
pix = None # release native pixmap memory immediately
self.thumb_cache[key] = img_bytes
if len(self.thumb_cache) > self.cache_max:
self.thumb_cache.popitem(last=False)
return img_bytes
editor = EditorState()
# ── Helpers ──────────────────────────────────────────────────────────
def human_size(nbytes):
for unit in ("B", "KB", "MB", "GB"):
if abs(nbytes) < 1024:
return f"{nbytes:.1f} {unit}"
nbytes /= 1024
return f"{nbytes:.1f} TB"
def _run_toc_bg(file_path, toc_out_dir, h1_only):
"""Background wrapper for _run_toc — logs result to console."""
try:
result, log = _run_toc(file_path, toc_out_dir, h1_only)
name = os.path.basename(file_path)
if result == "success":
print(f" TOC added: {name}")
else:
print(f" TOC {result}: {name}")
if log:
print(f" {log[:200]}")
except Exception as e:
print(f" TOC error for {os.path.basename(file_path)}: {e}")
def _run_toc(file_path, toc_out_dir, h1_only):
"""Run the TOC subprocess. Returns (toc_result, toc_log)."""
os.makedirs(toc_out_dir, exist_ok=True)
base = os.path.basename(file_path)
toc_dst = os.path.join(toc_out_dir, base)
if IS_FROZEN:
cmd = [HELPER, "toc", file_path, toc_dst]
else:
cmd = [sys.executable, "-u", HELPER, "toc", file_path, toc_dst]
if h1_only:
cmd.append("--h1-only")
env = os.environ.copy()
env["PYTHONIOENCODING"] = "utf-8"
try:
proc = subprocess.run(
cmd, capture_output=True, text=True,
timeout=TIMEOUT, env=env,
)
toc_result = "failed"
toc_log = []
for line in proc.stdout.splitlines():
if line.strip().startswith("__RESULT__:"):
toc_result = line.strip().split(":", 1)[1]
else:
toc_log.append(line)
if proc.stderr:
toc_log.append(proc.stderr)
return toc_result, "\n".join(toc_log).strip()
except Exception as e:
return "failed", str(e)
# ── License Gate ─────────────────────────────────────────────────────
LICENSE_EXEMPT_PREFIXES = ("/api/license/",)
@app.before_request
def license_gate():
"""Block all API routes if the app is not licensed.
Re-validates the license on every gated request. The actual
network call only happens every RECHECK_INTERVAL (5 min) inside
check_license(); the rest of the time it reads from cache.
"""
path = request.path
if path == "/" or path == "/static/logo.png" or any(path.startswith(p) for p in LICENSE_EXEMPT_PREFIXES):
return None
# Re-check license (phones home every 5 min, cache otherwise)
valid, msg, _ = lic.check_license()
app.config["LICENSE_VALID"] = valid
if not valid:
return jsonify(error="unlicensed", message=msg), 403
@app.route("/api/license/status")
def license_status():
"""Return current license state for the frontend."""
valid, message, needs_key = lic.check_license()
app.config["LICENSE_VALID"] = valid
return jsonify(valid=valid, message=message, needs_key=needs_key)
@app.route("/api/license/activate", methods=["POST"])
def license_activate():
"""Attempt to activate a license key."""
data = request.json or {}
key = data.get("key", "").strip()
if not key:
return jsonify(success=False, message="Please enter a license key.")
success, message = lic.activate_key(key)
if success:
app.config["LICENSE_VALID"] = True
return jsonify(success=success, message=message)
# ── Routes: Pages ───────────────────────────────────────────────────
@app.route("/")
def index():
valid, _, _ = lic.check_license()
app.config["LICENSE_VALID"] = valid
if valid:
return render_template("index.html")
return render_template("license.html")
# ── Routes: Browse ──────────────────────────────────────────────────
def _browse_tkinter_thread(mode, initial):
"""Run a tkinter file dialog in a dedicated thread.
Works in both frozen (PyInstaller) and development modes.
Tkinter must run in its own thread with its own mainloop.
"""
result = [None]
def _run():
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
root.withdraw()
root.attributes("-topmost", True)
if mode == "folder":
p = filedialog.askdirectory(
title="Select PDF Folder", initialdir=initial)
else:
p = filedialog.askopenfilename(
title="Open PDF",
filetypes=[("PDF files", "*.pdf")],
initialdir=initial)
result[0] = p or ""
root.destroy()
t = threading.Thread(target=_run)
t.start()
t.join(timeout=120)
return result[0] or ""
@app.route("/api/browse", methods=["POST"])
def browse():
data = request.json or {}
mode = data.get("mode", "folder")
initial = data.get("initial", str(SCRIPT_DIR))
if IS_FROZEN:
# Frozen: run tkinter in a thread (bundled by PyInstaller)
path = _browse_tkinter_thread(mode, initial)
else:
# Development: run tkinter file dialog in a subprocess to avoid
# "main thread is not in main loop" crashes.
script = (
"import tkinter as tk; from tkinter import filedialog; "
"root = tk.Tk(); root.withdraw(); root.attributes('-topmost', True); "
)
if mode == "folder":
script += (
f"p = filedialog.askdirectory(title='Select PDF Folder', "
f"initialdir=r'{initial}'); "
)
else:
script += (
f"p = filedialog.askopenfilename(title='Open PDF', "
f"filetypes=[('PDF files', '*.pdf')], initialdir=r'{initial}'); "
)
script += "print(p or ''); root.destroy()"
try:
result = subprocess.run(
[sys.executable, "-c", script],
capture_output=True, text=True, timeout=120,
)
path = result.stdout.strip()
except Exception:
path = ""
return jsonify(path=path or "")
# ── Routes: Folder Management ──────────────────────────────────────
@app.route("/api/folder/load", methods=["POST"])
def folder_load():
data = request.json or {}
path = data.get("path", "")
if not path or not os.path.isdir(path):
return jsonify(error="Not a valid directory"), 400
# Close any open editor document
with editor.lock:
editor.close()
folder.load_folder(path)
remaining = folder.remaining()
return jsonify(files=remaining, folder=path, count=len(remaining))
@app.route("/api/folder/select", methods=["POST"])
def folder_select():
data = request.json or {}
name = data.get("name", "")
if not name:
return jsonify(error="No filename specified"), 400
file_info = folder.find_file(name)
if not file_info:
return jsonify(error="File not found in folder"), 404
with editor.lock:
# Check for unsaved changes
if editor.doc and editor.modified:
return jsonify(
error="unsaved_changes",
current_file=os.path.basename(editor.path)
), 409
editor.close()
try:
editor.doc = fitz.open(file_info["path"])
except Exception as e:
return jsonify(error=f"Cannot open PDF: {e}"), 400
editor.path = file_info["path"]
editor.modified = False
editor.invalidate_cache()
page_count = len(editor.doc)
editor.page_sizes = []
for i in range(page_count):
r = editor.doc[i].rect
editor.page_sizes.append({"w": r.width, "h": r.height})
return jsonify(
page_count=page_count,
path=file_info["path"],
name=name,
page_sizes=editor.page_sizes,
)
@app.route("/api/folder/skip", methods=["POST"])
def folder_skip():
data = request.json or {}
name = data.get("name", "")
h1_only = data.get("h1_only", False)
if not name:
return jsonify(error="No filename specified"), 400
file_info = folder.find_file(name)
if not file_info:
return jsonify(error="File not found in folder"), 404
# Close editor if this file is currently open
with editor.lock:
if editor.path and os.path.basename(editor.path) == name:
editor.close()
folder.mark_processed(name)
remaining = folder.remaining()
# Run TOC in background thread (don't block the HTTP response)
toc_out_dir = os.path.join(folder.folder_path, "with_toc")
threading.Thread(
target=_run_toc_bg,
args=(file_info["path"], toc_out_dir, h1_only),
daemon=True,
).start()
return jsonify(
ok=True,
toc_result="pending",
remaining=len(remaining),
)
@app.route("/api/folder/save-and-finish", methods=["POST"])
def folder_save_and_finish():
data = request.json or {}
h1_only = data.get("h1_only", False)
with editor.lock:
if not editor.doc:
return jsonify(error="No document open"), 400
save_path = editor.path
name = os.path.basename(save_path)
try:
# Atomic save: write to .tmp then replace
tmp_path = save_path + ".tmp"
editor.doc.save(tmp_path, deflate=True, garbage=4)
editor.doc.close()
os.replace(tmp_path, save_path)
except Exception as e:
return jsonify(error=f"Save failed: {e}"), 500
# Fully close editor (don't reopen)
editor.doc = None
editor.path = None
editor.modified = False
editor.page_sizes = []
editor.thumb_cache.clear()
folder.mark_processed(name)
remaining = folder.remaining()
# Suggest next file
next_file = remaining[0]["name"] if remaining else None
# Run TOC in background thread (don't block the HTTP response)
base_dir = folder.folder_path or os.path.dirname(save_path)
toc_out_dir = os.path.join(base_dir, "with_toc")
threading.Thread(
target=_run_toc_bg,
args=(save_path, toc_out_dir, h1_only),
daemon=True,
).start()
return jsonify(
ok=True,
path=save_path,
toc_result="pending",
remaining=len(remaining),
next_file=next_file,
)
@app.route("/api/folder/skip-all", methods=["POST"])
def folder_skip_all():
"""Start batch-skipping all remaining files (add TOC to each)."""
if batch.running:
return jsonify(error="Batch already running"), 409
data = request.json or {}
h1_only = data.get("h1_only", False)
remaining = folder.remaining()
if not remaining:
return jsonify(error="No files remaining"), 400
# Close any open editor
with editor.lock:
editor.close()
batch.reset()
batch.running = True
batch.total = len(remaining)
t = threading.Thread(
target=_skip_all_worker,
args=(remaining, h1_only),
daemon=True,
)
t.start()
return jsonify(total=len(remaining))
def _skip_all_worker(files, h1_only):
total = len(files)
toc_out_dir = os.path.join(folder.folder_path, "with_toc")
os.makedirs(toc_out_dir, exist_ok=True)
env = os.environ.copy()
env["PYTHONIOENCODING"] = "utf-8"
success, skipped, crashed, failed = 0, 0, 0, 0
for idx, f in enumerate(files, 1):
if batch.cancelled:
batch.log_queue.put(("log", "\n--- Stopped by user ---\n"))
break
batch.current = idx
batch.log_queue.put((
"progress",
{"current": idx, "total": total,
"file": f["name"], "size": f["size_str"]},
))
dst = os.path.join(toc_out_dir, f["name"])
if IS_FROZEN:
cmd = [HELPER, "toc", f["path"], dst]
else:
cmd = [sys.executable, "-u", HELPER, "toc", f["path"], dst]
if h1_only:
cmd.append("--h1-only")
try:
batch.proc = subprocess.Popen(
cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
env=env, bufsize=0,
)
result = None
for raw in batch.proc.stdout:
line = raw.decode("utf-8", errors="replace")
if line.strip().startswith("__RESULT__:"):
result = line.strip().split(":", 1)[1]
else:
batch.log_queue.put(("log", line))
try:
batch.proc.wait(timeout=TIMEOUT)
except subprocess.TimeoutExpired:
batch.proc.kill()
batch.proc.wait()
batch.log_queue.put(("log", f" TIMEOUT after {TIMEOUT}s\n"))
crashed += 1
folder.mark_processed(f["name"])
continue
rc = batch.proc.returncode
if rc != 0:
batch.log_queue.put(("log", f" CRASHED (exit code {rc})\n"))
crashed += 1
elif result == "success":
success += 1
elif result in ("scanned", "skipped"):
skipped += 1
else:
failed += 1
except Exception as e:
batch.log_queue.put(("log", f" ERROR: {e}\n"))
failed += 1
finally:
batch.proc = None
# Mark processed regardless of outcome
folder.mark_processed(f["name"])
batch.log_queue.put(("processed", f["name"]))
batch.log_queue.put(("done", {
"success": success, "skipped": skipped,
"crashed": crashed, "failed": failed,
"output_dir": toc_out_dir,
}))
fitz.TOOLS.store_shrink(100)
gc.collect()
batch.running = False
# ── Routes: Batch Processing (DOCX only) ───────────────────────────
@app.route("/api/batch/start", methods=["POST"])
def batch_start():
if batch.running:
return jsonify(error="Batch already running"), 409
data = request.json
input_dir = Path(data.get("dir", folder.folder_path or ""))
mode = data.get("mode", "docx")
h1_only = data.get("h1_only", False)
if not input_dir.is_dir():
return jsonify(error="Not a valid directory"), 400
pdfs = sorted(input_dir.glob("*.pdf"))
if not pdfs:
return jsonify(error="No PDF files found"), 400
batch.reset()
batch.running = True
batch.total = len(pdfs)
out_dir = input_dir / ("with_toc" if mode == "toc" else "docx_output")
out_dir.mkdir(exist_ok=True)
t = threading.Thread(
target=_batch_worker,
args=(mode, input_dir, out_dir, pdfs, h1_only),
daemon=True,
)
t.start()
return jsonify(total=len(pdfs))
def _batch_worker(mode, input_dir, out_dir, pdfs, h1_only):
total = len(pdfs)
env = os.environ.copy()
env["PYTHONIOENCODING"] = "utf-8"
success, skipped, crashed, failed = 0, 0, 0, 0
for idx, pdf in enumerate(pdfs, 1):
if batch.cancelled:
batch.log_queue.put(("log", "\n--- Stopped by user ---\n"))
break
batch.current = idx
size = pdf.stat().st_size
batch.log_queue.put((
"progress",
{"current": idx, "total": total,
"file": pdf.name, "size": human_size(size)},
))
if mode == "toc":
dst = str(out_dir / pdf.name)
else:
dst = str(out_dir / (pdf.stem + ".docx"))
if IS_FROZEN:
cmd = [HELPER, mode, str(pdf), dst]
else:
cmd = [sys.executable, "-u", HELPER, mode, str(pdf), dst]
if mode == "toc" and h1_only:
cmd.append("--h1-only")
try:
batch.proc = subprocess.Popen(
cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
env=env, bufsize=0,
)
result = None
for raw in batch.proc.stdout:
line = raw.decode("utf-8", errors="replace")
if line.strip().startswith("__RESULT__:"):
result = line.strip().split(":", 1)[1]
else:
batch.log_queue.put(("log", line))
try:
batch.proc.wait(timeout=TIMEOUT)
except subprocess.TimeoutExpired:
batch.proc.kill()
batch.proc.wait()
batch.log_queue.put(("log", f" TIMEOUT after {TIMEOUT}s\n"))
crashed += 1
continue
rc = batch.proc.returncode
if rc != 0:
batch.log_queue.put(("log", f" CRASHED (exit code {rc})\n"))
crashed += 1
elif result == "success":
success += 1
elif result in ("scanned", "skipped"):
skipped += 1
else:
failed += 1
except Exception as e:
batch.log_queue.put(("log", f" ERROR: {e}\n"))
failed += 1
finally:
batch.proc = None
batch.log_queue.put(("done", {
"success": success, "skipped": skipped,
"crashed": crashed, "failed": failed,
"output_dir": str(out_dir),
}))
fitz.TOOLS.store_shrink(100)
gc.collect()
batch.running = False
@app.route("/api/batch/events")
def batch_events():
def generate():
while True:
try:
msg_type, data = batch.log_queue.get(timeout=1)
except queue.Empty:
yield ": keepalive\n\n"
if not batch.running:
yield "event: done\ndata: {}\n\n"
return
continue
payload = json.dumps(data) if isinstance(data, dict) else json.dumps(data)
yield f"event: {msg_type}\ndata: {payload}\n\n"
if msg_type == "done":
return
return Response(
stream_with_context(generate()),
mimetype="text/event-stream",
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
)
@app.route("/api/batch/stop", methods=["POST"])
def batch_stop():
batch.cancelled = True
if batch.proc and batch.proc.poll() is None:
batch.proc.terminate()
return jsonify(ok=True)
# ── Routes: Page Editor ─────────────────────────────────────────────
@app.route("/api/editor/thumb/<int:page>")
def editor_thumb(page):
with editor.lock:
if not editor.doc:
return "", 204 # doc closed — no content
if page < 0 or page >= len(editor.doc):
return "", 204 # page gone (deleted)
width = request.args.get("w", 180, type=int)
width = max(60, min(width, 600))
try:
img_bytes = editor.get_thumb(page, width)
except Exception:
return "", 204 # render failed — silently skip
return Response(img_bytes, mimetype="image/jpeg", headers={
"Cache-Control": "private, max-age=3600",
})
@app.route("/api/editor/preview/<int:page>")
def editor_preview(page):
with editor.lock:
if not editor.doc:
return jsonify(error="No document open"), 400
if page < 0 or page >= len(editor.doc):
return jsonify(error="Page out of range"), 400
dpi = request.args.get("dpi", 150, type=int)
dpi = max(72, min(dpi, 300))
try:
p = editor.doc[page]
zoom = dpi / 72
mat = fitz.Matrix(zoom, zoom)
pix = p.get_pixmap(matrix=mat, alpha=False)
img_bytes = pix.tobytes("jpeg", jpg_quality=75)
pix = None # release native pixmap memory immediately
except Exception:
return jsonify(error="Render failed"), 500
return Response(img_bytes, mimetype="image/jpeg")
@app.route("/api/editor/delete", methods=["POST"])
def editor_delete():
with editor.lock:
if not editor.doc:
return jsonify(error="No document open"), 400
pages = sorted(request.json.get("pages", []), reverse=True)
if not pages:
return jsonify(error="No pages specified"), 400
deleted = 0
for p in pages:
if 0 <= p < len(editor.doc):
editor.doc.delete_page(p)
deleted += 1
editor.modified = True
editor.invalidate_cache()
# Rebuild page_sizes
editor.page_sizes = []
for i in range(len(editor.doc)):
r = editor.doc[i].rect
editor.page_sizes.append({"w": r.width, "h": r.height})
return jsonify(page_count=len(editor.doc), deleted=deleted)
@app.route("/api/editor/save", methods=["POST"])
def editor_save():
"""Intermediate save — saves in-place, keeps doc open. No TOC."""
with editor.lock:
if not editor.doc:
return jsonify(error="No document open"), 400
save_path = editor.path
try:
tmp_path = save_path + ".tmp"
editor.doc.save(tmp_path, deflate=True, garbage=4)
editor.doc.close()
os.replace(tmp_path, save_path)
editor.doc = fitz.open(save_path)
editor.modified = False
editor.invalidate_cache()
except Exception as e:
return jsonify(error=f"Save failed: {e}"), 500
return jsonify(ok=True, path=save_path)
@app.route("/api/editor/redact", methods=["POST"])
def editor_redact():
with editor.lock:
if not editor.doc:
return jsonify(error="No document open"), 400
data = request.json or {}
rect = data.get("rect")
page_idx = data.get("page", 0)
scope = data.get("scope", "page")
if not rect:
return jsonify(error="No rect specified"), 400
r = fitz.Rect(rect["x0"], rect["y0"], rect["x1"], rect["y1"])
if scope == "all":
pages = range(len(editor.doc))
else:
pages = [page_idx]
affected = 0
for p in pages:
if 0 <= p < len(editor.doc):
page = editor.doc[p]
clipped = r & page.rect
if clipped.is_empty:
continue
page.add_redact_annot(clipped, fill=(1, 1, 1))
page.apply_redactions(images=2, graphics=1, text=0)
affected += 1
editor.modified = True
editor.invalidate_cache()
return jsonify(ok=True, affected_pages=affected,
page_count=len(editor.doc))
@app.route("/api/editor/page-numbers", methods=["POST"])
def editor_page_numbers():
with editor.lock:
if not editor.doc:
return jsonify(error="No document open"), 400
data = request.json or {}
point = data.get("point")
if not point:
return jsonify(error="No point specified"), 400
fontsize = data.get("fontsize", 10)
fontsize = max(4, min(fontsize, 72))
font = data.get("font", "helv")
if font not in ("helv", "tiro", "cour"):
font = "helv"
start = data.get("start", 1)
color = tuple(data.get("color", [0, 0, 0]))
px, py = float(point["x"]), float(point["y"])
for i in range(len(editor.doc)):
page = editor.doc[i]
num_text = str(start + i)
page.insert_text(
(px, py),
num_text,
fontsize=fontsize,
fontname=font,
color=color,
overlay=True,
)
editor.modified = True
editor.invalidate_cache()
return jsonify(ok=True, page_count=len(editor.doc))
@app.route("/api/folder/page-numbers-all", methods=["POST"])
def folder_page_numbers_all():
"""Add page numbers to ALL PDFs in the folder. Each book starts from 1."""
if batch.running:
return jsonify(error="Batch already running"), 409
data = request.json or {}
point = data.get("point")
if not point:
return jsonify(error="No point specified"), 400
fontsize = data.get("fontsize", 10)
fontsize = max(4, min(fontsize, 72))
font = data.get("font", "helv")
if font not in ("helv", "tiro", "cour"):
font = "helv"
color = tuple(data.get("color", [0, 0, 0]))
if not folder.folder_path:
return jsonify(error="No folder loaded"), 400
pdfs = sorted(Path(folder.folder_path).glob("*.pdf"))
if not pdfs:
return jsonify(error="No PDF files found"), 400
# Close any open editor to avoid file lock conflicts
with editor.lock:
editor.close()
batch.reset()
batch.running = True
batch.total = len(pdfs)