Skip to content

armgit / peach

Public Imported from GitHub
0

Peach: Local-first video metadata scraper and media manager.

feat: add private taste management

longmeidaod06e706f8dc6
diff --git a/README.md b/README.md
index aa108155e..a9c75f51e 100644
--- a/README.md
+++ b/README.md
@@ -97,6 +97,7 @@ macOS/Linux 用 `./scripts/test.sh follow`。可选域为 `follow`、`catalog`
| `/review` | 人工复核 |
| `/trash` | 回收站 |
| `/stats` | 统计 |
+| `/taste` | 品味画像与浏览记录管理 |
`/healthz` 提供无副作用健康状态,`/api/sources` 提供来源可达性。其他 API 契约以实现和测试为准,不在 README 维护容易漂移的端点全集。
diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md
index e5337bf97..b9c0050a1 100644
--- a/docs/HANDOFF.md
+++ b/docs/HANDOFF.md
@@ -152,6 +152,7 @@ Gofile token 是另一份本机可选凭据,只进 Gofile 请求头,不进 U
- Ledger 拥有真相和行为;Stash 是可替换适配器,调用统一经过 `StashClient`,外部 Scene ID 和来源进入 `media_binding`,不新增直接 GraphQL helper 或 Stash 私有 FFmpeg 路径。规范女优/厂牌/标签/创作者进入 `entity`、`entity_external_ref`、`asset_entity`;扁平 `asset_tag` 和 creator/studio 字段只是兼容投影。
- FastAPI 与前端保持单体部署,在线来源和 AI 只通过显式适配器进入;AI runtime 与推理 API 的协议边界见 ADR-0003。
- 当前页面、路由、交互与性能实现只写 `docs/STATUS.md`,由 API 和 `tests/test_web_ui.py` 守住;本文件不再复制易过期的版本号、像素值和控件清单。
+- `/taste` 只读合并 Peach 行为与本机私有浏览历史,时间窗使用当前资产的 `last_played` 和浏览访问时间;画像、补标签缺口和排名都只是候选。原始 URL/标题不进入页面或 ledger;上传原件保存在 `sources/taste-history/imports`,移除数据源只清理规范化分析库,不删除原件。浏览器数据库解析固定复用 `browserexport==0.4.4`,运行中浏览器仍先由 Peach 的 SQLite backup API 取得一致快照。
- 追更连接器、凭据、变体和跨站归组以 ADR-0019 为准。Rule34.xxx 来源身份大小写不敏感;作者显示名与头像优先经固定主机校验的官方页面,归档站只回退。
- 自动追更固定使用 APScheduler 3.11.3,只在 ledger writer 启动。频率保存在 `peach-data/state/follow-schedule.json`,默认每小时且启动后等待一个完整间隔;不要改成启动即抓。任务必须保持 `coalesce=True`、`max_instances=1`,并与手动检查共用 `WebContract.follow_check_lock`,reader 只显示不可用状态。
- 账本路径兼容和抽帧失败处理统一见 `.claude/skills/peach-cross-platform/SKILL.md` 与 `.claude/skills/peach-batch-jobs/SKILL.md`。
diff --git a/docs/REUSE.md b/docs/REUSE.md
index c5f4958b7..79bf30b69 100644
--- a/docs/REUSE.md
+++ b/docs/REUSE.md
@@ -91,7 +91,7 @@
| 当前能力 | 判断 | 已验证证据与 Peach 边界 |
|---|---|---|
-| `taste_history.py` 自写 Chrome/Firefox/Zen/Safari 发现、快照与 SQLite 解析 | **优先替换为 `browserexport==0.4.4`** | Python 3.14 依赖解析通过;在本机 7 个 Chrome/Firefox/Zen profile 上与 Peach 逐库计数完全一致。Peach 保留 Takeout、隐私存储、域名分析和 candidate 生成。 |
+| `taste_history.py` 自写 Chrome/Firefox/Zen/Safari SQLite 解析 | **已替换为 `browserexport==0.4.4`** | Python 3.14 依赖解析通过;审计 POC 在本机 7 个 Chrome/Firefox/Zen profile 上与 Peach 逐库计数完全一致。首个消费者是 `/taste` 的本机读取与导出导入;Peach 保留 SQLite backup、Takeout、私有原始存储、域名分析和 candidate 生成,并在 Windows 自己关闭只读连接以避开依赖的文件句柄滞留。 |
| `jobs.PidFileLock` | **优先替换为 `portalocker==4.3.0` 的 `PidFileLock`** | Python 3.14 解析通过,现成覆盖 PID 写入、锁持有者、原子替换、陈旧文件与释放清理。Peach 只保留任务归属和错误文案映射。 |
| Rule34Video 媒体页解析 | **部分替换为 `yt-dlp==2026.8.19`** | 对真实视频 4533145 无写入提取成功,取得 4 个格式、31 个标签、缩略图与时间。Peach 仍负责作者分页、合集/超多 model 排除、来源分组和跨站去重。 |
| FANBOX 正文解析 | **已采用 PixivUtil2 `v20251112` / `e537e96` 的公开正文模型** | Peach 的独立规范化 DTO 已覆盖 image/text/file/article/video/entry、`fileMap`、`embedMap`、`urlEmbedMap` 和旧 HTML 正文,并保留正文顺序、稳定去重、可播放媒体与文件页边界;BSD-2-Clause 依据写在实现头部。PixivUtil2 是完整下载器而非可嵌入解析库,因此不引入整套依赖;传输继续固定 `curl_cffi==0.16.2`。真实公开帖 12228983 只读 POC 得到 article、6 图和 Gofile `OS2Qz9`。 |
@@ -101,5 +101,5 @@
| Gofile API | **保留直接 HTTP** | 官方没有维护中的 Python SDK;社区 wrapper 只是薄封装,不能绕过 Premium `contents` 权限,也不能减少 Peach 的 Bearer 隔离与媒体规范化。 |
| `netwatch.py`、streaming/segments、sync、versioning/Windows update | **保留现有边界** | 分别是无 PyObjC 的系统通知、FFmpeg/Starlette 上的会话策略、单 writer ledger 规则和 Git/PyInstaller 更新契约;通用替代会保留同量 policy 或扩大依赖。 |
-FANBOX、浏览器历史、PID 锁和 Rule34Video 依次进入替换实施;其余保留项在约束改变或候选实现更新时
+FANBOX 与浏览器历史替换已完成;PID 锁和 Rule34Video 依次进入替换实施。其余保留项在约束改变或候选实现更新时
重新跑 POC,不因本表结论永久豁免外部检索。
diff --git a/docs/STATUS.md b/docs/STATUS.md
index 7ee884d05..119bd8c68 100644
--- a/docs/STATUS.md
+++ b/docs/STATUS.md
@@ -21,7 +21,7 @@
- FastAPI 是唯一 Web server;Ledger 保存资产、规范身份、行为和复核决定。Stash 与 CloudDrive 都经适配层进入,扁平 creator/studio/tag 字段只作兼容投影。
- 本地浏览器支持 MP4/WebM/Ogg;AVI 等由 `TranscodeService` 缓存成 H.264/AAC MP4。远端 MP4 默认走标准 Range,显式 HLS 使用关键帧对齐片段,失败会回退 Range,永不改写原媒体。
-- 首页、详情、实体资料、标签管理、照片、播放列表、统计、复核、回收站、关注管理和关注观看共用同一 SPA 与 JSON 契约;桌面和 390×844 手机均在验收范围内。
+- 首页、详情、实体资料、标签管理、照片、播放列表、统计、品味、复核、回收站、关注管理和关注观看共用同一 SPA 与 JSON 契约;桌面和 390×844 手机均在验收范围内。
- 多女优卡片叠放前 3 个头像,只显示第一位姓名和真实总人数,例如 `かわいゆい 等 37 人`;详情与沉浸模式仍保留完整或扩展后的出演信息。
- 当前源码的在线追更支持 FANBOX、Patreon、SubscribeStar、kemono/coomer/pawchive、rule34video、rule34.xxx、Rule34 Paheal 和 f95zone;FANBOX 可选 Cookie 用于公开详情被验证页拦截时复用用户会话,Gofile Premium API token 可展开 FANBOX/F95 外部文件页。两份凭据只发给各自站点。SimpCity 仍被 DDoS-Guard 阻塞,Peach 不绕过机器人验证。官方渠道只读取公开免费发布,不绕过登录或付费墙。
- Rule34.xxx 来源 ref 大小写不敏感;迁移会合并分批添加造成的重复来源并保留条目状态。F95 的 `Collection(s)` 后缀不进入作者名,五个来源可归到同一作者组。
@@ -32,7 +32,7 @@
- 搜索使用 FTS5 trigram,短查询回退 LIKE 并覆盖规范名、别名和检索词。搜索历史在 reader 写入被拒时降级到页面内存,不产生未处理异常。
- 回收站的单项删除和清空共用 `purge_assets()`:先处理媒体文件,再提交 ledger;删不掉的文件保留可见状态并回报,避免静默遗留。
- 复核页覆盖元数据、创作者标签、Logo、头像、身份、番号目录、FC2 证据和媒体失败。抓取与 AI 结果仍是候选,批准后才写真相字段。
-- 浏览历史增量采集使用 SQLite backup API,一致性读取本机浏览器和 Takeout;原始 URL/标题只留本机私有库,聚合候选不写 ledger。
+- 浏览历史增量采集使用 SQLite backup API 与固定版本 `browserexport==0.4.4`,一致性读取本机 Chrome/Firefox/Zen/Safari,也接受 Google Takeout ZIP 和 browserexport SQLite/JSON/JSONL 导出;原始 URL、标题和导出文件只留本机私有目录,聚合候选不写 ledger。
## 本批修正与验证
@@ -78,11 +78,12 @@
- 0.7.3 正式 EXE 已替换为 SHA-256 `97EBAEE965794D100FA3BC7093B042EB36F1147CDEE1432C3504D7ECFB9D4582`,上版备份为 `dist/Peach/Peach.pre-0.7.3-20260828-152459.exe`;80/443 已由新进程恢复监听,打包迁移为 22 个、0 待处理,项目 CA 严格 HTTPS `/healthz` 返回 200、0.7.3、writer,`/follow` 返回 200。部署没有触发生产检查更新,部署前后 ledger SHA-256 均为 `BC98556370E285C2B627DBA3A36820E79AFF4599A33A265B0DBDDE520379A697`;本改动没有页面、CSS 或交互变化,桌面/手机视觉验收不适用。
- 0.7.4 追更详情的多图改为左右按钮、方向键和点状分页;多视频继续使用 Mix 右侧队列。直达详情按条目 ID 精确读取,启动时不再先绘制首页。关注入口统一使用 RSS 图标,左侧窄栏与筛选抽屉共用可在设置中调整的顺序。自动追更固定复用 APScheduler 3.11.3,只在 writer 启动,默认每小时、首次等待完整间隔,手动与自动检查共用互斥锁;设置页可关闭或调整为 15 分钟至每天,并显示最近/下次运行状态。正式全量 1130 项先发现 1 条点状分页圆角门槛,修正后覆盖该门槛的 `catalog` 368 项全部通过;全量其余 1129 项通过、13 项按平台跳过。
- 0.7.4 正式 EXE 已替换为 SHA-256 `027C985CD85B509BDEAD52D3FB209CBA25421B674BED96E0A97D97C82C8B2C1C`,上版备份为 `dist/Peach/Peach.pre-0.7.4-20260828-160731.exe`;80/443 已恢复,打包迁移为 22 个、0 待处理,项目 CA 严格 HTTPS `/healthz` 返回 200、0.7.4、writer。生产 `/follow/item/791` 返回 200,精确 API 恢复到 FANBOX 条目 791 及 6 张图片;自动更新已启用为每小时,下次运行时间可读且首次未立即执行。浏览器实测左右按钮、左右键、6 个圆点、刷新后保留详情、RSS 导航、设置中的侧栏排序与自动更新状态均正常,控制台无错误;侧栏顺序测试后已恢复原顺序。本轮没有手动触发关注检查。`migrate status` 在 16:05 将 WAL 检查点写回主库,主文件 SHA-256 由部署前快照值变为 `B1D499D5AA89D2BCB7A7311B167C726B07EA4FF0620E1FB467FC3F03519C487A`,部署重启后保持稳定;SQLite `integrity_check=ok`、外键违规 0,asset 81555、follow_item 1008。
+- 管理页新增 `/taste`:以本机私有浏览历史和 Peach 播放、时长、评分、喜欢/不喜欢证据生成时间范围可切换的口味维度、Tag、创作者、女优、来源、不喜欢项、标签缺口与数据完整度;Peach 已有关联的排名可直接下钻筛选。支持读取本机浏览器、上传 Takeout/browserexport 导出和移除规范化数据源,均不把原始 URL/标题写入 ledger。变基到最新主线后正式 Windows 全量 1140 项通过、13 项按平台跳过;只读真实浏览历史与临时 ledger 副本实测 191,334 条浏览记录、354 个 Peach 项目和 7 个数据源合并成功,90 天范围收窄为 67,233 条,Tag 下钻到首页筛选正常。1440×900 为四列摘要、双列面板,390×844 为单列,均无横向溢出且控制台无错误。临时服务与副本已删除,未重启生产服务、未写真实 ledger。
## 下一批工作
1. 另行授权后先备份 ledger,再把 `follow_item` 181、184、185 从 `seen` 恢复为 `new`,复核状态计数、完整性与新哈希。
-2. 继续按复用审计依次替换浏览器历史、PID 锁和 Rule34Video 媒体页;每项固定版本/revision、首个消费者和隔离测试同批落地。
+2. 继续按复用审计依次替换 PID 锁和 Rule34Video 媒体页;每项固定版本/revision、首个消费者和隔离测试同批落地。
3. 分类剩余 44 个无预览变体,区分确无图片与来源解析遗漏。
4. 另行确认后在生产关注页检查 LazyProcrastinator FANBOX,把已验证的 6 图、正文与 Gofile `OS2Qz9` 资源页写入关注候选;Gofile token 当前未配置,且此前验证的账户不是 Premium,21 个视频仍未取得。
5. 在 `/review` 人工处理本批 JAV 日文系列名、官方标签及现有创作者标签、FC2、Javinizer、Logo、头像和媒体失败候选;未经批准不写真相字段。
diff --git a/pyproject.toml b/pyproject.toml
index 382a64014..674103296 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -10,6 +10,7 @@ requires-python = ">=3.12"
dependencies = [
"APScheduler==3.11.3",
"beautifulsoup4==4.15.0",
+ "browserexport==0.4.4",
"curl_cffi==0.16.2",
"fastapi==0.116.1",
"feedparser==6.0.12",
diff --git a/src/peach/api.py b/src/peach/api.py
index c3296c3a6..85d36b5e9 100644
--- a/src/peach/api.py
+++ b/src/peach/api.py
@@ -1,14 +1,19 @@
import hmac
import asyncio
import html
+import hashlib
import logging
+import os
+import re
import subprocess
+import uuid
import httpx
from concurrent.futures import ThreadPoolExecutor
from contextlib import asynccontextmanager
from functools import partial
+from pathlib import Path
from typing import Any
-from urllib.parse import parse_qs, quote
+from urllib.parse import parse_qs, quote, unquote
from fastapi import Body, Depends, FastAPI, HTTPException, Request
from fastapi.responses import (
@@ -16,6 +21,7 @@ from fastapi.responses import (
StreamingResponse,
)
from fastapi.staticfiles import StaticFiles
+from browserexport.common import BrowserexportError
from . import __version__, web_contract, web_follow
from .config import LOCATION_ROOT_DECLARATIONS, PROJECT_ROOT, PeachSettings
@@ -55,6 +61,7 @@ from .stash import StashClient
from .streaming import CancellableFileResponse, StreamSessionRegistry
from .sync import LedgerSync
from .transcodes import TranscodeCancelled, TranscodeService, TranscodeUnavailable
+from .taste_history import analyze_history, import_history_exports, write_manifest
LOGGER = logging.getLogger(__name__)
@@ -125,6 +132,10 @@ def create_app(
avatar_root=settings.avatar_root,
logo_root=settings.logo_root,
follow_state_root=settings.follow_state_root,
+ taste_history_root=settings.taste_history_output_root,
+ taste_history_store=settings.taste_history_store,
+ taste_history_import_root=settings.taste_history_import_root,
+ taste_history_manifest=settings.taste_history_manifest,
database=database,
)
repository = LedgerRepository(database)
@@ -767,6 +778,7 @@ def create_app(
@app.api_route("/immerse", methods=["GET", "HEAD"])
@app.api_route("/trash", methods=["GET", "HEAD"])
@app.api_route("/review", methods=["GET", "HEAD"])
+ @app.api_route("/taste", methods=["GET", "HEAD"])
@app.api_route("/duplicates", methods=["GET", "HEAD"])
@app.api_route("/quality-goals", methods=["GET", "HEAD"])
@app.api_route("/follow", methods=["GET", "HEAD"])
@@ -880,6 +892,70 @@ def create_app(
LOGGER.exception("unhandled GET contract error for /api/%s", route)
return JSONResponse({"error": "internal server error"}, status_code=500)
+ @app.post("/api/taste/import")
+ async def taste_import(
+ request: Request,
+ _args: dict[str, str] = Depends(require_auth),
+ ):
+ """Stream one private history export to local storage, then import it.
+
+ This deliberately avoids multipart/form-data and its extra parser dependency. The
+ browser sends the file bytes as-is and provides only a display filename header.
+ """
+ maximum = 1024 * 1024 * 1024
+ try:
+ declared = int(request.headers.get("content-length") or 0)
+ except ValueError:
+ declared = 0
+ if declared > maximum:
+ return JSONResponse({"error": "导出文件超过 1 GB"}, status_code=413)
+ filename = unquote(request.headers.get("x-peach-filename") or "history-export")
+ filename = re.sub(r"[^\w.()\-\u3400-\u9fff]+", "-", os.path.basename(filename)).strip(".-")
+ filename = filename[-160:] or "history-export"
+ root = contract.taste_history_import_root
+ root.mkdir(parents=True, exist_ok=True)
+ temporary = root / f".{uuid.uuid4().hex}.part"
+ imported_target: Path | None = None
+ digest = hashlib.sha256()
+ size = 0
+ try:
+ with temporary.open("xb") as handle:
+ async for chunk in request.stream():
+ size += len(chunk)
+ if size > maximum:
+ raise OverflowError
+ digest.update(chunk)
+ handle.write(chunk)
+ if not size:
+ raise ValueError("导出文件为空")
+ target = root / f"{digest.hexdigest()[:12]}-{filename}"
+ if target.exists():
+ temporary.unlink()
+ else:
+ os.replace(temporary, target)
+ imported_target = target
+ results = await asyncio.to_thread(
+ import_history_exports, [target], contract.taste_history_store,
+ )
+ analysis = await asyncio.to_thread(
+ analyze_history, contract.taste_history_store, contract.taste_history_root,
+ )
+ write_manifest(contract.taste_history_manifest, results, analysis)
+ contract.cache_bust()
+ return {
+ "refresh": results,
+ "dashboard": web_contract.q_taste(contract, {"window": "all"}),
+ }
+ except OverflowError:
+ temporary.unlink(missing_ok=True)
+ return JSONResponse({"error": "导出文件超过 1 GB"}, status_code=413)
+ except (BrowserexportError, OSError, ValueError, TypeError) as exc:
+ temporary.unlink(missing_ok=True)
+ if imported_target is not None:
+ imported_target.unlink(missing_ok=True)
+ LOGGER.warning("taste history import rejected: %s", exc)
+ return JSONResponse({"error": str(exc)}, status_code=400)
+
@app.post("/api/{route:path}")
def api_post(
route: str,
diff --git a/src/peach/config.py b/src/peach/config.py
index 4edfd2f7c..611407a28 100644
--- a/src/peach/config.py
+++ b/src/peach/config.py
@@ -120,5 +120,9 @@ class PeachSettings:
stream_root: Path = GENERATED_DIR / "stream-segments"
# 复核候选 CSV 的目录。走 settings 而不是模块常量,测试才不会读到真实的 generated 目录。
candidate_root: Path = GENERATED_DIR
+ taste_history_store: Path = SOURCES_DIR / "taste-history" / "history.sqlite"
+ taste_history_import_root: Path = SOURCES_DIR / "taste-history" / "imports"
+ taste_history_output_root: Path = DATA_ROOT / "review" / "taste-history"
+ taste_history_manifest: Path = STATE_DIR / "taste-history" / "manifest.json"
# 自动追更频率是本机运行偏好,不属于 ledger 真相。
follow_state_root: Path = STATE_DIR
diff --git a/src/peach/taste_history.py b/src/peach/taste_history.py
index a6abaaf52..cff3b20a3 100644
--- a/src/peach/taste_history.py
+++ b/src/peach/taste_history.py
@@ -8,6 +8,7 @@ import socket
import sqlite3
import tempfile
import zipfile
+import math
from collections import Counter, defaultdict
from contextlib import closing
from dataclasses import dataclass
@@ -16,6 +17,11 @@ from html.parser import HTMLParser
from pathlib import Path
from urllib.parse import parse_qs, unquote, urlparse
+from browserexport.parse import read_visits as read_browser_visits
+from browserexport.browsers.chrome import Chrome
+from browserexport.browsers.firefox import Firefox
+from browserexport.browsers.safari import Safari
+
@dataclass(frozen=True)
class HistorySource:
@@ -143,32 +149,48 @@ def _iso_from_safari(value: int | float) -> str:
return (datetime(2001, 1, 1, tzinfo=UTC) + timedelta(seconds=float(value))).isoformat()
-def _read_visits(snapshot: Path, browser: str) -> list[HistoryVisit]:
- with closing(sqlite3.connect(snapshot)) as db:
- if browser in {"firefox", "zen"}:
- rows = db.execute(
- "SELECT v.id, v.visit_date, p.url, COALESCE(p.title, '') "
- "FROM moz_historyvisits v JOIN moz_places p ON p.id = v.place_id "
- "WHERE v.visit_date IS NOT NULL AND p.url IS NOT NULL"
- )
- convert = _iso_from_unix_microseconds
- elif browser == "chrome":
- rows = db.execute(
- "SELECT v.id, v.visit_time, u.url, COALESCE(u.title, '') "
- "FROM visits v JOIN urls u ON u.id = v.url "
- "WHERE v.visit_time IS NOT NULL AND u.url IS NOT NULL"
- )
- convert = _iso_from_chrome
- elif browser == "safari":
- rows = db.execute(
- "SELECT v.id, v.visit_time, i.url, COALESCE(v.title, '') "
- "FROM history_visits v JOIN history_items i ON i.id = v.history_item "
- "WHERE v.visit_time IS NOT NULL AND i.url IS NOT NULL"
- )
- convert = _iso_from_safari
- else:
- raise ValueError(f"不支持的浏览器类型:{browser}")
- return [HistoryVisit(str(row[0]), convert(row[1]), row[2], row[3]) for row in rows]
+def _read_visits(snapshot: Path, _browser: str | None = None) -> list[HistoryVisit]:
+ """Use browserexport's maintained schema adapters and keep Peach's private DTO.
+
+ The source database is already a consistent SQLite backup when this is called for a
+ running browser. Exported JSON/JSONL and compressed files can be passed directly.
+ """
+ occurrences: Counter[tuple[str, str]] = Counter()
+ visits: list[HistoryVisit] = []
+
+ def consume(source, browser: str | None = None) -> None:
+ known = {"chrome": Chrome, "firefox": Firefox, "zen": Firefox, "safari": Safari}
+ iterator = known[browser].extract_visits(source) if browser in known else read_browser_visits(source)
+ for visit in iterator:
+ visited = visit.dt
+ if visited.tzinfo is None:
+ visited = visited.replace(tzinfo=UTC)
+ visited_at = visited.astimezone(UTC).isoformat()
+ url = str(visit.url)
+ fingerprint = (url, visited_at)
+ occurrences[fingerprint] += 1
+ ordinal = occurrences[fingerprint]
+ visit_key = hashlib.sha256(
+ f"{visited_at}\0{url}\0{ordinal}".encode("utf-8")
+ ).hexdigest()
+ title = ""
+ if visit.metadata is not None:
+ title = str(visit.metadata.title or "")
+ visits.append(HistoryVisit(visit_key, visited_at, url, title))
+
+ try:
+ with snapshot.open("rb") as handle:
+ is_sqlite = handle.read(16) == b"SQLite format 3\x00"
+ except OSError:
+ is_sqlite = False
+ if is_sqlite:
+ # browserexport 0.4.4 accepts an owned connection. Passing a path uses a
+ # context manager that commits but does not close sqlite3.Connection on Windows.
+ with closing(sqlite3.connect(_readonly_uri(snapshot), uri=True)) as connection:
+ consume(connection, _browser)
+ else:
+ consume(snapshot)
+ return visits
def _source_key(source: HistorySource, host: str) -> str:
@@ -444,6 +466,354 @@ def refresh_takeout_history(
return results
+def refresh_export_history(
+ exports: list[Path],
+ store_path: Path,
+ *,
+ host: str | None = None,
+) -> list[dict[str, object]]:
+ """Import browserexport SQLite/JSON/JSONL (including compressed variants).
+
+ Raw exports stay in the private sources directory. Only normalized visits enter the
+ private history store; no URL or title is copied to the Peach ledger.
+ """
+ host = host or socket.gethostname()
+ store_path.parent.mkdir(parents=True, exist_ok=True)
+ now = datetime.now(UTC).isoformat()
+ results: list[dict[str, object]] = []
+ with closing(sqlite3.connect(store_path)) as store:
+ _prepare_store(store)
+ for export_path in exports:
+ visits = _read_visits(export_path)
+ source = HistorySource("browserexport", export_path.name, export_path)
+ source_key = _source_key(source, host)
+ path_hash = hashlib.sha256(str(export_path.resolve()).encode("utf-8")).hexdigest()
+ store.execute(
+ "INSERT INTO history_source VALUES (?, ?, ?, ?, ?, ?, ?) "
+ "ON CONFLICT(source_key) DO UPDATE SET last_seen_at=excluded.last_seen_at",
+ (source_key, source.browser, source.profile, host, path_hash, now, now),
+ )
+ before = store.total_changes
+ store.executemany(
+ "INSERT OR IGNORE INTO history_visit(source_key, visit_key, visited_at, url, title) "
+ "VALUES (?, ?, ?, ?, ?)",
+ ((source_key, visit.visit_key, visit.visited_at, visit.url, visit.title)
+ for visit in visits),
+ )
+ results.append({
+ "browser": source.browser,
+ "profile": source.profile,
+ "visits": len(visits),
+ "added": store.total_changes - before,
+ "skipped": 0,
+ })
+ store.commit()
+ return results
+
+
+def import_history_exports(
+ exports: list[Path],
+ store_path: Path,
+ *,
+ host: str | None = None,
+) -> list[dict[str, object]]:
+ """Route Google Takeout archives and browserexport-compatible files."""
+ results: list[dict[str, object]] = []
+ for export_path in exports:
+ is_takeout = False
+ if zipfile.is_zipfile(export_path):
+ with zipfile.ZipFile(export_path) as archive:
+ members = set(archive.namelist())
+ is_takeout = TAKEOUT_HISTORY_MEMBER in members or any(
+ member in members for _browser, _profile, member in TAKEOUT_ACTIVITY_MEMBERS
+ )
+ if is_takeout:
+ results.extend(refresh_takeout_history([export_path], store_path, host=host))
+ else:
+ results.extend(refresh_export_history([export_path], store_path, host=host))
+ return results
+
+
+def remove_history_source(store_path: Path, source_key: str) -> int:
+ """Remove one normalized source while retaining the immutable raw export."""
+ if not store_path.is_file():
+ return 0
+ with closing(sqlite3.connect(store_path)) as store:
+ _prepare_store(store)
+ row = store.execute(
+ "SELECT count(*) FROM history_visit WHERE source_key=?", (source_key,),
+ ).fetchone()
+ removed = int(row[0]) if row else 0
+ store.execute("DELETE FROM history_visit WHERE source_key=?", (source_key,))
+ store.execute("DELETE FROM history_source WHERE source_key=?", (source_key,))
+ store.commit()
+ return removed
+
+
+def _history_dashboard_evidence(store_path: Path, since: str | None) -> dict[str, object]:
+ empty = {
+ "visits": 0, "sources": [], "range_start": None, "range_end": None,
+ "tags": Counter(), "creators": Counter(), "categories": Counter(),
+ "domains": Counter(),
+ }
+ if not store_path.is_file():
+ return empty
+ with closing(sqlite3.connect(store_path)) as store:
+ store.row_factory = sqlite3.Row
+ try:
+ source_rows = [dict(row) for row in store.execute(
+ "SELECT s.source_key,s.browser,s.profile,s.host,s.first_seen_at,s.last_seen_at,"
+ "count(v.visit_key) visits,min(v.visited_at) range_start,max(v.visited_at) range_end "
+ "FROM history_source s LEFT JOIN history_visit v ON v.source_key=s.source_key "
+ "GROUP BY s.source_key ORDER BY s.last_seen_at DESC,s.browser,s.profile"
+ )]
+ query = (
+ "SELECT v.visited_at,v.url FROM history_visit v "
+ "JOIN history_source s ON s.source_key=v.source_key"
+ )
+ params: tuple[str, ...] = ()
+ if since:
+ query += " WHERE v.visited_at>=?"
+ params = (since,)
+ rows = store.execute(query, params)
+ except sqlite3.DatabaseError:
+ return empty
+
+ tags: Counter[str] = Counter()
+ creators: Counter[str] = Counter()
+ categories: Counter[str] = Counter()
+ domains: Counter[str] = Counter()
+ seen: set[tuple[str, int]] = set()
+ range_start: str | None = None
+ range_end: str | None = None
+ visits = 0
+ for row in rows:
+ visited_at, url = str(row["visited_at"]), str(row["url"])
+ try:
+ fingerprint = (url, int(datetime.fromisoformat(visited_at).timestamp()))
+ except ValueError:
+ continue
+ if fingerprint in seen:
+ continue
+ seen.add(fingerprint)
+ visits += 1
+ range_start = visited_at if range_start is None or visited_at < range_start else range_start
+ range_end = visited_at if range_end is None or visited_at > range_end else range_end
+ domain, row_tags, row_creators = _url_candidates(url)
+ if domain and _is_taste_domain(domain):
+ domains[domain] += 1
+ tags.update(row_tags)
+ creators.update(row_creators)
+ for tag in row_tags:
+ compact = tag.replace(" ", "")
+ for category, terms in CATEGORY_TERMS.items():
+ if compact in terms or tag in terms:
+ categories[category] += 1
+ return {
+ "visits": visits,
+ "sources": source_rows,
+ "range_start": range_start,
+ "range_end": range_end,
+ "tags": tags,
+ "creators": creators,
+ "categories": categories,
+ "domains": domains,
+ }
+
+
+def _epoch(value: object) -> float | None:
+ if value is None:
+ return None
+ try:
+ return float(value)
+ except (TypeError, ValueError):
+ try:
+ return datetime.fromisoformat(str(value).replace("Z", "+00:00")).timestamp()
+ except ValueError:
+ return None
+
+
+def _peach_dashboard_evidence(connection: sqlite3.Connection, since: str | None) -> dict[str, object]:
+ since_epoch = datetime.fromisoformat(since).timestamp() if since else None
+ rows = connection.execute(
+ "SELECT a.id,a.creator,a.studio,a.play_count,a.play_seconds,a.o_count,a.rating,"
+ "a.feedback,a.last_played,COALESCE(p.liked,0) liked "
+ "FROM asset a LEFT JOIN asset_preference p ON p.asset_id=a.id AND p.profile_id='local-default' "
+ "WHERE COALESCE(a.play_count,0)>0 OR COALESCE(a.play_seconds,0)>0 "
+ "OR COALESCE(a.o_count,0)>0 OR COALESCE(a.rating,0)>0 "
+ "OR a.feedback IN ('seen','dislike') OR COALESCE(p.liked,0)>0"
+ ).fetchall()
+ assets: dict[int, dict[str, object]] = {}
+ total_seconds = 0.0
+ liked = disliked = 0
+ for raw in rows:
+ row = dict(raw)
+ played_at = _epoch(row.get("last_played"))
+ if since_epoch is not None and (played_at is None or played_at < since_epoch):
+ continue
+ seconds = max(float(row.get("play_seconds") or 0), 0)
+ plays = max(int(row.get("play_count") or 0), 0)
+ o_count = max(int(row.get("o_count") or 0), 0)
+ rating = max(int(row.get("rating") or 0), 0)
+ is_liked = bool(row.get("liked"))
+ is_disliked = row.get("feedback") == "dislike"
+ positive = (1.0 if plays or seconds else 0.0) + math.log2(1 + seconds / 60)
+ positive += min(plays, 12) * .75 + min(o_count, 8) * 1.5 + rating / 20
+ positive += 3.0 if is_liked else 0.0
+ positive += .5 if row.get("feedback") == "seen" else 0.0
+ row["positive"] = max(positive, 0.0)
+ row["negative"] = 1.0 if is_disliked else 0.0
+ assets[int(row["id"])] = row
+ total_seconds += seconds
+ liked += int(is_liked)
+ disliked += int(is_disliked)
+
+ scores: dict[str, Counter[str]] = defaultdict(Counter)
+ negatives: dict[str, Counter[str]] = defaultdict(Counter)
+ items: dict[str, dict[str, set[int]]] = defaultdict(lambda: defaultdict(set))
+ labels: dict[str, dict[str, str]] = defaultdict(dict)
+ entity_kinds: dict[int, set[str]] = defaultdict(set)
+ if assets:
+ ids = list(assets)
+ for offset in range(0, len(ids), 800):
+ batch = ids[offset:offset + 800]
+ placeholders = ",".join("?" for _ in batch)
+ entity_rows = connection.execute(
+ "SELECT ae.asset_id,e.kind,e.canonical_name,e.normalized_name "
+ f"FROM asset_entity ae JOIN entity e ON e.id=ae.entity_id WHERE ae.asset_id IN ({placeholders})",
+ batch,
+ )
+ for entity in entity_rows:
+ aid = int(entity["asset_id"])
+ kind = str(entity["kind"])
+ normalized = str(entity["normalized_name"] or entity["canonical_name"]).casefold()
+ labels[kind][normalized] = str(entity["canonical_name"])
+ entity_kinds[aid].add(kind)
+ if assets[aid]["positive"]:
+ scores[kind][normalized] += float(assets[aid]["positive"])
+ items[kind][normalized].add(aid)
+ if assets[aid]["negative"]:
+ negatives[kind][normalized] += 1
+
+ for aid, asset in assets.items():
+ for kind, column in (("creator", "creator"), ("studio", "studio")):
+ value = str(asset.get(column) or "").strip()
+ if not value or kind in entity_kinds[aid]:
+ continue
+ normalized = value.casefold()
+ labels[kind][normalized] = value
+ if asset["positive"]:
+ scores[kind][normalized] += float(asset["positive"])
+ items[kind][normalized].add(aid)
+ if asset["negative"]:
+ negatives[kind][normalized] += 1
+
+ tagged = sum("tag" in entity_kinds[aid] for aid in assets)
+ identified = sum(bool(entity_kinds[aid] & {"creator", "performer"}) for aid in assets)
+ return {
+ "assets": len(assets), "seconds": total_seconds, "liked": liked, "disliked": disliked,
+ "scores": scores, "negatives": negatives, "items": items, "labels": labels,
+ "coverage": {
+ "tagged": tagged, "identified": identified,
+ "untagged": len(assets) - tagged, "unidentified": len(assets) - identified,
+ },
+ }
+
+
+def _rank_combined(
+ kind: str,
+ web_values: Counter[str],
+ peach: dict[str, object],
+ *,
+ limit: int = 30,
+) -> list[dict[str, object]]:
+ scores = peach["scores"].get(kind, Counter())
+ labels = peach["labels"].get(kind, {})
+ item_sets = peach["items"].get(kind, {})
+ normalized_web: Counter[str] = Counter()
+ web_labels: dict[str, str] = {}
+ for label, count in web_values.items():
+ normalized = label.casefold().strip()
+ normalized_web[normalized] += count
+ web_labels.setdefault(normalized, label)
+ rows: list[dict[str, object]] = []
+ for normalized in set(scores) | set(normalized_web):
+ web_visits = int(normalized_web[normalized])
+ peach_score = float(scores[normalized])
+ combined = peach_score + math.log2(1 + web_visits) * 2.0
+ rows.append({
+ "name": labels.get(normalized) or web_labels.get(normalized) or normalized,
+ "score": round(combined, 2),
+ "web_visits": web_visits,
+ "peach_score": round(peach_score, 2),
+ "peach_items": len(item_sets.get(normalized, set())),
+ "evidence": [source for source, present in (
+ ("浏览记录", web_visits > 0), ("Peach", peach_score > 0),
+ ) if present],
+ })
+ rows.sort(key=lambda row: (-float(row["score"]), -int(row["web_visits"]), str(row["name"])))
+ return rows[:limit]
+
+
+def build_taste_dashboard(
+ history_store: Path,
+ ledger_connection: sqlite3.Connection,
+ *,
+ since: str | None = None,
+) -> dict[str, object]:
+ """Build a privacy-bounded, read-only taste view from both evidence stores."""
+ history = _history_dashboard_evidence(history_store, since)
+ peach = _peach_dashboard_evidence(ledger_connection, since)
+ tags = _rank_combined("tag", history["tags"], peach)
+ creators = _rank_combined("creator", history["creators"], peach)
+ performers = _rank_combined("performer", Counter(), peach)
+
+ category_scores: Counter[str] = Counter(history["categories"])
+ for row in tags:
+ compact = str(row["name"]).casefold().replace(" ", "")
+ for category, terms in CATEGORY_TERMS.items():
+ if compact in terms:
+ category_scores[category] += max(1, round(float(row["peach_score"])))
+
+ gaps = [row for row in tags if row["web_visits"] >= 2 and not row["peach_items"]][:12]
+ negative_tags = []
+ for normalized, count in peach["negatives"].get("tag", Counter()).most_common(12):
+ negative_tags.append({
+ "name": peach["labels"].get("tag", {}).get(normalized, normalized),
+ "disliked_items": count,
+ })
+ return {
+ "summary": {
+ "history_visits": history["visits"],
+ "history_sources": len(history["sources"]),
+ "peach_items": peach["assets"],
+ "peach_seconds": round(float(peach["seconds"])),
+ "liked": peach["liked"],
+ "disliked": peach["disliked"],
+ "range_start": history["range_start"],
+ "range_end": history["range_end"],
+ },
+ "sources": history["sources"],
+ "rankings": {
+ "categories": [{"name": name, "score": score}
+ for name, score in category_scores.most_common(20)],
+ "tags": tags,
+ "creators": creators,
+ "performers": performers,
+ "domains": [{"name": name, "visits": count}
+ for name, count in history["domains"].most_common(20)],
+ "negative_tags": negative_tags,
+ },
+ "coverage": peach["coverage"],
+ "gaps": gaps,
+ "privacy": {
+ "raw_history_local_only": True,
+ "ledger_unchanged": True,
+ "candidate_only": True,
+ },
+ }
+
+
def read_creator_candidates(output_dir: Path, limit: int = 200) -> list[dict]:
"""读最新一批创作者候选,按访问次数从多到少。
diff --git a/src/peach/web_contract.py b/src/peach/web_contract.py
index 5f73036a6..baed5f74a 100644
--- a/src/peach/web_contract.py
+++ b/src/peach/web_contract.py
@@ -14,6 +14,7 @@ import re
import threading
import time
import uuid
+from datetime import UTC, datetime, timedelta
from pathlib import Path, PurePosixPath
from typing import Sequence
from urllib.parse import quote, urlsplit
@@ -39,6 +40,14 @@ from .platform import (
translate_ledger_path,
)
from .repository import LedgerDatabase
+from .taste_history import (
+ analyze_history,
+ build_taste_dashboard,
+ discover_history_sources,
+ refresh_history,
+ remove_history_source,
+ write_manifest,
+)
from .web_follow import (
q_follow, q_follow_credentials, q_follow_schedule,
w_follow_check, w_follow_credential, w_follow_resolve, w_follow_schedule,
@@ -104,6 +113,9 @@ class WebContract:
follow_state_root: Path | None = None,
follow_shared_root: Path | None = None,
taste_history_root: Path | None = None,
+ taste_history_store: Path | None = None,
+ taste_history_import_root: Path | None = None,
+ taste_history_manifest: Path | None = None,
database: LedgerDatabase | None = None):
# 候选 CSV 的目录做成实例属性而不是模块常量,复核层才能在临时目录里被测试。
self.candidate_root = Path(candidate_root) if candidate_root is not None else GENERATED_DIR
@@ -125,6 +137,15 @@ class WebContract:
self.taste_history_root = (Path(taste_history_root)
if taste_history_root is not None
else DATA_ROOT / "review" / "taste-history")
+ self.taste_history_store = (Path(taste_history_store)
+ if taste_history_store is not None
+ else SOURCES_DIR / "taste-history" / "history.sqlite")
+ self.taste_history_import_root = (Path(taste_history_import_root)
+ if taste_history_import_root is not None
+ else SOURCES_DIR / "taste-history" / "imports")
+ self.taste_history_manifest = (Path(taste_history_manifest)
+ if taste_history_manifest is not None
+ else STATE_DIR / "taste-history" / "manifest.json")
self.database = database or LedgerDatabase(db_path)
self.db_path = self.database.db_path
self.snapshot_root = Path(snapshot_root) if snapshot_root is not None else None
@@ -449,6 +470,74 @@ def q_search_history(contract: WebContract, limit: int = 10):
return {"items": [row["query"] for row in rows]}
+TASTE_WINDOWS = {"all": None, "90d": 90, "365d": 365}
+
+
+def _taste_since(window: str) -> str | None:
+ if window not in TASTE_WINDOWS:
+ raise ValueError("invalid taste window")
+ days = TASTE_WINDOWS[window]
+ return (datetime.now(UTC) - timedelta(days=days)).isoformat() if days else None
+
+
+def q_taste(contract: WebContract, args=None):
+ args = args or {}
+ window = str(args.get("window") or "all")
+ with contract.read_connection() as connection:
+ payload = build_taste_dashboard(
+ contract.taste_history_store,
+ connection,
+ since=_taste_since(window),
+ )
+ updated_at = None
+ try:
+ manifest = json.loads(contract.taste_history_manifest.read_text(encoding="utf-8"))
+ updated_at = manifest.get("updated_at")
+ except (OSError, ValueError, TypeError):
+ pass
+ export_count = export_bytes = 0
+ try:
+ for path in contract.taste_history_import_root.iterdir():
+ if path.is_file() and not path.name.endswith(".part"):
+ export_count += 1
+ export_bytes += path.stat().st_size
+ except OSError:
+ pass
+ payload.update({
+ "window": window,
+ "updated_at": updated_at,
+ "storage": {"exports": export_count, "bytes": export_bytes},
+ })
+ return payload
+
+
+def w_taste_refresh(contract: WebContract, body):
+ window = str(body.get("window") or "all")
+ sources = discover_history_sources()
+ results = refresh_history(sources, contract.taste_history_store) if sources else []
+ if contract.taste_history_store.is_file():
+ analysis = analyze_history(contract.taste_history_store, contract.taste_history_root)
+ write_manifest(contract.taste_history_manifest, results, analysis)
+ contract.cache_bust()
+ return {"refresh": results, "dashboard": q_taste(contract, {"window": window})}
+
+
+def w_taste_source(contract: WebContract, body):
+ if body.get("operation") != "remove":
+ raise ValueError("invalid taste source operation")
+ source_key = str(body.get("source_key") or "")
+ if not re.fullmatch(r"[0-9a-f]{64}", source_key):
+ raise ValueError("invalid taste source key")
+ removed = remove_history_source(contract.taste_history_store, source_key)
+ analysis = analyze_history(contract.taste_history_store, contract.taste_history_root)
+ write_manifest(contract.taste_history_manifest, [{"removed": removed}], analysis)
+ contract.cache_bust()
+ return {
+ "removed": removed,
+ "dashboard": q_taste(contract, {"window": str(body.get("window") or "all")}),
+ }
+
+
def w_search_history(contract: WebContract, body):
operation = body.get("operation", "remember")
query = str(body.get("query", "")).strip()
@@ -2687,6 +2776,14 @@ def _get_search_history(contract, args):
return q_search_history(contract, int(args.get("limit", "10")))
+def _get_taste(contract, args):
+ window = str(args.get("window") or "all")
+ return contract.cached(
+ f"taste:{window}",
+ lambda: q_taste(contract, {"window": window}),
+ )
+
+
def _get_review(contract, _args):
return contract.cached("review", lambda: q_review(contract))
@@ -2716,6 +2813,7 @@ GET_HANDLERS = {
"/api/playlist": q_playlist,
"/api/facets": _get_facets,
"/api/search-history": _get_search_history,
+ "/api/taste": _get_taste,
"/api/review": _get_review,
}
@@ -2738,6 +2836,8 @@ POST_HANDLERS = {
"/api/item-tag": w_item_tag,
"/api/batch": w_batch,
"/api/search-history": w_search_history,
+ "/api/taste/refresh": w_taste_refresh,
+ "/api/taste/source": w_taste_source,
"/api/trash/empty": _post_empty_trash,
"/api/purge-missing": w_purge_missing,
"/api/review/auto-apply": w_review_auto_apply,
@@ -2750,6 +2850,7 @@ POST_HANDLERS = {
#: 追更的「查找」在只读端被拦成 409 是实测踩到的。
READ_ONLY_POST_ROUTES = frozenset({
"/api/follow/resolve", "/api/follow/credential",
+ "/api/taste/refresh", "/api/taste/source",
})
diff --git a/tests/test_fastapi_api.py b/tests/test_fastapi_api.py
index bcc9a763d..7f814b5e8 100644
--- a/tests/test_fastapi_api.py
+++ b/tests/test_fastapi_api.py
@@ -5,6 +5,7 @@ import sqlite3
import struct
import tempfile
import unittest
+from contextlib import closing
from pathlib import Path
from unittest.mock import patch
@@ -114,6 +115,10 @@ class FastApiContractTests(unittest.IsolatedAsyncioTestCase):
self.transcode_root = self.root / "transcodes"
self.photo_root = self.root / "photo-thumbs"
self.vendor_root = self.root / "vendor"
+ self.taste_store = self.root / "sources" / "taste-history" / "history.sqlite"
+ self.taste_import_root = self.root / "sources" / "taste-history" / "imports"
+ self.taste_output_root = self.root / "review" / "taste-history"
+ self.taste_manifest = self.root / "state" / "taste-history" / "manifest.json"
# 复核候选必须来自临时目录:早先版本直接读真实的 R:\peach-data\generated。
self.candidate_root = self.root / "generated"
self.candidate_root.mkdir()
@@ -170,6 +175,10 @@ class FastApiContractTests(unittest.IsolatedAsyncioTestCase):
poster_root=self.poster_root, avatar_root=self.avatar_root, logo_root=self.logo_root,
ffmpeg_root=self.root / "ffmpeg", transcode_root=self.transcode_root,
candidate_root=self.candidate_root, photo_root=self.photo_root,
+ taste_history_store=self.taste_store,
+ taste_history_import_root=self.taste_import_root,
+ taste_history_output_root=self.taste_output_root,
+ taste_history_manifest=self.taste_manifest,
)
self.app = create_app(self.settings)
self.assertIs(
@@ -319,6 +328,44 @@ class FastApiContractTests(unittest.IsolatedAsyncioTestCase):
removed = await self.client.post("/api/search-history?t=secret", json={"operation": "remove", "query": "ABW"})
self.assertEqual(removed.status_code, 200)
+ async def test_taste_import_combines_private_history_with_peach_behavior(self):
+ with closing(sqlite3.connect(self.db)) as connection:
+ connection.execute(
+ "UPDATE asset SET play_count=2,play_seconds=600,last_played=? WHERE id=1",
+ (1_700_000_200,),
+ )
+ connection.commit()
+ payload = json.dumps([{
+ "url": "https://rule34.xxx/index.php?page=post&s=list&tags=tag+a",
+ "dt": 1_700_000_000,
+ "metadata": None,
+ }]).encode()
+ imported = await self.client.post(
+ "/api/taste/import?t=secret",
+ content=payload,
+ headers={"Content-Type": "application/octet-stream",
+ "X-Peach-Filename": "history.json"},
+ )
+ self.assertEqual(imported.status_code, 200, imported.text)
+ dashboard = imported.json()["dashboard"]
+ self.assertEqual(dashboard["summary"]["history_visits"], 1)
+ self.assertEqual(dashboard["summary"]["peach_items"], 1)
+ self.assertEqual(dashboard["rankings"]["tags"][0]["name"], "Tag A")
+ self.assertNotIn("rule34.xxx/index.php", imported.text)
+ self.assertTrue(self.taste_store.is_file())
+ self.assertTrue(self.taste_manifest.is_file())
+
+ listed = await self.client.get("/api/taste?t=secret&window=all")
+ self.assertEqual(listed.status_code, 200)
+ source_key = listed.json()["sources"][0]["source_key"]
+ removed = await self.client.post(
+ "/api/taste/source?t=secret",
+ json={"operation": "remove", "source_key": source_key, "window": "all"},
+ )
+ self.assertEqual(removed.status_code, 200)
+ self.assertEqual(removed.json()["removed"], 1)
+ self.assertEqual(removed.json()["dashboard"]["summary"]["history_visits"], 0)
+
async def test_entity_focus_uses_the_apps_configured_avatar_root(self):
connection = sqlite3.connect(self.db)
connection.execute(
@@ -561,7 +608,7 @@ class FastApiContractTests(unittest.IsolatedAsyncioTestCase):
)
for path in ("/item/1", "/performers/Alice", "/studios/Prestige",
"/creators/luckydog11", "/series/Example", "/performers",
- "/creators", "/tags", "/stats", "/immerse", "/trash", "/review",
+ "/creators", "/tags", "/stats", "/taste", "/immerse", "/trash", "/review",
# 前端路由写好了不等于能直接打开:SPA 路径是逐条登记的,
# 漏登记时源码断言照样全绿,只有真的请求一次才会露出 404。
"/unseen", "/watch-later", "/flagged",
diff --git a/tests/test_rm_web.py b/tests/test_rm_web.py
index d3ef99658..afefcfd38 100644
--- a/tests/test_rm_web.py
+++ b/tests/test_rm_web.py
@@ -490,6 +490,7 @@ class WebDataTests(unittest.TestCase):
"/api/stats", "/api/tops", "/api/ads", "/api/related", "/api/facets",
"/api/search-history", "/api/review", "/api/playlists", "/api/playlist",
"/api/follow", "/api/follow/credentials", "/api/follow/schedule",
+ "/api/taste",
})
self.assertEqual(set(rm_web.POST_HANDLERS), {
"/api/activity", "/api/play", "/api/feedback", "/api/watch-later",
@@ -500,6 +501,7 @@ class WebDataTests(unittest.TestCase):
"/api/follow/check", "/api/follow/status", "/api/follow/save",
"/api/follow/source", "/api/follow/resolve", "/api/follow/credential",
"/api/follow/author-alias", "/api/follow/schedule",
+ "/api/taste/refresh", "/api/taste/source",
})
with self.assertRaises(rm_web.ContractRouteNotFound):
rm_web.dispatch_api_get(self.contract, "/api/typo", {})
diff --git a/tests/test_taste_history.py b/tests/test_taste_history.py
index 4ec30ae87..a117e4073 100644
--- a/tests/test_taste_history.py
+++ b/tests/test_taste_history.py
@@ -12,7 +12,9 @@ from urllib.parse import quote
from peach.taste_history import (
HistorySource,
analyze_history,
+ build_taste_dashboard,
discover_history_sources,
+ import_history_exports,
refresh_history,
refresh_takeout_history,
)
@@ -30,10 +32,11 @@ class TasteHistoryTests(unittest.TestCase):
path.parent.mkdir(parents=True)
with closing(sqlite3.connect(path)) as db:
db.executescript(
- "CREATE TABLE moz_places(id INTEGER PRIMARY KEY, url TEXT, title TEXT);"
+ "CREATE TABLE moz_places(id INTEGER PRIMARY KEY, url TEXT, title TEXT, "
+ "description TEXT, preview_image_url TEXT);"
"CREATE TABLE moz_historyvisits(id INTEGER PRIMARY KEY, place_id INTEGER, visit_date INTEGER);"
)
- db.execute("INSERT INTO moz_places VALUES (1, ?, ?)", ("https://rule34.xxx/search?tags=feet+cosplay", "secret"))
+ db.execute("INSERT INTO moz_places VALUES (1, ?, ?, NULL, NULL)", ("https://rule34.xxx/search?tags=feet+cosplay", "secret"))
db.execute("INSERT INTO moz_historyvisits VALUES (1, 1, 1700000000000000)")
db.commit()
@@ -42,10 +45,10 @@ class TasteHistoryTests(unittest.TestCase):
with closing(sqlite3.connect(path)) as db:
db.executescript(
"CREATE TABLE urls(id INTEGER PRIMARY KEY, url TEXT, title TEXT);"
- "CREATE TABLE visits(id INTEGER PRIMARY KEY, url INTEGER, visit_time INTEGER);"
+ "CREATE TABLE visits(id INTEGER PRIMARY KEY, url INTEGER, visit_time INTEGER, visit_duration INTEGER);"
)
db.execute("INSERT INTO urls VALUES (1, ?, ?)", ("https://onlyfans.com/creator_name", "private title"))
- db.execute("INSERT INTO visits VALUES (2, 1, 13344473600000000)")
+ db.execute("INSERT INTO visits VALUES (2, 1, 13344473600000000, 0)")
db.commit()
def _safari_db(self, path: Path) -> None:
@@ -163,6 +166,54 @@ class TasteHistoryTests(unittest.TestCase):
self.assertNotIn("https://", report)
self.assertNotIn("private takeout title", report)
+ def test_browserexport_json_and_peach_behavior_build_one_private_dashboard(self):
+ exported = self.root / "history.json"
+ exported.write_text(json.dumps([
+ {
+ "url": "https://rule34.xxx/index.php?page=post&s=list&tags=feet",
+ "dt": 1_700_000_000,
+ "metadata": {"title": "private", "description": None,
+ "preview_image": None, "duration": None},
+ },
+ {
+ "url": "https://onlyfans.com/alice",
+ "dt": 1_700_000_100,
+ "metadata": None,
+ },
+ ]), encoding="utf-8")
+ store = self.root / "sources" / "history.sqlite"
+ imported = import_history_exports([exported], store, host="test-host")
+ self.assertEqual(imported[0]["added"], 2)
+
+ ledger = self.root / "ledger.db"
+ with closing(sqlite3.connect(ledger)) as db:
+ db.row_factory = sqlite3.Row
+ db.executescript(
+ "CREATE TABLE asset(id INTEGER PRIMARY KEY,creator TEXT,studio TEXT,play_count INTEGER,"
+ "play_seconds REAL,o_count INTEGER,rating INTEGER,feedback TEXT,last_played REAL);"
+ "CREATE TABLE asset_preference(profile_id TEXT,asset_id INTEGER,liked INTEGER);"
+ "CREATE TABLE entity(id INTEGER PRIMARY KEY,kind TEXT,canonical_name TEXT,normalized_name TEXT);"
+ "CREATE TABLE asset_entity(asset_id INTEGER,entity_id INTEGER);"
+ )
+ db.execute("INSERT INTO asset VALUES(1,'Alice','Studio',2,600,1,80,NULL,1700000200)")
+ db.execute("INSERT INTO asset_preference VALUES('local-default',1,1)")
+ db.execute("INSERT INTO entity VALUES(1,'tag','feet','feet')")
+ db.execute("INSERT INTO entity VALUES(2,'creator','Alice','alice')")
+ db.execute("INSERT INTO asset_entity VALUES(1,1)")
+ db.execute("INSERT INTO asset_entity VALUES(1,2)")
+ db.commit()
+ dashboard = build_taste_dashboard(store, db)
+
+ self.assertEqual(dashboard["summary"]["history_visits"], 2)
+ self.assertEqual(dashboard["summary"]["peach_items"], 1)
+ feet = dashboard["rankings"]["tags"][0]
+ self.assertEqual(feet["name"], "feet")
+ self.assertEqual(feet["web_visits"], 1)
+ self.assertEqual(feet["peach_items"], 1)
+ alice = dashboard["rankings"]["creators"][0]
+ self.assertEqual(alice["evidence"], ["浏览记录", "Peach"])
+ self.assertNotIn("url", json.dumps(dashboard).casefold())
+
if __name__ == "__main__":
unittest.main()
diff --git a/tests/test_web_ui.py b/tests/test_web_ui.py
index afeb15af1..0297c1e16 100644
--- a/tests/test_web_ui.py
+++ b/tests/test_web_ui.py
@@ -544,7 +544,8 @@ class WebUiSourceTests(unittest.TestCase):
self.assertPageContains("['manage','管理','settings']")
self.assertPageContains("const MANAGE_SECTIONS=[")
for section in ("'stats','统计'", "'ads','疑似广告'", "'dupes','重复文件'",
- "'quality','高清版'", "'trash','回收站'", "'review','人工复核'"):
+ "'quality','高清版'", "'trash','回收站'", "'review','人工复核'",
+ "'taste','品味'"):
self.assertPageContains(section)
self.assertPageContains("function manageSection()")
self.assertPageContains("function buildManageBar()")
@@ -565,10 +566,22 @@ class WebUiSourceTests(unittest.TestCase):
sections = self.page.split("const MANAGE_SECTIONS=[", 1)[1].split("];", 1)[0]
order = [line.split("'")[1] for line in sections.splitlines() if line.strip().startswith("['")]
self.assertEqual(
- order, ["stats", "review", "ads", "dupes", "trash", "follow", "quality"],
+ order, ["stats", "taste", "review", "ads", "dupes", "trash", "follow", "quality"],
"管理导航的顺序是语义契约:现状 → 复核 → 清理 → 回收站 → 往外拿",
)
+ def test_taste_page_combines_private_exports_and_peach_behavior(self):
+ self.assertPageContains("if(path==='/taste'){await openTaste(false);return}")
+ self.assertPageContains("/api/taste?window=")
+ self.assertPageContains("/api/taste/import")
+ self.assertPageContains("/api/taste/refresh")
+ self.assertPageContains("/api/taste/source")
+ self.assertPageContains("原始 URL、标题与搜索内容不会显示在页面")
+ self.assertPageContains("data-taste-window")
+ self.assertPageContains("data-taste-remove")
+ self.assertPageContains(".tastegrid{display:grid")
+ self.assertPageContains("@media(max-width:640px){.tastehead")
+
def test_edge_and_drawer_share_one_navigation_dispatch(self):
"""窄栏和抽屉各写一份分支时,抽屉那份漏了追更和播放列表。
diff --git a/web/app.css b/web/app.css
index fd09eb91a..dbd5ba216 100644
--- a/web/app.css
+++ b/web/app.css
@@ -212,6 +212,18 @@ button,a,input,textarea,select,summary{touch-action:manipulation}
.statshead{display:flex;align-items:baseline;gap:12px;padding:2px 2px 14px;margin-bottom:14px}
.stats h2{margin:0 0 4px;font-size:var(--fs-2xl)}
.stats .sub{color:var(--muted);margin:0}
+
+/* 品味:先看证据规模,再看可操作的标签/身份,数据源管理留在末尾。 */
+.tastepage{padding:0 0 48px}.tastehead{display:flex;align-items:center;justify-content:flex-end;gap:16px;margin:-4px 0 12px}
+.tastehead p,.tastepanel header p{margin:0;color:var(--muted);font-size:var(--fs-xs)}
+.tasteactions{display:flex;align-items:center;gap:7px;flex-wrap:wrap}.tasteactions select,.tasteactions button{height:36px;border:1px solid var(--border-15);border-radius:8px;background:var(--surface);color:var(--ink);padding:0 11px;font:inherit;font-size:var(--fs-sm)}
+.tasteactions button{display:inline-flex;align-items:center;gap:7px;cursor:pointer}.tasteactions button:hover{border-color:var(--tungsten);color:var(--tungsten)}.tasteactions button:disabled{opacity:.5;cursor:wait}.tasteactions svg{width:16px;height:16px;stroke:currentColor;fill:none}
+.tastestate{min-height:20px;color:var(--meter);font-size:var(--fs-xs);margin-bottom:8px}.tastesummaries{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:10px;margin-bottom:14px}.tastesummary{display:grid;gap:3px;min-width:0;padding:15px 16px;border:1px solid var(--line-soft);border-radius:12px;background:var(--surface)}.tastesummary>span{color:var(--muted);font-size:var(--fs-xs)}.tastesummary>b{font-size:var(--fs-2xl);line-height:1.15}.tastesummary>small{color:var(--ink-2);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
+.tastegrid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px;margin-bottom:12px}.tastepanel{min-width:0;padding:15px 16px;border:1px solid var(--line-soft);border-radius:12px;background:var(--surface)}.tastepanel>h3,.tastepanel header h3{margin:0 0 11px;font-size:var(--fs-lg)}.tasteranks{display:grid}.tasterank{width:100%;min-width:0;display:grid;grid-template-columns:30px minmax(0,1fr) auto;align-items:center;gap:8px;padding:8px 3px;border:0;border-top:1px solid var(--line-soft);background:transparent;color:var(--ink);text-align:left}.tasterank:first-child{border-top:0}.tasterank:is(button){cursor:pointer}.tasterank:is(button):hover{color:var(--tungsten)}.tasterank>span:nth-child(2){min-width:0}.tasterank b,.tasterank small{display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.tasterank small{margin-top:2px;color:var(--muted);font-size:var(--fs-xs);font-weight:400}.tasterank>svg{width:16px;height:16px;stroke:currentColor;fill:none}.tastepos{color:var(--muted);font-size:var(--fs-xs)}
+.tastecoverage{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:9px}.tastecoverage>div{display:grid;gap:3px;padding:15px;border-radius:10px;background:var(--overlay-5)}.tastecoverage b{font-size:var(--fs-2xl)}.tastecoverage span{font-weight:650}.tastecoverage small{color:var(--muted)}
+.tastesources{padding-bottom:8px}.tastesources>header{display:flex;justify-content:space-between;align-items:baseline;gap:16px}.tastesources>div{display:grid}.tastesource{display:grid;grid-template-columns:34px minmax(0,1fr) 34px;align-items:center;gap:10px;padding:10px 0;border-top:1px solid var(--line-soft)}.tastesource:first-child{border-top:0}.tastebrowser{width:32px;height:32px;border-radius:9px;background:var(--overlay-5);display:grid;place-items:center;color:var(--tungsten)}.tastebrowser svg,.tastesource>button svg{width:17px;height:17px;stroke:currentColor;fill:none}.tastesource b,.tastesource small{display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.tastesource small{color:var(--muted);font-size:var(--fs-xs);margin-top:2px}.tastesource>button{width:32px;height:32px;border:0;border-radius:8px;background:transparent;color:var(--muted);display:grid;place-items:center;cursor:pointer}.tastesource>button:hover{background:var(--hover);color:var(--drop)}.tasteprivacy{margin:12px 2px 0;color:var(--muted);font-size:var(--fs-xs)}
+@media(max-width:900px){.tastesummaries{grid-template-columns:repeat(2,minmax(0,1fr))}}
+@media(max-width:640px){.tastehead{display:block}.tastehead>div:first-child{margin-bottom:8px}.tasteactions{display:grid;grid-template-columns:1fr 1fr}.tasteactions select{grid-column:1/-1}.tasteactions button{justify-content:center}.tastesummaries,.tastegrid{grid-template-columns:minmax(0,1fr)}.tastesource{grid-template-columns:32px minmax(0,1fr) 32px}.tastesources>header{display:block}.tastesources>header p{margin:-5px 0 9px}.tastesummary>b{font-size:var(--fs-xl)}}
.scards{display:grid;grid-template-columns:repeat(auto-fit,minmax(280px,1fr));gap:14px;margin-bottom:18px}
.scard2{background:color-mix(in srgb,var(--surface) 82%,transparent);border:1px solid var(--line-soft);
border-radius:14px;padding:18px;box-shadow:0 14px 36px -30px #000}
diff --git a/web/app.js b/web/app.js
index 3eafc1005..9a9c088ba 100644
--- a/web/app.js
+++ b/web/app.js
@@ -12,7 +12,7 @@ const api=async(p,o)=>{
};
const pageTitle=path=>{
const url=new URL(path,location.origin),parts=decodeURIComponent(url.pathname).split('/').filter(Boolean);
- const fixed={stats:'统计',review:'人工复核',duplicates:'重复文件','quality-goals':'高清版',
+ const fixed={stats:'统计',taste:'品味',review:'人工复核',duplicates:'重复文件','quality-goals':'高清版',
follow:'关注','follow-manage':'关注管理',playlists:'播放列表',performers:'女优',studios:'厂牌',
creators:'创作者',series:'系列',tags:'标签',unseen:'没看过','watch-later':'稍后看',flagged:'已标记',
immerse:'沉浸模式',mix:'Mix',item:'作品'};
@@ -1008,6 +1008,93 @@ function showHomeSurfaces(){
}
function closeStats(push=true){if(push)route('/');showHomeSurfaces();load(true)}
+let tasteWindow='all';
+const tasteDate=value=>value?new Date(value).toLocaleDateString('zh-CN'):'—';
+const tasteHours=seconds=>seconds>=3600?(seconds/3600).toFixed(1)+' 小时':Math.round(seconds/60)+' 分钟';
+const tasteRanking=(title,rows,kind,empty='暂无足够证据')=>`<section class="tastepanel"><h3>${title}</h3>
+ <div class="tasteranks">${rows.length?rows.map((row,index)=>{
+ const clickable=kind&&row.peach_items>0;
+ const detail=row.web_visits!=null
+ ?`${row.evidence.join(' + ')} · 浏览 ${row.web_visits} · Peach ${row.peach_items}`
+ :`${Number(row.score||row.visits||0).toLocaleString()}`;
+ return `<${clickable?'button':'div'} class="tasterank"${clickable?` data-taste-kind="${kind}" data-taste-name="${esc(row.name)}"`:''}>
+ <span class="tastepos mono">${index+1}</span><span><b>${esc(row.name)}</b><small>${esc(detail)}</small></span>
+ ${clickable?icon('chevron-right'):''}</${clickable?'button':'div'}>`}).join(''):`<p class="empty">${empty}</p>`}</div></section>`;
+function openTasteSignal(kind,name){
+ if(kind==='tag'){
+ state={...state,tag:name,tag_match:'all',creator:'',studio:'',q:'',state:'',orient:''};
+ $('#q').value='';route(homePath());showHomeSurfaces();buildBars();load(true);return
+ }
+ openEntity(kind,name);
+}
+function renderTaste(d){
+ const s=d.summary||{},coverage=d.coverage||{},rank=d.rankings||{},storage=d.storage||{};
+ const summary=(label,value,sub)=>`<div class="tastesummary"><span>${label}</span><b>${value}</b><small>${sub}</small></div>`;
+ const sourceRows=(d.sources||[]).map(source=>`<div class="tastesource">
+ <span class="tastebrowser">${icon(source.browser==='browserexport'?'upload':'database')}</span>
+ <span><b>${esc(source.profile)}</b><small>${esc(source.browser)} · ${esc(source.host)} · ${Number(source.visits||0).toLocaleString()} 条</small></span>
+ <button data-taste-remove="${source.source_key}" title="移除分析记录" aria-label="移除 ${esc(source.profile)}">${icon('trash')}</button></div>`).join('');
+ const gapRows=(d.gaps||[]).map(row=>({...row,evidence:['浏览记录']}));
+ const domainRows=(rank.domains||[]).map(row=>({name:row.name,score:row.visits}));
+ const categoryRows=(rank.categories||[]).map(row=>({name:row.name,score:row.score}));
+ const negativeRows=(rank.negative_tags||[]).map(row=>({name:row.name,score:row.disliked_items}));
+ $('#stats').innerHTML=`<div class="tastepage">
+ <header class="tastehead"><div><p>${d.updated_at?`更新于 ${tasteDate(d.updated_at)}`:'尚未采集浏览记录'}</p></div>
+ <div class="tasteactions"><select data-taste-window aria-label="分析范围">
+ <option value="all">全部时间</option><option value="365d">最近一年</option><option value="90d">最近 90 天</option></select>
+ <button data-taste-refresh>${icon('refresh-cw')}读取本机浏览器</button>
+ <button data-taste-import>${icon('upload')}导入历史</button><input data-taste-file type="file" hidden></div></header>
+ <div class="tastestate" data-taste-state role="status" aria-live="polite"></div>
+ <div class="tastesummaries">
+ ${summary('浏览记录',Number(s.history_visits||0).toLocaleString(),`${s.history_sources||0} 个数据源 · ${tasteDate(s.range_start)}—${tasteDate(s.range_end)}`)}
+ ${summary('Peach 看过',Number(s.peach_items||0).toLocaleString(),tasteHours(s.peach_seconds||0))}
+ ${summary('明确反馈',Number(s.liked||0).toLocaleString(),`喜欢 ${s.liked||0} · 不喜欢 ${s.disliked||0}`)}
+ ${summary('私有导出',Number(storage.exports||0).toLocaleString(),fmtSize(storage.bytes||0))}</div>
+ <div class="tastegrid">
+ ${tasteRanking('口味维度',categoryRows,'')}
+ ${tasteRanking('Tag',rank.tags||[],'tag')}
+ ${tasteRanking('创作者',rank.creators||[],'creator')}
+ ${tasteRanking('女优',rank.performers||[],'performer')}
+ ${tasteRanking('浏览候选',gapRows,'','这些词在浏览记录中出现,但 Peach 观看记录还没有对应证据')}
+ ${tasteRanking('常访问来源',domainRows,'')}
+ ${tasteRanking('不合口味',negativeRows,'','Peach 里还没有明确的不喜欢标签')}
+ <section class="tastepanel"><h3>数据完整度</h3><div class="tastecoverage">
+ <div><b>${coverage.tagged||0}</b><span>有标签</span><small>${coverage.untagged||0} 项待补</small></div>
+ <div><b>${coverage.identified||0}</b><span>有身份</span><small>${coverage.unidentified||0} 项待补</small></div></div></section>
+ </div>
+ <section class="tastepanel tastesources"><header><h3>数据源</h3><p>移除只清理分析库;原始导出仍保留在本机私有 sources。</p></header>
+ <div>${sourceRows||'<p class="empty">导入 Google Takeout ZIP、browserexport SQLite / JSON / JSONL,或读取本机浏览器。</p>'}</div></section>
+ <p class="tasteprivacy">原始 URL、标题与搜索内容不会显示在页面,也不会写入 ledger;所有画像均为候选。</p>
+ </div>`;
+ const root=$('#stats'),stateEl=root.querySelector('[data-taste-state]'),file=root.querySelector('[data-taste-file]');
+ root.querySelector('[data-taste-window]').value=d.window||tasteWindow;
+ root.querySelector('[data-taste-window]').onchange=e=>{tasteWindow=e.target.value;openTaste(false)};
+ root.querySelector('[data-taste-refresh]').onclick=async e=>{const button=e.currentTarget;button.disabled=true;stateEl.textContent='正在读取本机浏览器…';
+ try{const result=await api('/api/taste/refresh',{method:'POST',body:JSON.stringify({window:tasteWindow})});renderTaste(result.dashboard)}
+ catch(error){stateEl.textContent=error.message||'读取失败';button.disabled=false}};
+ root.querySelector('[data-taste-import]').onclick=()=>file.click();
+ file.onchange=async()=>{const selected=file.files[0];if(!selected)return;stateEl.textContent=`正在导入 ${selected.name}…`;
+ try{const response=await fetch('/api/taste/import',{method:'POST',headers:{'Content-Type':'application/octet-stream','X-Peach-Filename':encodeURIComponent(selected.name)},body:selected});
+ const payload=await response.json().catch(()=>null);if(!response.ok)throw new Error(payload?.error||`导入失败(${response.status})`);
+ tasteWindow='all';renderTaste(payload.dashboard)}catch(error){stateEl.textContent=error.message||'导入失败'}};
+ root.querySelectorAll('[data-taste-kind]').forEach(button=>button.onclick=()=>openTasteSignal(button.dataset.tasteKind,button.dataset.tasteName));
+ root.querySelectorAll('[data-taste-remove]').forEach(button=>button.onclick=async()=>{
+ if(!confirm('从品味分析中移除这个数据源?原始导出文件会保留。'))return;
+ button.disabled=true;stateEl.textContent='正在移除…';
+ try{const result=await api('/api/taste/source',{method:'POST',body:JSON.stringify({operation:'remove',source_key:button.dataset.tasteRemove,window:tasteWindow})});renderTaste(result.dashboard)}
+ catch(error){stateEl.textContent=error.message||'移除失败';button.disabled=false}});
+}
+async function openTaste(push=true){
+ releaseHoverPreviews();disposeStage(false);document.body.classList.remove('entity-open');
+ if(push)route('/taste');
+ $('#stats').hidden=false;$('#index').hidden=true;$('#grid').innerHTML='';$('#count').textContent='';
+ $('#loadSentinel').hidden=true;$('#shortsSec').hidden=true;buildManageBar();
+ $('#stats').innerHTML='<div class="tastepage"><p class="empty">正在分析…</p></div>';
+ try{const data=await api('/api/taste?window='+tasteWindow);if(location.pathname==='/taste')renderTaste(data)}
+ catch(error){$('#stats').innerHTML=`<div class="tastepage"><p class="empty">${esc(error.message||'分析未取得')}</p></div>`}
+ window.scrollTo({top:0,behavior:'smooth'});
+}
+
function playlistDialog(content){
document.querySelector('#playlistDialog')?.remove();
const dialog=document.createElement('dialog');dialog.id='playlistDialog';dialog.className='playlistdialog';
@@ -2883,6 +2970,7 @@ const EDGE_ICONS=[
原先把它夹在高清版和回收站中间,两边都不挨着。 */
const MANAGE_SECTIONS=[
['stats','统计','chart'],
+ ['taste','品味','heart'],
['review','人工复核','square-check-big'],
['ads','疑似广告','alert'],
['dupes','重复文件','hard-drive'],
@@ -2996,6 +3084,7 @@ function renderSidebarOrderSetting(){
function manageSection(){
const path=decodeURIComponent(location.pathname);
if(path==='/stats')return 'stats';
+ if(path==='/taste')return 'taste';
if(path==='/review')return 'review';
if(path==='/trash')return 'trash';
if(path==='/duplicates')return 'dupes';
@@ -3033,6 +3122,7 @@ function paintListTitle(){
}
function openManage(section='stats'){
if(section==='stats'){openStats();return}
+ if(section==='taste'){openTaste();return}
if(section==='review'){openReview();return}
if(section==='dupes'){openDuplicates();return}
if(section==='quality'){openQualityGoals();return}
@@ -4087,6 +4177,7 @@ async function refreshAll(automatic=false){
!$('#stage').hidden||!$('#tok').hidden||selectMode||selected.size||document.activeElement===$('#q')))return false;
if(!$('#stats').hidden){
if(location.pathname==='/review'){await openReview(false);return}
+ if(location.pathname==='/taste'){await openTaste(false);return}
if(location.pathname==='/duplicates'){await openDuplicates(false);return}
if(location.pathname==='/quality-goals'){await openQualityGoals(false);return}
if(location.pathname==='/playlists'){await openPlaylists(false);return}
@@ -4164,6 +4255,7 @@ async function restoreRoute(){
tagIndexCategory=TAG_CATEGORIES.some(([key])=>key===category)?category:'all'}
await openIndex(path.slice(1),params.get('q')||'',false);return}
if(path==='/stats'){await openStats(false);return}
+ if(path==='/taste'){await openTaste(false);return}
if(path==='/review'){await openReview(false);return}
if(path==='/duplicates'){await openDuplicates(false);return}
if(path==='/quality-goals'){await openQualityGoals(false);return}
diff --git a/web/index.html b/web/index.html
index 4fcc38169..566396311 100644
--- a/web/index.html
+++ b/web/index.html
@@ -56,6 +56,8 @@
<symbol id="i-chevron-up" viewBox="0 0 24 24"><path d="m18 15-6-6-6 6"/></symbol>
<symbol id="i-chevron-down" viewBox="0 0 24 24"><path d="m6 9 6 6 6-6"/></symbol>
<symbol id="i-heart" viewBox="0 0 24 24"><path d="M2 9.5a5.5 5.5 0 0 1 9.591-3.676.56.56 0 0 0 .818 0A5.49 5.49 0 0 1 22 9.5c0 2.29-1.5 4-3 5.5l-5.492 5.313a2 2 0 0 1-3 .019L5 15c-1.5-1.5-3-3.2-3-5.5"/></symbol>
+ <symbol id="i-upload" viewBox="0 0 24 24"><path d="M12 3v12"/><path d="m7 8 5-5 5 5"/><path d="M5 14v5a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2v-5"/></symbol>
+ <symbol id="i-database" viewBox="0 0 24 24"><ellipse cx="12" cy="5" rx="9" ry="3"/><path d="M3 5v14c0 1.7 4 3 9 3s9-1.3 9-3V5"/><path d="M3 12c0 1.7 4 3 9 3s9-1.3 9-3"/></symbol>
<symbol id="i-play" viewBox="0 0 24 24"><path d="M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z"/></symbol>
<symbol id="i-clock" viewBox="0 0 24 24"><circle cx="12" cy="12" r="10"/><path d="M12 6v6l4 2"/></symbol>
<symbol id="i-external-link" viewBox="0 0 24 24"><path d="M15 3h6v6"/><path d="M10 14 21 3"/><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/></symbol>