File size: 52,672 Bytes
675828a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7007e56
675828a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7007e56
 
 
675828a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d98ef41
 
 
 
 
675828a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7007e56
675828a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7007e56
675828a
 
 
 
 
 
 
 
 
 
 
 
 
 
7007e56
675828a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7007e56
675828a
 
7007e56
675828a
 
 
 
 
 
 
 
7007e56
 
675828a
 
 
 
7007e56
675828a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7007e56
 
675828a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7007e56
675828a
7007e56
675828a
7007e56
675828a
7007e56
675828a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7007e56
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
722e2a8
 
7007e56
 
 
 
 
 
 
 
722e2a8
7007e56
722e2a8
7007e56
 
 
 
 
 
722e2a8
7007e56
 
 
722e2a8
7007e56
 
722e2a8
7007e56
 
 
 
 
 
 
 
722e2a8
7007e56
 
 
 
 
 
 
 
722e2a8
 
 
7007e56
722e2a8
7007e56
 
 
 
 
722e2a8
 
675828a
722e2a8
7007e56
675828a
7007e56
 
 
 
722e2a8
7007e56
722e2a8
 
 
7007e56
 
 
722e2a8
 
7007e56
 
 
 
 
 
 
722e2a8
 
 
 
 
 
 
 
 
7007e56
 
675828a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7007e56
675828a
 
 
 
 
 
7007e56
675828a
 
 
 
 
 
 
 
 
7007e56
675828a
 
7007e56
675828a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7007e56
675828a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7007e56
675828a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7007e56
675828a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7007e56
675828a
 
7007e56
675828a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7007e56
675828a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7007e56
675828a
 
 
 
 
 
7007e56
 
675828a
 
 
 
 
 
 
 
 
 
 
 
7007e56
675828a
 
 
 
 
 
 
 
 
 
 
 
 
7007e56
675828a
 
 
 
 
 
 
 
 
 
 
7007e56
675828a
 
 
 
 
7007e56
675828a
 
7007e56
675828a
 
 
 
 
 
 
 
 
 
7007e56
675828a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7007e56
675828a
7007e56
675828a
 
 
 
7007e56
675828a
7007e56
675828a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7007e56
 
 
 
 
 
 
 
 
 
 
 
675828a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7007e56
 
 
 
 
 
 
 
 
 
 
 
 
 
675828a
 
7007e56
 
 
675828a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7007e56
675828a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7007e56
 
 
 
 
 
 
 
 
675828a
 
 
 
 
 
 
 
 
 
7007e56
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
from fastapi import FastAPI, BackgroundTasks
from fastapi.responses import HTMLResponse, JSONResponse, Response
from fastapi.staticfiles import StaticFiles
import pathlib, os, uvicorn, base64, json
from typing import Dict, List, Any
import asyncio
import logging
import threading
import concurrent.futures

# 로깅 설정
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

BASE = pathlib.Path(__file__).parent
app = FastAPI()
app.mount("/static", StaticFiles(directory=BASE), name="static")

# PDF 디렉토리 설정
PDF_DIR = BASE / "pdf"
if not PDF_DIR.exists():
    PDF_DIR.mkdir(parents=True)

# 캐시 디렉토리 설정
CACHE_DIR = BASE / "cache"
if not CACHE_DIR.exists():
    CACHE_DIR.mkdir(parents=True)

# 전역 캐시 객체
pdf_cache: Dict[str, Dict[str, Any]] = {}
# 캐싱 락
cache_locks = {}

# PDF 파일 목록 가져오기
def get_pdf_files():
    pdf_files = []
    if PDF_DIR.exists():
        pdf_files = [f for f in PDF_DIR.glob("*.pdf")]
    return pdf_files

# PDF 썸네일 생성 및 프로젝트 데이터 준비
def generate_pdf_projects():
    projects_data = []
    pdf_files = get_pdf_files()
    
    for pdf_file in pdf_files:
        projects_data.append({
            "path": str(pdf_file),
            "name": pdf_file.stem,
            "cached": pdf_file.stem in pdf_cache and pdf_cache[pdf_file.stem].get("status") == "completed"
        })
    
    return projects_data

# 캐시 파일 경로 생성
def get_cache_path(pdf_name: str):
    return CACHE_DIR / f"{pdf_name}_cache.json"

