-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscraper.py
More file actions
3123 lines (2824 loc) · 113 KB
/
Copy pathscraper.py
File metadata and controls
3123 lines (2824 loc) · 113 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import re
import sys
import time
import json
import math
import uuid
import asyncio
import hashlib
import argparse
import gzip
import random
import struct
import sqlite3
import logging
import threading
import unicodedata
from collections import Counter, defaultdict, OrderedDict
from dataclasses import dataclass, field, asdict
from functools import lru_cache
from pathlib import Path
from urllib.parse import (
urljoin, urlparse, urlencode, parse_qs, quote, unquote,
)
import orjson
import pymupdf
from selectolax.lexbor import LexborHTMLParser
from lxml import etree
from lxml_html_clean import Cleaner
import justext
import trafilatura
from trafilatura import bare_extraction, extract as trafilatura_extract
from htmldate import find_date
from dateparser import parse as dateparser_parse
from dateutil import parser as dateutil_parser
import textstat
import regex
import pyphen
import tld as _tld_mod
from courlan import clean_url, normalize_url, is_navigation_page
from defusedxml import ElementTree as SafeET
from babel import Locale
from tzlocal import get_localzone
from curl_cffi.requests import AsyncSession as _AsyncRequestsSession
from folder_manager import FolderManager, FolderError
from error_fast import (
install_all as _error_fast_install,
safe_asyncio_run,
safe_async_session_close,
fast_catch,
ErrorFast,
Kind as _EFKind,
swallow as _ef_swallow,
)
_error_fast_install()
from config import (
SEEDS, SEED_FILE, SEED_URL_FILE, SEED_SITEMAP_URLS, SEED_RSS_FEEDS,
OCR_MIN_TEXT_LEN, OCR_DPI, OCR_LANG, OCR_TIMEOUT,
MAX_LINKS_PER_PAGE,
QUALITY_MIN_WORDS, QUALITY_MIN_FLESCH, QUALITY_MIN_SENTENCES,
QUALITY_MAX_BOILERPLATE_RATIO, QUALITY_MIN_LANG_CONFIDENCE,
CONTENT_MIN_CHARS, CONTENT_MAX_CHARS,
TITLE_MAX_CHARS, INTRO_MAX_CHARS, SECTION_MAX_CHARS,
LANGUAGE_ALLOWLIST, LANGUAGE_FILTER_ENABLED,
LANGUAGE_DETECT_ORDER, LANGUAGE_NGRAM_ENABLED,
LANGUAGE_NGRAM_MIN_CONFIDENCE, LANGUAGE_NGRAM_MIN_TEXT_LEN,
LANGUAGE_RECORD_SOURCE, ENCODING_FALLBACK,
BLOCKED_STATUS_CODES, BLOCKED_BODY_MARKERS,
MAX_QUEUE_SIZE, MAX_DEPTH, MAX_WORKERS, OUTPUT_PATH,
MAX_RETRIES_PER_REQUEST, RETRY_BACKOFF_BASE,
DOMAIN_TOKEN_BUCKET_RATE, DOMAIN_TOKEN_BUCKET_BURST,
AGENT_CHUNK_ENABLED, AGENT_CHUNK_SIZE_TOKENS,
AGENT_CHUNK_OVERLAP_TOKENS, AGENT_CHUNK_MIN_TOKENS,
AGENT_CHUNK_MAX_CHUNKS_PER_DOC, AGENT_CHUNK_INCLUDE_HEADING_CONTEXT,
AGENT_CHUNK_INCLUDE_URL_CONTEXT,
AGENT_TOKEN_COUNT_RATIO,
AGENT_SUMMARY_ENABLED, AGENT_SUMMARY_MAX_TOKENS,
AGENT_SUMMARY_MIN_TOKENS, AGENT_SUMMARY_TOP_SENTENCES,
AGENT_ENTITY_EXTRACT_ENABLED, AGENT_ENTITY_MAX_PER_DOC,
AGENT_ENTITY_MIN_LENGTH, AGENT_ENTITY_DEDUP,
AGENT_ENTITY_CASE_INSENSITIVE_DEDUP,
AGENT_TOPIC_EXTRACT_ENABLED, AGENT_TOPIC_MAX_PER_DOC,
AGENT_TOPIC_MIN_SCORE, AGENT_TOPIC_NGRAM_MAX,
AGENT_KEYWORD_EXTRACT_ENABLED, AGENT_KEYWORD_MAX_PER_DOC,
AGENT_KEYWORD_MIN_LENGTH, AGENT_KEYWORD_LANGUAGES,
AGENT_PII_REDACT_ENABLED, AGENT_PII_REDACT_EMAIL,
AGENT_PII_REDACT_PHONE, AGENT_PII_REDACT_SSN,
AGENT_PII_REDACT_CREDIT_CARD, AGENT_PII_REDACT_IP,
AGENT_PII_REDACT_PLACEHOLDER,
AGENT_RECORD_FIELDS, AGENT_SCHEMA_VERSION,
AGENT_INCLUDE_PROVENANCE, AGENT_INCLUDE_QUALITY,
AGENT_INCLUDE_EMBEDDING_READY,
AGENT_INCLUDE_IDEMPOTENCY_KEY, AGENT_INCLUDE_EXTRACTOR_VERSION,
AGENT_INCLUDE_CONFIG_HASH,
EXTRACTOR_VERSION,
NLP_COMPLEXITY_GATE_ENABLED, NLP_MIN_WORDS, NLP_MIN_SENTENCES,
REGEX_INPUT_CAP, REGEX_URL_CAP, REGEX_WORD_CAP,
EXTRACTION_SCORING_ENABLED, EXTRACTION_SCORE_LENGTH_WEIGHT,
EXTRACTION_SCORE_BOILER_WEIGHT, EXTRACTION_SCORE_FLESCH_WEIGHT,
EXTRACTION_SCORE_TITLE_WEIGHT, EXTRACTION_SCORE_SECTIONS_WEIGHT,
EXTRACTION_SCORE_PUNCT_WEIGHT, EXTRACTION_SCORE_LENGTH_CAP,
EXTRACTION_SCORE_SECTIONS_CAP, EXTRACTION_SCORE_FLESCH_BEST,
EXTRACTION_SCORE_FLESCH_OK,
ARTICLE_ROOT_SELECTORS, ARTICLE_ROOT_MIN_CHARS,
PDF_MAX_PAGES, PDF_MAX_OCR_PAGES, PDF_TEXT_MODE,
PDF_RECONSTRUCT_PARAGRAPHS, PDF_TRUNCATE_MARKER,
ENTITY_FREQUENCY_FILTER_ENABLED, ENTITY_MIN_OCCURRENCES,
ENTITY_REPORTING_VERBS, ENTITY_REPORTING_WINDOW,
ENTITY_FIRSTNAME_DICT_ENABLED, ENTITY_FIRSTNAME_WEIGHT,
ENTITY_NON_FIRSTNAME_WEIGHT, ENTITY_BOUNDARY_ENABLED,
ENTITY_SECTION_AWARE, ENTITY_SKIP_TAGS,
ENTITY_AUTHOR_BOOST, ENTITY_ORG_SUFFIXES, ENTITY_COREF_ENABLED,
CHUNK_DEDUP_ENABLED, CHUNK_DEDUP_HAMMING, CHUNK_DEDUP_PREFER_LONGER,
AGENT_CHUNK_OFFSET_AWARE,
JS_REQUIRED_MARKERS,
CACHE_DIR, CACHE_EXTRACTION, CACHE_HARD, CACHE_DB,
CACHE_MAX_ROWS, CACHE_TTL_SECONDS,
MOS_ENABLED, MOS_HEDGE_ENABLED, MOS_HEDGE_POLICIES,
MOS_HEDGE_DELAY_MS, MOS_STICKY_TTL, MOS_STICKY_SUCCESS_THRESHOLD,
MOS_STICKY_FAILURE_THRESHOLD,
MOS_DAILY_BUDGET, MOS_BUDGET_WARN_RATIO, MOS_BUDGET_STOP_RATIO,
MOS_HOST_PREFS_FILE, MOS_BUDGET_FILE, MOS_CACHE_DB,
CORS_RELAYS, MD_RELAYS,
VERIFY_ENABLED, VERIFY_WAYBACK, VERIFY_COMMONCRAWL,
VERIFY_URLSCAN, VERIFY_DOH, VERIFY_DOH_RESOLVERS,
VERIFY_SAMPLE_RATIO,
ENRICH_DDG, ENRICH_WIKIPEDIA, ENRICH_DATAMUSE,
ENRICH_KIPRIO, ENRICH_MICROLINK,
WAYBACK_FIRST_HOSTS, WAYBACK_FIRST_ENABLED,
FREE_PROXY_ENABLED, FREE_PROXY_SOURCES,
FREE_PROXY_VALIDATE_ENDPOINT, FREE_PROXY_VALIDATE_INTERVAL,
API_ROUTER_ENABLED, API_ROUTER_TIMEOUT, API_ROUTER_MAX_ITEMS,
SE_API_ENABLED, SE_API_KEY, SE_API_MAX_ANSWERS, SE_API_TIMEOUT,
SE_ROUTE_BEFORE_DIRECT, SE_ACCEPT_EMPTY_TITLE,
MOS_FIRST_HOSTS,
LOG_LEVEL,
)
_LOG = logging.getLogger("scraper")
_LOG.setLevel(getattr(logging, LOG_LEVEL, logging.INFO))
def _log(msg, *args, level=logging.INFO):
try:
_LOG.log(level, msg, *args)
except Exception:
pass
# ============================================================================
# PRELOADER
# ============================================================================
class Preloader:
def __init__(self):
self.results = OrderedDict()
self.t_start = None
self.done = False
def _step(self, name, fn):
t0 = time.monotonic()
try:
fn()
elapsed = time.monotonic() - t0
self.results[name] = {"ok": True, "elapsed": round(elapsed, 4)}
_log("preload[%s] ok in %.3fs", name, elapsed)
except Exception as e:
elapsed = time.monotonic() - t0
self.results[name] = {"ok": False, "elapsed": round(elapsed, 4),
"error": repr(e)[:200]}
_log("preload[%s] FAILED in %.3fs: %r", name, elapsed, e,
level=logging.WARNING)
def load(self):
if self.done:
return self.results
self.t_start = time.monotonic()
_log("preloader starting")
self._step("folder_manager", FolderManager.bootstrap)
self._step("error_fast", _error_fast_install)
self._step("regexes", self._warm_regexes)
self._step("stopwords", self._warm_stopwords)
self._step("tld", self._warm_tld)
self._step("trafilatura", self._warm_trafilatura)
self._step("justext", self._warm_justext)
self._step("selectolax", self._warm_selectolax)
self._step("htmldate", self._warm_htmldate)
self._step("dateparser", self._warm_dateparser)
self._step("textstat", self._warm_textstat)
self._step("pymupdf", self._warm_pymupdf)
self._step("babel", self._warm_babel)
self._step("tzlocal", self._warm_tzlocal)
self._step("pyphen", self._warm_pyphen)
self._step("curl_cffi", self._warm_curl_cffi)
self._step("entity_patterns", self._warm_entity_patterns)
self._step("lang_stopword_map", self._warm_lang_map)
self._step("api_router", self._warm_api_router)
self._step("se_api", self._warm_se_api)
self._step("config_hash", self._warm_config_hash)
elapsed = time.monotonic() - self.t_start
failed = [k for k, v in self.results.items() if not v.get("ok")]
_log("preloader finished in %.3fs (failed=%d)", elapsed, len(failed))
self.done = True
return self.results
def _warm_regexes(self):
for rx in (_WS_RE, _CTRL_RE, _SENT_RE, _WORD_RE, _URL_RE, _CJK_RE,
_TITLE_TOKEN_RE):
rx.search("warmup")
def _warm_stopwords(self):
for _lang, stopset in _STOPWORDS_BY_LANG.items():
_ = len(stopset)
def _warm_tld(self):
for probe in ("example.com", "en.wikipedia.org", "co.uk",
"example.co.jp"):
_tld_mod.get_tld(probe, fix_protocol=True, fail_silently=True)
def _warm_trafilatura(self):
html = ("<html><head><title>T</title></head><body><article><h1>H</h1>"
"<p>" + ("warm content sentence. " * 60) + "</p></article>"
"</body></html>")
bare_extraction(html, url="https://example.com/",
include_comments=False, include_tables=True,
favor_recall=True, with_metadata=True)
trafilatura_extract(html, url="https://example.com/",
favor_recall=True)
def _warm_justext(self):
html = ("<html><body><p>" + ("warm content sentence. " * 40)
+ "</p></body></html>").encode("utf-8")
justext.justext(html, justext.get_stoplist("English"))
def _warm_selectolax(self):
tree = LexborHTMLParser("<html><body><p>warm</p></body></html>")
_ = tree.css_first("p")
_ = tree.css("p")
def _warm_htmldate(self):
find_date("<html><body><time datetime='2020-01-01'>x</time></body></html>",
original_date=True, extensive_search=False,
outputformat="%Y-%m-%d")
def _warm_dateparser(self):
try:
dateparser_parse("2020-01-01", languages=["en"])
except Exception:
pass
try:
dateutil_parser.parse("2020-01-01")
except Exception:
pass
def _warm_textstat(self):
sample = "The quick brown fox jumps over the lazy dog. " * 20
for fn in (textstat.lexicon_count, textstat.sentence_count,
textstat.syllable_count, textstat.flesch_reading_ease,
textstat.flesch_kincaid_grade, textstat.gunning_fog,
textstat.smog_index,
textstat.automated_readability_index,
textstat.coleman_liau_index,
textstat.dale_chall_readability_score,
textstat.difficult_words):
try:
fn(sample)
except Exception:
pass
try:
textstat.text_standard(sample, float_output=False)
except Exception:
pass
def _warm_pymupdf(self):
try:
doc = pymupdf.open()
page = doc.new_page()
page.insert_text((72, 72), "warm")
_ = doc.tobytes()
doc.close()
except Exception:
pass
def _warm_babel(self):
try:
Locale.parse("en")
Locale.parse("de")
except Exception:
pass
def _warm_tzlocal(self):
try:
get_localzone()
except Exception:
pass
def _warm_pyphen(self):
_get_pyphen()
def _warm_curl_cffi(self):
try:
from curl_cffi.requests import Session
s = Session(impersonate="chrome136", default_headers=False)
s.close()
except Exception:
pass
def _warm_entity_patterns(self):
for pat in _ENTITY_PATTERNS.values():
pat.search("warmup")
def _warm_lang_map(self):
_ = AGENT_KEYWORD_LANGUAGES
def _warm_api_router(self):
try:
import api_router # noqa: F401
except ImportError:
pass
def _warm_se_api(self):
try:
import se_api # noqa: F401
except ImportError:
pass
def _warm_config_hash(self):
_config_hash()
def report(self):
lines = []
for name, r in self.results.items():
status = "ok" if r.get("ok") else "FAIL"
lines.append(f" {name:20s} {status:5s} {r.get('elapsed', 0):>7.4f}s")
if not r.get("ok"):
lines.append(f" error: {r.get('error')}")
return "\n".join(lines)
_PRELOADER = Preloader()
def preload(force=False):
if force or not _PRELOADER.done:
return _PRELOADER.load()
return _PRELOADER.results
# ============================================================================
# MODULE CONSTANTS
# ============================================================================
_WS_RE = regex.compile(r"\s+")
_CTRL_RE = regex.compile(r"[\p{C}\p{Zl}\p{Zp}]+")
_SENT_RE = regex.compile(r"(?<=[.!?])\s+(?=[A-Z\"'(])")
_WORD_RE = regex.compile(r"\p{L}{3,}")
_URL_RE = regex.compile(r"https?://[^\s<>\"']+")
_CJK_RE = regex.compile(r"[\u4e00-\u9fff\u3040-\u30ff\uac00-\ud7af]")
_TITLE_TOKEN_RE = regex.compile(r"\b[\w\-']{3,}\b")
_SKIP_HEADINGS = frozenset((
"references", "external links", "see also", "notes",
"further reading", "bibliography", "sources", "citations",
"footnotes", "navigation",
))
_ABBREV_GUARD = (
"Mr.", "Mrs.", "Ms.", "Dr.", "Prof.", "Sr.", "Jr.", "St.",
"vs.", "etc.", "eg.", "ie.", "Fig.", "No.", "Vol.",
)
_CLEANER = Cleaner(
scripts=True, javascript=True, comments=True, style=True,
links=False, meta=False, page_structure=False,
embedded=False, frames=False, forms=False, safe_attrs_only=False,
)
_PII_PATTERNS = {
"EMAIL": regex.compile(r"\b[\w.+\-]+@[\w\-]+\.[\w.\-]+\b"),
"PHONE": regex.compile(r"\+?\d[\d\s().\-]{7,}\d"),
"SSN": regex.compile(r"\b\d{3}-\d{2}-\d{4}\b"),
"CC": regex.compile(r"\b(?:\d[ \-]?){13,19}\b"),
"IP": regex.compile(r"\b(?:\d{1,3}\.){3}\d{1,3}\b"),
}
_ENTITY_PATTERNS = {
"EMAIL": _PII_PATTERNS["EMAIL"],
"URL": _URL_RE,
"MONEY": regex.compile(r"(?:\$|€|£|¥)\s?\d[\d,.]*"),
"PERCENT": regex.compile(r"\b\d+(?:\.\d+)?\s?%"),
"DATE": regex.compile(r"\b(?:19|20)\d{2}-\d{2}-\d{2}\b"),
"YEAR": regex.compile(r"\b(?:19|20)\d{2}\b"),
"PHONE": _PII_PATTERNS["PHONE"],
"PERSON": regex.compile(r"\b[A-Z][a-z]{2,}(?:\s+[A-Z][a-z]{2,}){1,2}\b"),
"ORG": regex.compile(
r"\b(?:[A-Z][a-zA-Z]{1,}\s){1,4}"
r"(?:Inc|Ltd|LLC|Corp|GmbH|Co|SA|AG|Foundation|Institute|University|"
r"Ministry|Agency|Bureau|Council|Committee|Association|Organization|"
r"Organisation|Group|Holdings)\b\.?"
),
}
_STOPWORDS_EN = frozenset("""
a about above after again against all am an and any are aren't as at be because
been before being below between both but by can't cannot could couldn't did
didn't do does doesn't doing don't down during each few for from further had
hadn't has hasn't have haven't having he he'd he'll he's her here here's hers
herself him himself his how how's i i'd i'll i'm i've if in into is isn't it
it's its itself let's me more most mustn't my myself no nor not of off on once
only or other ought our ours ourselves out over own same shan't she she'd
she'll she's should shouldn't so some such than that that's the their theirs
them themselves then there there's these they they'd they'll they're they've
this those through to too under until up very was wasn't we we'd we'll we're
we've were weren't what what's when when's where where's which while who who's
whom why why's with won't would wouldn't you you'd you'll you're you've your
yours yourself yourselves will just don should now
""".split())
_STOPWORDS_BY_LANG = {
"en": _STOPWORDS_EN,
"de": frozenset("der die das und oder aber ist sind war waren ein eine einen einem eines dem den mit von zu auf für über unter nach bei aus durch".split()),
"fr": frozenset("le la les un une des et ou mais est sont était étaient avec de pour par sur dans sous entre vers chez sans".split()),
"es": frozenset("el la los las un una unos unas y o pero es son era eran con de por para sobre bajo entre hacia sin".split()),
"it": frozenset("il la i le un uno una e o ma è sono era erano con di per su sotto tra verso senza".split()),
"pt": frozenset("o a os as um uma uns umas e ou mas é são era eram com de por para sobre sob entre até sem".split()),
"nl": frozenset("de het een en of maar is zijn was waren met van voor op onder tussen naar zonder".split()),
"ru": frozenset("и в во не что он на я с со как а то все она так его но да ты к у же вы за бы по только".split()),
"zh": frozenset("的 了 和 是 就 都 而 及 与 着 或 一个 我们 他们 它们 这个 那个 什么 怎么 为什么".split()),
"ja": frozenset("の に は を た が で て と し れ さ ある いる も する から な こと として い や れる など なっ ない この ため その あっ よう また もの という あり まで られ なる へ か だ これ によって により おり より による ず なり られる".split()),
}
_PYPHEN_DIC = None
MOS_TOTAL_TIMEOUT = 25.0
MOS_PER_SERVICE_TIMEOUT = 15.0
MOS_MIN_WORDS_ACCEPT = 30
MOS_FAST_ACCEPT_WORDS = 300
def _get_pyphen():
global _PYPHEN_DIC
if _PYPHEN_DIC is None:
try:
_PYPHEN_DIC = pyphen.Pyphen(lang="en_US")
except Exception:
_PYPHEN_DIC = False
return _PYPHEN_DIC if _PYPHEN_DIC is not False else None
_PERSONAL_NAME_FIRST = frozenset("""
james john robert michael william david richard joseph thomas charles
christopher daniel matthew anthony donald mark paul steven andrew kenneth
george joshua kevin brian edward ronald timothy jason jeffrey ryan jacob
gary nicholas eric jonathan stephen larry justin scott brandon benjamin
samuel gregory frank alexander raymond patrick jack dennis jerry tyler
aaron jose adam henry nathan douglas zachary peter kyle ethan walter
mary patricia jennifer linda elizabeth barbara susan jessica sarah karen
nancy lisa margaret betty sandra ashley dorothy kimberly emily donna
michelle carol amanda melissa deborah stephanie rebecca laura sharon
cynthia kathleen amy angela shirley anna brenda pamela emma nicole helen
samantha katherine christine debra rachel carolyn janet catherine maria
heather diane ruth julie olivia joyce virginia victoria kelly lauren
christina joan evelyn judith megan andrea cheryl hannah jacqueline martha
mohammed muhammad ahmed ali omar hassan hussein fatima aisha layla
wei li zhang wang chen liu yang zhao huang zhou wu xu sun ma zhu hu guo
he gao lin luo zheng liang xie song tang han feng deng cao peng zeng
haruto yuto sota yuki hayato haru kaito riku takumi kenta daiki
min-jun seo-jun do-yun ji-ho ye-jun ha-eun seo-yeon ji-woo soo-ah min-seo
""".split())
# ============================================================================
# UTILITIES
# ============================================================================
def _norm_ws(s):
if not s:
return ""
return _WS_RE.sub(" ", _CTRL_RE.sub(" ", s)).strip()
def _attr(node, name, default=""):
if node is None:
return default
try:
v = node.attributes.get(name, default)
return v if v is not None else default
except Exception:
return default
def _urljoin_safe(base, href):
if not href:
return ""
try:
return urljoin(base, href)
except Exception:
return href
def _sentence_split(text):
if not text:
return []
text = _WS_RE.sub(" ", text)
parts = _SENT_RE.split(text)
out = []
for p in parts:
p = p.strip()
if not p:
continue
if out and out[-1].endswith(_ABBREV_GUARD):
out[-1] = out[-1] + " " + p
else:
out.append(p)
return out
def _token_count(text):
if not text:
return 0
words = text.count(" ") + text.count("\n") + 1
cjk = len(_CJK_RE.findall(text))
return int(words * AGENT_TOKEN_COUNT_RATIO) + int(cjk / 1.5)
def _decode_body(body, headers):
ct = ""
try:
ct = (headers or {}).get("content-type", "") or ""
except Exception:
pass
m = regex.search(r"charset=([\w\-]+)", ct, regex.I)
if m:
try:
return body.decode(m.group(1), "replace")
except LookupError:
pass
return body.decode(ENCODING_FALLBACK, "replace")
def _safe_parse_xml(data):
try:
return SafeET.fromstring(data)
except Exception:
try:
return etree.fromstring(data)
except Exception:
return None
def _tld_of(url):
try:
host = urlparse(url).netloc
return _tld_mod.get_tld(host, fix_protocol=True, fail_silently=True) or ""
except Exception:
return ""
def _host_of(url):
try:
return urlparse(url).netloc
except Exception:
return ""
def _capped_findall(pattern, text, cap):
if not text:
return []
if len(text) > cap:
text = text[:cap]
try:
return pattern.findall(text)
except Exception:
return []
# ============================================================================
# HASHING
# ============================================================================
def _content_hash(text):
if not text:
return ""
return hashlib.blake2b(text.encode("utf-8", "ignore"), digest_size=16).hexdigest()
def _hash_token(tok):
return int.from_bytes(
hashlib.blake2b(tok.encode("utf-8", "ignore"), digest_size=8).digest(),
"big",
)
def _simhash64(tokens):
if not tokens:
return 0
v = [0] * 64
for tok in tokens:
h = _hash_token(tok)
for i in range(64):
v[i] += 1 if (h >> i) & 1 else -1
out = 0
for i in range(64):
if v[i] > 0:
out |= 1 << i
return out
def _simhash_from_text(text):
if not text:
return 0
toks = [t.lower() for t in _capped_findall(_WORD_RE, text, REGEX_WORD_CAP)]
return _simhash64(toks)
def _hamming(a, b):
return (a ^ b).bit_count()
def _idempotency_key(url, profile_family=""):
return hashlib.blake2b(
f"{url}|{profile_family}|{EXTRACTOR_VERSION}".encode("utf-8", "ignore"),
digest_size=16,
).hexdigest()
@lru_cache(maxsize=1)
def _config_hash():
try:
import config as c
h = hashlib.blake2b(digest_size=16)
for k in sorted(dir(c)):
if k.isupper() and not k.startswith("_"):
try:
h.update(f"{k}={getattr(c, k)!r}".encode("utf-8", "ignore"))
except Exception:
pass
return h.hexdigest()
except Exception:
return ""
# ============================================================================
# QUALITY METRICS
# ============================================================================
_ZERO_QUALITY = {
"word_count": 0, "sentence_count": 0, "syllable_count": 0,
"char_count": 0, "reading_time_seconds": 0,
"flesch_reading_ease": -1.0, "flesch_kincaid_grade": -1.0,
"gunning_fog": -1.0, "smog_index": -1.0,
"automated_readability_index": -1.0, "coleman_liau_index": -1.0,
"dale_chall_score": -1.0, "text_standard": "",
"difficulty": 0,
}
def _quality_metrics(text):
zero = dict(_ZERO_QUALITY)
if not text or len(text) < 80:
return zero
try:
words = textstat.lexicon_count(text)
except Exception:
words = len(text.split())
if words < QUALITY_MIN_WORDS:
zero["word_count"] = words
return zero
def _safe(fn):
try:
return fn(text)
except Exception:
return -1.0
try:
sentences = textstat.sentence_count(text)
except Exception:
sentences = max(1, text.count("."))
if sentences < QUALITY_MIN_SENTENCES:
zero["word_count"] = words
zero["sentence_count"] = sentences
return zero
try:
syllables = textstat.syllable_count(text)
except Exception:
syllables = 0
try:
standard = textstat.text_standard(text, float_output=False)
except Exception:
standard = ""
return {
"word_count": words,
"sentence_count": sentences,
"syllable_count": syllables,
"char_count": len(text),
"reading_time_seconds": round(words / 200 * 60, 1),
"flesch_reading_ease": _safe(textstat.flesch_reading_ease),
"flesch_kincaid_grade": _safe(textstat.flesch_kincaid_grade),
"gunning_fog": _safe(textstat.gunning_fog),
"smog_index": _safe(textstat.smog_index),
"automated_readability_index": _safe(textstat.automated_readability_index),
"coleman_liau_index": _safe(textstat.coleman_liau_index),
"dale_chall_score": _safe(textstat.dale_chall_readability_score),
"text_standard": standard,
"difficulty": _safe(textstat.difficult_words),
}
def _should_run_nlp(text, quality):
if not NLP_COMPLEXITY_GATE_ENABLED:
return bool(text)
if not text:
return False
if quality.get("word_count", 0) < NLP_MIN_WORDS:
return False
if quality.get("sentence_count", 0) < NLP_MIN_SENTENCES:
return False
return True
def _extraction_score(text, title, sections, boiler_ratio):
if not EXTRACTION_SCORING_ENABLED or not text:
return -1.0
words = len(text.split())
if words < 30:
return -1.0
score = 0.0
score += min(words / EXTRACTION_SCORE_LENGTH_CAP, 1.0) * EXTRACTION_SCORE_LENGTH_WEIGHT
score += (1.0 - min(boiler_ratio, 1.0)) * EXTRACTION_SCORE_BOILER_WEIGHT
try:
flesch = textstat.flesch_reading_ease(text)
lo, hi = EXTRACTION_SCORE_FLESCH_BEST
lo2, hi2 = EXTRACTION_SCORE_FLESCH_OK
if lo <= flesch <= hi:
score += EXTRACTION_SCORE_FLESCH_WEIGHT
elif lo2 <= flesch <= hi2:
score += EXTRACTION_SCORE_FLESCH_WEIGHT * 0.5
except Exception:
pass
if title and title.lower() in text.lower():
score += EXTRACTION_SCORE_TITLE_WEIGHT
if sections:
score += (min(len(sections) / EXTRACTION_SCORE_SECTIONS_CAP, 1.0)
* EXTRACTION_SCORE_SECTIONS_WEIGHT)
if text.count(".") > 5:
score += EXTRACTION_SCORE_PUNCT_WEIGHT
return score
# ============================================================================
# CHUNKING
# ============================================================================
def chunk_text(text, size=None, overlap=None, min_size=None):
if not AGENT_CHUNK_ENABLED or not text:
return []
size = size or AGENT_CHUNK_SIZE_TOKENS
overlap = overlap if overlap is not None else AGENT_CHUNK_OVERLAP_TOKENS
min_size = min_size or AGENT_CHUNK_MIN_TOKENS
sentences = _sentence_split(text)
if not sentences:
return []
chunks = []
cur, cur_len = [], 0
for s in sentences:
tok = _token_count(s)
if cur_len + tok > size and cur:
chunks.append(" ".join(cur))
keep, kept = [], 0
for s2 in reversed(cur):
kept += _token_count(s2)
if kept > overlap:
break
keep.insert(0, s2)
cur, cur_len = keep, kept
cur.append(s)
cur_len += tok
if len(chunks) >= AGENT_CHUNK_MAX_CHUNKS_PER_DOC:
break
if cur and cur_len >= min_size:
chunks.append(" ".join(cur))
return chunks
def _dedup_chunks(chunks):
if not CHUNK_DEDUP_ENABLED or len(chunks) < 3:
return chunks
sigs = [_simhash64(c.lower().split()) for c in chunks]
keep = [True] * len(chunks)
for i in range(len(chunks)):
if not keep[i]:
continue
for j in range(i + 1, len(chunks)):
if not keep[j]:
continue
if _hamming(sigs[i], sigs[j]) <= CHUNK_DEDUP_HAMMING:
if CHUNK_DEDUP_PREFER_LONGER:
if len(chunks[i]) < len(chunks[j]):
keep[i] = False
break
else:
keep[j] = False
else:
keep[j] = False
return [c for c, k in zip(chunks, keep) if k]
def _attach_context(chunks, parent_url, parent_title, sections=None):
if not chunks:
return []
if AGENT_CHUNK_OFFSET_AWARE and sections:
chunks = _dedup_chunks(chunks)
heading_map = []
if sections:
for sec in sections:
heading_map.append(sec.get("heading", ""))
for sub in sec.get("subsections", []) or []:
heading_map.append(sub.get("heading", ""))
total = len(chunks)
out = []
for i, c in enumerate(chunks):
ctx = ""
if AGENT_CHUNK_INCLUDE_HEADING_CONTEXT and heading_map:
idx = min(int(i * len(heading_map) / max(total, 1)), len(heading_map) - 1)
ctx = heading_map[idx]
out.append({
"index": i,
"total": total,
"text": c,
"token_count": _token_count(c),
"heading_context": ctx if ctx else None,
"parent_url": parent_url if AGENT_CHUNK_INCLUDE_URL_CONTEXT else None,
"parent_title": parent_title,
"offset": None,
})
return out
# ============================================================================
# NLP-LITE
# ============================================================================
def extract_keywords(text, max_k=None, language="en"):
if not AGENT_KEYWORD_EXTRACT_ENABLED or not text:
return []
max_k = max_k or AGENT_KEYWORD_MAX_PER_DOC
words = [w.lower() for w in _capped_findall(_WORD_RE, text, REGEX_WORD_CAP)]
if not words:
return []
stop = _STOPWORDS_BY_LANG.get(language, _STOPWORDS_EN)
words = [w for w in words if w not in stop and len(w) >= AGENT_KEYWORD_MIN_LENGTH]
if not words:
return []
total = len(words)
unigrams = Counter(words)
scores = {w: c / total for w, c in unigrams.items()}
for n in range(2, AGENT_TOPIC_NGRAM_MAX + 1):
gram_counter = Counter(tuple(words[i:i + n]) for i in range(len(words) - n + 1))
for gram, c in gram_counter.items():
if c < 2:
continue
key = " ".join(gram)
scores[key] = (c / total) * math.log(1 + c)
ranked = sorted(scores.items(), key=lambda x: -x[1])[:max_k]
return [{"term": k, "score": round(v, 6)} for k, v in ranked]
def extract_topics(text, max_topics=None, language="en"):
if not AGENT_TOPIC_EXTRACT_ENABLED or not text:
return []
max_topics = max_topics or AGENT_TOPIC_MAX_PER_DOC
kw = extract_keywords(text, max_k=max_topics * 3, language=language)
out = []
for item in kw:
if " " in item["term"] and item["score"] >= AGENT_TOPIC_MIN_SCORE:
out.append(item)
if len(out) >= max_topics:
break
return out
def _entity_frequency(body, value):
if not ENTITY_FREQUENCY_FILTER_ENABLED:
return 1
try:
return body.count(value)
except Exception:
return 0
def _entity_near_reporting_verb(body, value):
if not ENTITY_REPORTING_VERBS:
return False
lo = body.lower()
vlo = value.lower()
idx = 0
while True:
idx = lo.find(vlo, idx)
if idx < 0:
return False
window = lo[max(0, idx - ENTITY_REPORTING_WINDOW):
idx + len(vlo) + ENTITY_REPORTING_WINDOW]
for verb in ENTITY_REPORTING_VERBS:
if verb in window:
return True
idx += len(vlo)
def extract_entities(text, max_n=None, body_for_freq=None):
if not AGENT_ENTITY_EXTRACT_ENABLED or not text:
return []
max_n = max_n or AGENT_ENTITY_MAX_PER_DOC
body = body_for_freq if body_for_freq is not None else text
seen = set()
out = []
def _add(kind, value, weight=1.0):
if len(value) < AGENT_ENTITY_MIN_LENGTH:
return
key = value.lower() if AGENT_ENTITY_CASE_INSENSITIVE_DEDUP else value
if AGENT_ENTITY_DEDUP and key in seen:
return
seen.add(key)
out.append({"type": kind, "value": value, "weight": round(weight, 3)})
for kind, pat in _ENTITY_PATTERNS.items():
for m in pat.finditer(text):
val = m.group(0).strip()
if kind == "PERSON":
tokens = val.split()
if not tokens:
continue
first = tokens[0].lower()
weight = (ENTITY_FIRSTNAME_WEIGHT if first in _PERSONAL_NAME_FIRST
else ENTITY_NON_FIRSTNAME_WEIGHT)
if ENTITY_FREQUENCY_FILTER_ENABLED:
freq = _entity_frequency(body, val)
near = _entity_near_reporting_verb(body, val)
if not (freq >= ENTITY_MIN_OCCURRENCES or near):
continue
if ENTITY_BOUNDARY_ENABLED:
start = max(0, m.start() - 1)
end = min(len(text), m.end() + 1)
if start > 0 and text[start].isalpha():
continue
if end < len(text) and text[end].isalpha():
continue
_add(kind, val, weight)
elif kind == "ORG":
if not any(suffix in val for suffix in ENTITY_ORG_SUFFIXES):
continue
_add(kind, val, 1.0)
else:
_add(kind, val, 1.0)
if len(out) >= max_n:
return out
return out
def summarize(text, max_sentences=None):
if not AGENT_SUMMARY_ENABLED or not text:
return ""
max_sentences = max_sentences or AGENT_SUMMARY_TOP_SENTENCES
sents = _sentence_split(text)
if len(sents) <= max_sentences:
return " ".join(sents)
freq = Counter(w.lower() for w in _capped_findall(_WORD_RE, text, REGEX_WORD_CAP))
for w in list(freq):
if w in _STOPWORDS_EN:
del freq[w]
if not freq:
return " ".join(sents[:max_sentences])
top = max(freq.values())
scores = []
for i, s in enumerate(sents):
ws = _WORD_RE.findall(s.lower())
if not ws:
continue
score = sum(freq.get(w, 0) for w in ws) / (top * len(ws) + 1)
if i < 3:
score *= 1.3
if i == len(sents) - 1:
score *= 0.85
scores.append((score, i, s))
if not scores:
return " ".join(sents[:max_sentences])
scores.sort(reverse=True)
picked = sorted(scores[:max_sentences], key=lambda x: x[1])
return " ".join(s for _, _, s in picked)
def redact_pii(text):
if not AGENT_PII_REDACT_ENABLED or not text: