File size: 41,026 Bytes
e0ab505
 
4279593
 
e0ab505
4279593
 
e0ab505
 
 
4279593
 
 
e0ab505
4279593
 
 
 
 
 
 
 
e0ab505
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4279593
e0ab505
 
 
 
 
4279593
e0ab505
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4279593
e0ab505
 
 
 
4279593
e0ab505
 
 
 
4279593
e0ab505
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4279593
e0ab505
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4279593
e0ab505
 
 
 
 
 
 
4279593
e0ab505
 
 
 
 
 
 
 
 
 
 
 
 
 
4279593
e0ab505
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4279593
e0ab505
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4279593
e0ab505
 
 
 
 
 
 
 
 
4279593
e0ab505
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4279593
e0ab505
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4279593
e0ab505
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4279593
e0ab505
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4279593
e0ab505
4279593
e0ab505
 
4279593
e0ab505
 
 
 
4279593
e0ab505
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4279593
e0ab505
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4279593
e0ab505
 
 
 
 
 
4279593
e0ab505
 
4279593
e0ab505
4279593
e0ab505
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4279593
e0ab505
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4279593
e0ab505
 
 
 
 
 
 
 
 
 
 
 
4279593
e0ab505
 
 
4279593
e0ab505
 
 
4279593
e0ab505
 
 
4279593
e0ab505
 
 
4279593
e0ab505
 
 
 
 
 
 
4279593
e0ab505
 
 
4279593
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c8abe84
 
 
4279593
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85a4a41
4279593
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85a4a41
 
4279593
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# from crawl4ai import AsyncWebCrawler
# from urllib.parse import urlparse
import aiohttp
import asyncio
# from asyncio.exceptions import TimeoutError as async_timeout
from fast_async import make_async
from bs4 import BeautifulSoup, NavigableString
# import secrets
# from datetime import datetime
# import random
import os
import re
import uuid
from typing import List, Dict, Optional #, Tuple
from io import BytesIO
import PyPDF2
from fake_useragent import FakeUserAgent
from htmlrag import clean_html, build_block_tree, EmbedHTMLPruner, BM25HTMLPruner
from transformers import AutoTokenizer, AutoConfig
import torch
import time

# class Crawler:
#     def __init__(self, user_dir=None, rate_limit=1, headless=True, verbose=False):
#         self.session_pool = {}  # Track active sessions
#         self.verbose = verbose
#         self.rate_limit = rate_limit
#         self.user_dir = user_dir
#         self.headless = headless
#         self.crawler = AsyncWebCrawler(
#             context_options={"userDataDir": self.user_dir}, 
#             headless=self.headless, 
#             verbose=self.verbose
#         )

#         # Browser context management
#         self._browser_contexts = {}
#         self._context_locks = {}

#     async def get_browser_context(self, session_id):
#         """Get or create a browser context with proper locking"""
#         if session_id not in self._context_locks:
#             self._context_locks[session_id] = asyncio.Lock()
        
#         async with self._context_locks[session_id]:
#             if session_id not in self._browser_contexts:
#                 context = await self.crawler.new_context()
#                 self._browser_contexts[session_id] = context
#             return self._browser_contexts[session_id]
        
#     async def cleanup_browser_context(self, session_id):
#         """Safely cleanup browser context"""
#         if session_id in self._context_locks:
#             async with self._context_locks[session_id]:
#                 if session_id in self._browser_contexts:
#                     try:
#                         await asyncio.shield(
#                             self._browser_contexts[session_id].close()
#                         )
#                     except Exception as e:
#                         print(f"Error cleaning up browser context: {e}")
#                     finally:
#                         del self._browser_contexts[session_id]

#     def create_session(self):
#         """Create a new session with secure ID"""
#         session_id = secrets.token_urlsafe(32)  # Secure session ID
#         self.session_pool[session_id] = {
#             'created_at': datetime.now(),
#             'last_used': datetime.now(),
#             'requests_count': 0
#         }
#         return session_id

#     def rotate_session(self, session_id):
#         """Implement session rotation logic"""
#         if self.session_pool[session_id]['requests_count'] > 100:
#             self.cleanup_session(session_id)
#             return self.create_session()
#         return session_id

#     def is_dynamic_page(self, html_content: str) -> Tuple[bool, Optional[str]]:
#         """Analyzes HTML content to determine if a webpage is dynamically loaded"""
#         def _check_structural_indicators(soup: BeautifulSoup) -> Dict[str, int]:
#             """Check structural indicators of dynamic content loading."""
#             scores = {
#                 'empty_containers': 0,
#                 'repeated_structures': 0,
#                 'api_endpoints': 0,
#                 'state_management': 0
#             }
            
