#!/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()