export_platform_statistics_xlsx.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. 从 stdin 读取 JSON(平台统计列表),生成 xlsx 并输出到 stdout(二进制)。
  5. 输入 JSON 格式:
  6. {
  7. "platforms": [
  8. {
  9. "platform": "baijiahao",
  10. "viewsCount": 5,
  11. "commentsCount": 1,
  12. "likesCount": 0,
  13. "fansIncrease": 1,
  14. "updateTime": "2026-01-27 14:30:00"
  15. }
  16. ]
  17. }
  18. """
  19. import json
  20. import sys
  21. from io import BytesIO
  22. from datetime import datetime
  23. # Ensure stdin is read as UTF-8 (important on Windows when Node passes UTF-8 JSON)
  24. if sys.platform == "win32":
  25. import io as _io
  26. if hasattr(sys.stdin, "buffer"):
  27. sys.stdin = _io.TextIOWrapper(sys.stdin.buffer, encoding="utf-8", errors="replace")
  28. try:
  29. from openpyxl import Workbook
  30. from openpyxl.styles import Font, Alignment, PatternFill, Border, Side
  31. from openpyxl.utils import get_column_letter
  32. except Exception as e: # pragma: no cover
  33. sys.stderr.write(
  34. "Missing dependency: openpyxl. Please install it in your python env.\n"
  35. "Example: pip install -r server/python/requirements.txt\n"
  36. f"Detail: {e}\n"
  37. )
  38. sys.exit(3)
  39. HEADERS = [
  40. "平台",
  41. "阅读(播放量)",
  42. "评论量",
  43. "点赞量",
  44. "涨粉量",
  45. "更新时间",
  46. ]
  47. COL_WIDTHS = [12, 16, 12, 12, 10, 18]
  48. def _safe_int(v):
  49. try:
  50. if v is None or v == "":
  51. return None
  52. return int(float(v))
  53. except Exception:
  54. return None
  55. def _safe_str(v) -> str:
  56. """
  57. 将任意值转换为字符串,并过滤掉 Excel 不支持的非法 Unicode 代理字符。
  58. """
  59. if v is None:
  60. return ""
  61. try:
  62. s = str(v)
  63. except Exception:
  64. s = repr(v)
  65. return "".join(ch for ch in s if not (0xD800 <= ord(ch) <= 0xDFFF))
  66. def _format_update_time(value: str) -> str:
  67. """\
  68. 格式化更新时间为统一的人类可读格式:
  69. - 如果是今年:MM-DD HH:mm
  70. - 如果是往年:YYYY-MM-DD HH:mm\
  71. """
  72. if not value:
  73. return ""
  74. s = str(value).strip()
  75. # 尝试解析 ISO 或常见时间格式
  76. try:
  77. if s.endswith("Z"):
  78. s_clean = s[:-1]
  79. else:
  80. s_clean = s
  81. s_clean = s_clean.replace(" ", "T")
  82. dt = datetime.fromisoformat(s_clean)
  83. now_year = datetime.now().year
  84. if dt.year == now_year:
  85. return dt.strftime("%m-%d %H:%M")
  86. return dt.strftime("%Y-%m-%d %H:%M")
  87. except Exception:
  88. pass
  89. # 尝试从 "YYYY-MM-DD HH:mm:ss" 中拆分
  90. try:
  91. if len(s) >= 16:
  92. parts = s.split(" ")
  93. if len(parts) >= 2:
  94. date_part = parts[0]
  95. time_part = parts[1]
  96. date_parts = date_part.split("-")
  97. time_parts = time_part.split(":")
  98. if len(date_parts) >= 3 and len(time_parts) >= 2:
  99. year = int(date_parts[0])
  100. month = date_parts[1].zfill(2)
  101. day = date_parts[2].zfill(2)
  102. hour = time_parts[0].zfill(2)
  103. minute = time_parts[1].zfill(2)
  104. now_year = datetime.now().year
  105. if year == now_year:
  106. return f"{month}-{day} {hour}:{minute}"
  107. return f"{year}-{month}-{day} {hour}:{minute}"
  108. except Exception:
  109. pass
  110. return s
  111. def build_xlsx(platforms):
  112. platform_name_map = {
  113. "douyin": "抖音",
  114. "baijiahao": "百家号",
  115. "weixin_video": "视频号",
  116. "xiaohongshu": "小红书",
  117. "bilibili": "哔哩哔哩",
  118. "kuaishou": "快手",
  119. }
  120. wb = Workbook()
  121. ws = wb.active
  122. ws.title = "平台数据"
  123. ws.append(HEADERS)
  124. header_font = Font(bold=True)
  125. header_fill = PatternFill("solid", fgColor="F2F2F2")
  126. center = Alignment(horizontal="center", vertical="center", wrap_text=False)
  127. left = Alignment(horizontal="left", vertical="center", wrap_text=False)
  128. thin = Side(style="thin", color="D9D9D9")
  129. border = Border(left=thin, right=thin, top=thin, bottom=thin)
  130. for col_idx in range(1, len(HEADERS) + 1):
  131. cell = ws.cell(row=1, column=col_idx)
  132. cell.font = header_font
  133. cell.fill = header_fill
  134. cell.alignment = center
  135. cell.border = border
  136. for i, w in enumerate(COL_WIDTHS, start=1):
  137. col_letter = get_column_letter(i)
  138. ws.column_dimensions[col_letter].width = w
  139. for p in platforms:
  140. platform_raw = (p.get("platform") or "").strip()
  141. platform_cn = platform_name_map.get(platform_raw, platform_raw)
  142. ws.append([
  143. _safe_str(platform_cn),
  144. _safe_int(p.get("viewsCount")) or 0,
  145. _safe_int(p.get("commentsCount")) or 0,
  146. _safe_int(p.get("likesCount")) or 0,
  147. _safe_int(p.get("fansIncrease")) or 0,
  148. _safe_str(_format_update_time(p.get("updateTime"))),
  149. ])
  150. int_cols = {"B", "C", "D", "E"}
  151. for row in range(2, ws.max_row + 1):
  152. for col in range(1, len(HEADERS) + 1):
  153. c = ws.cell(row=row, column=col)
  154. c.border = border
  155. if col == 1:
  156. c.alignment = left
  157. else:
  158. c.alignment = center
  159. for c_letter in int_cols:
  160. c = ws[f"{c_letter}{row}"]
  161. if c.value is not None:
  162. c.number_format = "0"
  163. ws.freeze_panes = "A2"
  164. bio = BytesIO()
  165. wb.save(bio)
  166. return bio.getvalue()
  167. def main():
  168. try:
  169. raw = sys.stdin.read()
  170. payload = json.loads(raw) if raw.strip() else {}
  171. except Exception as e:
  172. sys.stderr.write(f"Invalid JSON input: {e}\n")
  173. sys.exit(2)
  174. platforms = payload.get("platforms") or []
  175. xlsx_bytes = build_xlsx(platforms)
  176. sys.stdout.buffer.write(xlsx_bytes)
  177. if __name__ == "__main__":
  178. main()