返回 last30days-skill
x_judge.py
根目录 / skills / last30days / scripts / lib / x_judge.py
1 """X corpus judging for retrieve-judge-retry.
2
3 No I/O: judges items already retrieved. Reuses relevance.token_overlap_relevance.
4
5 The judge detects off-topic floods and determines which extracted handles should
6 be promoted to the FROM lane based on on-topic post ratio, not frequency.
7 """
8
9 import re
10 from collections import Counter
11 from typing import Any, Dict, List, Optional, Set, Tuple
12
13 from . import relevance
14
15 # Minimum on-topic ratio for the overall corpus. Below this, the engine should
16 # retry with a wider keyword query. Rome measured ~0.2 (8/40 on-topic).
17 CORPUS_ON_TOPIC_FLOOR = 0.4
18
19 # Minimum on-topic ratio for a handle's posts to qualify for FROM promotion.
20 HANDLE_ON_TOPIC_FLOOR = 0.5
21
22 # Minimum on-topic keyword hits before a handle can be promoted to FROM lane.
23 # Prevents promoting handles that appeared in thin phrase hits with only 1 match.
24 MIN_ON_TOPIC_HITS = 2
25
26
27 # Ambiguous short tokens that require case-sensitive matching to avoid
28 # pronoun/acronym collisions. E.g., "US" (country) vs "us" (pronoun).
29 # For these tokens, require the text to contain the uppercase form (acronym)
30 # rather than just the lowercase form (common word).
31 _CASE_SENSITIVE_ACRONYMS = frozenset({'us'})
32
33
34 def _compute_relevance(query: str, text: str) -> float:
35 """Compute relevance score for a post against the topic query.
36
37 Returns 0.0 for empty/stopword-only queries to avoid treating all items
38 as equally relevant (the shared relevance module returns 0.5 for empty
39 queries as a neutral fallback, but x_judge needs strict filtering).
40
41 Excludes ``relevance.LOW_SIGNAL_QUERY_TOKENS`` when informative tokens
42 exist (matching ``relevance.PreparedQuery``) so planner ranking-query
43 scaffolding words never promote off-topic posts above ``RELEVANCE_FLOOR``.
44
45 Uses case-sensitive matching for ambiguous short tokens like 'us' to
46 distinguish country acronym 'US' from pronoun 'us'.
47 """
48 if not query or not text:
49 return 0.0
50
51 q_tokens = relevance.tokenize(query)
52 if not q_tokens:
53 return 0.0 # All query tokens were stopwords
54
55 informative = {t for t in q_tokens if t not in relevance.LOW_SIGNAL_QUERY_TOKENS}
56 effective_q_tokens = informative or set(q_tokens)
57
58 # Check for ambiguous acronyms that need case-sensitive handling
59 t_tokens = relevance.tokenize(text)
60 filtered_q_tokens = set(effective_q_tokens)
61 for acronym in _CASE_SENSITIVE_ACRONYMS:
62 if acronym in effective_q_tokens and acronym in t_tokens:
63 # Text has the token, but we need to check if it's the acronym (US)
64 # or the common word (us). If text only has lowercase, don't count it.
65 has_uppercase = bool(re.search(rf'\b{acronym.upper()}\b', text))
66 has_lowercase = bool(re.search(rf'\b{acronym}\b', text))
67 if has_lowercase and not has_uppercase:
68 # Text only has lowercase version (pronoun) - don't count this
69 # token in query overlap. This effectively removes "us" from
70 # contributing to the score when text has only the pronoun.
71 t_tokens = t_tokens - {acronym}
72 # Also remove from query for this calculation to avoid
73 # penalizing the overall coverage ratio
74 filtered_q_tokens = filtered_q_tokens - {acronym}
75
76 # If filtering removed all query tokens, fall back to 0
77 if not filtered_q_tokens:
78 return 0.0
79
80 overlap_tokens = filtered_q_tokens & t_tokens
81 if not overlap_tokens:
82 return 0.0
83
84 # Compute simplified relevance: coverage ratio
85 # This is a simpler version of token_overlap_relevance that uses
86 # the filtered tokens rather than re-tokenizing the original text
87 coverage = len(overlap_tokens) / len(filtered_q_tokens)
88 return coverage
89
90
91 def judge_x_corpus(
92 items: List[Dict[str, Any]],
93 topic: str,
94 *,
95 ranking_query: str = "",
96 ) -> Dict[str, Any]:
97 """Judge the retrieved X corpus for on-topic ratio.
98
99 Args:
100 items: List of X items with 'author_handle' and 'text' fields
101 topic: The user topic (e.g., "Rome")
102 ranking_query: Optional ranking query for better relevance scoring
103
104 Returns:
105 Dict with:
106 - on_topic_ratio: float, fraction of posts that are on-topic
107 - is_off_topic_flood: bool, True if corpus fails the on-topic floor
108 - on_topic_items: list, items that passed relevance check
109 - off_topic_items: list, items that failed relevance check
110 - handle_stats: dict, per-handle on-topic counts and totals
111 """
112 if not items:
113 return {
114 "on_topic_ratio": 1.0,
115 "is_off_topic_flood": False,
116 "on_topic_items": [],
117 "off_topic_items": [],
118 "handle_stats": {},
119 }
120
121 # Use ranking_query if provided, otherwise topic
122 query = ranking_query or topic
123
124 on_topic_items = []
125 off_topic_items = []
126 handle_stats: Dict[str, Dict[str, int]] = {}
127
128 for item in items:
129 handle = (item.get("author_handle") or "").lower()
130 text = item.get("text") or ""
131 score = _compute_relevance(query, text)
132
133 # On-topic threshold: relevance.RELEVANCE_FLOOR is 0.1
134 is_on_topic = score >= relevance.RELEVANCE_FLOOR
135
136 if is_on_topic:
137 on_topic_items.append(item)
138 else:
139 off_topic_items.append(item)
140
141 if handle:
142 if handle not in handle_stats:
143 handle_stats[handle] = {"on_topic": 0, "total": 0}
144 handle_stats[handle]["total"] += 1
145 if is_on_topic:
146 handle_stats[handle]["on_topic"] += 1
147
148 on_topic_ratio = len(on_topic_items) / len(items) if items else 1.0
149
150 # Check if top-3 frequency authors have poor on-topic ratio
151 top_handles = sorted(
152 handle_stats.items(),
153 key=lambda x: x[1]["total"],
154 reverse=True,
155 )[:3]
156 top_authors_off_topic = all(
157 stats["on_topic"] / stats["total"] < HANDLE_ON_TOPIC_FLOOR
158 for _, stats in top_handles
159 if stats["total"] > 0
160 ) if top_handles else False
161
162 is_off_topic_flood = (
163 on_topic_ratio < CORPUS_ON_TOPIC_FLOOR
164 or (top_authors_off_topic and len(on_topic_items) < MIN_ON_TOPIC_HITS)
165 )
166
167 return {
168 "on_topic_ratio": on_topic_ratio,
169 "is_off_topic_flood": is_off_topic_flood,
170 "on_topic_items": on_topic_items,
171 "off_topic_items": off_topic_items,
172 "handle_stats": handle_stats,
173 }
174
175
176 def promotable_handles(
177 items: List[Dict[str, Any]],
178 topic: str,
179 extracted_handles: List[str],
180 *,
181 explicit_handles: Optional[List[str]] = None,
182 ranking_query: str = "",
183 ) -> Tuple[List[str], List[str]]:
184 """Determine which handles should be promoted to the FROM lane.
185
186 Split FROM promotion:
187 - Explicit handles (--x-handle/--x-related): always promoted, no AND topic
188 - Extracted handles: promoted only if:
189 - ≥MIN_ON_TOPIC_HITS on-topic keyword hits AND
190 - author on-topic ratio ≥ HANDLE_ON_TOPIC_FLOOR
191 - These pulls AND the topic (from:handle Rome)
192
193 Args:
194 items: List of X items with 'author_handle' and 'text' fields
195 topic: The user topic
196 extracted_handles: Handles extracted from entity_extract
197 explicit_handles: Explicit --x-handle/--x-related handles
198 ranking_query: Optional ranking query for relevance scoring
199
200 Returns:
201 Tuple of (explicit_promotable, extracted_promotable):
202 - explicit_promotable: handles that get FROM without AND topic
203 - extracted_promotable: handles that get FROM with AND topic
204 """
205 explicit_set = {
206 h.lower().lstrip("@")
207 for h in (explicit_handles or [])
208 if h and h.strip()
209 }
210
211 # Judge corpus to get handle stats
212 judgment = judge_x_corpus(items, topic, ranking_query=ranking_query)
213 handle_stats = judgment["handle_stats"]
214
215 explicit_promotable = []
216 extracted_promotable = []
217
218 for handle in extracted_handles:
219 handle_lower = handle.lower().lstrip("@")
220
221 # Explicit handles always promoted (no AND topic)
222 if handle_lower in explicit_set:
223 explicit_promotable.append(handle)
224 continue
225
226 # Check if handle qualifies for extracted promotion
227 stats = handle_stats.get(handle_lower, {"on_topic": 0, "total": 0})
228
229 # Need ≥MIN_ON_TOPIC_HITS on-topic posts
230 if stats["on_topic"] < MIN_ON_TOPIC_HITS:
231 continue
232
233 # Need ≥HANDLE_ON_TOPIC_FLOOR ratio
234 if stats["total"] > 0:
235 ratio = stats["on_topic"] / stats["total"]
236 if ratio >= HANDLE_ON_TOPIC_FLOOR:
237 extracted_promotable.append(handle)
238
239 # Also check explicit handles not in extracted list
240 for handle in (explicit_handles or []):
241 handle_lower = handle.lower().lstrip("@")
242 if handle_lower not in [h.lower() for h in explicit_promotable]:
243 if handle_lower not in [h.lower() for h in extracted_handles]:
244 explicit_promotable.append(handle)
245
246 return explicit_promotable, extracted_promotable
247
248
249 def should_retry_x_search(
250 items: List[Dict[str, Any]],
251 topic: str,
252 *,
253 ranking_query: str = "",
254 depth: str = "default",
255 ) -> bool:
256 """Determine if X search should retry with wider keyword query.
257
258 Skip retry on quick/mock (same as Phase 2).
259
260 Args:
261 items: Retrieved X items
262 topic: The user topic
263 ranking_query: Optional ranking query
264 depth: Search depth ("quick", "default", "deep")
265
266 Returns:
267 True if retry is warranted
268 """
269 if depth == "quick":
270 return False
271
272 if not items:
273 return False # Nothing to judge, no retry
274
275 judgment = judge_x_corpus(items, topic, ranking_query=ranking_query)
276 return judgment["is_off_topic_flood"]
277
278
279 def prune_off_topic_items(
280 items: List[Dict[str, Any]],
281 topic: str,
282 *,
283 ranking_query: str = "",
284 ) -> List[Dict[str, Any]]:
285 """Prune off-topic items before the pool.
286
287 Eight on-topic items with 32 pruned → ok with 8.
288 Zero on-topic → no-results, not ok with 40 junk.
289
290 Args:
291 items: Retrieved X items
292 topic: The user topic
293 ranking_query: Optional ranking query
294
295 Returns:
296 Only on-topic items
297 """
298 judgment = judge_x_corpus(items, topic, ranking_query=ranking_query)
299 return judgment["on_topic_items"]
300
300 lines PYTHON