#             # 1. Check for empty content containers
#             main_containers = soup.find_all(['main', 'div', 'section'], 
#                                         class_=lambda x: x and any(term in str(x).lower() 
#                                         for term in ['content', 'main', 'feed', 'list', 'container']))
            
#             for container in main_containers:
#                 # Check if container is empty or has minimal content
#                 if len(container.find_all()) < 3:
#                     scores['empty_containers'] += 1
                
#                 # Check for repeated similar structures (common in dynamic lists)
#                 children = container.find_all(recursive=False)
#                 if children:
#                     first_child_class = children[0].get('class', [])
#                     similar_siblings = [c for c in children[1:] 
#                                     if c.get('class', []) == first_child_class]
#                     if len(similar_siblings) > 0:
#                         scores['repeated_structures'] += 1

#             # 2. Check for API endpoints in scripts
#             scripts = soup.find_all('script', {'src': True})
#             api_patterns = ['/api/', '/graphql', '/rest/', '/v1/', '/v2/']
#             for script in scripts:
#                 if any(pattern in script['src'] for pattern in api_patterns):
#                     scores['api_endpoints'] += 1

#             # 3. Look for state management setup
#             state_patterns = [
#                 r'window\.__INITIAL_STATE__',
#                 r'window\.__PRELOADED_STATE__',
#                 r'__REDUX_STATE__',
#                 r'__NUXT__',
#                 r'__NEXT_DATA__',
#                 r'window\.__data'
#             ]
            
#             inline_scripts = soup.find_all('script')
#             for script in inline_scripts:
#                 if script.string:
#                     for pattern in state_patterns:
#                         if re.search(pattern, script.string):
#                             scores['state_management'] += 1

#             return scores

#         def _check_modern_framework_indicators(soup: BeautifulSoup) -> Dict[str, int]:
#             """Check for indicators of modern web frameworks and dynamic loading patterns."""
#             scores = {
#                 'framework_roots': 0,
#                 'hydration': 0,
#                 'routing': 0
#             }
            
#             # 1. Framework-specific root elements
#             framework_roots = {
#                 'react': ['react-root', 'react-app', 'root', '__next'],
#                 'angular': ['ng-version', 'ng-app'],
#                 'vue': ['v-app', '#app', 'nuxt-app'],
#                 'modern': ['app-root', 'application', 'spa-root']
#             }
            
#             for framework, identifiers in framework_roots.items():
#                 for id_value in identifiers:
#                     if (soup.find(attrs={'id': re.compile(id_value, re.I)}) or 
#                         soup.find(attrs={'class': re.compile(id_value, re.I)}) or
#                         soup.find(attrs={'data-': re.compile(id_value, re.I)})):
#                         scores['framework_roots'] += 1

#             # 2. Check for hydration indicators
#             hydration_patterns = [
#                 r'hydrate',
#                 r'createRoot',
#                 r'reactive',
#                 r'observable'
#             ]
            
#             scripts = soup.find_all('script')
#             for script in scripts:
#                 if script.string:
#                     for pattern in hydration_patterns:
#                         if re.search(pattern, script.string):
#                             scores['hydration'] += 1

#             # 3. Check for dynamic routing setup
#             router_patterns = [
#                 'router-view',
#                 'router-link',
#                 'route-link',
#                 'history.push',
#                 'navigation'
#             ]
            
#             for pattern in router_patterns:
#                 if soup.find(class_=re.compile(pattern, re.I)) or \
#                 soup.find(id=re.compile(pattern, re.I)):
#                     scores['routing'] += 1

#             return scores

#         def _check_dynamic_loading_patterns(soup: BeautifulSoup) -> Dict[str, int]:
#             """Check for various dynamic content loading patterns."""
#             scores = {
#                 'infinite_scroll': 0,
#                 'load_more_buttons': 0,
#                 'pagination': 0,
#                 'lazy_loading': 0,
#                 'loading_indicators': 0
#             }
            
#             # 1. Check for infinite scroll indicators
#             scroll_indicators = [
#                 'infinite-scroll',
#                 'data-infinite',
#                 'data-virtualized',
#                 'virtual-scroll',
#                 'scroll-container',
#                 'scroll-viewport'
#             ]
            
#             for indicator in scroll_indicators:
#                 elements = soup.find_all(
#                     lambda tag: any(indicator.lower() in str(v).lower() 
#                                 for v in tag.attrs.values())
#                 )
#                 if elements:
#                     scores['infinite_scroll'] += len(elements)

