File size: 120,648 Bytes
a33ba6c
 
 
 
 
 
 
 
e4615c4
10128bc
e4615c4
 
10128bc
 
 
052564a
a33ba6c
 
 
 
 
 
 
 
 
 
 
 
30e5400
a33ba6c
 
 
 
10128bc
 
a33ba6c
15a8e6e
8a9992f
052564a
 
e0663da
82cc547
83839e0
5997297
15a8e6e
242d2f6
 
 
 
ecf3b5a
242d2f6
 
 
 
 
5997297
242d2f6
 
 
 
 
 
 
15a8e6e
44c9429
7013b67
 
 
 
 
 
 
 
 
 
052564a
7013b67
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cc0ae3f
7013b67
 
 
 
 
052564a
a33ba6c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7031d55
 
 
a33ba6c
30e5400
7031d55
a33ba6c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10128bc
a33ba6c
 
 
 
 
 
 
 
 
 
 
 
da6797b
a33ba6c
13fb83e
7031d55
a33ba6c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7031d55
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a33ba6c
 
 
 
 
 
 
 
7031d55
a33ba6c
 
 
 
 
 
 
 
 
7031d55
 
a33ba6c
 
 
 
 
 
7031d55
a33ba6c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7031d55
a33ba6c
7031d55
a33ba6c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7031d55
a33ba6c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7031d55
 
a33ba6c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7031d55
 
a33ba6c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7031d55
 
 
 
 
 
 
 
 
 
a33ba6c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eff29ba
a33ba6c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e2ef6e1
 
 
 
 
39c4ab6
e2ef6e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
052564a
e2ef6e1
 
 
 
 
a33ba6c
e2ef6e1
 
7031d55
e2ef6e1
 
 
a33ba6c
e2ef6e1
 
 
a33ba6c
e2ef6e1
 
 
 
 
 
a33ba6c
e2ef6e1
a33ba6c
e2ef6e1
 
 
 
 
 
7031d55
e2ef6e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a33ba6c
 
e2ef6e1
 
 
a33ba6c
e2ef6e1
a33ba6c
 
 
e2ef6e1
 
 
 
 
a33ba6c
e2ef6e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a33ba6c
e2ef6e1
7031d55
e2ef6e1
7031d55
 
acaca02
7031d55
e2ef6e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a33ba6c
 
 
 
 
 
e2ef6e1
a33ba6c
 
e2ef6e1
a33ba6c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e2ef6e1
a33ba6c
 
 
 
 
 
e2ef6e1
242d2f6
 
 
 
a33ba6c
242d2f6
 
a33ba6c
242d2f6
 
a33ba6c
242d2f6
 
a33ba6c
 
 
 
 
 
 
 
 
 
242d2f6
a33ba6c
 
 
 
 
 
 
 
5997297
a33ba6c
 
 
 
e2ef6e1
a33ba6c
 
 
 
e2ef6e1
 
a33ba6c
e2ef6e1
 
a33ba6c
e2ef6e1
 
 
 
 
 
 
 
 
a33ba6c
 
e2ef6e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
242d2f6
 
 
 
a33ba6c
242d2f6
 
a33ba6c
242d2f6
 
e2ef6e1
242d2f6
 
e2ef6e1
 
 
a33ba6c
e2ef6e1
 
 
6b0a48b
a33ba6c
e2ef6e1
242d2f6
e2ef6e1
 
 
 
 
 
 
 
5997297
e2ef6e1
 
a33ba6c
e2ef6e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d9f6fc2
e2ef6e1
 
 
 
 
ea1ae6c
 
e2ef6e1
a29a783
 
e2ef6e1
d9f6fc2
e2ef6e1
10128bc
a33ba6c
 
 
 
5e73a2e
a33ba6c
fcf7255
5e73a2e
10128bc
 
a33ba6c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10128bc
 
 
 
 
 
a33ba6c
 
 
 
 
 
052564a
a33ba6c
 
 
 
b539e20
5aa9ee2
a33ba6c
 
fcf7255
a33ba6c
 
 
5aa9ee2
10128bc
a33ba6c
 
 
 
 
 
 
 
 
 
fcf7255
 
a33ba6c
 
 
 
 
 
10128bc
 
 
a33ba6c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10128bc
a33ba6c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10128bc
7031d55
 
fcf7255
7031d55
 
fcf7255
7031d55
a33ba6c
10128bc
a33ba6c
 
 
696e934
5e73a2e
a33ba6c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fbfef95
 
fcf7255
10128bc
 
fbfef95
fcf7255
fbfef95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fcf7255
fbfef95
 
 
 
 
 
 
 
 
 
e4615c4
fbfef95
 
 
 
 
 
 
 
10128bc
fbfef95
10128bc
fbfef95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fcf7255
fbfef95
 
fcf7255
10128bc
fbfef95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fcf7255
fbfef95
 
 
 
 
 
 
 
 
 
e4615c4
fbfef95
 
 
 
 
 
 
 
10128bc
fbfef95
 
 
 
 
 
 
fcf7255
fbfef95
 
 
 
10128bc
fbfef95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10128bc
fbfef95
10128bc
fbfef95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10128bc
 
 
fbfef95
 
10128bc
 
 
fbfef95
 
80b83ba
10128bc
 
 
052564a
80b83ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
052564a
80b83ba
 
 
 
 
 
 
 
 
 
 
 
 
10128bc
80b83ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dca685a
80b83ba
 
dca685a
 
80b83ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7031d55
80b83ba
7031d55
 
80b83ba
7031d55
10128bc
 
 
 
 
80b83ba
 
 
dca685a
 
 
 
 
80b83ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10128bc
80b83ba
dca685a
 
80b83ba
 
10128bc
80b83ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e4615c4
80b83ba
 
 
 
 
 
 
 
10128bc
80b83ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10128bc
80b83ba
dca685a
 
 
 
80b83ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e4615c4
80b83ba
 
 
 
 
 
 
 
10128bc
80b83ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10128bc
 
 
80b83ba
 
10128bc
 
 
 
80b83ba
dca685a
80b83ba
c2a2cf9
6c5993a
052564a
04f4367
d48c776
16c35c7
d48c776
052564a
d48c776
 
 
10128bc
 
d48c776
 
 
 
 
 
 
 
16c35c7
d48c776
 
 
052564a
d48c776
 
 
 
 
052564a
d48c776
 
 
052564a
d48c776
 
 
052564a
5997297
d48c776
052564a
d48c776
 
 
052564a
d48c776
 
052564a
d48c776
 
 
052564a
50629a4
d48c776
 
10128bc
d48c776
 
 
 
 
 
 
052564a
 
 
d48c776
 
052564a
d48c776
 
 
052564a
d48c776
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2b772a2
d48c776
 
 
2b772a2
052564a
 
d48c776
adb75eb
d48c776
 
 
 
 
052564a
d48c776
 
 
052564a
d48c776
 
 
 
 
052564a
d48c776
 
 
 
052564a
d48c776
 
 
 
 
052564a
d48c776
 
052564a
d48c776
 
 
 
 
 
 
052564a
d48c776
7031d55
052564a
7031d55
 
052564a
7031d55
d48c776
adb75eb
d48c776
 
adb75eb
 
d48c776
adb75eb
 
d48c776
 
 
052564a
d48c776
 
 
 
 
052564a
d48c776
 
 
 
052564a
d48c776
 
 
 
 
 
 
 
 
052564a
d48c776
 
052564a
d48c776
 
 
 
 
 
 
04f4367
d48c776
 
 
 
052564a
 
d48c776
052564a
d48c776
 
 
 
 
052564a
d48c776
052564a
d48c776
 
 
 
 
 
 
 
 
 
 
 
052564a
d48c776
 
 
 
 
052564a
adb75eb
d48c776
 
 
 
052564a
d48c776
 
052564a
d48c776
 
052564a
d48c776
 
052564a
d48c776
 
052564a
d48c776
 
 
052564a
 
d48c776
 
e4615c4
d48c776
 
 
 
 
 
 
 
 
 
 
 
052564a
d48c776
10128bc
 
052564a
d48c776
 
 
 
 
052564a
d48c776
 
052564a
d48c776
 
052564a
d48c776
 
 
 
 
 
 
052564a
adb75eb
d48c776
adb75eb
d48c776
 
 
 
052564a
6c5993a
d48c776
052564a
d48c776
 
 
 
 
052564a
d48c776
052564a
d48c776
 
 
 
 
 
 
 
 
 
052564a
d48c776
 
 
 
 
 
 
052564a
adb75eb
d48c776
 
 
 
052564a
d48c776
 
052564a
d48c776
 
052564a
d48c776
 
052564a
d48c776
 
052564a
d48c776
 
 
052564a
 
d48c776
adb75eb
e4615c4
d48c776
 
 
 
 
 
 
 
 
 
 
 
052564a
d48c776
10128bc
 
052564a
 
d48c776
 
 
 
052564a
d48c776
 
 
 
 
052564a
d48c776
 
 
 
 
 
 
052564a
d48c776
 
 
 
adb75eb
 
 
 
 
 
 
 
052564a
adb75eb
 
052564a
d48c776
 
052564a
6c5993a
d48c776
 
 
 
 
 
052564a
d48c776
052564a
d48c776
 
 
 
 
 
 
 
 
 
052564a
d48c776
 
052564a
d48c776
 
 
 
adb75eb
d48c776
adb75eb
 
d48c776
10128bc
 
 
 
 
 
 
a355392
10128bc
de9e0be
 
f27526e
10128bc
 
 
f27526e
de9e0be
 
 
 
7031d55
 
 
 
b5fe2ac
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
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
# -*- coding: utf-8 -*-
"""Copy of FindSpecsTrial(Retrieving+boundingBoxes)-InitialMarkups(ALL)_CleanedUp.ipynb

Automatically generated by Colab.

Original file is located at
    https://colab.research.google.com/drive/12XfVkmKmN3oVjHhLVE0_GgkftgArFEK2
"""
baselink='https://adr.trevorsadd.co.uk/api/view-pdf?'

newlink='https://adr.trevorsadd.co.uk/api/view-highlight?'
tobebilledonlyLink='https://adr.trevorsadd.co.uk/api/view-pdf-tobebilled?'

    


from urllib.parse import urlparse, unquote
import os
from io import BytesIO
import re
import requests
import pandas as pd
import fitz  # PyMuPDF
import re
import urllib.parse
import pandas as pd
import math
import random
import json
from datetime import datetime
from collections import defaultdict, Counter
import difflib
from fuzzywuzzy import fuzz
import copy
import tsadropboxretrieval

import urllib.parse

top_margin = 70
bottom_margin = 85

def changepdflinks(json_data, pdf_path):
    print('ll , ' ,json_data,pdf_path)
    # base_viewer_link = "https://findconsole-initialmarkups.hf.space/view-pdf?"

    updated_json = []
    for entry in json_data:
        # Extract needed fields
        zoom_str = entry.get("NBSLink", "")
        page_str=entry.get("Page","")
        
        # Encode the pdf link safely for URL usage
        encoded_pdf_link = urllib.parse.quote(pdf_path, safe='')

        # Construct the final link
        final_url = f"{baselink}pdfLink={encoded_pdf_link}#page={str(page_str)}&zoom={zoom_str}"

        # Replace the old NBSLink value with the full URL
        entry["NBSLink"] = final_url

        updated_json.append(entry)

    return updated_json



def get_toc_page_numbers(doc, max_pages_to_check=15):
    toc_pages = []

    # 1. Existing Dot Pattern (looking for ".....")
    dot_pattern = re.compile(r"\.{2,}")

    # 2. NEW: Title Pattern (looking for specific headers)
    # ^ and $ ensure the line is JUST that word (ignoring "The contents of the bag...")
    # re.IGNORECASE makes it match "CONTENTS", "Contents", "Index", etc.
    title_pattern = re.compile(r"^\s*(table of contents|contents|index)\s*$", re.IGNORECASE)

    for page_num in range(min(len(doc), max_pages_to_check)):
        page = doc.load_page(page_num)
        blocks = page.get_text("dict")["blocks"]

        dot_line_count = 0
        has_toc_title = False

        for block in blocks:
            for line in block.get("lines", []):
                # Extract text from spans (mimicking get_spaced_text_from_spans)
                line_text = " ".join([span["text"] for span in line["spans"]]).strip()

                # CHECK A: Does the line have dots?
                if dot_pattern.search(line_text):
                    dot_line_count += 1

                # CHECK B: Is this line a Title?
                # We check this early in the loop. If a page has a title "Contents",
                # we mark it immediately.
                if title_pattern.match(line_text):
                    has_toc_title = True

        # CONDITION:
        # It is a TOC page if it has a Title OR if it has dot leaders.
        # We use 'dot_line_count >= 1' to be sensitive to single-item lists.
        if has_toc_title or dot_line_count >= 1:
            toc_pages.append(page_num)

    # RETURN:
    # If we found TOC pages (e.g., [2, 3]), we return [0, 1, 2, 3]
    # This covers the cover page, inside cover, and the TOC itself.
    if toc_pages:
        last_toc_page = toc_pages[0]
        return list(range(0, last_toc_page + 1))

    return [] # Return empty list if nothing found



