#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
西柚洞察Dashboard生成器
将数据渲染为可视化HTML看板
使用方式:
from scripts.dashboard_generator import DashboardGenerator
generator = DashboardGenerator()
generator.render(data, output_file)
"""
import os
import json
from datetime import datetime
from typing import Dict, List, Any, Optional
class DashboardGenerator:
"""Dashboard生成器"""
HTML_TEMPLATE = """
{{TITLE}}
{{CONTENT}}
"""
def render(self, data: Dict[str, Any], output_file: str) -> str:
"""
渲染Dashboard
Args:
data: 结构化数据
output_file: 输出文件路径
Returns:
str: 输出文件路径
"""
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
title = data.get('title', '西柚洞察分析看板')
target = data.get('target', '')
site = data.get('site', '')
content = self._build_content(data)
html = self.HTML_TEMPLATE.replace('{{TITLE}}', title)\
.replace('{{TARGET}}', target)\
.replace('{{SITE}}', site)\
.replace('{{TIMESTAMP}}', timestamp)\
.replace('{{CONTENT}}', content)
os.makedirs(os.path.dirname(output_file), exist_ok=True)
with open(output_file, 'w', encoding='utf-8') as f:
f.write(html)
return output_file
def _build_content(self, data: Dict[str, Any]) -> str:
"""构建内容"""
content = ""
if data.get('overview'):
content += self._build_overview(data['overview'])
if data.get('traffic'):
content += self._build_traffic_section(data['traffic'])
if data.get('keywords'):
content += self._build_keywords_section(data['keywords'])
if data.get('ad_analysis'):
content += self._build_ad_section(data['ad_analysis'])
if data.get('comparison'):
content += self._build_comparison_section(data['comparison'])
if data.get('insights'):
content += self._build_insights_section(data['insights'])
return content
def _build_overview(self, overview: Dict[str, Any]) -> str:
"""构建概览卡片"""
items = []
for key, value in overview.items():
items.append(f"""
{key}
{value}
""")
return f"""
"""
def _build_traffic_section(self, traffic: Dict[str, Any]) -> str:
"""构建流量分析部分"""
content = ""
if traffic.get('scores'):
scores = traffic['scores']
chart_data = [
{"name": "自然流量", "value": scores.get('natural_traffic', 0), "itemStyle": {"color": "#3b82f6"}},
{"name": "广告流量", "value": scores.get('ad_traffic', 0), "itemStyle": {"color": "#f59e0b"}}
]
content += f"""
📊 流量得分
自然流量{scores.get('natural_traffic', '-')}
广告流量{scores.get('ad_traffic', '-')}
总流量{scores.get('total_traffic', '-')}
关键词数量{scores.get('keyword_count', '-')}
"""
if traffic.get('trends'):
dates = [d['date'] for d in traffic['trends']]
natural = [d['natural_traffic'] for d in traffic['trends']]
ad = [d['ad_traffic'] for d in traffic['trends']]
content += f"""
"""
return content
def _build_keywords_section(self, keywords: Any) -> str:
"""构建关键词部分"""
if not keywords:
return ""
if isinstance(keywords, dict):
all_keywords = []
for asin, kw_list in keywords.items():
for kw in kw_list:
kw['asin'] = asin
all_keywords.append(kw)
all_keywords.sort(key=lambda x: x.get('traffic', 0), reverse=True)
else:
all_keywords = keywords
top_keywords = all_keywords[:10]
table_rows = []
for kw in top_keywords:
table_rows.append(f"""
| {kw.get('keyword', '-')} |
{kw.get('natural_rank', '-')} |
{kw.get('ad_rank', '-')} |
{kw.get('traffic', '-')} |
{kw.get('traffic_share', '-')} |
""")
return f"""
🔑 Top关键词
| 关键词 | 自然排名 | 广告排名 | 流量 | 流量占比 |
{''.join(table_rows)}
"""
def _build_ad_section(self, ad_data: Dict[str, Any]) -> str:
"""构建广告分析部分"""
content = ""
if ad_data.get('type_share'):
chart_data = [{"name": k, "value": v} for k, v in ad_data['type_share'].items()]
content += f"""
"""
if ad_data.get('core_keywords'):
keywords = ad_data['core_keywords'][:10]
table_rows = []
for kw in keywords:
table_rows.append(f"""
| {kw.get('keyword', '-')} |
{kw.get('traffic_share', '-')} |
${{kw.get('cpc', '-')}} |
""")
content += f"""
💡 核心广告关键词
| 关键词 | 流量占比 | 建议竞价 |
{''.join(table_rows)}
"""
return content
def _build_comparison_section(self, comparison: Dict[str, Any]) -> str:
"""构建对比部分"""
if not comparison.get('items'):
return ""
items = comparison['items']
table_rows = []
for item in items:
table_rows.append(f"""
| {item.get('asin', '-')} |
{item.get('natural_traffic', '-')} |
{item.get('ad_traffic', '-')} |
{item.get('keyword_count', '-')} |
""")
return f"""
⚖️ ASIN对比
| ASIN | 自然流量 | 广告流量 | 关键词数量 |
{''.join(table_rows)}
"""
def _build_insights_section(self, insights: List[str]) -> str:
"""构建洞察部分"""
if not insights:
return ""
insight_items = []
for i, insight in enumerate(insights, 1):
insight_items.append(f"{insight}")
return f"""
"""
if __name__ == "__main__":
import sys
if len(sys.argv) < 3:
print("Usage: python dashboard_generator.py ")
sys.exit(1)
data_path = sys.argv[1]
output_file = sys.argv[2]
with open(data_path, 'r', encoding='utf-8') as f:
data = json.load(f)
generator = DashboardGenerator()
result = generator.render(data, output_file)
print(f"✅ Dashboard已生成: {result}")