#             # 2. Check for load more buttons
#             button_patterns = [
#                 r'load[_-]?more',
#                 r'show[_-]?more',
#                 r'view[_-]?more',
#                 r'see[_-]?more',
#                 r'more[_-]?posts',
#                 r'more[_-]?results'
#             ]
            
#             for pattern in button_patterns:
#                 elements = soup.find_all(
#                     ['button', 'a', 'div', 'span'],
#                     text=re.compile(pattern, re.I)
#                 )
#                 if elements:
#                     scores['load_more_buttons'] += len(elements)

#             # 3. Check for pagination
#             pagination_patterns = [
#                 'pagination',
#                 'page-numbers',
#                 'page-nav',
#                 'page-links'
#             ]
            
#             for pattern in pagination_patterns:
#                 elements = soup.find_all(class_=re.compile(pattern, re.I))
#                 if elements:
#                     scores['pagination'] += len(elements)

#             # 4. Check for lazy loading
#             lazy_patterns = ['lazy', 'data-src', 'data-lazy']
#             for pattern in lazy_patterns:
#                 elements = soup.find_all(
#                     lambda tag: any(pattern.lower() in str(v).lower() 
#                                 for v in tag.attrs.values())
#                 )
#                 if elements:
#                     scores['lazy_loading'] += len(elements)

#             # 5. Check for loading indicators
#             loading_patterns = [
#                 'loading',
#                 'spinner',
#                 'skeleton',
#                 'placeholder',
#                 'shimmer'
#             ]
            
#             for pattern in loading_patterns:
#                 elements = soup.find_all(class_=re.compile(pattern, re.I))
#                 if elements:
#                     scores['loading_indicators'] += len(elements)

#             return scores

#         def _evaluate_dynamic_indicators(
#             structural: Dict[str, int],
#             framework: Dict[str, int],
#             loading: Dict[str, int]
#         ) -> Tuple[bool, Optional[str]]:
#             """Evaluate dynamic indicators and return JavaScript instructions."""
#             methods = []
#             js_snippets = []

#             # Infinite Scroll
#             if loading['infinite_scroll'] > 0:
#                 methods.append("scroll")
#                 js_snippets.append(
#                     """
# window.scrollTo(0, document.body.scrollHeight);
# await new Promise(resolve => setTimeout(resolve, 1000));
#                     """.strip().replace('\n', '')
#                 )

#             # Load More Buttons
#             if loading['load_more_buttons'] > 0:
#                 methods.append("button")
#                 js_snippets.append(
#                     """
# const button = Array.from(document.querySelectorAll('button, a, div, span')).find(
#     el => /load[_-]?more|show[_-]?more/i.test(el.textContent)
# );
# if (button) {
#     button.click();
#     await new Promise(resolve => setTimeout(resolve, 1000));
# } else {
#     console.warn("No 'Load More' button found.");
# }
#                     """.strip().replace('\n', '')
#                 )

#             # Paginated Interfaces
#             if loading.get('pagination', 0) > 0:
#                 methods.append("pagination")
#                 js_snippets.append(
#                     """
#   const nextPage = document.querySelector('a[rel="next"], .pagination-next, .page-next');
# if (nextPage) {
#     nextPage.click();
#     await new Promise(resolve => setTimeout(resolve, 1000));
# } else {
#     console.warn("No pagination link found.");
# }
#                     """.strip().replace('\n', '')
#                 )

#             # Lazy Loading
#             if loading.get('lazy_loading', 0) > 0:
#                 methods.append("lazy")
#                 js_snippets.append(
#                     """
# if (window.__INITIAL_STATE__ || window.__REDUX_STATE__ || window.__NUXT__ || window.__NEXT_DATA__) {
#     console.log('Framework state detected. Consider monitoring network requests for further actions.');
# }
#                     """.strip().replace('\n', '')
#                 )

#             # Framework and State Management Indicators
#             if framework['framework_roots'] > 0 or structural['state_management'] > 0:
#                 methods.append("stateful")
#                 js_snippets.append(
#                     """
# if (window.__INITIAL_STATE__ || window.__REDUX_STATE__ || window.__NUXT__ || window.__NEXT_DATA__) {
#     console.log('Detected stateful framework data loading.');
#                     }
#                     """.strip().replace('\n', '')
#                 )

