generate_infographic_v3.py 10.4 KB
#!/usr/bin/env python3
"""generate_infographic_v3.py - 精美信息图生成器 v3 (Daily Digest专用)

Features:
- 卡片式布局,每个板块独立卡片
- 丰富的配色方案(渐变色块)
- 数据可视化元素(统计数字、进度条、标签)
- 图标系统(emoji + 色块组合)
- 更好的视觉层次
- 配图区域(用渐变色块+图标代替真实图片)

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

import argparse
import os
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",      # 卡片背景
    'shadow': "#e8e0d5",       # 阴影色
}

# 板块配色(每个板块有主题色)
CATEGORY_THEMES = {
    "AI Agent": {"bg": "#e8f4f8", "accent": "#2196F3", "icon": "🤖"},
    "大模型": {"bg": "#f0e8f8", "accent": "#9C27B0", "icon": "🧠"},
    "AI硬件": {"bg": "#e8f8e8", "accent": "#4CAF50", "icon": "🔧"},
    "行业动态": {"bg": "#fff8e8", "accent": "#FF9800", "icon": "📊"},
    "开源项目": {"bg": "#f8e8e8", "accent": "#F44336", "icon": "📦"},
    "群聊讨论": {"bg": "#e8e8f8", "accent": "#3F51B5", "icon": "💬"},
    "其他": {"bg": "#f0f0f0", "accent": "#607D8B", "icon": "📌"},
}


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, 10),
                    'small': ImageFont.truetype(path, 12),
                    'regular': ImageFont.truetype(path, 14),
                    'medium': ImageFont.truetype(path, 16),
                    'large': ImageFont.truetype(path, 20),
                    'xlarge': ImageFont.truetype(path, 28),
                    'title': ImageFont.truetype(path, 36),
                    'headline': ImageFont.truetype(path, 48),
                }
            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=20):
    """自动换行文本"""
    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_report(report_text):
    """解析报告"""
    sections = []
    current_section = None
    current_articles = []
    
    lines = report_text.split('\n')
    i = 0
    while i < len(lines):
        line = lines[i].strip()
        
        if line.startswith('### '):
            if current_section and current_articles:
                sections.append({'category': current_section, 'articles': current_articles})
            current_section = line[4:]
            current_articles = []
        elif line.startswith('- **'):
            title = line.split('**')[1] if '**' in line else line
            desc = ""
            if i + 1 < len(lines):
                next_line = lines[i + 1].strip()
                if next_line.startswith('  ') or next_line.startswith('\t') or next_line.startswith('('):
                    desc = next_line.strip('()').strip()
                    i += 1
            current_articles.append({'title': title, 'desc': desc})
        
        i += 1
    
    if current_section and current_articles:
        sections.append({'category': current_section, 'articles': current_articles})
    
    return sections


def create_infographic_v3(report_text, output_path, group_name="8-TG0和朋友们的AGI"):
    """创建精美信息图 v3"""
    
    WIDTH = 800
    MARGIN = 25
    CARD_MARGIN = 15
    
    fonts = load_fonts()
    sections = parse_report(report_text)
    
    # 计算高度
    total_height = 180  # 头部区域
    total_height += 80   # 统计栏
    
    for section in sections:
        total_height += 55  # 板块标题
        for article in section['articles']:
            total_height += 28  # 标题
            if article['desc']:
                total_height += 40  # 描述
            total_height += 12  # 间距
        total_height += 20  # 板块间距
    
    total_height += 60  # 页脚
    total_height = max(total_height, 1000)
    
    # 创建画布
    img = Image.new('RGB', (WIDTH, total_height), COLORS['bg'])
    draw = ImageDraw.Draw(img)
    
    y = 0
    
    # === 顶部装饰条 ===
    draw.rectangle([0, 0, WIDTH, 6], fill=COLORS['accent'])
    y += 15
    
    # === 报头 ===
    # 背景装饰
    draw.rectangle([MARGIN, y, WIDTH-MARGIN, y+120], fill=COLORS['bg_dark'], outline=COLORS['border'])
    
    # 报纸名称
    draw.text((WIDTH//2, y+35), "AI AGI 日报", fill=COLORS['accent2'], font=fonts['headline'], anchor="mm")
    
    # 装饰线
    draw.line([(MARGIN+50, y+65), (WIDTH-MARGIN-50, y+65)], fill=COLORS['accent'], width=2)
    
    # 日期、群名、版次
    date_str = datetime.now().strftime("%Y年%m月%d日")
    info_text = f"{group_name}  |  {date_str}  |  第1版"
    draw.text((WIDTH//2, y+90), info_text, fill=COLORS['text_light'], font=fonts['medium'], anchor="mm")
    
    y += 135
    
    # === 统计栏 ===
    total_articles = sum(len(s['articles']) for s in sections)
    
    # 统计卡片背景
    draw.rectangle([MARGIN, y, WIDTH-MARGIN, y+65], fill=COLORS['card_bg'], outline=COLORS['border'])
    
    # 统计项
    stats = [
        ("📰", str(total_articles), "篇文章"),
        ("🏷️", str(len(sections)), "个板块"),
        ("💬", "8", "条讨论"),
        ("👥", "12", "位成员"),
    ]
    
    stat_width = (WIDTH - 2*MARGIN) // len(stats)
    for i, (icon, num, label) in enumerate(stats):
        x = MARGIN + i * stat_width + stat_width//2
        # 数字
        draw.text((x, y+20), num, fill=COLORS['accent2'], font=fonts['xlarge'], anchor="mm")
        # 标签
        draw.text((x, y+45), label, fill=COLORS['text_light'], font=fonts['small'], anchor="mm")
    
    y += 80
    
    # === 板块内容 ===
    for section_idx, section in enumerate(sections):
        category = section['category']
        articles = section['articles']
        theme = CATEGORY_THEMES.get(category, CATEGORY_THEMES['其他'])
        
        # 板块卡片背景
        card_y = y
        card_height = 50 + len(articles) * 70
        draw.rectangle([MARGIN, card_y, WIDTH-MARGIN, card_y+card_height], 
                      fill=COLORS['card_bg'], outline=COLORS['border'])
        
        # 左侧色条
        draw.rectangle([MARGIN, card_y, MARGIN+6, card_y+card_height], fill=theme['accent'])
        
        # 板块标题区域
        title_y = card_y + 12
        
        # 图标背景
        draw.ellipse([MARGIN+15, title_y, MARGIN+45, title_y+30], fill=theme['accent'])
        # 图标文字(用emoji)
        draw.text((MARGIN+30, title_y+15), theme['icon'], font=fonts['medium'], anchor="mm")
        
        # 板块名称
        draw.text((MARGIN+55, title_y+15), f"{category}", fill=COLORS['text'], font=fonts['large'], anchor="lm")
        
        # 文章数量标签
        count_text = f"{len(articles)}篇"
        draw.rectangle([WIDTH-MARGIN-60, title_y, WIDTH-MARGIN-10, title_y+25], 
                      fill=theme['bg'], outline=theme['accent'])
        draw.text((WIDTH-MARGIN-35, title_y+12), count_text, fill=theme['accent'], 
                 font=fonts['small'], anchor="mm")
        
        y = card_y + 50
        
        # 文章列表
        for article in articles:
            title = article['title']
            desc = article['desc']
            
            # 文章标题
            draw.text((MARGIN+20, y), f"• {title}", fill=COLORS['text'], font=fonts['medium'])
            y += 22
            
            # 描述
            if desc:
                desc_text = desc[:60] + "..." if len(desc) > 60 else desc
                y = draw_text_wrapped(draw, desc_text, MARGIN+35, y, 
                                    WIDTH - 2*MARGIN - 50, 
                                    fonts['small'], COLORS['text_light'], line_height=16)
                y += 8
            
            y += 5
        
        y += 25
    
    # === 页脚 ===
    y += 10
    draw.rectangle([MARGIN, y, WIDTH-MARGIN, y+40], fill=COLORS['bg_dark'], outline=COLORS['border'])
    footer_text = f"🤖 由 AI 智能体生成  |  {datetime.now().strftime('%H:%M')}  |  数据来源:{group_name}"
    draw.text((WIDTH//2, y+20), footer_text, fill=COLORS['text_light'], font=fonts['small'], anchor="mm")
    
    # 底部装饰条
    y += 45
    draw.rectangle([0, y, WIDTH, y+6], fill=COLORS['accent'])
    
    # 保存
    img.save(output_path, quality=95)
    print(f"Infographic v3 saved: {output_path}")
    print(f"Size: {WIDTH}x{y+10}, Sections: {len(sections)}, Articles: {total_articles}")
    return output_path


def main():
    parser = argparse.ArgumentParser(description='Generate beautiful infographic v3')
    parser.add_argument('--report', required=True, help='Path to report markdown file')
    parser.add_argument('--output', default='/sdcard/WeChatDigest/infographic_v3.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_v3(report_text, args.output, args.group)


if __name__ == '__main__':
    main()