dsh-plugin-chuhai 0.2.2 → 0.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/CHANGELOG.md +31 -21
  2. package/LICENSE +21 -21
  3. package/README.md +25 -25
  4. package/books/ai-global-media/BOOK.md +129 -119
  5. package/books/ai-global-media/expert/SOURCE.json +41 -0
  6. package/books/ai-global-media/expert/agents/ilang-wechat-awesome.md +267 -0
  7. package/books/ai-global-media/expert/skills/remote-dispatch/SKILL.md +101 -0
  8. package/books/ai-global-media/expert/skills/remote-dispatch/references/gateway-api.md +58 -0
  9. package/books/ai-global-media/expert/skills/remote-dispatch/scripts/dispatch.py +299 -0
  10. package/books/ai-global-media/expert/skills/remote-dispatch/scripts/setup-gateway.ps1 +74 -0
  11. package/books/ai-global-media/expert/skills/remote-dispatch/scripts/setup-gateway.sh +94 -0
  12. package/books/ai-global-media/expert/skills/wechat-article/SKILL.md +80 -0
  13. package/books/ai-global-media/expert/skills/wechat-article/references/algorithm-and-rhythm.md +54 -0
  14. package/books/ai-global-media/expert/skills/wechat-article/references/compliance.md +68 -0
  15. package/books/ai-global-media/expert/skills/wechat-article/references/cover-prompt.md +19 -0
  16. package/books/ai-global-media/expert/skills/wechat-article/references/deai.md +64 -0
  17. package/books/ai-global-media/expert/skills/wechat-article/references/genes.md +168 -0
  18. package/books/ai-global-media/expert/skills/wechat-article/references/other-platforms.md +47 -0
  19. package/books/ai-global-media/expert/skills/wechat-article/references/self-check.md +32 -0
  20. package/books/ai-global-media/expert/skills/wechat-article/references/structures-and-titles.md +77 -0
  21. package/books/ai-global-media/expert/skills/wechat-article/references/wechat-format-and-api.md +61 -0
  22. package/books/ai-global-media/expert/skills/wechat-draft-push/SKILL.md +129 -0
  23. package/books/ai-global-media/expert/skills/wechat-draft-push/references/api-notes.md +168 -0
  24. package/books/ai-global-media/expert/skills/wechat-draft-push/references/html-rules.md +62 -0
  25. package/books/ai-global-media/expert/skills/wechat-draft-push/scripts/cards.html +75 -0
  26. package/books/ai-global-media/expert/skills/wechat-draft-push/scripts/newspic_cards.py +345 -0
  27. package/books/ai-global-media/expert/skills/wechat-draft-push/scripts/wechat_draft.py +1023 -0
  28. package/books/ai-global-media/expert/skills/wechat-topic-hunter/SKILL.md +92 -0
  29. package/books/ai-global-media/expert/skills/wechat-topic-hunter/references/method.md +49 -0
  30. package/books/ai-global-media/expert/skills/wechat-topic-hunter/references/wxrank-api.md +51 -0
  31. package/books/ai-global-media/expert/skills/wechat-topic-hunter/scripts/hot_sources.py +553 -0
  32. package/books/ai-global-media/expert/skills/wechat-topic-hunter/scripts/sources.json +714 -0
  33. package/books/ai-global-media/expert/skills/wechat-topic-hunter/scripts/wxrank_topics.py +466 -0
  34. package/books/ai-global-media/lens-yiyang.md +86 -0
  35. package/books/ai-global-media/poster-poju.jpg +0 -0
  36. package/cordis.patch.yml +8 -8
  37. package/lib/index.js +12 -1
  38. package/package.json +53 -53