#             # API-Driven Content
#             if structural['api_endpoints'] > 0:
#                 methods.append("api")
#                 js_snippets.append(
#                     """
# console.log('API requests detected. Use browser devtools to inspect network activity for specific endpoints.');
#                     """.strip().replace('\n', '')
#                 )

#             # Aggregate and finalize
#             if methods:
#                 js_code = "\n".join(js_snippets)
#                 return True, js_code
            
#             return False, None

#         # Main execution
#         soup = BeautifulSoup(html_content, 'html.parser')
        
#         # Run all checks
#         structural_scores = _check_structural_indicators(soup)
#         framework_scores = _check_modern_framework_indicators(soup)
#         loading_scores = _check_dynamic_loading_patterns(soup)
        
#         # Evaluate results
#         return _evaluate_dynamic_indicators(structural_scores, framework_scores, loading_scores)

#     async def crawl(
#             self, 
#             url, 
#             depth=2, 
#             max_pages=5, 
#             session_id=None, 
#             human_simulation=True, 
#             rotate_user_agent=True, 
#             rotate_proxy=True, 
#             return_html=False
#         ):
#         if not session_id:
#             session_id = self.create_session()

#         session_id = self.rotate_session(session_id)

#         # List of rotating user agents
#         user_agents = [
#             'Chrome/115.0.0.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36',
#             'Chrome/115.0.0.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36', 
#             'Chrome/115.0.0.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36',
#             'Chrome/115.0.0.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36',
#             'Chrome/115.0.0.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36'
#         ]

#         # List of rotating proxies
#         proxies = [
#             "http://50.62.183.123:80",
#             "http://104.129.60.84:6516", 
#             "http://156.228.118.163:3128",
#             "http://142.111.104.97:6107",
#             "http://156.228.99.99:3128"
#         ]

#         try:
#             async with self.crawler as crawler:
#                 # Rotate user agent and optimize headers for each attempt
#                 headers = {
#                     "User-Agent": random.choice(user_agents) if rotate_user_agent else user_agents[0],
#                     "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
#                     "Accept-Language": "en-US,en;q=0.5",
#                     "Accept-Encoding": "gzip, deflate",
#                     "Connection": "keep-alive",
#                     "Upgrade-Insecure-Requests": "1",
#                     "Sec-Fetch-Dest": "document",
#                     "Sec-Fetch-Mode": "navigate",
#                     "Sec-Fetch-Site": "none",
#                     "Sec-Fetch-User": "?1",
#                     "Cache-Control": "max-age=0"
#                 }
            
#                 # Update crawler headers for rotation
#                 crawler.crawler_strategy.headers = headers

#                 if rotate_proxy:
#                     # Update crawler proxy for rotation
#                     crawler.crawler_strategy.proxy = random.choice(proxies)

#                 result_1 = await crawler.arun(
#                     session_id=session_id,
#                     url=url,
#                     magic=True if human_simulation else False,
#                     simulate_user=True if human_simulation else False,
#                     override_navigator=True if human_simulation else False,
#                     depth=depth,
#                     max_pages=max_pages,
#                     bypass_cache=True,
#                     remove_overlay_elements=True,
#                     delay_before_retrieve_html=1.0,
#                     verbose=self.verbose
#                 )

#             # Update session metrics
#             self.session_pool[session_id]['requests_count'] += 1
#             self.session_pool[session_id]['last_used'] = datetime.now()

#             if result_1.success:
#                 if hasattr(result_1, 'html'):
#                     success, js_code = self.is_dynamic_page(result_1.html)

#                     if success:
#                         async with crawler as crawler:
#                             # Update crawler headers for rotation
#                             crawler.crawler_strategy.headers = headers

#                             if rotate_proxy:
#                                 # Update crawler proxy for rotation
#                                 crawler.crawler_strategy.proxy = random.choice(proxies)

#                             print(f"Executing JS code: {js_code}")
#                             result_2 = await crawler.arun(
#                                 session_id=session_id,
#                                 url=url,
#                                 magic=True if human_simulation else False,
#                                 simulate_user=True if human_simulation else False,
#                                 override_navigator=True if human_simulation else False,
#                                 depth=depth,
#                                 max_pages=max_pages,
#                                 js_code=js_code,
#                                 bypass_cache=True,
#                                 remove_overlay_elements=True,
#                                 delay_before_retrieve_html=1.0,
#                                 verbose=self.verbose
#                             )

#                         if result_2.success:
#                             result = result_2
#                         else:
#                             result = result_1

#                         # Update session metrics
#                         self.session_pool[session_id]['requests_count'] += 1
#                         self.session_pool[session_id]['last_used'] = datetime.now()