# 최적화된 PDF 페이지 캐싱 함수
async def cache_pdf(pdf_path: str):
    try:
        import fitz  # PyMuPDF
        
        pdf_file = pathlib.Path(pdf_path)
        pdf_name = pdf_file.stem
        
        # 락 생성 - 동일한 PDF에 대해 동시 캐싱 방지
        if pdf_name not in cache_locks:
            cache_locks[pdf_name] = threading.Lock()
        
        # 이미 캐싱 중이거나 캐싱 완료된 PDF는 건너뛰기
        if pdf_name in pdf_cache and pdf_cache[pdf_name].get("status") in ["processing", "completed"]:
            logger.info(f"PDF {pdf_name} 이미 캐싱 완료 또는 진행 중")
            return
        
        with cache_locks[pdf_name]:
            # 이중 체크 - 락 획득 후 다시 확인
            if pdf_name in pdf_cache and pdf_cache[pdf_name].get("status") in ["processing", "completed"]:
                return
            
            # 캐시 상태 업데이트
            pdf_cache[pdf_name] = {"status": "processing", "progress": 0, "pages": []}
            
            # 캐시 파일이 이미 존재하는지 확인
            cache_path = get_cache_path(pdf_name)
            if cache_path.exists():
                try:
                    with open(cache_path, "r") as cache_file:
                        cached_data = json.load(cache_file)
                        if cached_data.get("status") == "completed" and cached_data.get("pages"):
                            pdf_cache[pdf_name] = cached_data
                            pdf_cache[pdf_name]["status"] = "completed"
                            logger.info(f"캐시 파일에서 {pdf_name} 로드 완료")
                            return
                except Exception as e:
                    logger.error(f"캐시 파일 로드 실패: {e}")
            
            # PDF 파일 열기
            doc = fitz.open(pdf_path)
            total_pages = doc.page_count
            
            # 미리 썸네일만 먼저 생성 (빠른 UI 로딩용)
            if total_pages > 0:
                # 첫 페이지 썸네일 생성
                page = doc[0]
                pix_thumb = page.get_pixmap(matrix=fitz.Matrix(0.2, 0.2))  # 더 작은 썸네일
                thumb_data = pix_thumb.tobytes("png")
                b64_thumb = base64.b64encode(thumb_data).decode('utf-8')
                thumb_src = f"data:image/png;base64,{b64_thumb}"
                
                # 썸네일 페이지만 먼저 캐시
                pdf_cache[pdf_name]["pages"] = [{"thumb": thumb_src, "src": ""}]
                pdf_cache[pdf_name]["progress"] = 1
                pdf_cache[pdf_name]["total_pages"] = total_pages
            
            # 이미지 해상도 및 압축 품질 설정 (성능 최적화)
            scale_factor = 1.0  # 기본 해상도 (낮출수록 로딩 빠름)
            jpeg_quality = 80   # JPEG 품질 (낮출수록 용량 작아짐)
            
            # 페이지 처리 작업자 함수 (병렬 처리용)
            def process_page(page_num):
                try:
                    page = doc[page_num]
                    
                    # 이미지로 변환 시 매트릭스 스케일링 적용 (성능 최적화)
                    pix = page.get_pixmap(matrix=fitz.Matrix(scale_factor, scale_factor))
                    
                    # JPEG 형식으로 인코딩 (PNG보다 크기 작음)
                    img_data = pix.tobytes("jpeg", jpeg_quality)
                    b64_img = base64.b64encode(img_data).decode('utf-8')
                    img_src = f"data:image/jpeg;base64,{b64_img}"
                    
                    # 썸네일 (첫 페이지가 아니면 빈 문자열)
                    thumb_src = "" if page_num > 0 else pdf_cache[pdf_name]["pages"][0]["thumb"]
                    
                    return {
                        "page_num": page_num,
                        "src": img_src,
                        "thumb": thumb_src
                    }
                except Exception as e:
                    logger.error(f"페이지 {page_num} 처리 오류: {e}")
                    return {
                        "page_num": page_num,
                        "src": "",
                        "thumb": "",
                        "error": str(e)
                    }
            
            # 병렬 처리로 모든 페이지 처리
            pages = [None] * total_pages
            processed_count = 0
            
            # 페이지 배치 처리 (메모리 관리)
            batch_size = 5  # 한 번에 처리할 페이지 수
            
            for batch_start in range(0, total_pages, batch_size):
                batch_end = min(batch_start + batch_size, total_pages)
                current_batch = list(range(batch_start, batch_end))
                
                # 병렬 처리로 배치 페이지 렌더링
                with concurrent.futures.ThreadPoolExecutor(max_workers=min(5, batch_size)) as executor:
                    batch_results = list(executor.map(process_page, current_batch))
                
                # 결과 저장
                for result in batch_results:
                    page_num = result["page_num"]
                    pages[page_num] = {
                        "src": result["src"],
                        "thumb": result["thumb"]
                    }
                    
                    processed_count += 1
                    progress = round(processed_count / total_pages * 100)
                    pdf_cache[pdf_name]["progress"] = progress
                
                # 중간 저장
                pdf_cache[pdf_name]["pages"] = pages
                try:
                    with open(cache_path, "w") as cache_file:
                        json.dump({
                            "status": "processing", 
                            "progress": pdf_cache[pdf_name]["progress"], 
                            "pages": pdf_cache[pdf_name]["pages"],
                            "total_pages": total_pages
                        }, cache_file)
                except Exception as e:
                    logger.error(f"중간 캐시 저장 실패: {e}")
            
            # 캐싱 완료
            pdf_cache[pdf_name] = {
                "status": "completed",
                "progress": 100,
                "pages": pages,
                "total_pages": total_pages
            }
            
            # 최종 캐시 파일 저장
            try:
                with open(cache_path, "w") as cache_file:
                    json.dump(pdf_cache[pdf_name], cache_file)
                logger.info(f"PDF {pdf_name} 캐싱 완료, {total_pages}페이지")
            except Exception as e:
                logger.error(f"최종 캐시 저장 실패: {e}")
            
    except Exception as e:
        import traceback
        logger.error(f"PDF 캐싱 오류: {str(e)}\n{traceback.format_exc()}")
        if 'pdf_name' in locals() and pdf_name in pdf_cache:
            pdf_cache[pdf_name]["status"] = "error"
            pdf_cache[pdf_name]["error"] = str(e)

# 시작 시 모든 PDF 파일 캐싱
async def init_cache_all_pdfs():
    logger.info("PDF 캐싱 작업 시작")
    pdf_files = get_pdf_files()
    
    # 이미 캐시된 PDF 파일 로드 (빠른 시작을 위해 먼저 수행)
    for cache_file in CACHE_DIR.glob("*_cache.json"):
        try:
            pdf_name = cache_file.stem.replace("_cache", "")
            with open(cache_file, "r") as f:
                cached_data = json.load(f)
                if cached_data.get("status") == "completed" and cached_data.get("pages"):
                    pdf_cache[pdf_name] = cached_data
                    pdf_cache[pdf_name]["status"] = "completed"
                    logger.info(f"기존 캐시 로드: {pdf_name}")
        except Exception as e:
            logger.error(f"캐시 파일 로드 오류: {str(e)}")
    
    # 캐싱되지 않은 PDF 파일 병렬 처리
    await asyncio.gather(*[asyncio.create_task(cache_pdf(str(pdf_file))) 
                          for pdf_file in pdf_files 
                          if pdf_file.stem not in pdf_cache 
                          or pdf_cache[pdf_file.stem].get("status") != "completed"])

# 백그라운드 작업 시작 함수
@app.on_event("startup")
async def startup_event():
    # 백그라운드 태스크로 캐싱 실행
    asyncio.create_task(init_cache_all_pdfs())

# API 엔드포인트: PDF 프로젝트 목록
@app.get("/api/pdf-projects")
async def get_pdf_projects_api():
    return generate_pdf_projects()

# API 엔드포인트: PDF 썸네일 제공 (최적화)
@app.get("/api/pdf-thumbnail")
async def get_pdf_thumbnail(path: str):
    try:
        pdf_file = pathlib.Path(path)
        pdf_name = pdf_file.stem
        
        # 캐시에서 썸네일 가져오기
        if pdf_name in pdf_cache and pdf_cache[pdf_name].get("pages"):
            if pdf_cache[pdf_name]["pages"][0].get("thumb"):
                return {"thumbnail": pdf_cache[pdf_name]["pages"][0]["thumb"]}
            
        # 캐시에 없으면 생성 (더 작고 빠른 썸네일)
        import fitz
        doc = fitz.open(path)
        if doc.page_count > 0:
            page = doc[0]
            pix = page.get_pixmap(matrix=fitz.Matrix(0.2, 0.2))  # 더 작은 썸네일
            img_data = pix.tobytes("jpeg", 70)  # JPEG 압축 사용
            b64_img = base64.b64encode(img_data).decode('utf-8')
            
            # 백그라운드에서 캐싱 시작
            asyncio.create_task(cache_pdf(path))
            
            return {"thumbnail": f"data:image/jpeg;base64,{b64_img}"}
        
        return {"thumbnail": None}
    except Exception as e:
        logger.error(f"썸네일 생성 오류: {str(e)}")
        return {"error": str(e), "thumbnail": None}