def get_regular_font_size_and_color(doc):
    font_sizes = []
    colors = []
    fonts = []

    # Loop through all pages
    for page_num in range(len(doc)):
        page = doc.load_page(page_num)
        for span in page.get_text("dict")["blocks"]:
            if "lines" in span:
                for line in span["lines"]:
                    for span in line["spans"]:
                        font_sizes.append(span['size'])
                        colors.append(span['color'])
                        fonts.append(span['font'])

    # Get the most common font size, color, and font
    most_common_font_size = Counter(font_sizes).most_common(1)[0][0] if font_sizes else None
    most_common_color = Counter(colors).most_common(1)[0][0] if colors else None
    most_common_font = Counter(fonts).most_common(1)[0][0] if fonts else None

    return most_common_font_size, most_common_color, most_common_font

def normalize_text(text):
    if text is None:
        return ""
    return re.sub(r'\s+', ' ', text.strip().lower())

def get_spaced_text_from_spans(spans):
    return normalize_text(" ".join(span["text"].strip() for span in spans))

def is_header(span, most_common_font_size, most_common_color, most_common_font):
    fontname = span.get("font", "").lower()
    # is_italic = "italic" in fontname or "oblique" in fontname
    is_bold = "bold" in fontname or span.get("bold", False)
    return (
        (
            span["size"] > most_common_font_size or
            span["font"].lower() != most_common_font.lower() or
            (is_bold and span["size"] > most_common_font_size )
        )
    )

def add_span_to_nearest_group(span_y, grouped_dict, pageNum=None, threshold=0.5):
    for (p, y) in grouped_dict:
        if pageNum is not None and p != pageNum:
            continue
        if abs(y - span_y) <= threshold:
            return (p, y)
    return (pageNum, span_y)

def extract_headers(doc, toc_pages, most_common_font_size, most_common_color, most_common_font, top_margin, bottom_margin):

    grouped_headers = defaultdict(list)
    spans = []
    line_merge_threshold = 1.5  # Maximum vertical distance between lines to consider as part of same header

    for pageNum in range(len(doc)):
        if pageNum in toc_pages:
            continue
        page = doc.load_page(pageNum)
        page_height = page.rect.height
        text_instances = page.get_text("dict")

        # First pass: collect all potential header spans
        potential_header_spans = []
        for block in text_instances['blocks']:
            if block['type'] != 0:
                continue

            for line in block['lines']:
                for span in line['spans']:
                    span_y0 = span['bbox'][1]
                    span_y1 = span['bbox'][3]

                    if span_y0 < top_margin or span_y1 > (page_height - bottom_margin):
                        continue

                    span_text = normalize_text(span.get('text', ''))
                    if not span_text:
                        continue
                    if span_text.startswith('http://www') or span_text.startswith('www'):
                        continue
                    if any((
                        'page' in span_text,
                        not re.search(r'[a-z0-9]', span_text),
                        'end of section' in span_text,
                        re.search(r'page\s+\d+\s+of\s+\d+', span_text),
                        re.search(r'\b(?:\d{1,2}[/-])?\d{1,2}[/-]\d{2,4}\b', span_text),
                        # re.search(r'\b(?:jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)', span_text),
                        'specification:' in span_text
                    )):
                        continue

                    cleaned_text = re.sub(r'[.\-]{4,}.*$', '', span_text).strip()
                    cleaned_text = normalize_text(cleaned_text)

                    if is_header(span, most_common_font_size, most_common_color, most_common_font):
                        potential_header_spans.append({
                            'text': cleaned_text,
                            'size': span['size'],
                            'pageNum': pageNum,
                            'y0': span_y0,
                            'y1': span_y1,
                            'x0': span['bbox'][0],
                            'x1': span['bbox'][2],
                            'span': span
                        })

        # Sort spans by vertical position (top to bottom)
        potential_header_spans.sort(key=lambda s: (s['pageNum'], s['y0']))

        # Second pass: group spans that are vertically close and likely part of same header
        i = 0
        while i < len(potential_header_spans):
            current = potential_header_spans[i]
            header_text = current['text']
            header_size = current['size']
            header_page = current['pageNum']
            min_y = current['y0']
            max_y = current['y1']
            spans_group = [current['span']]

            # Look ahead to find adjacent lines that might be part of same header
            j = i + 1
            while j < len(potential_header_spans):
                next_span = potential_header_spans[j]
                # Check if on same page and vertically close with similar styling
                if (next_span['pageNum'] == header_page and
                    next_span['y0'] - max_y < line_merge_threshold and
                    abs(next_span['size'] - header_size) < 0.5):
                    header_text += " " + next_span['text']
                    max_y = next_span['y1']
                    spans_group.append(next_span['span'])
                    j += 1
                else:
                    break

            # Add the merged header
            grouped_headers[(header_page, min_y)].append({
                "text": header_text.strip(),
                "size": header_size,
                "pageNum": header_page,
                "spans": spans_group
            })
            spans.extend(spans_group)
            i = j  # Skip the spans we've already processed

    # Prepare final headers list
    headers = []
    for (pageNum, y), header_groups in sorted(grouped_headers.items()):
        for group in header_groups:
            headers.append([
                group['text'],
                group['size'],
                group['pageNum'],
                y
            ])

    font_sizes = [size for _, size, _, _ in headers]
    font_size_counts = Counter(font_sizes)

      # Filter font sizes that appear at least 3 times
    valid_font_sizes = [size for size, count in font_size_counts.items() if count >= 1]

    # Sort in descending order
    valid_font_sizes_sorted = sorted(valid_font_sizes, reverse=True)

    # If only 2 sizes, repeat the second one
    if len(valid_font_sizes_sorted) == 2:
        top_3_font_sizes = [valid_font_sizes_sorted[0], valid_font_sizes_sorted[1], valid_font_sizes_sorted[1]]
    else:
        top_3_font_sizes = valid_font_sizes_sorted[:3]

    # Get the smallest font size among valid ones
    smallest_font_size = min(valid_font_sizes) if valid_font_sizes else None
    
    return headers, top_3_font_sizes, smallest_font_size, spans


def is_numbered(text):
    return bool(re.match(r'^\d', text.strip()))

def is_similar(a, b, threshold=0.85):
    return difflib.SequenceMatcher(None, a, b).ratio() > threshold

def normalize(text):
    text = text.lower()
    text = re.sub(r'\.{2,}', '', text)  # remove long dots
    text = re.sub(r'\s+', ' ', text)    # replace multiple spaces with one
    return text.strip()

def clean_toc_entry(toc_text):
    """Remove page numbers and formatting from TOC entries"""
    # Remove everything after last sequence of dots/whitespace followed by digits
    return re.sub(r'[\.\s]+\d+.*$', '', toc_text).strip('. ')





def enforce_level_hierarchy(headers):
    """
    Ensure level 2 headers only exist under level 1 headers
    and clean up any orphaned headers
    """
    def process_node_list(node_list, parent_level=-1):
        i = 0
        while i < len(node_list):
            node = node_list[i]

            # Remove level 2 headers that don't have a level 1 parent
            if node['level'] == 2 and parent_level != 1:
                node_list.pop(i)
                continue

            # Recursively process children
            process_node_list(node['children'], node['level'])
            i += 1

    process_node_list(headers)
    return headers



def build_header_hierarchy(doc, toc_pages, most_common_font_size, most_common_color, most_common_font, top_margin=70, bottom_margin=70):
    # Extract headers with margin handling
    headers_list, top_3_font_sizes, smallest_font_size, spans = extract_headers(
        doc,
        toc_pages=toc_pages,
        most_common_font_size=most_common_font_size,
        most_common_color=most_common_color,
        most_common_font=most_common_font,
        top_margin=top_margin,
        bottom_margin=50
    )

    # Step 1: Collect and filter potential headers
    headers = []
    seen_headers = set()

    # First extract TOC entries to get exact level 0 header texts
    toc_entries = {}
    for pno in toc_pages:
        print(pno)
        page = doc[pno]
        toc_text = page.get_text()
        for line in toc_text.split('\n'):
            clean_line = line.strip()
            if clean_line:
                norm_line = normalize(clean_line)
                toc_entries[norm_line] = clean_line  # Store original text
    print(toc_pages)
    for h in headers_list:
        text, size, pageNum, y = h[:4]
        page = doc.load_page(pageNum)
        page_height = page.rect.height

        # Skip margin areas
        if y < top_margin or y > (page_height - bottom_margin):
            continue

        norm_text = normalize(text)
        if len(norm_text) > 2 and size >= most_common_font_size:
            headers.append({
                "text": text,
                "page": pageNum,
                "y": y,
                "size": size,
                "bold": h[4] if len(h) > 4 else False,
                # "italic": h[5] if len(h) > 5 else False,
                "color": h[6] if len(h) > 6 else None,
                "font": h[7] if len(h) > 7 else None,
                "children": [],
                "is_numbered": is_numbered(text),
                "original_size": size,
                "norm_text": norm_text,
                "level": -1  # Initialize as unassigned
            })

    # Sort by page and vertical position
    headers.sort(key=lambda h: (h['page'], h['y']))
    # Step 2: Detect consecutive headers and assign levels
    i = 0
    while i < len(headers) - 1:
        current = headers[i]
        next_header = headers[i+1]

        # Check if they are on the same page and very close vertically (likely consecutive lines)
        if (current['page'] == next_header['page'] and
            abs(current['y'] - next_header['y']) < 20):  # 20pt threshold for "same line"

            # Case 1: Both unassigned - make current level 1 and next level 2
            if current['level'] == -1 and next_header['level'] == -1:
                current['level'] = 1
                next_header['level'] = 2
                i += 1  # Skip next header since we processed it

            # Case 2: Current unassigned, next assigned - make current one level above
            elif current['level'] == -1 and next_header['level'] != -1:
                current['level'] = max(1, next_header['level'] - 1)

            # Case 3: Current assigned, next unassigned - make next one level below
            elif current['level'] != -1 and next_header['level'] == -1:
                next_header['level'] = current['level'] + 1
                i += 1  # Skip next header since we processed it
        i += 1
    # Step 2: Identify level 0 headers (largest and in TOC)
    # max_size = max(h['size'] for h in headers) if headers else 0
    print(top_3_font_sizes)
    max_size,subheaderSize,nbsheadersize=top_3_font_sizes
    print(max_size)
    toc_text_match=[]
    # Improved TOC matching with exact and substring matching
    toc_matches = []
    for h in headers:
        norm_text = h['norm_text']
        matching_toc_texts = []

        # Check both exact matches and substring matches
        for toc_norm, toc_text in toc_entries.items():
            # Exact match case
            if norm_text == toc_norm and len(toc_text)>4 and h['size']==max_size:
                matching_toc_texts.append(toc_text)
            # Substring match case (header is substring of TOC entry)
            elif norm_text in toc_norm and len(toc_text)>4 and h['size']==max_size:
                matching_toc_texts.append(toc_text)
            # Substring match case (TOC entry is substring of header)
            elif toc_norm in norm_text and len(toc_text)>4 and h['size']==max_size:
                matching_toc_texts.append(toc_text)

        if matching_toc_texts and h['size'] >= max_size * 0.9:
            best_match = max(matching_toc_texts,
                          key=lambda x: (len(x), -len(x.replace(norm_text, ''))))
            h['text'] = normalize_text(clean_toc_entry(best_match))
            h['level'] = 0
            if h['text'] not in  toc_text_match:
              toc_matches.append(h)
              toc_text_match.append(h['text'])
        elif matching_toc_texts and h['size'] < max_size * 0.9 and h['size'] > nbsheadersize : # h['size'] < max_size * 0.9 and h['size'] > max_size*0.75:
             print(h['text'],matching_toc_texts)
             headers.remove(h)
             continue


    # Remove duplicates - keep only first occurrence of each level 0 header
    unique_level0 = []
    seen_level0 = set()
    for h in toc_matches:
        # Use the cleaned text for duplicate checking
        cleaned_text = clean_toc_entry(h['text'])
        norm_cleaned_text = normalize(cleaned_text)

        if norm_cleaned_text not in seen_level0:
            seen_level0.add(norm_cleaned_text)
            # Update the header text with cleaned version
            h['text'] = cleaned_text
            unique_level0.append(h)
            print(f"Added unique header: {cleaned_text} (normalized: {norm_cleaned_text})")

    # Step 3: Process headers under each level 0 to identify level 1 format

    # First, group headers by their level 0 parent
    level0_headers = [h for h in headers if h['level'] == 0]
    header_groups = []

    for i, level0 in enumerate(level0_headers):
        start_idx = headers.index(level0)
        end_idx = headers.index(level0_headers[i+1]) if i+1 < len(level0_headers) else len(headers)
        group = headers[start_idx:end_idx]
        header_groups.append(group)

    # Now process each group to identify level 1 format
    for group in header_groups:
        level0 = group[0]
        level1_candidates = [h for h in group[1:] if h['level'] == -1]

        if not level1_candidates:
            continue

        # The first candidate is our reference level 1
        first_level1 = level1_candidates[0]
        level1_format = {
            'font': first_level1['font'],
            'color': first_level1['color'],
            'starts_with_number': is_numbered(first_level1['text']),
            'size': first_level1['size'],
            'bold': first_level1['bold']
            # 'italic': first_level1['italic']
        }

        # Assign levels based on the reference format
        for h in level1_candidates:
            current_format = {
                'font': h['font'],
                'color': h['color'],
                'starts_with_number': is_numbered(h['text']),
                'size': h['size'],
                'bold': h['bold']
                # 'italic': h['italic']
            }

            # Compare with level1 format
            if (current_format['font'] == level1_format['font'] and
                current_format['color'] == level1_format['color'] and
                current_format['starts_with_number'] == level1_format['starts_with_number'] and
                abs(current_format['size'] - level1_format['size']) <= 0.1 and
                current_format['bold'] == level1_format['bold'] ): #and
                # current_format['italic'] == level1_format['italic']):
                h['level'] = 1
            else:
                h['level'] = 2

    # Step 4: Assign levels to remaining unassigned headers
    unassigned = [h for h in headers if h['level'] == -1]
    if unassigned:
        # Cluster by size with tolerance
        sizes = sorted({h['size'] for h in unassigned}, reverse=True)
        clusters = []

        for size in sizes:
            found_cluster = False
            for cluster in clusters:
                if abs(size - cluster['size']) <= max(size, cluster['size']) * 0.1:
                    cluster['headers'].extend([h for h in unassigned if abs(h['size'] - size) <= size * 0.1])
                    found_cluster = True
                    break
            if not found_cluster:
                clusters.append({
                    'size': size,
                    'headers': [h for h in unassigned if abs(h['size'] - size) <= size * 0.1]
                })

        # Assign levels starting from 1
        clusters.sort(key=lambda x: -x['size'])
        for i, cluster in enumerate(clusters):
            for h in cluster['headers']:
                base_level = i + 1
                if h['bold']:
                    base_level = max(1, base_level - 1)
                h['level'] = base_level

    # Step 5: Build hierarchy
    root = []
    stack = []

    # Create a set of normalized texts from unique_level0 to avoid duplicates
    unique_level0_texts = {h['norm_text'] for h in unique_level0}

    # Filter out any headers from the original list that match unique_level0 headers
    filtered_headers = []
    for h in headers:
        if h['norm_text'] in unique_level0_texts and h not in unique_level0:
              h['level'] = 0
        filtered_headers.append(h)

    # Combine all headers - unique_level0 first, then the filtered headers
    all_headers = unique_level0 + filtered_headers
    all_headers.sort(key=lambda h: (h['page'], h['y']))

    # Track which level 0 headers we've already added
    added_level0 = set()

    for header in all_headers:
        if header['level'] < 0:
            continue

        if header['level'] == 0:
            norm_text = header['norm_text']
            if norm_text in added_level0:
                continue
            added_level0.add(norm_text)

        # Pop stack until we find a parent
        while stack and stack[-1]['level'] >= header['level']:
            stack.pop()

        current_parent = stack[-1] if stack else None

        if current_parent:
            current_parent['children'].append(header)
        else:
            root.append(header)

        stack.append(header)

    # Step 6: Enforce proper nesting
    def enforce_nesting(node_list, parent_level=-1):
        for node in node_list:
            if node['level'] <= parent_level:
                node['level'] = parent_level + 1
            enforce_nesting(node['children'], node['level'])

    enforce_nesting(root)
    root = [h for h in root if not (h['level'] == 0 and not h['children'])]
    header_tree = enforce_level_hierarchy(root)
    return header_tree

