From 26a752b7aeec0fe1eede7a2400b70fef6ae2ecd7 Mon Sep 17 00:00:00 2001 From: Adeel Ahmad Date: Thu, 15 Oct 2026 00:15:56 +0000 Subject: [PATCH] feat(evidence): put everything Lens found about a resource in its evidence PDF After each resource's own file, an evidence PDF now has pages of what Lens holds about it: details, metadata and custom fields, tags, topics, the summary and analysis models wrote, sections, speakers, emotion and sounds (overall, by speaker, and marked on each transcript line), entities, keywords, what is seen in it, and the places and dates found in it. Shared notes, highlights and comments go in when picked; private notes never do. `include` picks the parts in the API, and the web app's Export menu and collection page open a picker. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01Cbw4LbcmWzn27B4ai6tX7C --- CHANGELOG.md | 7 + docs/api.md | 29 +- fastapi_backend/app/api/evidence.py | 17 +- .../app/api/v1/routes/collections.py | 18 +- .../app/api/v1/routes/recordings.py | 13 +- fastapi_backend/app/domain/evidence.py | 46 +- fastapi_backend/app/domain/evidence_report.py | 579 ++++++++++++++++++ fastapi_backend/app/schemas/recordings.py | 18 + fastapi_backend/tests/api/test_evidence.py | 200 +++++- .../__tests__/evidence-parts.test.tsx | 47 ++ nextjs-frontend/app/openapi-client/sdk.gen.ts | 10 +- .../app/openapi-client/types.gen.ts | 50 +- .../collections/collection-detail.tsx | 39 +- .../components/evidence/parts-dialog.tsx | 122 ++++ .../components/recording/header.tsx | 84 +-- nextjs-frontend/components/recording/hooks.ts | 8 +- nextjs-frontend/openapi.json | 80 ++- threat-model.md | 1 + threat-model.yaml | 10 +- 19 files changed, 1300 insertions(+), 78 deletions(-) create mode 100644 fastapi_backend/app/domain/evidence_report.py create mode 100644 nextjs-frontend/__tests__/evidence-parts.test.tsx create mode 100644 nextjs-frontend/components/evidence/parts-dialog.tsx diff --git a/CHANGELOG.md b/CHANGELOG.md index 176d51f97..f2b17679b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,13 @@ The backend (`fastapi_backend`) and the frontend (`nextjs-frontend`) are version ## Unreleased +- **Evidence PDFs hold everything Lens found.** After each resource's own file come pages of what Lens knows about + it: its details, metadata and custom fields, tags, topics, the summary and analysis models wrote, its sections, + speakers, emotion and sounds (overall, by speaker, and marked on each transcript line, such as "(Happy, Laughter)"), + entities, keywords, the faces, objects, descriptions and text on screen seen in it, and the places and dates found + in it. Notes, highlights and comments people shared go in when picked. Export › Choose what goes in it… (and the + button beside a collection's Evidence PDF) picks the parts, and `include` does the same in the API + ([Evidence PDFs](docs/api.md#evidence-pdfs)). - **Apache Tika.** Lens can use an Apache Tika server (`--profile tika` in the compose files, or one of your own, set in Settings → Documents). Documents nothing here can make into a PDF, such as Word files on a lean server or a Raspberry Pi, are read by Tika as text, and every document's own title, authors, language and dates are read as diff --git a/docs/api.md b/docs/api.md index 5523d0134..3e62ce889 100644 --- a/docs/api.md +++ b/docs/api.md @@ -544,11 +544,38 @@ Manifest with a Canvas per page ([IIIF](iiif.md)), and its public page shows its collection you can read (a list in its own order, a filter's oldest first; 50 at most), as one PDF to hand on, made by [anytopdf](configuration.md#anytopdf). Each resource goes in as its own file: a document or an image as it is, a captured web page as captured, audio or video with Lens's transcript of it (its speakers' names on each line), and a -transcript without media as its text. The PDF is searchable PDF/A-3 with its text and chunks embedded, and its last +transcript without media as its text. After it come the pages of what Lens found about it, a text file of its own +named ` - what Lens found.txt`. The PDF is searchable PDF/A-3 with its text and chunks embedded, and its last page is a provenance page giving every file's SHA-256 and size, so whoever gets it can check each part against the file it came from. It holds no paths of the server (anytopdf's `share` profile), is made when asked for, and nothing of it is kept. Anyone who can read the resources can have it (share links and signed links can't). +`include` picks its parts (repeat it for several, `?include=file&include=summary`); without it, every part but +`notes` goes in. In the web app, a resource's Export menu has Evidence PDF (the default parts) and Choose what goes in +it…, and a collection's page has the same beside its Evidence PDF button; the picks are remembered in the browser. + +| Part | What goes in | +| --- | --- | +| `file` | its own file, as above | +| `details` | what it is, when it was recorded and added, its length or pages, size, language, words, content type, where it came from, its status; an email's subject, sender, recipients and date; a web page's address and when it was captured; what a document says about itself (Tika) and how its PDF was made | +| `metadata` | its description as saved over what it says about itself: title, description, date, language, creators, contributors, subjects, identifiers, rights, attribution, provider, related links, access, Dublin Core terms and other statements, and its custom fields | +| `tags` | its tags | +| `topics` | the topics it's about: accepted ones, then suggested ones, each saying how it came | +| `summary` | the summary a model wrote, its key points and follow-ups (each with where it comes from), the people and topics it names, its overall tone and importance | +| `analysis` | what its pipeline's model steps saved, by key, with the model | +| `sections` | its sections, with where each starts | +| `speakers` | who spoke, for how long and what share of the speech, their turns, words and pace, and how each was recognised | +| `emotion` | the share of the speech time of each emotion, overall and by speaker, and the sounds heard; each transcript line is marked with its emotion and sound, such as "(Happy, Laughter)" (neutral speech isn't marked) | +| `entities` | the names it mentions by type (people, organisations, places, dates …), each with how often | +| `keywords` | its keywords | +| `visual` | its shots, the faces found (and who, when recognised), the objects seen, what a model said each page or shot shows, and the text on screen, with where each is | +| `places` | the places and dates anytopdf found in it and where a photo was taken (members of its namespace only, as on its page) | +| `notes` | the highlights, shared notes and comments on it, with who wrote them (names only); never anyone's private notes | + +What a model wrote (the summary, analysis and descriptions) says so on its page. A list longer than 1,000 lines (text +on screen in a long video, say) shows the first 1,000 and says how many more there are. Making these pages calls no +model: they're read from what Lens already stored. + anytopdf runs as it does for conversions (no network, plugins or config file of its own); if it isn't here it's fetched on first use, unless Settings › Documents says never to use it (503). A conversion node takes one file per job and its own options: a single document goes as it is, and more go as one zip, with audio and video as their diff --git a/fastapi_backend/app/api/evidence.py b/fastapi_backend/app/api/evidence.py index fd68375d9..6d04b15d1 100644 --- a/fastapi_backend/app/api/evidence.py +++ b/fastapi_backend/app/api/evidence.py @@ -5,19 +5,28 @@ import urllib.error from typing import Any -from fastapi import HTTPException +from fastapi import HTTPException, Query from fastapi.responses import Response from app.api.streaming import LOCKED -from app.domain import anytopdf, evidence, keyring +from app.domain import anytopdf, evidence, evidence_report, keyring from app.domain.store import DB +from app.schemas.recordings import EvidencePart PDF: dict[int | str, dict[str, Any]] = {200: {"content": {"application/pdf": {}}}} +INCLUDE = Query( + None, + description="the parts of the PDF; repeat for several. Without it: every part but notes. " + + "; ".join(f"{k}: {v}" for k, v in evidence_report.PARTS.items()), +) -def download(db: DB, cfg: dict[str, Any], rids: list[int], title: str) -> Response: +def download( + db: DB, cfg: dict[str, Any], rids: list[int], title: str, include: list[EvidencePart] | None = None, places: set[int] | None = None +) -> Response: + """The evidence PDF of these resources as a download. `places`: the ones whose places the reader may see.""" try: - data = evidence.make(db, cfg, rids) + data = evidence.make(db, cfg, rids, include, places) except keyring.Locked: raise HTTPException(423, LOCKED) from None except FileNotFoundError as e: diff --git a/fastapi_backend/app/api/v1/routes/collections.py b/fastapi_backend/app/api/v1/routes/collections.py index 841721fc7..3e8290ef4 100644 --- a/fastapi_backend/app/api/v1/routes/collections.py +++ b/fastapi_backend/app/api/v1/routes/collections.py @@ -16,6 +16,7 @@ from app.domain.store import DB from app.schemas.collections import Collection, CollectionCreate, CollectionDetail, CollectionUpdate from app.schemas.common import Created, Ok +from app.schemas.recordings import EvidencePart router = APIRouter(prefix="/collections", tags=["collections"]) @@ -65,14 +66,25 @@ def get_collection(cid: int, user: CurrentUser, acl: Acl, db: Db) -> CollectionD @router.get("/{cid}/evidence.pdf", response_class=Response, responses=evidence_api.PDF) -def collection_evidence(cid: int, user: CurrentUser, acl: Acl, db: Db, cfg: Cfg) -> Response: +def collection_evidence( + cid: int, user: CurrentUser, acl: Acl, db: Db, cfg: Cfg, include: list[EvidencePart] | None = evidence_api.INCLUDE +) -> Response: """The collection's recordings you can read (a list in its order, a filter's oldest first) as one evidence PDF made by anytopdf (a download): each - one's pages, then a provenance page with every file's SHA-256 and size. At most 50 recordings.""" + one's pages and what Lens found about it, then a provenance page with every file's SHA-256 and size. `include` picks the parts, as for a + resource's evidence PDF. At most 50 recordings.""" col = own_collection(db, cid, user) ids = recsets.members(db, col, set(acl.roles)) if len(ids) > evidence.MAX: raise HTTPException(400, f"an evidence PDF holds {evidence.MAX} recordings at most; this collection has {len(ids)}") - return evidence_api.download(db, cfg, ids if col.get("recordings") is not None else ids[::-1], col["name"]) + recs = ( + db.rows( + "SELECT record::id(id) AS id, space, collection FROM recording WHERE id IN $ids", ids=[store.R("recording", i) for i in ids] + ) + if ids + else [] + ) + places = {r["id"] for r in recs if acl.member(r)} + return evidence_api.download(db, cfg, ids if col.get("recordings") is not None else ids[::-1], col["name"], include, places) @router.patch("/{cid}") diff --git a/fastapi_backend/app/api/v1/routes/recordings.py b/fastapi_backend/app/api/v1/routes/recordings.py index 4a2911719..49a331431 100644 --- a/fastapi_backend/app/api/v1/routes/recordings.py +++ b/fastapi_backend/app/api/v1/routes/recordings.py @@ -41,6 +41,7 @@ from app.schemas.recordings import ( AccessRequest, EmbedLink, + EvidencePart, JobQueued, LanguageCount, MediaKind, @@ -651,12 +652,16 @@ def export_recording(rid: int, fmt: str, acl: Acl, db: Db) -> Response: @router.get("/{rid}/evidence.pdf", response_class=Response, responses=evidence_api.PDF) -def evidence_pdf(rid: int, acl: Acl, db: Db, cfg: Cfg) -> Response: +def evidence_pdf(rid: int, acl: Acl, db: Db, cfg: Cfg, include: list[EvidencePart] | None = evidence_api.INCLUDE) -> Response: """The resource as an evidence PDF, made by anytopdf (a download): its own file's pages (audio and video with - their transcript), searchable, then a provenance page with the file's SHA-256 and size. 503 when anytopdf can't - run here (it's fetched on first use unless Settings › Documents says never to use it).""" + their transcript, each line marked with its emotion and sound), searchable, then the pages of what Lens found + about it (details, metadata, tags, topics, summary, analysis, sections, speakers, emotion, entities, keywords, + what is seen, places and dates; notes when asked for), then a provenance page with each file's SHA-256 and size. + `include` picks the parts. 503 when anytopdf can't run here (it's fetched on first use unless Settings › + Documents says never to use it).""" rec = acl.recording(rid) - return evidence_api.download(db, cfg, [rid], rec.get("title") or f"recording {rid}") + places = {rid} if acl.member(rec) else set() + return evidence_api.download(db, cfg, [rid], rec.get("title") or f"recording {rid}", include, places) @router.patch("/{rid}/segments/{idx}") diff --git a/fastapi_backend/app/domain/evidence.py b/fastapi_backend/app/domain/evidence.py index 8b96090df..3406269e9 100644 --- a/fastapi_backend/app/domain/evidence.py +++ b/fastapi_backend/app/domain/evidence.py @@ -4,8 +4,12 @@ SHA-256 and size, so whoever gets it can check each page against the file it came from. Its text is searchable and its chunks are embedded (PDF/A-3), so what an agent cites from it stays cited. -A resource without a file of its own (an imported transcript) goes in as its text. Nothing is kept: the PDF is made -when asked for, from plain copies in a folder of its own that is removed straight after. +A resource without a file of its own (an imported transcript) goes in as its text. After each resource's file come +the pages of what Lens found about it (evidence_report.py): its details, metadata, tags, topics, summary, analysis, +sections, speakers, emotion and sounds, entities, keywords, what is seen in it and the places and dates in it, each a +part that can be left out (`parts`); the notes, highlights and comments people shared on it go in when asked for. +Nothing is kept: the PDF is made when asked for, from plain copies in a folder of its own that is removed straight +after. """ from __future__ import annotations @@ -15,7 +19,7 @@ import shutil import tempfile -from . import anytopdf, ingest, keyring, render, store +from . import anytopdf, evidence_report, ingest, keyring, render, store R = store.R MAX = 50 # recordings in one evidence PDF, at most @@ -43,12 +47,27 @@ def ready(cfg, say=None): anytopdf.fetch(cfg, say) -def _gather(db, cfg, rid, i, into): - """Put one recording's file (and its transcript, for audio or video) into the folder: (input, transcript or None).""" +def _gather(db, cfg, rid, i, into, parts, places): + """Put one recording's file (and its transcript, for audio or video) and what Lens found about it into the folder: + ([its files, in order], transcript or None).""" rec = db.one("SELECT space, path, remote, source, title, media FROM $r", r=R("recording", rid)) if not rec: raise KeyError(rid) kind, name = render.kind(rec), _name(i, rec.get("title")) + d = render.player_data(db, rid) + out, said = [], None + if "file" in parts: + out, said = _own(db, cfg, rec, rid, kind, name, into, evidence_report.marked(d) if "emotion" in parts else d) + if evidence_report.has_findings(parts): + found = into / f"{name} - what Lens found.txt" + found.write_text(evidence_report.write(db, cfg, rid, parts, d, places), encoding="utf-8") + out.append(found) + return out, said + + +def _own(db, cfg, rec, rid, kind, name, into, d): + """The recording's own file copied into the folder, or its text when it has none: ([that file], its transcript or + None).""" src = None if kind != "transcript" and (rec.get("path") or rec.get("remote")): try: @@ -59,11 +78,10 @@ def _gather(db, cfg, rid, i, into): if kind in ("document", "image"): raise FileNotFoundError(f"the file of “{rec.get('title') or rid}” is missing on the server") src = None - d = render.player_data(db, rid) if src is None: # its text is all there is out = into / f"{name}.txt" out.write_text(render.export_text(d, "txt") or "(no text)\n", encoding="utf-8") - return out, None + return [out], None out = into / f"{name}{pathlib.PurePosixPath(str((rec.get('remote') or {}).get('path') or src)).suffix.lower()}" shutil.copyfile(src, out) said = None @@ -71,16 +89,20 @@ def _gather(db, cfg, rid, i, into): said = into / "transcripts" / f"{name}.srt" said.parent.mkdir(exist_ok=True) said.write_text(render.export_text(d, "srt"), encoding="utf-8") - return out, said + return [out], said -def make(db, cfg, rids): - """The evidence PDF of these recordings, in this order, as bytes.""" +def make(db, cfg, rids, include=None, places=None): + """The evidence PDF of these recordings, in this order, as bytes. `include`: its parts (evidence_report.PARTS; + None: everything but people's notes). `places`: the recordings whose places may go in (None: all of them).""" rids = list(dict.fromkeys(int(r) for r in rids)) if not rids: raise ValueError("there's nothing to put in it") if len(rids) > MAX: raise ValueError(f"an evidence PDF holds {MAX} recordings at most; this has {len(rids)}") + parts = evidence_report.parts_of(include) + if not parts: + raise ValueError("there's nothing to put in it: include its file or something Lens found") ready(cfg) work = pathlib.Path(cfg["data_dir"]) / "tmp" work.mkdir(parents=True, exist_ok=True) @@ -89,8 +111,8 @@ def make(db, cfg, rids): into.mkdir(mode=0o700) inputs, transcripts = [], [] for i, rid in enumerate(rids, 1): - f, t = _gather(db, cfg, rid, i, into) - inputs.append(f) + files, t = _gather(db, cfg, rid, i, into, parts, places is None or rid in places) + inputs += files transcripts += [t] if t else [] out = pathlib.Path(tmp) / "evidence.pdf" anytopdf.evidence(cfg, inputs, transcripts, out) diff --git a/fastapi_backend/app/domain/evidence_report.py b/fastapi_backend/app/domain/evidence_report.py new file mode 100644 index 000000000..3968f9d07 --- /dev/null +++ b/fastapi_backend/app/domain/evidence_report.py @@ -0,0 +1,579 @@ +"""What Lens found about a resource, as plain text for an evidence PDF (evidence.py, docs/api.md#evidence-pdfs). + +An evidence PDF holds each resource's own file and, after it, these pages: its details, metadata, tags and topics, the +summary and analysis models wrote, its sections, speakers, emotion and sounds, entities and keywords, what is seen in +it, the places and dates found in it, and (when asked for) the notes, highlights and comments people shared on it. +Each part can be left out (PARTS). What a model wrote says so, and what is cut short says how much more there is. + +It's plain text because that is what anytopdf reads the same way everywhere, here or on a conversion node: it lays +Markdown and HTML out as text too. Nothing here calls a model; it reads what Lens already stored. +""" + +from __future__ import annotations + +from collections import Counter, defaultdict +from functools import cached_property + +from . import analyze, comments, content_types, entity_setup, fields, highlights, hierarchy, library, metadata, render, store +from . import topics as topicmod + +R = store.R +# the parts of an evidence PDF, in their order there, with what each holds (the API's `include`) +PARTS = { + "file": "its own file: a document's pages, an image, or audio and video with Lens's transcript", + "details": "what it is, when it was made and added, its length, language, content type and where it came from", + "metadata": "its description as saved and derived (Dublin Core terms, rights, creators) and its custom fields", + "tags": "its tags", + "topics": "the topics it is about, accepted and suggested", + "summary": "the summary a model wrote: key points, follow-ups, people, overall tone and importance", + "analysis": "what its pipeline's model steps saved", + "sections": "the sections analysis split it into", + "speakers": "who spoke, for how long, and how each was recognised", + "emotion": "the emotion of what was said and the sounds heard, overall and by speaker, marked on each transcript line", + "entities": "the people, organisations, places and other names it mentions", + "keywords": "its keywords", + "visual": "the faces, objects, descriptions and text on screen seen in it", + "places": "the places and dates anytopdf found in it, and where a photo was taken", + "notes": "the notes, highlights and comments people shared on it", +} +# everything Lens found; people's own words (notes, highlights and comments) only when asked for +DEFAULT = tuple(k for k in PARTS if k != "notes") +MAX_ITEMS = 1000 # of one list (text on screen, descriptions …): the rest is counted, not shown +METHODS = {"voice": "matched by voice", "new": "a new voice", "label": "named in the transcript"} + + +def parts_of(include): + """The parts asked for, in their order: DEFAULT when nothing was said.""" + asked = set(DEFAULT if include is None else include) + unknown = asked - set(PARTS) + if unknown: + raise ValueError(f"an evidence PDF's parts are {', '.join(PARTS)}") + return [k for k in PARTS if k in asked] + + +def marked(d): + """The player's data with each transcript line marked with its emotion and sound, "(Happy, Laughter) …", as in + subtitles for the deaf; Neutral and plain speech aren't marked.""" + out = [] + for x in d["segments"]: + marks = [m for m in (x.get("e"), x.get("v")) if m and m not in ("Neutral", "Speech")] + out.append({**x, "text": f"({', '.join(marks)}) {x['text']}" if marks else x["text"]}) + return {**d, "segments": out} + + +class _Page: + """The text being written: headings, lines and lists.""" + + def __init__(self): + self.lines: list[str] = [] + + def heading(self, title): + self.lines += ["", title, "-" * len(title)] + + def line(self, text=""): + self.lines.append(str(text)) + + def pair(self, label, value): + value = _words(value) + if value: + self.lines.append(f"{label}: {value}") + + def items(self, rows, empty=None): + rows = [r for r in rows if r] + for r in rows[:MAX_ITEMS]: + self.lines.append(f"- {r}") + if len(rows) > MAX_ITEMS: + self.lines.append(f"(and {len(rows) - MAX_ITEMS:,} more, not shown here)") + if not rows and empty: + self.lines.append(empty) + + def text(self): + return "\n".join(self.lines).strip() + "\n" + + +def _words(v): + """A stored value in words: language maps, lists and {name, role}-like objects flattened.""" + if v is None or v == "" or v == [] or v == {}: + return "" + if isinstance(v, bool): + return "yes" if v else "no" + if isinstance(v, (int, float)): + return f"{v:,}" if isinstance(v, int) else f"{v:g}" + if isinstance(v, list): + return "; ".join(w for w in (_words(x) for x in v) if w) + if isinstance(v, dict): + if all(isinstance(x, list) for x in v.values()): # a language map + return "; ".join(w for w in (_words(x) for x in v.values()) if w) + for k in ("name", "label", "value", "text", "title", "id"): + if v.get(k): + rest = [f"{_words(x)}" for kk, x in v.items() if kk in ("role", "type") and x] + return f"{_words(v[k])}{f' ({rest[0]})' if rest else ''}" + return "; ".join(f"{k}: {w}" for k, w in ((k, _words(x)) for k, x in v.items()) if w) + return " ".join(str(v).split()) + + +def _outline(page, v, depth=0): + """Any JSON a model step saved, as nested lines.""" + pad = " " * depth + if isinstance(v, dict): + for k, x in v.items(): + if isinstance(x, (dict, list)) and x: + page.line(f"{pad}{k}:") + _outline(page, x, depth + 1) + elif _words(x): + page.line(f"{pad}{k}: {_words(x)}") + elif isinstance(v, list): + for x in v[:MAX_ITEMS]: + if isinstance(x, dict) and x: + page.line(f"{pad}-") + _outline(page, x, depth + 1) + elif _words(x): + page.line(f"{pad}- {_words(x)}") + if len(v) > MAX_ITEMS: + page.line(f"{pad}(and {len(v) - MAX_ITEMS:,} more, not shown here)") + elif _words(v): + page.line(f"{pad}{_words(v)}") + + +def _n(n, what): + """1 turn, 2 turns.""" + n = n or 0 + return f"{n:,} {what}{'' if n == 1 else 's'}" + + +def _share(part, whole): + return f"{100 * part / whole:.0f}%" if whole else "" + + +class Report: + """One resource's findings. `places`: whether the reader may see where it was (members of its namespace).""" + + def __init__(self, db, cfg, rid, d=None, places=True): + self.db, self.cfg, self.rid, self.places = db, cfg, rid, places + self.rec = db.one("SELECT * FROM $r", r=R("recording", rid)) or {} + if not self.rec: + raise KeyError(rid) + self.d = d or render.player_data(db, rid) + self.kind = render.kind(self.rec) + self.paged = self.kind in ("document", "image") + # a document's lines have reading-pace times: a moment on it is the page of the line it falls in + self._pages = [(x["t0"], x["t1"], x.get("p")) for x in self.d["segments"] if x.get("p") is not None] + + def at(self, t0, t1=None): + """Where in it a moment is: "p. 3" on a document, else "1:02" or "1:02 to 1:30".""" + if t0 is None: + return "" + if self.paged: + page = next((p for a, b, p in self._pages if a <= t0 < b), None) + if page is None and self._pages: + page = max((p for a, _, p in self._pages if a <= t0), default=self._pages[0][2]) + return f"p. {page + 1}" if page is not None else "" + return f"{store.tc(t0)} to {store.tc(t1)}" if t1 is not None and t1 > t0 else store.tc(t0) + + @cached_property + def stats(self): + """Its talk statistics: speakers, emotions, sounds and languages (analyze.talk_stats), with speakers' names.""" + return render.recording_stats(self.db, self.rid) + + def where(self, t, paged=None): + """A face's, an object's or a description's place: a page (from 0) on pages, else a time.""" + return f"p. {t + 1}" if (self.paged if paged is None else paged) else store.tc(t) + + def text(self, parts): + title = self.rec.get("title") or f"Resource {self.rid}" + page = _Page() + page.line(f"What Lens found: {title}") + page.line() + page.line( + f"Lens wrote these pages on {store.now()[:10]} from what it holds about resource {self.rid}. What a model " + "wrote says so; the rest comes from the file and Lens's own steps." + ) + for part in parts: + if part != "file" and (part != "places" or self.places): + getattr(self, f"_{part}")(page) + return page.text() + + # ---------- the parts ---------- + def _details(self, page): + rec, d, st = self.rec, self.d, self.stats + page.heading("Details") + page.pair("Type", self.kind) + page.pair("Namespace", d.get("namespace")) + if rec.get("collection") is not None: + page.pair("Collection", " / ".join(s["name"] for s in hierarchy.path(self.db, rec["collection"]))) + page.pair("Recorded", (rec.get("recorded_at") or "")[:16].replace("T", " ")) + page.pair("Added", (rec.get("created_at") or "")[:16].replace("T", " ")) + media = d.get("media") or {} + if self.paged: + page.pair("Pages", media.get("pages") or len(d.get("pages") or []) or None) + elif d.get("duration_ms"): + page.pair("Length", store.tc(d["duration_ms"])) + if media.get("width") and media.get("height"): + page.pair( + "Size", f"{media['width']} × {media['height']} pixels" + (f", {media['fps']:g} frames a second" if media.get("fps") else "") + ) + page.pair("Language", rec.get("language") if rec.get("language") not in ("none", "nospeech") else None) + if len(st.get("languages") or {}) > 1: + page.pair( + "Languages spoken", ", ".join(f"{k} ({_n(n, 'line')})" for k, n in sorted(st["languages"].items(), key=lambda kv: -kv[1])) + ) + page.pair("Words", st.get("words")) + try: + ct, chosen = content_types.of_recording(self.db, self.rid) + page.pair("Content type", f"{ct['label']} ({'chosen by a person' if chosen else 'recognised by Lens'})" if ct else None) + except KeyError: + pass + origins = library.Origins(self.db, self.cfg) + came = origins.of(rec) + page.pair("Came from", origins.names([came])[came]) + page.pair("Status", rec.get("status")) + if rec.get("attached_to") and rec["attached_to"].get("resource"): + email = self.db.one("SELECT title FROM $r", r=R("recording", int(rec["attached_to"]["resource"]))) or {} + page.pair("Attached to the email", email.get("title") or f"resource {rec['attached_to']['resource']}") + email = rec.get("email") or {} + for k, label in (("subject", "Email subject"), ("from", "From"), ("to", "To"), ("cc", "Cc"), ("date", "Sent")): + page.pair(label, email.get(k)) + web = rec.get("web") or {} + page.pair("Web page", web.get("url")) + if web.get("final") and web.get("final") != web.get("url"): + page.pair("It ended at", web["final"]) + page.pair("Captured", (web.get("captured_at") or "")[:16].replace("T", " ")) + told = rec.get("described") or {} + for k, label in ( + ("title", "Its own title"), + ("creators", "Its authors"), + ("subject", "Its subject"), + ("description", "Its description"), + ("publisher", "Its publisher"), + ("language", "Its language"), + ("created", "Made"), + ("modified", "Last changed"), + ("pages", "Pages it says it has"), + ("words", "Words it says it has"), + ("format", "Its format"), + ): + page.pair(label, told.get(k)) + made = rec.get("rendition") or {} + if made.get("from") and made.get("by"): + page.pair("Read from", f"a PDF {made['by']} made of its {made['from']} file") + + def _metadata(self, page): + meta = metadata.effective(self.db, self.cfg, self.rid) + page.heading("Metadata") + labels = ( + ("label", "Title"), + ("summary", "Description"), + ("navDate", "Date"), + ("language", "Language"), + ("creators", "Creators"), + ("contributors", "Contributors"), + ("subjects", "Subjects"), + ("identifiers", "Identifiers"), + ("rights", "Rights"), + ("attribution", "Attribution"), + ("provider", "Provider"), + ("homepage", "Homepage"), + ("related", "Related"), + ("access", "Access"), + ("open", "Open to anyone when public"), + ("featured", "Featured"), + ) + for k, label in labels: + page.pair(label, meta.get(k)) + for pair in meta.get("metadata") or []: + page.pair(_words(pair.get("label")), pair.get("value")) + for term, vals in sorted((meta.get("terms") or {}).items()): + page.pair(f"dcterms:{term}", vals) + for s in meta.get("statements") or []: + page.pair(s["p"], s["o"]) + defs, row = fields.resource_fields(self.db, self.rid) + for f in fields.shown(defs, row): + if f["value"] is not None: + page.pair(f["field"]["label"], fields.display(f["field"], f["value"])) + + def _tags(self, page): + page.heading("Tags") + page.line(", ".join(self.rec.get("tags") or []) or "None.") + + def _topics(self, page): + found = topicmod.of_recording(self.db, self.rid) + page.heading("Topics") + how = { + "person": "added by a person", + "entity": "made from an entity", + "analysis": "found by analysis", + "assistant": "by an assistant", + } + page.items( + [ + f"{t['label']} ({'accepted' if t['status'] == 'accepted' else 'suggested, not accepted yet'}" + f"{', ' + how[t['source']] if t.get('source') in how else ''})" + for t in sorted(found, key=lambda t: (t["status"] != "accepted", -(t.get("weight") or 0), t["label"].casefold())) + ], + "None.", + ) + + def _summary(self, page): + s = self.d.get("summary") or {} + page.heading("Summary (written by a model)") + if not s: + page.line("None yet.") + return + page.line(s.get("summary") or s.get("tldr") or "") + for key, title in (("key_points", "Key points"), ("action_items", "Follow-ups")): + rows = [] + for x in s.get(key) or []: + x = x if isinstance(x, dict) else {"text": x} + where = f"p. {x['page'] + 1}" if x.get("page") is not None else self.at(x.get("t0")) + rows.append(f"{x.get('who') + ': ' if x.get('who') else ''}{x.get('text')}{f' (at {where})' if where else ''}") + if rows: + page.line() + page.line(f"{title}:") + page.items(rows) + page.line() + page.pair("Topics it names", s.get("topics")) + page.pair("People it names", s.get("people")) + page.pair("Overall tone", s.get("sentiment")) + if s.get("importance"): + page.pair("Importance", f"{s['importance']} of 5") + known = {"summary", "tldr", "key_points", "action_items", "topics", "people", "sentiment", "importance"} + _outline(page, {k: v for k, v in s.items() if k not in known}) + + def _analysis(self, page): + rows = self.db.rows("SELECT key, value, origin, created_at FROM output WHERE recording = $r ORDER BY key", r=self.rid) + page.heading("Analysis (written by models)") + if not rows: + page.line("None.") + for o in rows: + by = (o.get("origin") or {}).get("model") if isinstance(o.get("origin"), dict) else None + page.line() + when = (o.get("created_at") or "")[:10] + page.line(f"{o['key']}{f' (by {by})' if by else ''}{f', {when}' if when else ''}:") + _outline(page, o.get("value"), 1) + + def _sections(self, page): + segs, secs = self.d["segments"], self.d.get("sections") or [] + page.heading("Sections") + rows = [] + for x in secs: + first = segs[x["seg0"]] if 0 <= x.get("seg0", -1) < len(segs) else None + where = f"p. {first['p'] + 1}" if self.paged and first and first.get("p") is not None else self.at(x.get("t0"), x.get("t1")) + rows.append(f"{where}: {x.get('title')}" if where else x.get("title")) + page.items(rows, "None.") + + def _speakers(self, page): + st = self.stats + apps = {a["speaker"]: a for a in self.db.rows("SELECT speaker, method, score FROM appearance WHERE recording = $r", r=self.rid)} + page.heading("Speakers") + speech = st.get("speech_ms") or 0 + rows = [] + for s in st.get("speakers") or []: + a = apps.get(s.get("speaker_id")) or {} + how = METHODS.get(a.get("method"), a.get("method")) + if how and a.get("score") is not None: + how += f", {a['score']:.2f}" + rows.append( + f"{s['name']}: {store.tc(s['talk_ms'])} ({_share(s['talk_ms'], speech)} of the speech), {_n(s.get('turns'), 'turn')}, " + f"{_n(s.get('words'), 'word')}, {s.get('wpm', 0):g} words a minute{f'; {how}' if how else ''}" + ) + page.items(rows, "None found.") + + def _emotion(self, page): + st = self.stats + page.heading("Emotion and sounds") + emo = {k: v for k, v in (st.get("emotions") or {}).items() if v} + total = sum(emo.values()) + if total: + page.line("Share of the speech time:") + page.items([f"{e}: {_share(ms, total)} ({store.tc(ms)})" for e, ms in sorted(emo.items(), key=lambda kv: -kv[1])]) + names = {sp["key"]: sp["name"] for sp in self.d["speakers"]} + by = defaultdict(Counter) + for x in self.d["segments"]: + if x.get("e"): + by[names.get(x.get("s"), "Unattributed")][x["e"]] += max(0, (x.get("t1") or 0) - (x.get("t0") or 0)) + if len(by) > 1 or (by and not total): + page.line() + page.line("By speaker:") + page.items( + [ + f"{who}: " + ", ".join(f"{e} {_share(ms, sum(c.values()))}" for e, ms in c.most_common() if ms) + for who, c in sorted(by.items(), key=lambda kv: -sum(kv[1].values())) + ] + ) + events = st.get("events") or {} + if events: + page.line() + page.line("Sounds heard:") + page.items([f"{e}: {_n(n, 'time')}" for e, n in sorted(events.items(), key=lambda kv: -kv[1])]) + if total or events: + page.line() + page.line( + "Each transcript line is marked with its emotion and sound, such as (Happy, Laughter); unmarked lines were neutral speech." + ) + else: + page.line("None read.") + + def _entities(self, page): + from .entities import TYPES + + ments = self.db.rows("SELECT entity, text FROM mentions WHERE recording = $r", r=self.rid) + ents = ( + { + e["id"]: e + for e in self.db.rows( + "SELECT record::id(id) AS id, space, name, type FROM entity WHERE id IN $ids AND hidden != true", + ids=[R("entity", i) for i in {m["entity"] for m in ments}], + ) + } + if ments + else {} + ) + own = entity_setup.labels(self.db, {e["space"] for e in ents.values()}) + counts = Counter(m["entity"] for m in ments if m["entity"] in ents and ents[m["entity"]]["type"] != "NUMBER") + groups = defaultdict(list) + for eid, n in counts.most_common(): + e = ents[eid] + groups[TYPES.get(e["type"]) or own.get(e["space"], {}).get(e["type"]) or e["type"].title()].append(f"{e['name']} ({n})") + page.heading("Entities") + if not groups: + page.line("None found.") + for kind, names in sorted(groups.items(), key=lambda kv: kv[0] == "Date"): + page.line( + f"{kind}: {', '.join(names[:MAX_ITEMS])}{f' (and {len(names) - MAX_ITEMS:,} more)' if len(names) > MAX_ITEMS else ''}" + ) + + def _keywords(self, page): + words = analyze.keywords(self.db, self.rid, 60) if self.rec.get("analyzed_at") else [] + page.heading("Keywords") + page.line(", ".join(w for w, _ in words) or "None.") + + def _visual(self, page): + d = self.d + page.heading("What's seen") + shown = False + if d.get("shots"): + page.pair("Shots", len(d["shots"])) + shown = True + people = d.get("faces") or [] + if people: + page.line() + page.line(f"Faces ({'recognised' if d.get('faces_mode') == 'recognize' else 'found'}):") + unit = (lambda n: f"on {_n(n, 'page')}") if self.paged else (lambda n: f"{store.tc(n)} on screen") + page.items([f"{t['name']}: {unit(t.get('screen_ms') or 0)}, first at {self.where(t.get('first_ms') or 0)}" for t in people]) + shown = True + objs = d.get("objects") or [] + if objs: + page.line() + page.line("Objects:") + rows = [] + for o in objs: + seen, n = o.get("screen_ms") or 0, o.get("count") or 0 + long = f"on {_n(seen, 'page')}" if o.get("paged") else f"{store.tc(seen)} on screen" + first = self.where(o.get("first_ms") or 0, o.get("paged")) + rows.append(f"{o['label']}: found {_n(n, 'time')}, {long}, first at {first}, {o.get('score') or 0:.2f} sure") + page.items(rows) + shown = True + said = d.get("descriptions") or [] + if said: + models = sorted({x.get("model") for x in said if x.get("model")}) + page.line() + page.line(f"What each {'page' if self.paged else 'shot'} shows (written by {', '.join(models) or 'a model'}):") + page.items([f"{self.where(x['t0'], x.get('paged'))}: {_words(x['text'])}" for x in said]) + shown = True + screen = d.get("screen_text") or [] + if screen: + page.line() + page.line("Text on screen:") + page.items([f"{store.tc(x['t0'])}: {_words(x['text'])}" for x in screen]) + shown = True + if not shown: + page.line("Nothing found." if self.kind == "video" or self.paged else "None: it has no pictures.") + + def _places(self, page): + e = self.rec.get("enrichment") or {} + page.heading("Places and dates") + if not e: + page.line("None found.") + return + + def place(p): + where = ", ".join(x for x in (p.get("name"),) if x) + if p.get("lat") is not None and p.get("lon") is not None: + where += f" ({p['lat']:.5f}, {p['lon']:.5f})" + if p.get("said") and p.get("said") != p.get("name"): + where += f', named as "{p["said"]}"' + return where + + if e.get("place"): + p = e["place"] + page.pair("Where it was taken", place(p) + (f", {p['km']:.1f} km from there" if p.get("km") is not None else "")) + if e.get("places"): + page.line("Places it names:") + page.items([place(p) for p in e["places"]]) + if e.get("dates"): + page.line("Dates it gives:") + page.items([x["text"] + (f" ({x['iso']})" if x.get("iso") and x["iso"] != x["text"] else "") for x in e["dates"]]) + page.pair("Found by", e.get("by")) + + def _notes(self, page): + hl = highlights.on(self.db, self.rid) + cm = comments.on(self.db, self.rid) + nt = self.db.rows( + "SELECT account, text, t0, t1, quote, created_at FROM note WHERE recording = $r AND shared = true ORDER BY created_at", + r=self.rid, + ) + accounts = {x["account"] for x in [*hl, *cm, *nt] if x.get("account") is not None} + people = ( + { + a["id"]: a.get("name") or "someone" + for a in self.db.rows( + "SELECT record::id(id) AS id, name FROM account WHERE id IN $ids", ids=[R("account", a) for a in accounts] + ) + } + if accounts + else {} + ) + + def about(x): + where = self.at(x.get("t0"), x.get("t1")) + quote = f' "{_words(x["quote"])}"' if x.get("quote") else "" + return f"{where}{quote}: " if where or quote else "" + + page.heading("Notes, highlights and comments") + if not (hl or cm or nt): + page.line("None shared.") + if hl: + page.line("Highlights:") + page.items( + [ + f"{about(h)}{h.get('label') or h.get('colour', '') + ' highlight'} ({people.get(h.get('account'), 'someone')})" + for h in hl + ] + ) + if nt: + page.line("Shared notes:") + page.items( + [ + f"{about(n)}{_words(n['text'])} ({people.get(n['account'], 'someone')})" + for n in sorted(nt, key=lambda n: n.get("t0") or 0) + ] + ) + if cm: + page.line("Comments:") + page.items( + [ + f"{'reply: ' if c.get('parent') is not None else about(c)}{_words(c['text'])} ({people.get(c.get('account'), 'someone')}" + f"{', resolved' if c.get('resolved') and c.get('parent') is None else ''})" + for c in cm + ] + ) + + +def write(db, cfg, rid, parts, d=None, places=True) -> str: + """The text of what Lens found about the resource, for these parts.""" + return Report(db, cfg, rid, d, places).text(parts) + + +def has_findings(parts): + """Whether these parts ask for any findings, beyond the file itself.""" + return any(p != "file" for p in parts) diff --git a/fastapi_backend/app/schemas/recordings.py b/fastapi_backend/app/schemas/recordings.py index 91d220439..f363e607d 100644 --- a/fastapi_backend/app/schemas/recordings.py +++ b/fastapi_backend/app/schemas/recordings.py @@ -9,6 +9,24 @@ # Recording statuses, plus two job states: a job queued or running (processing), the latest job failed (failed). RecordingState = Literal["new", "transcribed", "diarized", "analyzed", "error", "processing", "failed"] +# the parts of an evidence PDF (domain/evidence_report.py PARTS) +EvidencePart = Literal[ + "file", + "details", + "metadata", + "tags", + "topics", + "summary", + "analysis", + "sections", + "speakers", + "emotion", + "entities", + "keywords", + "visual", + "places", + "notes", +] MediaKind = Literal["audio", "video", "transcript", "document", "image"] RecordingSort = Literal[ "date", diff --git a/fastapi_backend/tests/api/test_evidence.py b/fastapi_backend/tests/api/test_evidence.py index fa4b74fdd..970012238 100644 --- a/fastapi_backend/tests/api/test_evidence.py +++ b/fastapi_backend/tests/api/test_evidence.py @@ -1,16 +1,18 @@ """Evidence PDFs (evidence.py): a recording or a collection as one PDF made by anytopdf, each resource's own file (audio -and video with Lens's transcript) then a provenance page with every file's SHA-256, made here or on a conversion node.""" +and video with Lens's transcript) and what Lens found about it (evidence_report.py), then a provenance page with every +file's SHA-256, made here or on a conversion node.""" from __future__ import annotations import hashlib import io +import json import pathlib import subprocess import pytest -from app.domain import anytopdf, evidence, ingest, settings, store +from app.domain import anytopdf, comments, evidence, highlights, ingest, library, notes, pipelines, settings, store, topics from tests import fake_anytopdf from tests.api.test_anytopdf import TOKEN from tests.api.test_documents import _upload @@ -116,6 +118,22 @@ def test_a_collection_as_one_evidence_pdf(here, client, env, db, cfg, folder): places = [text.index(x) for x in ("Second memo", "Alice: The invoice is paid.", "Carol: Only words here.", "First memo")] assert places == sorted(places) # the list's order args = fake_anytopdf.runs(here)[-1]["args"] + assert [x.rsplit("/", 1)[-1] for x in args[3:11]] == [ + "01 memo-b.txt", + "01 memo-b - what Lens found.txt", + "02 Supplier call.wav", + "02 Supplier call - what Lens found.txt", + "03 plain.txt", + "03 plain - what Lens found.txt", + "04 memo-a.txt", + "04 memo-a - what Lens found.txt", + ] + assert "What Lens found: Supplier call" in text + + # the parts picked go for every one of them + r = client.get(f"/api/v1/collections/{cid}/evidence.pdf", headers=he, params={"include": ["file"]}) + assert r.status_code == 200, r.text + args = fake_anytopdf.runs(here)[-1]["args"] assert [x.rsplit("/", 1)[-1] for x in args[3:7]] == ["01 memo-b.txt", "02 Supplier call.wav", "03 plain.txt", "04 memo-a.txt"] # someone who can't read pods can't have it @@ -123,6 +141,176 @@ def test_a_collection_as_one_evidence_pdf(here, client, env, db, cfg, folder): assert client.get(f"/api/v1/recordings/{a['recording']}/evidence.pdf", headers=ho).status_code in (403, 404) +def _enriched(db, cfg, folder, editor, outsider): + """The call, analysed, with everything Lens can know about it: emotion and sounds on its lines, a summary, an + analysis step's output, tags, a topic, places and dates, and people's notes, highlights and comments.""" + t = folder / "call.json" + lines = [ + {"t0": 1000, "t1": 3500, "speaker": "Alice", "text": "The invoice is paid in Berlin.", "emotion": "Happy", "event": "Laughter"}, + {"t0": 4000, "t1": 6000, "speaker": "Bob", "text": "Thanks, filed it.", "emotion": "Neutral", "event": "Speech"}, + ] + t.write_text(json.dumps({"lens": "lens/1", "doc": {"title": "Supplier call"}, "segments": lines})) + rid = ingest.import_transcript(db, cfg, "pods", t, log=quiet) + wav = folder / "call.wav" + write_wav(wav) + db.q("UPDATE $r SET source = 'audio', path = $p, title = 'Supplier call'", r=R("recording", rid), p=str(wav)) + from app.domain import analyze + + analyze.analyze_recording(db, cfg, rid) + summary = { + "summary": "Alice says the invoice is paid and Bob files it.", + "key_points": [{"text": "The invoice is paid", "t0": 1000}], + "action_items": [{"text": "File the invoice", "who": "Bob", "t0": 4000}], + "topics": ["invoices"], + "people": ["Alice", "Bob"], + "sentiment": "Happy", + "importance": 4, + } + db.q("UPDATE $r SET summary = $s", r=R("recording", rid), s=summary) + pipelines.save_output(db, rid, "risk", {"level": "low", "reasons": ["paid on time"]}, {"model": "test-model"}) + library.set_tags(db, rid, ["supplier", "paid"]) + sid = store.ns_id(db, "pods") + topics.tag(db, topics.create(db, sid, "Accounts payable"), [rid]) + enrichment = { + "by": "anytopdf 0.4.0", + "places": [{"name": "Berlin, Germany", "said": "Berlin", "lat": 52.524, "lon": 13.411, "from": "text"}], + "dates": [{"text": "3 March 2026", "iso": "2026-03-03", "kind": "date"}], + } + db.q("UPDATE $r SET enrichment = $e", r=R("recording", rid), e=enrichment) + notes.create(db, rid, sid, editor, "Shared with the team", t0=1000, shared=True) + notes.create(db, rid, sid, editor, "Only mine to read", t0=1000) + highlights.create(db, rid, sid, editor, 1000, 3000, quote="The invoice is paid", label="Payment") + comments.create(db, rid, sid, editor, "Is this the March invoice?", t0=4000) + return rid, wav + + +def test_everything_lens_found_goes_in(here, client, db, cfg, folder): + ed = make_user(db, "ed@x.io", "editor password 1", roles={"pods": "editor"}) + he = login(client, "ed@x.io", "editor password 1") + rid, wav = _enriched(db, cfg, folder, ed, None) + + r = client.get(f"/api/v1/recordings/{rid}/evidence.pdf", headers=he) + assert r.status_code == 200, r.text + text = _text(r.content) + args = fake_anytopdf.runs(here)[-1]["args"] + assert [x.rsplit("/", 1)[-1] for x in args[3:5]] == ["01 Supplier call.wav", "01 Supplier call - what Lens found.txt"] + + # each line of the transcript says how it was said + assert "Alice: (Happy, Laughter) The invoice is paid in Berlin." in text and "Bob: Thanks, filed it." in text + # and the pages after it hold everything else + for said in ( + "What Lens found: Supplier call", + "Type: audio", + "Namespace: pods", + "Summary (written by a model)", + "Alice says the invoice is paid and Bob files it.", + "The invoice is paid (at 0:01)", + "Bob: File the invoice (at 0:04)", + "Overall tone: Happy", + "Importance: 4 of 5", + "risk (by test-model)", + "level: low", + "- paid on time", + "paid, supplier", + "Accounts payable (accepted, added by a person)", + "Speakers", + "Alice: 0:02 (56% of the speech), 1 turn, 6 words", + "named in the transcript", + "Emotion and sounds", + "Happy: 56%", + "Alice: Happy 100%", + "Laughter: 1 time", + "Term: Berlin (1)", + "Places it names:", + "Berlin, Germany (52.52400, 13.41100)", + "3 March 2026 (2026-03-03)", + "Found by: anytopdf 0.4.0", + "Metadata", + "Title: Supplier call", + ): + assert said in text, said + # people's notes stay out unless asked for + assert "Shared with the team" not in text and "Payment" not in text and "March invoice" not in text + assert hashlib.sha256(wav.read_bytes()).hexdigest() in text # the provenance page, as before + + r = client.get(f"/api/v1/recordings/{rid}/evidence.pdf", headers=he, params={"include": ["notes", "file", "summary"]}) + assert r.status_code == 200, r.text + text = _text(r.content) + assert '0:01: Shared with the team (' in text and '0:01 to 0:03 "The invoice is paid": Payment (' in text + assert "Payment" in text and "Is this the March invoice?" in text + assert "Only mine to read" not in text # a private note is its writer's alone + assert "Summary (written by a model)" in text and "Term: Berlin" not in text and "Berlin, Germany" not in text + # without emotion, the transcript is as it was said + assert "Alice: The invoice is paid in Berlin." in text and "(Happy" not in text + + +def test_picking_the_parts(here, client, db, cfg, folder): + ed = make_user(db, "ed@x.io", "editor password 1", roles={"pods": "editor"}) + he = login(client, "ed@x.io", "editor password 1") + rid, wav = _enriched(db, cfg, folder, ed, None) + + # its file alone: the evidence PDF as it was before Lens added what it found + r = client.get(f"/api/v1/recordings/{rid}/evidence.pdf", headers=he, params={"include": "file"}) + assert r.status_code == 200, r.text + args = fake_anytopdf.runs(here)[-1]["args"] + assert not any("what Lens found" in a for a in args) and "What Lens found" not in _text(r.content) + assert "Alice: The invoice is paid in Berlin." in _text(r.content) + + # what Lens found alone, without the file + r = client.get(f"/api/v1/recordings/{rid}/evidence.pdf", headers=he, params={"include": ["summary", "tags"]}) + assert r.status_code == 200, r.text + args = fake_anytopdf.runs(here)[-1]["args"] + assert [a.rsplit("/", 1)[-1] for a in args[3:4]] == ["01 Supplier call - what Lens found.txt"] + assert "--transcript" not in args + text = _text(r.content) + assert "Summary (written by a model)" in text and "Tags" in text and "Speakers" not in text + + # a part that isn't one + r = client.get(f"/api/v1/recordings/{rid}/evidence.pdf", headers=he, params={"include": "everything"}) + assert r.status_code == 422 + + +def test_what_is_seen_on_pages_and_in_a_video(here, client, env, db, cfg, folder): + from app.domain import evidence_report + + he = env["he"] + doc = _upload(client, he, b"Invoice 42\n\nTotal: 100 EUR\n", "invoice.txt") + drain(db, settings.effective(db, cfg)) + rid = doc["recording"] + db.q( + "CREATE description CONTENT $d", + d={"recording": rid, "idx": 0, "t0": 0, "t1": 1, "paged": True, "text": "A printed invoice.", "model": "vision-test"}, + ) + obj = {"recording": rid, "label": "table", "spans": [[0, 1]], "screen_ms": 1, "first_ms": 0, "count": 1, "score": 0.8, "paged": True} + db.q("CREATE object_track CONTENT $d", d=obj) + text = evidence_report.write(db, cfg, rid, list(evidence_report.PARTS)) + assert "Type: document" in text and "Pages: 1" in text + assert "What each page shows (written by vision-test):" in text and "- p. 1: A printed invoice." in text + assert "- table: found 1 time, on 1 page, first at p. 1, 0.80 sure" in text + assert "Notes, highlights and comments" in text and "None shared." in text + + rid, _ = _call(db, cfg, folder) + db.q("UPDATE $r SET media = {kind: 'video', width: 640, height: 360, fps: 25}", r=R("recording", rid)) + db.q("CREATE shot CONTENT {recording: $r, idx: 0, t0: 0, t1: 4000}", r=rid) + db.q("CREATE ocr_span CONTENT {recording: $r, t0: 1000, t1: 2000, text: 'INVOICE 42'}", r=rid) + text = evidence_report.write(db, cfg, rid, ["details", "visual"]) + assert "Type: video" in text and "Size: 640 × 360 pixels, 25 frames a second" in text + assert "Shots: 1" in text and "Text on screen:" in text and "- 0:01: INVOICE 42" in text + assert "Summary" not in text + + +def test_places_only_for_members(db, cfg, folder): + from app.domain import evidence_report + + rid, _ = _call(db, cfg, folder) + db.q("UPDATE $r SET enrichment = $e", r=R("recording", rid), e={"by": "anytopdf 0.4.0", "places": [{"name": "Berlin, Germany"}]}) + assert "Berlin, Germany" in evidence_report.write(db, cfg, rid, ["places"]) + assert "Berlin" not in evidence_report.write(db, cfg, rid, ["places"], places=False) + assert evidence_report.parts_of(None) == [p for p in evidence_report.PARTS if p != "notes"] + with pytest.raises(ValueError): + evidence_report.parts_of(["everything"]) + + def test_too_many_or_none(here, client, env, db, cfg, monkeypatch): he = env["he"] r = client.post("/api/v1/collections", headers=he, json={"name": "Empty", "recordings": []}) @@ -169,10 +357,16 @@ def test_on_a_conversion_node(client, env, db, cfg, folder): doc = _upload(client, he, raw, "invoice.txt") drain(db, settings.effective(db, cfg)) fake_anytopdf.Node.jobs.clear() - r = client.get(f"/api/v1/recordings/{doc['recording']}/evidence.pdf", headers=he) + r = client.get(f"/api/v1/recordings/{doc['recording']}/evidence.pdf", headers=he, params={"include": "file"}) assert r.status_code == 200, r.text assert [j["name"] for j in fake_anytopdf.Node.jobs.values()] == ["01 invoice.txt"] # one document: as it is + # with what Lens found: a zip of both + r = client.get(f"/api/v1/recordings/{doc['recording']}/evidence.pdf", headers=he) + assert r.status_code == 200, r.text + assert list(fake_anytopdf.Node.jobs.values())[-1]["name"] == "evidence.zip" + assert "Invoice 7" in _text(r.content) and "What Lens found: invoice" in _text(r.content) + # several: one zip, audio as its transcript only rid, _ = _call(db, cfg, folder) r = client.post("/api/v1/collections", headers=he, json={"name": "Case", "recordings": [doc["recording"], rid]}) diff --git a/nextjs-frontend/__tests__/evidence-parts.test.tsx b/nextjs-frontend/__tests__/evidence-parts.test.tsx new file mode 100644 index 000000000..6f392edf5 --- /dev/null +++ b/nextjs-frontend/__tests__/evidence-parts.test.tsx @@ -0,0 +1,47 @@ +import { fireEvent, render, screen } from "@testing-library/react"; +import "@testing-library/jest-dom"; + +import { DEFAULT_PARTS, EVIDENCE_PARTS, EvidencePartsDialog } from "@/components/evidence/parts-dialog"; +import { TooltipProvider } from "@/components/ui/tooltip"; + +function open(onDownload: (parts: string[]) => void) { + return render( + <TooltipProvider> + <EvidencePartsDialog open onOpenChange={() => undefined} onDownload={onDownload} what="“Weekly sync”" /> + </TooltipProvider>, + ); +} + +describe("the evidence PDF's parts", () => { + beforeEach(() => localStorage.clear()); + + it("start with everything Lens found, and Download is focused so Enter downloads", () => { + const download = jest.fn(); + open(download); + expect(DEFAULT_PARTS).not.toContain("notes"); + expect(DEFAULT_PARTS).toHaveLength(EVIDENCE_PARTS.length - 1); + expect(screen.getByRole("checkbox", { name: "Emotion and sounds" })).toBeChecked(); + expect(screen.getByRole("checkbox", { name: "Notes, highlights and comments" })).not.toBeChecked(); + const button = screen.getByRole("button", { name: "Download PDF" }); + expect(button).toHaveFocus(); + fireEvent.click(button); + expect(download).toHaveBeenCalledWith(DEFAULT_PARTS); + }); + + it("send the parts picked, in their order, and start from them next time", () => { + const download = jest.fn(); + const { unmount } = open(download); + fireEvent.click(screen.getByRole("checkbox", { name: "Everything" })); // some picked: picks them all + fireEvent.click(screen.getByRole("checkbox", { name: "Everything" })); // all picked: picks none + expect(screen.getByRole("button", { name: "Download PDF" })).toHaveAttribute("aria-disabled", "true"); + fireEvent.click(screen.getByRole("checkbox", { name: "Notes, highlights and comments" })); + fireEvent.click(screen.getByRole("checkbox", { name: "Its own file" })); + fireEvent.click(screen.getByRole("button", { name: "Download PDF" })); + expect(download).toHaveBeenCalledWith(["file", "notes"]); + unmount(); + + open(download); + expect(screen.getByRole("checkbox", { name: "Notes, highlights and comments" })).toBeChecked(); + expect(screen.getByRole("checkbox", { name: "Summary" })).not.toBeChecked(); + }); +}); diff --git a/nextjs-frontend/app/openapi-client/sdk.gen.ts b/nextjs-frontend/app/openapi-client/sdk.gen.ts index 0b3515647..4648689f4 100644 --- a/nextjs-frontend/app/openapi-client/sdk.gen.ts +++ b/nextjs-frontend/app/openapi-client/sdk.gen.ts @@ -4560,8 +4560,11 @@ export class Resources { * Evidence Pdf * * The resource as an evidence PDF, made by anytopdf (a download): its own file's pages (audio and video with - * their transcript), searchable, then a provenance page with the file's SHA-256 and size. 503 when anytopdf can't - * run here (it's fetched on first use unless Settings › Documents says never to use it). + * their transcript, each line marked with its emotion and sound), searchable, then the pages of what Lens found + * about it (details, metadata, tags, topics, summary, analysis, sections, speakers, emotion, entities, keywords, + * what is seen, places and dates; notes when asked for), then a provenance page with each file's SHA-256 and size. + * `include` picks the parts. 503 when anytopdf can't run here (it's fetched on first use unless Settings › + * Documents says never to use it). */ public static evidencePdf<ThrowOnError extends boolean = false>( options: Options<EvidencePdfData, ThrowOnError>, @@ -8923,7 +8926,8 @@ export class Collections { * Collection Evidence * * The collection's recordings you can read (a list in its order, a filter's oldest first) as one evidence PDF made by anytopdf (a download): each - * one's pages, then a provenance page with every file's SHA-256 and size. At most 50 recordings. + * one's pages and what Lens found about it, then a provenance page with every file's SHA-256 and size. `include` picks the parts, as for a + * resource's evidence PDF. At most 50 recordings. */ public static collectionEvidence<ThrowOnError extends boolean = false>( options: Options<CollectionEvidenceData, ThrowOnError>, diff --git a/nextjs-frontend/app/openapi-client/types.gen.ts b/nextjs-frontend/app/openapi-client/types.gen.ts index 843b729a3..f53977eda 100644 --- a/nextjs-frontend/app/openapi-client/types.gen.ts +++ b/nextjs-frontend/app/openapi-client/types.gen.ts @@ -24700,7 +24700,30 @@ export type EvidencePdfData = { */ rid: number; }; - query?: never; + query?: { + /** + * Include + * + * the parts of the PDF; repeat for several. Without it: every part but notes. file: its own file: a document's pages, an image, or audio and video with Lens's transcript; details: what it is, when it was made and added, its length, language, content type and where it came from; metadata: its description as saved and derived (Dublin Core terms, rights, creators) and its custom fields; tags: its tags; topics: the topics it is about, accepted and suggested; summary: the summary a model wrote: key points, follow-ups, people, overall tone and importance; analysis: what its pipeline's model steps saved; sections: the sections analysis split it into; speakers: who spoke, for how long, and how each was recognised; emotion: the emotion of what was said and the sounds heard, overall and by speaker, marked on each transcript line; entities: the people, organisations, places and other names it mentions; keywords: its keywords; visual: the faces, objects, descriptions and text on screen seen in it; places: the places and dates anytopdf found in it, and where a photo was taken; notes: the notes, highlights and comments people shared on it + */ + include?: Array< + | "file" + | "details" + | "metadata" + | "tags" + | "topics" + | "summary" + | "analysis" + | "sections" + | "speakers" + | "emotion" + | "entities" + | "keywords" + | "visual" + | "places" + | "notes" + > | null; + }; url: "/api/v1/resources/{rid}/evidence.pdf"; }; @@ -33219,7 +33242,30 @@ export type CollectionEvidenceData = { */ cid: number; }; - query?: never; + query?: { + /** + * Include + * + * the parts of the PDF; repeat for several. Without it: every part but notes. file: its own file: a document's pages, an image, or audio and video with Lens's transcript; details: what it is, when it was made and added, its length, language, content type and where it came from; metadata: its description as saved and derived (Dublin Core terms, rights, creators) and its custom fields; tags: its tags; topics: the topics it is about, accepted and suggested; summary: the summary a model wrote: key points, follow-ups, people, overall tone and importance; analysis: what its pipeline's model steps saved; sections: the sections analysis split it into; speakers: who spoke, for how long, and how each was recognised; emotion: the emotion of what was said and the sounds heard, overall and by speaker, marked on each transcript line; entities: the people, organisations, places and other names it mentions; keywords: its keywords; visual: the faces, objects, descriptions and text on screen seen in it; places: the places and dates anytopdf found in it, and where a photo was taken; notes: the notes, highlights and comments people shared on it + */ + include?: Array< + | "file" + | "details" + | "metadata" + | "tags" + | "topics" + | "summary" + | "analysis" + | "sections" + | "speakers" + | "emotion" + | "entities" + | "keywords" + | "visual" + | "places" + | "notes" + > | null; + }; url: "/api/v1/collections/{cid}/evidence.pdf"; }; diff --git a/nextjs-frontend/components/collections/collection-detail.tsx b/nextjs-frontend/components/collections/collection-detail.tsx index 369e3b1b4..068440e9b 100644 --- a/nextjs-frontend/components/collections/collection-detail.tsx +++ b/nextjs-frontend/components/collections/collection-detail.tsx @@ -1,7 +1,16 @@ "use client"; import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; -import { ChevronLeft, FileCheck, FileText, MessagesSquare, Pencil, Play, Trash2 } from "lucide-react"; +import { + ChevronLeft, + FileCheck, + FileText, + MessagesSquare, + Pencil, + Play, + SlidersHorizontal, + Trash2, +} from "lucide-react"; import Link from "next/link"; import { useRouter } from "next/navigation"; import { useState } from "react"; @@ -10,10 +19,11 @@ import { Collections } from "@/app/openapi-client"; import type { Collection } from "@/app/openapi-client/types.gen"; import { CollectionDialog } from "@/components/collections/collection-dialog"; import { describeCollection } from "@/components/collections/describe"; +import { EvidencePartsDialog, type EvidencePart } from "@/components/evidence/parts-dialog"; import { saveBlob, slug } from "@/components/recording/hooks"; import { recordingHref } from "@/components/search/links"; import { Banner } from "@/components/ui/banner"; -import { Button } from "@/components/ui/button"; +import { Button, IconButton } from "@/components/ui/button"; import { Dialog } from "@/components/ui/dialog"; import { EmptyState, PageHeader, SkeletonRows } from "@/components/ui/states"; import { Table, Td, Th, THead, Tr } from "@/components/ui/table"; @@ -48,10 +58,16 @@ export function CollectionDetail({ id }: { id: number }) { router.push("/collections"); }, }); + const [picking, setPicking] = useState(false); const evidence = useMutation({ - mutationFn: async (name: string) => { + mutationFn: async ({ name, include }: { name: string; include?: EvidencePart[] }) => { const blob = (await data( - Collections.collectionEvidence({ client, path: { cid: id }, parseAs: "blob" }), + Collections.collectionEvidence({ + client, + path: { cid: id }, + query: include ? { include } : undefined, + parseAs: "blob", + }), )) as unknown as Blob; saveBlob(blob, `${slug(name)}-evidence.pdf`); }, @@ -145,10 +161,23 @@ export function CollectionDetail({ id }: { id: number }) { ? "An evidence PDF holds 50 recordings at most" : undefined } - onClick={() => evidence.mutate(c.name)} + onClick={() => evidence.mutate({ name: c.name })} > {evidence.isPending ? "Making the PDF…" : "Evidence PDF"} </Button> + <IconButton + label="Choose what goes in the evidence PDF" + disabled={c.count === 0 || c.count > 50 || evidence.isPending} + onClick={() => setPicking(true)} + > + <SlidersHorizontal /> + </IconButton> + <EvidencePartsDialog + open={picking} + onOpenChange={setPicking} + what={`the ${count(c.count)} ${c.count === 1 ? "recording" : "recordings"} in ${c.name}`} + onDownload={(include) => evidence.mutate({ name: c.name, include })} + /> <Button variant="ghost" icon={<Pencil />} diff --git a/nextjs-frontend/components/evidence/parts-dialog.tsx b/nextjs-frontend/components/evidence/parts-dialog.tsx new file mode 100644 index 000000000..ffd93a84c --- /dev/null +++ b/nextjs-frontend/components/evidence/parts-dialog.tsx @@ -0,0 +1,122 @@ +"use client"; + +import { useEffect, useState } from "react"; + +import type { EvidencePdfData } from "@/app/openapi-client/types.gen"; +import { Button } from "@/components/ui/button"; +import { Dialog } from "@/components/ui/dialog"; +import { Checkbox } from "@/components/ui/field"; + +export type EvidencePart = NonNullable<NonNullable<EvidencePdfData["query"]>["include"]>[number]; + +/** The parts of an evidence PDF, in their order there (the API's `include`), with what each holds. */ +export const EVIDENCE_PARTS: [EvidencePart, string, string][] = [ + ["file", "Its own file", "A document’s pages, an image, or audio and video with the transcript"], + ["details", "Details", "What it is, dates, length, language, content type, where it came from"], + ["metadata", "Metadata", "Its description, rights, creators, Dublin Core terms, custom fields"], + ["tags", "Tags", "Its tags"], + ["topics", "Topics", "Accepted and suggested topics"], + ["summary", "Summary", "Written by a model: key points, follow-ups, tone, importance"], + ["analysis", "Analysis", "What its pipeline’s model steps saved"], + ["sections", "Sections", "The sections analysis split it into"], + ["speakers", "Speakers", "Who spoke, for how long, how each was recognised"], + ["emotion", "Emotion and sounds", "Overall and by speaker, marked on each transcript line"], + ["entities", "Entities", "People, organisations, places and other names"], + ["keywords", "Keywords", "Its keywords"], + ["visual", "What’s seen", "Faces, objects, descriptions, text on screen"], + ["places", "Places and dates", "Found in it, and where a photo was taken"], + ["notes", "Notes, highlights and comments", "The ones people shared on it"], +]; + +/** What goes in when nothing is picked: everything Lens found, not people's notes (the API's default too). */ +export const DEFAULT_PARTS: EvidencePart[] = EVIDENCE_PARTS.map(([k]) => k).filter((k) => k !== "notes"); + +const KEY = "lens.evidence-parts"; + +function remembered(): EvidencePart[] { + try { + const known = new Set<string>(EVIDENCE_PARTS.map(([k]) => k)); + const saved = JSON.parse(localStorage.getItem(KEY) ?? "null") as string[] | null; + const parts = (saved ?? []).filter((k): k is EvidencePart => known.has(k)); + return parts.length ? parts : DEFAULT_PARTS; + } catch { + return DEFAULT_PARTS; + } +} + +/** Pick what goes in an evidence PDF, then download it (Enter downloads). Starts from the last picks made here. */ +export function EvidencePartsDialog({ + open, + onOpenChange, + onDownload, + what, +}: { + open: boolean; + onOpenChange: (open: boolean) => void; + onDownload: (include: EvidencePart[]) => void; + /** What it is of ("“Weekly sync”", "the 12 resources in Supplier dispute"), for the description. */ + what: string; +}) { + const [picked, setPicked] = useState<Set<EvidencePart>>(() => new Set(DEFAULT_PARTS)); + useEffect(() => { + if (open) setPicked(new Set(remembered())); + }, [open]); + const all = picked.size === EVIDENCE_PARTS.length; + const toggle = (k: EvidencePart, on: boolean) => + setPicked((p) => { + const next = new Set(p); + if (on) next.add(k); + else next.delete(k); + return next; + }); + const download = () => { + const include = EVIDENCE_PARTS.map(([k]) => k).filter((k) => picked.has(k)); + try { + localStorage.setItem(KEY, JSON.stringify(include)); + } catch { + /* the next time starts from everything Lens found */ + } + onOpenChange(false); + onDownload(include); + }; + return ( + <Dialog + open={open} + onOpenChange={onOpenChange} + title="What goes in the evidence PDF" + description={`Pick the parts of ${what}. Each resource’s file comes first, then what Lens found about it, then a page with every file’s SHA-256.`} + wide + actions={ + <> + <Button variant="ghost" onClick={() => onOpenChange(false)}> + Cancel + </Button> + <Button + variant="primary" + data-autofocus + disabled={picked.size === 0} + disabledReason="Pick at least one part" + onClick={download} + > + Download PDF + </Button> + </> + } + > + <Checkbox + checked={all ? true : picked.size ? "indeterminate" : false} + onCheckedChange={(on) => setPicked(new Set(on ? EVIDENCE_PARTS.map(([k]) => k) : []))} + label="Everything" + className="font-bold" + /> + <div className="grid gap-x-6 gap-y-3 sm:grid-cols-2"> + {EVIDENCE_PARTS.map(([k, label, hint]) => ( + <div key={k} className="flex flex-col gap-0.5"> + <Checkbox checked={picked.has(k)} onCheckedChange={(on) => toggle(k, on)} label={label} /> + <span className="pl-[28px] text-[12.5px] leading-snug text-fg-secondary">{hint}</span> + </div> + ))} + </div> + </Dialog> + ); +} diff --git a/nextjs-frontend/components/recording/header.tsx b/nextjs-frontend/components/recording/header.tsx index c42c149ad..6e45f2611 100644 --- a/nextjs-frontend/components/recording/header.tsx +++ b/nextjs-frontend/components/recording/header.tsx @@ -33,6 +33,7 @@ import { Fragment, useState, type ReactNode } from "react"; import { AccessBadge } from "@/components/access/access-fields"; import { libraryHref } from "@/components/library/collections-model"; import { usePlayerApi } from "@/components/player/media"; +import { EvidencePartsDialog } from "@/components/evidence/parts-dialog"; import { CreatePodcastDialog } from "@/components/podcasts/create-dialog"; import { useRec } from "@/components/recording/context"; import { pageAt, pagesSummary } from "@/components/recording/document/model"; @@ -222,45 +223,58 @@ export function ExportMenu({ trigger }: { trigger?: ReactNode }) { const { id, model, rec, paged } = useRec(); const exp = useExport(id); const evidence = useEvidence(id); + const [picking, setPicking] = useState(false); // a document's text has no times for subtitles const formats = paged ? EXPORTS.filter(([fmt]) => fmt !== "srt" && fmt !== "vtt") : EXPORTS; return ( - <Menu> - <MenuTrigger asChild> - {trigger ?? ( - <Button variant="secondary" size="sm" icon={<Download />} disabled={exp.isPending}> - Export - </Button> - )} - </MenuTrigger> - <MenuContent> - <MenuLabel>{paged ? "Download the text" : "Download the transcript"}</MenuLabel> - {formats.map(([fmt, label]) => ( - <MenuItem key={fmt} onSelect={() => exp.mutate({ fmt, title: model.title })} shortcut={`.${fmt}`}> - {label} - </MenuItem> - ))} - <MenuSeparator /> - <MenuItem - onSelect={() => evidence.mutate({ title: model.title })} - disabled={evidence.isPending} - shortcut=".pdf" - > - Evidence PDF - </MenuItem> - {rec.report_url && ( - <> - <MenuSeparator /> - <MenuItem asChild> - <a href={rec.report_url} target="_blank" rel="noreferrer" className="flex items-center gap-2.5"> - <ExternalLink /> - <span className="flex-1">Open the recording report</span> - </a> + <> + <Menu> + <MenuTrigger asChild> + {trigger ?? ( + <Button variant="secondary" size="sm" icon={<Download />} disabled={exp.isPending}> + Export + </Button> + )} + </MenuTrigger> + <MenuContent> + <MenuLabel>{paged ? "Download the text" : "Download the transcript"}</MenuLabel> + {formats.map(([fmt, label]) => ( + <MenuItem key={fmt} onSelect={() => exp.mutate({ fmt, title: model.title })} shortcut={`.${fmt}`}> + {label} </MenuItem> - </> - )} - </MenuContent> - </Menu> + ))} + <MenuSeparator /> + <MenuLabel>Evidence PDF: the file and everything Lens found</MenuLabel> + <MenuItem + onSelect={() => evidence.mutate({ title: model.title })} + disabled={evidence.isPending} + shortcut=".pdf" + > + Evidence PDF + </MenuItem> + <MenuItem onSelect={() => setPicking(true)} disabled={evidence.isPending}> + Choose what goes in it… + </MenuItem> + {rec.report_url && ( + <> + <MenuSeparator /> + <MenuItem asChild> + <a href={rec.report_url} target="_blank" rel="noreferrer" className="flex items-center gap-2.5"> + <ExternalLink /> + <span className="flex-1">Open the recording report</span> + </a> + </MenuItem> + </> + )} + </MenuContent> + </Menu> + <EvidencePartsDialog + open={picking} + onOpenChange={setPicking} + what={`“${model.title}”`} + onDownload={(include) => evidence.mutate({ title: model.title, include })} + /> + </> ); } diff --git a/nextjs-frontend/components/recording/hooks.ts b/nextjs-frontend/components/recording/hooks.ts index 1d4b8edf8..ddd72933b 100644 --- a/nextjs-frontend/components/recording/hooks.ts +++ b/nextjs-frontend/components/recording/hooks.ts @@ -16,6 +16,7 @@ import { Video, } from "@/app/openapi-client"; import type { CommentCreate, FileUpdate, HighlightCreate, NoteCreate, Recording } from "@/app/openapi-client/types.gen"; +import type { EvidencePart } from "@/components/evidence/parts-dialog"; import type { FileRole } from "@/components/recording/files-model"; import { isActive, normalizeJob, visualNotes, type JobInfo } from "@/components/recording/jobs"; import { normalizePlayer } from "@/components/recording/model"; @@ -589,14 +590,15 @@ export function useExport(id: number) { }); } -/** Download the resource as an evidence PDF (anytopdf): its pages, then the file's SHA-256 on a provenance page. */ +/** Download the resource as an evidence PDF (anytopdf): its pages, then what Lens found about it, then the file's + * SHA-256 on a provenance page. `include` picks the parts (none: everything Lens found). */ export function useEvidence(id: number) { const client = useApiClient(); const toast = useToast(); return useMutation({ - mutationFn: async ({ title }: { title: string }) => { + mutationFn: async ({ title, include }: { title: string; include?: EvidencePart[] }) => { const blob = (await data( - Resources.evidencePdf({ client, path: { rid: id }, parseAs: "blob" }), + Resources.evidencePdf({ client, path: { rid: id }, query: include ? { include } : undefined, parseAs: "blob" }), )) as unknown as Blob; saveBlob(blob, `${slug(title)}-evidence.pdf`); }, diff --git a/nextjs-frontend/openapi.json b/nextjs-frontend/openapi.json index 66fae3bc5..5a0014e13 100644 --- a/nextjs-frontend/openapi.json +++ b/nextjs-frontend/openapi.json @@ -8259,7 +8259,7 @@ "resources" ], "summary": "Evidence Pdf", - "description": "The resource as an evidence PDF, made by anytopdf (a download): its own file's pages (audio and video with\ntheir transcript), searchable, then a provenance page with the file's SHA-256 and size. 503 when anytopdf can't\nrun here (it's fetched on first use unless Settings \u203a Documents says never to use it).", + "description": "The resource as an evidence PDF, made by anytopdf (a download): its own file's pages (audio and video with\ntheir transcript, each line marked with its emotion and sound), searchable, then the pages of what Lens found\nabout it (details, metadata, tags, topics, summary, analysis, sections, speakers, emotion, entities, keywords,\nwhat is seen, places and dates; notes when asked for), then a provenance page with each file's SHA-256 and size.\n`include` picks the parts. 503 when anytopdf can't run here (it's fetched on first use unless Settings \u203a\nDocuments says never to use it).", "operationId": "evidence_pdf", "parameters": [ { @@ -8270,6 +8270,44 @@ "type": "integer", "title": "Rid" } + }, + { + "name": "include", + "in": "query", + "required": false, + "schema": { + "anyOf": [ + { + "type": "array", + "items": { + "enum": [ + "file", + "details", + "metadata", + "tags", + "topics", + "summary", + "analysis", + "sections", + "speakers", + "emotion", + "entities", + "keywords", + "visual", + "places", + "notes" + ], + "type": "string" + } + }, + { + "type": "null" + } + ], + "description": "the parts of the PDF; repeat for several. Without it: every part but notes. file: its own file: a document's pages, an image, or audio and video with Lens's transcript; details: what it is, when it was made and added, its length, language, content type and where it came from; metadata: its description as saved and derived (Dublin Core terms, rights, creators) and its custom fields; tags: its tags; topics: the topics it is about, accepted and suggested; summary: the summary a model wrote: key points, follow-ups, people, overall tone and importance; analysis: what its pipeline's model steps saved; sections: the sections analysis split it into; speakers: who spoke, for how long, and how each was recognised; emotion: the emotion of what was said and the sounds heard, overall and by speaker, marked on each transcript line; entities: the people, organisations, places and other names it mentions; keywords: its keywords; visual: the faces, objects, descriptions and text on screen seen in it; places: the places and dates anytopdf found in it, and where a photo was taken; notes: the notes, highlights and comments people shared on it", + "title": "Include" + }, + "description": "the parts of the PDF; repeat for several. Without it: every part but notes. file: its own file: a document's pages, an image, or audio and video with Lens's transcript; details: what it is, when it was made and added, its length, language, content type and where it came from; metadata: its description as saved and derived (Dublin Core terms, rights, creators) and its custom fields; tags: its tags; topics: the topics it is about, accepted and suggested; summary: the summary a model wrote: key points, follow-ups, people, overall tone and importance; analysis: what its pipeline's model steps saved; sections: the sections analysis split it into; speakers: who spoke, for how long, and how each was recognised; emotion: the emotion of what was said and the sounds heard, overall and by speaker, marked on each transcript line; entities: the people, organisations, places and other names it mentions; keywords: its keywords; visual: the faces, objects, descriptions and text on screen seen in it; places: the places and dates anytopdf found in it, and where a photo was taken; notes: the notes, highlights and comments people shared on it" } ], "responses": { @@ -22217,7 +22255,7 @@ "collections" ], "summary": "Collection Evidence", - "description": "The collection's recordings you can read (a list in its order, a filter's oldest first) as one evidence PDF made by anytopdf (a download): each\none's pages, then a provenance page with every file's SHA-256 and size. At most 50 recordings.", + "description": "The collection's recordings you can read (a list in its order, a filter's oldest first) as one evidence PDF made by anytopdf (a download): each\none's pages and what Lens found about it, then a provenance page with every file's SHA-256 and size. `include` picks the parts, as for a\nresource's evidence PDF. At most 50 recordings.", "operationId": "collection_evidence", "parameters": [ { @@ -22228,6 +22266,44 @@ "type": "integer", "title": "Cid" } + }, + { + "name": "include", + "in": "query", + "required": false, + "schema": { + "anyOf": [ + { + "type": "array", + "items": { + "enum": [ + "file", + "details", + "metadata", + "tags", + "topics", + "summary", + "analysis", + "sections", + "speakers", + "emotion", + "entities", + "keywords", + "visual", + "places", + "notes" + ], + "type": "string" + } + }, + { + "type": "null" + } + ], + "description": "the parts of the PDF; repeat for several. Without it: every part but notes. file: its own file: a document's pages, an image, or audio and video with Lens's transcript; details: what it is, when it was made and added, its length, language, content type and where it came from; metadata: its description as saved and derived (Dublin Core terms, rights, creators) and its custom fields; tags: its tags; topics: the topics it is about, accepted and suggested; summary: the summary a model wrote: key points, follow-ups, people, overall tone and importance; analysis: what its pipeline's model steps saved; sections: the sections analysis split it into; speakers: who spoke, for how long, and how each was recognised; emotion: the emotion of what was said and the sounds heard, overall and by speaker, marked on each transcript line; entities: the people, organisations, places and other names it mentions; keywords: its keywords; visual: the faces, objects, descriptions and text on screen seen in it; places: the places and dates anytopdf found in it, and where a photo was taken; notes: the notes, highlights and comments people shared on it", + "title": "Include" + }, + "description": "the parts of the PDF; repeat for several. Without it: every part but notes. file: its own file: a document's pages, an image, or audio and video with Lens's transcript; details: what it is, when it was made and added, its length, language, content type and where it came from; metadata: its description as saved and derived (Dublin Core terms, rights, creators) and its custom fields; tags: its tags; topics: the topics it is about, accepted and suggested; summary: the summary a model wrote: key points, follow-ups, people, overall tone and importance; analysis: what its pipeline's model steps saved; sections: the sections analysis split it into; speakers: who spoke, for how long, and how each was recognised; emotion: the emotion of what was said and the sounds heard, overall and by speaker, marked on each transcript line; entities: the people, organisations, places and other names it mentions; keywords: its keywords; visual: the faces, objects, descriptions and text on screen seen in it; places: the places and dates anytopdf found in it, and where a photo was taken; notes: the notes, highlights and comments people shared on it" } ], "responses": { diff --git a/threat-model.md b/threat-model.md index 84652f9f8..cc3752fe9 100644 --- a/threat-model.md +++ b/threat-model.md @@ -408,6 +408,7 @@ stored text for the consumer's format. | JSON API responses (titles, transcripts, notes, metadata) | AuthZ | as typed by people or produced by ASR/OCR; search `snippet` is HTML-escaped with `<mark>` | that any text field is safe for HTML, Markdown, SQL or a shell | *(documented, docs/api.md "an HTML-escaped `snippet`")* | | Signed links in responses | `api/media.py` | server-written for allow-listed fields only; text that looks like a link is never signed | that a link is private: it is a bearer credential until expiry | *(documented, docs/architecture.md "is never signed")* | | Exports, RDF, JSON-LD, IIIF manifests, WebVTT, Dublin Core | linked data, IIIF | values as typed; RDF responses send `Access-Control-Allow-Origin: *` | escaping for the consumer's format | *(inferred, Q24)* | +| Evidence PDFs | `evidence.py`, `evidence_report.py` | the resource's file and what Lens holds about it (metadata, summary, speakers, emotion, entities, what is seen), for anyone who can read it; places only for members of its namespace; shared notes, highlights and comments only when picked, never private notes; what a model wrote is labelled | that a PDF handed on holds less than its reader could see (pick its parts) | *(documented, docs/api.md "never anyone's private notes")* | | Recording description | IIIF, public pages | "never a closed part"; anyone who may see the page sees it | that closing parts hides the description | *(documented, docs/access.md "never a closed part")* | | Embed player and `/s/<code>` pages | `api/pages.py` | HTML built from DB values under a strict CSP; framable only per `server.embed_frame_ancestors` | that titles are inert outside this page | *(documented, docs/configuration.md "Content-Security-Policy")* | | Report pages | `api/pages.py` | links re-signed on read for every recording of the namespace in the page | that a report link opens only the report | *(inferred, Q10)* | diff --git a/threat-model.yaml b/threat-model.yaml index fa6748102..129431375 100644 --- a/threat-model.yaml +++ b/threat-model.yaml @@ -2,7 +2,7 @@ # Authority order: prose > yaml > json. Regenerate whenever the prose changes. schema: threat-model-sidecar/v2 project: lens -prose_version: "threat-model.md@sha256:866a8ecadd07a9c98b1846abb66ef740fa3ba5809698d42f531a66fc5d720db4" +prose_version: "threat-model.md@sha256:147e5951c9510b43587bb5d11b64039e5d1c925b9d771c699646692eac37c28f" model_status: under-review triage_policy: strict confidence: {documented: 201, maintainer: 46, inferred: 91, assumption: 8} @@ -610,6 +610,14 @@ outputs: invariants: [] downstream_must_not_assume: - {id: dmna-export-escaping, statement: "escaping for the consumer's format", provenance: {kind: inferred, question_id: Q24}} + - component: authz + channel: "Evidence PDFs (evidence.py, evidence_report.py)" + taint: same-as-input + x-taint-note: "the resource's file and what Lens holds about it, for anyone who can read it; places only for members of its namespace; shared notes, highlights and comments only when picked, never private notes; what a model wrote is labelled" + taint_provenance: {kind: documented, source: 'docs/api.md "never anyone''s private notes"'} + invariants: [] + downstream_must_not_assume: + - {id: dmna-evidence-pdf-less, statement: "that a PDF handed on holds less than its reader could see (pick its parts)", provenance: {kind: documented, source: 'docs/api.md "never anyone''s private notes"'}} - component: authz channel: "Recording description (IIIF, public pages)" taint: same-as-input