# API 엔드포인트: 캐시 상태 확인
@app.get("/api/cache-status")
async def get_cache_status(path: str = None):
    if path:
        pdf_file = pathlib.Path(path)
        pdf_name = pdf_file.stem
        if pdf_name in pdf_cache:
            return pdf_cache[pdf_name]
        return {"status": "not_cached"}
    else:
        return {name: {"status": info["status"], "progress": info.get("progress", 0)} 
                for name, info in pdf_cache.items()}

# API 엔드포인트: 캐시된 PDF 콘텐츠 제공 (점진적 로딩 지원)
@app.get("/api/cached-pdf")
async def get_cached_pdf(path: str, background_tasks: BackgroundTasks):
    try:
        pdf_file = pathlib.Path(path)
        pdf_name = pdf_file.stem
        
        # 캐시 확인
        if pdf_name in pdf_cache:
            status = pdf_cache[pdf_name].get("status", "")
            
            # 완료된 경우 전체 데이터 반환
            if status == "completed":
                return pdf_cache[pdf_name]
            
            # 처리 중인 경우 현재까지의 페이지 데이터 포함 (점진적 로딩)
            elif status == "processing":
                progress = pdf_cache[pdf_name].get("progress", 0)
                pages = pdf_cache[pdf_name].get("pages", [])
                total_pages = pdf_cache[pdf_name].get("total_pages", 0)
                
                return {
                    "status": "processing", 
                    "progress": progress,
                    "pages": pages,
                    "total_pages": total_pages,
                    "available_pages": len([p for p in pages if p and p.get("src")])
                }
        
        # 캐시가 없는 경우 백그라운드에서 캐싱 시작
        background_tasks.add_task(cache_pdf, path)
        return {"status": "started", "progress": 0}
        
    except Exception as e:
        logger.error(f"캐시된 PDF 제공 오류: {str(e)}")
        return {"error": str(e), "status": "error"}

# API 엔드포인트: PDF 원본 콘텐츠 제공(캐시가 없는 경우)
@app.get("/api/pdf-content")
async def get_pdf_content(path: str, background_tasks: BackgroundTasks):
    try:
        # 캐싱 상태 확인
        pdf_file = pathlib.Path(path)
        if not pdf_file.exists():
            return JSONResponse(content={"error": f"파일을 찾을 수 없습니다: {path}"}, status_code=404)
        
        pdf_name = pdf_file.stem
        
        # 캐시된 경우 리다이렉트
        if pdf_name in pdf_cache and (pdf_cache[pdf_name].get("status") == "completed" 
                                     or (pdf_cache[pdf_name].get("status") == "processing" 
                                         and pdf_cache[pdf_name].get("progress", 0) > 10)):
            return JSONResponse(content={"redirect": f"/api/cached-pdf?path={path}"})
        
        # 파일 읽기
        with open(path, "rb") as pdf_file:
            content = pdf_file.read()
            
        # 파일명 처리
        import urllib.parse
        filename = pdf_file.name
        encoded_filename = urllib.parse.quote(filename)
        
        # 백그라운드에서 캐싱 시작
        background_tasks.add_task(cache_pdf, path)
        
        # 응답 헤더 설정
        headers = {
            "Content-Type": "application/pdf",
            "Content-Disposition": f"inline; filename=\"{encoded_filename}\"; filename*=UTF-8''{encoded_filename}"
        }
        
        return Response(content=content, media_type="application/pdf", headers=headers)
    except Exception as e:
        import traceback
        error_details = traceback.format_exc()
        logger.error(f"PDF 콘텐츠 로드 오류: {str(e)}\n{error_details}")
        return JSONResponse(content={"error": str(e)}, status_code=500)

# HTML 파일 읽기 함수
def get_html_content():
    html_path = BASE / "flipbook_template.html"
    if html_path.exists():
        with open(html_path, "r", encoding="utf-8") as f:
            return f.read()
    return HTML  # 기본 HTML 사용

