Skip to content

⭐AI-driven public opinion & trend monitor with multi-platform aggregation, RSS, and smart alerts.🎯 告别信息过载,你的 AI 舆情监控助手与热点筛选工具!聚合多平台热点 + RSS 订阅,支持关键词精准筛选。AI 智能筛选新闻 + AI 翻译 + AI 分析简报直推手机,也支持接入 MCP 架构,赋能 AI 自然语言对话分析、情感洞察与趋势预测等。支持 Docker ,数据本地/云端自持。集成微信/飞书/钉钉/Telegram/邮件/ntfy/bark/slack 等渠道智能推送。

feat(report): HTML 报告全面升级 — 暗色模式、交互增强、信息卡片扩展,升级至 v6.8.0

sansana3afc79ddd0f
diff --git a/README-EN.md b/README-EN.md
index 7310d94cd2..94c768fa99 100644
--- a/README-EN.md
+++ b/README-EN.md
@@ -11,7 +11,7 @@ Deploy in <strong>30 seconds</strong> — Say goodbye to endless scrolling, only
[![GitHub Stars](https://img.shields.io/github/stars/sansan0/TrendRadar?style=flat-square&logo=github&color=yellow)](https://github.com/sansan0/TrendRadar/stargazers)
[![GitHub Forks](https://img.shields.io/github/forks/sansan0/TrendRadar?style=flat-square&logo=github&color=blue)](https://github.com/sansan0/TrendRadar/network/members)
[![License](https://img.shields.io/badge/license-GPL--3.0-blue.svg?style=flat-square)](LICENSE)
-[![Version](https://img.shields.io/badge/version-v6.7.1-blue.svg)](https://github.com/sansan0/TrendRadar)
+[![Version](https://img.shields.io/badge/version-v6.8.0-blue.svg)](https://github.com/sansan0/TrendRadar)
[![MCP](https://img.shields.io/badge/MCP-v4.0.4-green.svg)](https://github.com/sansan0/TrendRadar)
[![RSS](https://img.shields.io/badge/RSS-Feed_Support-orange.svg?style=flat-square&logo=rss&logoColor=white)](https://github.com/sansan0/TrendRadar)
[![AI Translation](https://img.shields.io/badge/AI-Multi--Language-purple.svg?style=flat-square)](https://github.com/sansan0/TrendRadar)
@@ -193,12 +193,13 @@ This contributes to the sustainable maintenance of the project and the growth of
- **Tip**: Check [Changelog] to understand specific [Features]
-### 2026/05/15 - v6.7.0
+### 2026/05/23 - v6.8.0
-- **Markdown Export**: New Markdown option in the report export dropdown — generate structured text with clickable links, perfect for LLM processing and cross-platform sharing ([#1121](https://github.com/sansan0/TrendRadar/issues/1121))
-- **RSS GUID Deduplication**: RSS storage now supports GUID field with priority order guid > url, preventing duplicate entries caused by URL changes for the same article
-- **Empty Title Protection**: Full-chain fallback logic across parser, renderer, and translation backfill ensures items without titles still display properly
-- **Translation Quality Enhancement**: Translation prompt now enforces numbered-item ordering preservation; empty translation results no longer overwrite original titles
+- **HTML Report Major Enhancement**: Added report metadata display (generation time, data sources, version), dark mode auto-adaptation, improved Tab bar interaction, and trend arrow visualization for a significantly better browser reading experience
+- **Version Check CDN Multi-Source Fallback**: Version check API now supports automatic fallback across GitHub → jsDelivr → Cloudflare CDN sources, ensuring reliable update notifications even in restricted network environments
+- **Display Region Toggles**: HTML reports and emails now properly respect `display.regions.ai_analysis` and `display.regions.standalone` switches — disabled regions are no longer rendered
+- **Export Button Fix**: Fixed dropdown menu icons disappearing after clicking the export button
+- **Markdown Export Fix**: Fixed JS newline character escaping error in HTML report Markdown export
### 2026/02/09 - mcp-v4.0.0
@@ -212,6 +213,13 @@ This contributes to the sustainable maintenance of the project and the growth of
<details>
<summary>👉 Click to expand: <strong>Historical Updates</strong></summary>
+### 2026/05/15 - v6.7.0
+
+- **Markdown Export**: New Markdown option in the report export dropdown — generate structured text with clickable links, perfect for LLM processing and cross-platform sharing ([#1121](https://github.com/sansan0/TrendRadar/issues/1121))
+- **RSS GUID Deduplication**: RSS storage now supports GUID field with priority order guid > url, preventing duplicate entries caused by URL changes for the same article
+- **Empty Title Protection**: Full-chain fallback logic across parser, renderer, and translation backfill ensures items without titles still display properly
+- **Translation Quality Enhancement**: Translation prompt now enforces numbered-item ordering preservation; empty translation results no longer overwrite original titles
+
### 2026/03/28 - v6.6.0
- **HTML Report Browser Enhancement**: Open the HTML report in a browser to unlock widescreen layout, Tab navigation for keyword groups and standalone sections, real-time title search, and more — email clients still show the original narrow layout with zero regression
diff --git a/README.md b/README.md
index 61e43ccd89..098e55f360 100644
--- a/README.md
+++ b/README.md
@@ -12,7 +12,7 @@
[![GitHub Stars](https://img.shields.io/github/stars/sansan0/TrendRadar?style=flat-square&logo=github&color=yellow)](https://github.com/sansan0/TrendRadar/stargazers)
[![GitHub Forks](https://img.shields.io/github/forks/sansan0/TrendRadar?style=flat-square&logo=github&color=blue)](https://github.com/sansan0/TrendRadar/network/members)
[![License](https://img.shields.io/badge/license-GPL--3.0-blue.svg?style=flat-square)](LICENSE)
-[![Version](https://img.shields.io/badge/version-v6.7.1-blue.svg)](https://github.com/sansan0/TrendRadar)
+[![Version](https://img.shields.io/badge/version-v6.8.0-blue.svg)](https://github.com/sansan0/TrendRadar)
[![MCP](https://img.shields.io/badge/MCP-v4.0.4-green.svg)](https://github.com/sansan0/TrendRadar)
[![RSS](https://img.shields.io/badge/RSS-订阅源支持-orange.svg?style=flat-square&logo=rss&logoColor=white)](https://github.com/sansan0/TrendRadar)
[![AI翻译](https://img.shields.io/badge/AI-多语言推送-purple.svg?style=flat-square)](https://github.com/sansan0/TrendRadar)
@@ -241,12 +241,13 @@
- **提示**:建议查看【历史更新】,明确具体的【功能内容】
-### 2026/05/15 - v6.7.0
+### 2026/05/23 - v6.8.0
-- **Markdown 导出**:报告导出下拉菜单新增 Markdown 格式,一键生成带链接的结构化文本,方便 LLM 二次加工和跨平台分享([#1121](https://github.com/sansan0/TrendRadar/issues/1121))
-- **RSS guid 去重**:RSS 存储新增 guid 字段,去重优先级改为 guid > url,解决同一文章因 URL 变化导致重复入库的问题
-- **空标题防护**:解析器、渲染层、翻译回填全链路增加空标题兜底逻辑,确保无标题条目也能正常显示
-- **翻译质量增强**:翻译提示词要求保留编号顺序,空翻译结果不再覆盖原始标题
+- **HTML 报告全面增强**:新增报告元数据展示(生成时间、数据来源、版本号)、暗色模式自动适配、Tab 栏交互优化、趋势箭头可视化,浏览器阅读体验大幅提升
+- **版本检查 CDN 多源回退**:版本检查接口支持 GitHub → jsDelivr → Cloudflare 等多个 CDN 源自动回退,国内网络环境也能稳定获取更新提示
+- **展示区域开关生效**:HTML 报告和邮件现在正确尊重 `display.regions.ai_analysis` 和 `display.regions.standalone` 开关,关闭即不渲染
+- **导出按钮修复**:修复导出按钮点击后下拉菜单图标消失的问题
+- **Markdown 导出修复**:修复 HTML 报告 Markdown 导出中 JS 换行符转义错误
### 2026/02/09 - mcp-v4.0.0
@@ -260,6 +261,13 @@
<details>
<summary>👉 点击展开:<strong>历史更新</strong></summary>
+### 2026/05/15 - v6.7.0
+
+- **Markdown 导出**:报告导出下拉菜单新增 Markdown 格式,一键生成带链接的结构化文本,方便 LLM 二次加工和跨平台分享([#1121](https://github.com/sansan0/TrendRadar/issues/1121))
+- **RSS guid 去重**:RSS 存储新增 guid 字段,去重优先级改为 guid > url,解决同一文章因 URL 变化导致重复入库的问题
+- **空标题防护**:解析器、渲染层、翻译回填全链路增加空标题兜底逻辑,确保无标题条目也能正常显示
+- **翻译质量增强**:翻译提示词要求保留编号顺序,空翻译结果不再覆盖原始标题
+
### 2026/03/28 - v6.6.0
- **HTML 报告浏览器增强**:在浏览器中打开报告可自动切换宽屏布局,关键词分组和独立展区均支持 Tab 快速切换,搜索框实时过滤新闻标题,邮件客户端仍显示原始窄屏布局,零回归
diff --git a/pyproject.toml b/pyproject.toml
index 2b9a42a449..7eae724d39 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -1,6 +1,6 @@
[project]
name = "trendradar"
-version = "6.7.1"
+version = "6.8.0"
description = "TrendRadar - 热点新闻聚合与分析工具"
requires-python = ">=3.12"
dependencies = [
diff --git a/trendradar/__init__.py b/trendradar/__init__.py
index c5619d34f9..35277fe352 100644
--- a/trendradar/__init__.py
+++ b/trendradar/__init__.py
@@ -9,5 +9,5 @@ TrendRadar - 热点新闻聚合与分析工具
from trendradar.context import AppContext
-__version__ = "6.7.1"
+__version__ = "6.8.0"
__all__ = ["AppContext", "__version__"]
diff --git a/trendradar/__main__.py b/trendradar/__main__.py
index b23ec67bdb..46727e4ffa 100644
--- a/trendradar/__main__.py
+++ b/trendradar/__main__.py
@@ -224,6 +224,13 @@ class NewsAnalyzer:
self._setup_proxy()
self.data_fetcher = DataFetcher(self.proxy_url)
+ # RSS/平台元数据(用于报告头部展示)
+ self._rss_source_total = 0
+ self._rss_source_failed = 0
+ self._rss_total_count = 0
+ self._rss_matched_count = 0
+ self._hotlist_total_count = 0
+
# 初始化存储管理器(使用 AppContext)
self._init_storage_manager()
# 注意:update_info 由 main() 函数设置,避免重复请求远程版本
@@ -833,6 +840,8 @@ class NewsAnalyzer:
mode=mode, global_filters=global_filters, quiet=quiet,
)
+ self._hotlist_total_count = total_titles
+
# 如果是 platform 模式,转换数据结构
if self.ctx.display_mode == "platform" and stats:
stats = convert_keyword_stats_to_platform_stats(
@@ -869,6 +878,9 @@ class NewsAnalyzer:
display_regions=display_regions,
)
+ # 计算 RSS 匹配条数(供 HTML 和推送共用)
+ self._rss_matched_count = sum(stat.get("count", 0) for stat in rss_items) if rss_items else 0
+
# HTML生成(如果启用)— 使用翻译后的数据
html_file = None
if self.ctx.config["STORAGE"]["FORMATS"]["HTML"]:
@@ -888,6 +900,14 @@ class NewsAnalyzer:
ai_analysis=html_ai,
standalone_data=html_standalone,
frequency_file=self.frequency_file,
+ report_metadata={
+ "hotlist_total": total_titles,
+ "platform_total": len(self.ctx.platform_ids),
+ "rss_matched_count": self._rss_matched_count,
+ "rss_total_count": self._rss_total_count,
+ "rss_source_total": self._rss_source_total,
+ "rss_source_failed": self._rss_source_failed,
+ },
)
return stats, html_file, ai_result, rss_items
@@ -961,6 +981,14 @@ class NewsAnalyzer:
# 准备报告数据
report_data = self.ctx.prepare_report(stats, failed_ids, new_titles, id_to_name, mode, frequency_file=self.frequency_file)
+ # 注入元数据(用于推送头部展示)
+ report_data["hotlist_total"] = self._hotlist_total_count
+ report_data["platform_total"] = len(self.ctx.platform_ids)
+ report_data["rss_matched_count"] = self._rss_matched_count
+ report_data["rss_total_count"] = self._rss_total_count
+ report_data["rss_source_total"] = self._rss_source_total
+ report_data["rss_source_failed"] = self._rss_source_failed
+
# 是否发送版本更新信息
update_info_to_send = self.update_info if cfg["SHOW_VERSION_UPDATE"] else None
@@ -1156,6 +1184,9 @@ class NewsAnalyzer:
# 抓取数据
rss_data = fetcher.fetch_all()
+ self._rss_source_total = len(feeds)
+ self._rss_source_failed = len(rss_data.failed_ids)
+
# 保存到存储后端
if self.storage_manager.save_rss_data(rss_data):
print(f"[RSS] 数据已保存到存储后端")
@@ -1344,6 +1375,7 @@ class NewsAnalyzer:
quiet=True,
)
+ self._rss_total_count = total
return rss_stats, rss_new_stats, raw_rss_items, rss_new_urls
def _convert_rss_items_to_list(self, items_dict: Dict, id_to_name: Dict) -> List[Dict]:
diff --git a/trendradar/ai/__init__.py b/trendradar/ai/__init__.py
index bb05903dc1..ff28d7cff2 100644
--- a/trendradar/ai/__init__.py
+++ b/trendradar/ai/__init__.py
@@ -13,7 +13,6 @@ from .formatter import (
render_ai_analysis_markdown,
render_ai_analysis_feishu,
render_ai_analysis_dingtalk,
- render_ai_analysis_html,
render_ai_analysis_html_rich,
render_ai_analysis_plain,
)
@@ -34,7 +33,6 @@ __all__ = [
"render_ai_analysis_markdown",
"render_ai_analysis_feishu",
"render_ai_analysis_dingtalk",
- "render_ai_analysis_html",
"render_ai_analysis_html_rich",
"render_ai_analysis_plain",
]
diff --git a/trendradar/ai/analyzer.py b/trendradar/ai/analyzer.py
index 715c8c5cc8..99ad268a99 100644
--- a/trendradar/ai/analyzer.py
+++ b/trendradar/ai/analyzer.py
@@ -35,9 +35,14 @@ class AIAnalysisResult:
total_news: int = 0 # 总新闻数(热榜+RSS)
analyzed_news: int = 0 # 实际分析的新闻数
max_news_limit: int = 0 # 分析上限配置值
- hotlist_count: int = 0 # 热榜新闻数
- rss_count: int = 0 # RSS 新闻数
+ hotlist_count: int = 0 # 热榜新闻数(总数)
+ rss_count: int = 0 # RSS 新闻数(总数)
+ hotlist_analyzed: int = 0 # 热榜实际分析数
+ rss_analyzed: int = 0 # RSS 实际分析数
+ standalone_analyzed: int = 0 # 独立展示区实际分析数
ai_mode: str = "" # AI 分析使用的模式 (daily/current/incremental)
+ include_rss: bool = True # 是否启用 RSS 分析
+ include_standalone: bool = False # 是否启用独立展示区分析
class AIAnalyzer:
@@ -134,7 +139,7 @@ class AIAnalyzer:
)
# 准备新闻内容并获取统计数据
- news_content, rss_content, hotlist_total, rss_total, analyzed_count = self._prepare_news_content(stats, rss_stats)
+ news_content, rss_content, hotlist_total, rss_total, analyzed_count, hotlist_analyzed, rss_analyzed = self._prepare_news_content(stats, rss_stats)
total_news = hotlist_total + rss_total
if not news_content and not rss_content:
@@ -171,8 +176,9 @@ class AIAnalyzer:
# 构建独立展示区内容
standalone_content = ""
+ standalone_count = 0
if self.include_standalone and standalone_data:
- standalone_content = self._prepare_standalone_content(standalone_data)
+ standalone_content, standalone_count = self._prepare_standalone_content(standalone_data)
user_prompt = user_prompt.replace("{standalone_content}", standalone_content)
if self.debug:
@@ -215,7 +221,12 @@ class AIAnalyzer:
result.hotlist_count = hotlist_total
result.rss_count = rss_total
result.analyzed_news = analyzed_count
+ result.hotlist_analyzed = hotlist_analyzed
+ result.rss_analyzed = rss_analyzed
+ result.standalone_analyzed = standalone_count
result.max_news_limit = self.max_news
+ result.include_rss = self.include_rss
+ result.include_standalone = self.include_standalone
return result
except Exception as e:
error_type = type(e).__name__
@@ -243,7 +254,7 @@ class AIAnalyzer:
RSS 包含:来源、标题、发布时间
Returns:
- tuple: (news_content, rss_content, hotlist_total, rss_total, analyzed_count)
+ tuple: (news_content, rss_content, hotlist_total, rss_total, analyzed_count, hotlist_analyzed, rss_analyzed)
"""
news_lines = []
rss_lines = []
@@ -348,7 +359,7 @@ class AIAnalyzer:
rss_content = "\n".join(rss_lines) if rss_lines else ""
total_count = news_count + rss_count
- return news_content, rss_content, hotlist_total, rss_total, total_count
+ return news_content, rss_content, hotlist_total, rss_total, total_count, news_count, rss_count
def _call_ai(self, user_prompt: str) -> str:
"""调用 AI API(使用 LiteLLM)"""
@@ -447,7 +458,7 @@ class AIAnalyzer:
return "→".join(parts)
- def _prepare_standalone_content(self, standalone_data: Dict) -> str:
+ def _prepare_standalone_content(self, standalone_data: Dict) -> tuple:
"""
将独立展示区数据转为文本,注入 AI 分析 prompt
@@ -455,7 +466,7 @@ class AIAnalyzer:
standalone_data: 独立展示区数据 {"platforms": [...], "rss_feeds": [...]}
Returns:
- 格式化的文本内容
+ tuple: (格式化的文本内容, 独立展示区条目数)
"""
lines = []
@@ -527,7 +538,12 @@ class AIAnalyzer:
lines.append(line)
lines.append("")
- return "\n".join(lines)
+ standalone_count = sum(
+ len(p.get("items", [])) for p in standalone_data.get("platforms", [])
+ ) + sum(
+ len(f.get("items", [])) for f in standalone_data.get("rss_feeds", [])
+ )
+ return "\n".join(lines), standalone_count
def _parse_response(self, response: str) -> AIAnalysisResult:
"""解析 AI 响应"""
diff --git a/trendradar/ai/formatter.py b/trendradar/ai/formatter.py
index f5c5d7f68d..bf24eb1892 100644
--- a/trendradar/ai/formatter.py
+++ b/trendradar/ai/formatter.py
@@ -196,94 +196,6 @@ def render_ai_analysis_dingtalk(result: AIAnalysisResult) -> str:
return "\n".join(lines)
-def render_ai_analysis_html(result: AIAnalysisResult) -> str:
- """渲染为 HTML 格式(邮件)"""
- if not result.success:
- if result.skipped:
- return f'<div class="ai-info">ℹ️ {_escape_html(result.error)}</div>'
- return (
- f'<div class="ai-error">⚠️ AI 分析失败: {_escape_html(result.error)}</div>'
- )
-
- html_parts = ['<div class="ai-analysis">', "<h3>✨ AI 热点分析</h3>"]
-
- if result.core_trends:
- content = _format_list_content(result.core_trends)
- content_html = _escape_html(content).replace("\n", "<br>")
- html_parts.extend(
- [
- '<div class="ai-section">',
- "<h4>核心热点态势</h4>",
- f'<div class="ai-content">{content_html}</div>',
- "</div>",
- ]
- )
-
- if result.sentiment_controversy:
- content = _format_list_content(result.sentiment_controversy)
- content_html = _escape_html(content).replace("\n", "<br>")
- html_parts.extend(
- [
- '<div class="ai-section">',
- "<h4>舆论风向争议</h4>",
- f'<div class="ai-content">{content_html}</div>',
- "</div>",
- ]
- )
-
- if result.signals:
- content = _format_list_content(result.signals)
- content_html = _escape_html(content).replace("\n", "<br>")
- html_parts.extend(
- [
- '<div class="ai-section">',
- "<h4>异动与弱信号</h4>",
- f'<div class="ai-content">{content_html}</div>',
- "</div>",
- ]
- )
-
- if result.rss_insights:
- content = _format_list_content(result.rss_insights)
- content_html = _escape_html(content).replace("\n", "<br>")
- html_parts.extend(
- [
- '<div class="ai-section">',
- "<h4>RSS 深度洞察</h4>",
- f'<div class="ai-content">{content_html}</div>',
- "</div>",
- ]
- )
-
- if result.outlook_strategy:
- content = _format_list_content(result.outlook_strategy)
- content_html = _escape_html(content).replace("\n", "<br>")
- html_parts.extend(
- [
- '<div class="ai-section ai-conclusion">',
- "<h4>研判策略建议</h4>",
- f'<div class="ai-content">{content_html}</div>',
- "</div>",
- ]
- )
-
- if result.standalone_summaries:
- summaries_text = _format_standalone_summaries(result.standalone_summaries)
- if summaries_text:
- summaries_html = _escape_html(summaries_text).replace("\n", "<br>")
- html_parts.extend(
- [
- '<div class="ai-section">',
- "<h4>独立源点速览</h4>",
- f'<div class="ai-content">{summaries_html}</div>',
- "</div>",
- ]
- )
-
- html_parts.append("</div>")
- return "\n".join(html_parts)
-
-
def render_ai_analysis_plain(result: AIAnalysisResult) -> str:
"""渲染为纯文本格式"""
if not result.success:
@@ -385,7 +297,7 @@ def render_ai_analysis_html_rich(result: AIAnalysisResult) -> str:
error_msg = result.error or "未知错误"
return f"""
<div class="ai-section">
- <div class="ai-error">⚠️ AI 分析失败: {_escape_html(str(error_msg))}</div>
+ <div class="ai-warning">AI 分析失败: {_escape_html(str(error_msg))}</div>
</div>"""
ai_html = """
diff --git a/trendradar/context.py b/trendradar/context.py
index 126b2daf55..198f3ac58d 100644
--- a/trendradar/context.py
+++ b/trendradar/context.py
@@ -320,6 +320,7 @@ class AppContext:
ai_analysis: Optional[Any] = None,
standalone_data: Optional[Dict] = None,
frequency_file: Optional[str] = None,
+ report_metadata: Optional[Dict] = None,
) -> str:
"""生成HTML报告"""
return generate_html_report(
@@ -337,6 +338,7 @@ class AppContext:
render_html_func=lambda *args, **kwargs: self.render_html(*args, rss_items=rss_items, rss_new_items=rss_new_items, ai_analysis=ai_analysis, standalone_data=standalone_data, **kwargs),
matches_word_groups_func=self.matches_word_groups,
load_frequency_words_func=lambda: self.load_frequency_words(frequency_file),
+ report_metadata=report_metadata,
)
def render_html(
diff --git a/trendradar/notification/renderer.py b/trendradar/notification/renderer.py
index 190124821b..42a0c1bb30 100644
--- a/trendradar/notification/renderer.py
+++ b/trendradar/notification/renderer.py
@@ -178,11 +178,8 @@ def render_dingtalk_content(
)
now = get_time_func() if get_time_func else datetime.now()
- # 头部信息
- header_content = f"**总新闻数:** {total_titles}\n\n"
- header_content += f"**时间:** {now.strftime('%Y-%m-%d %H:%M:%S')}\n\n"
- header_content += "**类型:** 热点分析报告\n\n"
- header_content += "---\n\n"
+ # 头部信息由 splitter 统一构建,此处不再重复
+ header_content = ""
# 生成热点词汇统计部分
stats_content = ""
diff --git a/trendradar/notification/senders.py b/trendradar/notification/senders.py
index 2632703802..7e72d102fa 100644
--- a/trendradar/notification/senders.py
+++ b/trendradar/notification/senders.py
@@ -33,6 +33,25 @@ from .batch import add_batch_headers, get_max_batch_header_size
from .formatters import convert_markdown_to_mrkdwn, strip_markdown
+def _extract_ai_stats(ai_analysis) -> Optional[Dict]:
+ """从 AI 分析结果中提取统计数据"""
+ if not ai_analysis or not getattr(ai_analysis, "success", False):
+ return None
+ return {
+ "total_news": getattr(ai_analysis, "total_news", 0),
+ "analyzed_news": getattr(ai_analysis, "analyzed_news", 0),
+ "max_news_limit": getattr(ai_analysis, "max_news_limit", 0),
+ "hotlist_count": getattr(ai_analysis, "hotlist_count", 0),
+ "rss_count": getattr(ai_analysis, "rss_count", 0),
+ "hotlist_analyzed": getattr(ai_analysis, "hotlist_analyzed", 0),
+ "rss_analyzed": getattr(ai_analysis, "rss_analyzed", 0),
+ "standalone_analyzed": getattr(ai_analysis, "standalone_analyzed", 0),
+ "ai_mode": getattr(ai_analysis, "ai_mode", ""),
+ "include_rss": getattr(ai_analysis, "include_rss", True),
+ "include_standalone": getattr(ai_analysis, "include_standalone", False),
+ }
+
+
def _render_ai_analysis(ai_analysis: Any, channel: str) -> str:
"""渲染 AI 分析内容为指定渠道格式"""
if not ai_analysis:
@@ -122,21 +141,9 @@ def send_to_feishu(
# 日志前缀
log_prefix = f"飞书{account_label}" if account_label else "飞书"
- # 渲染 AI 分析内容(如果有)
- ai_content = None
- ai_stats = None
- if ai_analysis:
- ai_content = _render_ai_analysis(ai_analysis, "feishu")
- # 提取 AI 分析统计数据(只要 AI 分析成功就显示)
- if getattr(ai_analysis, "success", False):
- ai_stats = {
- "total_news": getattr(ai_analysis, "total_news", 0),
- "analyzed_news": getattr(ai_analysis, "analyzed_news", 0),
- "max_news_limit": getattr(ai_analysis, "max_news_limit", 0),
- "hotlist_count": getattr(ai_analysis, "hotlist_count", 0),
- "rss_count": getattr(ai_analysis, "rss_count", 0),
- "ai_mode": getattr(ai_analysis, "ai_mode", ""),
- }
+ # 渲染 AI 分析内容并提取统计数据
+ ai_content = _render_ai_analysis(ai_analysis, "feishu") if ai_analysis else None
+ ai_stats = _extract_ai_stats(ai_analysis)
# 预留批次头部空间,避免添加头部后超限
header_reserve = get_max_batch_header_size("feishu")
@@ -266,21 +273,9 @@ def send_to_dingtalk(
# 日志前缀
log_prefix = f"钉钉{account_label}" if account_label else "钉钉"
- # 渲染 AI 分析内容(如果有)
- ai_content = None
- ai_stats = None
- if ai_analysis:
- ai_content = _render_ai_analysis(ai_analysis, "dingtalk")
- # 提取 AI 分析统计数据(只要 AI 分析成功就显示)
- if getattr(ai_analysis, "success", False):
- ai_stats = {
- "total_news": getattr(ai_analysis, "total_news", 0),
- "analyzed_news": getattr(ai_analysis, "analyzed_news", 0),
- "max_news_limit": getattr(ai_analysis, "max_news_limit", 0),
- "hotlist_count": getattr(ai_analysis, "hotlist_count", 0),
- "rss_count": getattr(ai_analysis, "rss_count", 0),
- "ai_mode": getattr(ai_analysis, "ai_mode", ""),
- }
+ # 渲染 AI 分析内容并提取统计数据
+ ai_content = _render_ai_analysis(ai_analysis, "dingtalk") if ai_analysis else None
+ ai_stats = _extract_ai_stats(ai_analysis)
# 预留批次头部空间,避免添加头部后超限
header_reserve = get_max_batch_header_size("dingtalk")
@@ -407,21 +402,9 @@ def send_to_wework(
# text 模式使用 wework_text,markdown 模式使用 wework
header_format_type = "wework_text" if is_text_mode else "wework"
- # 渲染 AI 分析内容(如果有)
- ai_content = None
- ai_stats = None
- if ai_analysis:
- ai_content = _render_ai_analysis(ai_analysis, "wework")
- # 提取 AI 分析统计数据(只要 AI 分析成功就显示)
- if getattr(ai_analysis, "success", False):
- ai_stats = {
- "total_news": getattr(ai_analysis, "total_news", 0),
- "analyzed_news": getattr(ai_analysis, "analyzed_news", 0),
- "max_news_limit": getattr(ai_analysis, "max_news_limit", 0),
- "hotlist_count": getattr(ai_analysis, "hotlist_count", 0),
- "rss_count": getattr(ai_analysis, "rss_count", 0),
- "ai_mode": getattr(ai_analysis, "ai_mode", ""),
- }
+ # 渲染 AI 分析内容并提取统计数据
+ ai_content = _render_ai_analysis(ai_analysis, "wework") if ai_analysis else None
+ ai_stats = _extract_ai_stats(ai_analysis)
# 获取分批内容,预留批次头部空间
header_reserve = get_max_batch_header_size(header_format_type)
@@ -537,21 +520,9 @@ def send_to_telegram(
# 日志前缀
log_prefix = f"Telegram{account_label}" if account_label else "Telegram"
- # 渲染 AI 分析内容(如果有)
- ai_content = None
- ai_stats = None
- if ai_analysis:
- ai_content = _render_ai_analysis(ai_analysis, "telegram")
- # 提取 AI 分析统计数据(只要 AI 分析成功就显示)
- if getattr(ai_analysis, "success", False):
- ai_stats = {
- "total_news": getattr(ai_analysis, "total_news", 0),
- "analyzed_news": getattr(ai_analysis, "analyzed_news", 0),
- "max_news_limit": getattr(ai_analysis, "max_news_limit", 0),
- "hotlist_count": getattr(ai_analysis, "hotlist_count", 0),
- "rss_count": getattr(ai_analysis, "rss_count", 0),
- "ai_mode": getattr(ai_analysis, "ai_mode", ""),
- }
+ # 渲染 AI 分析内容并提取统计数据
+ ai_content = _render_ai_analysis(ai_analysis, "telegram") if ai_analysis else None
+ ai_stats = _extract_ai_stats(ai_analysis)
# 获取分批内容,预留批次头部空间
header_reserve = get_max_batch_header_size("telegram")
@@ -846,21 +817,9 @@ def send_to_ntfy(
if proxy_url:
proxies = {"http": proxy_url, "https": proxy_url}
- # 渲染 AI 分析内容(如果有),合并到主内容中
- ai_content = None
- ai_stats = None
- if ai_analysis:
- ai_content = _render_ai_analysis(ai_analysis, "ntfy")
- # 提取 AI 分析统计数据(只要 AI 分析成功就显示)
- if getattr(ai_analysis, "success", False):
- ai_stats = {
- "total_news": getattr(ai_analysis, "total_news", 0),
- "analyzed_news": getattr(ai_analysis, "analyzed_news", 0),
- "max_news_limit": getattr(ai_analysis, "max_news_limit", 0),
- "hotlist_count": getattr(ai_analysis, "hotlist_count", 0),
- "rss_count": getattr(ai_analysis, "rss_count", 0),
- "ai_mode": getattr(ai_analysis, "ai_mode", ""),
- }
+ # 渲染 AI 分析内容并提取统计数据
+ ai_content = _render_ai_analysis(ai_analysis, "ntfy") if ai_analysis else None
+ ai_stats = _extract_ai_stats(ai_analysis)
# 获取分批内容,预留批次头部空间
header_reserve = get_max_batch_header_size("ntfy")
@@ -1033,21 +992,9 @@ def send_to_bark(
# 构建正确的 API 端点
api_endpoint = f"{parsed_url.scheme}://{parsed_url.netloc}/push"
- # 渲染 AI 分析内容(如果有),合并到主内容中
- ai_content = None
- ai_stats = None
- if ai_analysis:
- ai_content = _render_ai_analysis(ai_analysis, "bark")
- # 提取 AI 分析统计数据(只要 AI 分析成功就显示)
- if getattr(ai_analysis, "success", False):
- ai_stats = {
- "total_news": getattr(ai_analysis, "total_news", 0),
- "analyzed_news": getattr(ai_analysis, "analyzed_news", 0),
- "max_news_limit": getattr(ai_analysis, "max_news_limit", 0),
- "hotlist_count": getattr(ai_analysis, "hotlist_count", 0),
- "rss_count": getattr(ai_analysis, "rss_count", 0),
- "ai_mode": getattr(ai_analysis, "ai_mode", ""),
- }
+ # 渲染 AI 分析内容并提取统计数据
+ ai_content = _render_ai_analysis(ai_analysis, "bark") if ai_analysis else None
+ ai_stats = _extract_ai_stats(ai_analysis)
# 获取分批内容,预留批次头部空间
header_reserve = get_max_batch_header_size("bark")
@@ -1196,21 +1143,9 @@ def send_to_slack(
# 日志前缀
log_prefix = f"Slack{account_label}" if account_label else "Slack"
- # 渲染 AI 分析内容(如果有),合并到主内容中
- ai_content = None
- ai_stats = None
- if ai_analysis:
- ai_content = _render_ai_analysis(ai_analysis, "slack")
- # 提取 AI 分析统计数据(只要 AI 分析成功就显示)
- if getattr(ai_analysis, "success", False):
- ai_stats = {
- "total_news": getattr(ai_analysis, "total_news", 0),
- "analyzed_news": getattr(ai_analysis, "analyzed_news", 0),
- "max_news_limit": getattr(ai_analysis, "max_news_limit", 0),
- "hotlist_count": getattr(ai_analysis, "hotlist_count", 0),
- "rss_count": getattr(ai_analysis, "rss_count", 0),
- "ai_mode": getattr(ai_analysis, "ai_mode", ""),
- }
+ # 渲染 AI 分析内容并提取统计数据
+ ai_content = _render_ai_analysis(ai_analysis, "slack") if ai_analysis else None
+ ai_stats = _extract_ai_stats(ai_analysis)
# 获取分批内容,预留批次头部空间
header_reserve = get_max_batch_header_size("slack")
@@ -1319,21 +1254,9 @@ def send_to_generic_webhook(
# 日志前缀
log_prefix = f"通用Webhook{account_label}" if account_label else "通用Webhook"
- # 渲染 AI 分析内容(如果有)
- ai_content = None
- ai_stats = None
- if ai_analysis:
- # 通用 Webhook 使用 markdown 格式渲染 AI 分析
- ai_content = _render_ai_analysis(ai_analysis, "wework")
- # 提取 AI 分析统计数据
- if getattr(ai_analysis, "success", False):
- ai_stats = {
- "total_news": getattr(ai_analysis, "total_news", 0),
- "analyzed_news": getattr(ai_analysis, "analyzed_news", 0),
- "max_news_limit": getattr(ai_analysis, "max_news_limit", 0),
- "hotlist_count": getattr(ai_analysis, "hotlist_count", 0),
- "rss_count": getattr(ai_analysis, "rss_count", 0),
- }
+ # 渲染 AI 分析内容并提取统计数据(通用 Webhook 使用 markdown 格式)
+ ai_content = _render_ai_analysis(ai_analysis, "wework") if ai_analysis else None
+ ai_stats = _extract_ai_stats(ai_analysis)
# 获取分批内容
# 使用 'wework' 作为 format_type 以获取 markdown 格式的通用输出
diff --git a/trendradar/notification/splitter.py b/trendradar/notification/splitter.py
index d4b4202782..a081fce0d5 100644
--- a/trendradar/notification/splitter.py
+++ b/trendradar/notification/splitter.py
@@ -211,71 +211,99 @@ def split_content_into_batches(
# 构建头部信息
base_header = ""
-
- # 准备 AI 分析统计行(如果存在)
- ai_stats_line = ""
- if ai_stats and ai_stats.get("analyzed_news", 0) > 0:
- analyzed_news = ai_stats.get("analyzed_news", 0)
- total_news = ai_stats.get("total_news", 0)
- ai_mode = ai_stats.get("ai_mode", "")
-
- # 构建分析数显示:如果被截断则显示 "实际分析数/总可分析数"
- if total_news > analyzed_news:
- news_display = f"{analyzed_news}/{total_news}"
- else:
- news_display = str(analyzed_news)
- # 如果 AI 模式与推送模式不同,显示模式标识
+ # 格式化粗体标记
+ if format_type == "slack":
+ b_s, b_e = "*", "*"
+ elif format_type == "telegram":
+ b_s, b_e = "", ""
+ else:
+ b_s, b_e = "**", "**"
+
+ # 提取统计数据
+ hotlist_total = report_data.get("hotlist_total", total_hotlist_count)
+ new_count = report_data.get("total_new_count", 0)
+ platform_total = report_data.get("platform_total", 0)
+ failed_count = len(report_data.get("failed_ids", []))
+ platform_success = platform_total - failed_count if platform_total else 0
+ rss_matched = report_data.get("rss_matched_count", 0)
+ rss_total_items = report_data.get("rss_total_count", 0)
+ rss_source_total = report_data.get("rss_source_total", 0)
+ rss_source_failed = report_data.get("rss_source_failed", 0)
+ rss_source_success = max(0, rss_source_total - rss_source_failed)
+
+ # === 上半部分:数据统计 ===
+
+ # 1. 总新闻
+ rss_new_count = sum(len(stat.get("titles", [])) for stat in (rss_new_items or []))
+ total_new = new_count + rss_new_count
+ total_news_line = f"{b_s}总新闻:{b_e} {total_titles} 条"
+ if total_new > 0:
+ total_news_line += f"(新增 {new_count} + {rss_new_count})"
+ base_header += f"{total_news_line}\n"
+
+ # 2. 热榜
+ hotlist_info = f"{b_s}热榜:{b_e} {total_hotlist_count}/{hotlist_total}"
+ if platform_total > 0:
+ hotlist_info += f"(平台 {platform_success}/{platform_total})"
+ base_header += f"{hotlist_info}\n"
+
+ # 3. RSS
+ if rss_source_total > 0:
+ rss_info = f"{b_s}RSS:{b_e} {rss_matched}/{rss_total_items}(源 {rss_source_success}/{rss_source_total})"
+ base_header += f"{rss_info}\n"
+
+ # 4. 独立展示区(仅在有数据时显示)
+ if standalone_data:
+ sa_platform_count = sum(len(p.get("items", [])) for p in standalone_data.get("platforms", []))
+ sa_rss_count = sum(len(f.get("items", [])) for f in standalone_data.get("rss_feeds", []))
+ sa_total = sa_platform_count + sa_rss_count
+ if sa_total > 0:
+ sa_parts = []
+ if sa_platform_count > 0:
+ sa_parts.append(f"热榜 {sa_platform_count}")
+ if sa_rss_count > 0:
+ sa_parts.append(f"RSS {sa_rss_count}")
+ base_header += f"{b_s}独立展示:{b_e} {sa_total} 条({' + '.join(sa_parts)})\n"
+
+ # 5. AI 分析(仅在有分析数据时显示)
+ standalone_analyzed = ai_stats.get("standalone_analyzed", 0) if ai_stats else 0
+ ai_has_data = ai_stats and (ai_stats.get("analyzed_news", 0) > 0 or standalone_analyzed > 0)
+ if ai_has_data:
+ hotlist_analyzed = ai_stats.get("hotlist_analyzed", 0)
+ rss_analyzed = ai_stats.get("rss_analyzed", 0)
+ ai_mode_val = ai_stats.get("ai_mode", "")
+
+ ai_parts = [str(hotlist_analyzed)]
+ if ai_stats.get("include_rss", True):
+ ai_parts.append(str(rss_analyzed))
+ if ai_stats.get("include_standalone", False):
+ ai_parts.append(str(standalone_analyzed))
+ ai_display = " + ".join(ai_parts) if sum(int(p) for p in ai_parts) > 0 else "0"
+
mode_suffix = ""
- if ai_mode and ai_mode != mode:
- mode_map = {
- "daily": "全天汇总",
- "current": "当前榜单",
- "incremental": "增量分析"
- }
- mode_label = mode_map.get(ai_mode, ai_mode)
- mode_suffix = f" ({mode_label})"
+ if ai_mode_val and ai_mode_val != mode:
+ mode_map = {"daily": "全天汇总", "current": "当前榜单", "incremental": "增量分析"}
+ mode_suffix = f" [{mode_map.get(ai_mode_val, ai_mode_val)}]"
- if format_type in ("wework", "bark", "ntfy", "feishu", "dingtalk"):
- ai_stats_line = f"**AI 分析数:** {news_display}{mode_suffix}\n"
- elif format_type == "slack":
- ai_stats_line = f"*AI 分析数:* {news_display}{mode_suffix}\n"
- elif format_type == "telegram":
- ai_stats_line = f"AI 分析数: {news_display}{mode_suffix}\n"
+ base_header += f"{b_s}AI 分析:{b_e} {ai_display}{mode_suffix}\n"
- # 构建统一的头部(总是显示总新闻数、时间和类型)
- if format_type in ("wework", "bark"):
- base_header = f"**总新闻数:** {total_titles}\n"
- base_header += ai_stats_line
- base_header += f"**时间:** {now.strftime('%Y-%m-%d %H:%M:%S')}\n"
- base_header += f"**类型:** {report_type}\n\n"
- elif format_type == "telegram":
- base_header = f"总新闻数: {total_titles}\n"
- base_header += ai_stats_line
- base_header += f"时间: {now.strftime('%Y-%m-%d %H:%M:%S')}\n"
- base_header += f"类型: {report_type}\n\n"
- elif format_type == "ntfy":
- base_header = f"**总新闻数:** {total_titles}\n"
- base_header += ai_stats_line
- base_header += f"**时间:** {now.strftime('%Y-%m-%d %H:%M:%S')}\n"
- base_header += f"**类型:** {report_type}\n\n"
- elif format_type == "feishu":
- base_header = f"**总新闻数:** {total_titles}\n"
- base_header += ai_stats_line
- base_header += f"**时间:** {now.strftime('%Y-%m-%d %H:%M:%S')}\n"
- base_header += f"**类型:** {report_type}\n\n"
- base_header += "---\n\n"
- elif format_type == "dingtalk":
- base_header = f"**总新闻数:** {total_titles}\n"
- base_header += ai_stats_line
- base_header += f"**时间:** {now.strftime('%Y-%m-%d %H:%M:%S')}\n"
- base_header += f"**类型:** {report_type}\n\n"
- base_header += "---\n\n"
- elif format_type == "slack":
- base_header = f"*总新闻数:* {total_titles}\n"
- base_header += ai_stats_line
- base_header += f"*时间:* {now.strftime('%Y-%m-%d %H:%M:%S')}\n"
- base_header += f"*类型:* {report_type}\n\n"
+ # === 空行分隔 ===
+ base_header += "\n"
+
+ # === 下半部分:元信息 ===
+ base_header += f"{b_s}类型:{b_e} {report_type}\n"
+ base_header += f"{b_s}时间:{b_e} {now.strftime('%Y-%m-%d %H:%M:%S')}\n"
+
+ top_words = report_data.get("stats", [])[:3]
+ if top_words:
+ topics = " | ".join(f"{s['word']}({s['count']})" for s in top_words)
+ base_header += f"{b_s}最热话题:{b_e} {topics}\n"
+
+ if format_type in ("feishu", "dingtalk"):
+ base_header += "\n---\n\n"
+ else:
+ base_header += "\n"
base_footer = ""
if format_type in ("wework", "bark"):
@@ -1694,7 +1722,8 @@ def _format_standalone_platform_item(item: Dict, index: int, format_type: str, r
# 如果没有 ranks 列表,用单个 rank 构造
if not ranks and rank > 0:
ranks = [rank]
- rank_display = format_rank_display(ranks, rank_threshold, format_type) if ranks else ""
+ rank_timeline = item.get("rank_timeline")
+ rank_display = format_rank_display(ranks, rank_threshold, format_type, rank_timeline=rank_timeline) if ranks else ""
# 构建时间显示(用 ~ 连接范围,与热点词汇统计区一致)
# 将 HH-MM 格式转换为 HH:MM 格式
diff --git a/trendradar/report/formatter.py b/trendradar/report/formatter.py
index 57e41fc2c6..a79b718212 100644
--- a/trendradar/report/formatter.py
+++ b/trendradar/report/formatter.py
@@ -45,7 +45,8 @@ def format_title_for_platform(
格式化后的标题字符串
"""
rank_display = format_rank_display(
- title_data["ranks"], title_data["rank_threshold"], platform
+ title_data["ranks"], title_data["rank_threshold"], platform,
+ rank_timeline=title_data.get("rank_timeline"),
)
link_url = title_data["mobile_url"] or title_data["url"]
@@ -196,7 +197,8 @@ def format_title_for_platform(
# 排名(使用 * 加粗)
rank_display = format_rank_display(
- title_data["ranks"], title_data["rank_threshold"], "slack"
+ title_data["ranks"], title_data["rank_threshold"], "slack",
+ rank_timeline=title_data.get("rank_timeline"),
)
if rank_display:
result += f" {rank_display}"
@@ -209,7 +211,8 @@ def format_title_for_platform(
elif platform == "html":
rank_display = format_rank_display(
- title_data["ranks"], title_data["rank_threshold"], "html"
+ title_data["ranks"], title_data["rank_threshold"], "html",
+ rank_timeline=title_data.get("rank_timeline"),
)
link_url = title_data["mobile_url"] or title_data["url"]
diff --git a/trendradar/report/generator.py b/trendradar/report/generator.py
index 374ea0b7d4..54b2681089 100644
--- a/trendradar/report/generator.py
+++ b/trendradar/report/generator.py
@@ -41,64 +41,61 @@ def prepare_report_data(
"""
processed_new_titles = []
- # 在增量模式下或配置关闭时隐藏新增新闻区域
- hide_new_section = mode == "incremental" or not show_new_section
-
- # 只有在非隐藏模式下才处理新增新闻部分
- if not hide_new_section:
- filtered_new_titles = {}
- if new_titles and id_to_name:
- # 如果提供了匹配函数,使用它过滤
- if matches_word_groups_func and load_frequency_words_func:
- word_groups, filter_words, global_filters = load_frequency_words_func()
- for source_id, titles_data in new_titles.items():
- filtered_titles = {}
- for title, title_data in titles_data.items():
- if matches_word_groups_func(title, word_groups, filter_words, global_filters):
- filtered_titles[title] = title_data
- if filtered_titles:
- filtered_new_titles[source_id] = filtered_titles
- else:
- # 没有匹配函数时,使用全部
- filtered_new_titles = new_titles
-
- # 打印过滤后的新增热点数(与推送显示一致)
- original_new_count = sum(len(titles) for titles in new_titles.values()) if new_titles else 0
- filtered_new_count = sum(len(titles) for titles in filtered_new_titles.values()) if filtered_new_titles else 0
- if original_new_count > 0:
- print(f"频率词过滤后:{filtered_new_count} 条新增热点匹配(原始 {original_new_count} 条)")
-
- if filtered_new_titles and id_to_name:
- for source_id, titles_data in filtered_new_titles.items():
- source_name = id_to_name.get(source_id, source_id)
- source_titles = []
-
+ # 始终过滤新增标题用于计数(头部统计需要),但区域展示受配置控制
+ filtered_new_titles = {}
+ if new_titles and id_to_name:
+ if matches_word_groups_func and load_frequency_words_func:
+ word_groups, filter_words, global_filters = load_frequency_words_func()
+ for source_id, titles_data in new_titles.items():
+ filtered_titles = {}
for title, title_data in titles_data.items():
- url = title_data.get("url", "")
- mobile_url = title_data.get("mobileUrl", "")
- ranks = title_data.get("ranks", [])
+ if matches_word_groups_func(title, word_groups, filter_words, global_filters):
+ filtered_titles[title] = title_data
+ if filtered_titles:
+ filtered_new_titles[source_id] = filtered_titles
+ else:
+ filtered_new_titles = new_titles
+
+ original_new_count = sum(len(titles) for titles in new_titles.values()) if new_titles else 0
+ filtered_new_count = sum(len(titles) for titles in filtered_new_titles.values()) if filtered_new_titles else 0
+ if original_new_count > 0:
+ print(f"频率词过滤后:{filtered_new_count} 条新增热点匹配(原始 {original_new_count} 条)")
+
+ # 在增量模式下或配置关闭时隐藏新增新闻区域(但计数已完成)
+ hide_new_section = mode == "incremental" or not show_new_section
- processed_title = {
- "title": title,
+ if not hide_new_section and filtered_new_titles and id_to_name:
+ for source_id, titles_data in filtered_new_titles.items():
+ source_name = id_to_name.get(source_id, source_id)
+ source_titles = []
+
+ for title, title_data in titles_data.items():
+ url = title_data.get("url", "")
+ mobile_url = title_data.get("mobileUrl", "")
+ ranks = title_data.get("ranks", [])
+
+ processed_title = {
+ "title": title,
+ "source_name": source_name,
+ "time_display": "",
+ "count": 1,
+ "ranks": ranks,
+ "rank_threshold": rank_threshold,
+ "url": url,
+ "mobile_url": mobile_url,
+ "is_new": True,
+ "rank_timeline": title_data.get("rank_timeline", []),
+ }
+ source_titles.append(processed_title)
+
+ if source_titles:
+ processed_new_titles.append(
+ {
+ "source_id": source_id,
"source_name": source_name,
- "time_display": "",
- "count": 1,
- "ranks": ranks,
- "rank_threshold": rank_threshold,
- "url": url,
- "mobile_url": mobile_url,
- "is_new": True,
+ "titles": source_titles,
}
- source_titles.append(processed_title)
-
- if source_titles:
- processed_new_titles.append(
- {
- "source_id": source_id,
- "source_name": source_name,
- "titles": source_titles,
- }
- )
+ )
processed_stats = []
for stat in stats:
@@ -117,6 +114,7 @@ def prepare_report_data(
"url": title_data.get("url", ""),
"mobile_url": title_data.get("mobileUrl", ""),
"is_new": title_data.get("is_new", False),
+ "rank_timeline": title_data.get("rank_timeline", []),
}
processed_titles.append(processed_title)
@@ -129,13 +127,14 @@ def prepare_report_data(
}
)
+ # total_new_count 始终从过滤结果计算(用于头部统计),不受 hide_new_section 影响
+ total_new_count = sum(len(titles) for titles in filtered_new_titles.values())
+
return {
"stats": processed_stats,
"new_titles": processed_new_titles,
"failed_ids": failed_ids or [],
- "total_new_count": sum(
- len(source["titles"]) for source in processed_new_titles
- ),
+ "total_new_count": total_new_count,
}
@@ -154,6 +153,7 @@ def generate_html_report(
render_html_func: Optional[Callable] = None,
matches_word_groups_func: Optional[Callable] = None,
load_frequency_words_func: Optional[Callable] = None,
+ report_metadata: Optional[Dict] = None,
) -> str:
"""
生成 HTML 报告
@@ -202,6 +202,15 @@ def generate_html_report(
load_frequency_words_func,
)
+ if report_metadata:
+ _METADATA_KEYS = {
+ "hotlist_total", "platform_total", "rss_matched_count",
+ "rss_total_count", "rss_source_total", "rss_source_failed",
+ }
+ for key in _METADATA_KEYS:
+ if key in report_metadata:
+ report_data[key] = report_metadata[key]
+
# 渲染 HTML 内容
if render_html_func:
html_content = render_html_func(
diff --git a/trendradar/report/helpers.py b/trendradar/report/helpers.py
index 4898e94e92..c9e3b1daaf 100644
--- a/trendradar/report/helpers.py
+++ b/trendradar/report/helpers.py
@@ -6,7 +6,7 @@
"""
import re
-from typing import List
+from typing import Dict, List, Optional
def clean_title(title: str) -> str:
@@ -59,14 +59,49 @@ def html_escape(text: str) -> str:
)
-def format_rank_display(ranks: List[int], rank_threshold: int, format_type: str) -> str:
+def calculate_rank_trend(rank_timeline=None, ranks=None):
+ """根据排名时间线或排名列表计算趋势方向
+
+ Args:
+ rank_timeline: 按时间顺序的排名记录列表,如 [{"time": "10:00", "rank": 5}, ...]
+ ranks: 排名列表
+
+ Returns:
+ "up" (排名上升/数值变小), "down" (排名下降/数值变大), 或 None
+ """
+ prev_rank = None
+ curr_rank = None
+
+ if rank_timeline:
+ valid_ranks = [r["rank"] for r in rank_timeline if r.get("rank") is not None]
+ if len(valid_ranks) >= 2:
+ prev_rank = valid_ranks[-2]
+ curr_rank = valid_ranks[-1]
+ elif ranks and len(ranks) >= 2:
+ prev_rank = ranks[-2]
+ curr_rank = ranks[-1]
+
+ if prev_rank is not None and curr_rank is not None:
+ if curr_rank < prev_rank:
+ return "up"
+ elif curr_rank > prev_rank:
+ return "down"
+ return None
+
+
+def format_rank_display(
+ ranks: List[int],
+ rank_threshold: int,
+ format_type: str,
+ rank_timeline: Optional[List[Dict]] = None,
+) -> str:
"""格式化排名显示
根据不同平台类型生成对应格式的排名字符串。
当最小排名小于等于阈值时,使用高亮格式。
Args:
- ranks: 排名列表(可能包含重复值)
+ ranks: 排名列表(去重后的唯一值,用于范围显示)
rank_threshold: 高亮阈值,小于等于此值的排名会高亮显示
format_type: 平台类型,支持:
- "html": HTML格式
@@ -76,6 +111,7 @@ def format_rank_display(ranks: List[int], rank_threshold: int, format_type: str)
- "telegram": Telegram格式
- "slack": Slack格式
- 其他: 默认markdown格式
+ rank_timeline: 按时间顺序的排名记录列表(可选,用于计算趋势)
Returns:
格式化后的排名字符串,如 "[1]" 或 "[1 - 5]"
@@ -125,17 +161,7 @@ def format_rank_display(ranks: List[int], rank_threshold: int, format_type: str)
else:
rank_str = f"[{min_rank} - {max_rank}]"
- # 计算热度趋势
- trend_arrow = ""
- if len(ranks) >= 2:
- prev_rank = ranks[-2]
- curr_rank = ranks[-1]
- if curr_rank < prev_rank:
- trend_arrow = "🔺" # 排名上升(数值变小)
- elif curr_rank > prev_rank:
- trend_arrow = "🔻" # 排名下降(数值变大)
- else:
- trend_arrow = "➖" # 排名持平
- # len(ranks) == 1 时不显示趋势箭头(新上榜由 is_new 字段在 formatter.py 中处理)
+ trend = calculate_rank_trend(rank_timeline, ranks)
+ trend_arrow = {"up": "📈", "down": "📉"}.get(trend, "")
return f"{rank_str} {trend_arrow}" if trend_arrow else rank_str
diff --git a/trendradar/report/html.py b/trendradar/report/html.py
index 98f7b8c6f7..ff2f7b98a7 100644
--- a/trendradar/report/html.py
+++ b/trendradar/report/html.py
@@ -8,7 +8,7 @@ HTML 报告渲染模块
from datetime import datetime
from typing import Any, Dict, List, Optional, Callable
-from trendradar.report.helpers import html_escape
+from trendradar.report.helpers import html_escape, calculate_rank_trend
from trendradar.utils.time import convert_time_for_display
from trendradar.ai.formatter import render_ai_analysis_html_rich
@@ -174,17 +174,17 @@ def render_html_content(
top: 100%;
right: 0;
margin-top: 4px;
- background: rgba(30, 30, 50, 0.92);
+ background: rgba(255, 255, 255, 0.95);
backdrop-filter: blur(16px);
- border: 1px solid rgba(255, 255, 255, 0.15);
- border-radius: 8px;
+ border: 1px solid rgba(0, 0, 0, 0.08);
+ border-radius: 10px;
padding: 4px;
min-width: 140px;
opacity: 0;
visibility: hidden;
transform: translateY(-4px);
transition: all 0.2s ease;
- box-shadow: 0 8px 24px rgba(0,0,0,0.3);
+ box-shadow: 0 8px 24px rgba(0,0,0,0.12);
}
.save-btn-group:hover .save-dropdown-menu,
@@ -200,17 +200,18 @@ def render_html_content(
padding: 9px 14px;
background: none;
border: none;
- color: white;
+ color: #374151;
font-size: 13px;
cursor: pointer;
- border-radius: 5px;
+ border-radius: 6px;
text-align: left;
transition: background 0.15s;
white-space: nowrap;
}
.save-dropdown-item:hover {
- background: rgba(255, 255, 255, 0.15);
+ background: #f3f4f6;
+ color: #4f46e5;
}
.dropdown-icon {
@@ -368,11 +369,11 @@ def render_html_content(
.news-number.copied .num-text { opacity: 0 !important; }
.news-number.copied .copy-icon { opacity: 1 !important; }
body.dark-mode .news-item:hover .news-number {
- background: #2a2a5a;
- color: #8ab4f8;
+ background: #4338ca;
+ color: #e0e7ff;
}
body.dark-mode .news-number.copied {
- background: #14532d !important;
+ background: #166534 !important;
}
.news-content {
@@ -422,6 +423,12 @@ def render_html_content(
.rank-num.top { background: #dc2626; }
.rank-num.high { background: #ea580c; }
+ .trend-up, .trend-down {
+ font-size: 12px;
+ margin-left: 2px;
+ vertical-align: middle;
+ }
+
.time-info {
color: #999;
font-size: 11px;
@@ -863,6 +870,15 @@ def render_html_content(
font-size: 14px;
}
+ .ai-warning {
+ padding: 16px;
+ background: #fffbeb;
+ border: 1px solid #fde68a;
+ border-radius: 8px;
+ color: #92400e;
+ font-size: 14px;
+ }
+
.ai-info {
padding: 16px;
background: #f0f9ff;
@@ -912,23 +928,76 @@ def render_html_content(
body.wide-mode .standalone-group { margin-bottom: 0; }
/* Tab 栏 */
- .tab-bar {
+ .tab-bar-wrapper {
+ position: sticky;
+ top: 0;
+ z-index: 10;
+ background: white;
display: none;
+ margin-bottom: 20px;
+ align-items: stretch;
+ border-bottom: 2px solid #e5e7eb;
+ }
+ body.wide-mode .tab-bar-wrapper { display: flex; }
+ body.wide-mode .tab-bar-wrapper.tab-hidden { display: none; }
+
+ .tab-bar {
+ flex: 1;
+ min-width: 0;
+ display: flex;
overflow-x: auto;
white-space: nowrap;
padding: 8px 0 12px 0;
- margin-bottom: 20px;
- border-bottom: 2px solid #e5e7eb;
-webkit-overflow-scrolling: touch;
- scrollbar-width: thin;
- position: sticky;
- top: 0;
- background: white;
- z-index: 10;
+ scrollbar-width: none;
+ -ms-overflow-style: none;
gap: 4px;
+ mask-image: linear-gradient(to right, transparent, black 24px, black calc(100% - 24px), transparent);
+ -webkit-mask-image: linear-gradient(to right, transparent, black 24px, black calc(100% - 24px), transparent);
+ }
+ .tab-bar::-webkit-scrollbar { display: none; }
+ .tab-bar.scroll-start {
+ mask-image: linear-gradient(to right, black, black calc(100% - 24px), transparent);
+ -webkit-mask-image: linear-gradient(to right, black, black calc(100% - 24px), transparent);
+ }
+ .tab-bar.scroll-end {
+ mask-image: linear-gradient(to right, transparent, black 24px, black);
+ -webkit-mask-image: linear-gradient(to right, transparent, black 24px, black);
+ }
+ .tab-bar.scroll-start.scroll-end,
+ .tab-bar.no-overflow {
+ mask-image: none;
+ -webkit-mask-image: none;
+ }
+
+ .tab-arrow {
+ flex-shrink: 0;
+ width: 28px;
+ display: none;
+ align-items: center;
+ justify-content: center;
+ background: none;
+ border: none;
+ color: #9ca3af;
+ font-size: 20px;
+ font-weight: 300;
+ cursor: pointer;
+ padding: 0;
+ transition: color 0.15s ease;
+ }
+ .tab-arrow:hover { color: #4f46e5; }
+ .tab-arrow.visible { display: flex; }
+
+ .tab-scroll-indicator {
+ position: absolute;
+ bottom: 0;
+ left: 0;
+ width: 0;
+ height: 2px;
+ background: #4f46e5;
+ border-radius: 0 1px 1px 0;
+ transition: width 0.1s linear;
}
- body.wide-mode .tab-bar { display: flex; }
- body.wide-mode .tab-bar.tab-hidden { display: none; }
.tab-btn {
display: inline-flex;
@@ -938,7 +1007,7 @@ def render_html_content(
border: none;
background: #f3f4f6;
color: #6b7280;
- border-radius: 8px 8px 0 0;
+ border-radius: 8px;
cursor: pointer;
font-size: 13px;
font-weight: 500;
@@ -955,9 +1024,6 @@ def render_html_content(
border-radius: 10px;
}
.tab-btn.active .tab-count { background: rgba(255,255,255,0.3); }
- .tab-bar::-webkit-scrollbar { height: 4px; }
- .tab-bar::-webkit-scrollbar-track { background: #f1f5f9; border-radius: 2px; }
- .tab-bar::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 2px; }
/* 搜索栏 */
.search-bar { display: none; padding: 0 0 16px 0; }
@@ -1103,83 +1169,188 @@ def render_html_content(
transform: translateY(-1px);
}
- /* 暗色模式 */
+ /* ===== 暗色模式 ===== */
body.dark-mode {
- background: #1a1a2e;
- color: #e0e0e0;
+ background: #0f172a;
+ color: #e2e8f0;
}
body.dark-mode .container {
- background: #16213e;
- box-shadow: 0 2px 16px rgba(0,0,0,0.3);
+ background: #1e293b;
+ box-shadow: 0 4px 24px rgba(0,0,0,0.4);
}
body.dark-mode .header {
- background: linear-gradient(135deg, #0f3460 0%, #533483 100%);
+ background: linear-gradient(135deg, #3730a3 0%, #7c3aed 100%);
}
body.dark-mode .content {
- background: #16213e;
+ background: #1e293b;
+ }
+
+ /* 文字颜色 */
+ body.dark-mode .word-name,
+ body.dark-mode .new-section-title,
+ body.dark-mode .standalone-name,
+ body.dark-mode .new-item-title,
+ body.dark-mode .project-name { color: #f1f5f9; }
+ body.dark-mode .word-count,
+ body.dark-mode .word-index,
+ body.dark-mode .source-name,
+ body.dark-mode .time-info,
+ body.dark-mode .feed-count,
+ body.dark-mode .new-source-title,
+ body.dark-mode .standalone-count,
+ body.dark-mode .rss-section-count,
+ body.dark-mode .standalone-section-count,
+ body.dark-mode .news-meta,
+ body.dark-mode .rss-time,
+ body.dark-mode .rss-author,
+ body.dark-mode .rss-summary { color: #94a3b8; }
+ body.dark-mode .info-value { color: white; }
+
+ /* 链接 */
+ body.dark-mode .news-title a,
+ body.dark-mode .rss-title a,
+ body.dark-mode .new-item a,
+ body.dark-mode .standalone-item a,
+ body.dark-mode .rss-link { color: #93c5fd; }
+ body.dark-mode .news-title a:visited { color: #c4b5fd; }
+ body.dark-mode .rss-link:hover { color: #6ee7b7; }
+
+ /* 强调色 */
+ body.dark-mode .keyword-tag {
+ background: rgba(99,102,241,0.15);
+ color: #a5b4fc;
+ }
+ body.dark-mode .count-info { color: #6ee7b7; }
+ body.dark-mode .rss-source,
+ body.dark-mode .feed-name,
+ body.dark-mode .rss-section-title,
+ body.dark-mode .standalone-section-title { color: #6ee7b7; }
+
+ /* 边框与分割线 */
+ body.dark-mode .word-header,
+ body.dark-mode .news-item,
+ body.dark-mode .new-item,
+ body.dark-mode .standalone-item,
+ body.dark-mode .new-source-title,
+ body.dark-mode .standalone-header { border-bottom-color: #334155; }
+ body.dark-mode .section-divider { border-top-color: #334155; }
+ body.dark-mode .feed-header { border-bottom-color: #166534; }
+ body.dark-mode .tab-bar { border-bottom-color: #334155; }
+
+ /* 序号圆圈 */
+ body.dark-mode .news-number,
+ body.dark-mode .new-item-number {
+ background: #334155;
+ color: #94a3b8;
}
- body.dark-mode .word-header {
- border-bottom-color: #2a2a4a;
+
+ /* 折叠 hover */
+ body.dark-mode .word-header.collapsible:hover { background: #253347; }
+
+ /* Tab 栏 */
+ body.dark-mode .tab-bar-wrapper {
+ background: #1e293b;
+ border-bottom-color: #334155;
}
- body.dark-mode .word-header.collapsible:hover {
- background: #1a1a3e;
+ body.dark-mode .tab-arrow { color: #64748b; }
+ body.dark-mode .tab-arrow:hover { color: #c4b5fd; }
+ body.dark-mode .tab-scroll-indicator { background: #818cf8; }
+ body.dark-mode .tab-btn {
+ background: #334155;
+ color: #94a3b8;
}
- body.dark-mode .news-item {
- border-bottom-color: #2a2a4a;
+ body.dark-mode .tab-btn:hover {
+ background: #475569;
+ color: #e2e8f0;
}
- body.dark-mode .news-title a {
- color: #8ab4f8;
+ body.dark-mode .tab-btn.active {
+ background: #6d28d9;
+ color: white;
}
- body.dark-mode .news-title a:visited {
- color: #c58af9;
+ body.dark-mode .tab-bar::-webkit-scrollbar-track { background: #1e293b; }
+ body.dark-mode .tab-bar::-webkit-scrollbar-thumb { background: #475569; }
+
+ /* 搜索框 */
+ body.dark-mode .search-input {
+ background: #1e293b;
+ border-color: #334155;
+ color: #e2e8f0;
}
- body.dark-mode .news-meta {
- color: #888;
+ body.dark-mode .search-input:focus {
+ border-color: #818cf8;
+ box-shadow: 0 0 0 3px rgba(129,140,248,0.15);
}
- body.dark-mode .tab-bar {
- background: #16213e;
- border-bottom-color: #2a2a4a;
+ body.dark-mode .search-input::placeholder { color: #64748b; }
+
+ /* RSS 卡片 */
+ body.dark-mode .rss-item {
+ background: #1a2e25;
+ border-left-color: #059669;
}
- body.dark-mode .tab-btn {
- color: #aaa;
+
+ /* AI 分析区 */
+ body.dark-mode .ai-section {
+ background: linear-gradient(135deg, #1e1b4b 0%, #1e293b 100%);
+ border-color: #334155;
}
- body.dark-mode .tab-btn.active {
- color: #8ab4f8;
- border-bottom-color: #8ab4f8;
+ body.dark-mode .ai-section-title { color: #a5b4fc; }
+ body.dark-mode .ai-section-badge { background: #4f46e5; }
+ body.dark-mode .ai-block {
+ background: #1e293b;
+ border-color: #334155;
+ box-shadow: 0 1px 3px rgba(0,0,0,0.2);
}
- body.dark-mode .tab-btn:hover {
- color: #ccc;
- background: rgba(255,255,255,0.05);
+ body.dark-mode .ai-block-title { color: #a5b4fc; }
+ body.dark-mode .ai-block-content { color: #cbd5e1; }
+ body.dark-mode .ai-warning {
+ background: #422006;
+ border-color: #854d0e;
+ color: #fbbf24;
}
- body.dark-mode .search-input {
- background: #1a1a3e;
- border-color: #2a2a4a;
- color: #e0e0e0;
+ body.dark-mode .ai-error {
+ background: #450a0a;
+ border-color: #991b1b;
+ color: #fca5a5;
}
- body.dark-mode .search-input:focus {
- border-color: #8ab4f8;
+ body.dark-mode .ai-info {
+ background: #172554;
+ border-color: #1e40af;
+ color: #93c5fd;
}
- /* dark fab-btn 已在 .fab-btn 中处理 */
- body.dark-mode .footer {
- background: #0f3460;
- color: rgba(255,255,255,0.7);
+
+ /* 错误区 */
+ body.dark-mode .error-section {
+ background: #1c1917;
+ border-color: #78350f;
}
- body.dark-mode .rss-item,
- body.dark-mode .new-item,
- body.dark-mode .standalone-item {
- border-bottom-color: #2a2a4a;
+ body.dark-mode .error-title { color: #fca5a5; }
+ body.dark-mode .error-item { color: #f87171; }
+
+ /* Footer */
+ body.dark-mode .footer {
+ background: #0f172a;
+ border-top-color: #334155;
+ color: #94a3b8;
}
- body.dark-mode .rss-title a,
- body.dark-mode .new-item a,
- body.dark-mode .standalone-item a {
- color: #8ab4f8;
+ body.dark-mode .footer-link { color: #93c5fd; }
+ body.dark-mode .footer-link:hover { color: #c4b5fd; }
+
+ /* 悬浮按钮 */
+ body.dark-mode .fab-btn { background: #6d28d9; }
+ body.dark-mode .fab-btn:hover { background: #7c3aed; }
+
+ /* 下拉菜单 */
+ body.dark-mode .save-dropdown-menu {
+ background: rgba(30,41,59,0.95);
+ border-color: #475569;
+ box-shadow: 0 8px 24px rgba(0,0,0,0.4);
}
- body.dark-mode .ai-block {
- background: #1a1a3e;
- border-color: #2a2a4a;
+ body.dark-mode .save-dropdown-item {
+ color: #e2e8f0;
}
- body.dark-mode .info-value {
- color: white;
+ body.dark-mode .save-dropdown-item:hover {
+ background: #334155;
+ color: #c4b5fd;
}
/* 暗色模式切换按钮 */
@@ -1249,63 +1420,139 @@ def render_html_content(
<button class="toggle-wide-btn" onclick="toggleWideMode()" title="切换宽屏/窄屏">⛶</button>
<button class="toggle-dark-btn" onclick="toggleDarkMode()" title="切换暗色/亮色">☽</button>
<div class="save-btn-group">
- <button class="save-btn" onclick="saveAsImage()">导出</button>
+ <button class="save-btn" onclick="saveAsImage(event)">导出</button>
<button class="save-dropdown-trigger">▾</button>
<div class="save-dropdown-menu">
- <button class="save-dropdown-item" onclick="saveAsImage()"><svg class="dropdown-icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5"><rect x="2" y="2" width="12" height="12" rx="2"/><circle cx="8" cy="7.5" r="2.5"/><path d="M12 4h.01"/></svg>整页截图</button>
- <button class="save-dropdown-item" onclick="saveAsMultipleImages()"><svg class="dropdown-icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5"><rect x="1" y="4" width="10" height="10" rx="1.5"/><path d="M5 4V2.5A1.5 1.5 0 016.5 1h7A1.5 1.5 0 0115 2.5v7a1.5 1.5 0 01-1.5 1.5H12"/></svg>分段截图</button>
+ <button class="save-dropdown-item" onclick="saveAsImage(event)"><svg class="dropdown-icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5"><rect x="2" y="2" width="12" height="12" rx="2"/><circle cx="8" cy="7.5" r="2.5"/><path d="M12 4h.01"/></svg>整页截图</button>
+ <button class="save-dropdown-item" onclick="saveAsMultipleImages(event)"><svg class="dropdown-icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5"><rect x="1" y="4" width="10" height="10" rx="1.5"/><path d="M5 4V2.5A1.5 1.5 0 016.5 1h7A1.5 1.5 0 0115 2.5v7a1.5 1.5 0 01-1.5 1.5H12"/></svg>分段截图</button>
<button class="save-dropdown-item" onclick="saveAsMarkdown()"><svg class="dropdown-icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M2.5 2h11A1.5 1.5 0 0115 3.5v9a1.5 1.5 0 01-1.5 1.5h-11A1.5 1.5 0 011 12.5v-9A1.5 1.5 0 012.5 2z"/><path d="M4 11V5l2.5 3L9 5v6"/><path d="M11.5 8v3m0 0l-1.5-2m1.5 2l1.5-2"/></svg>Markdown</button>
</div>
</div>
</div>
<div class="header-title">热点新闻分析</div>
- <div class="header-info">
- <div class="info-item">
- <span class="info-label">报告类型</span>
- <span class="info-value">"""
+ <div class="header-info">"""
+
+ # 使用提供的时间函数或默认 datetime.now
+ if get_time_func:
+ now = get_time_func()
+ else:
+ now = datetime.now()
- # 处理报告类型显示(根据 mode 直接显示)
+ # 处理报告类型显示
if mode == "current":
- html += "当前榜单"
+ mode_display = "当前榜单"
elif mode == "incremental":
- html += "增量分析"
+ mode_display = "增量分析"
else:
- html += "全天汇总"
+ mode_display = "全天汇总"
- html += """</span>
- </div>
+ # 计算各项数据
+ hot_news_count = sum(len(stat["titles"]) for stat in report_data["stats"])
+ new_count = report_data.get("total_new_count", 0)
+
+ # 从元数据获取 RSS 和平台信息
+ hotlist_total = report_data.get("hotlist_total", total_titles)
+ platform_total = report_data.get("platform_total", 0)
+ failed_count = len(report_data.get("failed_ids", []))
+ platform_success = platform_total - failed_count if platform_total else 0
+ rss_matched = report_data.get("rss_matched_count", 0)
+ rss_total = report_data.get("rss_total_count", 0)
+ rss_source_total = report_data.get("rss_source_total", 0)
+ rss_source_failed = report_data.get("rss_source_failed", 0)
+ rss_source_success = max(0, rss_source_total - rss_source_failed)
+
+ # 1. 报告类型
+ html += f"""
<div class="info-item">
- <span class="info-label">新闻总数</span>
- <span class="info-value">"""
+ <span class="info-label">报告类型</span>
+ <span class="info-value">{mode_display}</span>
+ </div>"""
- html += f"{total_titles} 条"
+ # 2. 生成时间
+ html += f"""
+ <div class="info-item">
+ <span class="info-label">生成时间</span>
+ <span class="info-value">{now.strftime("%m-%d %H:%M")}</span>
+ </div>"""
- # 计算筛选后的热点新闻数量
- hot_news_count = sum(len(stat["titles"]) for stat in report_data["stats"])
+ # 3. 热榜命中
+ html += f"""
+ <div class="info-item">
+ <span class="info-label">热榜命中</span>
+ <span class="info-value">{hot_news_count} / {hotlist_total}</span>
+ </div>"""
- html += """</span>
- </div>
+ # 4. RSS 命中
+ if rss_source_total > 0:
+ rss_value = f"{rss_matched} / {rss_total}"
+ else:
+ rss_value = "未启用"
+ html += f"""
+ <div class="info-item">
+ <span class="info-label">RSS 命中</span>
+ <span class="info-value">{rss_value}</span>
+ </div>"""
+
+ # 5. 热榜平台
+ if platform_total > 0:
+ platform_value = f"{platform_success}/{platform_total}"
+ else:
+ platform_value = "--"
+ html += f"""
<div class="info-item">
- <span class="info-label">热点新闻</span>
- <span class="info-value">"""
+ <span class="info-label">热榜平台</span>
+ <span class="info-value">{platform_value}</span>
+ </div>"""
- html += f"{hot_news_count} 条"
+ # 6. RSS 源
+ if rss_source_total > 0:
+ rss_source_value = f"{rss_source_success}/{rss_source_total}"
+ else:
+ rss_source_value = "--"
+ html += f"""
+ <div class="info-item">
+ <span class="info-label">RSS 源</span>
+ <span class="info-value">{rss_source_value}</span>
+ </div>"""
- html += """</span>
- </div>
+ # 7. 新增热点(热榜新增 + RSS 新增)
+ rss_new_count = sum(len(stat.get("titles", [])) for stat in (rss_new_items or []))
+ total_new = new_count + rss_new_count
+ new_value = f"{new_count} + {rss_new_count}" if total_new > 0 else "0"
+ html += f"""
<div class="info-item">
- <span class="info-label">生成时间</span>
- <span class="info-value">"""
+ <span class="info-label">新增热点</span>
+ <span class="info-value">{new_value}</span>
+ </div>"""
- # 使用提供的时间函数或默认 datetime.now
- if get_time_func:
- now = get_time_func()
+ # 8. AI 分析
+ if ai_analysis and getattr(ai_analysis, "success", False):
+ hotlist_analyzed = getattr(ai_analysis, "hotlist_analyzed", 0)
+ rss_analyzed = getattr(ai_analysis, "rss_analyzed", 0)
+ standalone_analyzed = getattr(ai_analysis, "standalone_analyzed", 0)
+ ai_include_rss = getattr(ai_analysis, "include_rss", True)
+ ai_include_standalone = getattr(ai_analysis, "include_standalone", False)
+
+ ai_parts = [str(hotlist_analyzed)]
+ if ai_include_rss:
+ ai_parts.append(str(rss_analyzed))
+ if ai_include_standalone:
+ ai_parts.append(str(standalone_analyzed))
+ ai_value = " + ".join(ai_parts) if sum(int(p) for p in ai_parts) > 0 else "0"
+ elif ai_analysis:
+ if getattr(ai_analysis, "skipped", False):
+ ai_value = "已跳过"
+ else:
+ ai_value = "待配置"
else:
- now = datetime.now()
- html += now.strftime("%m-%d %H:%M")
+ ai_value = "未启用"
+ html += f"""
+ <div class="info-item">
+ <span class="info-label">AI 分析</span>
+ <span class="info-value">{ai_value}</span>
+ </div>"""
- html += """</span>
- </div>
+ html += """
</div>
</div>
@@ -1333,13 +1580,14 @@ def render_html_content(
total_count = len(report_data["stats"])
# 生成 Tab 栏 HTML
- tab_bar_html = '<div class="tab-bar">'
+ total_news_count = sum(s["count"] for s in report_data["stats"])
+ tab_bar_html = '<div class="tab-bar-wrapper"><div class="tab-bar">'
+ tab_bar_html += f'<button class="tab-btn" data-tab-index="all">全部<span class="tab-count">{total_news_count}</span></button>'
for tab_i, tab_stat in enumerate(report_data["stats"]):
escaped_tab_word = html_escape(tab_stat["word"])
tab_count = tab_stat["count"]
tab_bar_html += f'<button class="tab-btn" data-tab-index="{tab_i}">{escaped_tab_word}<span class="tab-count">{tab_count}</span></button>'
- tab_bar_html += '<button class="tab-btn" data-tab-index="all">全部</button>'
- tab_bar_html += '</div>'
+ tab_bar_html += '</div></div>'
for i, stat in enumerate(report_data["stats"], 1):
count = stat["count"]
@@ -1405,7 +1653,16 @@ def render_html_content(
else:
rank_text = f"{min_rank}-{max_rank}"
- stats_html += f'<span class="rank-num {rank_class}">{rank_text}</span>'
+ # 计算趋势箭头
+ rank_timeline = title_data.get("rank_timeline", [])
+ trend = calculate_rank_trend(rank_timeline, ranks)
+ trend_html = ""
+ if trend == "up":
+ trend_html = '<span class="trend-up">📈</span>'
+ elif trend == "down":
+ trend_html = '<span class="trend-down">📉</span>'
+
+ stats_html += f'<span class="rank-num {rank_class}">{rank_text}</span>{trend_html}'
# 处理时间显示
time_display = title_data.get("time_display", "")
@@ -1984,12 +2241,67 @@ def render_html_content(
if (btn) btn.textContent = isDark ? '☀' : '☽';
}
+ function initTabScroll(tabBar) {
+ var wrapper = tabBar.closest('.tab-bar-wrapper') || tabBar.parentNode;
+ var leftArrow = wrapper.querySelector('.tab-arrow-left');
+ var rightArrow = wrapper.querySelector('.tab-arrow-right');
+ var indicator = wrapper.querySelector('.tab-scroll-indicator');
+ if (!leftArrow) {
+ leftArrow = document.createElement('button');
+ leftArrow.className = 'tab-arrow tab-arrow-left';
+ leftArrow.innerHTML = '‹';
+ rightArrow = document.createElement('button');
+ rightArrow.className = 'tab-arrow tab-arrow-right';
+ rightArrow.innerHTML = '›';
+ indicator = document.createElement('div');
+ indicator.className = 'tab-scroll-indicator';
+ wrapper.insertBefore(leftArrow, tabBar);
+ tabBar.after(rightArrow);
+ wrapper.appendChild(indicator);
+ }
+ var scrollStep = 200;
+ leftArrow.addEventListener('click', function(e) {
+ e.stopPropagation();
+ tabBar.scrollBy({ left: -scrollStep, behavior: 'smooth' });
+ });
+ rightArrow.addEventListener('click', function(e) {
+ e.stopPropagation();
+ tabBar.scrollBy({ left: scrollStep, behavior: 'smooth' });
+ });
+ function updateArrows() {
+ var sl = tabBar.scrollLeft;
+ var sw = tabBar.scrollWidth;
+ var cw = tabBar.clientWidth;
+ var noOverflow = sw <= cw + 1;
+ var atStart = sl <= 1;
+ var atEnd = sl + cw >= sw - 1;
+ leftArrow.classList.toggle('visible', !noOverflow && !atStart);
+ rightArrow.classList.toggle('visible', !noOverflow && !atEnd);
+ tabBar.classList.toggle('scroll-start', atStart);
+ tabBar.classList.toggle('scroll-end', atEnd);
+ tabBar.classList.toggle('no-overflow', noOverflow);
+ var progress = noOverflow ? 0 : sl / (sw - cw);
+ indicator.style.width = (progress * 100) + '%';
+ }
+ tabBar.addEventListener('scroll', updateArrows, { passive: true });
+ tabBar.addEventListener('wheel', function(e) {
+ if (Math.abs(e.deltaY) > Math.abs(e.deltaX)) {
+ tabBar.scrollLeft += e.deltaY;
+ e.preventDefault();
+ }
+ }, { passive: false });
+ updateArrows();
+ new ResizeObserver(updateArrows).observe(tabBar);
+ }
+
function initTabs() {
- var tabBar = document.querySelector('.tab-bar');
+ var wrapper = document.querySelector('.tab-bar-wrapper');
+ var tabBar = wrapper ? wrapper.querySelector('.tab-bar') : null;
if (!tabBar) return;
var tabs = tabBar.querySelectorAll('.tab-btn');
var groups = document.querySelectorAll('.word-group[data-tab-index]');
initTabVisibility();
+ initTabScroll(tabBar);
function activateTab(index) {
tabs.forEach(function(t) { t.classList.remove('active'); });
@@ -2004,11 +2316,13 @@ def render_html_content(
tabs.forEach(function(t) {
if (parseInt(t.dataset.tabIndex) === idx) t.classList.add('active');
});
- if (document.body.classList.contains('wide-mode') && !tabBar.classList.contains('tab-hidden')) {
+ if (document.body.classList.contains('wide-mode') && !wrapper.classList.contains('tab-hidden')) {
groups.forEach(function(g) {
g.style.display = (parseInt(g.dataset.tabIndex) === idx) ? '' : 'none';
});
}
+ var activeBtn = tabBar.querySelector('.tab-btn.active');
+ if (activeBtn) activeBtn.scrollIntoView({ block: 'nearest', inline: 'nearest', behavior: 'smooth' });
try { history.replaceState(null, '', '#tab-' + idx); } catch(e) {}
}
@@ -2039,49 +2353,63 @@ def render_html_content(
}
function initTabVisibility() {
- var tabBar = document.querySelector('.tab-bar');
- if (!tabBar) return;
+ var wrapper = document.querySelector('.tab-bar-wrapper');
+ if (!wrapper) return;
+ var tabBar = wrapper.querySelector('.tab-bar');
var groups = document.querySelectorAll('.word-group[data-tab-index]');
var isWide = document.body.classList.contains('wide-mode');
if (!isWide || groups.length <= 2) {
- tabBar.classList.add('tab-hidden');
+ wrapper.classList.add('tab-hidden');
groups.forEach(function(g) { g.style.display = ''; });
} else {
- tabBar.classList.remove('tab-hidden');
+ wrapper.classList.remove('tab-hidden');
var activeTab = tabBar.querySelector('.tab-btn.active');
if (activeTab) { activeTab.click(); }
else {
- var firstTab = tabBar.querySelector('.tab-btn');
+ var firstTab = tabBar.querySelector('.tab-btn[data-tab-index="0"]');
if (firstTab) firstTab.click();
}
}
}
- function handleSearch(query) {
- query = query.toLowerCase();
- document.querySelectorAll('.news-item').forEach(function(item) {
- var title = (item.querySelector('.news-title') || {}).textContent || '';
- item.style.display = (!query || title.toLowerCase().indexOf(query) !== -1) ? '' : 'none';
- });
- document.querySelectorAll('.rss-item').forEach(function(item) {
- var title = (item.querySelector('.rss-title') || {}).textContent || '';
- item.style.display = (!query || title.toLowerCase().indexOf(query) !== -1) ? '' : 'none';
- });
- }
+ var handleSearch = (function() {
+ var timer = null;
+ return function(query) {
+ clearTimeout(timer);
+ timer = setTimeout(function() {
+ query = query.toLowerCase();
+ document.querySelectorAll('.news-item').forEach(function(item) {
+ var title = (item.querySelector('.news-title') || {}).textContent || '';
+ item.style.display = (!query || title.toLowerCase().indexOf(query) !== -1) ? '' : 'none';
+ });
+ document.querySelectorAll('.rss-item').forEach(function(item) {
+ var title = (item.querySelector('.rss-title') || {}).textContent || '';
+ item.style.display = (!query || title.toLowerCase().indexOf(query) !== -1) ? '' : 'none';
+ });
+ }, 200);
+ };
+ })();
function initBackToTop() {
var fabBar = document.querySelector('.fab-bar');
if (!fabBar) return;
+ var ticking = false;
window.addEventListener('scroll', function() {
- fabBar.classList.toggle('visible', window.scrollY > 300);
+ if (!ticking) {
+ requestAnimationFrame(function() {
+ fabBar.classList.toggle('visible', window.scrollY > 300);
+ ticking = false;
+ });
+ ticking = true;
+ }
});
}
function initCollapse() {
document.querySelectorAll('.word-header').forEach(function(header) {
header.addEventListener('click', function() {
- var tabBar = document.querySelector('.tab-bar');
- if (document.body.classList.contains('wide-mode') && tabBar && !tabBar.classList.contains('tab-hidden')) return;
+ var wrapper = document.querySelector('.tab-bar-wrapper');
+ if (document.body.classList.contains('wide-mode') && wrapper && !wrapper.classList.contains('tab-hidden')) return;
var group = header.closest('.word-group');
if (group) group.classList.toggle('collapsed');
});
@@ -2091,8 +2419,8 @@ def render_html_content(
function initCollapseVisibility() {
var headers = document.querySelectorAll('.word-header');
- var tabBar = document.querySelector('.tab-bar');
- var isTabMode = document.body.classList.contains('wide-mode') && tabBar && !tabBar.classList.contains('tab-hidden');
+ var wrapper = document.querySelector('.tab-bar-wrapper');
+ var isTabMode = document.body.classList.contains('wide-mode') && wrapper && !wrapper.classList.contains('tab-hidden');
headers.forEach(function(h) {
if (isTabMode) { h.classList.remove('collapsible'); }
else { h.classList.add('collapsible'); }
@@ -2110,6 +2438,7 @@ def render_html_content(
if (!tabBar) return;
var groups = document.querySelectorAll('.standalone-group[data-standalone-tab]');
var btns = tabBar.querySelectorAll('.tab-btn[data-standalone-tab]');
+ initTabScroll(tabBar);
function activateStandaloneTab(val) {
btns.forEach(function(b) {
@@ -2169,7 +2498,7 @@ def render_html_content(
g.style.display = '';
}
});
- document.querySelectorAll('.tab-bar, .standalone-tab-bar, .search-bar, .fab-bar, .toggle-wide-btn').forEach(function(el) {
+ document.querySelectorAll('.tab-bar-wrapper, .standalone-tab-bar, .search-bar, .fab-bar, .toggle-wide-btn').forEach(function(el) {
el.dataset.prevDisplay = el.style.display || '';
el.style.display = 'none';
});
@@ -2194,7 +2523,7 @@ def render_html_content(
if (standaloneGroups[i]) standaloneGroups[i].style.display = 'none';
});
}
- document.querySelectorAll('.tab-bar, .standalone-tab-bar, .search-bar, .fab-bar, .toggle-wide-btn').forEach(function(el) {
+ document.querySelectorAll('.tab-bar-wrapper, .standalone-tab-bar, .search-bar, .fab-bar, .toggle-wide-btn').forEach(function(el) {
el.style.display = el.dataset.prevDisplay || '';
delete el.dataset.prevDisplay;
});
@@ -2202,7 +2531,6 @@ def render_html_content(
el.style.display = el.dataset.prevDisplay || ''; delete el.dataset.prevDisplay;
});
document.querySelectorAll('.reading-progress').forEach(function(el) { el.style.display = ''; });
- document.querySelectorAll('.reading-progress').forEach(function(el) { el.style.display = ''; });
document.querySelectorAll('.header-watermark').forEach(function(el) { el.style.display = ''; });
initTabVisibility();
initCollapseVisibility();
@@ -2213,9 +2541,10 @@ def render_html_content(
// ===== 截图功能 =====
- async function saveAsImage() {
- const button = event.target;
- const originalText = button.textContent;
+ async function saveAsImage(e) {
+ const button = e.target.closest('.save-dropdown-item') || e.target;
+ const originalHTML = button.innerHTML;
+ var screenshotState = null;
try {
button.textContent = '生成中...';
@@ -2226,7 +2555,7 @@ def render_html_content(
await new Promise(resolve => setTimeout(resolve, 200));
// 截图前准备:切回窄屏布局
- var screenshotState = prepareForScreenshot();
+ screenshotState = prepareForScreenshot();
// 截图前隐藏按钮
const buttons = document.querySelector('.save-buttons');
@@ -2273,31 +2602,32 @@ def render_html_content(
button.textContent = '保存成功!';
setTimeout(() => {
- button.textContent = originalText;
+ button.innerHTML = originalHTML;
button.disabled = false;
}, 2000);
} catch (error) {
const buttons = document.querySelector('.save-buttons');
buttons.style.visibility = 'visible';
- restoreAfterScreenshot(screenshotState);
+ if (screenshotState) { restoreAfterScreenshot(screenshotState); }
button.textContent = '保存失败';
setTimeout(() => {
- button.textContent = originalText;
+ button.innerHTML = originalHTML;
button.disabled = false;
}, 2000);
}
}
- async function saveAsMultipleImages() {
- const button = event.target;
- const originalText = button.textContent;
+ async function saveAsMultipleImages(e) {
+ const button = e.target.closest('.save-dropdown-item') || e.target;
+ const originalHTML = button.innerHTML;
const container = document.querySelector('.container');
const scale = 1.5;
const maxHeight = 5000 / scale;
- var screenshotState2 = prepareForScreenshot();
+ var screenshotState2 = null;
try {
+ screenshotState2 = prepareForScreenshot();
button.textContent = '分析中...';
button.disabled = true;
@@ -2506,7 +2836,7 @@ def render_html_content(
button.textContent = `已保存 ${segments.length} 张图片!`;
restoreAfterScreenshot(screenshotState2);
setTimeout(() => {
- button.textContent = originalText;
+ button.innerHTML = originalHTML;
button.disabled = false;
}, 2000);
@@ -2514,10 +2844,10 @@ def render_html_content(
console.error('分段保存失败:', error);
const buttons = document.querySelector('.save-buttons');
buttons.style.visibility = 'visible';
- restoreAfterScreenshot(screenshotState2);
+ if (screenshotState2) { restoreAfterScreenshot(screenshotState2); }
button.textContent = '保存失败';
setTimeout(() => {
- button.textContent = originalText;
+ button.innerHTML = originalHTML;
button.disabled = false;
}, 2000);
}
@@ -2626,6 +2956,73 @@ def render_html_content(
});
}
+ // RSS 订阅更新区
+ var rssSection = document.querySelector('.rss-section');
+ if (rssSection) {
+ var rssSectionTitle = rssSection.querySelector('.rss-section-title');
+ lines.push('## ' + (rssSectionTitle ? rssSectionTitle.textContent.trim() : 'RSS 订阅更新'));
+ lines.push('');
+ var feedGroups = rssSection.querySelectorAll('.feed-group');
+ feedGroups.forEach(function(group) {
+ var feedName = group.querySelector('.feed-name');
+ var feedCount = group.querySelector('.feed-count');
+ if (feedName) {
+ lines.push('### ' + feedName.textContent.trim() + (feedCount ? ' (' + feedCount.textContent.trim() + ')' : ''));
+ lines.push('');
+ }
+ var items = group.querySelectorAll('.rss-item');
+ items.forEach(function(item, i) {
+ var titleEl = item.querySelector('.rss-title a');
+ var titleText = titleEl ? titleEl.textContent.trim() : '';
+ var url = titleEl ? (titleEl.href || '') : '';
+ if (!titleText) return;
+ var meta = [];
+ var time = item.querySelector('.rss-time');
+ if (time) meta.push(time.textContent.trim());
+ var author = item.querySelector('.rss-author');
+ if (author) meta.push(author.textContent.trim());
+ var line = (i + 1) + '. ';
+ if (url) { line += '[' + titleText.replace(/[\\[\\]]/g, '') + '](' + url + ')'; }
+ else { line += titleText; }
+ if (meta.length) line += ' `' + meta.join(' | ') + '`';
+ lines.push(line);
+ });
+ lines.push('');
+ });
+ }
+
+ // AI 热点分析区
+ var aiSection = document.querySelector('.ai-section');
+ if (aiSection) {
+ var aiError = aiSection.querySelector('.ai-error') || aiSection.querySelector('.ai-warning');
+ var aiInfo = aiSection.querySelector('.ai-info');
+ if (aiError) {
+ lines.push('## AI 分析');
+ lines.push('');
+ lines.push('> ' + aiError.textContent.trim());
+ lines.push('');
+ } else if (aiInfo) {
+ // 跳过 info 提示(如"跳过")
+ } else {
+ var aiTitle = aiSection.querySelector('.ai-section-title');
+ lines.push('## ' + (aiTitle ? aiTitle.textContent.trim() : 'AI 热点分析'));
+ lines.push('');
+ var aiBlocks = aiSection.querySelectorAll('.ai-block');
+ aiBlocks.forEach(function(block) {
+ var blockTitle = block.querySelector('.ai-block-title');
+ var blockContent = block.querySelector('.ai-block-content');
+ if (blockTitle) {
+ lines.push('### ' + blockTitle.textContent.trim());
+ lines.push('');
+ }
+ if (blockContent) {
+ lines.push(blockContent.textContent.trim());
+ lines.push('');
+ }
+ });
+ }
+ }
+
// 独立展示区(热榜平台 + RSS)
var standaloneSection = document.querySelector('.standalone-section');
if (standaloneSection) {
@@ -2735,9 +3132,16 @@ def render_html_content(
// 阅读进度条
var progressBar = document.querySelector('.reading-progress');
if (progressBar) {
+ var progressTicking = false;
window.addEventListener('scroll', function() {
- var h = document.documentElement.scrollHeight - window.innerHeight;
- progressBar.style.width = (h > 0 ? (window.scrollY / h * 100) : 0) + '%';
+ if (!progressTicking) {
+ requestAnimationFrame(function() {
+ var h = document.documentElement.scrollHeight - window.innerHeight;
+ progressBar.style.width = (h > 0 ? (window.scrollY / h * 100) : 0) + '%';
+ progressTicking = false;
+ });
+ progressTicking = true;
+ }
});
}
@@ -2754,14 +3158,28 @@ def render_html_content(
numEl.addEventListener('click', function(e) {
e.stopPropagation();
var text = titleEl.textContent.trim() + ' ' + titleEl.href;
- navigator.clipboard.writeText(text).then(function() {
+ function onCopySuccess() {
numEl.classList.add('copied');
numEl.querySelector('.copy-icon').innerHTML = checkSvg;
setTimeout(function() {
numEl.classList.remove('copied');
numEl.querySelector('.copy-icon').innerHTML = copySvg;
}, 1500);
- });
+ }
+ function fallbackCopy(str, cb) {
+ var ta = document.createElement('textarea');
+ ta.value = str; ta.style.position = 'fixed'; ta.style.opacity = '0';
+ document.body.appendChild(ta); ta.select();
+ try { document.execCommand('copy'); cb(); } catch(ex) {}
+ document.body.removeChild(ta);
+ }
+ if (navigator.clipboard && navigator.clipboard.writeText) {
+ navigator.clipboard.writeText(text).then(onCopySuccess).catch(function() {
+ fallbackCopy(text, onCopySuccess);
+ });
+ } else {
+ fallbackCopy(text, onCopySuccess);
+ }
});
});
diff --git a/trendradar/storage/sqlite_mixin.py b/trendradar/storage/sqlite_mixin.py
index 5921bbf44c..d1e6d03a5d 100644
--- a/trendradar/storage/sqlite_mixin.py
+++ b/trendradar/storage/sqlite_mixin.py
@@ -389,6 +389,9 @@ class SQLiteStorageMixin:
for rh_row in cursor.fetchall():
news_id, rank, crawl_time = rh_row[0], rh_row[1], rh_row[2]
+ if not crawl_time:
+ continue
+
# 构建 ranks 列表(去重,排除脱榜记录 rank=0)
if news_id not in rank_history_map:
rank_history_map[news_id] = []
@@ -399,7 +402,10 @@ class SQLiteStorageMixin:
if news_id not in rank_timeline_map:
rank_timeline_map[news_id] = []
# 提取时间部分(HH:MM)
- time_part = crawl_time.split()[1][:5] if ' ' in crawl_time else crawl_time[:5]
+ try:
+ time_part = crawl_time.split()[1][:5] if ' ' in crawl_time else crawl_time[:5]
+ except (IndexError, AttributeError):
+ time_part = "??:??"
rank_timeline_map[news_id].append({
"time": time_part,
"rank": rank if rank != 0 else None # 0 转为 None 表示脱榜
@@ -535,6 +541,9 @@ class SQLiteStorageMixin:
for rh_row in cursor.fetchall():
news_id, rank, crawl_time = rh_row[0], rh_row[1], rh_row[2]
+ if not crawl_time:
+ continue
+
# 构建 ranks 列表(去重,排除脱榜记录 rank=0)
if news_id not in rank_history_map:
rank_history_map[news_id] = []
@@ -545,7 +554,10 @@ class SQLiteStorageMixin:
if news_id not in rank_timeline_map:
rank_timeline_map[news_id] = []
# 提取时间部分(HH:MM)
- time_part = crawl_time.split()[1][:5] if ' ' in crawl_time else crawl_time[:5]
+ try:
+ time_part = crawl_time.split()[1][:5] if ' ' in crawl_time else crawl_time[:5]
+ except (IndexError, AttributeError):
+ time_part = "??:??"
rank_timeline_map[news_id].append({
"time": time_part,
"rank": rank if rank != 0 else None # 0 转为 None 表示脱榜
@@ -1607,22 +1619,40 @@ class SQLiteStorageMixin:
# 批量查排名历史(热榜)
ranks_map: Dict[int, List[int]] = {}
+ rank_timeline_map: Dict[int, List[Dict[str, Any]]] = {}
if hotlist_news_ids:
unique_ids = list(set(hotlist_news_ids))
placeholders = ",".join("?" * len(unique_ids))
cursor.execute(f"""
- SELECT news_item_id, rank FROM rank_history
- WHERE news_item_id IN ({placeholders}) AND rank != 0
+ SELECT news_item_id, rank, crawl_time FROM rank_history
+ WHERE news_item_id IN ({placeholders})
+ ORDER BY news_item_id, crawl_time
""", unique_ids)
for rh_row in cursor.fetchall():
- nid, rank = rh_row[0], rh_row[1]
+ nid, rank, crawl_time = rh_row[0], rh_row[1], rh_row[2]
+
+ if not crawl_time:
+ continue
+
if nid not in ranks_map:
ranks_map[nid] = []
- if rank not in ranks_map[nid]:
+ if rank != 0 and rank not in ranks_map[nid]:
ranks_map[nid].append(rank)
+ if nid not in rank_timeline_map:
+ rank_timeline_map[nid] = []
+ try:
+ time_part = crawl_time.split()[1][:5] if ' ' in crawl_time else crawl_time[:5]
+ except (IndexError, AttributeError):
+ time_part = "??:??"
+ rank_timeline_map[nid].append({
+ "time": time_part,
+ "rank": rank if rank != 0 else None
+ })
+
for item in results:
item["ranks"] = ranks_map.get(item["news_item_id"], [item["rank"]])
+ item["rank_timeline"] = rank_timeline_map.get(item["news_item_id"], [])
# RSS 结果(如果有 rss 库)
try:
diff --git a/uv.lock b/uv.lock
index 4ce3e5fe55..8bcad33f81 100644
--- a/uv.lock
+++ b/uv.lock
@@ -1996,7 +1996,7 @@ wheels = [
[[package]]
name = "trendradar"
-version = "6.7.1"
+version = "6.8.0"
source = { editable = "." }
dependencies = [
{ name = "boto3" },
diff --git a/version b/version
index 06a765991f..e029aa99b7 100644
--- a/version
+++ b/version
@@ -1 +1 @@
-6.7.1
+6.8.0