Repository navigation
Expand file tree
/
Copy pathapp.py
More file actions
1582 lines (1454 loc) · 63.6 KB
/
Copy pathapp.py
File metadata and controls
1582 lines (1454 loc) · 63.6 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
from __future__ import annotations
import argparse
import getpass
import hashlib
import io
import ipaddress
import json
import os
import re
import secrets
import socket
import sqlite3
import subprocess
import sys
import threading
import webbrowser
import xml.etree.ElementTree as ET
from datetime import UTC, datetime
from html import escape, unescape
from pathlib import Path
from urllib.parse import parse_qsl, urlencode, urljoin, urlsplit, urlunsplit
import httpx
import keyring
import qrcode
from bs4 import BeautifulSoup
from flask import Flask, abort, redirect, render_template_string, request, send_file, url_for
APP_NAME = "WechatAutoShare"
KEYRING_SERVICE = "wechat-auto-share"
MAX_DOWNLOAD_BYTES = 2_000_000
WECOM_TOKEN_URL = "https://qyapi.weixin.qq.com/cgi-bin/gettoken"
WECOM_MOMENT_URL = "https://qyapi.weixin.qq.com/cgi-bin/externalcontact/add_moment_task"
DEFAULT_SOURCES = (
("OpenAI News", "https://openai.com/news/rss.xml", "rss", "A"),
("Google DeepMind", "https://deepmind.google/blog/rss.xml", "rss", "A"),
("Hugging Face Blog", "https://huggingface.co/blog/feed.xml", "rss", "A"),
("Anthropic News", "https://www.anthropic.com/news", "html", "A"),
("DeepSeek Research & News", "https://deepseek.com/en/news/", "html", "A"),
("量子位", "https://www.qbitai.com/", "html", "B"),
)
TRACKING_QUERY_KEYS = {
"from",
"ref",
"source",
"spm",
"utm_campaign",
"utm_content",
"utm_medium",
"utm_source",
"utm_term",
}
AI_WORDS = (
"ai",
"artificial intelligence",
"agent",
"agi",
"claude",
"deepseek",
"gemini",
"gpt",
"llm",
"model",
"人工智能",
"大模型",
"智能体",
"模型",
)
GENERAL_WORDS = (
"app",
"available",
"launch",
"product",
"release",
"tool",
"use",
"应用",
"产品",
"发布",
"上线",
"工具",
)
HARDCORE_WORDS = (
"architecture",
"benchmark",
"inference",
"model card",
"open source",
"paper",
"research",
"training",
"weights",
"基准",
"开源",
"架构",
"论文",
"推理",
"训练",
)
def now_iso() -> str:
return datetime.now(UTC).replace(microsecond=0).isoformat()
def data_dir() -> Path:
override = os.environ.get("WECHAT_AUTO_SHARE_DATA_DIR")
if override:
return Path(override).resolve()
root = os.environ.get("LOCALAPPDATA") or str(Path.home() / "AppData" / "Local")
return Path(root) / APP_NAME
def db_path() -> Path:
return data_dir() / "app.db"
class ClosingConnection(sqlite3.Connection):
def __exit__(self, exc_type, exc_value, traceback):
try:
return super().__exit__(exc_type, exc_value, traceback)
finally:
self.close()
def connect() -> sqlite3.Connection:
data_dir().mkdir(parents=True, exist_ok=True)
conn = sqlite3.connect(db_path(), factory=ClosingConnection)
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA foreign_keys = ON")
return conn
def ensure_column(conn: sqlite3.Connection, table: str, column: str, definition: str) -> None:
columns = {row["name"] for row in conn.execute(f"PRAGMA table_info({table})")}
if column not in columns:
conn.execute(f"ALTER TABLE {table} ADD COLUMN {column} {definition}")
def init_db() -> None:
with connect() as conn:
conn.executescript(
"""
CREATE TABLE IF NOT EXISTS sources (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL UNIQUE,
url TEXT NOT NULL UNIQUE,
kind TEXT NOT NULL CHECK(kind IN ('rss', 'html', 'manual')),
tier TEXT NOT NULL CHECK(tier IN ('A', 'B')),
enabled INTEGER NOT NULL DEFAULT 1,
last_scan_at TEXT,
last_error TEXT
);
CREATE TABLE IF NOT EXISTS articles (
id INTEGER PRIMARY KEY,
source_id INTEGER NOT NULL REFERENCES sources(id),
url TEXT NOT NULL UNIQUE,
title TEXT NOT NULL,
content TEXT NOT NULL DEFAULT '',
summary TEXT NOT NULL DEFAULT '',
published_at TEXT,
fingerprint TEXT NOT NULL UNIQUE,
created_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS candidates (
id INTEGER PRIMARY KEY,
article_id INTEGER NOT NULL UNIQUE REFERENCES articles(id),
general_score INTEGER NOT NULL,
hardcore_score INTEGER NOT NULL,
reason TEXT NOT NULL,
general_copy TEXT NOT NULL DEFAULT '',
hardcore_copy TEXT NOT NULL DEFAULT '',
status TEXT NOT NULL DEFAULT 'pending',
created_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS settings (
key TEXT PRIMARY KEY,
value TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS delivery_jobs (
id INTEGER PRIMARY KEY,
candidate_id INTEGER NOT NULL REFERENCES candidates(id),
target TEXT NOT NULL,
audience TEXT NOT NULL,
idempotency_key TEXT NOT NULL UNIQUE,
status TEXT NOT NULL,
external_id TEXT NOT NULL DEFAULT '',
request_json TEXT NOT NULL,
response_json TEXT NOT NULL DEFAULT '',
error TEXT NOT NULL DEFAULT '',
confirmed_at TEXT NOT NULL,
created_at TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS drafts (
id INTEGER PRIMARY KEY,
target TEXT NOT NULL,
audience TEXT NOT NULL,
title TEXT NOT NULL,
summary TEXT NOT NULL,
body_markdown TEXT NOT NULL,
html TEXT NOT NULL,
sources_json TEXT NOT NULL,
status TEXT NOT NULL DEFAULT 'editing',
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
);
"""
)
ensure_column(conn, "candidates", "general_copy", "TEXT NOT NULL DEFAULT ''")
ensure_column(conn, "candidates", "hardcore_copy", "TEXT NOT NULL DEFAULT ''")
conn.executemany(
"INSERT OR IGNORE INTO sources(name, url, kind, tier) VALUES (?, ?, ?, ?)",
DEFAULT_SOURCES,
)
conn.execute(
"INSERT OR IGNORE INTO sources(name, url, kind, tier) VALUES (?, ?, 'manual', 'B')",
("手动提交", "manual://submitted"),
)
conn.execute(
"INSERT OR IGNORE INTO settings(key, value) VALUES ('csrf_token', ?)",
(secrets.token_urlsafe(24),),
)
def get_setting(key: str, default: str = "") -> str:
with connect() as conn:
row = conn.execute("SELECT value FROM settings WHERE key = ?", (key,)).fetchone()
return row["value"] if row else default
def set_setting(key: str, value: str) -> None:
with connect() as conn:
conn.execute(
"INSERT INTO settings(key, value) VALUES (?, ?) "
"ON CONFLICT(key) DO UPDATE SET value = excluded.value",
(key, value),
)
def set_wecom_credentials(corp_id: str, secret: str) -> None:
corp_id = corp_id.strip()
secret = secret.strip()
if not corp_id or len(corp_id) > 128 or not secret or len(secret) > 512:
raise ValueError("CorpID 和 Secret 不能为空")
set_setting("wecom_corp_id", corp_id)
keyring.set_password(KEYRING_SERVICE, "wecom-secret", secret)
def wecom_credentials() -> tuple[str, str]:
corp_id = get_setting("wecom_corp_id")
secret = keyring.get_password(KEYRING_SERVICE, "wecom-secret") or ""
if not corp_id or not secret:
raise ValueError("请先配置企业微信 CorpID 和 Secret")
return corp_id, secret
def wecom_access_token() -> str:
corp_id, secret = wecom_credentials()
response = httpx.get(
WECOM_TOKEN_URL,
params={"corpid": corp_id, "corpsecret": secret},
timeout=20,
)
response.raise_for_status()
result = response.json()
if not isinstance(result, dict):
raise ValueError("企业微信鉴权返回了无效数据")
if int(result.get("errcode", -1)) != 0 or not result.get("access_token"):
raise RuntimeError(f"企业微信鉴权失败:{result.get('errcode', -1)} {result.get('errmsg', '未知错误')}")
return str(result["access_token"])
def split_values(raw: str) -> list[str]:
return [value.strip() for value in re.split(r"[,,\s]+", raw) if value.strip()]
def safe_error_text(error: Exception) -> str:
return re.sub(
r"(?i)(access_token|corpsecret)=([^&\s]+)",
r"\1=***",
str(error),
)[:1000]
def build_wecom_moment_payload(
candidate: sqlite3.Row,
audience: str,
user_list: str,
department_list: str,
tag_list: str,
) -> dict[str, object]:
if audience not in {"general", "hardcore"}:
raise ValueError("受众模式无效")
users = split_values(user_list)
try:
departments = [int(value) for value in split_values(department_list)]
except ValueError as exc:
raise ValueError("部门 ID 必须是整数") from exc
if any(value <= 0 for value in departments):
raise ValueError("部门 ID 必须大于 0")
if not users and not departments:
raise ValueError("为防止误发,请至少填写一个执行成员或部门")
sender_list: dict[str, object] = {}
if users:
sender_list["user_list"] = users
if departments:
sender_list["department_list"] = departments
visible_range: dict[str, object] = {"sender_list": sender_list}
tags = split_values(tag_list)
if tags:
visible_range["external_contact_list"] = {"tag_list": tags}
return {
"text": {"content": str(candidate[f"{audience}_copy"])[:2000]},
"attachments": [
{
"msgtype": "link",
"link": {"title": str(candidate["title"])[:128], "url": candidate["url"]},
}
],
"visible_range": visible_range,
}
def submit_wecom_moment(
candidate_id: int,
audience: str,
user_list: str,
department_list: str,
tag_list: str,
) -> dict[str, object]:
with connect() as conn:
candidate = conn.execute(
"""
SELECT c.*, a.title, a.url
FROM candidates c JOIN articles a ON a.id = c.article_id
WHERE c.id = ?
""",
(candidate_id,),
).fetchone()
if not candidate:
raise ValueError("候选文章不存在")
payload = build_wecom_moment_payload(candidate, audience, user_list, department_list, tag_list)
request_json = json.dumps(payload, ensure_ascii=False, sort_keys=True)
idempotency_key = hashlib.sha256(f"{candidate_id}\n{request_json}".encode("utf-8")).hexdigest()
timestamp = now_iso()
with connect() as conn:
conn.execute("BEGIN IMMEDIATE")
existing = conn.execute(
"SELECT * FROM delivery_jobs WHERE idempotency_key = ?", (idempotency_key,)
).fetchone()
if existing and existing["status"] in {"submitting", "submitted"}:
return {
"duplicate": True,
"status": existing["status"],
"jobid": existing["external_id"],
}
if existing:
job_id = existing["id"]
conn.execute(
"UPDATE delivery_jobs SET status = 'submitting', error = '', confirmed_at = ? WHERE id = ?",
(timestamp, job_id),
)
else:
cursor = conn.execute(
"""
INSERT INTO delivery_jobs(
candidate_id, target, audience, idempotency_key, status,
request_json, confirmed_at, created_at
) VALUES (?, 'wecom_moment', ?, ?, 'submitting', ?, ?, ?)
""",
(candidate_id, audience, idempotency_key, request_json, timestamp, timestamp),
)
job_id = cursor.lastrowid
try:
token = wecom_access_token()
response = httpx.post(
WECOM_MOMENT_URL,
params={"access_token": token},
json=payload,
timeout=30,
)
response.raise_for_status()
result = response.json()
if not isinstance(result, dict):
raise ValueError("企业微信创建任务返回了无效数据")
if int(result.get("errcode", -1)) != 0 or not result.get("jobid"):
raise RuntimeError(
f"企业微信创建任务失败:{result.get('errcode', -1)} {result.get('errmsg', '未知错误')}"
)
response_json = json.dumps(result, ensure_ascii=False)
with connect() as conn:
conn.execute(
"UPDATE delivery_jobs SET status = 'submitted', external_id = ?, response_json = ? WHERE id = ?",
(str(result["jobid"]), response_json, job_id),
)
return {"duplicate": False, "status": "submitted", "jobid": str(result["jobid"])}
except (httpx.HTTPError, KeyError, TypeError, ValueError, RuntimeError, keyring.errors.KeyringError) as exc:
with connect() as conn:
conn.execute(
"UPDATE delivery_jobs SET status = 'failed', error = ? WHERE id = ?",
(safe_error_text(exc), job_id),
)
raise
def normalize_url(url: str) -> str:
parts = urlsplit(url.strip())
query = [
(key, value)
for key, value in parse_qsl(parts.query, keep_blank_values=True)
if key.lower() not in TRACKING_QUERY_KEYS and not key.lower().startswith("utm_")
]
path = parts.path or "/"
if path != "/":
path = path.rstrip("/")
return urlunsplit((parts.scheme.lower(), parts.netloc.lower(), path, urlencode(query), ""))
def validate_public_url(url: str, *, resolve: bool = True) -> str:
normalized = normalize_url(url)
parts = urlsplit(normalized)
if parts.scheme not in {"http", "https"} or not parts.hostname or parts.username:
raise ValueError("只允许不含账号信息的 HTTP/HTTPS 链接")
if parts.hostname.lower() == "localhost":
raise ValueError("不允许访问本机地址")
try:
literal = ipaddress.ip_address(parts.hostname)
addresses = [literal]
except ValueError:
addresses = []
if resolve:
addresses = {
ipaddress.ip_address(item[4][0])
for item in socket.getaddrinfo(parts.hostname, parts.port or 443, type=socket.SOCK_STREAM)
}
if any(address.is_private or address.is_loopback or address.is_link_local or address.is_reserved for address in addresses):
raise ValueError("不允许访问内网或保留地址")
return normalized
def fetch_text(url: str) -> str:
safe_url = validate_public_url(url)
headers = {"User-Agent": "WechatAutoShare/0.1 (+local single-user reader)"}
with httpx.Client(follow_redirects=True, timeout=20, headers=headers) as client:
response = client.get(safe_url)
response.raise_for_status()
final_url = validate_public_url(str(response.url))
if final_url != normalize_url(str(response.url)):
raise ValueError("重定向目标无效")
if int(response.headers.get("content-length", "0") or 0) > MAX_DOWNLOAD_BYTES:
raise ValueError("页面超过 2 MB 限制")
if len(response.content) > MAX_DOWNLOAD_BYTES:
raise ValueError("页面超过 2 MB 限制")
return response.text
def local_name(tag: str) -> str:
return tag.rsplit("}", 1)[-1].lower()
def child_text(element: ET.Element, *names: str) -> str:
wanted = {name.lower() for name in names}
for child in element.iter():
if child is element:
continue
if local_name(child.tag) in wanted and child.text:
return child.text.strip()
return ""
def strip_html(value: str) -> str:
decoded = unescape(value or "")
if "<" not in decoded and ">" not in decoded:
return " ".join(decoded.split())
return " ".join(BeautifulSoup(decoded, "html.parser").get_text(" ").split())
def parse_rss(xml_text: str, feed_url: str) -> list[dict[str, str]]:
root = ET.fromstring(xml_text)
nodes = [node for node in root.iter() if local_name(node.tag) in {"item", "entry"}]
items: list[dict[str, str]] = []
for node in nodes:
title = strip_html(child_text(node, "title"))
link = child_text(node, "link")
if not link:
for child in node.iter():
if local_name(child.tag) == "link" and child.attrib.get("href"):
link = child.attrib["href"]
break
if not title or not link:
continue
items.append(
{
"title": title,
"url": urljoin(feed_url, link),
"summary": strip_html(child_text(node, "description", "summary", "content")),
"published_at": child_text(node, "pubdate", "published", "updated", "date"),
}
)
return items
def parse_html_index(html_text: str, page_url: str) -> list[dict[str, str]]:
soup = BeautifulSoup(html_text, "html.parser")
candidates = soup.select("article a[href], h2 a[href], h3 a[href], a[href*='/news/'], a[href*='/blog/']")
host = urlsplit(page_url).hostname
seen: set[str] = set()
items: list[dict[str, str]] = []
for anchor in candidates:
title = " ".join(anchor.get_text(" ", strip=True).split())
if len(title) < 8:
continue
url = normalize_url(urljoin(page_url, anchor.get("href", "")))
if url in seen or urlsplit(url).hostname != host or url == normalize_url(page_url):
continue
seen.add(url)
items.append({"title": title, "url": url, "summary": "", "published_at": ""})
return items
def extract_article(html_text: str, fallback_title: str = "") -> tuple[str, str]:
soup = BeautifulSoup(html_text, "html.parser")
for node in soup.select("script, style, nav, footer, noscript, svg"):
node.decompose()
title_node = soup.select_one("meta[property='og:title']")
title = title_node.get("content", "").strip() if title_node else ""
if not title and soup.title:
title = soup.title.get_text(" ", strip=True)
title = title or fallback_title
main = soup.select_one("article") or soup.select_one("main") or soup.body
paragraphs = main.select("p, li") if main else []
content = "\n".join(
text
for text in (" ".join(node.get_text(" ", strip=True).split()) for node in paragraphs)
if len(text) >= 30
)
return title[:500], content[:30_000]
def heuristic_score(title: str, content: str, source: str, tier: str) -> dict[str, object]:
text = f"{title}\n{content[:10_000]}".lower()
ai_hits = sum(1 for word in AI_WORDS if word in text)
general_hits = sum(1 for word in GENERAL_WORDS if word in text)
hardcore_hits = sum(1 for word in HARDCORE_WORDS if word in text)
source_bonus = 10 if tier == "A" else 4
general = min(100, 10 + source_bonus + ai_hits * 10 + general_hits * 6)
hardcore = min(100, 10 + source_bonus + ai_hits * 10 + hardcore_hits * 8)
return {
"general_score": general,
"hardcore_score": hardcore,
"reason": f"本地初筛:AI 关键词 {ai_hits},应用信号 {general_hits},技术信号 {hardcore_hits},来源 {tier} 级。",
"general_copy": f"推荐一篇 AI 新文章:《{title}》。来自{source},适合快速了解这项变化会带来什么影响。",
"hardcore_copy": f"技术向推荐:《{title}》。建议重点关注其中的架构、基准数据、实现限制与可复现信息。来源:{source}。",
}
def ai_config() -> tuple[str, str, str] | None:
base_url = get_setting("ai_base_url")
model = get_setting("ai_model")
api_key = keyring.get_password(KEYRING_SERVICE, "ai-api-key")
if base_url and model and api_key:
return base_url, model, api_key
return None
def set_ai_credentials(base_url: str, model: str, api_key: str) -> None:
base_url = validate_public_url(base_url.strip())
model = model.strip()
api_key = api_key.strip()
if not model or len(model) > 200 or not api_key or len(api_key) > 2000:
raise ValueError("模型名称和 API Key 不能为空")
set_setting("ai_base_url", base_url.rstrip("/"))
set_setting("ai_model", model)
keyring.set_password(KEYRING_SERVICE, "ai-api-key", api_key)
def score_article(title: str, content: str, source: str, tier: str) -> dict[str, object]:
config = ai_config()
if not config:
return heuristic_score(title, content, source, tier)
base_url, model, api_key = config
endpoint = base_url.rstrip("/")
if not endpoint.endswith("/chat/completions"):
endpoint += "/chat/completions"
prompt = {
"title": title,
"source": source,
"source_tier": tier,
"content": content[:12_000],
}
payload = {
"model": model,
"temperature": 0,
"messages": [
{
"role": "system",
"content": (
"评估一篇 AI 文章。只返回 JSON,字段为 general_score、hardcore_score、reason、"
"general_copy、hardcore_copy。"
"两个分数均为 0-100 整数。通俗分衡量普通人可理解的产品与影响价值;"
"硬核分衡量架构、论文、基准、训练、推理与开源价值。未经证实的传闻应降分。"
"两段 copy 分别是自然、不夸张的朋友圈推荐语,不包含文章链接,每段不超过 180 字。"
),
},
{"role": "user", "content": json.dumps(prompt, ensure_ascii=False)},
],
}
try:
response = httpx.post(
endpoint,
headers={"Authorization": f"Bearer {api_key}"},
json=payload,
timeout=45,
)
response.raise_for_status()
raw = response.json()["choices"][0]["message"]["content"]
raw = re.sub(r"^```(?:json)?|```$", "", raw.strip(), flags=re.IGNORECASE).strip()
result = json.loads(raw)
return {
"general_score": max(0, min(100, int(result["general_score"]))),
"hardcore_score": max(0, min(100, int(result["hardcore_score"]))),
"reason": str(result["reason"])[:1000],
"general_copy": str(result["general_copy"])[:500],
"hardcore_copy": str(result["hardcore_copy"])[:500],
}
except (httpx.HTTPError, KeyError, TypeError, ValueError, json.JSONDecodeError) as exc:
fallback = heuristic_score(title, content, source, tier)
fallback["reason"] = f"AI 评分失败,已使用本地初筛:{type(exc).__name__}。{fallback['reason']}"
return fallback
def markdown_body_html(body: str) -> str:
parts: list[str] = []
in_list = False
for raw_line in body.splitlines():
line = raw_line.strip()
if not line:
if in_list:
parts.append("</ul>")
in_list = False
continue
if line.startswith("## "):
if in_list:
parts.append("</ul>")
in_list = False
parts.append(f"<h2>{escape(line[3:])}</h2>")
elif line.startswith("### "):
if in_list:
parts.append("</ul>")
in_list = False
parts.append(f"<h3>{escape(line[4:])}</h3>")
elif line.startswith("- "):
if not in_list:
parts.append("<ul>")
in_list = True
parts.append(f"<li>{escape(line[2:])}</li>")
else:
if in_list:
parts.append("</ul>")
in_list = False
parts.append(f"<p>{escape(line)}</p>")
if in_list:
parts.append("</ul>")
return "\n".join(parts)
def render_draft_html(title: str, summary: str, body: str, sources: list[dict[str, str]]) -> str:
source_items = "\n".join(
f'<li>[{index}] {escape(item["source"])}:<a href="{escape(item["url"], quote=True)}">{escape(item["title"])}</a></li>'
for index, item in enumerate(sources, 1)
)
return (
f"<article><h1>{escape(title)}</h1><p class=\"summary\">{escape(summary)}</p>"
f"{markdown_body_html(body)}<h2>参考来源</h2><ol>{source_items}</ol></article>"
)
def draft_markdown(draft: sqlite3.Row) -> str:
sources = json.loads(draft["sources_json"])
source_lines = "\n".join(
f'{index}. [{item["source"]}:{item["title"]}]({item["url"]})'
for index, item in enumerate(sources, 1)
)
return f'# {draft["title"]}\n\n> {draft["summary"]}\n\n{draft["body_markdown"]}\n\n## 参考来源\n\n{source_lines}\n'
def fallback_draft(rows: list[sqlite3.Row], audience: str) -> dict[str, str]:
topic = rows[0]["title"]
source_points = "\n".join(
f'- {row["source_name"]}发布了《{row["title"]}》[{index}]。'
for index, row in enumerate(rows, 1)
)
focus = (
"这些变化会影响哪些真实使用场景、普通用户何时能够接触到,以及现阶段有哪些限制。"
if audience == "general"
else "建议逐项核对架构、训练与推理方法、基准口径、开放程度和复现条件。"
)
return {
"title": f"从多方信息看:{topic}",
"summary": "基于多个来源整理的编辑提纲;配置 AI API 后可生成完整原创稿。",
"body": (
"## 已确认的信息\n\n"
f"{source_points}\n\n"
"## 值得关注的问题\n\n"
f"{focus}\n\n"
"## 编辑说明\n\n"
"当前未使用云端模型,因此这里只生成可核对来源的结构提纲,不建议未经补充和审校直接发布。"
),
}
def generate_draft_content(rows: list[sqlite3.Row], audience: str) -> dict[str, str]:
config = ai_config()
if not config:
return fallback_draft(rows, audience)
base_url, model, api_key = config
endpoint = base_url.rstrip("/")
if not endpoint.endswith("/chat/completions"):
endpoint += "/chat/completions"
source_data = [
{
"number": index,
"source": row["source_name"],
"title": row["title"],
"url": row["url"],
"content": row["content"][:3000],
}
for index, row in enumerate(rows, 1)
]
system = (
"根据多个可靠来源写一篇中文微信公众号原创专题稿。只返回 JSON,字段为 title、summary、"
"introduction、sections、conclusion;sections 是含 heading 和 body 的数组。"
f"受众模式为{'通俗' if audience == 'general' else '硬核'}。"
"事实陈述必须在句末用 [1]、[2] 标出来源编号;不得编造来源未提供的数字、评价或结论。"
"区分事实、来源观点和分析,写明限制;不要输出参考来源列表,系统会自动追加。"
)
try:
response = httpx.post(
endpoint,
headers={"Authorization": f"Bearer {api_key}"},
json={
"model": model,
"temperature": 0.2,
"messages": [
{"role": "system", "content": system},
{"role": "user", "content": json.dumps(source_data, ensure_ascii=False)},
],
},
timeout=90,
)
response.raise_for_status()
raw = response.json()["choices"][0]["message"]["content"]
raw = re.sub(r"^```(?:json)?|```$", "", raw.strip(), flags=re.IGNORECASE).strip()
result = json.loads(raw)
sections = result["sections"]
if not isinstance(sections, list) or not sections:
raise ValueError("缺少文章章节")
body_parts = [str(result["introduction"])[:4000]]
for section in sections[:8]:
body_parts.extend(
[f'## {str(section["heading"])[:120]}', str(section["body"])[:8000]]
)
body_parts.extend(["## 结语", str(result["conclusion"])[:4000]])
title = str(result["title"]).strip()[:200]
summary = str(result["summary"]).strip()[:500]
body = "\n\n".join(body_parts)
if not title or not summary or not all(f"[{index}]" in body for index in range(1, len(rows) + 1)):
raise ValueError("草稿缺少标题、摘要或完整来源标注")
return {
"title": title,
"summary": summary,
"body": body,
}
except (httpx.HTTPError, KeyError, TypeError, ValueError, json.JSONDecodeError):
return fallback_draft(rows, audience)
def create_official_draft(candidate_ids: list[int], audience: str) -> int:
if audience not in {"general", "hardcore"}:
raise ValueError("受众模式无效")
ids = sorted(set(candidate_ids))
if len(ids) < 2 or len(ids) > 5:
raise ValueError("请选择 2–5 篇候选文章")
placeholders = ",".join("?" for _ in ids)
with connect() as conn:
rows = conn.execute(
f"""
SELECT c.id AS candidate_id, a.title, a.url, a.content, a.published_at,
s.id AS source_id, s.name AS source_name, s.tier
FROM candidates c
JOIN articles a ON a.id = c.article_id
JOIN sources s ON s.id = a.source_id
WHERE c.id IN ({placeholders})
ORDER BY c.id
""",
ids,
).fetchall()
if len(rows) != len(ids):
raise ValueError("部分候选文章不存在")
if len({row["source_id"] for row in rows}) < 2:
raise ValueError("公众号专题至少需要两个不同来源")
sources = [
{
"source": row["source_name"],
"title": row["title"],
"url": row["url"],
"published_at": row["published_at"] or "",
}
for row in rows
]
content = generate_draft_content(rows, audience)
html = render_draft_html(content["title"], content["summary"], content["body"], sources)
timestamp = now_iso()
with connect() as conn:
cursor = conn.execute(
"""
INSERT INTO drafts(
target, audience, title, summary, body_markdown, html,
sources_json, created_at, updated_at
) VALUES ('official_account', ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
audience,
content["title"],
content["summary"],
content["body"],
html,
json.dumps(sources, ensure_ascii=False),
timestamp,
timestamp,
),
)
return int(cursor.lastrowid)
def article_exists(url: str) -> bool:
with connect() as conn:
row = conn.execute("SELECT 1 FROM articles WHERE url = ?", (normalize_url(url),)).fetchone()
return row is not None
def store_candidate(source: sqlite3.Row, item: dict[str, str], content: str) -> bool:
url = normalize_url(item["url"])
title = item["title"].strip()[:500]
fingerprint = hashlib.sha256(f"{url}\n{title.lower()}".encode("utf-8")).hexdigest()
score = score_article(title, content, source["name"], source["tier"])
if max(int(score["general_score"]), int(score["hardcore_score"])) < 45:
return False
with connect() as conn:
cursor = conn.execute(
"""
INSERT OR IGNORE INTO articles(
source_id, url, title, content, summary, published_at, fingerprint, created_at
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
""",
(
source["id"],
url,
title,
content,
item.get("summary", "")[:2000],
item.get("published_at", "")[:200],
fingerprint,
now_iso(),
),
)
if not cursor.rowcount:
return False
article_id = cursor.lastrowid
conn.execute(
"""
INSERT INTO candidates(
article_id, general_score, hardcore_score, reason,
general_copy, hardcore_copy, created_at
) VALUES (?, ?, ?, ?, ?, ?, ?)
""",
(
article_id,
score["general_score"],
score["hardcore_score"],
score["reason"],
score["general_copy"],
score["hardcore_copy"],
now_iso(),
),
)
return True
def scan_source(source: sqlite3.Row, max_items: int) -> dict[str, object]:
added = 0
error = ""
item_failures: list[str] = []
try:
index = fetch_text(source["url"])
items = parse_rss(index, source["url"]) if source["kind"] == "rss" else parse_html_index(index, source["url"])
for item in items[:max_items]:
item["url"] = validate_public_url(item["url"], resolve=False)
if article_exists(item["url"]):
continue
try:
article_html = fetch_text(item["url"])
extracted_title, content = extract_article(article_html, item["title"])
item["title"] = extracted_title
except (httpx.HTTPError, OSError, ValueError) as exc:
content = item.get("summary", "")
item_failures.append(f"{type(exc).__name__}: {item['url']}")
if not content:
continue
if store_candidate(source, item, content or item.get("summary", "")):
added += 1
except (ET.ParseError, httpx.HTTPError, OSError, ValueError) as exc:
error = f"{type(exc).__name__}: {exc}"[:1000]
if not error and item_failures:
error = f"部分正文不可抓取,已使用摘要或跳过:{len(item_failures)} 条。{item_failures[0]}"[:1000]
with connect() as conn:
conn.execute(
"UPDATE sources SET last_scan_at = ?, last_error = ? WHERE id = ?",
(now_iso(), error, source["id"]),
)
return {"source": source["name"], "added": added, "error": error}
def scan_all(max_items: int = 3) -> list[dict[str, object]]:
init_db()
with connect() as conn:
sources = conn.execute(
"SELECT * FROM sources WHERE enabled = 1 AND kind != 'manual' ORDER BY tier, id"
).fetchall()
return [scan_source(source, max_items) for source in sources]
TOAST_SCRIPT = r"""
[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType=WindowsRuntime] > $null
[Windows.UI.Notifications.ToastNotification, Windows.UI.Notifications, ContentType=WindowsRuntime] > $null
[Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType=WindowsRuntime] > $null
$xml = New-Object Windows.Data.Xml.Dom.XmlDocument
$title = [Security.SecurityElement]::Escape($env:WECHAT_AUTO_SHARE_TOAST_TITLE)
$message = [Security.SecurityElement]::Escape($env:WECHAT_AUTO_SHARE_TOAST_MESSAGE)
$xml.LoadXml("<toast><visual><binding template='ToastGeneric'><text>$title</text><text>$message</text></binding></visual></toast>")
$toast = [Windows.UI.Notifications.ToastNotification]::new($xml)
[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier('Microsoft.Windows.PowerShell').Show($toast)
"""
def notify_windows(title: str, message: str) -> bool:
if os.name != "nt":
return False
env = os.environ.copy()
env["WECHAT_AUTO_SHARE_TOAST_TITLE"] = title[:100]
env["WECHAT_AUTO_SHARE_TOAST_MESSAGE"] = message[:500]
flags = getattr(subprocess, "CREATE_NO_WINDOW", 0)
try:
result = subprocess.run(
["powershell.exe", "-NoProfile", "-NonInteractive", "-Command", TOAST_SCRIPT],
env=env,
capture_output=True,
timeout=10,
creationflags=flags,
check=False,
)
return result.returncode == 0
except (OSError, subprocess.TimeoutExpired):
return False
def maybe_notify(added: int) -> bool:
if added <= 0:
return False
local_now = datetime.now()
if local_now.hour >= 22 or local_now.hour < 8:
return False
today = local_now.date().isoformat()
if get_setting("notification_date") != today:
set_setting("notification_date", today)
set_setting("notification_count", "0")
count = int(get_setting("notification_count", "0"))
if count >= 2:
return False
sent = notify_windows("AI 内容分发助手", f"发现 {added} 篇新的候选文章,点击本地管理页查看。")
if sent:
set_setting("notification_count", str(count + 1))
return sent
def scheduled_action() -> str:
if getattr(sys, "frozen", False):
return f'"{sys.executable}" scan --max-items 3'
return f'"{sys.executable}" "{Path(__file__).resolve()}" scan --max-items 3'
def install_schedule() -> None:
action = scheduled_action()
flags = getattr(subprocess, "CREATE_NO_WINDOW", 0)
for suffix, time in (("Morning", "09:00"), ("Evening", "18:00")):
result = subprocess.run(
[
"schtasks.exe",