File size: 64,131 Bytes
455679a
d72fd49
 
 
 
b33797d
d72fd49
c489b93
 
455679a
d72fd49
 
 
 
 
 
 
14c5401
1259fe0
 
c489b93
 
d72fd49
455679a
 
 
 
 
14c5401
455679a
 
14c5401
c489b93
 
 
 
 
d72fd49
 
 
455679a
 
 
 
d72fd49
9e32c06
d72fd49
 
 
 
 
 
 
9e32c06
d72fd49
 
 
9e32c06
d72fd49
9e32c06
 
 
d72fd49
9e32c06
 
 
 
 
 
 
 
 
 
 
 
 
 
d72fd49
 
 
 
9e32c06
d72fd49
 
 
 
 
 
 
 
 
9e32c06
d72fd49
 
9e32c06
 
 
 
d72fd49
 
9e32c06
 
 
d72fd49
9e32c06
d72fd49
 
9e32c06
 
 
 
 
 
d72fd49
 
9e32c06
 
 
 
d72fd49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c489b93
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14c5401
c489b93
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
455679a
c489b93
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14c5401
 
455679a
 
 
 
d72fd49
 
455679a
 
 
 
 
 
 
 
 
 
 
 
 
b33797d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c489b93
b33797d
 
 
 
 
c489b93
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b33797d
14c5401
d72fd49
c489b93
14c5401
c489b93
 
 
 
 
455679a
c489b93
455679a
14c5401
d72fd49
 
 
14c5401
d72fd49
 
 
455679a
d72fd49
 
 
 
b33797d
 
 
 
 
 
 
 
c489b93
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b33797d
d72fd49
455679a
d72fd49
a258fc5
 
 
 
14c5401
d72fd49
 
455679a
c489b93
 
 
455679a
 
 
 
c489b93
d72fd49
455679a
 
 
c489b93
 
 
 
 
 
455679a
 
 
 
 
 
 
 
 
c489b93
455679a
 
 
 
d72fd49
a3a3acc
 
 
 
 
 
b33797d
d72fd49
 
14c5401
455679a
c489b93
 
 
455679a
 
 
b33797d
455679a
c489b93
455679a
d72fd49
 
 
 
455679a
 
14c5401
d72fd49
c489b93
14c5401
 
455679a
 
 
 
 
 
 
 
c489b93
 
 
 
 
 
 
 
 
 
 
455679a
 
 
 
 
 
 
 
 
14c5401
 
d72fd49
455679a
 
 
 
d72fd49
455679a
 
c489b93
 
455679a
d72fd49
 
 
 
 
c489b93
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d72fd49
c489b93
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14c5401
9e32c06
455679a
c489b93
455679a
c489b93
 
 
 
 
 
455679a
14c5401
c489b93
 
 
 
 
 
 
b33797d
c489b93
 
 
 
 
 
 
 
b33797d
c489b93
 
 
 
 
b33797d
c489b93
 
 
 
 
 
 
b33797d
455679a
c489b93
 
 
 
 
 
 
 
 
 
 
 
d72fd49
b33797d
c489b93
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
455679a
b33797d
c489b93
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b33797d
c489b93
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b33797d
 
 
c489b93
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b33797d
 
c489b93
 
 
14c5401
c489b93
 
 
 
 
 
 
 
 
 
 
 
 
d72fd49
c489b93
 
 
d72fd49
 
455679a
b33797d
d72fd49
c489b93
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14c5401
455679a
c489b93
 
14c5401
 
e5663e2
455679a
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
import atexit
import base64
import io
import json
import os
import re
import tempfile
import threading
import time
import uuid
import zipfile
from pathlib import Path

import gradio as gr
import requests
from PIL import Image

# API Configuration

API_URL = os.environ["API_URL"]

TOKEN = os.environ["API_TOKEN"]

LOGO_PATH = Path(__file__).parent / "pp-structurev3.png"
with open(LOGO_PATH, "rb") as image_file:
    LOGO_BASE64 = (
        f"data:image/png;base64,{base64.b64encode(image_file.read()).decode('utf-8')}"
    )

TEMP_DIR = tempfile.TemporaryDirectory()
atexit.register(TEMP_DIR.cleanup)

paddle_theme = gr.themes.Soft(
    font=["Roboto", "Open Sans", "Arial", "sans-serif"],
    font_mono=["Fira Code", "monospace"],
)


CSS = """
:root {
    --sand-color: #FAF9F6;
    --white: #ffffff;
    --shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    --text-color: #F3F4F7;
    --black:#000000;
    --link-hover: #2b6cb0;
    --content-width: 1200px;
}

body {
    display: flex;
    justify-content: center;
    background-color: var(--sand-color);
    color: var(--text-color);
    font-family: Arial, sans-serif;
}

.upload-section {
    width: 100%;
    margin: 0 auto 30px;
    padding: 20px;
    background-color: var(--sand-color) !important;
    border-radius: 8px;
    box-shadow: var(--shadow);
}

.center-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    text-align: center;
    margin-bottom: 20px;
}

.header {
    margin-bottom: 30px;
    width: 100%;
}

.logo-container {
    width: 100%;
    margin-bottom: 20px;
}

.logo-img {
    width: 100%;
    max-width: var(--content-width);
    margin: 0 auto;
    display: block;
}

.nav-bar {
    display: flex;
    justify-content: center;
    background-color: var(--white);
    padding: 15px 0;
    box-shadow: var(--shadow);
    margin-bottom: 20px;
}

.nav-links {
    display: flex;
    gap: 30px;
    width: 100%;
    justify-content: center;
}

.nav-link {
    color: var(--black);
    text-decoration: none;
    font-weight: bold;
    font-size: 24px;
    transition: color 0.2s;
}

.nav-link:hover {
    color: var(--link-hover);
    text-decoration: none;
}

button {
    background-color: var(--text-color) !important;
    color: var(--black) !important;
    border: none !important;
    border-radius: 4px;
    padding: 8px 16px;
}

.file-download {
    margin-top: 15px !important;
}
.loader {
    border: 5px solid #f3f3f3;
    border-top: 5px solid #3498db;
    border-radius: 50%;
    width: 50px;
    height: 50px;
    animation: spin 1s linear infinite;
    margin: 20px auto;
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}

.loader-container {
    text-align: center;
    margin: 20px 0;
}
.loader-container-prepare {
    text-align: left;
    margin: 20px 0;
}
.bold-label .gr-radio {
    margin-top: 8px;
    background-color: var(--white);
    padding: 10px;
    border-radius: 4px;
}

.bold-label .gr-radio label {
    font-size: 14px;
    color: var(--black);
}

#analyze-btn {
    background-color: #FF5722 !important;
    color: white !important;
    transition: all 0.3s ease !important;
    box-shadow: 0 2px 5px rgba(0,0,0,0.2) !important;
    position: fixed !important;
    bottom: 1% !important;
    left: 3% !important;
    z-index: 1000 !important;
}


#unzip-btn {
    background-color: #4CAF50 !important;
    color: white !important;
    transition: all 0.3s ease !important;
    box-shadow: 0 2px 5px rgba(0,0,0,0.2) !important;
    position: fixed !important;
    bottom: 1% !important;
    left: 18% !important;
    z-index: 1000 !important;
}

#download_file {
    position: fixed !important;
    bottom: 1% !important;
    left: 22% !important;
    z-index: 1000 !important;
}

#analyze-btn:hover,#unzip-btn:hover{
    transform: translateY(-3px) !important;
    box-shadow: 0 4px 8px rgba(0,0,0,0.3) !important;
}

.square-pdf-btn {
    width: 90% !important;
    height: 3% !important;
    padding: 0 !important;
    display: flex !important;
    flex-direction: column !important;
    align-items: center !important;
    justify-content: center !important;
    gap: 8px !important;
}


.square-pdf-btn img {
    width: 20% !important;
    height: 1% !important;
    margin: 0 !important;
}


.square-pdf-btn span {
    font-size: 14px !important;
    text-align: center !important;
}


.gradio-gallery-item:hover {
    background-color: transparent !important;
    filter: none !important;
    transform: none !important;
}

.custom-markdown h3 {
    font-size: 25px !important;
}

.tight-spacing {
    margin-bottom: -20px !important;
}

.tight-spacing-as {
    margin-top: 0px !important;
    margin-bottom: 0px !important;
}

.left-margin-column {
    margin-left: 5%;
}

.image-container img {
    display: inline-block !important;
}

}
"""
MAX_NUM_PAGES = 10
TMP_DELETE_TIME = 900
THREAD_WAKEUP_TIME = 600

