agentic_media_pipeline.py
11.8 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
#!/usr/bin/env python3
"""
agentic_media_pipeline.py - 完整的 Agentic Media 工作流
4-Agent Pipeline:
1. News Collector: 从微信群收集消息
2. News Editor: 用 Kimi 2.6 编辑内容,生成结构化日报
3. Layout Planner: 规划报纸版面布局
4. GPT Image 2: 生成维多利亚报纸风格信息图
Usage:
python3 agentic_media_pipeline.py --group "8-TG0和朋友们的AGI" --output /sdcard/WeChatDigest/
"""
import argparse
import json
import os
import sys
import re
import xml.etree.ElementTree as ET
from datetime import datetime, timezone, timedelta
# Add skill paths
sys.path.insert(0, os.path.expanduser('~/.hermes/skills/research/kimi-api/scripts'))
sys.path.insert(0, os.path.expanduser('~/.hermes/skills/image-generation/scripts'))
from kimi_client import simple_chat
from generate_image import generate_image
def parse_args():
parser = argparse.ArgumentParser(description='Agentic Media Pipeline - 4-Agent Daily Digest')
parser.add_argument('--group', required=True, help='WeChat group name')
parser.add_argument('--output', default='/sdcard/WeChatDigest/', help='Output directory')
parser.add_argument('--date', help='Date (YYYYMMDD), default today')
parser.add_argument('--skip-image', action='store_true', help='Skip image generation')
return parser.parse_args()
def get_today_timestamp():
"""获取今天零点的时间戳(毫秒)"""
beijing = timezone(timedelta(hours=8))
now = datetime.now(beijing)
today_start = now.replace(hour=0, minute=0, second=0, microsecond=0)
return int(today_start.timestamp() * 1000)
def query_wechat_messages(group_name, date_str=None):
"""Agent 1: News Collector - 从微信群收集消息"""
print("\n=== Agent 1: News Collector ===")
# 查询群聊ID
import subprocess
result = subprocess.run([
'sqlite3', os.path.expanduser('~/EnMicroMsg.db'),
'-line',
f"SELECT username, nickname FROM rcontact WHERE username LIKE '%chatroom%' AND nickname LIKE '%{group_name}%';"
], capture_output=True, text=True)
# 解析结果
chatroom_id = None
for line in result.stdout.split('\n'):
if 'username =' in line:
chatroom_id = line.split('=')[1].strip()
if 'nickname =' in line and group_name in line:
break
if not chatroom_id:
print(f"❌ Group '{group_name}' not found")
return []
print(f"✅ Found group: {chatroom_id}")
# 查询今天的消息
today_ts = get_today_timestamp()
result = subprocess.run([
'sqlite3', os.path.expanduser('~/EnMicroMsg.db'),
'-line',
f"SELECT msgId, type, isSend, talker, content, createTime FROM message WHERE talker = '{chatroom_id}' AND createTime >= {today_ts} ORDER BY createTime DESC LIMIT 100;"
], capture_output=True, text=True)
messages = []
current_msg = {}
for line in result.stdout.split('\n'):
line = line.strip()
if not line:
if current_msg:
messages.append(current_msg)
current_msg = {}
continue
if '=' in line:
key, value = line.split('=', 1)
key = key.strip()
value = value.strip()
current_msg[key] = value
if current_msg:
messages.append(current_msg)
print(f"✅ Collected {len(messages)} messages")
return messages
def extract_articles(messages):
"""从消息中提取公众号文章"""
articles = []
discussions = []
for msg in messages:
msg_type = msg.get('type', '0')
content = msg.get('content', '')
if msg_type == '49': # 公众号文章
try:
root = ET.fromstring(content)
title = root.find('.//title')
url = root.find('.//url')
desc = root.find('.//des')
if title is not None and url is not None:
articles.append({
'title': title.text or '',
'url': url.text or '',
'description': desc.text if desc is not None else '',
'source': 'WeChat'
})
except:
pass
elif msg_type == '1': # 文本消息
if content and len(content) > 10:
discussions.append({
'sender': msg.get('talker', 'Unknown'),
'content': content
})
return articles, discussions
def agent_news_editor(articles, discussions):
"""Agent 2: News Editor - 用 Kimi 2.6 编辑内容"""
print("\n=== Agent 2: News Editor (Kimi 2.6) ===")
# 准备输入内容
articles_text = "\n\n".join([
f"标题: {a['title']}\n来源: {a['source']}\n链接: {a['url']}\n描述: {a['description']}"
for a in articles[:20] # 限制数量
])
discussions_text = "\n".join([
f"{d['sender']}: {d['content'][:100]}"
for d in discussions[:50]
])
# Prompt V1: 提取结构化信息
prompt_v1 = f"""你是一名《AI时代日报》的主编。
请阅读以下内容:
【公众号文章】
{articles_text}
【群聊讨论】
{discussions_text}
任务:
从所有内容中提取:
1. 今日最重要的4条新闻
2. 今日最有价值的5条观点
3. 今日最重要的人物
4. 今日最重要的项目
5. 今日最重要的趋势
要求:
不要简单摘要。
要按照科技日报编辑部的方式:
- 去重
- 聚类
- 提炼主题
- 总结行业意义
输出JSON:
{{
"date":"{datetime.now().strftime('%Y-%m-%d')}",
"headline":"一句话总标题",
"hero_story":{{
"title":"主标题",
"summary":"100字摘要"
}},
"news":[
{{
"title":"",
"summary":"",
"source":""
}}
],
"quotes":[
{{
"author":"",
"quote":""
}}
],
"trend":{{
"title":"",
"summary":""
}}
}}"""
# 调用 Kimi 2.6
result = simple_chat(prompt_v1, timeout=120)
# 提取 JSON
try:
json_match = re.search(r'\{.*\}', result, re.DOTALL)
if json_match:
daily_json = json.loads(json_match.group())
else:
daily_json = json.loads(result)
except:
print(f"⚠️ JSON parse failed, using raw text")
daily_json = {
"date": datetime.now().strftime('%Y-%m-%d'),
"headline": "AI行业日报",
"news": [],
"quotes": [],
"trend": {"title": "", "summary": ""}
}
print(f"✅ Generated structured report with {len(daily_json.get('news', []))} news items")
# Prompt V2: 深度编辑
prompt_v2 = f"""你是一名拥有30年经验的科技媒体总编辑。
请根据以下内容:
{json.dumps(daily_json, ensure_ascii=False, indent=2)}
完成以下工作:
1. 找出今天最大的行业主线
2. 生成报纸头版标题
3. 生成副标题
4. 给每条新闻重新命名
5. 给每条新闻写50字导语
6. 提炼5条最有洞察的观点
要求:
风格参考:
- 华尔街日报
- The Economist
- Wired
- MIT Technology Review
输出Markdown格式日报。
"""
markdown_report = simple_chat(prompt_v2, timeout=120)
print(f"✅ Generated Markdown report ({len(markdown_report)} chars)")
return daily_json, markdown_report
def agent_layout_planner(daily_json):
"""Agent 3: Layout Planner - 规划报纸版面"""
print("\n=== Agent 3: Layout Planner ===")
layout = {
"newspaper_name": "TGO和朋友们的AGI",
"headline": daily_json.get("headline", "AI行业日报"),
"hero_image": {
"concept": "server rack shaking hands with printing press"
},
"columns": [],
"quotes": daily_json.get("quotes", [])
}
# 为每条新闻创建版面
for news in daily_json.get("news", []):
layout["columns"].append({
"title": news.get("title", ""),
"content": news.get("summary", "")[:100]
})
print(f"✅ Planned layout with {len(layout['columns'])} columns")
return layout
def agent_gpt_image2(layout, output_path):
"""Agent 4: GPT Image 2 - 生成维多利亚报纸风格信息图"""
print("\n=== Agent 4: GPT Image 2 (Victorian Newspaper) ===")
# 构建提示词
headline = layout["headline"]
columns_text = "\n".join([
f"{i+1}. {col['title']}: {col['content'][:50]}"
for i, col in enumerate(layout["columns"][:6])
])
prompt = f"""Create a front-page Victorian newspaper poster.
Style:
1880 Victorian newspaper
19th century financial times
The Economist cover
engraving illustration
woodcut etching
vintage printing press
old yellow paper
aged newspaper texture
ink engraving
black and white line art
Layout:
large newspaper masthead "AI AGI 日报" on top
main headline: "{headline}"
multiple newspaper columns with Chinese text
{columns_text}
Main Illustration:
server rack shaking hands with printing press
engraving style
US dollar bill engraving
extremely detailed line work
woodcut illustration
banknote etching
centerpiece illustration
Mood:
historical
authoritative
intellectual
industrial revolution
Color:
sepia paper
black ink only
Aspect ratio: 1:1"""
# 生成图片
result = generate_image(prompt, model="GPT Image 2")
if result.get("image_path") and os.path.exists(result["image_path"]):
import shutil
shutil.copy(result["image_path"], output_path)
print(f"✅ Generated Victorian newspaper: {output_path}")
return output_path
else:
print(f"❌ Image generation failed")
return None
def main():
args = parse_args()
# 确保输出目录存在
os.makedirs(args.output, exist_ok=True)
date_str = args.date or datetime.now().strftime('%Y%m%d')
# Agent 1: News Collector
messages = query_wechat_messages(args.group, date_str)
if not messages:
print("❌ No messages found")
return
# 提取文章和讨论
articles, discussions = extract_articles(messages)
print(f"✅ Extracted {len(articles)} articles, {len(discussions)} discussions")
# Agent 2: News Editor
daily_json, markdown_report = agent_news_editor(articles, discussions)
# 保存 Markdown 报告
report_path = os.path.join(args.output, f"report_{date_str}.md")
with open(report_path, 'w', encoding='utf-8') as f:
f.write(markdown_report)
print(f"✅ Saved report: {report_path}")
# 保存 JSON
json_path = os.path.join(args.output, f"report_{date_str}.json")
with open(json_path, 'w', encoding='utf-8') as f:
json.dump(daily_json, f, ensure_ascii=False, indent=2)
print(f"✅ Saved JSON: {json_path}")
# Agent 3: Layout Planner
layout = agent_layout_planner(daily_json)
# 保存 Layout JSON
layout_path = os.path.join(args.output, f"layout_{date_str}.json")
with open(layout_path, 'w', encoding='utf-8') as f:
json.dump(layout, f, ensure_ascii=False, indent=2)
print(f"✅ Saved layout: {layout_path}")
# Agent 4: GPT Image 2
if not args.skip_image:
image_path = os.path.join(args.output, f"infographic_{date_str}.png")
image_result = agent_gpt_image2(layout, image_path)
if image_result:
print(f"\n🎉 Complete! Files generated:")
print(f" - Report: {report_path}")
print(f" - JSON: {json_path}")
print(f" - Layout: {layout_path}")
print(f" - Image: {image_result}")
else:
print(f"\n✅ Pipeline complete (image generation skipped)")
print(f" - Report: {report_path}")
print(f" - JSON: {json_path}")
print(f" - Layout: {layout_path}")
if __name__ == '__main__':
main()