# -*- coding: utf-8 -*- """「今天的视频情况」—— 生成一张表格图片,发到企业微信。 **为什么是图片而不是文字。** 企业微信的 markdown 在手机上不支持表格,用空格对齐的 文本会被挤成一团;运营要的是扫一眼今天各号的数据,所以直接画成图。 **为什么没有播放量。** 抖音的 `statistics.play_count` 对普通作品恒为 0(见 `platforms.py` 的说明),所以表里不摆这一列 —— 宁可少一列,也不要一整列 0。 """ import io from datetime import date, datetime from pathlib import Path from typing import Any, Dict, List, Optional, Sequence from PIL import Image, ImageDraw, ImageFont from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession from . import notify from .models import MonitorNote, MonitorNoteMetric, MonitorTask # 按出现顺序找第一个能用的。容器里装的是 wqy(见 Dockerfile);开发机上是微软雅黑。 FONT_CANDIDATES = ( "/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc", "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc", "/usr/share/fonts/truetype/noto/NotoSansCJK-Regular.ttc", "C:/Windows/Fonts/msyh.ttc", "C:/Windows/Fonts/simhei.ttf", ) # --- 版式 ------------------------------------------------------------------- WIDTH = 1080 MARGIN = 24 TITLE_FONT = 30 BODY_FONT = 19 SMALL_FONT = 16 HEADER_H = 40 ROW_H = 44 MAX_ROWS = 40 # 再多就只是一张长图,手机上一屏看不完;超出部分用文字交代 # 列:左边界 + 宽度。右边界 = MARGIN + sum(widths) = WIDTH - MARGIN COLS = ( ("博主", 24, 200, "left"), ("标题", 224, 530, "left"), ("点赞", 754, 80, "right"), ("评论", 834, 70, "right"), ("收藏", 904, 70, "right"), ("分享", 974, 82, "right"), ) BG = (255, 255, 255) INK = (15, 23, 42) MUTED = (100, 116, 139) LINE = (226, 232, 240) HEAD_BG = (15, 23, 42) HEAD_INK = (255, 255, 255) ALT_BG = (248, 250, 252) ACCENT = (14, 165, 233) def _font_path() -> Optional[str]: for candidate in FONT_CANDIDATES: if Path(candidate).is_file(): return candidate return None def _font(size: int) -> ImageFont.FreeTypeFont: path = _font_path() if path is None: raise RuntimeError( "找不到中文字体,无法生成图片。容器需要 fonts-wqy-zenhei(见 Dockerfile)。" ) try: return ImageFont.truetype(path, size, index=0) except OSError: return ImageFont.truetype(path, size) def _fit(draw: ImageDraw.ImageDraw, text: str, font, max_width: int) -> str: """超出列宽就截断并加省略号 —— 不能让文字压到下一列上。""" if draw.textlength(text, font=font) <= max_width: return text trimmed = text while trimmed and draw.textlength(trimmed + "…", font=font) > max_width: trimmed = trimmed[:-1] return trimmed + "…" if trimmed else "…" def _number(value: Optional[int]) -> str: if value is None: return "—" return f"{value:,}" async def daily_rows( session: AsyncSession, platform: str, day: Optional[date] = None ) -> List[Dict[str, Any]]: """当天发布的作品 + 各自最近一轮的指标,按点赞降序。 「当天」按**发布时间**算(不是首次采到):这张图回答的是「他们今天发了什么」。 """ target_day = day or date.today() start = int(datetime.combine(target_day, datetime.min.time()).timestamp() * 1000) end = start + 86_400_000 task_ids = list( await session.scalars(select(MonitorTask.id).where(MonitorTask.platform == platform)) ) if not task_ids: return [] notes = ( await session.execute( select( MonitorNote.task_id, MonitorNote.note_id, MonitorNote.title, MonitorNote.creator_name, MonitorNote.hashtags, MonitorNote.published_at, ) .where( MonitorNote.task_id.in_(task_ids), MonitorNote.published_at.is_not(None), MonitorNote.published_at >= start, MonitorNote.published_at < end, ) .order_by(MonitorNote.published_at.desc()) ) ).all() if not notes: return [] note_ids = {row.note_id for row in notes} metric_rows = ( await session.execute( select( MonitorNoteMetric.task_id, MonitorNoteMetric.note_id, MonitorNoteMetric.run_id, MonitorNoteMetric.liked_count, MonitorNoteMetric.comment_count, MonitorNoteMetric.collected_count, MonitorNoteMetric.share_count, ).where( MonitorNoteMetric.task_id.in_(task_ids), MonitorNoteMetric.note_id.in_(note_ids), ) ) ).all() latest: Dict[tuple, Any] = {} for metric in metric_rows: key = (metric.task_id, metric.note_id) current = latest.get(key) if current is None or metric.run_id > current.run_id: latest[key] = metric rows: List[Dict[str, Any]] = [] seen: set = set() for note in notes: # 同一个作品挂在多个任务下时只算一次。 if note.note_id in seen: continue seen.add(note.note_id) metric = latest.get((note.task_id, note.note_id)) rows.append( { "note_id": note.note_id, "creator": note.creator_name or "", "title": note.title or "", "hashtags": note.hashtags or "", "likes": metric.liked_count if metric else None, "comments": metric.comment_count if metric else None, "collected": metric.collected_count if metric else None, "shares": metric.share_count if metric else None, } ) # 点赞降序,取不到指标的沉底 —— 图的最上面应该是最值得看的。 rows.sort(key=lambda item: (item["likes"] is None, -(item["likes"] or 0))) return rows def render_table( rows: Sequence[Dict[str, Any]], day: date, platform_label: str = "抖音" ) -> bytes: """把当天的数据画成 PNG。没有数据也画一张 —— 「今天没发」本身就是要报的信息。""" title_font = _font(TITLE_FONT) body_font = _font(BODY_FONT) small_font = _font(SMALL_FONT) shown = list(rows[:MAX_ROWS]) overflow = max(0, len(rows) - len(shown)) head_height = 120 table_h = HEADER_H + ROW_H * len(shown) if shown else 120 footer_h = 56 height = head_height + table_h + footer_h image = Image.new("RGB", (WIDTH, height), BG) draw = ImageDraw.Draw(image) # --- 标题 --- draw.text( (MARGIN, 26), f"{platform_label} · {day.isoformat()} 视频情况", font=title_font, fill=INK, ) if rows: totals = { "条数": len(rows), "点赞": sum(row["likes"] or 0 for row in rows), "评论": sum(row["comments"] or 0 for row in rows), "收藏": sum(row["collected"] or 0 for row in rows), "分享": sum(row["shares"] or 0 for row in rows), } summary = " · ".join(f"{key} {value:,}" for key, value in totals.items()) else: summary = "今天没有新作品" draw.text((MARGIN, 76), summary, font=small_font, fill=MUTED) # --- 表头 --- top = head_height draw.rectangle((MARGIN, top, WIDTH - MARGIN, top + HEADER_H), fill=HEAD_BG) for name, x, width, align in COLS: if align == "right": draw.text( (x + width - 10, top + 10), name, font=small_font, fill=HEAD_INK, anchor="ra", ) else: draw.text((x + 6, top + 10), name, font=small_font, fill=HEAD_INK) # --- 数据行 --- y = top + HEADER_H if not shown: draw.text( (WIDTH // 2, y + 34), "今天没有新作品", font=body_font, fill=MUTED, anchor="ma", ) y += 100 for index, row in enumerate(shown): if index % 2 == 1: draw.rectangle((MARGIN, y, WIDTH - MARGIN, y + ROW_H), fill=ALT_BG) draw.line((MARGIN, y + ROW_H, WIDTH - MARGIN, y + ROW_H), fill=LINE, width=1) baseline = y + 12 for name, x, width, align in COLS: if name == "博主": text = _fit(draw, row["creator"] or "—", body_font, width - 10) draw.text((x + 6, baseline), text, font=body_font, fill=INK) elif name == "标题": text = _fit(draw, row["title"] or "—", body_font, width - 10) draw.text((x + 6, baseline), text, font=body_font, fill=INK) else: key = {"点赞": "likes", "评论": "comments", "收藏": "collected", "分享": "shares"}[name] value = row[key] draw.text( (x + width - 10, baseline + 2), _number(value), font=small_font, fill=INK if value else MUTED, anchor="ra", ) y += ROW_H # --- 页脚 --- footer = f"共 {len(rows)} 条" if overflow: footer += f",图中只列点赞最高的 {len(shown)} 条,另有 {overflow} 条未列出" footer += " · 播放量抖音未提供,故未统计" draw.text((MARGIN, y + 16), footer, font=small_font, fill=MUTED) buffer = io.BytesIO() image.save(buffer, format="PNG", optimize=True) return buffer.getvalue() async def send_daily_digest( session: AsyncSession, platform: str, day: Optional[date] = None ) -> tuple[bool, str, int]: """生成并发送。返回 (ok, detail, 作品条数)。""" target_day = day or date.today() rows = await daily_rows(session, platform, target_day) webhook = await notify.get_webhook_url(session) if not webhook: return False, "Webhook 未配置", len(rows) label = "抖音" if platform == "dy" else "小红书" image_bytes = render_table(rows, target_day, label) ok, detail = await notify.send_wecom_image(webhook, image_bytes) return ok, detail, len(rows)