fix(pdf): 优化 PDF 模板生成情况

This commit is contained in:
SXP-Simon
2026-03-25 16:09:54 +08:00
parent 58615d2752
commit 72ead04182
12 changed files with 811 additions and 716 deletions
+7
View File
@@ -21,3 +21,10 @@ debug_simple.html
debug_spring_festival.html debug_spring_festival.html
debug_spring.html debug_spring.html
data/debug_data/avatar/cache.db data/debug_data/avatar/cache.db
scripts/output_all/debug_format_test_group_*.pdf
scripts/output_all/debug_hack_test_group_*.pdf
scripts/output_all/debug_retro_futurism_test_group_*.pdf
scripts/output_all/debug_scrapbook_test_group_*.pdf
scripts/output_all/debug_simple_test_group_*.pdf
scripts/output_all/debug_spring_festival_test_group_*.pdf
scripts/data/avatar/cache.db
+235
View File
@@ -0,0 +1,235 @@
import asyncio
import os
import sys
import types
from pathlib import Path
# ==========================================
# 1. Environment Setup
# ==========================================
current_dir = os.path.dirname(os.path.abspath(__file__))
plugin_root = os.path.abspath(os.path.join(current_dir, ".."))
sys.path.insert(0, plugin_root)
# Mock astrbot.api
astrbot_api = types.ModuleType("astrbot.api")
class MockLogger:
def info(self, msg, *args, **kwargs):
print(f"[INFO] {msg}")
def error(self, msg, *args, **kwargs):
print(f"[ERROR] {msg}")
def warning(self, msg, *args, **kwargs):
print(f"[WARN] {msg}")
def debug(self, msg, *args, **kwargs):
print(f"[DEBUG] {msg}")
def log(self, level, msg, *args, **kwargs):
print(f"[LOG {level}] {msg}")
def isEnabledFor(self, level):
return True
astrbot_api.logger = MockLogger()
astrbot_api.AstrBotConfig = dict
sys.modules["astrbot.api"] = astrbot_api
# Mock astrbot.core.utils.astrbot_path
astrbot_core_utils = types.ModuleType("astrbot.core.utils")
astrbot_path = types.ModuleType("astrbot.core.utils.astrbot_path")
astrbot_path.get_astrbot_data_path = lambda: Path(".")
sys.modules["astrbot.core.utils"] = astrbot_core_utils
sys.modules["astrbot.core.utils.astrbot_path"] = astrbot_path
# Now import plugin modules
from src.domain.entities.analysis_result import ( # noqa: E402
ActivityVisualization,
EmojiStatistics,
GoldenQuote,
GroupStatistics,
SummaryTopic,
TokenUsage,
UserTitle,
)
from src.infrastructure.reporting.generators import ReportGenerator # noqa: E402
# ==========================================
# 2. Mocks
# ==========================================
class MockConfigManager:
def __init__(self, theme="scrapbook"):
self.theme = theme
def get_pdf_output_dir(self):
return os.path.join(current_dir, "output_all")
def get_pdf_filename_format(self):
return f"debug_{self.theme}_{{group_id}}_{{date}}.pdf"
def get_max_topics(self):
return 5
def get_max_user_titles(self):
return 8
def get_max_golden_quotes(self):
return 5
def get_report_template(self):
return self.theme
def get_enable_user_card(self):
return True
def get_t2i_max_concurrent(self):
return 2
@property
def playwright_available(self):
return True
def get_browser_path(self):
return ""
async def mock_get_user_avatar(avatar_id: str, avatar_url_getter=None) -> str:
return f"https://q4.qlogo.cn/headimg_dl?dst_uin={avatar_id}&spec=640"
# ==========================================
# 3. Main Execution
# ==========================================
async def generate_theme(theme_name):
print(f"\n>>> Generating PDF for theme: {theme_name}")
config_manager = MockConfigManager(theme_name)
data_dir = Path(current_dir) / "data"
generator = ReportGenerator(config_manager, data_dir)
generator._get_user_avatar = mock_get_user_avatar
stats = GroupStatistics(
message_count=1280,
total_characters=8500,
participant_count=42,
most_active_period="20:00-22:00",
emoji_count=156,
emoji_statistics=EmojiStatistics(face_count=100, mface_count=56),
activity_visualization=ActivityVisualization(
hourly_activity={i: (i * 5) % 65 for i in range(24)},
daily_activity={"2026-03-25": 1280},
),
)
topics = [
SummaryTopic(
topic="AstrBot新功能",
detail="大家对PDF生成功能的讨论非常热烈。",
contributors=["开发者", "测试员"],
),
SummaryTopic(
topic="代码调试",
detail="关于Python异步编程的深入探讨。",
contributors=["大神"],
),
SummaryTopic(
topic="周三摸鱼",
detail="今天群里大家都在发表情包。",
contributors=["全体群友"],
),
]
user_titles = [
UserTitle(
name="Simon",
user_id="10001",
title="极客之魂",
mbti="INTJ",
reason="完成了所有PDF模板的优化。",
),
UserTitle(
name="Bot",
user_id="10002",
title="全能助手",
mbti="ENFJ",
reason="一直在努力工作。",
),
]
stats.golden_quotes = [
GoldenQuote(
sender="Simon",
content="这PDF现在看起来高端多了!",
reason="这是真的。",
user_id="10001",
),
GoldenQuote(
sender="User",
content="能不能不分页?",
reason="用户反馈。",
user_id="10002",
),
]
stats.token_usage = TokenUsage(
prompt_tokens=2500, completion_tokens=1500, total_tokens=4000
)
class MockDimension:
def __init__(self, name, percentage, comment, color):
self.name, self.percentage, self.comment, self.color = (
name,
percentage,
comment,
color,
)
class MockChatQualityReview:
def __init__(self):
self.title = "今日群聊质量分析"
self.subtitle = "基于AI的深度神经网络评估"
self.dimensions = [
MockDimension("讨论活跃度", 95, "大家讨论非常热烈", "#FF5722"),
MockDimension("情感温度", 88, "群内氛围融洽", "#E91E63"),
]
self.summary = "整体聊天的质量很高,技术讨论和日常闲聊达到了完美的平衡。"
analysis_result = {
"statistics": stats,
"topics": topics,
"user_titles": user_titles,
"chat_quality_review": MockChatQualityReview(),
"user_analysis": {"10001": {"nickname": "Simon"}, "10002": {"nickname": "Bot"}},
"token_usage": stats.token_usage,
}
try:
pdf_path = await generator.generate_pdf_report(
analysis_result, group_id="test_group"
)
if pdf_path and os.path.exists(pdf_path):
print(f"[SUCCESS] {theme_name} PDF generated: {pdf_path}")
else:
print(f"[FAILURE] {theme_name} PDF generation failed or file not found.")
except Exception as e:
print(f"[ERROR] Failed to generate {theme_name}: {e}")
async def main():
themes = [
"scrapbook",
"hack",
"retro_futurism",
"simple",
"spring_festival",
"format",
]
for theme in themes:
await generate_theme(theme)
if __name__ == "__main__":
asyncio.run(main())
+1 -1
View File
@@ -254,7 +254,7 @@ async def main():
self.dimensions = [ self.dimensions = [
MockDimension("讨论活跃度", 85, "大家讨论非常热烈", "#FF5722"), MockDimension("讨论活跃度", 85, "大家讨论非常热烈", "#FF5722"),
MockDimension("知识共享度", 70, "分享了很多有用的技术信息", "#4CAF50"), MockDimension("知识共享度", 70, "分享了很多有用的技术信息", "#4CAF50"),
MockDimension("情感温度", 92, "群内氛围非常融洽", "#E91E63") MockDimension("情感温度", 92, "群内氛围非常融洽", "#E91E63"),
] ]
self.summary = "整体聊天的质量很高,技术讨论和日常闲聊达到了完美的平衡。" self.summary = "整体聊天的质量很高,技术讨论和日常闲聊达到了完美的平衡。"
@@ -9,6 +9,11 @@
href="https://fonts.googleapis.com/css2?family=Noto+Serif+SC:wght@400;600;700&family=Inter:wght@300;400;500;600&display=swap" href="https://fonts.googleapis.com/css2?family=Noto+Serif+SC:wght@400;600;700&family=Inter:wght@300;400;500;600&display=swap"
rel="stylesheet"> rel="stylesheet">
<style> <style>
@page {
size: A4;
margin: 0;
}
:root { :root {
--bg-body: #f2f2f2; --bg-body: #f2f2f2;
--bg-card: #ffffff; --bg-card: #ffffff;
@@ -31,18 +36,19 @@
background-color: var(--bg-body); background-color: var(--bg-body);
color: var(--text-main); color: var(--text-main);
line-height: 1.6; line-height: 1.6;
padding: 20px; padding: 20mm;
-webkit-font-smoothing: antialiased; -webkit-font-smoothing: antialiased;
} }
.container { .container {
width: 100%; width: 100%;
max-width: none; max-width: 170mm;
margin: 0 auto; margin: 0 auto;
background: var(--bg-card); background: var(--bg-card);
border-radius: var(--radius); border-radius: var(--radius);
box-shadow: var(--shadow); box-shadow: var(--shadow);
overflow: hidden; overflow: hidden;
min-height: 250mm;
} }
/* Header - Editorial Style */ /* Header - Editorial Style */
@@ -437,6 +443,14 @@
padding: 30px; padding: 30px;
font-size: 0.8em; font-size: 0.8em;
border-top: 1px solid var(--border); border-top: 1px solid var(--border);
display: flex;
justify-content: space-between;
align-items: flex-end;
}
.footer a {
color: var(--text-main);
text-decoration: underline;
} }
/* Responsive */ /* Responsive */
@@ -521,11 +535,27 @@
{{topics_html | safe}} {{topics_html | safe}}
{{titles_html | safe}} {{titles_html | safe}}
{{quotes_html | safe}} {{quotes_html | safe}}
{% if chat_quality_html %}
<div class="section full-width-section">
<h2 class="section-title">智睿洞察 // Chat Quality</h2>
<div style="margin-top: 20px;">
{{ chat_quality_html | safe }}
</div>
</div>
{% endif %}
</div> </div>
<div class="footer"> <div class="footer">
由 AstrBot QQ群日常分析插件 生成 | {{current_datetime}} | SXP-Simon/astrbot_plugin_qq_group_daily_analysis<br> <div style="text-align: left;">
<small style="opacity: 0.8; font-size: 0.9em; margin-top: 8px; display: block;">AI分析消耗:{{total_tokens}} <strong>Generated by SXP-Simon</strong><br>
tokens (输入: {{prompt_tokens}}, 输出: {{completion_tokens}})</small> <a href="https://github.com/SXP-Simon/astrbot_plugin_qq_group_daily_analysis" target="_blank">
GitHub Repository
</a>
</div>
<div style="text-align: right;">
{{current_datetime}}<br>
Tokens: {{total_tokens}} (P:{{prompt_tokens}} / C:{{completion_tokens}})
</div>
</div> </div>
</div> </div>
</body> </body>
@@ -3,7 +3,7 @@
<div class="activity-col"> <div class="activity-col">
<span class="activity-val-top">{{ item.count }}</span> <span class="activity-val-top">{{ item.count }}</span>
<div class="activity-bar-v" style="--h:{{ "%.2f"|format(item.percentage) }}%;"></div> <div class="activity-bar-v" style="--h:{{ "%.2f"|format(item.percentage) }}%;"></div>
<span class="activity-tick">{{ "%02d"|format(item.hour) }}:00</span> <span class="activity-tick">{{ "%02d"|format(item.hour) }}</span>
</div> </div>
{% endfor %} {% endfor %}
{% else %} {% else %}
@@ -53,9 +53,11 @@
} }
.layout { .layout {
max-width: 1000px; width: 100%;
max-width: 190mm;
margin: 0 auto; margin: 0 auto;
padding: 40px; padding: 10mm;
min-height: 297mm;
} }
.main-container { .main-container {
@@ -145,10 +147,10 @@
} }
h1 { h1 {
font-size: 3.5rem; font-size: 2.8rem;
font-weight: 800; font-weight: 800;
margin: 0 0 15px; margin: 0 0 15px;
letter-spacing: -1.5px; letter-spacing: -1px;
line-height: 1; line-height: 1;
color: #fff; color: #fff;
} }
@@ -202,10 +204,49 @@
.chart-container { .chart-container {
height: 220px; height: 220px;
position: relative; position: relative;
padding: 20px 5px; padding: 30px 5px 40px;
display: flex; display: flex;
align-items: flex-end; align-items: flex-end;
justify-content: space-between; justify-content: space-between;
gap: 2px;
}
.activity-col {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
height: 100%;
justify-content: flex-end;
min-width: 0;
}
.activity-bar-v {
width: 80%;
max-width: 10px;
background: var(--accent-orange);
height: var(--h, 0%);
border-radius: 1px 1px 0 0;
box-shadow: 0 0 8px rgba(255, 153, 0, 0.3);
position: relative;
}
.activity-tick {
font-family: var(--font-mono);
font-size: 0.5rem;
color: var(--text-secondary);
margin-top: 8px;
transform: rotate(-60deg);
transform-origin: top center;
white-space: nowrap;
}
.activity-val-top {
font-family: var(--font-mono);
font-size: 0.5rem;
color: var(--text-primary);
margin-bottom: 4px;
opacity: 0.6;
} }
.topic-list, .topic-list,
@@ -308,16 +349,22 @@
} }
footer { footer {
margin-top: 60px; margin-top: 40px;
padding-top: 20px; padding-top: 20px;
border-top: 1px solid var(--border-color); border-top: 1px solid var(--border-color);
display: flex; display: flex;
justify-content: space-between; justify-content: space-between;
align-items: flex-end;
font-family: var(--font-mono); font-family: var(--font-mono);
font-size: 0.75rem; font-size: 0.7rem;
color: var(--text-secondary); color: var(--text-secondary);
} }
.footer-repo a {
color: var(--accent-orange);
text-decoration: underline;
}
.avoid-break { .avoid-break {
page-break-inside: avoid; page-break-inside: avoid;
} }
@@ -345,12 +392,19 @@
</div> </div>
</div> </div>
<div class="avoid-break"> <div>
<div class="section-header"><span class="prompt">$</span> ls ./topics</div> <div class="section-header"><span class="prompt">$</span> ls ./topics</div>
<div class="topic-list"> <div class="topic-list">
{{topics_html | safe}} {{topics_html | safe}}
</div> </div>
</div> </div>
{% if chat_quality_html %}
<div style="margin-top: 30px;" class="avoid-break">
<div class="section-header"><span class="prompt">$</span> analyze quality</div>
{{ chat_quality_html | safe }}
</div>
{% endif %}
</div> </div>
<!-- Right Column: Chart & People --> <!-- Right Column: Chart & People -->
@@ -368,25 +422,33 @@
</div> </div>
</div> </div>
<div class="avoid-break">
<div class="section-header"><span class="prompt">$</span> cat users</div> <div class="section-header"><span class="prompt">$</span> cat users</div>
<div class="user-grid"> <div class="user-grid">
{{titles_html | safe}} {{titles_html | safe}}
</div> </div>
</div>
<div style="margin-top: 30px;">
<div class="avoid-break"> <div class="section-header"><span class="prompt">$</span> grep golden</div>
<div class="section-header"><span class="prompt">$</span> grep golden</div> <div class="quote-grid">
<div class="quote-grid"> {{quotes_html | safe}}
{{quotes_html | safe}} </div>
</div> </div>
</div>
</div> </div>
</div> </div>
</div>
<footer> <footer>
<div>SYSTEM_REPORT // {{current_datetime}}</div> <div class="footer-repo">
<div style="color: var(--accent-orange);">AstrBotDevs/AstrBot 群分析</div> <div class="comment">// SXP-Simon</div>
<a href="https://github.com/SXP-Simon/astrbot_plugin_qq_group_daily_analysis" target="_blank">
github.com/SXP-Simon/astrbot_plugin_qq_group_daily_analysis
</a>
</div>
<div style="text-align: right;">
<div class="comment">// {{current_datetime}}</div>
<div>Tokens: {{total_tokens}} [P:{{prompt_tokens}} C:{{completion_tokens}}]</div>
</div>
</footer> </footer>
</div> </div>
</body> </body>
@@ -4,7 +4,7 @@
<div class="activity-col"> <div class="activity-col">
<span class="activity-col-count">{{ item.count }}</span> <span class="activity-col-count">{{ item.count }}</span>
<div class="activity-bar-vertical" style="--h: {{ "%.2f"|format(item.percentage) }}%;"></div> <div class="activity-bar-vertical" style="--h: {{ "%.2f"|format(item.percentage) }}%;"></div>
<span class="activity-label-hour">{{ "%02d"|format(item.hour) }}:00</span> <span class="activity-label-hour">{{ "%02d"|format(item.hour) }}</span>
</div> </div>
{% endfor %} {% endfor %}
</div> </div>
File diff suppressed because it is too large Load Diff
@@ -964,6 +964,13 @@
{{quotes_html | safe}} {{quotes_html | safe}}
<div class="quality-section"> <div class="quality-section">
<div class="section-title">
<svg class="doodle" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
<path d="M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18z" />
<path d="M12 8v4l3 3" />
</svg>
智睿洞察 // Chat Quality
</div>
{{ chat_quality_html | safe }} {{ chat_quality_html | safe }}
</div> </div>
</div> </div>
@@ -5,51 +5,105 @@
<meta charset="UTF-8"> <meta charset="UTF-8">
<title>Simple Report</title> <title>Simple Report</title>
<style> <style>
@page {
size: A4;
margin: 0;
}
body { body {
font-family: sans-serif; font-family: 'Noto Sans SC', sans-serif;
background: #fafafa;
margin: 0;
padding: 20mm;
color: #333;
}
.container {
max-width: 170mm;
margin: 0 auto;
background: #fff;
padding: 20px; padding: 20px;
box-shadow: 0 0 10px rgba(0,0,0,0.05);
min-height: 250mm;
} }
.section { .section {
margin-bottom: 20px; margin-bottom: 25px;
border: 1px solid #ccc; border-bottom: 1px solid #eee;
padding: 10px; padding-bottom: 15px;
} }
h1, h1 { color: #2c3e50; border-left: 5px solid #3498db; padding-left: 15px; }
h2 { h2 { color: #34495e; font-size: 1.2rem; }
color: #333;
.footer {
margin-top: 40px;
padding-top: 20px;
border-top: 2px solid #eee;
color: #7f8c8d;
font-size: 0.85rem;
display: flex;
justify-content: space-between;
align-items: flex-end;
} }
.footer a { color: #3498db; text-decoration: none; }
</style> </style>
</head> </head>
<body> <body>
<h1>群聊日报 - {{current_date}}</h1> <div class="container">
<h1>群聊日报 - {{current_date}}</h1>
<div class="section"> <div class="section">
<h2>基础统计</h2> <h2>基础统计</h2>
<p>消息数: {{message_count}}</p> <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px;">
<p>参与人数: {{participant_count}}</p> <p>消息数: <strong>{{message_count}}</strong></p>
<p>总字符数: {{total_characters}}</p> <p>参与人数: <strong>{{participant_count}}</strong></p>
<p>表情数: {{emoji_count}}</p> <p>总字符数: <strong>{{total_characters}}</strong></p>
<p>最活跃时段: {{most_active_period}}</p> <p>表情数: <strong>{{emoji_count}}</strong></p>
</div> <p>最活跃时段: <strong>{{most_active_period}}</strong></p>
</div>
</div>
<div class="section"> <div class="section">
<h2>活跃度图表</h2> <h2>活跃度图表</h2>
{{hourly_chart_html | safe}} <div style="background: #f9f9f9; padding: 10px; border-radius: 4px;">
</div> {{hourly_chart_html | safe}}
</div>
{{topics_html | safe}} </div>
{{titles_html | safe}}
{{quotes_html | safe}}
<div class="footer"> <div class="section">
Generated by AstrBot | {{current_datetime}} {{topics_html | safe}}
<br> </div>
<small>Token Usage: {{total_tokens}} (Prompt: {{prompt_tokens}}, Completion: {{completion_tokens}})</small>
<div class="section">
{{titles_html | safe}}
</div>
<div class="section" style="border: none;">
{{quotes_html | safe}}
</div>
{% if chat_quality_html %}
<div class="section">
<h2>Chat Quality</h2>
{{ chat_quality_html | safe }}
</div>
{% endif %}
<div class="footer">
<div>
<strong>Generated by SXP-Simon</strong><br>
<a href="https://github.com/SXP-Simon/astrbot_plugin_qq_group_daily_analysis" target="_blank">
GitHub Repository
</a>
</div>
<div style="text-align: right;">
{{current_datetime}}<br>
Tokens: {{total_tokens}} (P:{{prompt_tokens}} / C:{{completion_tokens}})
</div>
</div>
</div> </div>
</body> </body>
@@ -31,7 +31,7 @@
transform: rotate(-45deg); transform: rotate(-45deg);
font-weight: bold; font-weight: bold;
"> ">
{{ "%02d"|format(item.hour) }}:00 {{ "%02d"|format(item.hour) }}
</div> </div>
</div> </div>
{% endfor %} {% endfor %}
@@ -42,11 +42,12 @@
} }
.layout { .layout {
max-width: 900px; width: 100%;
max-width: 190mm;
margin: 0 auto; margin: 0 auto;
padding: 40px; padding: 10mm;
border: 10px solid var(--red-festive); border: 10mm solid var(--red-festive);
min-height: 100vh; min-height: 297mm;
position: relative; position: relative;
} }
@@ -266,6 +267,14 @@
padding-top: 20px; padding-top: 20px;
font-size: 0.8rem; font-size: 0.8rem;
color: var(--red-festive); color: var(--red-festive);
display: flex;
flex-direction: column;
gap: 8px;
}
.footer-repo a {
color: var(--red-festive);
text-decoration: underline;
} }
.avoid-break { .avoid-break {
@@ -317,12 +326,25 @@
{{titles_html | safe}} {{titles_html | safe}}
</div> </div>
</div> </div>
{% if chat_quality_html %}
<div class="sf-section-title">智睿点评 // Chat Quality</div>
{{ chat_quality_html | safe }}
{% endif %}
<div class="sf-section-title">每日金句回响</div> <div class="sf-section-title">每日金句回响</div>
{{quotes_html | safe}} {{quotes_html | safe}}
<footer> <footer>
<div>Generated by SXP-Simon / astrbot_plugin_qq_group_daily_analysis // {{current_datetime}}</div> <div class="footer-repo">
<a href="https://github.com/SXP-Simon/astrbot_plugin_qq_group_daily_analysis" target="_blank">
github.com/SXP-Simon/astrbot_plugin_qq_group_daily_analysis
</a>
</div>
<div>Generated by SXP-Simon // {{current_datetime}}</div>
<div style="font-size: 0.75rem; opacity: 0.8;">
Tokens: {{total_tokens}} (P: {{prompt_tokens}} / C: {{completion_tokens}})
</div>
</footer> </footer>
</div> </div>
</body> </body>