#                     else:
#                         result = result_1
            
#                     if return_html and hasattr(result, 'html'):
#                         return result.html
#                     elif hasattr(result, 'fit_markdown'):
#                         return result.fit_markdown
#                     elif hasattr(result, 'markdown'):
#                         return self.extract_content(result.markdown)
                
#         except Exception as e:
#             print(f"Error crawling {url}: {str(e)}")

#         return None
        
#     async def crawl_with_retry(
#             self, 
#             url, 
#             depth=2, 
#             max_pages=5, 
#             max_retries=3, 
#             backoff_factor=1, 
#             session_id=None,
#             human_simulation=True,
#             rotate_user_agent=True, 
#             rotate_proxy=True,
#             return_html=False,
#             timeout=10.0
#         ):
#         """Crawl with retry logic and anti-blocking measures"""

#         async def attempt_crawl(attempt):
#             try:
#                 async with async_timeout.timeout(timeout):
#                     context = await self.get_browser_context(session_id)
#                     return await self.crawl(
#                         context, 
#                         url, 
#                         depth, 
#                         max_pages, 
#                         session_id, 
#                         human_simulation, 
#                         rotate_user_agent,
#                         rotate_proxy,
#                         return_html
#                     )
#             except asyncio.TimeoutError:
#                 print(f"Timeout on attempt {attempt} for {url}")
#                 raise
#             except Exception as e:
#                 print(f"Error on attempt {attempt} for {url}: {e}")
#                 raise

#         if not self.is_valid_url(url) and not self.is_html_url(url):
#             print(f"Invalid URL: {url}")
#             return f"No web results found for query: {url}"

#         for attempt in range(max_retries):
#             try:
#                 if attempt > 0:
#                     # Add delay between retries with exponential backoff
#                     delay = backoff_factor * (2 ** (attempt - 1))
#                     await asyncio.sleep(delay)
                
#                 return await attempt_crawl(attempt + 1)
#             except Exception as e:
#                 if attempt == max_retries - 1:
#                     print(f"Max retries ({max_retries}) reached for {url}")
#                     return f"Failed to crawl after {max_retries} attempts: {url}"
#                 continue

#         return f"No content found after {max_retries} attempts for: {url}"

#     def extract_content(self, html_content):
#         soup = BeautifulSoup(html_content, 'html.parser')
#         for script in soup(["script", "style"]):
#             script.decompose()
#         text = soup.get_text()
#         lines = (line.strip() for line in text.splitlines())
#         chunks = (phrase.strip() for line in lines for phrase in line.split("  "))
#         text = '\n'.join(chunk for chunk in chunks if chunk)
#         return text
    
#     def cleanup_session(self, session_id):
#         """Clean up a session"""
#         print(f"Cleaning up session {session_id}")
#         if session_id in self.session_pool:
#             self.crawler.crawler_strategy.kill_session(session_id)
#             del self.session_pool[session_id]

#     def cleanup_expired_sessions(self):
#         """Regular cleanup of expired sessions using proper time calculation"""
#         try:
#             current_time = datetime.now()
#             expired_sessions = []
            
#             for sid, data in self.session_pool.items():
#                 # Calculate time difference in seconds
#                 time_diff = (current_time - data['last_used']).total_seconds()
                
#                 # Check if more than 1 hour (3600 seconds)
#                 if time_diff > 3600:
#                     expired_sessions.append(sid)
            
#             # Cleanup expired sessions
#             for session_id in expired_sessions:
#                 self.cleanup_session(session_id)
                
#         except Exception as e:
#             if self.verbose:
#                 print(f"Error during session cleanup: {str(e)}")
    
#     @staticmethod
#     def is_valid_url(url):
#         try:
#             result = urlparse(url)
#             return all([result.scheme, result.netloc])
#         except ValueError:
#             return False
        
#     @staticmethod
#     def is_html_url(url):
#         return url.endswith(".html") or url.endswith(".htm")
    