def adjust_levels_if_level0_not_in_toc(doc, toc_pages, root):
    def normalize(text):
        return re.sub(r'\s+', ' ', text.strip().lower())

    toc_text = ""
    for pno in toc_pages:
        page = doc.load_page(pno)
        toc_text += page.get_text()
    toc_text_normalized = normalize(toc_text)

    def is_level0_in_toc_text(header):
        return header['level'] == 0 and normalize(header['text']) in toc_text_normalized

    if any(is_level0_in_toc_text(h) for h in root):
        return  # No change needed

    def increase_levels(node_list):
        for node in node_list:
            node['level'] += 1
            increase_levels(node['children'])

def assign_numbers_to_headers(headers, prefix=None):
    for idx, header in enumerate(headers, 1):
        current_number = f"{prefix}.{idx}" if prefix else str(idx)
        header["number"] = current_number
        assign_numbers_to_headers(header["children"], current_number)

def print_tree_with_numbers(headers, indent=0):
    for header in headers:
        size_info = f"size:{header['original_size']:.1f}" if 'original_size' in header else ""
        print("  " * indent +
              f"{header.get('number', '?')} {header['text']} " +
              f"(Level {header['level']}, p:{header['page']+1}, {size_info})")
        print_tree_with_numbers(header["children"], indent + 1)

def process_document_headers(doc, toc_pages, most_common_font_size, most_common_color, most_common_font, top_margin=70, bottom_margin=50):
    print(f"Processing with margins - top:{top_margin}pt, bottom:{bottom_margin}pt")
    header_tree = build_header_hierarchy(doc, toc_pages, most_common_font_size, most_common_color, most_common_font, top_margin, bottom_margin)
    adjust_levels_if_level0_not_in_toc(doc, toc_pages, header_tree)
    print("Assigning numbers...")
    assign_numbers_to_headers(header_tree)
    print("Document structure (excluding margins):")
    print_tree_with_numbers(header_tree)
    return header_tree


def highlight_boxes(doc, highlights, stringtowrite, fixed_width=500):  # Set your desired width here
    for page_num, bbox in highlights.items():
        page = doc.load_page(page_num)
        page_width = page.rect.width

        # Get original rect for vertical coordinates
        orig_rect = fitz.Rect(bbox)
        rect_height = orig_rect.height
        if rect_height > 30:
            if orig_rect.width > 10:
                # Center horizontally using fixed width
                center_x = page_width / 2
                new_x0 = center_x - fixed_width / 2
                new_x1 = center_x + fixed_width / 2
                new_rect = fitz.Rect(new_x0, orig_rect.y0, new_x1, orig_rect.y1)
    
                # Add highlight rectangle
                annot = page.add_rect_annot(new_rect)
                if stringtowrite.startswith('Not'):
                    annot.set_colors(stroke=(0.5, 0.5, 0.5), fill=(0.5, 0.5, 0.5))
                else:
                    annot.set_colors(stroke=(1, 1, 0), fill=(1, 1, 0))
 
                annot.set_opacity(0.3)
                annot.update()
    
                # Add right-aligned freetext annotation inside the fixed-width box
                text = '['+stringtowrite +']'
                annot1 = page.add_freetext_annot(
                    new_rect,
                    text,
                    fontsize=15,
                    fontname='helv',
                    text_color=(1, 0, 0),
                    rotate=page.rotation,
                    align=2  # right alignment
                )
                annot1.update()

def get_leaf_headers_with_paths(listtoloop, path=None, output=None):
    if path is None:
        path = []
    if output is None:
        output = []
    for header in listtoloop:
        current_path = path + [header['text']]
        if not header['children']:
            if header['level'] != 0 and header['level'] != 1:
                output.append((header, current_path))
        else:
            get_leaf_headers_with_paths(header['children'], current_path, output)
    return output
# Add this helper function at the top of your code
def words_match_ratio(text1, text2):
    words1 = set(text1.split())
    words2 = set(text2.split())
    if not words1 or not words2:
        return 0.0
    common_words = words1 & words2
    return len(common_words) / len(words1)

def same_start_word(s1, s2):
    # Split both strings into words
    words1 = s1.strip().split()
    words2 = s2.strip().split()

    # Check if both have at least one word and compare the first ones
    if words1 and words2:
        return words1[0].lower() == words2[0].lower()
    return False

