generate_infographic_v3.py
10.4 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
#!/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()