class CustomCrawler:
    def __init__(
            self, 
            embed_model: str = "HIT-TMG/KaLM-embedding-multilingual-mini-instruct-v1", 
            max_concurrent_requests: int = 10, 
            verbose: bool = True
        ):
        print(f"πŸ¦€ Initializing the crawler") if verbose else None
        time.sleep(1)
        self.embed_model = embed_model
        self.max_concurrent_requests = max_concurrent_requests
        self.verbose = verbose
        self.ua = FakeUserAgent()
        self.semaphore = asyncio.Semaphore(self.max_concurrent_requests)
        self.sessions = {}

        # Intilizing HTML Pruners and Tokenizer
        print(f"πŸ”ƒ Loading HTML Pruners and Tokenizer with {self.embed_model}") if self.verbose else None
        self.bm25_html_pruner = BM25HTMLPruner()
        self.embed_html_pruner = EmbedHTMLPruner(
            embed_model=self.embed_model,
            local_inference=True
        )
        self.tokenizer = AutoTokenizer.from_pretrained(
            self.embed_model, 
            use_fast=True, 
            trust_remote_code=True,
            device="cuda" if torch.cuda.is_available() else "cpu"
        )

        # Get the model config and set the max context length for the model
        print(f"πŸ› οΈ  Getting model configuration for {self.embed_model}") if self.verbose else None
        self.config = AutoConfig.from_pretrained(self.embed_model)
        self.tokenizer.max_seq_length = self.config.max_position_embeddings
        print(f"πŸ“ Setting max context length to {self.tokenizer.max_seq_length}") if self.verbose else None

    async def create_session(self):
        session_id = str(uuid.uuid4())
        timeout = aiohttp.ClientTimeout(total=600) # Set a 10-minute timeout
        connector = aiohttp.TCPConnector(limit=self.max_concurrent_requests) # Connection pool
        self.sessions[session_id] = aiohttp.ClientSession(timeout=timeout, connector=connector)
        print(f"πŸ”— Created session: {session_id}") if self.verbose else None
        return session_id

    async def close_session(self, session_id):
        session = self.sessions.pop(session_id, None)
        if session:
            await session.close()
            print(f"πŸŒ‚ Closed session: {session_id}") if self.verbose else None

    async def cleanup_expired_sessions(self, expiration_time: int = 600): # Default 10 minutes
        current_time = time.time()
        expired_sessions = []
        print("πŸ” Checking for expired sessions") if self.verbose else None
        for session_id, (session, creation_time) in self.sessions.items():
            if current_time - creation_time > expiration_time:
                expired_sessions.append(session_id)

        for session_id in expired_sessions:
            await self.close_session(session_id)

        print(f"πŸ—‘οΈ  Successfully cleaned up all expired sessions") if self.verbose else None

    @make_async
    def html_rag(
            self, 
            query: str, 
            html: str, 
            max_context_length: int = 32000, 
            buffer: int = 2000
        ) -> str:
        if not html:
            raise Exception("No HTML contents provided.")
        
        # Validate HTML structure
        try:
            BeautifulSoup(html, 'html.parser')
        except Exception as e:
            raise Exception(f"Invalid HTML content: {e}")

        prompt_for_retrieval = \