def extract_section_under_header(multiplePDF_Paths):
    filenames=[]
    keywords = {'installation', 'execution', 'miscellaneous items', 'workmanship', 'testing', 'labeling'}
    arrayofPDFS=multiplePDF_Paths.split(',')
    print(multiplePDF_Paths)
    print(arrayofPDFS,len(arrayofPDFS))
    docarray=[]
    jsons=[]
    df = pd.DataFrame(columns=["PDF Name","NBSLink","Subject","Page","Author","Creation Date","Layer",'Code', 'head above 1', "head above 2","BodyText"])
    for pdf_path in arrayofPDFS:
        headertoContinue1 = False
        headertoContinue2=False
        Alltexttobebilled=''
        parsed_url = urlparse(pdf_path)
        filename = os.path.basename(parsed_url.path)
        filename = unquote(filename)  # decode URL-encoded characters
        filenames.append(filename)
        # Optimized URL handling
        if pdf_path and ('http' in pdf_path or 'dropbox' in pdf_path):
            pdf_path = pdf_path.replace('dl=0', 'dl=1')

        # Cache frequently used values
        response = requests.get(pdf_path)
        pdf_content = BytesIO(response.content)
        if not pdf_content:
            raise ValueError("No valid PDF content found.")

        doc = fitz.open(stream=pdf_content, filetype="pdf")
        docHighlights = fitz.open(stream=pdf_content, filetype="pdf")
        most_common_font_size, most_common_color, most_common_font = get_regular_font_size_and_color(doc)

        # Precompute regex patterns
        dot_pattern = re.compile(r'\.{3,}')
        url_pattern = re.compile(r'https?://\S+|www\.\S+')

       
        toc_pages = get_toc_page_numbers(doc)

        headers, top_3_font_sizes, smallest_font_size, headersSpans = extract_headers(
            doc, toc_pages, most_common_font_size, most_common_color, most_common_font, top_margin, bottom_margin
        )

        hierarchy = build_header_hierarchy(doc, toc_pages, most_common_font_size, most_common_color, most_common_font)
        listofHeaderstoMarkup = get_leaf_headers_with_paths(hierarchy)
        
        # Precompute all children headers once
        allchildrenheaders = [normalize_text(item['text']) for item, p in listofHeaderstoMarkup]
        allchildrenheaders_set = set(allchildrenheaders)  # For faster lookups

        df = pd.DataFrame(columns=["NBSLink","Subject","Page","Author","Creation Date","Layer",'Code', 'head above 1', "head above 2"])
        dictionaryNBS={}
        data_list_JSON = []

        if len(top_3_font_sizes)==3:
            mainHeaderFontSize, subHeaderFontSize, subsubheaderFontSize = top_3_font_sizes
        elif len(top_3_font_sizes)==2:
            mainHeaderFontSize= top_3_font_sizes[0]
            subHeaderFontSize= top_3_font_sizes[1]
            subsubheaderFontSize= top_3_font_sizes[1]

        

        # Preload all pages to avoid repeated loading
        # pages = [doc.load_page(page_num) for page_num in range(len(doc)) if page_num not in toc_pages]

        for heading_to_searchDict, paths in listofHeaderstoMarkup:
            heading_to_search = heading_to_searchDict['text']
            heading_to_searchPageNum = heading_to_searchDict['page']

            # Initialize variables
            headertoContinue1 = False
            headertoContinue2 = False
            matched_header_line = None
            done = False
            collecting = False
            collected_lines = []
            page_highlights = {}
            current_bbox = {}
            last_y1s = {}
            mainHeader = ''
            subHeader = ''
            matched_header_line_norm = heading_to_search
            break_collecting = False
            heading_norm = normalize_text(heading_to_search)
            paths_norm = [normalize_text(p) for p in paths[0]] if paths and paths[0] else []

            for page_num in range(heading_to_searchPageNum,len(doc)):
                if page_num in toc_pages:
                    continue
                if break_collecting:
                    break
                page=doc[page_num]
                page_height = page.rect.height
                blocks = page.get_text("dict")["blocks"]

                for block in blocks:
                    if break_collecting:
                        break

                    lines = block.get("lines", [])
                    i = 0
                    while i < len(lines):
                        if break_collecting:
                            break

                        spans = lines[i].get("spans", [])
                        if not spans:
                            i += 1
                            continue

                        y0 = spans[0]["bbox"][1]
                        y1 = spans[0]["bbox"][3]
                        if y0 < top_margin or y1 > (page_height - bottom_margin):
                            i += 1
                            continue

                        line_text = get_spaced_text_from_spans(spans).lower()
                        line_text_norm = normalize_text(line_text)

                        # Combine with next line if available
                        if i + 1 < len(lines):
                            next_spans = lines[i + 1].get("spans", [])
                            next_line_text = get_spaced_text_from_spans(next_spans).lower()
                            combined_line_norm = normalize_text(line_text + " " + next_line_text)
                        else:
                            combined_line_norm = line_text_norm

                        # Check if we should continue processing
                        if combined_line_norm and combined_line_norm in paths[0]:
                            
                            headertoContinue1 = combined_line_norm
                        if combined_line_norm and combined_line_norm in paths[-2]:
                        
                            headertoContinue2 = combined_line_norm
                        if  'installation' in paths[-2].lower() or 'execution' in paths[-2].lower() or 'miscellaneous items' in paths[-2].lower() :
                            stringtowrite='Not to be billed'
                        else:
                            stringtowrite='To be billed'
                        # Optimized header matching
                        existsfull = (
                            ( combined_line_norm in allchildrenheaders_set or
                            combined_line_norm in allchildrenheaders ) and heading_to_search in combined_line_norm
                        )

                        # New word-based matching
                        current_line_words = set(combined_line_norm.split())
                        heading_words = set(heading_norm.split())
                        all_words_match = current_line_words.issubset(heading_words) and len(current_line_words) > 0

                        substring_match = (
                            heading_norm in combined_line_norm or
                            combined_line_norm in heading_norm or
                            all_words_match  # Include the new word-based matching
                        )
                        # substring_match = (
                        #     heading_norm in combined_line_norm or
                        #     combined_line_norm in heading_norm
                        # )

                        if (substring_match and existsfull and not collecting and
                            len(combined_line_norm) > 0 ):#and (headertoContinue1 or headertoContinue2) ):

                            # Check header conditions more efficiently
                            header_spans = [
                                span for span in spans
                                if (is_header(span, most_common_font_size, most_common_color, most_common_font)
                                    # and span['size'] >= subsubheaderFontSize
                                    and span['size'] < mainHeaderFontSize)
                            ]
                            if header_spans:
                                collecting = True
                                matched_header_font_size = max(span["size"] for span in header_spans)

                                collected_lines.append(line_text)
                                valid_spans = [span for span in spans if span.get("bbox")]

                                if valid_spans:
                                    x0s = [span["bbox"][0] for span in valid_spans]
                                    x1s = [span["bbox"][2] for span in valid_spans]
                                    y0s = [span["bbox"][1] for span in valid_spans]
                                    y1s = [span["bbox"][3] for span in valid_spans]

                                    header_bbox = [min(x0s), min(y0s), max(x1s), max(y1s)]

                                    if page_num in current_bbox:
                                        cb = current_bbox[page_num]
                                        current_bbox[page_num] = [
                                            min(cb[0], header_bbox[0]),
                                            min(cb[1], header_bbox[1]),
                                            max(cb[2], header_bbox[2]),
                                            max(cb[3], header_bbox[3])
                                        ]
                                    else:
                                        current_bbox[page_num] = header_bbox
                                    last_y1s[page_num] = header_bbox[3]
                                    x0, y0, x1, y1 = header_bbox

                                    zoom = 200
                                    left = int(x0)
                                    top = int(y0)
                                    zoom_str = f"{zoom},{left},{top}"
                                    pageNumberFound = page_num + 1

                                # Build the query parameters
                                    # params = {
                                    #     'pdfLink': pdf_path,  # Your PDF link
                                    #     'keyword': heading_to_search,  # Your keyword (could be a string or list)
                                    # }

                                    # # URL encode each parameter
                                    # encoded_params = {key: urllib.parse.quote(value, safe='') for key, value in params.items()}

                                    # # Construct the final encoded link
                                    # encoded_link = '&'.join([f"{key}={value}" for key, value in encoded_params.items()])

                                    # # Correctly construct the final URL with page and zoom
                                    # final_url = f"{baselink}{encoded_link}#page={str(pageNumberFound)}&zoom={zoom_str}"

                                    # Get current date and time
                                    now = datetime.now()

                                    # Format the output
                                    formatted_time = now.strftime("%d/%m/%Y %I:%M:%S %p")
                                    # Optionally, add the URL to a DataFrame


                                    data_entry = {
                                            "NBSLink": zoom_str,
                                            "Subject": heading_to_search,
                                            "Page": str(pageNumberFound),
                                            "Author": "ADR",
                                            "Creation Date": formatted_time,
                                            "Layer": "Initial",
                                            "Code": stringtowrite,
                                            "head above 1":  paths[-2],
                                            "head above 2":  paths[0],
                                            # "MC Connnection": 'Go to ' +  paths[0].strip().split()[0] +'/'+ heading_to_search.strip().split()[0] + ' in '+ filename
                                        }
                                    data_list_JSON.append(data_entry)

                                    # Convert list to JSON
                                    # json_output = json.dumps(data_list_JSON, indent=4)

                                    i += 2
                                    continue
                        else:
                            if (substring_match and not collecting and
                                len(combined_line_norm) > 0): # and (headertoContinue1 or headertoContinue2) ):

                                # Calculate word match percentage
                                word_match_percent = words_match_ratio(heading_norm, combined_line_norm) * 100

                                # Check if at least 70% of header words exist in this line
                                meets_word_threshold = word_match_percent >= 100

                                # Check header conditions (including word threshold)
                                header_spans = [
                                    span for span in spans
                                    if (is_header(span, most_common_font_size, most_common_color, most_common_font)
                                        # and span['size'] >= subsubheaderFontSize
                                        and span['size'] < mainHeaderFontSize)
                                ]

                                if header_spans and (meets_word_threshold or same_start_word(heading_to_search, combined_line_norm) ):
                                    collecting = True
                                    matched_header_font_size = max(span["size"] for span in header_spans)
                                
                                    collected_lines.append(line_text)
                                    valid_spans = [span for span in spans if span.get("bbox")]

                                    if valid_spans:
                                        x0s = [span["bbox"][0] for span in valid_spans]
                                        x1s = [span["bbox"][2] for span in valid_spans]
                                        y0s = [span["bbox"][1] for span in valid_spans]
                                        y1s = [span["bbox"][3] for span in valid_spans]

                                        header_bbox = [min(x0s), min(y0s), max(x1s), max(y1s)]

                                        if page_num in current_bbox:
                                            cb = current_bbox[page_num]
                                            current_bbox[page_num] = [
                                                min(cb[0], header_bbox[0]),
                                                min(cb[1], header_bbox[1]),
                                                max(cb[2], header_bbox[2]),
                                                max(cb[3], header_bbox[3])
                                            ]
                                        else:
                                            current_bbox[page_num] = header_bbox

                                        last_y1s[page_num] = header_bbox[3]
                                        x0, y0, x1, y1 = header_bbox
                                        zoom = 200
                                        left = int(x0)
                                        top = int(y0)
                                        zoom_str = f"{zoom},{left},{top}"
                                        pageNumberFound = page_num + 1

                                    # Build the query parameters
                                        # params = {
                                        #     'pdfLink': pdf_path,  # Your PDF link
                                        #     'keyword': heading_to_search,  # Your keyword (could be a string or list)
                                        # }

                                        # # URL encode each parameter
                                        # encoded_params = {key: urllib.parse.quote(value, safe='') for key, value in params.items()}

                                        # # Construct the final encoded link
                                        # encoded_link = '&'.join([f"{key}={value}" for key, value in encoded_params.items()])

                                        # # Correctly construct the final URL with page and zoom
                                        # final_url = f"{baselink}{encoded_link}#page={str(pageNumberFound)}&zoom={zoom_str}"

                                        # Get current date and time
                                        now = datetime.now()

                                        # Format the output
                                        formatted_time = now.strftime("%d/%m/%Y %I:%M:%S %p")
                                        # Optionally, add the URL to a DataFrame


                                        data_entry = {
                                                "NBSLink": zoom_str,
                                                "Subject": heading_to_search,
                                                "Page": str(pageNumberFound),
                                                "Author": "ADR",
                                                "Creation Date": formatted_time,
                                                "Layer": "Initial",
                                                "Code": stringtowrite,
                                                "head above 1":  paths[-2],
                                                "head above 2":  paths[0],
                                                # "MC Connnection": 'Go to ' +  paths[0].strip().split()[0] +'/'+ heading_to_search.strip().split()[0] + ' in '+ filename
                                            }
                                        data_list_JSON.append(data_entry)

                                        # Convert list to JSON
                                        # json_output = json.dumps(data_list_JSON, indent=4)

                    
                                        i += 2
                                        continue
                        if collecting:
                            norm_line = normalize_text(line_text)

                            # Optimized URL check
                            if url_pattern.match(norm_line):
                                line_is_header = False
                            else:
                                line_is_header = any(is_header(span, most_common_font_size, most_common_color, most_common_font) for span in spans)

                            if line_is_header:
                                header_font_size = max(span["size"] for span in spans)
                                is_probably_real_header = (
                                    header_font_size >= matched_header_font_size and
                                    is_header(spans[0], most_common_font_size, most_common_color, most_common_font) and
                                    len(line_text.strip()) > 2
                                )

                                if (norm_line != matched_header_line_norm and
                                    norm_line != heading_norm and
                                    is_probably_real_header):
                                    if line_text not in heading_norm:
                                        collecting = False
                                        done = True
                                        headertoContinue1 = False
                                        headertoContinue2=False
                                        for page_num, bbox in current_bbox.items():
                                            bbox[3] = last_y1s.get(page_num, bbox[3])
                                            page_highlights[page_num] = bbox
                                        highlight_boxes(docHighlights, page_highlights,stringtowrite)

                                        break_collecting = True
                                        break

                            if break_collecting:
                                break

                            collected_lines.append(line_text)
                            valid_spans = [span for span in spans if span.get("bbox")]
                            if valid_spans:
                                x0s = [span["bbox"][0] for span in valid_spans]
                                x1s = [span["bbox"][2] for span in valid_spans]
                                y0s = [span["bbox"][1] for span in valid_spans]
                                y1s = [span["bbox"][3] for span in valid_spans]

                                line_bbox = [min(x0s), min(y0s), max(x1s), max(y1s)]

                                if page_num in current_bbox:
                                    cb = current_bbox[page_num]
                                    current_bbox[page_num] = [
                                        min(cb[0], line_bbox[0]),
                                        min(cb[1], line_bbox[1]),
                                        max(cb[2], line_bbox[2]),
                                        max(cb[3], line_bbox[3])
                                    ]
                                else:
                                    current_bbox[page_num] = line_bbox

                                last_y1s[page_num] = line_bbox[3]
                        i += 1

            if not done:
                for page_num, bbox in current_bbox.items():
                    bbox[3] = last_y1s.get(page_num, bbox[3])
                    page_highlights[page_num] = bbox
                if  'installation' in paths[-2].lower() or 'execution' in paths[-2].lower() or 'miscellaneous items' in paths[-2].lower() :
                    stringtowrite='Not to be billed'
                else:
                    stringtowrite='To be billed'
                highlight_boxes(docHighlights, page_highlights,stringtowrite)

        docarray.append(docHighlights)
        jsons.append(data_list_JSON)
    print('lenght of json:',len(jsons))
    dbxTeam = tsadropboxretrieval.ADR_Access_DropboxTeam('user')
    dbPath = '/TSA JOBS/ADR Test/FIND/'
    jsonCombined=[] 
    for i in range(len(arrayofPDFS)):
        pdflink = tsadropboxretrieval.uploadanyFile(doc=docarray[i], path=dbPath, pdfname=filenames[i])
        json_input = copy.deepcopy(jsons[i])  # make a deep copy
        json_output1 = changepdflinks(json_input, pdflink)
        jsonCombined.extend(json_output1)
        pdf_bytes = BytesIO()
        docHighlights.save(pdf_bytes)
    combined_json_str = json.dumps(jsonCombined, indent=1)
    print('lenght of json:',len(combined_json_str))
    return pdf_bytes.getvalue(), docHighlights , combined_json_str
 
########################################################################################################################################################
########################################################################################################################################################