@@ -0,0 +1,553 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """公众号代写 · 拉热点源。只用标准库,只读公开的 RSS / JSON / 页面,8 秒超时,打不开就跳过。
4
+
5
+ 用法:
6
+ python hot_sources.py 全部源,每源最多 8 条
7
+ python hot_sources.py --group AI,热榜 只拉某几个方向(AI 科技 热榜 财经 产品 海外)
8
+ python hot_sources.py --n 5 --keyword 公众号,副业 每源 5 条,只留标题含关键词的
9
+ python hot_sources.py --cluster 跨平台同事件聚一起,标出几个源同时在爆
10
+ python hot_sources.py --words 订阅词.txt 按订阅词文件筛(语法见下)
11
+ python hot_sources.py --json 机器可读输出
12
+
13
+ 订阅词文件:一行一个词,空行分组。普通词=命中任一即可;+词=这组必须含;!词=这组排除;/正则/=正则;@数字=这组最多留几条。
14
+ 例:
15
+ AI写作
16
+ 公众号
17
+ +副业
18
+ !招聘
19
+ @5
20
+
21
+ 输出每条:源 | 时间 | 标题 | 链接。只拿标题和链接当选题线索,不搬正文。
22
+ """
23
+ import argparse, concurrent.futures, datetime, html, io, json, math, os, re, sys, time
24
+ import urllib.request, urllib.error
25
+ import xml.etree.ElementTree as ET
26
+
27
+ try:
28
+ sys.stdout.reconfigure(encoding="utf-8")
29
+ except Exception:
30
+ pass
31
+
32
+ HERE = os.path.dirname(os.path.abspath(__file__))
33
+ UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36"
34
+
35
+
36
+ def fetch(url, timeout=8):
37
+ req = urllib.request.Request(url, headers={"User-Agent": UA, "Accept": "*/*", "Accept-Language": "zh-CN,zh;q=0.9"})
38
+ with urllib.request.urlopen(req, timeout=timeout) as r:
39
+ return r.read()
40
+
41
+
42
+ def strip_tags(s):
43
+ return html.unescape(re.sub(r"<[^>]+>", "", s or "")).strip()
44
+
45
+
46
+ DATE_TITLE = re.compile(r"^[\s\d\-/.:年月日号周星期一二三四五六日天期第]+$")
47
+
48
+
49
+ def pure_date_title(s):
50
+ """标题只是日期或编号(早报入口、列表页),不是一个具体的题。"""
51
+ return bool(s) and bool(DATE_TITLE.match(s.strip()))
52
+
53
+
54
+ def explode_digest(raw, keep=1):
55
+ """日报类 RSS:标题是日期,正文里才是一条条标题。把最近 keep 条日报的正文拆成单条,带上日报的链接和日期。"""
56
+ out = []
57
+ try:
58
+ root = ET.fromstring(raw)
59
+ except ET.ParseError:
60
+ return out
61
+ done = 0
62
+ for it in root.iter("item"):
63
+ title = strip_tags(it.findtext("title") or "")
64
+ if not pure_date_title(title):
65
+ continue
66
+ link = (it.findtext("link") or "").strip()
67
+ date = (it.findtext("pubDate") or "").strip()
68
+ desc = strip_tags(it.findtext("description") or it.findtext("{http://purl.org/rss/1.0/modules/content/}encoded") or "")
69
+ parts = re.split(r"↗\s*\d*|\n|(?<=[。!?])\s", desc)
70
+ for p in parts:
71
+ p = re.sub(r"^\s*(AI 早报.*?概览|概览|要闻|开发生态|产品应用|模型|行业|研究|观点|视频版.*?哔哩哔哩)\s*", "", p.strip())
72
+ p = re.sub(r"\s*\d+\s*$", "", p).strip(" ::||")
73
+ if 8 <= len(p) <= 90 and not pure_date_title(p) and not JUNK.search(p):
74
+ out.append((p, link, date))
75
+ done += 1
76
+ if done >= keep:
77
+ break
78
+ seen, uniq = set(), []
79
+ for x in out:
80
+ if x[0] not in seen:
81
+ seen.add(x[0]); uniq.append(x)
82
+ return uniq
83
+
84
+
85
+ def parse_rss(raw):
86
+ items = []
87
+ try:
88
+ root = ET.fromstring(raw)
89
+ except ET.ParseError:
90
+ return items
91
+ ns = {"a": "http://www.w3.org/2005/Atom"}
92
+ for it in root.iter("item"):
93
+ t = strip_tags((it.findtext("title") or ""))
94
+ l = (it.findtext("link") or "").strip()
95
+ d = (it.findtext("pubDate") or it.findtext("{http://purl.org/dc/elements/1.1/}date") or "").strip()
96
+ if t:
97
+ items.append((t, l, d))
98
+ if not items:
99
+ for e in root.findall(".//a:entry", ns):
100
+ t = strip_tags(e.findtext("a:title", default="", namespaces=ns))
101
+ le = e.find("a:link", ns)
102
+ l = le.get("href") if le is not None else ""
103
+ d = (e.findtext("a:updated", default="", namespaces=ns) or e.findtext("a:published", default="", namespaces=ns)).strip()
104
+ if t:
105
+ items.append((t, l, d))
106
+ return items
107
+
108
+
109
+ def _get(obj, keys):
110
+ """大小写不敏感地按顺序取第一个像样的字符串字段。"""
111
+ low = {str(k).lower(): v for k, v in obj.items()}
112
+ for k in keys:
113
+ v = low.get(k.lower())
114
+ if isinstance(v, str) and v.strip():
115
+ return v.strip()
116
+ return None
117
+
118
+
119
+ JUNK = re.compile(r"榜单介绍|上榜规则|登录|注册|VIP|充值|©|^\d{4}-\d{2}-\d{2}$|^https?://")
120
+
121
+
122
+ TIME_KEYS = ("time", "pubDate", "publishDate", "publish_time", "created", "created_at", "createtime", "display_time", "ctime", "pubtime", "updated_at", "date")
123
+
124
+
125
+ def walk_json(obj, out, url_tpl=None, depth=0, ctx=None):
126
+ """从任意 JSON 里捞 {标题, 链接, 时间} 三元组,键名大小写不敏感。url_tpl 用字段值拼链接,如 {contId};
127
+ ctx 是祖先节点的标量字段,拼链接和取时间时兜底(金十的 id、time 在外层,title 在 data 里)。"""
128
+ if depth > 7:
129
+ return
130
+ ctx = ctx or {}
131
+ if isinstance(obj, dict):
132
+ scal = dict(ctx)
133
+ scal.update({k: v for k, v in obj.items() if isinstance(v, (str, int))})
134
+ t = _get(obj, ("title", "word", "query", "topic", "topic_name", "name", "hotWord", "keyword"))
135
+ if not (t and 4 <= len(t) <= 120):
136
+ t2 = _get(obj, ("text", "content"))
137
+ t = t2 if t2 and 6 <= len(t2) <= 90 else None
138
+ if t and not JUNK.search(t):
139
+ l = _get(obj, ("url", "link", "mobileUrl", "mobil_url", "href", "short_link_v2", "short_link", "shareUrl", "article_url", "appUrl", "pcUrl", "topic_url", "topicUrl", "source_link")) or ""
140
+ if not l and isinstance(obj.get("links"), dict):
141
+ l = next((v for v in obj["links"].values() if isinstance(v, str) and v.startswith("http")), "")
142
+ if not l and isinstance(obj.get("bvid"), str):
143
+ l = "https://www.bilibili.com/video/" + obj["bvid"]
144
+ if not l and url_tpl:
145
+ try:
146
+ l = url_tpl.format(**scal)
147
+ except Exception:
148
+ l = ""
149
+ l = html.unescape(l) if l else ""
150
+ if l and not l.startswith("http"):
151
+ l = ""
152
+ d = _get(obj, TIME_KEYS) or _get({k: str(v) for k, v in scal.items()}, TIME_KEYS) or ""
153
+ out.append((strip_tags(t), l, d))
154
+ scal = {}
155
+ for v in obj.values():
156
+ walk_json(v, out, url_tpl, depth + 1, scal)
157
+ elif isinstance(obj, list):
158
+ for v in obj:
159
+ walk_json(v, out, url_tpl, depth + 1, ctx)
160
+
161
+
162
+ def dedupe(items):
163
+ seen, uniq = set(), []
164
+ for it in items:
165
+ if it[0] not in seen:
166
+ seen.add(it[0]); uniq.append(it)
167
+ return uniq
168
+
169
+
170
+ def parse_json(raw, url_tpl=None):
171
+ try:
172
+ data = json.loads(raw.decode("utf-8", "replace"))
173
+ except Exception:
174
+ return []
175
+ out = []
176
+ walk_json(data, out, url_tpl)
177
+ return dedupe(out)
178
+
179
+
180
+ def parse_js(raw, url_tpl=None):
181
+ s = raw.decode("utf-8", "replace").strip()
182
+ s = re.sub(r"^\s*(var|let|const)\s+\w+\s*=\s*", "", s).rstrip(";").strip()
183
+ return parse_json(s.encode("utf-8"), url_tpl)
184
+
185
+
186
+ def parse_sdata(raw, url_tpl=None):
187
+ s = raw.decode("utf-8", "replace")
188
+ m = re.search(r"<!--s-data:(.*?)-->", s, re.S)
189
+ if not m:
190
+ return []
191
+ return parse_json(m.group(1).encode("utf-8"), url_tpl)
192
+
193
+
194
+ def parse_html(raw, src):
195
+ s = raw.decode("utf-8", "replace")
196
+ pat = src.get("pattern")
197
+ if not pat:
198
+ return []
199
+ base = src.get("base") or re.match(r"https?://[^/]+", src["url"]).group(0)
200
+ items = []
201
+ for m in re.finditer(pat, s, re.S | re.I):
202
+ g = m.groupdict()
203
+ t = strip_tags(g.get("title") or "")
204
+ l = (g.get("href") or "").strip()
205
+ if l.startswith("/"):
206
+ l = base + l
207
+ if 6 <= len(t) <= 120 and not JUNK.search(t):
208
+ items.append((t, l, ""))
209
+ return dedupe(items)
210
+
211
+
212
+ REL_RE = re.compile(r"(\d+)\s*(秒|分钟|分|小时|时|天|日|周|星期|个月|月)\s*前")
213
+ REL_UNIT = {"秒": 1 / 3600, "分钟": 1 / 60, "分": 1 / 60, "小时": 1, "时": 1, "天": 24, "日": 24, "周": 168, "星期": 168, "个月": 720, "月": 720}
214
+ ISO_RE = re.compile(r"(\d{4})[-/.年](\d{1,2})[-/.月](\d{1,2})日?(?:[T\s]+(\d{1,2}):(\d{2})(?::(\d{2}))?(?:\.\d+)?\s*(Z|[+-]\d{2}:?\d{2})?)?")
215
+ MD_RE = re.compile(r"^(\d{1,2})[-/月](\d{1,2})日?(?:\s+(\d{1,2}):(\d{2}))?$")
216
+
217
+
218
+ def norm_time(d, now=None):
219
+ """各源的时间写法统一成本地钟的 'MM-DD HH:MM':时间戳、ISO(带时区的换算成本地)、RFC2822(同上)、
220
+ '22分钟前'、'昨天 12:30'、只有日期的按当天 00:00。认不出的原样截 16 位。"""
221
+ if not d:
222
+ return ""
223
+ d = str(d).strip()
224
+ now = now or datetime.datetime.now()
225
+ try:
226
+ if re.fullmatch(r"\d{10}", d):
227
+ return datetime.datetime.fromtimestamp(int(d)).strftime("%m-%d %H:%M")
228
+ if re.fullmatch(r"\d{13}", d):
229
+ return datetime.datetime.fromtimestamp(int(d) / 1000).strftime("%m-%d %H:%M")
230
+ if d.startswith("刚刚") or d in ("今天", "今日"):
231
+ return now.strftime("%m-%d %H:%M")
232
+ m = REL_RE.search(d)
233
+ if m:
234
+ return (now - datetime.timedelta(hours=int(m.group(1)) * REL_UNIT[m.group(2)])).strftime("%m-%d %H:%M")
235
+ m = re.match(r"^(今天|昨天|前天)\s*(\d{1,2}):(\d{2})$", d)
236
+ if m:
237
+ day = now - datetime.timedelta(days={"今天": 0, "昨天": 1, "前天": 2}[m.group(1)])
238
+ return day.strftime("%m-%d") + " %02d:%s" % (int(m.group(2)), m.group(3))
239
+ m = ISO_RE.search(d)
240
+ if m:
241
+ dt = datetime.datetime(int(m.group(1)), int(m.group(2)), int(m.group(3)), int(m.group(4) or 0), int(m.group(5) or 0))
242
+ tz = m.group(7)
243
+ if tz:
244
+ off = 0 if tz.upper() == "Z" else (1 if tz[0] == "+" else -1) * (int(tz[1:3]) * 60 + int(tz[-2:]))
245
+ dt = dt.replace(tzinfo=datetime.timezone(datetime.timedelta(minutes=off))).astimezone().replace(tzinfo=None)
246
+ return dt.strftime("%m-%d %H:%M")
247
+ m = MD_RE.match(d)
248
+ if m:
249
+ return "%02d-%02d %02d:%s" % (int(m.group(1)), int(m.group(2)), int(m.group(3) or 0), m.group(4) or "00")
250
+ import email.utils
251
+ dt = email.utils.parsedate_to_datetime(d)
252
+ if dt.tzinfo is not None:
253
+ dt = dt.astimezone().replace(tzinfo=None)
254
+ return dt.strftime("%m-%d %H:%M")
255
+ except Exception:
256
+ return d[:16]
257
+
258
+
259
+ def age_hours(t, now=None):
260
+ """'MM-DD HH:MM' → 距今小时数;一月初碰到去年十二月的按去年算;不是这个格式返回 None。"""
261
+ m = re.match(r"^(\d{2})-(\d{2}) (\d{2}):(\d{2})$", t or "")
262
+ if not m:
263
+ return None
264
+ now = now or datetime.datetime.now()
265
+ try:
266
+ dt = datetime.datetime(now.year, int(m.group(1)), int(m.group(2)), int(m.group(3)), int(m.group(4)))
267
+ if dt > now + datetime.timedelta(days=2):
268
+ dt = dt.replace(year=now.year - 1)
269
+ except ValueError:
270
+ return None
271
+ return (now - dt).total_seconds() / 3600
272
+
273
+
274
+ def newest(times, now=None):
275
+ """一组 'MM-DD HH:MM' 里最新的那个:按距今小时数比,不按字符串比大小,跨年不出错。"""
276
+ best, best_age = "", None
277
+ for x in times:
278
+ a = age_hours(x, now)
279
+ if a is not None and (best_age is None or a < best_age):
280
+ best, best_age = x, a
281
+ return best or (max(times) if times else "")
282
+
283
+
284
+ def pull(src, n):
285
+ """拉一个源。打不开、解析不了、配置坏了都只返回 (src, [], 说明),不抛异常:一条坏源不能拖死整轮。"""
286
+ t0 = time.time()
287
+ url = src.get("url") or ""
288
+ if not url.startswith("http"):
289
+ return src, [], "配置坏了 缺 url"
290
+ if src.get("cache_bust"):
291
+ url += ("&" if "?" in url else "?") + "%s=%d" % (src["cache_bust"], int(time.time() * 1000))
292
+ try:
293
+ raw = fetch(url)
294
+ except Exception as e:
295
+ return src, [], "打不开 %s" % type(e).__name__
296
+ try:
297
+ typ = src.get("type", "rss")
298
+ if typ == "rss":
299
+ items = parse_rss(raw)
300
+ if src.get("explode_digest"):
301
+ items = explode_digest(raw, int(src.get("explode_digest") if str(src.get("explode_digest")).isdigit() else 1)) + items
302
+ elif typ == "json":
303
+ items = parse_json(raw, src.get("url_tpl"))
304
+ elif typ == "js":
305
+ items = parse_js(raw, src.get("url_tpl"))
306
+ elif typ == "sdata":
307
+ items = parse_sdata(raw, src.get("url_tpl"))
308
+ else:
309
+ items = parse_html(raw, src)
310
+ if src.get("need_link"):
311
+ items = [it for it in items if it[1]]
312
+ if not src.get("keep_date_titles"):
313
+ items = [it for it in items if not pure_date_title(it[0])]
314
+ except Exception as e:
315
+ return src, [], "解析失败 %s" % type(e).__name__
316
+ return src, items[:n], "%.1fs" % (time.time() - t0)
317
+
318
+
319
+ # ---------- 跨平台同事件聚类(照 beacon 的思路自己写:去数字标点停用字模板词,2-gram 余弦) ----------
320
+ STOP = set("的了是在和与及对为被从把这那个吗呢啊吧也都就还又很之其中于上下里外后前")
321
+ TEMPLATE = re.compile(r"如何看待|如何评价|怎么看|怎样看待|直击|重磅|突发|官方回应|网友热议|最新消息|刚刚|今日|今天|图集|视频|组图|实探|深度|观察|独家")
322
+
323
+
324
+ def norm_title(t):
325
+ t = TEMPLATE.sub("", t)
326
+ t = re.sub(r"[0-90-9]+", "", t)
327
+ t = re.sub(r"[^\w一-鿿]+", "", t)
328
+ return "".join(ch for ch in t if ch not in STOP)
329
+
330
+
331
+ def grams(t):
332
+ t = norm_title(t)
333
+ return set(t[i:i + 2] for i in range(len(t) - 1)) if len(t) >= 2 else set()
334
+
335
+
336
+ def cosine(a, b):
337
+ if not a or not b:
338
+ return 0.0
339
+ return len(a & b) / math.sqrt(len(a) * len(b))
340
+
341
+
342
+ VERSION_RE = re.compile(r"(?<![\w.])v?\d+(?:\.\d+)+(?![\w.])|(?<=[A-Za-z])[\s-]?\d+(?:\.\d+)?(?![\w.])", re.I)
343
+ EN_STOP = set("the a an of to in on for and or with by at from is are was were be as it its this that these those new how why what when who vs".split())
344
+
345
+
346
+ def is_ascii(t):
347
+ return bool(re.fullmatch(r"[\x00-\x7f]*", t))
348
+
349
+
350
+ def words(t):
351
+ return set(w for w in re.findall(r"[a-z0-9][a-z0-9.+#-]*", t.lower()) if len(w) >= 3 and w not in EN_STOP)
352
+
353
+
354
+ def versions(t):
355
+ return set(m.group(0).strip(" -").lower() for m in VERSION_RE.finditer(t))
356
+
357
+
358
+ OPPOSITES = [("跌破", "突破"), ("下跌", "上涨"), ("跌停", "涨停"), ("新低", "新高"), ("最低", "最高"), ("下降", "上升"), ("下滑", "增长"),
359
+ ("减少", "增加"), ("亏损", "盈利"), ("低于", "超过"), ("退市", "上市"), ("关闭", "开放"), ("否决", "通过"), ("反对", "支持"),
360
+ ("败诉", "胜诉"), ("否认", "承认"), ("取消", "恢复"), ("下架", "上架"), ("解约", "签约"), ("离职", "入职"), ("卸任", "上任"),
361
+ ("跌", "涨"), ("降", "升"), ("减", "增")]
362
+
363
+
364
+ def opposite(a, b):
365
+ """一边说跌破一边说突破这种相反说法,不算同一件事。两边都含同一对词的(涨跌互现)不算。"""
366
+ for x, y in OPPOSITES:
367
+ ax, ay, bx, by = x in a, y in a, x in b, y in b
368
+ if (ax and not ay and by and not bx) or (ay and not ax and bx and not by):
369
+ return True
370
+ return False
371
+
372
+
373
+ def same_event(a, b, ga, gb, th):
374
+ """候选合并判定:字面相似。中文二字片段余弦,英文词集余弦;完全相同必合并;
375
+ 两边都带版本号且不同不合并(含 GPT-4 / GPT-5 这种连字符);相反说法不合并;
376
+ 中文去掉数字标点后不足 5 字、英文不足 2 个实词的短名只在完全相同时合并。"""
377
+ va, vb = versions(a), versions(b)
378
+ if va and vb and va != vb:
379
+ return False
380
+ na, nb = norm_title(a), norm_title(b)
381
+ if na and na == nb:
382
+ return True
383
+ if opposite(a, b):
384
+ return False
385
+ if is_ascii(a) or is_ascii(b):
386
+ if not (is_ascii(a) and is_ascii(b)):
387
+ return False
388
+ wa, wb = words(a), words(b)
389
+ if min(len(wa), len(wb)) < 2:
390
+ return False
391
+ return cosine(wa, wb) >= 0.5 and len(wa & wb) / min(len(wa), len(wb)) >= 0.6
392
+ if min(len(na), len(nb)) < 5:
393
+ return False
394
+ if not (ga and gb):
395
+ return False
396
+ return cosine(ga, gb) >= th and len(ga & gb) / min(len(ga), len(gb)) >= 0.6
397
+
398
+
399
+ def cluster(entries, th=0.42):
400
+ """entries: [(source, title, url, time)]。返回 [[entry,...], ...],按不同源的个数降序。
401
+ 这是候选合并,不是已确认的同一事件:只看标题字面,成员标题要留给人核对。"""
402
+ gs = [grams(e[1]) for e in entries]
403
+ used = [False] * len(entries)
404
+ clusters = []
405
+ for i in range(len(entries)):
406
+ if used[i]:
407
+ continue
408
+ group = [entries[i]]; used[i] = True
409
+ for j in range(i + 1, len(entries)):
410
+ if not used[j] and same_event(entries[i][1], entries[j][1], gs[i], gs[j], th):
411
+ group.append(entries[j]); used[j] = True
412
+ clusters.append(group)
413
+ clusters.sort(key=lambda g: (-len(set(e[0] for e in g)), -len(g)))
414
+ return clusters
415
+
416
+
417
+ # ---------- 订阅词(照 TrendRadar 的语法自己写一版简化的) ----------
418
+ def _valid(g):
419
+ return bool(g and (g["any"] or g["must"] or g["regex"]))
420
+
421
+
422
+ def load_words(path):
423
+ """空行分组;「# 名字」给下一组起名;普通词任一命中;+词 必须含;!词 排除;/正则/;@数字 这组最多留几条。"""
424
+ groups, cur, pending = [], None, None
425
+ for line in io.open(path, encoding="utf-8"):
426
+ s = line.strip()
427
+ if not s or s.startswith("#"):
428
+ if _valid(cur):
429
+ groups.append(cur)
430
+ cur = None
431
+ if s.startswith("#"):
432
+ pending = s.lstrip("#").strip() or None
433
+ continue
434
+ if cur is None:
435
+ cur = {"any": [], "must": [], "exclude": [], "regex": [], "cap": None, "name": pending or s}
436
+ pending = None
437
+ if s.startswith("+"):
438
+ cur["must"].append(s[1:].strip())
439
+ elif s.startswith("!"):
440
+ cur["exclude"].append(s[1:].strip())
441
+ elif s.startswith("@") and s[1:].strip().isdigit():
442
+ cur["cap"] = int(s[1:].strip())
443
+ elif len(s) >= 3 and s.startswith("/") and s.endswith("/"):
444
+ try:
445
+ cur["regex"].append(re.compile(s[1:-1], re.I))
446
+ except re.error:
447
+ pass
448
+ elif "=>" in s:
449
+ continue
450
+ else:
451
+ cur["any"].append(s)
452
+ if _valid(cur):
453
+ groups.append(cur)
454
+ return groups
455
+
456
+
457
+ def match_group(title, g):
458
+ t = title.lower()
459
+ if any(w.lower() in t for w in g["exclude"]):
460
+ return False
461
+ if any(w.lower() not in t for w in g["must"]):
462
+ return False
463
+ if g["any"] or g["regex"]:
464
+ return any(w.lower() in t for w in g["any"]) or any(r.search(title) for r in g["regex"])
465
+ return True
466
+
467
+
468
+ def drop_fallbacks(results):
469
+ """主源拉到了东西,它的备用源(fallback_for)就不要,免得同一个榜出现两份。results: [(src, items, note)]"""
470
+ got = {s["name"] for s, items, _ in results if items}
471
+ return [(s, items, note) for s, items, note in results if not (s.get("fallback_for") and s["fallback_for"] in got)]
472
+
473
+
474
+ def load_sources(path=None):
475
+ """读 sources.json,跳过 disabled 的源。"""
476
+ cfg = json.load(io.open(path or os.path.join(HERE, "sources.json"), encoding="utf-8"))
477
+ return [s for s in cfg["sources"] if not s.get("disabled")]
478
+
479
+
480
+ def main():
481
+ ap = argparse.ArgumentParser()
482
+ ap.add_argument("--group", help="AI 科技 热榜 财经 产品 海外,逗号隔开")
483
+ ap.add_argument("--n", type=int, default=8)
484
+ ap.add_argument("--keyword", help="只留标题含这些词的,逗号隔开")
485
+ ap.add_argument("--words", help="订阅词文件")
486
+ ap.add_argument("--cluster", action="store_true", help="跨平台同事件聚一起")
487
+ ap.add_argument("--json", action="store_true")
488
+ a = ap.parse_args()
489
+ srcs = load_sources()
490
+ if a.group:
491
+ gs = set(x.strip() for x in a.group.split(","))
492
+ srcs = [s for s in srcs if s.get("group") in gs]
493
+ kws = [k.strip() for k in (a.keyword or "").split(",") if k.strip()]
494
+ results = []
495
+ with concurrent.futures.ThreadPoolExecutor(max_workers=8) as ex:
496
+ for src, items, note in ex.map(lambda s: pull(s, a.n), srcs):
497
+ if kws:
498
+ items = [it for it in items if any(k.lower() in it[0].lower() for k in kws)]
499
+ results.append((src, items, note))
500
+ results = drop_fallbacks(results)
501
+ now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M")
502
+
503
+ if a.words:
504
+ groups = load_words(a.words)
505
+ entries = [(s["name"], t, l, norm_time(d)) for s, items, _ in results for t, l, d in items]
506
+ out = {}
507
+ for g in groups:
508
+ hits = [e for e in entries if match_group(e[1], g)]
509
+ if g["cap"]:
510
+ hits = hits[:g["cap"]]
511
+ out[g["name"]] = hits
512
+ if a.json:
513
+ print(json.dumps({k: [{"source": s, "title": t, "url": l, "time": d} for s, t, l, d in v] for k, v in out.items()}, ensure_ascii=False, indent=1)); return
514
+ for k, v in out.items():
515
+ print("## 订阅组 %s(%d 条)" % (k, len(v)))
516
+ for s, t, l, d in v:
517
+ print("- %s | %s | %s | %s" % (s, d or "--", t, l or "-"))
518
+ print()
519
+ print("拉取时间 %s。" % now); return
520
+
521
+ if a.cluster:
522
+ entries = [(s["name"], t, l, norm_time(d)) for s, items, _ in results for t, l, d in items]
523
+ cl = cluster(entries)
524
+ if a.json:
525
+ print(json.dumps([{"sources": sorted(set(e[0] for e in g)), "items": [{"source": s, "title": t, "url": l, "time": d} for s, t, l, d in g]} for g in cl], ensure_ascii=False, indent=1)); return
526
+ multi = [g for g in cl if len(set(e[0] for e in g)) >= 2]
527
+ print("## 多个源同时在爆(%d 组,按源数排)" % len(multi))
528
+ for g in multi:
529
+ names = sorted(set(e[0] for e in g))
530
+ print("- [%d 个源] %s" % (len(names), g[0][1]))
531
+ for s, t, l, d in g:
532
+ print(" · %s | %s | %s" % (s, t, l or "-"))
533
+ print()
534
+ print("## 单源条目 %d 条(略)" % sum(1 for g in cl if len(set(e[0] for e in g)) < 2))
535
+ print("拉取时间 %s。" % now); return
536
+
537
+ total = 0
538
+ if a.json:
539
+ print(json.dumps([{"source": s["name"], "group": s.get("group"), "note": note,
540
+ "items": [{"title": t, "url": l, "time": norm_time(d)} for t, l, d in items]}
541
+ for s, items, note in results], ensure_ascii=False, indent=1))
542
+ return
543
+ for s, items, note in results:
544
+ print("## %s(%s,%s)" % (s["name"], s.get("group", ""), note if not items else "%d 条 %s" % (len(items), note)))
545
+ for t, l, d in items:
546
+ total += 1
547
+ print("- %s | %s | %s" % (norm_time(d) or "--", t, l or "-"))
548
+ print()
549
+ print("共 %d 条,拉取时间 %s。只拿标题和角度当选题线索,不搬正文。" % (total, now))
550
+
551
+
552
+ if __name__ == "__main__":
553
+ main()