"""Given a query, your task is to retrieve the most relevant passages that answers and/or is relevant to the query.

Query:"""

        self.embed_html_pruner.query_instruction_for_retrieval = prompt_for_retrieval

        print(f"🧹 Pruning HTML for query: {query}") if self.verbose else None
        cleaned_html = clean_html(html)
        block_tree, cleaned_html = build_block_tree(cleaned_html, max_node_words=10)

        block_rankings = self.bm25_html_pruner.calculate_block_rankings(query, cleaned_html, block_tree)
        
        max_context_window = max_context_length - buffer
        pruned_html = self.embed_html_pruner.prune_HTML(
            cleaned_html,
            block_tree,
            block_rankings,
            self.tokenizer,
            max_context_window
        )
        print(f"πŸ‘ Successfully pruned HTML for query: {query}") if self.verbose else None
        return pruned_html

    async def fetch_page_contents(
        self,
        urls: List[str],
        query: Optional[str] = None,
        session_id: Optional[str] = None,
        max_attempts: int = 3,
        delay: float = 1.0,
        timeout: float = 10.0,
        return_type: str = "markdown",
        rotate_headers: bool = True,
    ) -> List[Optional[str]]:
        async def fetch_single_page(url, proxies, session=None, query=query):
            for attempt in range(max_attempts):
                print(f"πŸ” Attempt {attempt + 1}/{max_attempts}: Fetching content from {url}") if self.verbose else None
                content = await self._fetch_page_contents(
                    url=url,
                    query=query,
                    timeout=timeout,
                    return_type=return_type,
                    rotate_headers=rotate_headers,
                    proxies=proxies,
                    session=session
                )
                
                if content:
                    print(f"βœ… Successfully fetched content from {url}") if self.verbose else None
                    return content
                else:
                    if max_attempts > 1:
                        print(f"🚫 Failed to fetch content from {url}. Retrying in {delay} seconds...") if self.verbose else None
                        await asyncio.sleep(delay)

            print(f"🚫 Failed to fetch content from {url} after {max_attempts} attempts.") if self.verbose else None
            return None
        
        proxy_list = self.load_proxies()  # Load proxies from environment variables
        if proxy_list:
            proxies = proxy_list
        else:
            proxies = None

        if not urls:
            raise Exception("No URLs provided!")
            
        if return_type == "fit_markdown" and query is None:
            raise Exception("Query must be provided when return_type is 'fit_markdown'!")

        if session_id:  # Use existing session if provided
            if session_id not in self.sessions:
                raise ValueError(f"Invalid session ID: {session_id}")
            session = self.sessions[session_id]
            tasks = [fetch_single_page(url, proxies, session) for url in urls]  # Pass session to tasks
        else:  # No session handling if session_id is None
            tasks = [fetch_single_page(url, proxies) for url in urls]  # No session passed

        results = await asyncio.gather(*tasks)
        return [result for result in results if result is not None]
    
    async def _fetch_page_contents(
        self, 
        url: str, 
        query: Optional[str] = None,
        timeout: float = 5.0,
        return_type: str = "markdown",
        rotate_headers: bool = True,
        proxies: Optional[List[str]] = None,
        session: Optional[aiohttp.ClientSession] = None
    ) -> Optional[str]:
        async def get_content(response, return_type=return_type):
            print(f"πŸ“„ Getting content from {url}") if self.verbose else None
            if return_type == "html":
                return await response.text()

            response.raise_for_status()
            content_type = response.headers.get('Content-Type', '').lower()

            if 'application/pdf' in content_type:
                content = await response.read()
                text = self.extract_text_from_pdf(content)
                return text
            elif 'text/html' in content_type:
                html_content = await response.text()
                if return_type == "fit_markdown":
                    html_content = self.html_rag(query, html_content).wait()

                soup = BeautifulSoup(html_content, "html.parser")
                for script_or_style in soup(["script", "style"]):
                    script_or_style.decompose()
                text = self.html_to_markdown(soup)
                return text.strip()
            else:
                print(f"🚫 Unsupported content type {content_type} for URL {url}") if self.verbose else None
                return None

        headers = self.get_headers() if rotate_headers else {}
        proxy = self.get_proxy(proxies) if proxies else None

        # Total connection timeout
        timeout_config = aiohttp.ClientTimeout(total=timeout)

        try:
            # Use provided session if available
            if session:
                async with session.get(url, proxy=proxy, timeout=timeout_config, headers=headers) as response:
                    return await get_content(response)
            # Otherwise, create a new session for each request
            else:
                async with aiohttp.ClientSession() as new_session:
                    async with new_session.get(url, proxy=proxy, timeout=timeout_config, headers=headers) as response:
                        return await get_content(response)

        except aiohttp.ClientError as e:
            print(f"🚫 Request Exception for {url}: {e}") if self.verbose else None
            return None
        except asyncio.TimeoutError as e:
            print(f"🚫 Timeout error for {url}") if self.verbose else None
            return None
        except Exception as e:
            print(f"🚫 Unexpected error fetching {url}: {e}") if self.verbose else None
            return None
        
    def load_proxies(self) -> Optional[List[str]]:
        # Get all environment variables
        env_vars = dict(os.environ)

        # Load proxies from environment variables
        proxy_pattern = re.compile(r"PROXY_\d+")
        proxies = [env_vars[key] for key in env_vars if proxy_pattern.match(key)]

        if proxies:
            print(f"πŸ”Œ Loaded {len(proxies)} proxies from environment variables") if self.verbose else None
            return proxies
        else:
            return None
    
    def get_proxy(self, proxies: List[str]) -> str:
        if proxies:  # Check if the proxies list is not empty
            return next(iter(proxies))
        return None  # Or raise an exception, handle differently, etc.

    def get_headers(self) -> Dict[str, str]:
        return {'User-Agent': self.ua.random}

    def extract_text_from_pdf(self, pdf_content: bytes) -> str:
        try:
            print(f"πŸ“• Extracting text from PDF") if self.verbose else None
            pdf_reader = PyPDF2.PdfReader(BytesIO(pdf_content))
            text = ''
            for page in pdf_reader.pages:
                text += page.extract_text()
            print(f"πŸ’ͺ Successfully extracted text from PDF") if self.verbose else None
            return text
        except Exception as e:
            print(f"🚫 Error extracting text from PDF: {e}") if self.verbose else None
            return ""
        
    def html_to_markdown(self, soup):
        markdown_text = ""
        print(f"πŸ“Ÿ Converting HTML to Markdown") if self.verbose else None
        def process_element(element, indent=0):
            nonlocal markdown_text

            if isinstance(element, NavigableString):
                text = str(element).strip()
                if text:
                    markdown_text += text + " "
                return

            tag = element.name

            if tag == "h1":
                markdown_text += "# " + element.text.strip() + "\n\n"
            elif tag == "h2":
                markdown_text += "## " + element.text.strip() + "\n\n"
            elif tag == "h3":
                markdown_text += "### " + element.text.strip() + "\n\n"
            elif tag == "h4":
                markdown_text += "#### " + element.text.strip() + "\n\n"
            elif tag == "h5":
                markdown_text += "##### " + element.text.strip() + "\n\n"
            elif tag == "h6":
                markdown_text += "###### " + element.text.strip() + "\n\n"
            elif tag == "p":
                markdown_text += element.text.strip() + "\n\n"
            elif tag == "br":
                markdown_text += "\n"
            elif tag == "ul":
                for li in element.find_all("li", recursive=False):
                    markdown_text += "  " * indent + "- "
                    process_element(li, indent + 1)
                    markdown_text += "\n"
                markdown_text += "\n"
            elif tag == "ol":
                for i, li in enumerate(element.find_all("li", recursive=False), 1):
                    markdown_text += "  " * indent + f"{i}. "
                    process_element(li, indent + 1)
                    markdown_text += "\n"
                markdown_text += "\n"
            elif tag == "table":
                rows = element.find_all("tr")
                for row in rows:
                    cells = row.find_all(["td", "th"])
                    row_text = [cell.text.strip() for cell in cells]
                    markdown_text += "| " + " | ".join(row_text) + " |\n"
                    if row == rows[0]:  # Header row separator
                        markdown_text += "| " + " | ".join(["---"] * len(cells)) + " |\n"
                markdown_text += "\n"
            elif tag == "blockquote":
                markdown_text += "> " + element.text.strip().replace("\n", "\n> ") + "\n\n"
            elif tag == "strong" or tag == "b":
                markdown_text += "**" + element.text.strip() + "**"
            elif tag == "em" or tag == "i":
                markdown_text += "*" + element.text.strip() + "*"
            elif tag == "code":
                markdown_text += "`" + element.text.strip() + "`"
            elif tag == "pre":
                markdown_text += "```\n" + element.text + "\n```\n\n"
            elif tag == "hr":
                markdown_text += "---\n\n"
            else:
                for child in element.children:
                    process_element(child, indent)

        process_element(soup)
        print(f"πŸ‘Œ Successfully converted HTML to Markdown") if self.verbose else None
        return markdown_text
    