def extract_section_under_header_tobebilledOnly(pdf_path):
    Alltexttobebilled=''
    alltextWithoutNotbilled=''
    # keywordstoSkip=["installation", "execution", "miscellaneous items", "workmanship", "testing", "labeling"]
    
    headertoContinue1 = False
    headertoContinue2=False
    
    parsed_url = urlparse(pdf_path)
    filename = os.path.basename(parsed_url.path)
    filename = unquote(filename)  # decode URL-encoded characters

    # Optimized URL handling
    if pdf_path and ('http' in pdf_path or 'dropbox' in pdf_path):
        pdf_path = pdf_path.replace('dl=0', 'dl=1')

    # Cache frequently used values
    response = requests.get(pdf_path)
    pdf_content = BytesIO(response.content)
    if not pdf_content:
        raise ValueError("No valid PDF content found.")

    doc = fitz.open(stream=pdf_content, filetype="pdf")
    docHighlights = fitz.open(stream=pdf_content, filetype="pdf")   
    parsed_url = urlparse(pdf_path)
    filename = os.path.basename(parsed_url.path)
    filename = unquote(filename)  # decode URL-encoded characters


    most_common_font_size, most_common_color, most_common_font = get_regular_font_size_and_color(doc)

    # Precompute regex patterns
    dot_pattern = re.compile(r'\.{3,}')
    url_pattern = re.compile(r'https?://\S+|www\.\S+')

  
    toc_pages = get_toc_page_numbers(doc)

    headers, top_3_font_sizes, smallest_font_size, headersSpans = extract_headers(
        doc, toc_pages, most_common_font_size, most_common_color, most_common_font, top_margin, bottom_margin
    )

    hierarchy = build_header_hierarchy(doc, toc_pages, most_common_font_size, most_common_color, most_common_font)
    listofHeaderstoMarkup = get_leaf_headers_with_paths(hierarchy)
    
    # Precompute all children headers once
    allchildrenheaders = [normalize_text(item['text']) for item, p in listofHeaderstoMarkup]
    allchildrenheaders_set = set(allchildrenheaders)  # For faster lookups

    df = pd.DataFrame(columns=["NBSLink","Subject","Page","Author","Creation Date","Layer",'Code', 'head above 1', "head above 2",'BodyText'])
    dictionaryNBS={}
    data_list_JSON = []

    if len(top_3_font_sizes)==3:
        mainHeaderFontSize, subHeaderFontSize, subsubheaderFontSize = top_3_font_sizes
    elif len(top_3_font_sizes)==2:
        mainHeaderFontSize= top_3_font_sizes[0]
        subHeaderFontSize= top_3_font_sizes[1]
        subsubheaderFontSize= top_3_font_sizes[1]

    

    # Preload all pages to avoid repeated loading
    # pages = [doc.load_page(page_num) for page_num in range(len(doc)) if page_num not in toc_pages]

    for heading_to_searchDict, paths in listofHeaderstoMarkup:
        heading_to_search = heading_to_searchDict['text']
        heading_to_searchPageNum = heading_to_searchDict['page']
        
        
        
        # Initialize variables
        headertoContinue1 = False
        headertoContinue2 = False
        matched_header_line = None
        done = False
        collecting = False
        collected_lines = []
        page_highlights = {}
        current_bbox = {}
        last_y1s = {}
        mainHeader = ''
        subHeader = ''
        matched_header_line_norm = heading_to_search
        break_collecting = False
        heading_norm = normalize_text(heading_to_search)
        paths_norm = [normalize_text(p) for p in paths[0]] if paths and paths[0] else []
        
        for page_num in range(heading_to_searchPageNum,len(doc)):
            if page_num in toc_pages:
              continue
            if break_collecting:
                break
            page=doc[page_num]
            page_height = page.rect.height
            blocks = page.get_text("dict")["blocks"]

            for block in blocks:
                if break_collecting:
                    break

                lines = block.get("lines", [])
                i = 0
                while i < len(lines):
                    if break_collecting:
                        break

                    spans = lines[i].get("spans", [])
                    if not spans:
                        i += 1
                        continue

                    y0 = spans[0]["bbox"][1]
                    y1 = spans[0]["bbox"][3]
                    if y0 < top_margin or y1 > (page_height - bottom_margin):
                        i += 1
                        continue

                    line_text = get_spaced_text_from_spans(spans).lower()
                    line_text_norm = normalize_text(line_text)

                    # Combine with next line if available
                    if i + 1 < len(lines):
                        next_spans = lines[i + 1].get("spans", [])
                        next_line_text = get_spaced_text_from_spans(next_spans).lower()
                        combined_line_norm = normalize_text(line_text + " " + next_line_text)
                    else:
                        combined_line_norm = line_text_norm
   
                    # Check if we should continue processing
                    if combined_line_norm and combined_line_norm in paths[0]:
                        
                        headertoContinue1 = combined_line_norm
                    if combined_line_norm and combined_line_norm in paths[-2]:
                    
                        headertoContinue2 = combined_line_norm
                    if  'installation' in paths[-2].lower() or 'execution' in paths[-2].lower() or 'miscellaneous items' in paths[-2].lower() :
                    # if any(word in paths[-2].lower() for word in keywordstoSkip):
                      stringtowrite='Not to be billed'
                    else:
                      stringtowrite='To be billed'
                    if stringtowrite!='To be billed':
                        alltextWithoutNotbilled+= combined_line_norm #################################################
                    # Optimized header matching
                    existsfull = (
                        ( combined_line_norm in allchildrenheaders_set or
                        combined_line_norm in allchildrenheaders ) and heading_to_search in combined_line_norm
                    )

                    # New word-based matching
                    current_line_words = set(combined_line_norm.split())
                    heading_words = set(heading_norm.split())
                    all_words_match = current_line_words.issubset(heading_words) and len(current_line_words) > 0

                    substring_match = (
                        heading_norm in combined_line_norm or
                        combined_line_norm in heading_norm or
                        all_words_match  # Include the new word-based matching
                    )
                    # substring_match = (
                    #     heading_norm in combined_line_norm or
                    #     combined_line_norm in heading_norm
                    # )

                    if (substring_match and existsfull and not collecting and
                        len(combined_line_norm) > 0 ):#and (headertoContinue1 or headertoContinue2) ):

                        # Check header conditions more efficiently
                        header_spans = [
                            span for span in spans
                            if (is_header(span, most_common_font_size, most_common_color, most_common_font)
                                # and span['size'] >= subsubheaderFontSize
                                and span['size'] < mainHeaderFontSize)
                        ]
                        if header_spans and stringtowrite.startswith('To'):
                            collecting = True
                            matched_header_font_size = max(span["size"] for span in header_spans)
                            Alltexttobebilled+= ' '+ combined_line_norm
                            
                            # collected_lines.append(line_text)
                            valid_spans = [span for span in spans if span.get("bbox")]

                            if valid_spans:
                                x0s = [span["bbox"][0] for span in valid_spans]
                                x1s = [span["bbox"][2] for span in valid_spans]
                                y0s = [span["bbox"][1] for span in valid_spans]
                                y1s = [span["bbox"][3] for span in valid_spans]

                                header_bbox = [min(x0s), min(y0s), max(x1s), max(y1s)]

                                if page_num in current_bbox:
                                    cb = current_bbox[page_num]
                                    current_bbox[page_num] = [
                                        min(cb[0], header_bbox[0]),
                                        min(cb[1], header_bbox[1]),
                                        max(cb[2], header_bbox[2]),
                                        max(cb[3], header_bbox[3])
                                    ]
                                else:
                                    current_bbox[page_num] = header_bbox
                                last_y1s[page_num] = header_bbox[3]
                                x0, y0, x1, y1 = header_bbox

                                zoom = 200
                                left = int(x0)
                                top = int(y0)
                                zoom_str = f"{zoom},{left},{top}"
                                pageNumberFound = page_num + 1

                              # Build the query parameters
                                params = {
                                    'pdfLink': pdf_path,  # Your PDF link
                                    'keyword': heading_to_search,  # Your keyword (could be a string or list)
                                }

                                # URL encode each parameter
                                encoded_params = {key: urllib.parse.quote(value, safe='') for key, value in params.items()}

                                # Construct the final encoded link
                                encoded_link = '&'.join([f"{key}={value}" for key, value in encoded_params.items()])

                                # Correctly construct the final URL with page and zoom
                                final_url = f"{baselink}{encoded_link}#page={str(pageNumberFound)}&zoom={zoom_str}"

                                # Get current date and time
                                now = datetime.now()

                                # Format the output
                                formatted_time = now.strftime("%d/%m/%Y %I:%M:%S %p")
                                # Optionally, add the URL to a DataFrame


                                data_entry = {
                                        "NBSLink": zoom_str,
                                        "Subject": heading_to_search,
                                        "Page": str(pageNumberFound),
                                        "Author": "ADR",
                                        "Creation Date": formatted_time,
                                        "Layer": "Initial",
                                        "Code": stringtowrite,
                                        "head above 1":  paths[-2],
                                        "head above 2":  paths[0],
                                        "BodyText": collected_lines,
                                        "MC Connnection": 'Go to ' +  paths[0].strip().split()[0] +'/'+ heading_to_search.strip().split()[0] + ' in '+ filename

                                    }
                                data_list_JSON.append(data_entry)

                                # Convert list to JSON
                                json_output = json.dumps(data_list_JSON, indent=4)

                                i += 2
                                continue
                    else:
                        if (substring_match and not collecting and
                            len(combined_line_norm) > 0): # and (headertoContinue1 or headertoContinue2) ):

                            # Calculate word match percentage
                            word_match_percent = words_match_ratio(heading_norm, combined_line_norm) * 100

                            # Check if at least 70% of header words exist in this line
                            meets_word_threshold = word_match_percent >= 100

                            # Check header conditions (including word threshold)
                            header_spans = [
                                span for span in spans
                                if (is_header(span, most_common_font_size, most_common_color, most_common_font)
                                    # and span['size'] >= subsubheaderFontSize
                                    and span['size'] < mainHeaderFontSize)
                            ]

                            if header_spans and (meets_word_threshold or same_start_word(heading_to_search, combined_line_norm) ) and stringtowrite.startswith('To'):
                                collecting = True
                                matched_header_font_size = max(span["size"] for span in header_spans)
                                Alltexttobebilled+= ' '+ combined_line_norm
                                
                                collected_lines.append(line_text)
                                valid_spans = [span for span in spans if span.get("bbox")]

                                if valid_spans:
                                    x0s = [span["bbox"][0] for span in valid_spans]
                                    x1s = [span["bbox"][2] for span in valid_spans]
                                    y0s = [span["bbox"][1] for span in valid_spans]
                                    y1s = [span["bbox"][3] for span in valid_spans]

                                    header_bbox = [min(x0s), min(y0s), max(x1s), max(y1s)]

                                    if page_num in current_bbox:
                                        cb = current_bbox[page_num]
                                        current_bbox[page_num] = [
                                            min(cb[0], header_bbox[0]),
                                            min(cb[1], header_bbox[1]),
                                            max(cb[2], header_bbox[2]),
                                            max(cb[3], header_bbox[3])
                                        ]
                                    else:
                                        current_bbox[page_num] = header_bbox

                                    last_y1s[page_num] = header_bbox[3]
                                    x0, y0, x1, y1 = header_bbox
                                    zoom = 200
                                    left = int(x0)
                                    top = int(y0)
                                    zoom_str = f"{zoom},{left},{top}"
                                    pageNumberFound = page_num + 1

                                  # Build the query parameters
                                    params = {
                                        'pdfLink': pdf_path,  # Your PDF link
                                        'keyword': heading_to_search,  # Your keyword (could be a string or list)
                                    }

                                    # URL encode each parameter
                                    encoded_params = {key: urllib.parse.quote(value, safe='') for key, value in params.items()}

                                    # Construct the final encoded link
                                    encoded_link = '&'.join([f"{key}={value}" for key, value in encoded_params.items()])

                                    # Correctly construct the final URL with page and zoom
                                    final_url = f"{baselink}{encoded_link}#page={str(pageNumberFound)}&zoom={zoom_str}"

                                    # Get current date and time
                                    now = datetime.now()

                                    # Format the output
                                    formatted_time = now.strftime("%d/%m/%Y %I:%M:%S %p")
                                    # Optionally, add the URL to a DataFrame


                                    data_entry = {
                                            "NBSLink": zoom_str,
                                            "Subject": heading_to_search,
                                            "Page": str(pageNumberFound),
                                            "Author": "ADR",
                                            "Creation Date": formatted_time,
                                            "Layer": "Initial",
                                            "Code": stringtowrite,
                                            "head above 1":  paths[-2],
                                            "head above 2":  paths[0],
                                            "BodyText": collected_lines,
                                            "MC Connnection": 'Go to ' +  paths[0].strip().split()[0] +'/'+ heading_to_search.strip().split()[0] + ' in '+ filename
                                        }
                                    data_list_JSON.append(data_entry)

                                    # Convert list to JSON
                                    json_output = json.dumps(data_list_JSON, indent=4)

                
                                    i += 2
                                    continue
                    if collecting:
                        norm_line = normalize_text(line_text)
                        
                        # Optimized URL check
                        if url_pattern.match(norm_line):
                            line_is_header = False
                        else:
                            line_is_header = any(is_header(span, most_common_font_size, most_common_color, most_common_font) for span in spans)

                        if line_is_header:
                            header_font_size = max(span["size"] for span in spans)
                            is_probably_real_header = (
                                header_font_size >= matched_header_font_size and
                                is_header(spans[0], most_common_font_size, most_common_color, most_common_font) and
                                len(line_text.strip()) > 2
                            )

                            if (norm_line != matched_header_line_norm and
                                norm_line != heading_norm and
                                is_probably_real_header):
                                if line_text not in heading_norm:
                                  collecting = False
                                  done = True
                                  headertoContinue1 = False
                                  headertoContinue2=False
                                  for page_num, bbox in current_bbox.items():
                                      bbox[3] = last_y1s.get(page_num, bbox[3])
                                      page_highlights[page_num] = bbox
                                  highlight_boxes(docHighlights, page_highlights,stringtowrite)

                                  break_collecting = True
                                  break

                        if break_collecting:
                            break


                        collected_lines.append(line_text)
                        
                        valid_spans = [span for span in spans if span.get("bbox")]
                        if valid_spans:
                            x0s = [span["bbox"][0] for span in valid_spans]
                            x1s = [span["bbox"][2] for span in valid_spans]
                            y0s = [span["bbox"][1] for span in valid_spans]
                            y1s = [span["bbox"][3] for span in valid_spans]

                            line_bbox = [min(x0s), min(y0s), max(x1s), max(y1s)]

                            if page_num in current_bbox:
                                cb = current_bbox[page_num]
                                current_bbox[page_num] = [
                                    min(cb[0], line_bbox[0]),
                                    min(cb[1], line_bbox[1]),
                                    max(cb[2], line_bbox[2]),
                                    max(cb[3], line_bbox[3])
                                ]
                            else:
                                current_bbox[page_num] = line_bbox

                            last_y1s[page_num] = line_bbox[3]
                    i += 1

        if not done:
            for page_num, bbox in current_bbox.items():
                bbox[3] = last_y1s.get(page_num, bbox[3])
                page_highlights[page_num] = bbox
            if  'installation' in paths[-2].lower() or 'execution' in paths[-2].lower() or 'miscellaneous items' in paths[-2].lower() :
                stringtowrite='Not to be billed'
            else:
                stringtowrite='To be billed'
            highlight_boxes(docHighlights, page_highlights,stringtowrite)

    # docHighlights.save("highlighted_output.pdf", garbage=4, deflate=True)

    dbxTeam = tsadropboxretrieval.ADR_Access_DropboxTeam('user')
    metadata = dbxTeam.sharing_get_shared_link_metadata(pdf_path)
    dbPath = '/TSA JOBS/ADR Test/FIND/'
    pdf_bytes = BytesIO()
    docHighlights.save(pdf_bytes)
    pdflink = tsadropboxretrieval.uploadanyFile(doc=docHighlights, path=dbPath, pdfname=filename)
    json_output=changepdflinks(json_output,pdflink)
    return pdf_bytes.getvalue(), docHighlights , json_output , Alltexttobebilled , alltextWithoutNotbilled , filename