EXAMPLES_TEST = [
    "examples/chinese-formula.jpg",
    "examples/chemical-equation.jpg",
    "examples/formula-chart.jpg",
    "examples/table.jpg",
    "examples/complex-formula.jpg",
    "examples/complex-typeset.jpg",
    "examples/muti-column.jpg",
    "examples/Handwritten.jpg",
    "examples/janpan-paper.jpg",
    "examples/vertical-text.jpg",
    "examples/tradition-chinese.jpg",
]

DESC_DICT = {
    "concatenate_pages": "Whether to merge pages",
    "use_formula_recognition": "Whether to use formula recognition subpipeline. If used, the formula can be converted into Latex code. If not used, the formula part is the text recognition result.",
    "use_chart_recognition": "Use the PP-Chart2Table model to parse and convert the charts in the document into tables.",
    "use_doc_orientation_classify": "Whether to use the document image orientation classification module. After use, you can correct distorted images, such as wrinkles, tilts, etc.",
    "use_doc_unwarping": "Whether to use the document unwarping module. After use, you can correct distorted images, such as wrinkles, tilts, etc.",
    "use_textline_orientation": "Whether to use the text line orientation classification module to support the distinction and correction of text lines of 0 degrees and 180 degrees.",
    "use_region_detection": "Whether to use the layout region detection. After using it, it can handle complex layouts such as newspapers and magazines.",
    "use_seal_recognition": "Whether to seal text recognition subpipeline. After use, the seal text content in the document can be extracted.",
    "use_table_recognition": "Whether to table recognition subpipeline. If used, the table can be identified as a structured format (such as HTML, Markdown, etc.). If not used, the table part will be in the form of an image.",
    "layout_threshold_nb": "The threshold used to filter out low confidence prediction results for the layout region, ranging from 0 to 1. If there are missed regions, this value can be appropriately lowered.",
    "layout_nms": "Whether the layout region detection model uses NMS post-processing. After using it, nested boxes or those with large intersections can be removed.",
    "layout_unclip_ratio_nb": "Use this method to expand each region of ​​the layout. The larger the value, the larger the expanded region.",
    "text_det_limit_type": "[Short side] means to ensure that the shortest side of the image is not less than [Image side length limit for text detection], and [Long side] means to ensure that the longest side of the image is not greater than [Image side length limit for text detection].",
    "text_det_limit_side_len_nb": "For the side length limit of the text detection input image, for large images with dense text, if you want more accurate recognition, you should choose a larger size. This parameter is used in conjunction with the [Image side length limit type for text detection]. Generally, the maximum [Long side] is suitable for scenes with large images and text, and the minimum [Short side] is suitable for document scenes with small and dense images.",
    "text_det_thresh_nb": "In the output probability map, only pixels with scores greater than the threshold are considered text pixels, and the value range is 0~1.",
    "text_det_box_thresh_nb": "When the average score of all pixels in the detection result border is greater than the threshold, the result will be considered as a text area, and the value range is 0 to 1. If missed detection occurs, this value can be appropriately lowered.",
    "text_det_unclip_ratio_nb": "Use this method to expand the text area. The larger the value, the larger the expanded area.",
    "text_rec_score_thresh_nb": "After text detection, the text box performs text recognition, and the text results with scores greater than the threshold will be retained. The value range is 0~1.",
    "seal_det_limit_type": "[Short side] means ensuring that the shortest side of the image is not less than [Image side length limit for seal text recognition], and [Long side] means ensuring that the longest side of the image is not greater than [Image side length limit for seal text recognition].",
    "seal_det_limit_side_len_nb": "For the side length limit of the input image for seal text detection, for large images with dense text, if you want more accurate recognition, you should choose a larger size. This parameter is used in conjunction with [Image side length limit type for seal text detection]. Generally, the maximum [Long side] is suitable for scenes with large images and text, and the minimum [Short side] is suitable for document scenes with small and dense images and text.",
    "seal_det_thresh_nb": "In the output probability map, only pixels with scores greater than the threshold are considered text pixels, and the value range is 0~1.",
    "seal_det_box_thresh_nb": "When the average score of all pixels within the detection result border is greater than the threshold, the result will be considered as a text area, and the value range is 0~1.",
    "seal_det_unclip_ratio_nb": "Use this method to expand the seal text area. The larger the value, the larger the expanded area.",
    "seal_rec_score_thresh_nb": "After the seal text is detected, the text box is subjected to text recognition. The text results with scores greater than the threshold will be retained. The value range is 0~1.",
    "use_ocr_results_with_table_cells": "Whether to enable the cell OCR mode. If not enabled, the global OCR result is used to fill the HTML table. If enabled, OCR is performed cell by cell and filled into the HTML table (which will increase the time consumption).",
    "use_e2e_wired_table_rec_model": "Whether to enable the wired table end-to-end prediction mode. If not enabled, the table cell detection model prediction results are used to fill the HTML table. If enabled, the end-to-end table structure recognition model cell prediction results are used to fill the HTML table.",
    "use_e2e_wireless_table_rec_model": "Whether to enable the wireless table end-to-end prediction mode. If not enabled, the table cell detection model prediction results are used to fill the HTML table. If enabled, the end-to-end table structure recognition model cell prediction results are used to fill the HTML table.",
    "use_wired_table_cells_trans_to_html": "The wired table cell detection results are directly converted to HTML. The wired table structure recognition model is no longer used to predict the HTML structure. Instead, HTML is directly constructed based on the geometric relationship of the wired table cell detection results.",
    "use_wireless_table_cells_trans_to_html": "The wireless table cell detection results are directly converted to HTML. The wireless table structure recognition model is no longer used to predict the HTML structure. Instead, HTML is directly constructed based on the geometric relationship of the wireless table cell detection results.",
    "use_table_orientation_classify": "Using table orientation classification, when the table in the image is rotated 90/180/270 degrees, the orientation can be corrected and the table recognition can be completed correctly.",
}
tmp_time = {}
lock = threading.Lock()


