diff --git a/api/main.py b/api/main.py index 91cb508..63da27e 100644 --- a/api/main.py +++ b/api/main.py @@ -39,7 +39,7 @@ from dotenv import load_dotenv load_dotenv(PROJECT_ROOT / ".env") import uvicorn -from fastapi import Depends, FastAPI +from fastapi import Depends, FastAPI, HTTPException from fastapi.middleware.cors import CORSMiddleware from fastapi.staticfiles import StaticFiles from fastapi.responses import FileResponse @@ -201,6 +201,21 @@ async def serve_frontend(): } +# 独立的报表页。**刻意不放进 api/webui** —— 那个目录是 gitignore 的 Vite 产物, +# 每次构建都会把它清掉。这里的文件是仓库里的源码,直接原样发出去。 +# 页面本身不含数据,数据走 /api/monitor/matrix(带鉴权),所以这个壳不需要再拦一道。 +REPORTS_DIR = os.path.join(os.path.dirname(__file__), "reports") + + +@app.get("/report/matrix") +async def serve_matrix_report(): + """日期 × 博主 的标签矩阵。""" + path = os.path.join(REPORTS_DIR, "matrix.html") + if not os.path.exists(path): + raise HTTPException(status_code=404, detail="报表页面不存在") + return FileResponse(path) + + @app.get("/api/health") async def health_check(): return {"status": "ok"} diff --git a/api/monitor/service.py b/api/monitor/service.py index 9794188..d818e9a 100644 --- a/api/monitor/service.py +++ b/api/monitor/service.py @@ -20,6 +20,7 @@ import asyncio import re +from datetime import datetime from typing import Any, Dict, List, Optional, Sequence, Tuple from urllib.parse import parse_qs, urlparse @@ -1443,3 +1444,111 @@ async def mark_events_read(session: AsyncSession, task_id: Optional[int] = None) for row in rows: row.is_read = True return len(rows) + + +# --------------------------------------------------------------------------- +# 标签矩阵(日期 × 博主) +# --------------------------------------------------------------------------- + + +async def daily_tag_matrix( + session: AsyncSession, platform: str, days: int +) -> Dict[str, Any]: + """日期 × 博主 → 当天发出去的作品标签。给 ``/report/matrix`` 用。 + + **为什么分组放在 Python 里做。** MySQL 5.7 没有 PIVOT,而列数随博主变化;用 SQL + 拼动态列只能靠 PREPARE 拼一整段字符串,既没法参数化,也没法在测试用的 SQLite 上 + 跑。这里只读两次(作品、标签),分组交给 Python —— 一个窗口内的作品量级是几百条, + 代价可以忽略。 + + 返回**长表结构**,转置由前端做: + + {"dates": ["2026-10-21", ...], # 新到旧 + "creators": [{"hash": ..., "name": ...}], # 按昵称排序 + "cells": {"2026-10-21": {"": {"count": 2, "tags": ["大字报", "养号"]}}}} + """ + task_ids = await platform_task_ids(session, platform) + empty = { + "platform": platform, + "days": days, + "dates": [], + "creators": [], + "cells": {}, + } + if not task_ids: + return empty + + since = get_current_timestamp() - max(1, days) * 86_400_000 + notes = ( + await session.execute( + select( + MonitorNote.note_id, + MonitorNote.creator_hash, + MonitorNote.creator_name, + MonitorNote.published_at, + ) + .where( + MonitorNote.task_id.in_(task_ids), + MonitorNote.published_at.is_not(None), + MonitorNote.published_at >= since, + ) + .order_by(MonitorNote.published_at.desc()) + ) + ).all() + if not notes: + return empty + + # 标签一次取完,按 note_id 归组;顺序跟词表里的 sort_order 一致。 + note_ids = {row.note_id for row in notes} + tag_rows = ( + await session.execute( + select(MonitorNoteTag.note_id, MonitorTag.name) + .join(MonitorTag, MonitorTag.id == MonitorNoteTag.tag_id) + .where( + MonitorNoteTag.platform == platform, + MonitorNoteTag.note_id.in_(note_ids), + ) + .order_by(MonitorTag.sort_order, MonitorTag.id) + ) + ).all() + tags_by_note: Dict[str, List[str]] = {} + for note_id, name in tag_rows: + tags_by_note.setdefault(note_id, []).append(name) + + cells: Dict[str, Dict[str, Dict[str, Any]]] = {} + names: Dict[str, str] = {} + # 同一个作品可能挂在多个任务下(monitor_note 的唯一键是 (task_id, note_id)), + # 不按 note_id 去重会把计数翻倍。 + seen: set = set() + + for row in notes: + note_key = (row.creator_hash, row.note_id) + if note_key in seen: + continue + seen.add(note_key) + + day = datetime.fromtimestamp((row.published_at or 0) / 1000).strftime("%Y-%m-%d") + creator_key = row.creator_hash or f"note:{row.note_id}" + names.setdefault(creator_key, row.creator_name or "") + + bucket = cells.setdefault(day, {}).setdefault( + creator_key, {"count": 0, "tags": []} + ) + bucket["count"] += 1 + for tag in tags_by_note.get(row.note_id, []): + if tag not in bucket["tags"]: + bucket["tags"].append(tag) + + creators = [ + {"hash": key, "name": name or f"未知({key[:6]})"} + for key, name in names.items() + ] + creators.sort(key=lambda item: item["name"]) + + return { + "platform": platform, + "days": days, + "dates": sorted(cells, reverse=True), + "creators": creators, + "cells": cells, + } diff --git a/api/reports/matrix.html b/api/reports/matrix.html new file mode 100644 index 0000000..074412f --- /dev/null +++ b/api/reports/matrix.html @@ -0,0 +1,316 @@ + + + + + + 标签矩阵 · 综合采集平台 + + + + +
+

