newspaper_infographic_v4.py 12.7 KB
#!/usr/bin/env python3
"""newspaper_infographic_v4.py - 基于完整报告的信息图生成器

Features:
- 基于完整报告内容生成
- 每篇文章有标题+摘要+来源
- 群聊讨论有话题+观点
- 丰富的配色和图标
- 高信息密度

Usage:
    python3 newspaper_infographic_v4.py --report report.md --output infographic.png
"""

import argparse
import os
import re
from datetime import datetime
from PIL import Image, ImageDraw, ImageFont


# 配色方案
COLORS = {
    'bg': "#faf8f3",
    'bg_dark': "#f0ebe3",
    'text': "#2c2c2c",
    'text_light': "#5a5a5a",
    'text_white': "#ffffff",
    'accent': "#c9a84c",
    'accent2': "#8b4513",
    'border': "#d4c4a8",
    'card_bg': "#ffffff",
}

# 板块配色
CATEGORY_THEMES = {
    "AI Agent": {"bg": "#e3f2fd", "accent": "#1976D2", "icon": "🤖", "dark": "#1565C0"},
    "大模型": {"bg": "#f3e5f5", "accent": "#7B1FA2", "icon": "🧠", "dark": "#6A1B9A"},
    "AI硬件": {"bg": "#e8f5e9", "accent": "#388E3C", "icon": "🔧", "dark": "#2E7D32"},
    "行业动态": {"bg": "#fff3e0", "accent": "#F57C00", "icon": "📊", "dark": "#EF6C00"},
    "开源项目": {"bg": "#ffebee", "accent": "#D32F2F", "icon": "📦", "dark": "#C62828"},
    "讨论精选": {"bg": "#f5f5f5", "accent": "#616161", "icon": "💬", "dark": "#424242"},
}


def load_fonts():
    """加载字体"""
    font_paths = [
        "/data/data/com.termux/files/usr/share/fonts/truetype/noto/NotoSansCJK-Regular.ttc",
        "/system/fonts/NotoSansCJK-Regular.ttc",
        "/data/data/com.termux/files/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
    ]
    
    for path in font_paths:
        if os.path.exists(path):
            try:
                return {
                    'tiny': ImageFont.truetype(path, 9),
                    'small': ImageFont.truetype(path, 11),
                    'regular': ImageFont.truetype(path, 13),
                    'medium': ImageFont.truetype(path, 15),
                    'large': ImageFont.truetype(path, 18),
                    'xlarge': ImageFont.truetype(path, 24),
                    'title': ImageFont.truetype(path, 32),
                    'headline': ImageFont.truetype(path, 42),
                }
            except:
                continue
    
    default = ImageFont.load_default()
    return {k: default for k in ['tiny', 'small', 'regular', 'medium', 'large', 'xlarge', 'title', 'headline']}


def draw_text_wrapped(draw, text, x, y, max_width, font, fill, line_height=18):
    """绘制自动换行的文本"""
    lines = []
    current_line = ""
    
    for char in text:
        test_line = current_line + char
        bbox = draw.textbbox((0, 0), test_line, font=font)
        if bbox[2] - bbox[0] > max_width and current_line:
            lines.append(current_line)
            current_line = char
        else:
            current_line = test_line
    
    if current_line:
        lines.append(current_line)
    
    for i, line in enumerate(lines):
        draw.text((x, y + i * line_height), line, fill=fill, font=font)
    
    return y + len(lines) * line_height