def gen_tooltip_radio(desc_dict):
    tooltip = {}
    for key, desc in desc_dict.items():
        suffixes = ["_rd", "_md"]
        if key.endswith("_nb"):
            suffix = "_nb"
            suffixes = ["_nb", "_md"]
            key = key[: -len(suffix)]
        for suffix in suffixes:
            tooltip[f"{key}{suffix}"] = desc
    return tooltip


TOOLTIP_RADIO = gen_tooltip_radio(DESC_DICT)


def url_to_bytes(url, *, timeout=10):
    resp = requests.get(url, timeout=timeout)
    resp.raise_for_status()
    return resp.content


def bytes_to_image(image_bytes):
    return Image.open(io.BytesIO(image_bytes))


def embed_images_into_markdown_text(markdown_text, markdown_images):
    for img_path, img_url in markdown_images.items():
        # HACK
        markdown_text = markdown_text.replace(
            f'<img src="{img_path}"', f'<img src="{img_url}"'
        )
    return markdown_text


# HACK: Adapted from PaddleX 3.0.0 code
def concatenate_markdown_pages(markdown_list):
    markdown_texts = ""
    previous_page_last_element_paragraph_end_flag = True

    for res in markdown_list:
        # Get the paragraph flags for the current page
        page_first_element_paragraph_start_flag: bool = res["isStart"]
        page_last_element_paragraph_end_flag: bool = res["isEnd"]

        # Determine whether to add a space or a newline
        if (
            not page_first_element_paragraph_start_flag
            and not previous_page_last_element_paragraph_end_flag
        ):
            last_char_of_markdown = markdown_texts[-1] if markdown_texts else ""
            first_char_of_handler = res["text"]

            # Check if the last character and the first character are Chinese characters
            last_is_chinese_char = (
                re.match(r"[\u4e00-\u9fff]", last_char_of_markdown)
                if last_char_of_markdown
                else False
            )
            first_is_chinese_char = (
                re.match(r"[\u4e00-\u9fff]", first_char_of_handler)
                if first_char_of_handler
                else False
            )
            if not (last_is_chinese_char or first_is_chinese_char):
                markdown_texts += " " + res["text"]
            else:
                markdown_texts += res["text"]
        else:
            markdown_texts += "\n\n" + res["text"]
        previous_page_last_element_paragraph_end_flag = (
            page_last_element_paragraph_end_flag
        )

    return markdown_texts


def process_file(
    file_path,
    image_input,
    use_formula_recognition,
    use_chart_recognition,
    use_doc_orientation_classify,
    use_doc_unwarping,
    use_textline_orientation,
    use_region_detection,
    use_seal_recognition,
    use_table_recognition,
    layout_threshold,
    layout_nms,
    layout_unclip_ratio,
    text_det_limit_type,
    text_det_limit_side_len,
    text_det_thresh,
    text_det_box_thresh,
    text_det_unclip_ratio,
    text_rec_score_thresh,
    seal_det_limit_type,
    seal_det_limit_side_len,
    seal_det_thresh,
    seal_det_box_thresh,
    seal_det_unclip_ratio,
    seal_rec_score_thresh,
    use_ocr_results_with_table_cells,
    use_e2e_wired_table_rec_model,
    use_e2e_wireless_table_rec_model,
    use_wired_table_cells_trans_to_html,
    use_wireless_table_cells_trans_to_html,
    use_table_orientation_classify,
):
    """Process uploaded file with API"""
    try:
        if not file_path and not image_input:
            raise ValueError("Please upload a file first")
        if file_path:
            if Path(file_path).suffix == ".pdf":
                file_type = "pdf"
            else:
                file_type = "image"
        else:
            file_path = image_input
            file_type = "image"
        # Read file content
        with open(file_path, "rb") as f:
            file_bytes = f.read()

        # Call API for processing
        file_data = base64.b64encode(file_bytes).decode("ascii")
        headers = {
            "Authorization": f"token {TOKEN}",
            "Content-Type": "application/json",
        }

        response = requests.post(
            API_URL,
            json={
                "file": file_data,
                "fileType": 0 if file_type == "pdf" else 1,
                "useFormulaRecognition": use_formula_recognition,
                "useChartRecognition": use_chart_recognition,
                "useDocOrientationClassify": use_doc_orientation_classify,
                "useDocUnwarping": use_doc_unwarping,
                "useTextlineOrientation": use_textline_orientation,
                "useSealRecognition": use_seal_recognition,
                "useRegionDetection": use_region_detection,
                "useTableRecognition": use_table_recognition,
                "layoutThreshold": layout_threshold,
                "layoutNms": layout_nms,
                "layoutUnclipRatio": layout_unclip_ratio,
                "textDetLimitType": text_det_limit_type,
                "textTetLimitSideLen": text_det_limit_side_len,
                "textDetThresh": text_det_thresh,
                "textDetBoxThresh": text_det_box_thresh,
                "textDetUnclipRatio": text_det_unclip_ratio,
                "textRecScoreThresh": text_rec_score_thresh,
                "sealDetLimitType": seal_det_limit_type,
                "sealDetLimitSideLen": seal_det_limit_side_len,
                "sealDetThresh": seal_det_thresh,
                "sealDetBoxThresh": seal_det_box_thresh,
                "sealDetUnclipRatio": seal_det_unclip_ratio,
                "sealRecScoreThresh": seal_rec_score_thresh,
                "useOcrResultsWithTableCells": use_ocr_results_with_table_cells,
                "useE2eWiredTableRecModel": use_e2e_wired_table_rec_model,
                "useE2eWirelessTableRecModel": use_e2e_wireless_table_rec_model,
                "useWiredTableCellsTransToHtml": use_wired_table_cells_trans_to_html,
                "useWirelessWableCellsTransToHtml": use_wireless_table_cells_trans_to_html,
                "useTableOrientationClassify": use_table_orientation_classify,
            },
            headers=headers,
            timeout=1000,
        )
        try:
            response.raise_for_status()
        except requests.exceptions.RequestException as e:
            raise RuntimeError("API request failed") from e
        # Parse API response
        result = response.json()
        layout_results = result.get("result", {}).get("layoutParsingResults", [])
        layout_ordering_images = []
        layout_det_res_images = []
        overall_ocr_res_images = []
        output_json = result.get("result", {})
        markdown_texts = []
        markdown_images = []
        markdown_content_list = []
        input_images = []
        input_images_gallery = []
        for res in layout_results:
            layout_ordering_images.append(
                url_to_bytes(res["outputImages"]["layout_order_res"])
            )
            layout_det_res_images.append(
                url_to_bytes(res["outputImages"]["layout_det_res"])
            )
            overall_ocr_res_images.append(
                url_to_bytes(res["outputImages"]["overall_ocr_res"])
            )
            markdown = res["markdown"]
            markdown_text = markdown["text"]
            markdown_texts.append(markdown_text)
            img_path_to_url = markdown["images"]
            img_path_to_bytes = {}
            for path, url in img_path_to_url.items():
                img_path_to_bytes[path] = url_to_bytes(url)
            markdown_images.append(img_path_to_bytes)
            input_images.append(url_to_bytes(res["inputImage"]))
            input_images_gallery.append(res["inputImage"])
            markdown_content = embed_images_into_markdown_text(
                markdown_text, img_path_to_url
            )
            markdown_content_list.append(markdown_content)

        markdown_list = []
        for res, cont in zip(layout_results, markdown_content_list):
            markdown = res["markdown"].copy()
            markdown["text"] = cont
            markdown_list.append(markdown)
        concatenated_markdown_content = concatenate_markdown_pages(markdown_list)

        return {
            "original_file": file_path,
            "file_type": file_type,
            "layout_ordering_images": layout_ordering_images,
            "layout_det_res_images": layout_det_res_images,
            "overall_ocr_res_images": overall_ocr_res_images,
            "output_json": output_json,
            "markdown_texts": markdown_texts,
            "markdown_images": markdown_images,
            "markdown_content_list": markdown_content_list,
            "concatenated_markdown_content": concatenated_markdown_content,
            "input_images": input_images,
            "input_images_gallery": input_images_gallery,
            "api_response": result,
        }
    except Exception as e:
        raise gr.Error(f"Error processing file: {str(e)}")