标签矩阵

+ + + + + + 返回控制台 +
+ +
+ 请先在控制台登录,再回到这个页面。 +
+ +
+
+ N = 当天发出的作品条数 + 无标签 = 发了但没打标签 + 空白 = 当天没发作品 + 标签按词表里的顺序排列 +
+ + + + diff --git a/api/routers/monitor.py b/api/routers/monitor.py index c86a989..98aefda 100644 --- a/api/routers/monitor.py +++ b/api/routers/monitor.py @@ -749,6 +749,20 @@ def _to_xlsx(rows: List[Dict[str, Any]], columns: List[tuple[str, str]], sheet: return output.getvalue() +@router.get("/matrix") +async def get_tag_matrix( + platform: str = Query(default=PLATFORM_XHS, description="dy / xhs"), + days: int = Query(default=14, ge=1, le=90, description="回看多少天"), +): + """日期 × 博主 → 当天发出去的作品标签。 + + 返回**长表结构**(dates / creators / cells),转置交给前端的报表页 + (``/report/matrix``)。理由见 ``service.daily_tag_matrix`` 的说明。 + """ + async with get_session() as session: + return await service.daily_tag_matrix(session, platform, days) + + @router.get("/report") async def get_report( task_id: Optional[List[int]] = Query( diff --git a/tests/test_monitor_matrix.py b/tests/test_monitor_matrix.py new file mode 100644 index 0000000..96f9d9c --- /dev/null +++ b/tests/test_monitor_matrix.py @@ -0,0 +1,208 @@ +# -*- coding: utf-8 -*- +"""标签矩阵:日期 × 博主 → 当天发出去的标签。 + +这个接口的形状(长表 + 前端转置)是被 MySQL 5.7 逼出来的 —— 没有 PIVOT,列数又随 +博主变化。所以这里重点测**分组与去重**,那才是容易出错的地方: + +* 同一天同一个号的几条作品要合成一格,计数相加、标签取并集且保序; +* 同一个作品挂在两个任务下(``monitor_note`` 的唯一键是 ``(task_id, note_id)``) + 只能算一次,否则计数翻倍; +* 窗口外的老作品不出现。 +""" + +from datetime import datetime, timedelta + +import httpx +import pytest +import pytest_asyncio + +from api.main import app +from api.monitor import db as monitor_db +from api.monitor import service +from api.monitor.models import ( + MODE_CREATOR, + MonitorNote, + MonitorNoteTag, + MonitorTag, + MonitorTask, +) +from tools.time_util import get_current_timestamp + +DAY_MS = 86_400_000 + + +def _day(ms: int) -> str: + return datetime.fromtimestamp(ms / 1000).strftime("%Y-%m-%d") + + +@pytest_asyncio.fixture +async def db(tmp_path): + monitor_db.set_sqlite_path(tmp_path / "matrix.db") + await monitor_db.init_db() + yield monitor_db + await monitor_db.dispose_engine() + + +@pytest_asyncio.fixture +async def client(tmp_path): + monitor_db.set_sqlite_path(tmp_path / "matrix_api.db") + await monitor_db.init_db() + transport = httpx.ASGITransport(app=app) + async with httpx.AsyncClient(transport=transport, base_url="http://test") as http: + yield http + await monitor_db.dispose_engine() + + +async def _task(platform: str = "dy", name: str = "矩阵测试") -> int: + async with monitor_db.get_session() as session: + task = MonitorTask( + name=name, + platform=platform, + mode=MODE_CREATOR, + enabled=True, + interval_minutes=60, + max_notes_count=20, + enable_comments=False, + max_comments_count=10, + run_timeout_seconds=3600, + created_at=0, + updated_at=0, + ) + session.add(task) + await session.flush() + return task.id + + +async def _note( + task_id: int, note_id: str, name: str, published_at: int, creator_hash: str = "hash-a" +) -> None: + async with monitor_db.get_session() as session: + session.add( + MonitorNote( + task_id=task_id, + note_id=note_id, + title="t", + note_url="", + cover="", + creator_hash=creator_hash, + creator_name=name, + source_kind="video", + published_at=published_at, + first_seen_at=published_at, + last_seen_at=published_at, + ) + ) + + +async def _tag(name: str, sort_order: int) -> int: + async with monitor_db.get_session() as session: + tag = MonitorTag(name=name, color="cyan", keywords="", sort_order=sort_order, created_at=0) + session.add(tag) + await session.flush() + return tag.id + + +async def _attach(platform: str, note_id: str, tag_id: int) -> None: + async with monitor_db.get_session() as session: + session.add( + MonitorNoteTag(platform=platform, note_id=note_id, tag_id=tag_id, created_at=0) + ) + + +@pytest.mark.asyncio +async def test_same_day_notes_collapse_with_tags_union(db): + task_id = await _task() + today = get_current_timestamp() - 1000 + await _note(task_id, "n1", "博主A", today) + await _note(task_id, "n2", "博主A", today) + + dazibao = await _tag("大字报", 1) + yanghao = await _tag("养号", 2) + await _attach("dy", "n1", dazibao) + await _attach("dy", "n2", yanghao) + await _attach("dy", "n2", dazibao) + + async with monitor_db.get_session() as session: + data = await service.daily_tag_matrix(session, "dy", days=7) + + assert data["dates"] == [_day(today)] + assert [c["name"] for c in data["creators"]] == ["博主A"] + + cell = data["cells"][_day(today)]["hash-a"] + assert cell["count"] == 2 + # 按词表 order 排序,不是按出现顺序 + assert cell["tags"] == ["大字报", "养号"] + + +@pytest.mark.asyncio +async def test_dates_newest_first_and_creators_sorted(db): + task_id = await _task() + now = get_current_timestamp() + await _note(task_id, "n1", "B博主", now - 2 * DAY_MS, creator_hash="hash-b") + await _note(task_id, "n2", "A博主", now - 1000, creator_hash="hash-a") + + async with monitor_db.get_session() as session: + data = await service.daily_tag_matrix(session, "dy", days=7) + + assert data["dates"] == sorted(data["dates"], reverse=True) + assert [c["name"] for c in data["creators"]] == ["A博主", "B博主"] + + +@pytest.mark.asyncio +async def test_notes_outside_the_window_are_excluded(db): + task_id = await _task() + now = get_current_timestamp() + await _note(task_id, "fresh", "博主A", now - 1000) + await _note(task_id, "old", "博主A", now - 40 * DAY_MS) + + async with monitor_db.get_session() as session: + data = await service.daily_tag_matrix(session, "dy", days=7) + + assert data["dates"] == [_day(now - 1000)] + assert data["cells"][_day(now - 1000)]["hash-a"]["count"] == 1 + + +@pytest.mark.asyncio +async def test_the_same_note_under_two_tasks_counts_once(db): + first = await _task(name="任务一") + second = await _task(name="任务二") + now = get_current_timestamp() - 1000 + # 同一个作品被两个任务各记了一行 + await _note(first, "same", "博主A", now) + await _note(second, "same", "博主A", now) + + async with monitor_db.get_session() as session: + data = await service.daily_tag_matrix(session, "dy", days=7) + + assert data["cells"][_day(now)]["hash-a"]["count"] == 1 + + +@pytest.mark.asyncio +async def test_no_tasks_returns_an_empty_shape(db): + async with monitor_db.get_session() as session: + data = await service.daily_tag_matrix(session, "dy", days=7) + + assert data == { + "platform": "dy", + "days": 7, + "dates": [], + "creators": [], + "cells": {}, + } + + +@pytest.mark.asyncio +async def test_endpoint_returns_the_long_shape(client): + task_id = await _task() + now = get_current_timestamp() - 1000 + await _note(task_id, "n1", "博主A", now) + tag_id = await _tag("大字报", 1) + await _attach("dy", "n1", tag_id) + + response = await client.get("/api/monitor/matrix", params={"platform": "dy", "days": 7}) + + assert response.status_code == 200 + body = response.json() + assert body["dates"] == [_day(now)] + assert body["creators"][0]["name"] == "博主A" + assert body["cells"][_day(now)]["hash-a"] == {"count": 1, "tags": ["大字报"]} diff --git a/webui/src/components/layout/Sidebar.tsx b/webui/src/components/layout/Sidebar.tsx index cf10af5..20b309e 100644 --- a/webui/src/components/layout/Sidebar.tsx +++ b/webui/src/components/layout/Sidebar.tsx @@ -1,5 +1,5 @@ import { useState } from 'react' -import { Briefcase, Bug, Wifi, BarChart3, Cog, LogOut, Radar, Settings, Terminal } from 'lucide-react' +import { Briefcase, Bug, Wifi, BarChart3, Cog, Grid3x3, LogOut, Radar, Settings, Terminal } from 'lucide-react' import { useTranslation } from 'react-i18next' import { Badge } from '@/components/ui/badge' import { SystemSettingsDialog } from '@/components/settings/SystemSettingsDialog' @@ -72,6 +72,19 @@ export function Sidebar({ currentView, onViewChange, onLogout }: SidebarProps) { ) })} + + {/* 标签矩阵是**独立页面**(/report/matrix),不是这个 SPA 的一个 view: + 它由后端直接发一份静态 HTML,不走 Vite 构建,所以这里用普通链接打开。 + 新标签页是因为它会占满整屏做宽表,来回切视图反而碍事。 */} + + + 标签矩阵 +