def parse_full_report(report_text):
    """解析完整报告,提取结构化数据"""
    data = {
        'title': 'AI AGI 日报',
        'group': '8-TG0和朋友们的AGI',
        'date': '2026年6月23日',
        'edition': '第1版',
        'headline': '',
        'articles': [],
        'discussions': [],
        'stats': {}
    }
    
    lines = report_text.split('\n')
    i = 0
    current_category = None
    
    while i < len(lines):
        line = lines[i].strip()
        
        # 检测头条
        if line.startswith('### 🔥') or line.startswith('### 今日最大话题'):
            if i + 1 < len(lines):
                data['headline'] = lines[i + 1].strip()
        
        # 检测文章板块
        if line.startswith('### ') and '文章' in line:
            current_category = None
        
        # 检测文章
        article_match = re.match(r'###\s+(\d+)\.\s+(.+)', line)
        if article_match:
            title = article_match.group(2)
            source = ""
            summary = ""
            keywords = ""
            
            # 读取后续行
            j = i + 1
            while j < len(lines) and j < i + 10:
                next_line = lines[j].strip()
                if next_line.startswith('**来源**'):
                    source = next_line.replace('**来源**:', '').strip()
                elif next_line.startswith('**摘要**'):
                    summary = next_line.replace('**摘要**:', '').strip()
                elif next_line.startswith('**关键信息**'):
                    keywords = next_line.replace('**关键信息**:', '').strip()
                elif next_line.startswith('### ') or next_line.startswith('## '):
                    break
                j += 1
            
            data['articles'].append({
                'title': title,
                'source': source,
                'summary': summary,
                'keywords': keywords,
                'category': current_category or '其他'
            })
        
        # 检测讨论话题
        if line.startswith('### 话题') or line.startswith('### 话题'):
            topic = line.replace('### ', '').strip()
            participants = ""
            views = []
            
            j = i + 1
            while j < len(lines) and j < i + 15:
                next_line = lines[j].strip()
                if next_line.startswith('**参与者**'):
                    participants = next_line.replace('**参与者**:', '').strip()
                elif next_line.startswith('- ') or next_line.startswith('• '):
                    views.append(next_line[2:])
                elif next_line.startswith('### ') or next_line.startswith('## '):
                    break
                j += 1
            
            data['discussions'].append({
                'topic': topic,
                'participants': participants,
                'views': views
            })
        
        # 检测统计
        if line.startswith('|') and '公众号文章' in line:
            parts = line.split('|')
            if len(parts) >= 3:
                data['stats']['articles'] = parts[2].strip()
        
        i += 1
    
    return data