def export_full_results(results):
    """Create ZIP file with all analysis results"""
    try:
        global tmp_time
        if not results:
            raise ValueError("No results to export")

        filename = Path(results["original_file"]).stem + f"_{uuid.uuid4().hex}.zip"
        zip_path = Path(TEMP_DIR.name, filename)

        with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zipf:
            for i, img_bytes in enumerate(results["layout_ordering_images"]):
                zipf.writestr(f"layout_ordering_images/page_{i+1}.jpg", img_bytes)

            for i, img_bytes in enumerate(results["layout_det_res_images"]):
                zipf.writestr(f"layout_det_res_images/page_{i+1}.jpg", img_bytes)

            for i, img_bytes in enumerate(results["overall_ocr_res_images"]):
                zipf.writestr(f"overall_ocr_res_images/page_{i+1}.jpg", img_bytes)

            zipf.writestr(
                "output.json",
                json.dumps(results["output_json"], indent=2, ensure_ascii=False),
            )

            for i, (md_text, md_imgs) in enumerate(
                zip(
                    results["markdown_texts"],
                    results["markdown_images"],
                )
            ):
                zipf.writestr(f"markdown/page_{i+1}.md", md_text)
                for img_path, img_bytes in md_imgs.items():
                    zipf.writestr(f"markdown/{img_path}", img_bytes)

            # Add API response
            api_response = results.get("api_response", {})
            zipf.writestr(
                "api_response.json",
                json.dumps(api_response, indent=2, ensure_ascii=False),
            )

            for i, img_bytes in enumerate(results["input_images"]):
                zipf.writestr(f"input_images/page_{i+1}.jpg", img_bytes)
        with lock:
            tmp_time[zip_path] = time.time()
        return str(zip_path)

    except Exception as e:
        raise gr.Error(f"Error creating ZIP file: {str(e)}")


def on_file_change(file):
    if file:
        return gr.Textbox(
            value=f"βœ… Chosen file:  {os.path.basename(file.name)}", visible=True
        )
    else:
        return gr.Textbox()


def clear_file_selection():
    return gr.File(value=None), gr.Textbox(value=None)


def clear_file_selection_examples(image_input):
    text_name = "βœ… Chosen file: " + os.path.basename(image_input)
    return gr.File(value=None), gr.Textbox(value=text_name, visible=True)


def toggle_sections(choice):
    return {
        Module_Options: gr.Column(visible=(choice == "Module Options")),
        Subpipeline_Options: gr.Column(visible=(choice == "Subpipeline Options")),
        Layout_region_detection_Options: gr.Column(
            visible=(choice == "Layout region detection Options")
        ),
        Text_detection_Options: gr.Column(visible=(choice == "Text detection Options")),
        Seal_text_recognition_Options: gr.Column(
            visible=(choice == "Seal text recognition Options")
        ),
        Table_recognition_Options: gr.Column(
            visible=(choice == "Table recognition Options")
        ),
    }


# Interaction logic
def toggle_spinner():
    return (
        gr.Column(visible=True),
        gr.Column(visible=False),
        gr.File(visible=False),
        gr.update(visible=False),
    )


def hide_spinner():
    return gr.Column(visible=False), gr.update(visible=True)


def update_display(results, concatenate_pages):
    if not results:
        return gr.skip()

    assert len(results["layout_ordering_images"]) <= MAX_NUM_PAGES, len(
        results["layout_ordering_images"]
    )
    assert len(results["layout_det_res_images"]) <= MAX_NUM_PAGES, len(
        results["layout_det_res_images"]
    )
    assert len(results["overall_ocr_res_images"]) <= MAX_NUM_PAGES, len(
        results["overall_ocr_res_images"]
    )
    assert len(results["input_images_gallery"]) <= MAX_NUM_PAGES, len(
        results["input_images_gallery"]
    )
    gallery_list_imgs = []
    for i in range(len(gallery_list)):
        gallery_list_imgs.append(
            gr.Gallery(
                value=results["input_images_gallery"],
                rows=len(results["input_images_gallery"]),
            )
        )

    layout_order_imgs = []
    for img in results["layout_ordering_images"]:
        layout_order_imgs.append(gr.Image(value=bytes_to_image(img), visible=True))
    for _ in range(len(results["layout_ordering_images"]), MAX_NUM_PAGES):
        layout_order_imgs.append(gr.Image(visible=False))

    layout_det_imgs = []
    for img in results["layout_det_res_images"]:
        layout_det_imgs.append(gr.Image(value=bytes_to_image(img), visible=True))
    for _ in range(len(results["layout_det_res_images"]), MAX_NUM_PAGES):
        layout_det_imgs.append(gr.Image(visible=False))

    ocr_imgs = []
    for img in results["overall_ocr_res_images"]:
        ocr_imgs.append(gr.Image(value=bytes_to_image(img), visible=True))
    for _ in range(len(results["overall_ocr_res_images"]), MAX_NUM_PAGES):
        ocr_imgs.append(gr.Image(visible=False))

    output_json = [gr.Markdown(value=results["output_json"], visible=True)]

    if concatenate_pages:
        markdown_content = results["concatenated_markdown_content"]
        ret_cont = [gr.Markdown(value=markdown_content, visible=True)]
        for _ in range(1, MAX_NUM_PAGES):
            ret_cont.append(gr.Markdown(visible=False))
    else:
        assert len(results["markdown_content_list"]) <= MAX_NUM_PAGES, len(
            results["markdown_content_list"]
        )
        ret_cont = []
        for cont in results["markdown_content_list"]:
            ret_cont.append(gr.Markdown(value=cont, visible=True))
        for _ in range(len(results["markdown_content_list"]), MAX_NUM_PAGES):
            ret_cont.append(gr.Markdown(visible=False))
    return (
        layout_order_imgs
        + layout_det_imgs
        + ocr_imgs
        + output_json
        + ret_cont
        + gallery_list_imgs
    )


