Files
UHD_Media_Tool/apps/web/app/components/library/identity-pool-sheet.tsx
T
rootandClaude Opus 5.5 f4666a4671 feat(identity): web metadata enrichment for titles missing on TMDB (META-1)
- metadata.enrich (propose, low, replay safe): normalized-title cache (kv_cache
  region enrich, 7 days) -> daily budget -> web.search (title + 短剧 / 电视剧 平台,
  second query limited to whitelist via site:) -> web.fetch of up to 3 relevant
  whitelisted pages (registered site domains never read, redirects out of the
  whitelist dropped) -> upstream model extraction with rule fallback -> server-side
  evidence check (rule_confirmed / multi_evidence / needs_review). Suggestion only.
- POST /identity-pool/{id}/enrich (suggest) and /enrich/apply (console session):
  provisional entity or same-title merge, season/episode units, field-level
  metadata with source web/agent + evidence, aliases, release assignment.
  Poster proxy GET /img/enrich/{id} (og:image from whitelisted pages only).
- Auto-enrich once per pool entry when subscription/rule lookups find nothing on
  TMDB (identity.autoEnrich, off by default); identity.enrichDailyBudget,
  identity.enrichDomains settings; web.fetch now returns og:image.
- Pool sheet "元数据补全" section; entity detail shows evidence links.
- Migration 0049_enrichment (metadata_enrichment, metadata_field.evidence, source
  web). Requires image rebuild / api + worker restart to take effect.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-09-29 15:57:48 +08:00

271 lines
11 KiB
TypeScript