def extract_section_under_header_tobebilled2(pdf_path):
    # keywordstoSkip=["installation", "execution", "miscellaneous items", "workmanship", "testing", "labeling"]

    keywords = {'installation', 'execution', 'miscellaneous items', 'workmanship', 'testing', 'labeling'}

    headertoContinue1 = False
    headertoContinue2=False
    Alltexttobebilled=''
    parsed_url = urlparse(pdf_path)
    filename = os.path.basename(parsed_url.path)
    filename = unquote(filename)  # decode URL-encoded characters

    # Optimized URL handling
    if pdf_path and ('http' in pdf_path or 'dropbox' in pdf_path):
        pdf_path = pdf_path.replace('dl=0', 'dl=1')

    # Cache frequently used values
    response = requests.get(pdf_path)
    pdf_content = BytesIO(response.content)
    if not pdf_content:
        raise ValueError("No valid PDF content found.")

    doc = fitz.open(stream=pdf_content, filetype="pdf")
    docHighlights = fitz.open(stream=pdf_content, filetype="pdf")
    most_common_font_size, most_common_color, most_common_font = get_regular_font_size_and_color(doc)

    # Precompute regex patterns
    dot_pattern = re.compile(r'\.{3,}')
    url_pattern = re.compile(r'https?://\S+|www\.\S+')

   
    toc_pages = get_toc_page_numbers(doc)

    headers, top_3_font_sizes, smallest_font_size, headersSpans = extract_headers(
        doc, toc_pages, most_common_font_size, most_common_color, most_common_font, top_margin, bottom_margin
    )

    hierarchy = build_header_hierarchy(doc, toc_pages, most_common_font_size, most_common_color, most_common_font)
    listofHeaderstoMarkup = get_leaf_headers_with_paths(hierarchy)
    
    # Precompute all children headers once
    allchildrenheaders = [normalize_text(item['text']) for item, p in listofHeaderstoMarkup]
    allchildrenheaders_set = set(allchildrenheaders)  # For faster lookups

    df = pd.DataFrame(columns=["NBSLink","Subject","Page","Author","Creation Date","Layer",'Code', 'head above 1', "head above 2","BodyText"])
    dictionaryNBS={}
    data_list_JSON = []
    currentgroupname=''
    if len(top_3_font_sizes)==3:
        mainHeaderFontSize, subHeaderFontSize, subsubheaderFontSize = top_3_font_sizes
    elif len(top_3_font_sizes)==2:
        mainHeaderFontSize= top_3_font_sizes[0]
        subHeaderFontSize= top_3_font_sizes[1]
        subsubheaderFontSize= top_3_font_sizes[1]

    

    # Preload all pages to avoid repeated loading
    # pages = [doc.load_page(page_num) for page_num in range(len(doc)) if page_num not in toc_pages]

    for heading_to_searchDict, paths in listofHeaderstoMarkup:
        heading_to_search = heading_to_searchDict['text']
        heading_to_searchPageNum = heading_to_searchDict['page']

        # Initialize variables
        headertoContinue1 = False
        headertoContinue2 = False
        matched_header_line = None
        done = False
        collecting = False
        collected_lines = []
        page_highlights = {}
        current_bbox = {}
        last_y1s = {}
        mainHeader = ''
        subHeader = ''
        matched_header_line_norm = heading_to_search
        break_collecting = False
        heading_norm = normalize_text(heading_to_search)
        paths_norm = [normalize_text(p) for p in paths[0]] if paths and paths[0] else []
        for page_num in range(heading_to_searchPageNum,len(doc)):
            print(heading_to_search)
            if paths[0].strip().lower() != currentgroupname.strip().lower():
                Alltexttobebilled+= paths[0] +'\n'
                currentgroupname=paths[0]
                print(paths[0])

                
            if page_num in toc_pages:
              continue
            if break_collecting:
                break
            page=doc[page_num]
            page_height = page.rect.height
            blocks = page.get_text("dict")["blocks"]

            for block in blocks:
                if break_collecting:
                    break

                lines = block.get("lines", [])
                i = 0
                while i < len(lines):
                    if break_collecting:
                        break

                    spans = lines[i].get("spans", [])
                    if not spans:
                        i += 1
                        continue

                    y0 = spans[0]["bbox"][1]
                    y1 = spans[0]["bbox"][3]
                    if y0 < top_margin or y1 > (page_height - bottom_margin):
                        i += 1
                        continue

                    line_text = get_spaced_text_from_spans(spans).lower()
                    line_text_norm = normalize_text(line_text)

                    # Combine with next line if available
                    if i + 1 < len(lines):
                        next_spans = lines[i + 1].get("spans", [])
                        next_line_text = get_spaced_text_from_spans(next_spans).lower()
                        combined_line_norm = normalize_text(line_text + " " + next_line_text)
                    else:
                        combined_line_norm = line_text_norm

                    # Check if we should continue processing
                    if combined_line_norm and combined_line_norm in paths[0]:
                        
                        headertoContinue1 = combined_line_norm
                    if combined_line_norm and combined_line_norm in paths[-2]:
                    
                        headertoContinue2 = combined_line_norm
                    # if  'installation' in paths[-2].lower() or 'execution' in paths[-2].lower() or 'miscellaneous items' in paths[-2].lower() :
                    last_path = paths[-2].lower()
                    # if any(word in paths[-2].lower() for word in keywordstoSkip):
                    # if  'installation' in paths[-2].lower() or 'execution' in paths[-2].lower() or 'miscellaneous items' in paths[-2].lower() or 'workmanship' in paths[-2].lower() or 'testing' in paths[-2].lower() or 'labeling' in paths[-2].lower():
                    if any(keyword in last_path for keyword in keywords):
                      stringtowrite='Not to be billed'
                    else:
                      stringtowrite='To be billed'
                    if stringtowrite=='To be billed':
                        # Alltexttobebilled+= combined_line_norm  #################################################
                        if matched_header_line_norm in combined_line_norm:
                            Alltexttobebilled+='\n'
                        Alltexttobebilled+= ' '+combined_line_norm 
                    # Optimized header matching
                    existsfull = (
                        ( combined_line_norm in allchildrenheaders_set or
                        combined_line_norm in allchildrenheaders ) and heading_to_search in combined_line_norm
                    )

                    # New word-based matching
                    current_line_words = set(combined_line_norm.split())
                    heading_words = set(heading_norm.split())
                    all_words_match = current_line_words.issubset(heading_words) and len(current_line_words) > 0

                    substring_match = (
                        heading_norm in combined_line_norm or
                        combined_line_norm in heading_norm or
                        all_words_match  # Include the new word-based matching
                    )
                    # substring_match = (
                    #     heading_norm in combined_line_norm or
                    #     combined_line_norm in heading_norm
                    # )

                    if (substring_match and existsfull and not collecting and
                        len(combined_line_norm) > 0 ):#and (headertoContinue1 or headertoContinue2) ):

                        # Check header conditions more efficiently
                        header_spans = [
                            span for span in spans
                            if (is_header(span, most_common_font_size, most_common_color, most_common_font)
                                # and span['size'] >= subsubheaderFontSize
                                and span['size'] < mainHeaderFontSize)
                        ]
                        if header_spans and stringtowrite.startswith('To'):
                            collecting = True
                            # if stringtowrite=='To be billed':
                            #     Alltexttobebilled+='\n'
                            matched_header_font_size = max(span["size"] for span in header_spans)

                            # collected_lines.append(line_text)
                            valid_spans = [span for span in spans if span.get("bbox")]

                            if valid_spans:
                                x0s = [span["bbox"][0] for span in valid_spans]
                                x1s = [span["bbox"][2] for span in valid_spans]
                                y0s = [span["bbox"][1] for span in valid_spans]
                                y1s = [span["bbox"][3] for span in valid_spans]

                                header_bbox = [min(x0s), min(y0s), max(x1s), max(y1s)]

                                if page_num in current_bbox:
                                    cb = current_bbox[page_num]
                                    current_bbox[page_num] = [
                                        min(cb[0], header_bbox[0]),
                                        min(cb[1], header_bbox[1]),
                                        max(cb[2], header_bbox[2]),
                                        max(cb[3], header_bbox[3])
                                    ]
                                else:
                                    current_bbox[page_num] = header_bbox
                                last_y1s[page_num] = header_bbox[3]
                                x0, y0, x1, y1 = header_bbox

                                zoom = 200
                                left = int(x0)
                                top = int(y0)
                                zoom_str = f"{zoom},{left},{top}"
                                pageNumberFound = page_num + 1

                              # Build the query parameters
                                params = {
                                    'pdfLink': pdf_path,  # Your PDF link
                                    'keyword': heading_to_search,  # Your keyword (could be a string or list)
                                }

                                # URL encode each parameter
                                encoded_params = {key: urllib.parse.quote(value, safe='') for key, value in params.items()}

                                # Construct the final encoded link
                                encoded_link = '&'.join([f"{key}={value}" for key, value in encoded_params.items()])

                                # Correctly construct the final URL with page and zoom
                                final_url = f"{baselink}{encoded_link}#page={str(pageNumberFound)}&zoom={zoom_str}"

                                # Get current date and time
                                now = datetime.now()

                                # Format the output
                                formatted_time = now.strftime("%d/%m/%Y %I:%M:%S %p")
                                # Optionally, add the URL to a DataFrame


                                data_entry = {
                                        "NBSLink": zoom_str,
                                        "Subject": heading_to_search,
                                        "Page": str(pageNumberFound),
                                        "Author": "ADR",
                                        "Creation Date": formatted_time,
                                        "Layer": "Initial",
                                        "Code": stringtowrite,
                                        "head above 1":  paths[-2],
                                        "head above 2":  paths[0],
                                        "BodyText":collected_lines,
                                        "MC Connnection": 'Go to ' +  paths[0].strip().split()[0] +'/'+ heading_to_search.strip().split()[0] + ' in '+ filename
                                    }
                                data_list_JSON.append(data_entry)

                                # Convert list to JSON
                                json_output = json.dumps(data_list_JSON, indent=4)

                                i += 2
                                continue
                    else:
                        if (substring_match and not collecting and
                            len(combined_line_norm) > 0): # and (headertoContinue1 or headertoContinue2) ):

                            # Calculate word match percentage
                            word_match_percent = words_match_ratio(heading_norm, combined_line_norm) * 100

                            # Check if at least 70% of header words exist in this line
                            meets_word_threshold = word_match_percent >= 100

                            # Check header conditions (including word threshold)
                            header_spans = [
                                span for span in spans
                                if (is_header(span, most_common_font_size, most_common_color, most_common_font)
                                    # and span['size'] >= subsubheaderFontSize
                                    and span['size'] < mainHeaderFontSize)
                            ]

                            if header_spans and (meets_word_threshold or same_start_word(heading_to_search, combined_line_norm) ) and stringtowrite.startswith('To'):
                                collecting = True
                                if stringtowrite=='To be billed':
                                    Alltexttobebilled+='\n'
                                # if stringtowrite=='To be billed':
                                #     Alltexttobebilled+= ' '+ combined_line_norm
                                matched_header_font_size = max(span["size"] for span in header_spans)
                             
                                collected_lines.append(line_text)
                                valid_spans = [span for span in spans if span.get("bbox")]

                                if valid_spans:
                                    x0s = [span["bbox"][0] for span in valid_spans]
                                    x1s = [span["bbox"][2] for span in valid_spans]
                                    y0s = [span["bbox"][1] for span in valid_spans]
                                    y1s = [span["bbox"][3] for span in valid_spans]

                                    header_bbox = [min(x0s), min(y0s), max(x1s), max(y1s)]

                                    if page_num in current_bbox:
                                        cb = current_bbox[page_num]
                                        current_bbox[page_num] = [
                                            min(cb[0], header_bbox[0]),
                                            min(cb[1], header_bbox[1]),
                                            max(cb[2], header_bbox[2]),
                                            max(cb[3], header_bbox[3])
                                        ]
                                    else:
                                        current_bbox[page_num] = header_bbox

                                    last_y1s[page_num] = header_bbox[3]
                                    x0, y0, x1, y1 = header_bbox
                                    zoom = 200
                                    left = int(x0)
                                    top = int(y0)
                                    zoom_str = f"{zoom},{left},{top}"
                                    pageNumberFound = page_num + 1

                                  # Build the query parameters
                                    params = {
                                        'pdfLink': pdf_path,  # Your PDF link
                                        'keyword': heading_to_search,  # Your keyword (could be a string or list)
                                    }

                                    # URL encode each parameter
                                    encoded_params = {key: urllib.parse.quote(value, safe='') for key, value in params.items()}

                                    # Construct the final encoded link
                                    encoded_link = '&'.join([f"{key}={value}" for key, value in encoded_params.items()])

                                    # Correctly construct the final URL with page and zoom
                                    final_url = f"{baselink}{encoded_link}#page={str(pageNumberFound)}&zoom={zoom_str}"

                                    # Get current date and time
                                    now = datetime.now()

                                    # Format the output
                                    formatted_time = now.strftime("%d/%m/%Y %I:%M:%S %p")
                                    # Optionally, add the URL to a DataFrame


                                    data_entry = {
                                            "NBSLink": zoom_str,
                                            "Subject": heading_to_search,
                                            "Page": str(pageNumberFound),
                                            "Author": "ADR",
                                            "Creation Date": formatted_time,
                                            "Layer": "Initial",
                                            "Code": stringtowrite,
                                            "head above 1":  paths[-2],
                                            "head above 2":  paths[0],
                                            "BodyText":collected_lines,
                                            "MC Connnection": 'Go to ' +  paths[0].strip().split()[0] +'/'+ heading_to_search.strip().split()[0] + ' in '+ filename
                                        }
                                    data_list_JSON.append(data_entry)

                                    # Convert list to JSON
                                    json_output = json.dumps(data_list_JSON, indent=4)

                
                                    i += 2
                                    continue
                    if collecting:
                        norm_line = normalize_text(line_text)

                        # Optimized URL check
                        if url_pattern.match(norm_line):
                            line_is_header = False
                        else:
                            line_is_header = any(is_header(span, most_common_font_size, most_common_color, most_common_font) for span in spans)

                        if line_is_header:
                            header_font_size = max(span["size"] for span in spans)
                            is_probably_real_header = (
                                header_font_size >= matched_header_font_size and
                                is_header(spans[0], most_common_font_size, most_common_color, most_common_font) and
                                len(line_text.strip()) > 2
                            )

                            if (norm_line != matched_header_line_norm and
                                norm_line != heading_norm and
                                is_probably_real_header):
                                if line_text not in heading_norm:
                                  collecting = False
                                  done = True
                                  headertoContinue1 = False
                                  headertoContinue2=False
                                  for page_num, bbox in current_bbox.items():
                                      bbox[3] = last_y1s.get(page_num, bbox[3])
                                      page_highlights[page_num] = bbox
                                  highlight_boxes(docHighlights, page_highlights,stringtowrite)

                                  break_collecting = True
                                  break

                        if break_collecting:
                            break

                        collected_lines.append(line_text)
                        valid_spans = [span for span in spans if span.get("bbox")]
                        if valid_spans:
                            x0s = [span["bbox"][0] for span in valid_spans]
                            x1s = [span["bbox"][2] for span in valid_spans]
                            y0s = [span["bbox"][1] for span in valid_spans]
                            y1s = [span["bbox"][3] for span in valid_spans]

                            line_bbox = [min(x0s), min(y0s), max(x1s), max(y1s)]

                            if page_num in current_bbox:
                                cb = current_bbox[page_num]
                                current_bbox[page_num] = [
                                    min(cb[0], line_bbox[0]),
                                    min(cb[1], line_bbox[1]),
                                    max(cb[2], line_bbox[2]),
                                    max(cb[3], line_bbox[3])
                                ]
                            else:
                                current_bbox[page_num] = line_bbox

                            last_y1s[page_num] = line_bbox[3]
                    i += 1

        if not done:
            for page_num, bbox in current_bbox.items():
                bbox[3] = last_y1s.get(page_num, bbox[3])
                page_highlights[page_num] = bbox
            if  'installation' in paths[-2].lower() or 'execution' in paths[-2].lower() or 'miscellaneous items' in paths[-2].lower() :
                stringtowrite='Not to be billed'
            else:
                stringtowrite='To be billed'
            highlight_boxes(docHighlights, page_highlights,stringtowrite)

    # docHighlights.save("highlighted_output.pdf", garbage=4, deflate=True)

    dbxTeam = tsadropboxretrieval.ADR_Access_DropboxTeam('user')
    metadata = dbxTeam.sharing_get_shared_link_metadata(pdf_path)
    dbPath = '/TSA JOBS/ADR Test/FIND/'
    pdf_bytes = BytesIO()
    docHighlights.save(pdf_bytes)
    pdflink = tsadropboxretrieval.uploadanyFile(doc=docHighlights, path=dbPath, pdfname=filename)
    json_output=changepdflinks(json_output,pdflink)
    return pdf_bytes.getvalue(), docHighlights , json_output, Alltexttobebilled , filename