def create_infographic_v4(report_text, output_path, group_name="8-TG0和朋友们的AGI"):
    """创建信息图 v4 - 基于完整报告"""
    
    WIDTH = 900
    MARGIN = 20
    
    fonts = load_fonts()
    data = parse_full_report(report_text)
    
    # 计算高度
    total_height = 160  # 标题
    total_height += 50   # 统计栏
    total_height += 40   # 头条
    
    # 文章区域
    articles_per_col = (len(data['articles']) + 1) // 2
    total_height += articles_per_col * 80  # 每篇文章约80px
    
    # 讨论区域
    total_height += len(data['discussions']) * 60
    
    total_height += 50   # 页脚
    total_height = max(total_height, 1200)
    
    # 创建画布
    img = Image.new('RGB', (WIDTH, total_height), COLORS['bg'])
    draw = ImageDraw.Draw(img)
    
    y = 0
    
    # === 顶部装饰条 ===
    draw.rectangle([0, 0, WIDTH, 5], fill=COLORS['accent'])
    y += 10
    
    # === 报头 ===
    draw.rectangle([MARGIN, y, WIDTH-MARGIN, y+120], fill=COLORS['bg_dark'], outline=COLORS['border'])
    
    # 报纸名称
    draw.text((WIDTH//2, y+35), data['title'], fill=COLORS['accent2'], font=fonts['headline'], anchor="mm")
    
    # 装饰线
    draw.line([(MARGIN+50, y+65), (WIDTH-MARGIN-50, y+65)], fill=COLORS['accent'], width=2)
    
    # 副标题
    subtitle = f"{data['group']}  |  {data['date']}  |  {data['edition']}"
    draw.text((WIDTH//2, y+90), subtitle, fill=COLORS['text_light'], font=fonts['medium'], anchor="mm")
    
    y += 135
    
    # === 统计栏 ===
    stats_text = f"📰 {len(data['articles'])}篇文章  |  💬 {len(data['discussions'])}个话题  |  🔥 6个领域"
    draw.rectangle([MARGIN, y, WIDTH-MARGIN, y+40], fill=COLORS['card_bg'], outline=COLORS['border'])
    draw.text((WIDTH//2, y+20), stats_text, fill=COLORS['text'], font=fonts['medium'], anchor="mm")
    
    y += 55
    
    # === 头条 ===
    if data['headline']:
        headline_text = f"🔥 今日热点: {data['headline'][:60]}"
        draw.rectangle([MARGIN, y, WIDTH-MARGIN, y+35], fill="#fff8e1", outline=COLORS['accent'])
        draw.text((MARGIN+10, y+17), headline_text, fill=COLORS['accent2'], font=fonts['medium'], anchor="lm")
        y += 45
    
    # === 文章列表(双栏) ===
    col_width = (WIDTH - 2*MARGIN - 10) // 2
    left_x = MARGIN
    right_x = MARGIN + col_width + 10
    
    left_y = y
    right_y = y
    
    for i, article in enumerate(data['articles'][:12]):
        x = left_x if i % 2 == 0 else right_x
        current_y = left_y if i % 2 == 0 else right_y
        
        # 文章卡片背景
        card_height = 75
        draw.rectangle([x, current_y, x+col_width, current_y+card_height], 
                      fill=COLORS['card_bg'], outline=COLORS['border'])
        
        # 序号
        draw.text((x+5, current_y+5), f"{i+1}.", fill=COLORS['accent'], font=fonts['small'])
        
        # 标题
        title = article['title'][:25] + "..." if len(article['title']) > 25 else article['title']
        draw.text((x+20, current_y+5), title, fill=COLORS['text'], font=fonts['regular'])
        
        # 摘要
        if article['summary']:
            summary = article['summary'][:40] + "..." if len(article['summary']) > 40 else article['summary']
            draw.text((x+5, current_y+25), summary, fill=COLORS['text_light'], font=fonts['tiny'])
        
        # 来源
        if article['source']:
            draw.text((x+5, current_y+45), f"来源: {article['source'][:15]}", fill=COLORS['accent'], font=fonts['tiny'])
        
        # 关键词标签
        if article['keywords']:
            keywords = article['keywords'][:20]
            draw.rectangle([x+5, current_y+58, x+80, current_y+72], fill=COLORS['bg_dark'])
            draw.text((x+8, current_y+65), keywords, fill=COLORS['text_light'], font=fonts['tiny'], anchor="lm")
        
        if i % 2 == 0:
            left_y += card_height + 5
        else:
            right_y += card_height + 5
    
    y = max(left_y, right_y) + 15
    
    # === 讨论精选 ===
    if data['discussions']:
        draw.rectangle([MARGIN, y, WIDTH-MARGIN, y+30], fill="#f5f5f5", outline=COLORS['border'])
        draw.text((MARGIN+10, y+15), "💬 群聊讨论精选", fill=COLORS['text'], font=fonts['large'], anchor="lm")
        y += 35
        
        for disc in data['discussions'][:4]:
            # 讨论卡片
            disc_height = 50
            draw.rectangle([MARGIN, y, WIDTH-MARGIN, y+disc_height], fill=COLORS['card_bg'], outline=COLORS['border'])
            
            # 话题
            topic = disc['topic'][:40] + "..." if len(disc['topic']) > 40 else disc['topic']
            draw.text((MARGIN+10, y+5), f"• {topic}", fill=COLORS['text'], font=fonts['regular'])
            
            # 参与者
            if disc['participants']:
                draw.text((MARGIN+10, y+22), f"👥 {disc['participants'][:30]}", fill=COLORS['text_light'], font=fonts['tiny'])
            
            # 观点
            if disc['views']:
                view = disc['views'][0][:50] + "..." if len(disc['views'][0]) > 50 else disc['views'][0]
                draw.text((MARGIN+10, y+36), f"💡 {view}", fill=COLORS['text_light'], font=fonts['tiny'])
            
            y += disc_height + 5
    
    # === 页脚 ===
    y += 10
    draw.rectangle([MARGIN, y, WIDTH-MARGIN, y+35], fill=COLORS['bg_dark'], outline=COLORS['border'])
    footer_text = f"🤖 由 AI 智能体生成  |  {datetime.now().strftime('%H:%M')}  |  {data['group']}"
    draw.text((WIDTH//2, y+17), footer_text, fill=COLORS['text_light'], font=fonts['small'], anchor="mm")
    
    # 底部装饰条
    y += 40
    draw.rectangle([0, y, WIDTH, y+5], fill=COLORS['accent'])
    
    # 保存
    img.save(output_path, quality=95)
    print(f"Infographic v4 saved: {output_path}")
    print(f"Size: {WIDTH}x{y+10}")
    print(f"Articles: {len(data['articles'])}, Discussions: {len(data['discussions'])}")
    return output_path


def main():
    parser = argparse.ArgumentParser(description='Generate infographic v4 from full report')
    parser.add_argument('--report', required=True, help='Path to full report markdown file')
    parser.add_argument('--output', default='/sdcard/WeChatDigest/infographic_v4.png', 
                        help='Output image path')
    parser.add_argument('--group', default='8-TG0和朋友们的AGI', help='Group name')
    args = parser.parse_args()
    
    with open(args.report, 'r', encoding='utf-8') as f:
        report_text = f.read()
    
    create_infographic_v4(report_text, args.output, args.group)


if __name__ == '__main__':
    main()