newspaper_infographic_v5.py 14.6 KB
#!/usr/bin/env python3
"""newspaper_infographic_v5.py - 基于 Kimi 设计的专业信息图生成器

Features:
- 基于 Kimi 设计的专业提示词
- 丰富的配色方案(每个板块独立主题色)
- 清晰的视觉层次
- 高信息密度
- 装饰性元素(边框、分隔线、图标)

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

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


# === 配色方案(基于 Kimi 设计) ===
COLORS = {
    'bg': "#f5f0e1",           # 米黄色背景
    'bg_dark': "#e8e0d0",      # 深色背景
    'text': "#2c2c2c",         # 主文字
    'text_light': "#5a5a5a",   # 次要文字
    'text_white': "#ffffff",   # 白色文字
    'accent': "#c9a84c",       # 金色强调
    'accent2': "#8b4513",      # 棕色强调
    'border': "#d4c4a8",       # 边框色
    'card_bg': "#faf8f3",      # 卡片背景
    'shadow': "#e0d8c8",       # 阴影色
}

# 板块主题色(基于 Kimi 设计)
CATEGORY_THEMES = {
    "AI Agent": {
        "bg": "#e3f2fd", "accent": "#1565C0", "icon": "🤖", "dark": "#0D47A1",
        "gradient": ["#1976D2", "#1565C0"]
    },
    "大模型": {
        "bg": "#f3e5f5", "accent": "#7B1FA2", "icon": "🧠", "dark": "#4A148C",
        "gradient": ["#9C27B0", "#7B1FA2"]
    },
    "AI硬件": {
        "bg": "#e8f5e9", "accent": "#388E3C", "icon": "🔧", "dark": "#1B5E20",
        "gradient": ["#4CAF50", "#388E3C"]
    },
    "行业动态": {
        "bg": "#fff3e0", "accent": "#F57C00", "icon": "📊", "dark": "#E65100",
        "gradient": ["#FF9800", "#F57C00"]
    },
    "开源项目": {
        "bg": "#ffebee", "accent": "#D32F2F", "icon": "📦", "dark": "#B71C1C",
        "gradient": ["#F44336", "#D32F2F"]
    },
    "讨论精选": {
        "bg": "#f5f5f5", "accent": "#616161", "icon": "💬", "dark": "#424242",
        "gradient": ["#9E9E9E", "#616161"]
    },
}


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, 8),
                    'small': ImageFont.truetype(path, 10),
                    'regular': ImageFont.truetype(path, 12),
                    'medium': ImageFont.truetype(path, 14),
                    'large': ImageFont.truetype(path, 16),
                    'xlarge': ImageFont.truetype(path, 20),
                    'title': ImageFont.truetype(path, 28),
                    'headline': ImageFont.truetype(path, 38),
                }
            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=16):
    """绘制自动换行的文本"""
    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': datetime.now().strftime('%Y年%m月%d日'),
        'edition': '第1版',
        'headline': '',
        'articles': [],
        'discussions': [],
        'stats': {
            'articles': 0,
            'discussions': 0,
            'fields': 0,
            'members': 0
        }
    }
    
    lines = report_text.split('\n')
    i = 0
    current_category = None
    
    while i < len(lines):
        line = lines[i].strip()
        
        # 检测头条
        if '今日最大话题' in line:
            if i + 1 < len(lines):
                data['headline'] = lines[i + 1].strip()
        
        # 检测文章
        if line.startswith('### ') and not line.startswith('### 话题') and not '最大话题' in line:
            title = line[4:].strip()
            source = ""
            summary = ""
            
            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('### ') or next_line.startswith('## '):
                    break
                j += 1
            
            data['articles'].append({
                'title': title,
                'source': source,
                'summary': summary,
                'category': current_category or '其他'
            })
            data['stats']['articles'] += 1
        
        # 检测讨论话题
        if line.startswith('### 话题') or ('话题' in line and '参与者' in line):
            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
            })
            data['stats']['discussions'] += 1
        
        i += 1
    
    # 计算领域数和成员数
    data['stats']['fields'] = len(set(a.get('category', '其他') for a in data['articles']))
    data['stats']['members'] = len(set(
        s for disc in data['discussions'] 
        for s in disc.get('participants', '').split(', ') 
        if s
    ))
    
    return data


def create_infographic_v5(report_text, output_path, group_name="8-TG0和朋友们的AGI"):
    """创建信息图 v5 - 基于 Kimi 设计"""
    
    WIDTH = 900
    MARGIN = 20
    
    fonts = load_fonts()
    data = parse_full_report(report_text)
    
    # 计算高度
    total_height = 180  # 标题区域
    total_height += 50   # 统计栏
    total_height += 40   # 头条
    
    # 文章区域(双栏)
    articles_per_col = (len(data['articles']) + 1) // 2
    total_height += articles_per_col * 70  # 每篇文章约70px
    
    # 讨论区域
    total_height += len(data['discussions']) * 55
    
    total_height += 50   # 页脚
    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, 4], fill=COLORS['accent'])
    y += 8
    
    # === 报头(Kimi 设计:大标题 + 副标题) ===
    draw.rectangle([MARGIN, y, WIDTH-MARGIN, y+130], fill=COLORS['bg_dark'], outline=COLORS['border'])
    
    # 报纸名称(大号字体)
    draw.text((WIDTH//2, y+30), data['title'], fill=COLORS['accent2'], font=fonts['headline'], anchor="mm")
    
    # 装饰线
    draw.line([(MARGIN+80, y+55), (WIDTH-MARGIN-80, y+55)], fill=COLORS['accent'], width=2)
    
    # 副标题(群名 + 日期 + 版次)
    subtitle = f"{data['group']}  |  {data['date']}  |  {data['edition']}"
    draw.text((WIDTH//2, y+75), subtitle, fill=COLORS['text_light'], font=fonts['medium'], anchor="mm")
    
    # 装饰边框(维多利亚风格)
    draw.rectangle([MARGIN+5, y+5, WIDTH-MARGIN-5, y+125], outline=COLORS['accent'], width=1)
    
    y += 140
    
    # === 统计栏(Kimi 设计:图标 + 数字) ===
    stats = [
        ("📰", str(data['stats']['articles']), "文章数"),
        ("💬", str(data['stats']['discussions']), "讨论数"),
        ("🏷️", str(data['stats']['fields']), "领域数"),
        ("👥", str(data['stats']['members']), "活跃人数"),
    ]
    
    stats_width = (WIDTH - 2*MARGIN) // len(stats)
    draw.rectangle([MARGIN, y, WIDTH-MARGIN, y+45], fill=COLORS['card_bg'], outline=COLORS['border'])
    
    for i, (icon, num, label) in enumerate(stats):
        x = MARGIN + i * stats_width + stats_width//2
        # 数字(大号)
        draw.text((x, y+10), num, fill=COLORS['accent2'], font=fonts['xlarge'], anchor="mm")
        # 标签
        draw.text((x, y+32), label, fill=COLORS['text_light'], font=fonts['tiny'], anchor="mm")
    
    y += 55
    
    # === 头条(Kimi 设计:高亮区域) ===
    if data['headline']:
        headline_text = f"🔥 今日热点: {data['headline'][:80]}"
        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
    
    # === 文章列表(Kimi 设计:分板块 + 独立配色) ===
    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
        
        # 获取板块主题色
        category = article.get('category', '其他')
        theme = CATEGORY_THEMES.get(category, CATEGORY_THEMES['讨论精选'])
        
        # 文章卡片(带左侧色条)
        card_height = 65
        draw.rectangle([x, current_y, x+col_width, current_y+card_height], 
                      fill=COLORS['card_bg'], outline=COLORS['border'])
        
        # 左侧色条(渐变效果)
        draw.rectangle([x, current_y, x+5, current_y+card_height], fill=theme['accent'])
        
        # 序号
        draw.text((x+10, current_y+3), f"{i+1}.", fill=theme['accent'], font=fonts['small'])
        
        # 标题
        title = article['title'][:22] + "..." if len(article['title']) > 22 else article['title']
        draw.text((x+25, current_y+3), title, fill=COLORS['text'], font=fonts['regular'])
        
        # 摘要
        if article['summary']:
            summary = article['summary'][:35] + "..." if len(article['summary']) > 35 else article['summary']
            draw.text((x+10, current_y+20), summary, fill=COLORS['text_light'], font=fonts['tiny'])
        
        # 来源标签
        if article['source']:
            source_text = article['source'][:12]
            draw.rectangle([x+10, current_y+38, x+80, current_y+52], fill=theme['bg'])
            draw.text((x+12, current_y+45), f"来源: {source_text}", fill=theme['dark'], font=fonts['tiny'], anchor="lm")
        
        # 关键词标签
        if category:
            draw.rectangle([x+85, current_y+38, x+140, current_y+52], fill=theme['bg'])
            draw.text((x+88, current_y+45), f"{theme['icon']} {category}", fill=theme['dark'], 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
    
    # === 讨论精选(Kimi 设计:对话气泡风格) ===
    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][:45] + "..." if len(disc['views'][0]) > 45 else disc['views'][0]
                draw.text((MARGIN+10, y+36), f"💡 {view}", fill=COLORS['text_light'], font=fonts['tiny'])
            
            y += disc_height + 5
    
    # === 页脚(Kimi 设计:生成时间 + 数据来源) ===
    y += 10
    draw.rectangle([MARGIN, y, WIDTH-MARGIN, y+35], fill=COLORS['bg_dark'], outline=COLORS['border'])
    footer_text = f"🤖 Generated at {datetime.now().strftime('%H:%M')}  |  Data Source: {data['group']}  |  AI AGI Daily"
    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+4], fill=COLORS['accent'])
    
    # 保存
    img.save(output_path, quality=95)
    print(f"Infographic v5 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 v5 based on Kimi design')
    parser.add_argument('--report', required=True, help='Path to full report markdown file')
    parser.add_argument('--output', default='/sdcard/WeChatDigest/infographic_v5.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_v5(report_text, args.output, args.group)


if __name__ == '__main__':
    main()