def extract_section_under_header_tobebilledMultiplePDFS(multiplePDF_Paths):
    # keywordstoSkip=["installation", "execution", "miscellaneous items", "workmanship", "testing", "labeling"]
    filenames=[]
    keywords = {'installation', 'execution', 'miscellaneous items', 'workmanship', 'testing', 'labeling'}

    arrayofPDFS=multiplePDF_Paths.split(',')
    print(multiplePDF_Paths)
    print(arrayofPDFS)
    docarray=[]
    jsons=[]
    df = pd.DataFrame(columns=["PDF Name","NBSLink","Subject","Page","Author","Creation Date","Layer",'Code', 'head above 1', "head above 2","BodyText"])
    for pdf_path in arrayofPDFS:
        headertoContinue1 = False
        headertoContinue2=False
        Alltexttobebilled=''
        parsed_url = urlparse(pdf_path)
        filename = os.path.basename(parsed_url.path)
        filename = unquote(filename)  # decode URL-encoded characters
        filenames.append(filename)
        # Optimized URL handling
        if pdf_path and ('http' in pdf_path or 'dropbox' in pdf_path):
            pdf_path = pdf_path.replace('dl=0', 'dl=1')
    
        # Cache frequently used values
        response = requests.get(pdf_path)
        pdf_content = BytesIO(response.content)
        if not pdf_content:
            raise ValueError("No valid PDF content found.")
    
        doc = fitz.open(stream=pdf_content, filetype="pdf")
        docHighlights = fitz.open(stream=pdf_content, filetype="pdf")
        most_common_font_size, most_common_color, most_common_font = get_regular_font_size_and_color(doc)
    
        # Precompute regex patterns
        dot_pattern = re.compile(r'\.{3,}')
        url_pattern = re.compile(r'https?://\S+|www\.\S+')
    

        toc_pages = get_toc_page_numbers(doc)
    
        headers, top_3_font_sizes, smallest_font_size, headersSpans = extract_headers(
            doc, toc_pages, most_common_font_size, most_common_color, most_common_font, top_margin, bottom_margin
        )
    
        hierarchy = build_header_hierarchy(doc, toc_pages, most_common_font_size, most_common_color, most_common_font)
        listofHeaderstoMarkup = get_leaf_headers_with_paths(hierarchy)
        
        # Precompute all children headers once
        allchildrenheaders = [normalize_text(item['text']) for item, p in listofHeaderstoMarkup]
        allchildrenheaders_set = set(allchildrenheaders)  # For faster lookups
    
        # df = pd.DataFrame(columns=["NBSLink","Subject","Page","Author","Creation Date","Layer",'Code', 'head above 1', "head above 2","BodyText"])
        dictionaryNBS={}
        data_list_JSON = []
        json_output=[]
        currentgroupname=''
        if len(top_3_font_sizes)==3:
            mainHeaderFontSize, subHeaderFontSize, subsubheaderFontSize = top_3_font_sizes
        elif len(top_3_font_sizes)==2:
            mainHeaderFontSize= top_3_font_sizes[0]
            subHeaderFontSize= top_3_font_sizes[1]
            subsubheaderFontSize= top_3_font_sizes[1]
    
        
    
        # Preload all pages to avoid repeated loading
        # pages = [doc.load_page(page_num) for page_num in range(len(doc)) if page_num not in toc_pages]
    
        for heading_to_searchDict, paths in listofHeaderstoMarkup:
            heading_to_search = heading_to_searchDict['text']
            heading_to_searchPageNum = heading_to_searchDict['page']
    
            # Initialize variables
            headertoContinue1 = False
            headertoContinue2 = False
            matched_header_line = None
            done = False
            collecting = False
            collected_lines = []
            page_highlights = {}
            current_bbox = {}
            last_y1s = {}
            mainHeader = ''
            subHeader = ''
            matched_header_line_norm = heading_to_search
            break_collecting = False
            heading_norm = normalize_text(heading_to_search)
            paths_norm = [normalize_text(p) for p in paths[0]] if paths and paths[0] else []
            for page_num in range(heading_to_searchPageNum,len(doc)):
                # print(heading_to_search)
                if paths[0].strip().lower() != currentgroupname.strip().lower():
                    Alltexttobebilled+= paths[0] +'\n'
                    currentgroupname=paths[0]
                    # print(paths[0])
    
                    
                if page_num in toc_pages:
                  continue
                if break_collecting:
                    break
                page=doc[page_num]
                page_height = page.rect.height
                blocks = page.get_text("dict")["blocks"]
    
                for block in blocks:
                    if break_collecting:
                        break
    
                    lines = block.get("lines", [])
                    i = 0
                    while i < len(lines):
                        if break_collecting:
                            break
    
                        spans = lines[i].get("spans", [])
                        if not spans:
                            i += 1
                            continue
    
                        y0 = spans[0]["bbox"][1]
                        y1 = spans[0]["bbox"][3]
                        if y0 < top_margin or y1 > (page_height - bottom_margin):
                            i += 1
                            continue
    
                        line_text = get_spaced_text_from_spans(spans).lower()
                        line_text_norm = normalize_text(line_text)
    
                        # Combine with next line if available
                        if i + 1 < len(lines):
                            next_spans = lines[i + 1].get("spans", [])
                            next_line_text = get_spaced_text_from_spans(next_spans).lower()
                            combined_line_norm = normalize_text(line_text + " " + next_line_text)
                        else:
                            combined_line_norm = line_text_norm
    
                        # Check if we should continue processing
                        if combined_line_norm and combined_line_norm in paths[0]:
                            
                            headertoContinue1 = combined_line_norm
                        if combined_line_norm and combined_line_norm in paths[-2]:
                        
                            headertoContinue2 = combined_line_norm
                        # if  'installation' in paths[-2].lower() or 'execution' in paths[-2].lower() or 'miscellaneous items' in paths[-2].lower() :
                        last_path = paths[-2].lower()
                        # if any(word in paths[-2].lower() for word in keywordstoSkip):
                        # if  'installation' in paths[-2].lower() or 'execution' in paths[-2].lower() or 'miscellaneous items' in paths[-2].lower() or 'workmanship' in paths[-2].lower() or 'testing' in paths[-2].lower() or 'labeling' in paths[-2].lower():
                        if any(keyword in last_path for keyword in keywords):
                          stringtowrite='Not to be billed'
                        else:
                          stringtowrite='To be billed'
                        if stringtowrite=='To be billed':
                            # Alltexttobebilled+= combined_line_norm  #################################################
                            if matched_header_line_norm in combined_line_norm:
                                Alltexttobebilled+='\n'
                            Alltexttobebilled+= ' '+combined_line_norm 
                        # Optimized header matching
                        existsfull = (
                            ( combined_line_norm in allchildrenheaders_set or
                            combined_line_norm in allchildrenheaders ) and heading_to_search in combined_line_norm
                        )
    
                        # New word-based matching
                        current_line_words = set(combined_line_norm.split())
                        heading_words = set(heading_norm.split())
                        all_words_match = current_line_words.issubset(heading_words) and len(current_line_words) > 0
    
                        substring_match = (
                            heading_norm in combined_line_norm or
                            combined_line_norm in heading_norm or
                            all_words_match  # Include the new word-based matching
                        )
                        # substring_match = (
                        #     heading_norm in combined_line_norm or
                        #     combined_line_norm in heading_norm
                        # )
    
                        if (substring_match and existsfull and not collecting and
                            len(combined_line_norm) > 0 ):#and (headertoContinue1 or headertoContinue2) ):
    
                            # Check header conditions more efficiently
                            header_spans = [
                                span for span in spans
                                if (is_header(span, most_common_font_size, most_common_color, most_common_font)
                                    # and span['size'] >= subsubheaderFontSize
                                    and span['size'] < mainHeaderFontSize)
                            ]
                            if header_spans and stringtowrite.startswith('To') :
                                collecting = True
                                # if stringtowrite=='To be billed':
                                #     Alltexttobebilled+='\n'
                                matched_header_font_size = max(span["size"] for span in header_spans)
    
                                # collected_lines.append(line_text)
                                valid_spans = [span for span in spans if span.get("bbox")]
    
                                if valid_spans:
                                    x0s = [span["bbox"][0] for span in valid_spans]
                                    x1s = [span["bbox"][2] for span in valid_spans]
                                    y0s = [span["bbox"][1] for span in valid_spans]
                                    y1s = [span["bbox"][3] for span in valid_spans]
    
                                    header_bbox = [min(x0s), min(y0s), max(x1s), max(y1s)]
    
                                    if page_num in current_bbox:
                                        cb = current_bbox[page_num]
                                        current_bbox[page_num] = [
                                            min(cb[0], header_bbox[0]),
                                            min(cb[1], header_bbox[1]),
                                            max(cb[2], header_bbox[2]),
                                            max(cb[3], header_bbox[3])
                                        ]
                                    else:
                                        current_bbox[page_num] = header_bbox
                                    last_y1s[page_num] = header_bbox[3]
                                    x0, y0, x1, y1 = header_bbox
    
                                    zoom = 200
                                    left = int(x0)
                                    top = int(y0)
                                    zoom_str = f"{zoom},{left},{top}"
                                    pageNumberFound = page_num + 1
    
                                  # Build the query parameters
                                    params = {
                                        'pdfLink': pdf_path,  # Your PDF link
                                        'keyword': heading_to_search,  # Your keyword (could be a string or list)
                                    }
    
                                    # URL encode each parameter
                                    encoded_params = {key: urllib.parse.quote(value, safe='') for key, value in params.items()}
    
                                    # Construct the final encoded link
                                    encoded_link = '&'.join([f"{key}={value}" for key, value in encoded_params.items()])
    
                                    # Correctly construct the final URL with page and zoom
                                    final_url = f"{baselink}{encoded_link}#page={str(pageNumberFound)}&zoom={zoom_str}"
    
                                    # Get current date and time
                                    now = datetime.now()
    
                                    # Format the output
                                    formatted_time = now.strftime("%d/%m/%Y %I:%M:%S %p")
                                    # Optionally, add the URL to a DataFrame
    
    
                                    data_entry = {
                                            "PDF Name":filename,
                                            "NBSLink": zoom_str,
                                            "Subject": heading_to_search,
                                            "Page": str(pageNumberFound),
                                            "Author": "ADR",
                                            "Creation Date": formatted_time,
                                            "Layer": "Initial",
                                            "Code": stringtowrite,
                                            "head above 1":  paths[-2],
                                            "head above 2":  paths[0],
                                            "BodyText":collected_lines,
                                            "MC Connnection": 'Go to ' +  paths[0].strip().split()[0] +'/'+ heading_to_search.strip().split()[0] + ' in '+ filename
                                        }
                                    data_list_JSON.append(data_entry)
    
                                    # Convert list to JSON
                                    # json_output = [data_list_JSON]
                                    # json_output = json.dumps(data_list_JSON, indent=4)
    
                                    i += 2
                                    continue
                        else:
                            if (substring_match and not collecting and
                                len(combined_line_norm) > 0): # and (headertoContinue1 or headertoContinue2) ):
    
                                # Calculate word match percentage
                                word_match_percent = words_match_ratio(heading_norm, combined_line_norm) * 100
    
                                # Check if at least 70% of header words exist in this line
                                meets_word_threshold = word_match_percent >= 100
    
                                # Check header conditions (including word threshold)
                                header_spans = [
                                    span for span in spans
                                    if (is_header(span, most_common_font_size, most_common_color, most_common_font)
                                        # and span['size'] >= subsubheaderFontSize
                                        and span['size'] < mainHeaderFontSize)
                                ]
    
                                if header_spans and (meets_word_threshold or same_start_word(heading_to_search, combined_line_norm) ) and stringtowrite.startswith('To'):
                                    collecting = True
                                    if stringtowrite=='To be billed':
                                        Alltexttobebilled+='\n'
                                    # if stringtowrite=='To be billed':
                                    #     Alltexttobebilled+= ' '+ combined_line_norm
                                    matched_header_font_size = max(span["size"] for span in header_spans)
                                 
                                    collected_lines.append(line_text)
                                    valid_spans = [span for span in spans if span.get("bbox")]
    
                                    if valid_spans:
                                        x0s = [span["bbox"][0] for span in valid_spans]
                                        x1s = [span["bbox"][2] for span in valid_spans]
                                        y0s = [span["bbox"][1] for span in valid_spans]
                                        y1s = [span["bbox"][3] for span in valid_spans]
    
                                        header_bbox = [min(x0s), min(y0s), max(x1s), max(y1s)]
    
                                        if page_num in current_bbox:
                                            cb = current_bbox[page_num]
                                            current_bbox[page_num] = [
                                                min(cb[0], header_bbox[0]),
                                                min(cb[1], header_bbox[1]),
                                                max(cb[2], header_bbox[2]),
                                                max(cb[3], header_bbox[3])
                                            ]
                                        else:
                                            current_bbox[page_num] = header_bbox
    
                                        last_y1s[page_num] = header_bbox[3]
                                        x0, y0, x1, y1 = header_bbox
                                        zoom = 200
                                        left = int(x0)
                                        top = int(y0)
                                        zoom_str = f"{zoom},{left},{top}"
                                        pageNumberFound = page_num + 1
    
                                      # Build the query parameters
                                        params = {
                                            'pdfLink': pdf_path,  # Your PDF link
                                            'keyword': heading_to_search,  # Your keyword (could be a string or list)
                                        }
    
                                        # URL encode each parameter
                                        encoded_params = {key: urllib.parse.quote(value, safe='') for key, value in params.items()}
    
                                        # Construct the final encoded link
                                        encoded_link = '&'.join([f"{key}={value}" for key, value in encoded_params.items()])
    
                                        # Correctly construct the final URL with page and zoom
                                        final_url = f"{baselink}{encoded_link}#page={str(pageNumberFound)}&zoom={zoom_str}"
    
                                        # Get current date and time
                                        now = datetime.now()
    
                                        # Format the output
                                        formatted_time = now.strftime("%d/%m/%Y %I:%M:%S %p")
                                        # Optionally, add the URL to a DataFrame
    
    
                                        data_entry = {
                                                "PDF Name":filename,
                                                "NBSLink": zoom_str,
                                                "Subject": heading_to_search,
                                                "Page": str(pageNumberFound),
                                                "Author": "ADR",
                                                "Creation Date": formatted_time,
                                                "Layer": "Initial",
                                                "Code": stringtowrite,
                                                "head above 1":  paths[-2],
                                                "head above 2":  paths[0],
                                                "BodyText":collected_lines,
                                                "MC Connnection": 'Go to ' +  paths[0].strip().split()[0] +'/'+ heading_to_search.strip().split()[0] + ' in '+ filename
                                            }
                                        data_list_JSON.append(data_entry)
    
                                        # Convert list to JSON
                                        # json_output = [data_list_JSON]
                                        # json_output = json.dumps(data_list_JSON, indent=4)
    
                    
                                        i += 2
                                        continue
                        if collecting:
                            norm_line = normalize_text(line_text)
    
                            # Optimized URL check
                            if url_pattern.match(norm_line):
                                line_is_header = False
                            else:
                                line_is_header = any(is_header(span, most_common_font_size, most_common_color, most_common_font) for span in spans)
    
                            if line_is_header:
                                header_font_size = max(span["size"] for span in spans)
                                is_probably_real_header = (
                                    header_font_size >= matched_header_font_size and
                                    is_header(spans[0], most_common_font_size, most_common_color, most_common_font) and
                                    len(line_text.strip()) > 2
                                )
    
                                if (norm_line != matched_header_line_norm and
                                    norm_line != heading_norm and
                                    is_probably_real_header):
                                    if line_text not in heading_norm:
                                      collecting = False
                                      done = True
                                      headertoContinue1 = False
                                      headertoContinue2=False
                                      for page_num, bbox in current_bbox.items():
                                          bbox[3] = last_y1s.get(page_num, bbox[3])
                                          page_highlights[page_num] = bbox
                                      highlight_boxes(docHighlights, page_highlights,stringtowrite)
    
                                      break_collecting = True
                                      break
    
                            if break_collecting:
                                break
    
                            collected_lines.append(line_text)
                            valid_spans = [span for span in spans if span.get("bbox")]
                            if valid_spans:
                                x0s = [span["bbox"][0] for span in valid_spans]
                                x1s = [span["bbox"][2] for span in valid_spans]
                                y0s = [span["bbox"][1] for span in valid_spans]
                                y1s = [span["bbox"][3] for span in valid_spans]
    
                                line_bbox = [min(x0s), min(y0s), max(x1s), max(y1s)]
    
                                if page_num in current_bbox:
                                    cb = current_bbox[page_num]
                                    current_bbox[page_num] = [
                                        min(cb[0], line_bbox[0]),
                                        min(cb[1], line_bbox[1]),
                                        max(cb[2], line_bbox[2]),
                                        max(cb[3], line_bbox[3])
                                    ]
                                else:
                                    current_bbox[page_num] = line_bbox
    
                                last_y1s[page_num] = line_bbox[3]
                        i += 1
    
            if not done:
                for page_num, bbox in current_bbox.items():
                    bbox[3] = last_y1s.get(page_num, bbox[3])
                    page_highlights[page_num] = bbox
                if  'installation' in paths[-2].lower() or 'execution' in paths[-2].lower() or 'miscellaneous items' in paths[-2].lower() :
                    stringtowrite='Not to be billed'
                else:
                    stringtowrite='To be billed'
                highlight_boxes(docHighlights, page_highlights,stringtowrite)
        docarray.append(docHighlights)
        jsons.append(data_list_JSON)
    dbxTeam = tsadropboxretrieval.ADR_Access_DropboxTeam('user')
    dbPath = '/TSA JOBS/ADR Test/FIND/'
    jsonCombined=[]
    for i in range(len(arrayofPDFS)):
        singlepdf=arrayofPDFS[i]
        
        metadata = dbxTeam.sharing_get_shared_link_metadata(singlepdf) 
        pdf_bytes = BytesIO()
        docHighlights.save(pdf_bytes)
        pdflink = tsadropboxretrieval.uploadanyFile(doc=docarray[i], path=dbPath, pdfname=filenames[i])
        # json_copy = copy.deepcopy(jsons[i])
        # Update links for this JSON
        # json_output1 = changepdflinks(json_copy, pdflink)
        json_output1=changepdflinks(jsons[i],pdflink)
        jsonCombined.extend(json_output1)
    combined_json_str = json.dumps(jsonCombined, indent=1)
    print(combined_json_str)
    return pdf_bytes.getvalue(), docHighlights , combined_json_str, Alltexttobebilled , filenames