if __name__ == "__main__":
    import time
    import winloop

    URLS = [
        "https://en.wikipedia.org/wiki/Treaty_Principles_Bill#:~:text=The%20Treaty%20Principles%20Bill%2C%20or,of%20the%20Treaty%20of%20Waitangi.",
        "https://www.parliament.nz/en/pb/sc/make-a-submission/document/54SCJUST_SCF_227E6D0B-E632-42EB-CFFE-08DCFEB826C6/principles-of-the-treaty-of-waitangi-bill",
        "https://en.wikipedia.org/wiki/Waitangi_Tribunal",
        "https://aljazeera.com/news/2024/11/19/why-are-new-zealands-maori-protesting-over-colonial-era-treaty-bill",
        "https://downiewenjack.ca/treaty-of-waitangi-treaty-principles-bill/"
    ]#  * 10   # Make 50 requests

    query = "What is the Treaty of Waitangi Bill?"
    loop = asyncio.get_event_loop()
    custom_crawler = CustomCrawler(max_concurrent_requests=1000)
    session_id = loop.run_until_complete(custom_crawler.create_session())
    start = time.perf_counter()
    winloop.install()
    result = loop.run_until_complete(custom_crawler.fetch_page_contents(
            URLS, 
            query,
            session_id=session_id, 
            timeout=20,
            max_attempts=1,
            return_type="fit_markdown",
        )
    )
    end = time.perf_counter()
    loop.run_until_complete(custom_crawler.close_session(session_id))
    loop.run_until_complete(custom_crawler.cleanup_expired_sessions())
    print("\n\n".join([f"Document {i+1}:\n\n{result[i]}" for i in range(len(result))]))  
    print(f"\n\nTime taken: {end - start} seconds")