import type { IdentityPoolItem, PoolCandidate } from "@umt/contracts";
import { ArrowRight, BellOff, ExternalLink, LoaderCircle, RotateCw } from "lucide-react";
import { useId, useState } from "react";
import { Link } from "react-router";
import { toast } from "sonner";
import { useAssignPool, useDismissPool, useRetryPool } from "~/api/identity.ts";
import { DetailSection, DetailSheet } from "~/components/console/detail-sheet.tsx";
import { FormField } from "~/components/console/form-field.tsx";
import { JsonView } from "~/components/console/json-view.tsx";
import { KvList } from "~/components/console/kv-list.tsx";
import { consolePath } from "~/components/console/nav.ts";
import { EntityPicker, type PickedEntity } from "~/components/library/identity-entity-picker.tsx";
import { Button } from "~/components/ui/button.tsx";
import { Input } from "~/components/ui/input.tsx";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "~/components/ui/select.tsx";
import { errorMessage } from "~/lib/api.ts";
import { formatDateTime } from "~/lib/utils.ts";
import { EnrichSection } from "./identity-enrich.tsx";
import { EVIDENCE_LEVEL, POOL_REASON, POOL_STATUS } from "./labels.ts";
import { Chip, Tone } from "./parts.tsx";
// 待识别资源详情:候选证据 + 重新识别 + 手动指定。进了待处理的(与订阅相关的歧义 / 无结果)在待处理里选候选;
// 没进待处理的(unmatched:未命中订阅,惰性识别没查 TMDB)在这里手动指定 TMDB ID / 本地作品,或忽略。
/** 与订阅 / 本地作品相关的歧义开"待确认身份"事项,相关却无结果开"待识别"事项(同来源同标题合并);unmatched 不进待处理 */
export function inInbox(item: Pick<IdentityPoolItem, "status" | "reason" | "candidates" | "decisionId">): boolean {
return item.status === "pending" && (item.decisionId !== null || hasCandidates(item));
}
function hasCandidates(item: Pick<IdentityPoolItem, "reason" | "candidates">): boolean {
return (item.reason === "ambiguous" || item.reason === "proposed") && item.candidates.length > 0;
}
export const INBOX_IDENTITY = `${consolePath("inbox")}?kind=identity_ambiguous`;
export const INBOX_UNRESOLVED = `${consolePath("inbox")}?kind=identity_unresolved`;
/** 条目对应的待处理筛选链接 */
export function inboxLink(item: Pick<IdentityPoolItem, "reason" | "candidates">): string {
return hasCandidates(item) ? INBOX_IDENTITY : INBOX_UNRESOLVED;
}
/** query 摘要:标题 / 年份 / 季集 */
export function querySummary(q: Record<string, unknown>): string {
const parts: string[] = [];
if (q.title) parts.push(String(q.title));
if (q.year) parts.push(String(q.year));
if (q.season !== undefined && q.season !== null) parts.push(`S${String(q.season).padStart(2, "0")}`);
if (q.episode !== undefined && q.episode !== null) parts.push(`E${String(q.episode).padStart(2, "0")}`);
if (q.segment) parts.push(String(q.segment));
if (q.cut) parts.push(String(q.cut));
return parts.join(" · ") || "—";
}
function CandidateRow({ c, index }: { c: PoolCandidate; index: number }) {
return (
<li className="min-w-0 rounded-lg border border-border/80 p-3">
<div className="flex flex-wrap items-start justify-between gap-2">
<div className="min-w-0">
<p className="font-medium break-words text-foreground">
{index + 1}. {c.title}
{c.year ? ` (${c.year})` : ""}
</p>
<p className="font-mono text-meta break-all text-muted-foreground">
{c.provider}:{c.entityType}:{c.externalId}
</p>
</div>
</div>
<div className="mt-2 flex flex-wrap items-center gap-1.5">
<Chip>{EVIDENCE_LEVEL[c.level] ?? c.level}</Chip>
{c.localEntityId ? (
<Link
to={consolePath("library", c.localEntityId)}
className="inline-flex items-center gap-1 text-meta text-muted-foreground underline-offset-4 hover:text-foreground hover:underline"
>
本地作品
<ExternalLink className="h-3 w-3" />
</Link>
) : (
<span className="text-meta text-muted-foreground">本地未建档</span>
)}
</div>
{c.evidence.length ? (
<ul className="mt-2 list-disc space-y-0.5 pl-5 text-meta text-muted-foreground">
{c.evidence.map((e) => (
<li key={e} className="break-words">
{e}
</li>
))}
</ul>
) : null}
</li>
);
}
/** 手动指定(复用 /identity-pool/{id}/assign,加人工锁)与忽略 */
function ManualAssign({ item }: { item: IdentityPoolItem }) {
const uid = useId();
const assign = useAssignPool();
const dismiss = useDismissPool();
const [tmdbType, setTmdbType] = useState<"movie" | "tv">(item.query.season != null ? "tv" : "movie");
const [tmdbId, setTmdbId] = useState("");
const [entity, setEntity] = useState<PickedEntity | null>(null);
const tmdbOk = /^\d{1,10}$/.test(tmdbId.trim());
const run = async (body: Parameters<typeof assign.mutateAsync>[0], ok: string) => {
try {
await assign.mutateAsync(body);
toast.success(ok);
} catch (err) {
toast.error(errorMessage(err, "指定失败"));
}
};
return (
<DetailSection title="手动指定">
<div className="grid gap-x-2 sm:grid-cols-[8rem_minmax(0,1fr)_auto] sm:items-end">
<FormField label="类型" htmlFor={`${uid}-type`}>
<Select value={tmdbType} onValueChange={(v) => setTmdbType(v as "movie" | "tv")}>
<SelectTrigger id={`${uid}-type`} className="w-full">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="movie">电影</SelectItem>
<SelectItem value="tv">剧集</SelectItem>
</SelectContent>
</Select>
</FormField>
<FormField label="TMDB ID" htmlFor={`${uid}-tmdb`} hint="纯数字,如 872585">
<Input
id={`${uid}-tmdb`}
inputMode="numeric"
value={tmdbId}
onChange={(e) => setTmdbId(e.target.value)}
aria-invalid={tmdbId.trim() !== "" && !tmdbOk}
/>
</FormField>
<Button
variant="outline"
className="mb-4"
disabled={!tmdbOk || assign.isPending}
onClick={() =>
run(
{
id: item.id,
external: { provider: "tmdb", entityType: tmdbType, externalId: tmdbId.trim() },
lock: true,
},
"已按 TMDB ID 指定",
)
}
>
指定
</Button>
</div>
<div className="grid gap-x-2 sm:grid-cols-[minmax(0,1fr)_auto] sm:items-end">
<FormField label="或选本地作品">
<EntityPicker value={entity} onChange={setEntity} />
</FormField>
<Button
variant="outline"
className="mb-4"
disabled={!entity || assign.isPending}
onClick={() => entity && run({ id: item.id, mediaEntityId: entity.id, lock: true }, "已关联本地作品")}
>
关联
</Button>
</div>
<Button
variant="ghost"
size="sm"
disabled={dismiss.isPending}
onClick={async () => {
try {
await dismiss.mutateAsync({ id: item.id });
toast.success("已忽略");
} catch (err) {
toast.error(errorMessage(err, "操作失败"));
}
}}
>
<BellOff />
忽略此资源
</Button>
</DetailSection>
);
}
export function PoolSheet({ item, onClose }: { item: IdentityPoolItem | null; onClose: () => void }) {
const retry = useRetryPool();
if (!item) return null;
const queued = inInbox(item);
return (
<DetailSheet
open
width="lg"
onOpenChange={(o) => !o && onClose()}
title={item.release.title}
description={item.release.subtitle ?? undefined}
footer={
<>
<Button
variant="outline"
disabled={retry.isPending}
onClick={async () => {
try {
await retry.mutateAsync(item.id);
toast.success("已重新识别");
} catch (err) {
toast.error(errorMessage(err));
}
}}
>
{retry.isPending ? <LoaderCircle className="animate-spin" /> : <RotateCw />}
重新识别
</Button>
{queued ? (
<Button asChild>
<Link to={inboxLink(item)}>
去待处理
<ArrowRight />
</Link>
</Button>
) : null}
</>
}
>
{queued ? (
<p className="rounded-lg border border-warning/40 bg-warning/10 px-3 py-2 text-caption text-warning">
已进待处理,在那里选择候选或忽略。
</p>
) : null}
<KvList
items={[
{ label: "状态", value: <Tone v={POOL_STATUS[item.status]} /> },
{ label: "原因", value: <Tone v={POOL_REASON[item.reason]} /> },
{ label: "解析结果", value: querySummary(item.query), wide: true },
{ label: "站点分类", value: item.release.categoryRaw },
{ label: "首次发现", value: formatDateTime(item.release.firstSeenAt) },
{ label: "尝试次数", value: String(item.attempts) },
{ label: "上次尝试", value: formatDateTime(item.lastAttemptAt) },
{ label: "下次复查", value: item.nextReviewAt ? formatDateTime(item.nextReviewAt) : "不再自动复查" },
{ label: "证据版本", value: item.evidenceVersion, mono: true },
]}
/>
{item.status !== "resolved" && !queued ? <ManualAssign item={item} /> : null}
{item.status === "pending" && item.reason !== "ambiguous" && item.reason !== "proposed" ? (
<EnrichSection key={item.id} item={item} />
) : null}
<DetailSection title={`候选(${item.candidates.length})`}>
{item.candidates.length ? (
<ul className="space-y-2">
{item.candidates.map((c, i) => (
<CandidateRow key={`${c.provider}:${c.entityType}:${c.externalId}`} c={c} index={i} />
))}
</ul>
) : (
<p className="text-caption text-muted-foreground">
{item.reason === "unmatched"
? "没有命中订阅或本地作品,未查询 TMDB。点「重新识别」会查一次 TMDB;新增相近别名时自动重试。"
: "没有候选。有新证据时自动重试。"}
</p>
)}
</DetailSection>
<JsonView label="解析条件(原始)" value={item.query} defaultOpen={false} />
</DetailSheet>
);
}