# HTML 문자열 (UI 수정 버전)
HTML = """
<!doctype html>
<html lang="ko">
<head>
  <meta charset="utf-8">
  <title>FlipBook Space</title>
  <link rel="stylesheet" href="/static/flipbook.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
  <script src="/static/three.js"></script>
  <script src="/static/iscroll.js"></script>
  <script src="/static/mark.js"></script>
  <script src="/static/mod3d.js"></script>
  <script src="/static/pdf.js"></script>
  <script src="/static/flipbook.js"></script>
  <script src="/static/flipbook.book3.js"></script>
  <script src="/static/flipbook.scroll.js"></script>
  <script src="/static/flipbook.swipe.js"></script>
  <script src="/static/flipbook.webgl.js"></script>
  <style>
  /* 전체 사이트 파스텔톤 테마 */
  :root {
    --primary-color: #a5d8ff; /* 파스텔 블루 */
    --secondary-color: #ffd6e0; /* 파스텔 핑크 */
    --tertiary-color: #c3fae8; /* 파스텔 민트 */
    --accent-color: #d0bfff; /* 파스텔 퍼플 */
    --bg-color: #f8f9fa; /* 밝은 배경 */
    --text-color: #495057; /* 부드러운 어두운 색 */
    --card-bg: #ffffff; /* 카드 배경색 */
    --shadow-sm: 0 2px 8px rgba(0,0,0,0.05);
    --shadow-md: 0 4px 12px rgba(0,0,0,0.08);
    --shadow-lg: 0 8px 24px rgba(0,0,0,0.12);
    --radius-sm: 8px;
    --radius-md: 12px;
    --radius-lg: 16px;
    --transition: all 0.3s ease;
  }

  body {
    margin: 0;
    /* ▼ 고급진 블루 계열 그라디에이션으로 변경 */
    background-image: linear-gradient(135deg, #0f2027 0%, #203a43 50%, #2c5364 100%);
    background-attachment: fixed;
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    color: var(--text-color);
  }

  /* 헤더 제목 제거 및 Home 버튼 레이어 처리 */
  .floating-home {
    position: fixed;
    top: 20px;
    left: 20px;
    width: 60px;
    height: 60px;
    border-radius: 50%;
    background: rgba(255, 255, 255, 0.9);
    backdrop-filter: blur(10px);
    box-shadow: var(--shadow-md);
    z-index: 9999;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    transition: var(--transition);
    overflow: hidden;
  }
  
  .floating-home:hover {
    transform: scale(1.05);
    box-shadow: var(--shadow-lg);
  }
  
  .floating-home .icon {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    font-size: 22px;
    color: var(--primary-color);
    transition: var(--transition);
  }
  
  .floating-home:hover .icon {
    color: #8bc5f8;
  }
  
  .floating-home .title {
    position: absolute;
    left: 70px;
    background: rgba(255, 255, 255, 0.95);
    padding: 8px 20px;
    border-radius: 20px;
    box-shadow: var(--shadow-sm);
    font-weight: 600;
    font-size: 14px;
    white-space: nowrap;
    pointer-events: none;
    opacity: 0;
    transform: translateX(-10px);
    transition: all 0.3s ease;
  }
  
  .floating-home:hover .title {
    opacity: 1;
    transform: translateX(0);
  }
  
  #home, #viewerPage {
    padding-top: 100px;
    max-width: 1200px;
    margin: 0 auto;
    padding-bottom: 60px;
    padding-left: 30px;
    padding-right: 30px;
    position: relative;
  }

  /* 업로드 버튼 스타일 */
  .upload-container {
    display: flex;
    margin-bottom: 30px;
    justify-content: center;
  }

  button.upload {
    all: unset;
    cursor: pointer;
    padding: 12px 20px;
    border-radius: var(--radius-md);
    background: white;
    margin: 0 10px;
    font-weight: 500;
    display: inline-flex;
    align-items: center;
    box-shadow: var(--shadow-sm);
    transition: var(--transition);
    position: relative;
    overflow: hidden;
  }

  button.upload::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: linear-gradient(120deg, var(--primary-color), var(--secondary-color));
    opacity: 0.08;
    z-index: -1;
  }

  button.upload:hover {
    transform: translateY(-3px);
    box-shadow: var(--shadow-md);
  }

  button.upload:hover::before {
    opacity: 0.15;
  }

  button.upload i {
    margin-right: 8px;
    font-size: 20px;
  }

  /* 그리드 및 카드 스타일 */
  .grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: 24px;
    margin-top: 36px;
  }

  .card {
    background: var(--card-bg);
    border-radius: var(--radius-md);
    cursor: pointer;
    box-shadow: var(--shadow-sm);
    width: 100%;
    height: 280px;
    position: relative;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    transition: var(--transition);
    overflow: hidden;
  }

  .card::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: linear-gradient(135deg, var(--secondary-color) 0%, var(--primary-color) 100%);
    opacity: 0.06;
    z-index: 1;
  }

  .card::after {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 30%;
    background: linear-gradient(to bottom, rgba(255,255,255,0.8) 0%, rgba(255,255,255,0) 100%);
    z-index: 2;
  }

  .card img {
    width: 65%;
    height: auto;
    object-fit: contain;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -65%);
    border: 1px solid rgba(0,0,0,0.05);
    box-shadow: 0 4px 15px rgba(0,0,0,0.08);
    z-index: 3;
    transition: var(--transition);
  }

  .card:hover {
    transform: translateY(-5px);
    box-shadow: var(--shadow-md);
  }

  .card:hover img {
    transform: translate(-50%, -65%) scale(1.03);
    box-shadow: 0 8px 20px rgba(0,0,0,0.12);
  }

  .card p {
    position: absolute;
    bottom: 20px;
    left: 50%;
    transform: translateX(-50%);
    background: rgba(255, 255, 255, 0.9);
    padding: 8px 16px;
    border-radius: 30px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.05);
    width: 80%;
    text-align: center;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    font-size: 14px;
    font-weight: 500;
    color: var(--text-color);
    z-index: 4;
    transition: var(--transition);
  }

  .card:hover p {
    background: rgba(255, 255, 255, 0.95);
    box-shadow: 0 4px 12px rgba(0,0,0,0.08);
  }

  /* 캐시 상태 뱃지 */
  .cached-status {
    position: absolute;
    top: 10px;
    right: 10px;
    background: var(--accent-color);
    color: white;
    font-size: 11px;
    padding: 3px 8px;
    border-radius: 12px;
    z-index: 5;
    box-shadow: var(--shadow-sm);
  }

  /* 뷰어 스타일 */
  #viewer {
    width: 90%;
    height: 90vh;
    max-width: 90%;
    margin: 0;
    background: var(--card-bg);
    border: none;
    border-radius: var(--radius-lg);
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: 1000;
    box-shadow: var(--shadow-lg);
    max-height: calc(90vh - 40px);
    aspect-ratio: auto;
    object-fit: contain;
    overflow: hidden;
  }

  /* FlipBook 컨트롤바 스타일 */
  .flipbook-container .fb3d-menu-bar {
    z-index: 2000 !important;
    opacity: 1 !important;
    bottom: 0 !important;
    background-color: rgba(255,255,255,0.9) !important;
    backdrop-filter: blur(10px) !important;
    border-radius: 0 0 var(--radius-lg) var(--radius-lg) !important;
    padding: 12px 0 !important;
    box-shadow: 0 -4px 20px rgba(0,0,0,0.1) !important;
  }

  .flipbook-container .fb3d-menu-bar > ul > li > img,
  .flipbook-container .fb3d-menu-bar > ul > li > div {
    opacity: 1 !important;
    transform: scale(1.2) !important;
    filter: drop-shadow(0 2px 3px rgba(0,0,0,0.1)) !important;
  }

  .flipbook-container .fb3d-menu-bar > ul > li {
    margin: 0 12px !important;
  }

  /* 메뉴 툴팁 스타일 */
  .flipbook-container .fb3d-menu-bar > ul > li > span {
    background-color: rgba(0,0,0,0.7) !important;
    color: white !important;
    border-radius: var(--radius-sm) !important;
    padding: 8px 12px !important;
    font-size: 13px !important;
    bottom: 55px !important;
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif !important;
    letter-spacing: 0.3px !important;
  }

  /* 뷰어 모드일 때 배경 오버레이 */
  .viewer-mode {
    background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%) !important;
  }

  /* 뷰어 페이지 배경 */
  #viewerPage {
    background: transparent;
  }

  /* 로딩 애니메이션 */
  @keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
  }

  .loading-spinner {
    border: 4px solid rgba(255,255,255,0.3);
    border-top: 4px solid var(--primary-color);
    border-radius: 50%;
    width: 50px;
    height: 50px;
    margin: 0 auto;
    animation: spin 1.5s ease-in-out infinite;
  }

  .loading-container {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    text-align: center;
    background: rgba(255, 255, 255, 0.85);
    backdrop-filter: blur(10px);
    padding: 30px;
    border-radius: var(--radius-md);
    box-shadow: var(--shadow-md);
    z-index: 9999;
  }

  .loading-text {
    margin-top: 20px;
    font-size: 16px;
    color: var(--text-color);
    font-weight: 500;
  }

  /* 페이지 전환 애니메이션 */
  @keyframes fadeIn {
    from { opacity: 0; }
    to { opacity: 1; }
  }

  .fade-in {
    animation: fadeIn 0.5s ease-out;
  }

  /* 추가 스타일 */
  .section-title {
    font-size: 1.3rem;
    font-weight: 600;
    margin: 30px 0 15px;
    color: var(--text-color);
  }

  .no-projects {
    text-align: center;
    margin: 40px 0;
    color: var(--text-color);
    font-size: 16px;
  }

  /* 프로그레스 바 */
  .progress-bar-container {
    width: 100%;
    height: 6px;
    background-color: rgba(0,0,0,0.1);
    border-radius: 3px;
    margin-top: 15px;
    overflow: hidden;
  }

  .progress-bar {
    height: 100%;
    background: linear-gradient(to right, var(--primary-color), var(--accent-color));
    border-radius: 3px;
    transition: width 0.3s ease;
  }

  /* 헤더 로고 및 타이틀 */
  /* ▼ pointer-events: none 제거, 높이와 패딩 조정하여 제목을 더 위로 */
  .library-header {
    position: fixed;
    top: 10px;  /* 기존 20px -> 10px으로 */
    left: 0;
    right: 0;
    text-align: center;
    z-index: 100;
  }
  
  .library-header .title {
    display: inline-block;
    /* 높이 줄이기 위한 패딩/폰트 크기 조정 */
    padding: 8px 20px; /* 기존 12px 30px -> 8px 20px */
    background: rgba(255, 255, 255, 0.85);
    backdrop-filter: blur(10px);
    border-radius: 30px;
    box-shadow: var(--shadow-md);
    font-size: 1.2rem; /* 기존 1.5rem -> 1.2rem */
    font-weight: 600;
    background-image: linear-gradient(120deg, #667eea 0%, #764ba2 100%);
    -webkit-background-clip: text;
    background-clip: text;
    color: transparent;
  }
  
  /* 점진적 로딩 표시 */
  .loading-pages {
    position: absolute;
    bottom: 20px;
    left: 50%;
    transform: translateX(-50%);
    background: rgba(255, 255, 255, 0.9);
    padding: 10px 20px;
    border-radius: 20px;
    box-shadow: var(--shadow-md);
    font-size: 14px;
    color: var(--text-color);
    z-index: 9998;
    text-align: center;
  }

  /* 반응형 디자인 */
  @media (max-width: 768px) {
    .grid {
      grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
      gap: 16px;
    }
    
    .card {
      height: 240px;
    }
    
    .library-header .title {
      font-size: 1rem;
      padding: 6px 16px;
    }
    
    .floating-home {
      width: 50px;
      height: 50px;
    }
    
    .floating-home .icon {
      font-size: 18px;
    }
  }
  </style>
</head>
<body>
  <!-- 제목을 Home 버튼과 함께 레이어로 처리 -->
  <div id="homeButton" class="floating-home" style="display:none;">
    <div class="icon"><i class="fas fa-home"></i></div>
    <div class="title">홈으로 돌아가기</div>
  </div>
  
  <!-- 센터 정렬된 타이틀 -->
  <div class="library-header">
    <div class="title">FlipBook Library</div>
  </div>

  <section id="home" class="fade-in">
    <div class="upload-container">
      <button class="upload" id="imageUploadBtn">
        <i class="fas fa-images"></i> 이미지 추가
        <input id="imgInput" type="file" accept="image/*" multiple hidden>
      </button>
      <button class="upload" id="pdfUploadBtn">
        <i class="fas fa-file-pdf"></i> PDF 추가
        <input id="pdfInput" type="file" accept="application/pdf" hidden>
      </button>
    </div>
    
    <div class="section-title">내 프로젝트</div>
    <div class="grid" id="grid">
      <!-- 카드가 여기에 동적으로 추가됩니다 -->
    </div>
    <div id="noProjects" class="no-projects" style="display: none;">
      프로젝트가 없습니다. 이미지나 PDF를 추가하여 시작하세요.
    </div>
  </section>

  <section id="viewerPage" style="display:none">
    <div id="viewer"></div>
    <div id="loadingPages" class="loading-pages" style="display:none;">페이지 로딩 중... <span id="loadingPagesCount">0/0</span></div>
  </section>

  <script>
    let projects=[], fb=null;
    const grid=$id('grid'), viewer=$id('viewer');
    pdfjsLib.GlobalWorkerOptions.workerSrc='/static/pdf.worker.js';

    // 서버에서 미리 로드된 PDF 프로젝트
    let serverProjects = [];
    
    // 현재 페이지 로딩 상태
    let currentLoadingPdfPath = null;
    let pageLoadingInterval = null;

    /* 🔊 오디오 unlock – 내장 Audio 와 같은 MP3 경로 사용 */
    ['click','touchstart'].forEach(evt=>{
      document.addEventListener(evt,function u(){new Audio('static/turnPage2.mp3')
            .play().then(a=>a.pause()).catch(()=>{});document.removeEventListener(evt,u,{capture:true});},
            {once:true,capture:true});
    });
    
    /* ── 유틸 ── */
    function $id(id){return document.getElementById(id)}
    
    // 직접 이벤트 리스너 설정 (업로드 버튼 클릭시 파일 선택창 열기)
    function setupDirectEvents() {
      // 이미지 업로드 버튼
      const imageBtn = $id('imageUploadBtn');
      const imageInput = $id('imgInput');
      if (imageBtn && imageInput) {
        console.log('이미지 업로드 버튼 이벤트 설정');
        imageBtn.onclick = function(e) {
          e.preventDefault();
          e.stopPropagation();
          imageInput.click();
        };
      }
      
      // PDF 업로드 버튼
      const pdfBtn = $id('pdfUploadBtn');
      const pdfInput = $id('pdfInput');
      if (pdfBtn && pdfInput) {
        console.log('PDF 업로드 버튼 이벤트 설정');
        pdfBtn.onclick = function(e) {
          e.preventDefault();
          e.stopPropagation();
          pdfInput.click();
        };
      }
    }

    function addCard(i, thumb, title, isCached = false) {
      const d = document.createElement('div');
      d.className = 'card fade-in';
      d.onclick = () => open(i);
      
      const displayTitle = title ? 
        (title.length > 15 ? title.substring(0, 15) + '...' : title) : 
        '프로젝트 ' + (i+1);
      
      const cachedBadge = isCached ? 
        '<div class="cached-status">캐시됨</div>' : '';
      
      d.innerHTML = `
        <div class="card-inner">
          ${cachedBadge}
          <img src="${thumb}" alt="${displayTitle}" loading="lazy">
          <p title="${title || '프로젝트 ' + (i+1)}">${displayTitle}</p>
        </div>
      `;
      grid.appendChild(d);
      
      // 프로젝트가 있으면 '프로젝트 없음' 메시지 숨기기
      $id('noProjects').style.display = 'none';
    }

    /* ── 이미지 업로드 ── */
    $id('imgInput').onchange = e => {
      const files = [...e.target.files];
      if(!files.length) return;
      
      showLoading("이미지 로딩 중...");
      
      const pages=[], tot = files.length; 
      let done = 0;
      files.forEach((f,i)=> {
        const r=new FileReader();
        r.onload=x=>{
          pages[i] = {src: x.target.result, thumb: x.target.result};
          if(++done===tot) {
            save(pages, '이미지 컬렉션');
            hideLoading();
          }
        };
        r.readAsDataURL(f);
      });
    };

    /* ── PDF 업로드 ── */
    $id('pdfInput').onchange = e => {
      const file = e.target.files[0];
      if(!file) return;
      
      showLoading("PDF 로딩 중...");
      
      const fr = new FileReader();
      fr.onload = v => {
        pdfjsLib.getDocument({data: v.target.result}).promise.then(async pdf=>{
          const pages = [];
          
          for(let p=1; p <= pdf.numPages; p++){
            updateLoading(\`PDF 페이지 로딩 중... (\${p}/\${pdf.numPages})\`);
            const pg=await pdf.getPage(p), vp=pg.getViewport({scale:1});
            const c=document.createElement('canvas');
            c.width=vp.width;c.height=vp.height;
            await pg.render({canvasContext:c.getContext('2d'),viewport:vp}).promise;
            pages.push({src:c.toDataURL(), thumb:c.toDataURL()});
          }
          hideLoading();
          save(pages, file.name.replace('.pdf', ''));
        }).catch(error => {
          console.error("PDF 로딩 오류:", error);
          hideLoading();
          showError("PDF 로딩 중 오류가 발생했습니다.");
        });
      };
      fr.readAsArrayBuffer(file);
    };

    function save(pages, title, isCached = false){
      const id=projects.push(pages)-1;
      addCard(id, pages[0].thumb, title, isCached);
    }

    /* ── 서버 PDF 로드 및 캐시 상태 확인 ── */
    async function loadServerPDFs() {
      try {
        if (document.querySelectorAll('.card').length === 0) {
          showLoading("라이브러리 로딩 중...");
        }
        
        // 먼저 캐시 상태 확인
        const cacheStatusRes = await fetch('/api/cache-status');
        const cacheStatus = await cacheStatusRes.json();
        
        // PDF 프로젝트 목록 가져오기
        const response = await fetch('/api/pdf-projects');
        serverProjects = await response.json();
        
        if (serverProjects.length === 0) {
          hideLoading();
          $id('noProjects').style.display = 'block';
          return;
        }
        
        const thumbnailPromises = serverProjects.map(async (project, index) => {
          updateLoading(\`PDF 프로젝트 로딩 중... (\${index+1}/\${serverProjects.length})\`);
          
          const pdfName = project.name;
          const isCached = cacheStatus[pdfName] && cacheStatus[pdfName].status === "completed";
          
          try {
            // 썸네일 가져오기
            const response = await fetch(\`/api/pdf-thumbnail?path=\${encodeURIComponent(project.path)}\`);
            const data = await response.json();
            
            if(data.thumbnail) {
              const pages = [{
                src: data.thumbnail,
                thumb: data.thumbnail,
                path: project.path,
                cached: isCached
              }];
              return { pages, name: project.name, isCached };
            }
          } catch (err) {
            console.error(\`썸네일 로드 오류 (\${project.name}):\`, err);
          }
          
          return null;
        });
        
        const results = await Promise.all(thumbnailPromises);
        
        results.filter(result => result !== null).forEach(result => {
          save(result.pages, result.name, result.isCached);
        });
        
        hideLoading();
        
        if (document.querySelectorAll('.card').length === 0) {
          $id('noProjects').style.display = 'block';
        }
      } catch(error) {
        console.error('서버 PDF 로드 실패:', error);
        hideLoading();
        showError("라이브러리 로딩 중 오류가 발생했습니다.");
      }
    }

    /* ── 캐시 상태 정기적으로 확인 ── */
    async function checkCacheStatus() {
      try {
        const response = await fetch('/api/cache-status');
        const cacheStatus = await response.json();
        
        // 현재 카드 상태 업데이트
        const cards = document.querySelectorAll('.card');
        
        for(let i = 0; i < cards.length; i++) {
          if(projects[i] && projects[i][0] && projects[i][0].path) {
            const pdfPath = projects[i][0].path;
            const pdfName = pdfPath.split('/').pop().replace('.pdf', '');
            
            let badgeEl = cards[i].querySelector('.cached-status');
            
            if(cacheStatus[pdfName] && cacheStatus[pdfName].status === "completed") {
              if(!badgeEl) {
                badgeEl = document.createElement('div');
                badgeEl.className = 'cached-status';
                badgeEl.textContent = '캐시됨';
                cards[i].querySelector('.card-inner')?.appendChild(badgeEl);
              } else if (badgeEl.textContent !== '캐시됨') {
                badgeEl.textContent = '캐시됨';
                badgeEl.style.background = 'var(--accent-color)';
              }
              projects[i][0].cached = true;
            } else if(cacheStatus[pdfName] && cacheStatus[pdfName].status === "processing") {
              if(!badgeEl) {
                badgeEl = document.createElement('div');
                badgeEl.className = 'cached-status';
                cards[i].querySelector('.card-inner')?.appendChild(badgeEl);
              }
              badgeEl.textContent = \`\${cacheStatus[pdfName].progress}%\`;
              badgeEl.style.background = 'var(--secondary-color)';
            }
          }
        }
        
        // 현재 로딩 중인 PDF가 있으면 상태 확인
        if (currentLoadingPdfPath && pageLoadingInterval) {
          const pdfName = currentLoadingPdfPath.split('/').pop().replace('.pdf', '');
          if (cacheStatus[pdfName]) {
            const status = cacheStatus[pdfName].status;
            const progress = cacheStatus[pdfName].progress || 0;
            
            if (status === "completed") {
              clearInterval(pageLoadingInterval);
              $id('loadingPages').style.display = 'none';
              currentLoadingPdfPath = null;
              refreshFlipBook();
            } else if (status === "processing") {
              $id('loadingPages').style.display = 'block';
              $id('loadingPagesCount').textContent = \`\${progress}%\`;
            }
          }
        }
      } catch(error) {
        console.error('캐시 상태 확인 오류:', error);
      }
    }

    /* ── 카드 → FlipBook ── */
    async function open(i) {
      toggle(false);
      const pages = projects[i];
      
      if(fb) {
        fb.destroy();
        viewer.innerHTML = '';
      }
      
      if(pages[0].path) {
        const pdfPath = pages[0].path;
        let progressiveLoading = false;
        currentLoadingPdfPath = pdfPath;
        
        if(pages[0].cached) {
          showLoading("캐시된 PDF 로딩 중...");
          try {
            const response = await fetch(\`/api/cached-pdf?path=\${encodeURIComponent(pdfPath)}\`);
            const cachedData = await response.json();
            
            if(cachedData.status === "completed" && cachedData.pages) {
              hideLoading();
              createFlipBook(cachedData.pages);
              currentLoadingPdfPath = null;
              return;
            } else if(cachedData.status === "processing" && cachedData.pages && cachedData.pages.length > 0) {
              hideLoading();
              createFlipBook(cachedData.pages);
              progressiveLoading = true;
              startProgressiveLoadingIndicator(cachedData.progress, cachedData.total_pages);
            }
          } catch(error) {
            console.error("캐시 데이터 로드 오류:", error);
          }
        }
        
        if(!progressiveLoading) {
          showLoading("PDF 준비 중...");
          try {
            const response = await fetch(\`/api/pdf-content?path=\${encodeURIComponent(pdfPath)}\`);
            const data = await response.json();
            
            if(data.redirect) {
              const redirectRes = await fetch(data.redirect);
              const cachedData = await redirectRes.json();
              
              if(cachedData.status === "completed" && cachedData.pages) {
                hideLoading();
                createFlipBook(cachedData.pages);
                currentLoadingPdfPath = null;
                return;
              } else if(cachedData.status === "processing" && cachedData.pages && cachedData.pages.length > 0) {
                hideLoading();
                createFlipBook(cachedData.pages);
                startProgressiveLoadingIndicator(cachedData.progress, cachedData.total_pages);
                return;
              }
            }
            
            const pdfResponse = await fetch(\`/api/pdf-content?path=\${encodeURIComponent(pdfPath)}\`);
            
            try {
              const jsonData = await pdfResponse.clone().json();
              if (jsonData.redirect) {
                const redirectRes = await fetch(jsonData.redirect);
                const cachedData = await redirectRes.json();
                
                if(cachedData.pages && cachedData.pages.length > 0) {
                  hideLoading();
                  createFlipBook(cachedData.pages);
                  if(cachedData.status === "processing") {
                    startProgressiveLoadingIndicator(cachedData.progress, cachedData.total_pages);
                  } else {
                    currentLoadingPdfPath = null;
                  }
                  return;
                }
              }
            } catch (e) {
              // JSON 파싱 실패 -> PDF 원본 데이터로 처리
            }
            
            const pdfData = await pdfResponse.arrayBuffer();
            const pdf = await pdfjsLib.getDocument({data: pdfData}).promise;
            const pdfPages = [];
            
            for(let p=1; p <= pdf.numPages; p++) {
              updateLoading(\`페이지 준비 중... (\${p}/\${pdf.numPages})\`);
              const pg = await pdf.getPage(p);
              const vp = pg.getViewport({scale: 1});
              const c = document.createElement('canvas');
              c.width = vp.width;
              c.height = vp.height;
              await pg.render({canvasContext: c.getContext('2d'), viewport: vp}).promise;
              pdfPages.push({src: c.toDataURL(), thumb: c.toDataURL()});
            }
            hideLoading();
            createFlipBook(pdfPages);
            currentLoadingPdfPath = null;
          } catch(error) {
            console.error('PDF 처리 중 오류:', error);
            hideLoading();
            showError("PDF를 로드하는 중 오류가 발생했습니다.");
            currentLoadingPdfPath = null;
          }
        }
      } else {
        createFlipBook(pages);
        currentLoadingPdfPath = null;
      }
    }

    function startProgressiveLoadingIndicator(progress, totalPages) {
      $id('loadingPages').style.display = 'block';
      $id('loadingPagesCount').textContent = \`\${progress}%\`;
      
      if (pageLoadingInterval) {
        clearInterval(pageLoadingInterval);
      }
      pageLoadingInterval = setInterval(async () => {
        if (!currentLoadingPdfPath) {
          clearInterval(pageLoadingInterval);
          $id('loadingPages').style.display = 'none';
          return;
        }
        try {
          const response = await fetch(\`/api/cache-status?path=\${encodeURIComponent(currentLoadingPdfPath)}\`);
          const status = await response.json();
          
          if (status.status === "completed") {
            clearInterval(pageLoadingInterval);
            $id('loadingPages').style.display = 'none';
            refreshFlipBook();
            currentLoadingPdfPath = null;
          } else if (status.status === "processing") {
            $id('loadingPagesCount').textContent = \`\${status.progress}%\`;
          }
        } catch (e) {
          console.error("캐시 상태 확인 오류:", e);
        }
      }, 1000);
    }

    async function refreshFlipBook() {
      if (!currentLoadingPdfPath || !fb) return;
      try {
        const response = await fetch(\`/api/cached-pdf?path=\${encodeURIComponent(currentLoadingPdfPath)}\`);
        const cachedData = await response.json();
        
        if(cachedData.status === "completed" && cachedData.pages) {
          fb.destroy();
          viewer.innerHTML = '';
          createFlipBook(cachedData.pages);
          currentLoadingPdfPath = null;
        }
      } catch (e) {
        console.error("플립북 새로고침 오류:", e);
      }
    }

    function createFlipBook(pages) {
      console.log('FlipBook 생성 시작. 페이지 수:', pages.length);
      try {
        const calculateAspectRatio = () => {
          const windowWidth = window.innerWidth;
          const windowHeight = window.innerHeight;
          const aspectRatio = windowWidth / windowHeight;
          
          let width, height;
          if (aspectRatio > 1) {
            height = Math.min(windowHeight * 0.9, windowHeight - 40);
            width = height * aspectRatio * 0.8;
            if (width > windowWidth * 0.9) {
              width = windowWidth * 0.9;
              height = width / (aspectRatio * 0.8);
            }
          } else {
            width = Math.min(windowWidth * 0.9, windowWidth - 40);
            height = width / aspectRatio * 0.9;
            if (height > windowHeight * 0.9) {
              height = windowHeight * 0.9;
              width = height * aspectRatio * 0.9;
            }
          }
          return {
            width: Math.round(width),
            height: Math.round(height)
          };
        };
        
        const size = calculateAspectRatio();
        viewer.style.width = size.width + 'px';
        viewer.style.height = size.height + 'px';
        
        const validPages = pages.map(page => {
          if (!page || !page.src) {
            return {
              src: 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTAwIiBoZWlnaHQ9IjEwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48cmVjdCB3aWR0aD0iMTAwJSIgaGVpZ2h0PSIxMDAlIiBmaWxsPSIjZjVmNWY1Ii8+PHRleHQgeD0iNTAlIiB5PSI1MCUiIGZvbnQtZmFtaWx5PSJBcmlhbCIgZm9udC1zaXplPSIxMiIgdGV4dC1hbmNob3I9Im1pZGRsZSIgZHk9Ii4zZW0iIGZpbGw9IiM1NTUiPkxvYWRpbmcuLi48L3RleHQ+PC9zdmc+',
              thumb: page && page.thumb ? page.thumb : ''
            };
          }
          return page;
        });
        
        fb = new FlipBook(viewer, {
          pages: validPages,
          viewMode: 'webgl',
          autoSize: true,
          flipDuration: 800,
          backgroundColor: '#fff',
          sound: true,
          assets: {flipMp3: 'static/turnPage2.mp3', hardFlipMp3: 'static/turnPage2.mp3'},
          controlsProps: {
            enableFullscreen: true,
            enableToc: true,
            enableDownload: false,
            enablePrint: false,
            enableZoom: true,
            enableShare: false,
            enableSearch: true,
            enableAutoPlay: true,
            enableAnnotation: false,
            enableSound: true,
            enableLightbox: false,
            layout: 10,
            skin: 'light',
            autoNavigationTime: 3600,
            hideControls: false,
            paddingTop: 10,
            paddingLeft: 10,
            paddingRight: 10,
            paddingBottom: 10,
            pageTextureSize: 1024,
            thumbnails: true,
            autoHideControls: false,
            controlsTimeout: 8000
          }
        });
        
        window.addEventListener('resize', () => {
          if (fb) {
            const newSize = calculateAspectRatio();
            viewer.style.width = newSize.width + 'px';
            viewer.style.height = newSize.height + 'px';
            fb.resize();
          }
        });
        
        setTimeout(() => {
          try {
            const menuBars = document.querySelectorAll('.flipbook-container .fb3d-menu-bar');
            if (menuBars && menuBars.length > 0) {
              menuBars.forEach(menuBar => {
                menuBar.style.display = 'block';
                menuBar.style.opacity = '1';
                menuBar.style.visibility = 'visible';
                menuBar.style.zIndex = '9999';
              });
            }
          } catch (e) {
            console.warn('컨트롤바 스타일 적용 중 오류:', e);
          }
        }, 1000);
        
        console.log('FlipBook 생성 완료');
      } catch (error) {
        console.error('FlipBook 생성 중 오류 발생:', error);
        showError("FlipBook을 생성하는 중 오류가 발생했습니다.");
      }
    }

    $id('homeButton').onclick = () => {
      if(fb) {
        fb.destroy();
        viewer.innerHTML = '';
        fb = null;
      }
      toggle(true);
      if (pageLoadingInterval) {
        clearInterval(pageLoadingInterval);
        pageLoadingInterval = null;
      }
      $id('loadingPages').style.display = 'none';
      currentLoadingPdfPath = null;
    };

    function toggle(showHome){
      $id('home').style.display = showHome?'block':'none';
      $id('viewerPage').style.display = showHome?'none':'block';
      $id('homeButton').style.display = showHome?'none':'block';
      
      if(!showHome) {
        document.body.classList.add('viewer-mode');
      } else {
        document.body.classList.remove('viewer-mode');
      }
    }

    function showLoading(message, progress = -1) {
      hideLoading();
      const loadingContainer = document.createElement('div');
      loadingContainer.className = 'loading-container fade-in';
      loadingContainer.id = 'loadingContainer';
      
      let progressBarHtml = '';
      if (progress >= 0) {
        progressBarHtml = `
          <div class="progress-bar-container">
            <div id="progressBar" class="progress-bar" style="width: ${progress}%;"></div>
          </div>
        `;
      }
      
      loadingContainer.innerHTML = `
        <div class="loading-spinner"></div>
        <p class="loading-text" id="loadingText">${message || '로딩 중...'}</p>
        ${progressBarHtml}
      `;
      
      document.body.appendChild(loadingContainer);
    }
    
    function updateLoading(message, progress = -1) {
      const loadingText = $id('loadingText');
      if (loadingText) {
        loadingText.textContent = message;
      }
      
      if (progress >= 0) {
        let progressBar = $id('progressBar');
        if (!progressBar) {
          const loadingContainer = $id('loadingContainer');
          if (loadingContainer) {
            const progressContainer = document.createElement('div');
            progressContainer.className = 'progress-bar-container';
            progressContainer.innerHTML = `<div id="progressBar" class="progress-bar" style="width: ${progress}%;"></div>`;
            loadingContainer.appendChild(progressContainer);
            progressBar = $id('progressBar');
          }
        } else {
          progressBar.style.width = \`\${progress}%\`;
        }
      }
    }
    
    function hideLoading() {
      const loadingContainer = $id('loadingContainer');
      if (loadingContainer) {
        loadingContainer.remove();
      }
    }
    
    function showError(message) {
      const existingError = $id('errorContainer');
      if (existingError) {
        existingError.remove();
      }
      
      const errorContainer = document.createElement('div');
      errorContainer.className = 'loading-container fade-in';
      errorContainer.id = 'errorContainer';
      errorContainer.innerHTML = `
        <p class="loading-text" style="color: #e74c3c;">${message}</p>
        <button id="errorCloseBtn" style="margin-top: 15px; padding: 8px 16px; background: #3498db; color: white; border: none; border-radius: 4px; cursor: pointer;">확인</button>
      `;
      
      document.body.appendChild(errorContainer);
      
      $id('errorCloseBtn').onclick = () => {
        errorContainer.remove();
      };
      
      setTimeout(() => {
        if ($id('errorContainer')) {
          $id('errorContainer').remove();
        }
      }, 5000);
    }

    window.addEventListener('DOMContentLoaded', () => {
      // 업로드 버튼이 정상 동작하도록 직접 이벤트 설정
      setupDirectEvents();
      
      loadServerPDFs();
      
      // 캐시 상태를 주기적으로 확인
      setInterval(checkCacheStatus, 3000);
    });
  </script>
</body>
</html>
"""

@app.get("/", response_class=HTMLResponse)
async def root():
    return get_html_content()

if __name__ == "__main__":
    uvicorn.run("app:app", host="0.0.0.0", port=int(os.getenv("PORT", 7860)))