-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
3300 lines (2904 loc) · 100 KB
/
utils.py
File metadata and controls
3300 lines (2904 loc) · 100 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
"""Shared utility helpers for digest routing, token budgeting, logging, and query search."""
from __future__ import annotations
import asyncio
from collections import Counter, deque
import contextlib
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone, tzinfo
from email.utils import parsedate_to_datetime
from html import escape as _escape_html, unescape as _unescape_html
import hashlib
import json
import logging
import math
from pathlib import Path
import re
import threading
import time
from typing import Any, Awaitable, Callable, Iterable, List, Sequence, Tuple
from urllib.parse import quote_plus, urlparse
import xml.etree.ElementTree as ET
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
import config
from db import (
load_recent_breaking,
load_recent_media_signatures,
purge_recent_breaking,
purge_recent_media_signatures,
save_recent_breaking,
save_recent_media_signature,
)
from news_taxonomy import match_news_category, record_ontology_label_resolution
from news_signals import looks_like_live_event_update, should_downgrade_explainer_urgency
from shared_http import get_web_http_client
_QUERY_MAX_HOURS_BACK = 24 * 30
class _NamedFixedOffsetZone(tzinfo):
def __init__(self, *, key: str, offset: timedelta, name: str) -> None:
self.key = key
self._offset = offset
self._name = name
def utcoffset(self, dt: datetime | None) -> timedelta:
return self._offset
def dst(self, dt: datetime | None) -> timedelta:
return timedelta(0)
def tzname(self, dt: datetime | None) -> str:
return self._name
_RUNTIME_TZ_ALIASES = {
"IST": "Asia/Kolkata",
}
_RUNTIME_TZ_FIXED_FALLBACKS = {
"Asia/Kolkata": _NamedFixedOffsetZone(
key="Asia/Kolkata",
offset=timedelta(hours=5, minutes=30),
name="IST",
),
}
def runtime_timezone():
raw = str(getattr(config, "TIMEZONE", "UTC") or "").strip()
if not raw:
raw = "UTC"
zone_name = _RUNTIME_TZ_ALIASES.get(raw.upper(), raw)
try:
return ZoneInfo(zone_name)
except ZoneInfoNotFoundError:
return _RUNTIME_TZ_FIXED_FALLBACKS.get(zone_name, timezone.utc)
def runtime_now() -> datetime:
return datetime.now(runtime_timezone())
def estimate_tokens_rough(text: str) -> int:
"""Fast rough token estimate (works well enough for budgeting)."""
if not text:
return 0
# Roughly ~4 chars/token average for mixed English + symbols.
return max(1, len(text) // 4)
def normalize_space(text: str) -> str:
return re.sub(r"\s+", " ", text or "").strip()
def media_duplicate_match_score(left: str, right: str) -> float:
left_norm, _ = build_dupe_fingerprint(left)
right_norm, _ = build_dupe_fingerprint(right)
if not left_norm or not right_norm:
return 1.0 if left_norm == right_norm else 0.0
left_tokens = tuple(_tokenize_for_dupe(left_norm))
right_tokens = tuple(_tokenize_for_dupe(right_norm))
tfidf = _tfidf_cosine(left_tokens, right_tokens)
fuzzy = 0.0
try:
from difflib import SequenceMatcher
fuzzy = SequenceMatcher(None, left_norm, right_norm).ratio()
except Exception:
fuzzy = 0.0
overlap = _set_jaccard(left_tokens, right_tokens)
left_anchors = _anchor_tokens(left_tokens)
right_anchors = _anchor_tokens(right_tokens)
anchor_overlap = _set_dice(left_anchors, right_anchors)
shared_tokens = set(left_tokens) & set(right_tokens)
strong_shared = {
token for token in shared_tokens if token.isdigit() or len(token) >= 5 or token in _BREAKING_HINTS
}
score = (0.35 * tfidf) + (0.20 * fuzzy) + (0.20 * overlap) + (0.25 * anchor_overlap)
if len(strong_shared) >= 3:
score = max(score, 0.34)
if anchor_overlap >= 0.5 and overlap >= 0.18:
score = max(score, 0.36)
return max(0.0, min(1.0, score))
_ALERT_LABEL_RULES: tuple[tuple[str, tuple[str, ...]], ...] = (
(
"🕯️ Casualty Alert",
(
"killed",
"dead",
"deaths",
"casualties",
"casualty",
"injured",
"wounded",
"fatalities",
"fatality",
"massacre",
"body count",
),
),
(
"🛡️ Interception Alert",
(
"intercepted",
"interception",
"interceptions",
"shot down",
"air defense",
"air-defence",
"air defence",
"iron dome",
"defenses activated",
"defence activated",
),
),
(
"⚠️ Civil Warning",
(
"evacuate",
"evacuation",
"warning",
"warnings",
"shelter",
"shelters",
"airspace closed",
"closure",
"curfew",
"stay indoors",
"sirens",
),
),
(
"🚨 Strike Alert",
(
"airstrike",
"air strike",
"strike",
"strikes",
"missile",
"missiles",
"rocket",
"rockets",
"drone strike",
"bombing",
"blast",
"blasts",
"explosion",
"explosions",
"shelling",
"raid",
"raids",
),
),
(
"📣 Major Statement",
(
"said",
"says",
"announced",
"declared",
"statement",
"spokesperson",
"spokesman",
"spokeswoman",
"official says",
"minister says",
"president says",
"trump says",
),
),
(
"🚢 Maritime Watch",
(
"vessel",
"ship",
"shipping",
"cargo ship",
"tanker",
"strait of hormuz",
"naval",
"port",
"crew rescued",
),
),
(
"🏛️ Leadership Alert",
(
"leader",
"supreme leader",
"president",
"prime minister",
"commander",
"succession",
"cabinet",
"government reshuffle",
"assassinated",
"resigned",
),
),
(
"⚡ Disruption Alert",
(
"outage",
"blackout",
"cyber",
"internet down",
"power cut",
"power outage",
"communications down",
"disruption",
),
),
)
_GENERIC_BREAKING = "Breaking"
_GENERIC_NEWS_UPDATE = "News Update"
_ENHANCED_CATEGORY_EMOJI_PREFIXES = {
"air_defense": "🛡️",
"missile_strike": "🎯",
"rocket_fire": "🚀",
"drone_attack": "🛸",
"artillery_shelling": "💥",
"border_clash": "⚔️",
"maritime_security": "⚓",
"piracy_hijacking": "🏴☠️",
"sanctions_export_control": "⛓️",
"covert_intelligence": "🕵️",
"leadership_change": "🏛️",
"treaty_agreement": "✍️",
"corruption_probe": "🧾",
"policing_public_safety": "🚔",
"commodity_energy": "🛢️",
"labor_strike": "🪧",
"telecom_internet": "📡",
"aviation_incident": "🛬",
"shipping_port": "⚓",
"rail_transit": "🚆",
"industrial_fire_explosion": "🏭💥",
"water_sanitation": "🚰",
"earthquake": "🌍",
"storm_typhoon": "🌪️",
"heat_cold": "🌡️",
"hospital_health_emergency": "🚑",
"space_launch_incident": "🛰️",
}
def _generic_alert_label(severity: str) -> str:
normalized_severity = normalize_space(severity).lower()
if normalized_severity == "high":
return _GENERIC_BREAKING
return _GENERIC_NEWS_UPDATE
def _strip_label_prefix_icon(label: str) -> str:
cleaned = normalize_space(label)
if not cleaned:
return ""
parts = cleaned.split()
while parts and not re.search(r"[A-Za-z]", parts[0]):
parts.pop(0)
return normalize_space(" ".join(parts)) or cleaned
def _enhance_taxonomy_label(category_key: str, label: str) -> str:
plain_label = _strip_label_prefix_icon(label)
if not plain_label:
return label
prefix = _ENHANCED_CATEGORY_EMOJI_PREFIXES.get(normalize_space(category_key).lower(), "")
if not prefix:
return label
return f"{prefix} {plain_label}"
def _choose_alert_label_legacy(text: str, *, severity: str = "high") -> str:
"""
Pick a more specific, human-readable alert label than generic "BREAKING".
"""
lowered = normalize_space(text).lower()
if lowered:
for label, markers in _ALERT_LABEL_RULES:
if any(marker in lowered for marker in markers):
return label
normalized_severity = normalize_space(severity).lower()
if normalized_severity == "high":
return "🔥 Flash Update"
if normalized_severity == "medium":
return "⚠️ Live Update"
return "ℹ️ Situation Update"
def choose_alert_label(text: str, *, severity: str = "high") -> str:
"""
Use taxonomy-backed themed labels when a concrete category is present.
Explainer material falls back to a calm generic label.
"""
normalized = normalize_space(text)
if normalized and not should_downgrade_explainer_urgency(normalized):
match = match_news_category(normalized)
if match is not None:
record_ontology_label_resolution(matched=True)
return _enhance_taxonomy_label(match.category_key, match.label)
record_ontology_label_resolution(matched=False)
return _generic_alert_label(severity)
def build_alert_header(
text: str,
*,
severity: str,
source_title: str,
include_source: bool,
) -> str:
label = choose_alert_label(text, severity=severity)
if include_source:
safe_source = sanitize_telegram_html(source_title)
return f"<b>{label} \u2022 {safe_source}</b>"
return f"<b>{label}</b>"
@dataclass(frozen=True)
class QueryPlan:
original_query: str
cleaned_query: str
hours_back: int
start_ts: int | None
end_ts: int | None
explicit_time_filter: bool
broad_query: bool
keywords: tuple[str, ...]
expanded_terms: tuple[str, ...]
numbers: tuple[str, ...]
search_variants: tuple[str | None, ...]
def build_query_plan(query: str, *, default_hours: int = 24) -> QueryPlan:
original = normalize_space(query)
hours_back, cleaned, start_ts, end_ts = parse_time_filter_from_query(original, default_hours)
effective = cleaned or original
explicit_time_filter = (
hours_back != max(1, int(default_hours))
or effective != original
or start_ts is not None
or end_ts is not None
)
broad = is_broad_news_query(original)
keywords = tuple(extract_query_keywords(effective))
expanded_terms = tuple(expand_query_terms(effective))
numbers = tuple(extract_query_numbers(effective))
variants = tuple(build_query_search_variants(effective, broad_query=broad))
return QueryPlan(
original_query=original,
cleaned_query=effective,
hours_back=hours_back,
start_ts=start_ts,
end_ts=end_ts,
explicit_time_filter=explicit_time_filter,
broad_query=broad,
keywords=keywords,
expanded_terms=expanded_terms,
numbers=numbers,
search_variants=variants,
)
_QUERY_GENERIC_TERMS = {
"about",
"after",
"all",
"also",
"and",
"any",
"are",
"as",
"brief",
"briefing",
"can",
"could",
"current",
"day",
"days",
"detail",
"details",
"did",
"do",
"does",
"development",
"developments",
"digest",
"explain",
"find",
"for",
"from",
"give",
"has",
"have",
"happened",
"happening",
"headline",
"headlines",
"how",
"hour",
"hours",
"into",
"is",
"its",
"last",
"latest",
"lookup",
"look",
"me",
"my",
"news",
"now",
"of",
"on",
"or",
"past",
"please",
"present",
"query",
"recent",
"recently",
"recap",
"regarding",
"report",
"reports",
"reply",
"replying",
"roundup",
"search",
"searching",
"show",
"situation",
"status",
"subject",
"summary",
"than",
"that",
"the",
"tell",
"there",
"this",
"today",
"up",
"update",
"updates",
"want",
"was",
"were",
"what",
"which",
"when",
"where",
"who",
"would",
"with",
"why",
"you",
"yesterday",
}
_QUERY_ALIAS_MAP: dict[str, tuple[str, ...]] = {
"tehran": ("tehran", "teheran", "تهران"),
"iran": ("iran", "iranian", "ایران"),
"israel": ("israel", "israeli", "اسرائیل", "اسراییل"),
"gaza": ("gaza", "غزه"),
"beirut": ("beirut", "بيروت", "بیروت"),
"lebanon": ("lebanon", "لبنان"),
"damascus": ("damascus", "دمشق"),
"syria": ("syria", "syrian", "سوريا", "سوریه"),
"baghdad": ("baghdad", "بغداد"),
"iraq": ("iraq", "iraqi", "العراق", "عراق"),
"erbil": ("erbil", "اربيل", "اربیل"),
"basra": ("basra", "البصرة", "بصره", "بصرہ"),
"hormuz": ("hormuz", "هرمز", "hormoz"),
"dubai": ("dubai", "دبي", "دبی"),
"bahrain": ("bahrain", "بحرين", "بحرین"),
"telaviv": ("tel aviv", "تل أبيب", "تلآویو", "تل ابیب"),
"tel": ("tel aviv", "تل أبيب", "تلآویو", "تل ابیب"),
"haifa": ("haifa", "حيفا", "حیفا"),
"yemen": ("yemen", "اليمن", "یمن"),
"sanaa": ("sanaa", "صنعاء", "صنعا"),
"aden": ("aden", "عدن"),
"saada": ("saada", "صعدة", "صعده"),
"saudi": ("saudi", "saudi arabia", "السعودية", "سعودی"),
"riyadh": ("riyadh", "الرياض", "ریاض"),
"uae": ("uae", "united arab emirates", "الإمارات", "امارات"),
"emirates": ("uae", "united arab emirates", "الإمارات", "امارات"),
"qatar": ("qatar", "قطر"),
"jordan": ("jordan", "الأردن", "اردن"),
"egypt": ("egypt", "مصر"),
}
_QUERY_FOCUS_LEAD_IN_RE = re.compile(
r"^(?:"
r"what(?:'s| is)?|which|who|where|when|why|"
r"how(?: many| much)?|"
r"tell me|show me|give me|find|search(?: for)?|look(?: up)?|"
r"can you|could you|would you|do you know"
r")\b",
re.IGNORECASE,
)
_QUERY_FOCUS_TOPIC_RE = re.compile(
r"^(?:"
r"the\s+|"
r"latest|recent|current|new|news|updates?|status|situation|coverage|"
r"report(?:ing)?|brief(?:ing)?|summary|recap|about|on|for|regarding|re|around"
r")+\b",
re.IGNORECASE,
)
_QUERY_TREND_MARKERS = (
"escalating",
"escalation",
"de-escalating",
"deescalating",
"de-escalation",
"deescalation",
"worsening",
"worsen",
"intensifying",
"intensify",
"easing",
"ease",
"cooling",
"cool off",
"calming",
"stabilizing",
"trajectory",
"trend",
"direction",
"momentum",
)
_QUERY_ASSESSMENT_MARKERS = (
"what is the situation",
"what's the situation",
"current situation",
"where things stand",
"to what extent",
"how serious",
"how intense",
"how bad",
"how severe",
"is it escalating",
"is this escalating",
"is it de-escalating",
"is this de-escalating",
)
def extract_query_keywords(query: str) -> list[str]:
"""
Extract meaningful subject terms from a natural-language query.
Generic request words like "digest", "latest", "summary", "today" are
intentionally removed so broad recap queries do not collapse into useless
literal searches.
"""
lowered = normalize_space(query).lower()
if not lowered:
return []
tokens = re.findall(r"[a-z0-9]{3,}", lowered)
out: list[str] = []
seen: set[str] = set()
for token in tokens:
if token.isdigit():
continue
if token in _QUERY_GENERIC_TERMS:
continue
if token in seen:
continue
seen.add(token)
out.append(token)
return out
def expand_query_terms(query: str) -> list[str]:
"""
Expand keywords with lightweight multilingual aliases and transliterations.
"""
base_keywords = extract_query_keywords(query)
out: list[str] = []
seen: set[str] = set()
def _push(value: str) -> None:
cleaned = normalize_space(value)
if not cleaned:
return
key = cleaned.lower()
if key in seen:
return
seen.add(key)
out.append(cleaned)
for keyword in base_keywords:
_push(keyword)
alias_values = _QUERY_ALIAS_MAP.get(keyword.lower())
if alias_values:
for alias in alias_values:
_push(alias)
return out
def extract_query_focus_phrases(query: str) -> list[str]:
"""
Pull shorter focus phrases from natural-language questions so search
variants emphasize the subject, not the question framing.
"""
normalized = normalize_space(query)
if not normalized:
return []
phrases: list[str] = []
seen: set[str] = set()
def _push(value: str) -> None:
cleaned = normalize_space(value)
if not cleaned:
return
key = cleaned.lower()
if key in seen:
return
seen.add(key)
phrases.append(cleaned)
for segment in re.split(r"[,:;|]+", normalized):
working = normalize_space(re.sub(r"[?!]+", " ", segment))
if not working:
continue
previous = ""
while working and working != previous:
previous = working
working = normalize_space(_QUERY_FOCUS_LEAD_IN_RE.sub("", working))
working = normalize_space(_QUERY_FOCUS_TOPIC_RE.sub("", working))
keywords = extract_query_keywords(working)
if keywords:
_push(" ".join(keywords[:5]))
parts = re.split(r"\b(?:or|vs\.?|versus|and/or)\b", working, flags=re.IGNORECASE)
if len(parts) <= 1:
continue
comparison_terms: list[str] = []
for part in parts:
part_keywords = extract_query_keywords(part)
if not part_keywords:
continue
_push(" ".join(part_keywords[:3]))
comparison_terms.extend(part_keywords[:2])
comparison_terms = dedupe_preserve_order(comparison_terms)
if len(comparison_terms) >= 2:
_push(" ".join(comparison_terms[:4]))
return phrases
def build_query_search_variants(query: str, *, broad_query: bool = False) -> list[str | None]:
"""
Build multiple retrieval-friendly search variants from one user query.
"""
normalized = normalize_space(query)
base_keywords = extract_query_keywords(query)
focus_phrases = extract_query_focus_phrases(query)
expanded_terms = expand_query_terms(query)
numbers = extract_query_numbers(query)
variants: list[str | None] = []
seen: set[str] = set()
def _push(value: str | None) -> None:
if value is None:
key = "__none__"
if key in seen:
return
seen.add(key)
variants.append(None)
return
cleaned = normalize_space(value)
if not cleaned:
return
key = cleaned.lower()
if key in seen:
return
seen.add(key)
variants.append(cleaned)
if normalized:
_push(normalized)
for phrase in focus_phrases[:6]:
_push(phrase)
if base_keywords:
_push(" ".join(base_keywords[:5]))
if len(base_keywords) >= 2:
_push(" ".join(base_keywords[:2]))
_push(" ".join(base_keywords[-2:]))
if len(base_keywords) >= 3:
_push(" ".join(base_keywords[:3]))
_push(" ".join(base_keywords[-3:]))
for term in base_keywords[:10]:
_push(term)
pairwise_terms = base_keywords[:6]
for idx in range(len(pairwise_terms)):
for jdx in range(idx + 1, len(pairwise_terms)):
_push(f"{pairwise_terms[idx]} {pairwise_terms[jdx]}")
if expanded_terms:
base_keyword_keys = {item.lower() for item in base_keywords}
alias_terms = [
term for term in expanded_terms
if term.lower() not in base_keyword_keys
]
for term in alias_terms[:10]:
_push(term)
if alias_terms and base_keywords:
_push(" ".join([base_keywords[0], alias_terms[0]]))
if numbers:
for number in numbers[:4]:
_push(number)
if base_keywords:
_push(" ".join([*numbers[:2], *base_keywords[:2]]))
_push(" ".join([*base_keywords[:2], *numbers[:2]]))
if broad_query and not base_keywords and not focus_phrases and not numbers:
_push(None)
return variants or [None]
def extract_query_numbers(query: str) -> list[str]:
"""
Extract meaningful numeric claims from a query.
Examples:
- "217 killed and 798 injured" -> ["217", "798"]
- "last 24 hours" -> []
"""
lowered = normalize_space(query).lower()
if not lowered:
return []
values: list[str] = []
seen: set[str] = set()
for token in re.findall(r"\b\d{2,6}\b", lowered):
if token in seen:
continue
if token in {"24", "48", "72"} and re.search(rf"\b{re.escape(token)}\s*(?:hours?|hrs?|h)\b", lowered):
continue
seen.add(token)
values.append(token)
return values
def is_broad_news_query(query: str) -> bool:
"""
Detect recap-style prompts that should use broad time-window evidence rather
than literal keyword matching.
"""
lowered = normalize_space(query).lower()
if not lowered:
return False
recap_markers = (
"digest",
"summary",
"recap",
"roundup",
"briefing",
"what happened",
"latest updates",
"latest developments",
"top updates",
"news update",
)
if any(marker in lowered for marker in recap_markers):
return True
if re.search(r"\b(?:today|yesterday)\b", lowered):
return True
if re.search(r"\b(?:last|past)\s+\d{1,3}\s*(?:hours?|hrs?|h|days?|d)\b", lowered):
return not extract_query_keywords(lowered)
topical_markers = (
"latest",
"recent",
"news",
"updates",
"status",
"situation",
"overview",
"brief",
"briefing",
)
direct_question_markers = (
"who",
"why",
"when",
"where",
"how many",
"how much",
"did",
"does",
"is there",
"are there",
)
hard_fact_markers = (
"leader",
"successor",
"succession",
"president",
"prime minister",
"assassinated",
"nuclear",
"reactor",
)
keywords = extract_query_keywords(lowered)
if (
keywords
and any(marker in lowered for marker in topical_markers)
and not any(marker in lowered for marker in direct_question_markers)
and not any(marker in lowered for marker in hard_fact_markers)
):
return True
return not extract_query_keywords(lowered)
def query_prefers_direct_answer(query: str) -> bool:
"""
Some broad strategic questions still need a direct analytical answer instead
of a digest-style recap.
"""
lowered = normalize_space(query).lower()
if not lowered:
return False
has_assessment_marker = any(marker in lowered for marker in _QUERY_ASSESSMENT_MARKERS)
has_trend_marker = any(marker in lowered for marker in _QUERY_TREND_MARKERS)
has_question_shape = (
"?" in lowered
or lowered.startswith(("what ", "what's ", "how ", "is ", "are ", "where "))
)
has_comparison = bool(
re.search(
r"\b(?:escalat(?:ing|ion)|worsen(?:ing)?|intensif(?:ying|ication))\b.+\b(?:or|vs\.?|versus)\b.+\b(?:de-?escalat(?:ing|ion)|eas(?:ing|e)|calm(?:ing)?)\b",
lowered,
)
)
return bool(
has_question_shape
and (
has_assessment_marker
or has_comparison
or (
has_trend_marker
and any(marker in lowered for marker in ("situation", "conflict", "war", "front", "exchange"))
)
)
)
def dedupe_preserve_order(items: Sequence[str]) -> List[str]:
seen = set()
out: List[str] = []
for item in items:
if item in seen:
continue
seen.add(item)
out.append(item)
return out
def split_markdown_chunks(text: str, max_chars: int = 3600) -> List[str]:
"""Split long markdown text into Telegram-safe chunks without breaking too hard."""
if len(text) <= max_chars:
return [text]
chunks: List[str] = []
remaining = text
while len(remaining) > max_chars:
cut = remaining.rfind("\n", 0, max_chars)
if cut < int(max_chars * 0.5):
cut = remaining.rfind(" ", 0, max_chars)
if cut < int(max_chars * 0.5):
cut = max_chars
part = remaining[:cut].rstrip()
if part:
chunks.append(part)
remaining = remaining[cut:].lstrip()
if remaining:
chunks.append(remaining)
return chunks
def split_html_chunks(text: str, max_chars: int = 3600) -> List[str]:
"""Split long HTML text into Telegram-safe chunks."""
if len(text) <= max_chars:
return [text]
chunks: List[str] = []
remaining = text
while len(remaining) > max_chars:
cut = remaining.rfind("\n", 0, max_chars)
if cut < int(max_chars * 0.5):
cut = remaining.rfind("<br>", 0, max_chars)
if cut < int(max_chars * 0.5):
cut = remaining.rfind(" ", 0, max_chars)
if cut < int(max_chars * 0.5):
cut = max_chars
if cut <= 0:
cut = max_chars
part = remaining[:cut].rstrip()
if part:
chunks.append(part)
remaining = remaining[cut:].lstrip()
if remaining:
chunks.append(remaining)
return chunks
_ALLOWED_HTML_TAGS = {
"b",
"i",
"u",
"s",
"tg-spoiler",
"tg-emoji",
"code",
"pre",
"blockquote",
"a",
}
_HTML_TAG_RE = re.compile(r"</?([a-zA-Z0-9-]+)([^>]*)>")
_HTML_BR_RE = re.compile(r"<br\s*/?>", re.IGNORECASE)
_HTML_EMOJI_ID_RE = re.compile(
r"""emoji-id\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))""",
re.IGNORECASE,