def update_image(evt: gr.SelectData):
    update_images = []
    for index in range(MAX_NUM_PAGES):
        update_images.append(
            gr.Image(visible=False) if index != evt.index else gr.Image(visible=True)
        )
    return update_images


def update_markdown(concatenate_pages, evt: gr.SelectData):
    update_markdowns = []
    if not concatenate_pages:
        for index in range(MAX_NUM_PAGES):
            update_markdowns.append(
                gr.Markdown(visible=False)
                if index != evt.index
                else gr.Markdown(visible=True)
            )
    else:
        gr.Warning(
            "When page merging is on, the thumbnail-to-page linking is disabled. If you want to navigate to the corresponding page when clicking on the thumbnail, please turn off page merging."
        )
        for index in range(MAX_NUM_PAGES):
            update_markdowns.append(
                gr.Markdown(visible=True) if index == 0 else gr.Markdown(visible=False)
            )
    return update_markdowns


def delete_file_periodically():
    global tmp_time
    while True:
        current_time = time.time()
        delete_tmp = []
        for filename, strat_time in list(tmp_time.items()):
            if (current_time - strat_time) >= TMP_DELETE_TIME:
                if os.path.exists(filename):
                    os.remove(filename)
                    delete_tmp.append(filename)
        for filename in delete_tmp:
            with lock:
                del tmp_time[filename]
        time.sleep(THREAD_WAKEUP_TIME)


with gr.Blocks(css=CSS, title="Document Analysis System", theme=paddle_theme) as demo:
    results_state = gr.State()
    # Header with logo
    with gr.Column(elem_classes=["logo-container"]):
        gr.HTML(f'<img src="{LOGO_BASE64}" class="logo-img">')
        gr.Markdown(
            """
            Since our inference server is deployed in mainland China, cross-border
            network transmission may be slow, which could result in a suboptimal experience on Hugging Face.
            We recommend visiting the [PaddlePaddle AI Studio Community](https://aistudio.baidu.com/community/app/518494/webUI?source=appCenter) to try the demo for a smoother experience.
            """,
            elem_classes=["tight-spacing-as"],
            visible=True,
        )
    # Upload section
    with gr.Row():
        with gr.Column(scale=4):
            file_input = gr.File(
                label="Upload document",
                file_types=[".pdf", ".jpg", ".jpeg", ".png"],
                type="filepath",
                visible=False,
            )
            file_select = gr.Textbox(label="Select File Path", visible=False)
            image_input = gr.Image(
                label="Image",
                sources="upload",
                type="filepath",
                visible=False,
                interactive=True,
                placeholder="Click to upload image...",
            )
            pdf_btn = gr.Button(
                "Click to upload file...",
                variant="primary",
                icon="icon/upload.png",
                elem_classes=["square-pdf-btn"],
            )
            examples_image = gr.Examples(
                fn=clear_file_selection_examples,
                inputs=image_input,
                outputs=[file_input, file_select],
                examples_per_page=11,
                examples=EXAMPLES_TEST,
                run_on_click=True,
            )

            file_input.change(
                fn=on_file_change, inputs=file_input, outputs=[file_select]
            )
            concatenate_pages_md = gr.Markdown(
                "### Merge pages", elem_id="concatenate_pages_md"
            )
            concatenate_pages_rd = gr.Radio(
                choices=[("yes", True), ("no", False)],
                value=False,
                interactive=True,
                show_label=False,
                elem_id="concatenate_pages_rd",
            )
            with gr.Column():
                section_choice = gr.Dropdown(
                    choices=[
                        "Module Options",
                        "Subpipeline Options",
                        "Layout region detection Options",
                        "Text detection Options",
                        "Seal text recognition Options",
                        "Table recognition Options",
                    ],
                    value="Module Options",
                    label="Advance Options",
                    show_label=True,
                    container=True,
                    scale=0,
                    elem_classes=["tight-spacing"],
                )
                with gr.Column(
                    visible=True, elem_classes="left-margin-column"
                ) as Module_Options:
                    use_chart_recognition_md = gr.Markdown(
                        "### Using the chart parsing module",
                        elem_id="use_chart_recognition_md",
                    )
                    use_chart_recognition_rd = gr.Radio(
                        choices=[("yes", True), ("no", False)],
                        value=False,
                        interactive=True,
                        show_label=False,
                        elem_id="use_chart_recognition_rd",
                    )
                    use_region_detection_md = gr.Markdown(
                        "### Using the layout region detection module",
                        elem_id="use_region_detection_md",
                    )
                    use_region_detection_rd = gr.Radio(
                        choices=[("yes", True), ("no", False)],
                        value=True,
                        interactive=True,
                        show_label=False,
                        elem_id="use_region_detection_rd",
                    )
                    use_doc_orientation_classify_md = gr.Markdown(
                        "### Using the document image orientation classification module",
                        elem_id="use_doc_orientation_classify_md",
                    )
                    use_doc_orientation_classify_rd = gr.Radio(
                        choices=[("yes", True), ("no", False)],
                        value=False,
                        interactive=True,
                        show_label=False,
                        elem_id="use_doc_orientation_classify_rd",
                    )
                    use_doc_unwarping_md = gr.Markdown(
                        "### Using the document unwarping module",
                        elem_id="use_doc_unwarping_md",
                    )
                    use_doc_unwarping_rd = gr.Radio(
                        choices=[("yes", True), ("no", False)],
                        value=False,
                        interactive=True,
                        show_label=False,
                        elem_id="use_doc_unwarping_rd",
                    )
                    use_textline_orientation_md = gr.Markdown(
                        "### Using the text line orientation classification module",
                        elem_id="use_textline_orientation_md",
                    )
                    use_textline_orientation_rd = gr.Radio(
                        choices=[("yes", True), ("no", False)],
                        value=False,
                        interactive=True,
                        show_label=False,
                        elem_id="use_textline_orientation_rd",
                    )
                with gr.Column(
                    visible=False, elem_classes="left-margin-column"
                ) as Subpipeline_Options:
                    use_seal_recognition_md = gr.Markdown(
                        "### Using the seal text recognition subpipeline",
                        elem_id="use_seal_recognition_md",
                    )
                    use_seal_recognition_rd = gr.Radio(
                        choices=[("yes", True), ("no", False)],
                        value=True,
                        interactive=True,
                        show_label=False,
                        elem_id="use_seal_recognition_rd",
                    )
                    use_formula_recognition_md = gr.Markdown(
                        "### Using the formula recognition subpipeline",
                        elem_id="use_formula_recognition_md",
                    )
                    use_formula_recognition_rd = gr.Radio(
                        choices=[("yes", True), ("no", False)],
                        value=True,
                        interactive=True,
                        show_label=False,
                        elem_id="use_formula_recognition_rd",
                    )
                    use_table_recognition_md = gr.Markdown(
                        "### Using the table recognition subpipeline",
                        elem_id="use_table_recognition_md",
                    )
                    use_table_recognition_rd = gr.Radio(
                        choices=[("yes", True), ("no", False)],
                        value=True,
                        interactive=True,
                        show_label=False,
                        elem_id="use_table_recognition_rd",
                    )
                with gr.Column(
                    visible=False, elem_classes="left-margin-column"
                ) as Layout_region_detection_Options:
                    layout_threshold_md = gr.Markdown(
                        "### Score threshold of layout region detection model",
                        elem_id="layout_threshold_md",
                    )
                    layout_threshold_nb = gr.Number(
                        value=0.5,
                        step=0.1,
                        minimum=0,
                        maximum=1,
                        interactive=True,
                        show_label=False,
                        elem_id="layout_threshold_nb",
                    )
                    layout_nms_md = gr.Markdown(
                        "### NMS post-processing of layout region detection",
                        elem_id="layout_nms_md",
                    )
                    layout_nms_rd = gr.Radio(
                        choices=[("yes", True), ("no", False)],
                        value=True,
                        interactive=True,
                        show_label=False,
                        elem_id="layout_nms_rd",
                    )
                    layout_unclip_ratio_md = gr.Markdown(
                        "### Layout region detection expansion coefficient",
                        elem_id="layout_unclip_ratio_md",
                    )
                    layout_unclip_ratio_nb = gr.Number(
                        value=1.0,
                        step=0.1,
                        minimum=0,
                        maximum=10.0,
                        interactive=True,
                        show_label=False,
                        elem_id="layout_unclip_ratio_nb",
                    )
                with gr.Column(
                    visible=False, elem_classes="left-margin-column"
                ) as Text_detection_Options:
                    text_det_limit_type_md = gr.Markdown(
                        "### Image side length restriction type for text detection",
                        elem_id="text_det_limit_type_md",
                    )
                    text_det_limit_type_rd = gr.Radio(
                        choices=[("Short side", "min"), ("Long side", "max")],
                        value="min",
                        interactive=True,
                        show_label=False,
                        elem_id="text_det_limit_type_rd",
                    )
                    text_det_limit_side_len_md = gr.Markdown(
                        "### Image side length limitation for text detection",
                        elem_id="text_det_limit_side_len_md",
                    )
                    text_det_limit_side_len_nb = gr.Number(
                        value=736,
                        step=1,
                        minimum=0,
                        maximum=10000,
                        interactive=True,
                        show_label=False,
                        elem_id="text_det_limit_side_len_nb",
                    )
                    text_det_thresh_md = gr.Markdown(
                        "### Text detection pixel threshold",
                        elem_id="text_det_thresh_md",
                    )
                    text_det_thresh_nb = gr.Number(
                        value=0.30,
                        step=0.01,
                        minimum=0.00,
                        maximum=1.00,
                        interactive=True,
                        show_label=False,
                        elem_id="text_det_thresh_nb",
                    )
                    text_det_box_thresh_md = gr.Markdown(
                        "### Text detection box threshold",
                        elem_id="text_det_box_thresh_md",
                    )
                    text_det_box_thresh_nb = gr.Number(
                        value=0.60,
                        step=0.01,
                        minimum=0.00,
                        maximum=1.00,
                        interactive=True,
                        show_label=False,
                        elem_id="text_det_box_thresh_nb",
                    )
                    text_det_unclip_ratio_md = gr.Markdown(
                        "### Text detection unclip ratio",
                        elem_id="text_det_unclip_ratio_md",
                    )
                    text_det_unclip_ratio_nb = gr.Number(
                        value=1.5,
                        step=0.1,
                        minimum=0,
                        maximum=10.0,
                        interactive=True,
                        show_label=False,
                        elem_id="text_det_unclip_ratio_nb",
                    )

                    text_rec_score_thresh_md = gr.Markdown(
                        "### Text recognition score threshold",
                        elem_id="text_rec_score_thresh_md",
                    )
                    text_rec_score_thresh_nb = gr.Number(
                        value=0.00,
                        step=0.01,
                        minimum=0,
                        maximum=1.00,
                        interactive=True,
                        show_label=False,
                        elem_id="text_rec_score_thresh_nb",
                    )

                with gr.Column(
                    visible=False, elem_classes="left-margin-column"
                ) as Seal_text_recognition_Options:
                    seal_det_limit_type_md = gr.Markdown(
                        "### Image side length restriction type for seal text detection",
                        elem_id="seal_det_limit_type_md",
                    )
                    seal_det_limit_type_rd = gr.Radio(
                        choices=[("Short side", "min"), ("Long side", "max")],
                        value="min",
                        interactive=True,
                        show_label=False,
                        elem_id="seal_det_limit_type_rd",
                    )
                    seal_det_limit_side_len_md = gr.Markdown(
                        "### Image side length limitation for seal text detection",
                        elem_id="seal_det_limit_side_len_md",
                    )
                    seal_det_limit_side_len_nb = gr.Number(
                        value=736,
                        step=1,
                        minimum=0,
                        maximum=10000,
                        interactive=True,
                        show_label=False,
                        elem_id="seal_det_limit_side_len_nb",
                    )
                    seal_det_thresh_md = gr.Markdown(
                        "### Pixel threshold for seal text detection",
                        elem_id="seal_det_thresh_md",
                    )
                    seal_det_thresh_nb = gr.Number(
                        value=0.20,
                        step=0.01,
                        minimum=0.00,
                        maximum=1.00,
                        interactive=True,
                        show_label=False,
                        elem_id="seal_det_thresh_nb",
                    )
                    seal_det_box_thresh_md = gr.Markdown(
                        "### Seal text detection box threshold",
                        elem_id="seal_det_box_thresh_md",
                    )
                    seal_det_box_thresh_nb = gr.Number(
                        value=0.60,
                        step=0.01,
                        minimum=0.00,
                        maximum=1.00,
                        interactive=True,
                        show_label=False,
                        elem_id="seal_det_box_thresh_nb",
                    )
                    seal_det_unclip_ratio_md = gr.Markdown(
                        "### Seal text detection unclip ratio",
                        elem_id="seal_det_unclip_ratio_md",
                    )
                    seal_det_unclip_ratio_nb = gr.Number(
                        value=0.5,
                        step=0.1,
                        minimum=0,
                        maximum=10.0,
                        interactive=True,
                        show_label=False,
                        elem_id="seal_det_unclip_ratio_nb",
                    )
                    seal_rec_score_thresh_md = gr.Markdown(
                        "### Seal text detection threshold",
                        elem_id="seal_rec_score_thresh_md",
                    )
                    seal_rec_score_thresh_nb = gr.Number(
                        value=0.00,
                        step=0.01,
                        minimum=0,
                        maximum=1.00,
                        interactive=True,
                        show_label=False,
                        elem_id="seal_rec_score_thresh_nb",
                    )
                with gr.Column(
                    visible=False, elem_classes="left-margin-column"
                ) as Table_recognition_Options:
                    use_ocr_results_with_table_cells_md = gr.Markdown(
                        "### Cell OCR mode",
                        elem_id="use_ocr_results_with_table_cells_md",
                    )
                    use_ocr_results_with_table_cells_rd = gr.Radio(
                        choices=[("yes", True), ("no", False)],
                        value=True,
                        interactive=True,
                        show_label=False,
                        elem_id="use_ocr_results_with_table_cells_rd",
                    )
                    use_e2e_wired_table_rec_model_md = gr.Markdown(
                        "### Wired Table End-to-End Prediction model",
                        elem_id="use_e2e_wired_table_rec_model_md",
                    )
                    use_e2e_wired_table_rec_model_rd = gr.Radio(
                        choices=[("yes", True), ("no", False)],
                        value=False,
                        interactive=True,
                        show_label=False,
                        elem_id="use_e2e_wired_table_rec_model_rd",
                    )
                    use_e2e_wireless_table_rec_model_md = gr.Markdown(
                        "### Wireless Table End-to-End Prediction model",
                        elem_id="use_e2e_wireless_table_rec_model_md",
                    )
                    use_e2e_wireless_table_rec_model_rd = gr.Radio(
                        choices=[("yes", True), ("no", False)],
                        value=False,
                        interactive=True,
                        show_label=False,
                        elem_id="use_e2e_wireless_table_rec_model_rd",
                    )
                    use_wired_table_cells_trans_to_html_md = gr.Markdown(
                        "### Wired table to HTML mode",
                        elem_id="use_wired_table_cells_trans_to_html_md",
                    )
                    use_wired_table_cells_trans_to_html_rd = gr.Radio(
                        choices=[("yes", True), ("no", False)],
                        value=False,
                        interactive=True,
                        show_label=False,
                        elem_id="use_wired_table_cells_trans_to_html_rd",
                    )
                    use_wireless_table_cells_trans_to_html_md = gr.Markdown(
                        "### Wireless table to HTML mode",
                        elem_id="use_wireless_table_cells_trans_to_html_md",
                    )
                    use_wireless_table_cells_trans_to_html_rd = gr.Radio(
                        choices=[("yes", True), ("no", False)],
                        value=False,
                        interactive=True,
                        show_label=False,
                        elem_id="use_wireless_table_cells_trans_to_html_rd",
                    )
                    use_table_orientation_classify_md = gr.Markdown(
                        "### Using table orientation classify module",
                        elem_id="use_table_orientation_classify_md",
                    )
                    use_table_orientation_classify_rd = gr.Radio(
                        choices=[("yes", True), ("no", False)],
                        value=True,
                        interactive=True,
                        show_label=False,
                        elem_id="use_table_orientation_classify_rd",
                    )
            with gr.Row():
                process_btn = gr.Button(
                    "πŸš€ Parse Document", elem_id="analyze-btn", variant="primary"
                )
                download_all_btn = gr.Button(
                    "πŸ“¦ Download Full Results (ZIP)",
                    elem_id="unzip-btn",
                    variant="primary",
                )
            gr.Markdown(
                f"""
                1. Only the first {MAX_NUM_PAGES} pages will be processed.
                2. Some formulas might not display correctly because of renderer limitations or syntax errors.
                """
            )

        # Results display section
        with gr.Column(scale=7):
            gr.Markdown("### Results", elem_classes="custom-markdown")
            loading_spinner = gr.Column(
                visible=False, elem_classes=["loader-container"]
            )
            with loading_spinner:
                gr.HTML(
                    """
                <div class="loader"></div>
                <p>Processing, please wait...</p>
                """
                )
            prepare_spinner = gr.Column(
                visible=True, elem_classes=["loader-container-prepare"]
            )
            with prepare_spinner:
                gr.HTML(
                    """
                <div style="
                    max-width: 100%;
                    max-height: 100%;
                    margin: 24px 0 0 12px;
                    padding: 24px 32px;
                    border: 2px solid #A8C1E7;
                    border-radius: 12px;
                    background: #f8faff;
                    box-shadow: 0 2px 8px rgba(100,150,200,0.08);
                    font-size: 18px;
                ">
                    <b>πŸš€ User Guide</b><br>
                    <b>Step 1:</b> Upload Your File<br>
                    Supported formats: JPG, PNG, PDF, JPEG<br>
                    <b>Step 2:</b> Click Analyze Document Button<br>
                    System will process automatically<br>
                    <b>Step 3:</b> Wait for Results<br>
                    Results will be displayed after processing<br>
                    <b>Step 4:</b> Download results zip<br>
                    Results zip will be displayed after processing<br>
                </div>
                """
                )
            download_file = gr.File(visible=False, label="Download File")
            markdown_display_list = []
            layout_ordering_images = []
            layout_det_res_images = []
            overall_ocr_res_images = []
            output_json_list = []
            gallery_list = []
            with gr.Tabs(visible=False) as tabs:
                with gr.Tab("Layout Parsing"):
                    with gr.Row():
                        with gr.Column(scale=2, min_width=1):
                            gallery_markdown = gr.Gallery(
                                show_label=False,
                                allow_preview=False,
                                preview=False,
                                columns=1,
                                min_width=10,
                                object_fit="contain",
                                visible=True,
                            )
                            gallery_list.append(gallery_markdown)
                        with gr.Column(scale=10):
                            for i in range(MAX_NUM_PAGES):
                                markdown_display_list.append(
                                    gr.Markdown(
                                        visible=False,
                                        container=True,
                                        show_copy_button=True,
                                        latex_delimiters=[
                                            {
                                                "left": "$$",
                                                "right": "$$",
                                                "display": True,
                                            },
                                            {
                                                "left": "$",
                                                "right": "$",
                                                "display": False,
                                            },
                                        ],
                                        elem_classes=["image-container"],
                                    )
                                )
                with gr.Tab("Reading Order"):
                    with gr.Row():
                        with gr.Column(scale=2, min_width=1):
                            gallery_layout_order = gr.Gallery(
                                show_label=False,
                                allow_preview=False,
                                preview=False,
                                columns=1,
                                min_width=10,
                                object_fit="contain",
                            )
                            gallery_list.append(gallery_layout_order)
                        with gr.Column(scale=10):
                            for i in range(MAX_NUM_PAGES):
                                layout_ordering_images.append(
                                    gr.Image(
                                        label=f"Layout Ordering Image {i}",
                                        show_label=True,
                                        visible=False,
                                        container=True,
                                    )
                                )
                with gr.Tab("Layout Region Detection"):
                    with gr.Row():
                        with gr.Column(scale=2, min_width=1):
                            gallery_layout_det = gr.Gallery(
                                show_label=False,
                                allow_preview=False,
                                preview=False,
                                columns=1,
                                min_width=10,
                                object_fit="contain",
                            )
                            gallery_list.append(gallery_layout_det)
                        with gr.Column(scale=10):
                            for i in range(MAX_NUM_PAGES):
                                layout_det_res_images.append(
                                    gr.Image(
                                        label=f"Layout Detection Image {i}",
                                        show_label=True,
                                        visible=False,
                                    )
                                )
                with gr.Tab("OCR"):
                    with gr.Row():
                        with gr.Column(scale=2, min_width=1):
                            gallery_ocr_det = gr.Gallery(
                                show_label=False,
                                allow_preview=False,
                                preview=False,
                                columns=1,
                                min_width=10,
                                object_fit="contain",
                            )
                            gallery_list.append(gallery_ocr_det)
                        with gr.Column(scale=10):
                            for i in range(MAX_NUM_PAGES):
                                overall_ocr_res_images.append(
                                    gr.Image(
                                        label=f"OCR Image {i}",
                                        show_label=True,
                                        visible=False,
                                    )
                                )
                with gr.Tab("JSON"):
                    with gr.Row():
                        with gr.Column(scale=2, min_width=1):
                            gallery_json = gr.Gallery(
                                show_label=False,
                                allow_preview=False,
                                preview=False,
                                columns=1,
                                min_width=10,
                                object_fit="contain",
                            )
                            gallery_list.append(gallery_json)
                        with gr.Column(scale=10):
                            gr.HTML(
                                """
                            <style>
                            .line.svelte-19ir0ev svg {
                                width: 30px !important;
                                height: 30px !important;
                                min-width: 30px !important;
                                min-height: 30px !important;
                                padding: 0 !important;
                                font-size: 18px !important;
                            }
                            .line.svelte-19ir0ev span:contains('Object(') {
                                font-size: 12px;
                                }
                            </style>
                            """
                            )
                            output_json_list.append(
                                gr.JSON(
                                    visible=False,
                                )
                            )
    # # Navigation bar
    with gr.Column(elem_classes=["nav-bar"]):
        gr.HTML(
            """
        <div class="nav-links">
            <a href="https://github.com/PaddlePaddle/PaddleOCR" class="nav-link" target="_blank">GitHub</a>
        </div>
        """
        )

    section_choice.change(
        fn=toggle_sections,
        inputs=section_choice,
        outputs=[
            Module_Options,
            Subpipeline_Options,
            Layout_region_detection_Options,
            Text_detection_Options,
            Seal_text_recognition_Options,
            Table_recognition_Options,
        ],
    )
    pdf_btn.click(
        fn=clear_file_selection, inputs=[], outputs=[file_input, file_select]
    ).then(
        None,
        [],
        [],
        js="""
        () => {
            const fileInput = document.querySelector('input[type="file"]');
            fileInput.value = '';
            fileInput.click();
        }
    """,
    )
    process_btn.click(
        toggle_spinner, outputs=[loading_spinner, prepare_spinner, download_file, tabs]
    ).then(
        process_file,
        inputs=[
            file_input,
            image_input,
            use_formula_recognition_rd,
            use_chart_recognition_rd,
            use_doc_orientation_classify_rd,
            use_doc_unwarping_rd,
            use_textline_orientation_rd,
            use_region_detection_rd,
            use_seal_recognition_rd,
            use_table_recognition_rd,
            layout_threshold_nb,
            layout_nms_rd,
            layout_unclip_ratio_nb,
            text_det_limit_type_rd,
            text_det_limit_side_len_nb,
            text_det_thresh_nb,
            text_det_box_thresh_nb,
            text_det_unclip_ratio_nb,
            text_rec_score_thresh_nb,
            seal_det_limit_type_rd,
            seal_det_limit_side_len_nb,
            seal_det_thresh_nb,
            seal_det_box_thresh_nb,
            seal_det_unclip_ratio_nb,
            seal_rec_score_thresh_nb,
            use_ocr_results_with_table_cells_rd,
            use_e2e_wired_table_rec_model_rd,
            use_e2e_wireless_table_rec_model_rd,
            use_wired_table_cells_trans_to_html_rd,
            use_wireless_table_cells_trans_to_html_rd,
            use_table_orientation_classify_rd,
        ],
        outputs=[results_state],
    ).then(
        hide_spinner, outputs=[loading_spinner, tabs]
    ).then(
        update_display,
        inputs=[results_state, concatenate_pages_rd],
        outputs=layout_ordering_images
        + layout_det_res_images
        + overall_ocr_res_images
        + output_json_list
        + markdown_display_list
        + gallery_list,
    )

    gallery_markdown.select(
        update_markdown,
        inputs=concatenate_pages_rd,
        outputs=markdown_display_list,
    )
    gallery_layout_order.select(update_image, outputs=layout_ordering_images)
    gallery_layout_det.select(update_image, outputs=layout_det_res_images)
    gallery_ocr_det.select(update_image, outputs=overall_ocr_res_images)

    download_all_btn.click(
        export_full_results, inputs=[results_state], outputs=[download_file]
    ).success(lambda: gr.File(visible=True), outputs=[download_file])

    demo.load(
        fn=lambda: None,
        inputs=[],
        outputs=[],
        js=f"""
        () => {{
            const tooltipTexts = {TOOLTIP_RADIO};
            let tooltip = document.getElementById("custom-tooltip");
            if (!tooltip) {{
                tooltip = document.createElement("div");
                tooltip.id = "custom-tooltip";
                tooltip.style.position = "fixed";
                tooltip.style.background = "rgba(0, 0, 0, 0.75)";
                tooltip.style.color = "white";
                tooltip.style.padding = "6px 10px";
                tooltip.style.borderRadius = "4px";
                tooltip.style.fontSize = "13px";
                tooltip.style.maxWidth = "300px";
                tooltip.style.zIndex = "10000";
                tooltip.style.pointerEvents = "none";
                tooltip.style.transition = "opacity 0.2s";
                tooltip.style.opacity = "0";
                tooltip.style.whiteSpace = "normal";
                document.body.appendChild(tooltip);
            }}
            Object.keys(tooltipTexts).forEach(id => {{
                const elem = document.getElementById(id);
                if (!elem) return;
                function showTooltip(e) {{
                    tooltip.style.opacity = "1";
                    tooltip.innerText = tooltipTexts[id];
                    let x = e.clientX + 10;
                    let y = e.clientY + 10;
                    if (x + tooltip.offsetWidth > window.innerWidth) {{
                        x = e.clientX - tooltip.offsetWidth - 10;
                    }}
                    if (y + tooltip.offsetHeight > window.innerHeight) {{
                        y = e.clientY - tooltip.offsetHeight - 10;
                    }}
                    tooltip.style.left = x + "px";
                    tooltip.style.top = y + "px";
                }}

                function hideTooltip() {{
                    tooltip.style.opacity = "0";
                }}

                elem.addEventListener("mousemove", showTooltip);
                elem.addEventListener("mouseleave", hideTooltip);
            }});
        }}
        """,
    )


if __name__ == "__main__":
    t = threading.Thread(target=delete_file_periodically)
    t.start()
    demo.launch(
        server_name="0.0.0.0",
        server_port=7860,
    )