feat(lead): open a source in the review pane and keep it with the label
A source link loads in the reviewer's browser instead of a new tab. Include stores the page when the site returns it and appends human focus highlights. An existing full text stays. Exclude stores nothing.
This commit is contained in:
323
src/lead/explore/reader.py
Normal file
323
src/lead/explore/reader.py
Normal file
@@ -0,0 +1,323 @@
|
||||
"""Open an article inside the review, then store the page the reviewer landed on.
|
||||
|
||||
The pane fetches the page itself. Publisher sites refuse to be framed, and a
|
||||
normal link leaves the review for a new browser tab. Links in the fetched
|
||||
page are returned so the next click stays here. The address is checked before
|
||||
every request so a link cannot point the server at this machine.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import ipaddress
|
||||
import socket
|
||||
from dataclasses import dataclass
|
||||
from html.parser import HTMLParser
|
||||
from urllib.parse import urljoin, urlsplit, urlunsplit
|
||||
|
||||
import httpx
|
||||
|
||||
USER_AGENT = "stack-lead-review/1.0 (mailto:ci@fhirworx.io)"
|
||||
_MAX_BYTES = 40 * 1024 * 1024
|
||||
_MAX_REDIRECTS = 5
|
||||
_PORTS = {80, 443}
|
||||
_SKIP_TAGS = {"script", "style", "iframe", "object", "embed", "form", "svg"}
|
||||
_KEEP_TAGS = {
|
||||
"p",
|
||||
"br",
|
||||
"h1",
|
||||
"h2",
|
||||
"h3",
|
||||
"h4",
|
||||
"blockquote",
|
||||
"ul",
|
||||
"ol",
|
||||
"li",
|
||||
"em",
|
||||
"strong",
|
||||
"b",
|
||||
"i",
|
||||
"pre",
|
||||
"code",
|
||||
"table",
|
||||
"thead",
|
||||
"tbody",
|
||||
"tr",
|
||||
"th",
|
||||
"td",
|
||||
"sup",
|
||||
"sub",
|
||||
"div",
|
||||
"span",
|
||||
}
|
||||
|
||||
|
||||
class ReaderError(ValueError):
|
||||
"""The page cannot be opened in the pane."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Fetched:
|
||||
url: str
|
||||
kind: str
|
||||
body: bytes
|
||||
content_type: str
|
||||
links: tuple[tuple[str, str], ...]
|
||||
html: str
|
||||
|
||||
|
||||
def fetch(url: str, *, client: httpx.Client | None = None) -> Fetched:
|
||||
"""GET ``url`` and the redirects it returns. Each hop must be a public web address."""
|
||||
own = client is None
|
||||
if client is None:
|
||||
client = httpx.Client(timeout=httpx.Timeout(20.0, connect=5.0))
|
||||
try:
|
||||
current = _public_url(url)
|
||||
for _hop in range(_MAX_REDIRECTS + 1):
|
||||
with client.stream(
|
||||
"GET",
|
||||
current,
|
||||
headers={"User-Agent": USER_AGENT},
|
||||
follow_redirects=False,
|
||||
) as response:
|
||||
if response.status_code in {301, 302, 303, 307, 308}:
|
||||
loc = response.headers.get("location")
|
||||
if not loc:
|
||||
raise ReaderError("that page redirected nowhere")
|
||||
current = _public_url(urljoin(current, loc))
|
||||
continue
|
||||
if response.status_code != 200:
|
||||
raise ReaderError(f"that page answered {response.status_code}")
|
||||
content_type = response.headers.get("content-type", "")
|
||||
body = _body(response)
|
||||
if _challenge(body):
|
||||
raise ReaderError("that site asked for a browser check")
|
||||
kind = _kind(content_type, body)
|
||||
links: tuple[tuple[str, str], ...] = ()
|
||||
html = ""
|
||||
if kind == "html":
|
||||
html, links = _read_html(
|
||||
body.decode("utf-8", errors="replace"), current
|
||||
)
|
||||
elif kind == "text":
|
||||
html = f"<pre>{_escape(body.decode('utf-8', errors='replace'))}</pre>"
|
||||
return Fetched(current, kind, body, content_type, links, html)
|
||||
raise ReaderError("that page redirected too many times")
|
||||
finally:
|
||||
if own:
|
||||
client.close()
|
||||
|
||||
|
||||
def _body(response: httpx.Response) -> bytes:
|
||||
chunks: list[bytes] = []
|
||||
total = 0
|
||||
for chunk in response.iter_bytes():
|
||||
total += len(chunk)
|
||||
if total > _MAX_BYTES:
|
||||
raise ReaderError("that page is over 40 MB")
|
||||
chunks.append(chunk)
|
||||
if total == 0:
|
||||
raise ReaderError("that page was empty")
|
||||
return b"".join(chunks)
|
||||
|
||||
|
||||
def _challenge(body: bytes) -> bool:
|
||||
"""A bot wall, not the article. The reviewer's browser may still open it."""
|
||||
head = body[:8000].lower()
|
||||
return (
|
||||
b"just a moment" in head
|
||||
or b"checking your browser" in head
|
||||
or b"cf-browser-verification" in head
|
||||
)
|
||||
|
||||
|
||||
def _kind(content_type: str, body: bytes) -> str:
|
||||
low = content_type.lower()
|
||||
if "pdf" in low or body.startswith(b"%PDF"):
|
||||
return "pdf"
|
||||
if "html" in low or body.lstrip()[:1] == b"<":
|
||||
return "html"
|
||||
if low.startswith("text/") or not low:
|
||||
return "text"
|
||||
raise ReaderError("that page is not an article or a pdf")
|
||||
|
||||
|
||||
def _public_url(raw: str) -> str:
|
||||
"""An http(s) URL on port 80 or 443 whose host resolves to public addresses."""
|
||||
parts = urlsplit(raw.strip())
|
||||
if parts.scheme not in {"http", "https"} or not parts.hostname:
|
||||
raise ReaderError("that link is not a web page")
|
||||
if parts.username or parts.password:
|
||||
raise ReaderError("that link carries a login")
|
||||
port = parts.port or (443 if parts.scheme == "https" else 80)
|
||||
if port not in _PORTS:
|
||||
raise ReaderError("that link is not a web page")
|
||||
host = parts.hostname.rstrip(".").lower()
|
||||
if host in {"localhost"} or host.endswith(".local") or host.endswith(".internal"):
|
||||
raise ReaderError("that address stays on this network")
|
||||
for ip in _addresses(host):
|
||||
if _blocked(ip):
|
||||
raise ReaderError("that address stays on this network")
|
||||
# Rebuild so a backslash host or a missing scheme cannot survive.
|
||||
netloc = host if port in {80, 443} and parts.port is None else f"{host}:{port}"
|
||||
if ":" in host:
|
||||
netloc = f"[{host}]" if parts.port is None else f"[{host}]:{port}"
|
||||
return urlunsplit((parts.scheme, netloc, parts.path or "/", parts.query, ""))
|
||||
|
||||
|
||||
def _addresses(host: str) -> tuple[ipaddress.IPv4Address | ipaddress.IPv6Address, ...]:
|
||||
try:
|
||||
return (ipaddress.ip_address(host),)
|
||||
except ValueError:
|
||||
pass
|
||||
try:
|
||||
infos = socket.getaddrinfo(host, None)
|
||||
except socket.gaierror as exc:
|
||||
raise ReaderError("that host did not resolve") from exc
|
||||
found = []
|
||||
for info in infos:
|
||||
addr = str(info[4][0]).split("%", 1)[0]
|
||||
found.append(ipaddress.ip_address(addr))
|
||||
if not found:
|
||||
raise ReaderError("that host did not resolve")
|
||||
return tuple(found)
|
||||
|
||||
|
||||
def _blocked(ip: ipaddress.IPv4Address | ipaddress.IPv6Address) -> bool:
|
||||
return bool(
|
||||
ip.is_private
|
||||
or ip.is_loopback
|
||||
or ip.is_link_local
|
||||
or ip.is_reserved
|
||||
or ip.is_multicast
|
||||
or ip.is_unspecified
|
||||
)
|
||||
|
||||
|
||||
class _Page(HTMLParser):
|
||||
"""Links to follow, and a script-free fragment of the article."""
|
||||
|
||||
def __init__(self, page_url: str) -> None:
|
||||
super().__init__(convert_charrefs=True)
|
||||
self.page_url = page_url
|
||||
self._skip = 0
|
||||
self._anchor: list[str] | None = None
|
||||
self._href = ""
|
||||
self.links: list[tuple[str, str]] = []
|
||||
self._seen: set[str] = set()
|
||||
self._html: list[str] = []
|
||||
|
||||
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
|
||||
tag = tag.lower()
|
||||
if tag in _SKIP_TAGS:
|
||||
self._skip += 1
|
||||
return
|
||||
if self._skip:
|
||||
return
|
||||
if tag == "a":
|
||||
self._href = dict(attrs).get("href") or ""
|
||||
self._anchor = []
|
||||
return
|
||||
if tag == "br":
|
||||
self._html.append("<br>")
|
||||
return
|
||||
if tag in _KEEP_TAGS:
|
||||
self._html.append(f"<{tag}>")
|
||||
|
||||
def handle_endtag(self, tag: str) -> None:
|
||||
tag = tag.lower()
|
||||
if tag in _SKIP_TAGS:
|
||||
if self._skip:
|
||||
self._skip -= 1
|
||||
return
|
||||
if self._skip:
|
||||
return
|
||||
if tag == "a":
|
||||
label = " ".join("".join(self._anchor or []).split())
|
||||
self._keep_link(label, self._href)
|
||||
if label:
|
||||
self._html.append(_escape(label))
|
||||
self._anchor = None
|
||||
self._href = ""
|
||||
return
|
||||
if tag in _KEEP_TAGS:
|
||||
self._html.append(f"</{tag}>")
|
||||
|
||||
def handle_data(self, data: str) -> None:
|
||||
if self._skip:
|
||||
return
|
||||
if self._anchor is not None:
|
||||
self._anchor.append(data)
|
||||
return
|
||||
if data.strip():
|
||||
self._html.append(_escape(data))
|
||||
|
||||
def _keep_link(self, label: str, href: str) -> None:
|
||||
if not href or href.startswith(("#", "mailto:", "javascript:")):
|
||||
return
|
||||
absolute = urljoin(self.page_url, href)
|
||||
parts = urlsplit(absolute)
|
||||
if parts.scheme not in {"http", "https"} or not parts.hostname:
|
||||
return
|
||||
clean = urlunsplit((parts.scheme, parts.netloc, parts.path, parts.query, ""))
|
||||
if clean.rstrip("/") in self._seen:
|
||||
return
|
||||
self._seen.add(clean.rstrip("/"))
|
||||
text = label.strip() or parts.path.rsplit("/", 1)[-1] or parts.netloc
|
||||
self.links.append((text[:80], clean))
|
||||
|
||||
def fragment(self) -> str:
|
||||
body = "".join(self._html).strip()
|
||||
return body[:200_000]
|
||||
|
||||
|
||||
def _read_html(text: str, page_url: str) -> tuple[str, tuple[tuple[str, str], ...]]:
|
||||
page = _Page(page_url)
|
||||
page.feed(text)
|
||||
return page.fragment(), tuple(page.links[:24])
|
||||
|
||||
|
||||
def pdf_preview(
|
||||
data: bytes, *, limit: int = 24, scale: float = 1.25
|
||||
) -> tuple[tuple[bytes, ...], int]:
|
||||
"""PNG pages from a PDF, and the page count. The first ``limit`` pages only."""
|
||||
if not data.startswith(b"%PDF"):
|
||||
raise ReaderError("that pdf could not be opened")
|
||||
try:
|
||||
import pypdfium2 as pdfium
|
||||
except ImportError as exc:
|
||||
raise ReaderError("a pdf viewer is not installed") from exc
|
||||
try:
|
||||
document = pdfium.PdfDocument(data)
|
||||
except Exception as exc:
|
||||
raise ReaderError("that pdf could not be opened") from exc
|
||||
pages: list[bytes] = []
|
||||
try:
|
||||
total = len(document)
|
||||
for index in range(min(total, limit)):
|
||||
page = document[index]
|
||||
try:
|
||||
bitmap = page.render(scale=scale)
|
||||
try:
|
||||
image = bitmap.to_pil()
|
||||
buffer = io.BytesIO()
|
||||
image.save(buffer, format="PNG")
|
||||
pages.append(buffer.getvalue())
|
||||
finally:
|
||||
bitmap.close()
|
||||
finally:
|
||||
page.close()
|
||||
except Exception as exc:
|
||||
raise ReaderError("that pdf could not be opened") from exc
|
||||
finally:
|
||||
document.close()
|
||||
return tuple(pages), total
|
||||
|
||||
|
||||
def _escape(text: str) -> str:
|
||||
return (
|
||||
text.replace("&", "&")
|
||||
.replace("<", "<")
|
||||
.replace(">", ">")
|
||||
.replace('"', """)
|
||||
)
|
||||
@@ -2,13 +2,24 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import os
|
||||
import re
|
||||
import sqlite3
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
import httpx
|
||||
import streamlit as st
|
||||
|
||||
from lead.explore.reader import (
|
||||
USER_AGENT,
|
||||
Fetched,
|
||||
ReaderError,
|
||||
_read_html,
|
||||
fetch,
|
||||
pdf_preview,
|
||||
)
|
||||
from lead.review.codes import (
|
||||
GATE,
|
||||
PROJECTS,
|
||||
@@ -22,10 +33,15 @@ from lead.review.library import (
|
||||
connect,
|
||||
load_item,
|
||||
next_unlabeled,
|
||||
pass_two_keys,
|
||||
project_keys,
|
||||
)
|
||||
from lead.review.sources import dropped_paths, dropped_text, save_dropped
|
||||
from lead.review.sources import (
|
||||
dropped_paths,
|
||||
dropped_text,
|
||||
format_highlights,
|
||||
save_dropped,
|
||||
save_highlights,
|
||||
)
|
||||
from lead.review.store import Store
|
||||
from prisma.audit import disagreements
|
||||
from prisma.export import _extract_fulltext
|
||||
@@ -45,6 +61,43 @@ _LABELS = os.environ.get(
|
||||
# Same shape the viewer accepts. A path, not an llm host URL: the llm
|
||||
# host refuses to be framed, and this host routes the pane to that service.
|
||||
_FOCUS_KEY = re.compile(r"^[A-Za-z0-9]{6,12}$")
|
||||
_HTTP_URL = re.compile(r"https?://[^\s<>\"']+")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Tally:
|
||||
"""One pass, one queue. ``left + include + exclude + unsure == total``."""
|
||||
|
||||
total: int
|
||||
include: int
|
||||
exclude: int
|
||||
unsure: int
|
||||
|
||||
@property
|
||||
def done(self) -> int:
|
||||
return self.include + self.exclude + self.unsure
|
||||
|
||||
@property
|
||||
def left(self) -> int:
|
||||
return self.total - self.done
|
||||
|
||||
|
||||
def tally(keys: tuple[str, ...] | list[str], labeled: dict[str, str]) -> Tally:
|
||||
"""Count decisions that belong to this queue.
|
||||
|
||||
A label whose key is not in ``keys`` is an orphan and does not count.
|
||||
Any stored decision other than include or exclude counts as not sure.
|
||||
"""
|
||||
include = exclude = unsure = 0
|
||||
for key in keys:
|
||||
decision = labeled.get(key)
|
||||
if decision == "include":
|
||||
include += 1
|
||||
elif decision == "exclude":
|
||||
exclude += 1
|
||||
elif decision is not None:
|
||||
unsure += 1
|
||||
return Tally(len(keys), include, exclude, unsure)
|
||||
|
||||
|
||||
def review() -> None:
|
||||
@@ -85,22 +138,16 @@ def _review_body(store: Store, lib: sqlite3.Connection) -> None:
|
||||
labeled = store.latest(project, stage_name, pass_n)
|
||||
first = store.latest(project, stage_name, 1)
|
||||
second = store.latest(project, stage_name, 2)
|
||||
target = GATE[stage_name]
|
||||
keys = project_keys(lib, project)
|
||||
if pass_n == 1:
|
||||
pending = next_unlabeled(keys, set(labeled))
|
||||
left = sum(1 for key in keys if key not in labeled)
|
||||
else:
|
||||
queue = pass_two_keys(keys, set(first), set(labeled))
|
||||
pending = queue[0] if queue else None
|
||||
left = len(queue)
|
||||
st.caption(
|
||||
f"{left} unlabeled on this pass. "
|
||||
f"Pass 1: {len(first)} of {target}. "
|
||||
f"Pass 2: {store.count(project, stage_name, 2)} of {target}. "
|
||||
f"{_disagree_phrase(first, second)} "
|
||||
"The queue is Zotero key order. A stratified calibration sample "
|
||||
"has not been drawn, so the first items are not that sample."
|
||||
# Pass 2 reviews what pass 1 already labeled and the library still holds.
|
||||
universe = keys if pass_n == 1 else tuple(key for key in keys if key in first)
|
||||
counts = tally(universe, labeled)
|
||||
pending = next_unlabeled(universe, set(labeled))
|
||||
_show_progress(
|
||||
counts,
|
||||
stage=stage_name,
|
||||
pass_n=pass_n,
|
||||
disagree=_disagree_phrase(first, second),
|
||||
)
|
||||
if pending is None:
|
||||
if pass_n == 2 and not first:
|
||||
@@ -111,11 +158,61 @@ def _review_body(store: Store, lib: sqlite3.Connection) -> None:
|
||||
|
||||
item = load_item(lib, pending, Path(_STORAGE))
|
||||
with st.container(border=True):
|
||||
_show_record(item, stage_name, project)
|
||||
_show_record(item, stage_name, project, pass_n)
|
||||
_action_bar(store, item, project, stage_name, pass_n)
|
||||
|
||||
|
||||
def _show_record(item: Item, stage: str, project: str) -> None:
|
||||
def _show_progress(counts: Tally, *, stage: str, pass_n: int, disagree: str) -> None:
|
||||
"""The queue, not the calibration gate. The four figures sum to the queue."""
|
||||
target = GATE[stage]
|
||||
stage_words = "Title and abstract" if stage == "title_abstract" else "Full text"
|
||||
with st.container(border=True):
|
||||
st.markdown(f":material/rate_review: **Pass {pass_n}** · {stage_words}")
|
||||
fraction = counts.done / counts.total if counts.total else 0.0
|
||||
st.progress(fraction, text=f"{counts.done:,} of {counts.total:,} labeled")
|
||||
with st.container(horizontal=True):
|
||||
st.metric(
|
||||
"Left", f"{counts.left:,}", border=True, icon=":material/pending:"
|
||||
)
|
||||
st.metric(
|
||||
"Include",
|
||||
f"{counts.include:,}",
|
||||
border=True,
|
||||
icon=":material/check:",
|
||||
)
|
||||
st.metric(
|
||||
"Exclude",
|
||||
f"{counts.exclude:,}",
|
||||
border=True,
|
||||
icon=":material/close:",
|
||||
)
|
||||
st.metric(
|
||||
"Not sure",
|
||||
f"{counts.unsure:,}",
|
||||
border=True,
|
||||
icon=":material/help:",
|
||||
)
|
||||
if counts.done >= target:
|
||||
st.badge(
|
||||
"Gate met",
|
||||
icon=":material/verified:",
|
||||
color="green",
|
||||
)
|
||||
gate = f"Calibration gate of {target:,} is met."
|
||||
else:
|
||||
st.badge("Gate open", icon=":material/flag:", color="orange")
|
||||
gate = (
|
||||
f"{target - counts.done:,} more labels meet the "
|
||||
f"calibration gate of {target:,}."
|
||||
)
|
||||
st.caption(
|
||||
f"{gate} {disagree} "
|
||||
"The queue is Zotero key order. A stratified calibration sample "
|
||||
"has not been drawn, so the first items are not that sample."
|
||||
)
|
||||
|
||||
|
||||
def _show_record(item: Item, stage: str, project: str, pass_n: int) -> None:
|
||||
st.subheader(item.title or "(no title)")
|
||||
if stage == "full_text":
|
||||
_full_text(item)
|
||||
@@ -140,13 +237,12 @@ def _show_record(item: Item, stage: str, project: str) -> None:
|
||||
if detail:
|
||||
st.markdown(" · ".join(detail))
|
||||
notes = provenance_lines(item)
|
||||
if notes:
|
||||
st.caption(" · ".join(notes))
|
||||
plain = [note for note in notes if not _HTTP_URL.search(note)]
|
||||
if plain:
|
||||
st.caption(" · ".join(plain))
|
||||
if item.history:
|
||||
st.caption(item.history)
|
||||
links = record_links(item)
|
||||
if links:
|
||||
st.markdown(" · ".join(f"[{label}]({href})" for label, href in links))
|
||||
_article_links(item, _screen_id(project, stage, pass_n, item.key))
|
||||
abstract = item.abstract.strip()
|
||||
if abstract:
|
||||
st.text_area("Abstract", abstract, height=220, disabled=True)
|
||||
@@ -154,6 +250,217 @@ def _show_record(item: Item, stage: str, project: str) -> None:
|
||||
st.caption(_missing_line(item))
|
||||
|
||||
|
||||
def _article_links(item: Item, screen: str) -> None:
|
||||
"""Source and full-text addresses. A button opens the pane. A bare link does not."""
|
||||
stored = _fulltext_path(item)
|
||||
if stored is not None:
|
||||
_show_stored(stored)
|
||||
links = _pane_links(item)
|
||||
if not links:
|
||||
return
|
||||
st.text("\n".join(href for _label, href in links))
|
||||
if stored is not None:
|
||||
return
|
||||
with st.container(horizontal=True):
|
||||
for label, href in links:
|
||||
if st.button(
|
||||
label,
|
||||
key=f"open-{item.key}-{_token(href)}",
|
||||
icon=":material/article:",
|
||||
width="content",
|
||||
):
|
||||
_open_article(screen, href)
|
||||
st.rerun()
|
||||
_article_pane(item, screen)
|
||||
|
||||
|
||||
def _pane_links(item: Item) -> tuple[tuple[str, str], ...]:
|
||||
found = list(record_links(item))
|
||||
seen = {href.rstrip("/") for _label, href in found}
|
||||
for note in provenance_lines(item):
|
||||
for raw in _HTTP_URL.findall(note):
|
||||
href = raw.rstrip(").,;")
|
||||
if href.rstrip("/") in seen:
|
||||
continue
|
||||
seen.add(href.rstrip("/"))
|
||||
label = _HTTP_URL.sub(" ", note)
|
||||
label = " ".join(label.replace("—", " ").split()).strip(" :-")
|
||||
found.append((label or "Open the full text", href))
|
||||
return tuple(found)
|
||||
|
||||
|
||||
def _article_pane(item: Item, screen: str) -> None:
|
||||
current = st.session_state.get("lead_reader", {}).get(screen)
|
||||
if not current:
|
||||
return
|
||||
url = str(current.get("url") or "")
|
||||
if not url:
|
||||
return
|
||||
with st.container(border=True):
|
||||
st.markdown(":material/article: **Article**")
|
||||
st.caption("This pane is your browser.")
|
||||
st.text(url)
|
||||
if not url.startswith(("https://", "http://")):
|
||||
st.warning("that link is not a web page")
|
||||
return
|
||||
with st.container(horizontal=True):
|
||||
back = list(current.get("back") or [])
|
||||
if back and st.button(
|
||||
"Back",
|
||||
key=f"article-back-{item.key}",
|
||||
icon=":material/arrow_back:",
|
||||
width="content",
|
||||
):
|
||||
current["url"] = back[-1]
|
||||
current["back"] = back[:-1]
|
||||
st.rerun()
|
||||
if st.button(
|
||||
"Close",
|
||||
key=f"article-close-{item.key}",
|
||||
icon=":material/close:",
|
||||
width="content",
|
||||
):
|
||||
st.session_state["lead_reader"].pop(screen, None)
|
||||
st.session_state.get("lead_reader_page", {}).pop(screen, None)
|
||||
st.rerun()
|
||||
st.iframe(url, height=640, alt="Article")
|
||||
if st.button(
|
||||
"Pull this page in",
|
||||
key=f"pull-{item.key}",
|
||||
icon=":material/download:",
|
||||
width="content",
|
||||
):
|
||||
_pull_article(item, url)
|
||||
st.rerun()
|
||||
|
||||
|
||||
def _fulltext_path(item: Item) -> Path | None:
|
||||
for path in dropped_paths(_LABELS, item.key):
|
||||
if path.name.startswith("fulltext."):
|
||||
return path
|
||||
return None
|
||||
|
||||
|
||||
def _show_stored(path: Path) -> None:
|
||||
"""The full text already attached to this review."""
|
||||
try:
|
||||
data = path.read_bytes()
|
||||
except OSError:
|
||||
st.warning("the stored full text could not be read")
|
||||
return
|
||||
with st.container(border=True):
|
||||
st.markdown(":material/article: **Stored full text**")
|
||||
st.caption("Stored with this review. Not written into Zotero.")
|
||||
suffix = path.suffix.lower()
|
||||
if suffix == ".pdf":
|
||||
_show_fetched(Fetched("stored", "pdf", data, "application/pdf", (), ""))
|
||||
elif suffix in {".html", ".htm"}:
|
||||
html, _links = _read_html(data.decode("utf-8", errors="replace"), "")
|
||||
_show_fetched(Fetched("stored", "html", data, "text/html", (), html))
|
||||
else:
|
||||
st.text(data.decode("utf-8", errors="replace")[:20_000])
|
||||
|
||||
|
||||
@st.cache_data(max_entries=4, show_spinner=False)
|
||||
def _pdf_pages(data: bytes) -> tuple[tuple[bytes, ...], int]:
|
||||
return pdf_preview(data)
|
||||
|
||||
|
||||
def _show_fetched(page: Fetched) -> None:
|
||||
if page.kind == "pdf":
|
||||
try:
|
||||
images, total = _pdf_pages(page.body)
|
||||
except ReaderError as exc:
|
||||
st.warning(str(exc))
|
||||
return
|
||||
if not images:
|
||||
st.warning("that pdf has no pages")
|
||||
return
|
||||
with st.container(height=640):
|
||||
for index, png in enumerate(images, start=1):
|
||||
st.image(
|
||||
png,
|
||||
alt=f"Page {index} of the article",
|
||||
width="stretch",
|
||||
)
|
||||
if total > len(images):
|
||||
st.caption(
|
||||
f"Showing the first {len(images):,} of {total:,} pages. "
|
||||
"Pull this page in keeps the whole file."
|
||||
)
|
||||
return
|
||||
if page.html:
|
||||
with st.container(height=520):
|
||||
st.html(page.html)
|
||||
|
||||
|
||||
def _open_article(screen: str, href: str) -> None:
|
||||
box = st.session_state.setdefault("lead_reader", {})
|
||||
current = box.get(screen) or {}
|
||||
previous = str(current.get("url") or "")
|
||||
back = list(current.get("back") or [])
|
||||
if previous and previous != href:
|
||||
back.append(previous)
|
||||
box[screen] = {"url": href, "back": back[-12:]}
|
||||
|
||||
|
||||
def _write_page(item: Item, page: Fetched) -> None:
|
||||
suffix = {"pdf": ".pdf", "html": ".html"}.get(page.kind, ".txt")
|
||||
save_dropped(_LABELS, item.key, f"article{suffix}", page.body)
|
||||
|
||||
|
||||
def _pull_article(item: Item, url: str) -> None:
|
||||
try:
|
||||
_write_page(item, fetch(url))
|
||||
except ReaderError as exc:
|
||||
st.warning(str(exc))
|
||||
except ValueError as exc:
|
||||
st.error(str(exc))
|
||||
|
||||
|
||||
def review_highlights(key: str) -> str:
|
||||
"""Human highlights from the focus pane. Empty when the pane store is quiet."""
|
||||
base = os.environ.get("LEAD_FOCUS_URL", "http://llm:8000").strip().rstrip("/")
|
||||
if not base or not re.fullmatch(r"[A-Za-z0-9]{1,16}", key):
|
||||
return ""
|
||||
try:
|
||||
with httpx.Client(timeout=httpx.Timeout(4.0, connect=1.5)) as client:
|
||||
response = client.get(
|
||||
f"{base}/api/focus/{key}/annotations",
|
||||
params={"protocol": "prisma-screen"},
|
||||
headers={"User-Agent": USER_AGENT},
|
||||
)
|
||||
except httpx.HTTPError:
|
||||
return ""
|
||||
if response.status_code != 200:
|
||||
return ""
|
||||
try:
|
||||
payload = response.json()
|
||||
except ValueError:
|
||||
return ""
|
||||
return format_highlights(payload)
|
||||
|
||||
|
||||
def _keep_article(item: Item, project: str, stage: str, pass_n: int) -> None:
|
||||
"""Attach the open page and any highlights. A rejection never calls this."""
|
||||
if _fulltext_path(item) is None:
|
||||
screen = _screen_id(project, stage, pass_n, item.key)
|
||||
current = (st.session_state.get("lead_reader") or {}).get(screen) or {}
|
||||
url = str(current.get("url") or "")
|
||||
if url:
|
||||
try:
|
||||
_write_page(item, fetch(url))
|
||||
except (ReaderError, ValueError):
|
||||
pass
|
||||
text = review_highlights(item.key)
|
||||
if text:
|
||||
save_highlights(_LABELS, item.key, text)
|
||||
|
||||
|
||||
def _token(href: str) -> str:
|
||||
return hashlib.sha256(href.encode()).hexdigest()[:10]
|
||||
|
||||
|
||||
_ASK = {
|
||||
"lead-history": (
|
||||
"Include primary CMS methodology, a paper those methods cite, or a "
|
||||
@@ -372,6 +679,8 @@ def _commit(
|
||||
except ValueError as exc:
|
||||
st.error(str(exc))
|
||||
return
|
||||
if decision == "include":
|
||||
_keep_article(item, project, stage, pass_n)
|
||||
st.session_state.pop("lead_exclude_for", None)
|
||||
st.rerun()
|
||||
|
||||
|
||||
@@ -52,17 +52,59 @@ def save_dropped(
|
||||
folder = sources_root(labels_path) / key
|
||||
dest = folder / f"fulltext{suffix}"
|
||||
if dest.is_file() and dest.read_bytes() == data:
|
||||
extras = [path for path in folder.iterdir() if path.is_file() and path != dest]
|
||||
extras = [
|
||||
path
|
||||
for path in folder.iterdir()
|
||||
if path.is_file() and path != dest and path.name != "highlights.txt"
|
||||
]
|
||||
if not extras:
|
||||
return dest, False
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
for old in folder.iterdir():
|
||||
if old.is_file() and old != dest:
|
||||
if old.is_file() and old != dest and old.name != "highlights.txt":
|
||||
old.unlink()
|
||||
dest.write_bytes(data)
|
||||
return dest, True
|
||||
|
||||
|
||||
def save_highlights(labels_path: str | Path, zotero_key: str, text: str) -> Path | None:
|
||||
"""Store review highlights beside the full text. Does not remove that file."""
|
||||
body = text.strip()
|
||||
key = zotero_key.strip()
|
||||
if not body or not _KEY.fullmatch(key):
|
||||
return None
|
||||
folder = sources_root(labels_path) / key
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
dest = folder / "highlights.txt"
|
||||
data = body.encode("utf-8")
|
||||
if dest.is_file() and dest.read_bytes() == data:
|
||||
return dest
|
||||
dest.write_bytes(data)
|
||||
return dest
|
||||
|
||||
|
||||
def format_highlights(rows: object) -> str:
|
||||
"""Human highlight lines. Model rows and deleted rows are left out."""
|
||||
if not isinstance(rows, list):
|
||||
return ""
|
||||
lines: list[str] = []
|
||||
for row in rows:
|
||||
if not isinstance(row, dict) or row.get("deleted_at"):
|
||||
continue
|
||||
if row.get("provenance") != "human":
|
||||
continue
|
||||
quote = " ".join(str(row.get("quote") or "").split())
|
||||
if not quote:
|
||||
continue
|
||||
label = " ".join(str(row.get("label") or "").split())
|
||||
note = " ".join(str(row.get("note") or "").split())
|
||||
line = f"{label}: {quote}" if label else quote
|
||||
if note:
|
||||
line = f"{line} ({note})"
|
||||
lines.append(line)
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def dropped_paths(labels_path: str | Path, zotero_key: str) -> tuple[Path, ...]:
|
||||
"""Files already dropped for this key. Empty when the key is not safe."""
|
||||
key = zotero_key.strip()
|
||||
|
||||
@@ -41,6 +41,23 @@ def _blob(at) -> str:
|
||||
return "\n".join(part for part in chunks if part)
|
||||
|
||||
|
||||
def _counts(at) -> dict[str, int]:
|
||||
metrics = {item.label: str(item.value) for item in at.metric}
|
||||
return {
|
||||
name: int(metrics[name].replace(",", ""))
|
||||
for name in ("Left", "Include", "Exclude", "Not sure")
|
||||
}
|
||||
|
||||
|
||||
def _assert_adds_up(at) -> None:
|
||||
counts = _counts(at)
|
||||
total = sum(counts.values())
|
||||
done = total - counts["Left"]
|
||||
bar = at.progress[0]
|
||||
assert bar.text == f"{done:,} of {total:,} labeled"
|
||||
assert bar.value == (round(100 * done / total) if total else 0)
|
||||
|
||||
|
||||
def _widget(at, kind: str, label: str):
|
||||
kinds = ("button", "form_submit_button") if kind == "button" else (kind,)
|
||||
found = [
|
||||
@@ -346,10 +363,15 @@ def test_the_label_page_saves_a_decision_and_shows_a_full_text(tmp_path, monkeyp
|
||||
assert "off-topic" in blob
|
||||
assert "Nothing to type." in blob
|
||||
assert "Nothing unlabeled" not in blob
|
||||
assert _counts(at) == {"Left": 1, "Include": 0, "Exclude": 0, "Not sure": 0}
|
||||
_assert_adds_up(at)
|
||||
assert "200 more labels meet the calibration gate of 200." in blob
|
||||
assert list(at.get("iframe")) == []
|
||||
_widget(at, "button", "Include").click().run()
|
||||
assert not at.exception, at.exception
|
||||
assert "Nothing unlabeled on this pass." in _blob(at)
|
||||
assert _counts(at) == {"Left": 0, "Include": 1, "Exclude": 0, "Not sure": 0}
|
||||
_assert_adds_up(at)
|
||||
|
||||
from lead.review.store import Store
|
||||
|
||||
@@ -361,6 +383,8 @@ def test_the_label_page_saves_a_decision_and_shows_a_full_text(tmp_path, monkeyp
|
||||
_widget(at, "segmented_control", "Pass").set_value(2).run()
|
||||
assert not at.exception, at.exception
|
||||
assert "Ada Lovelace" in _blob(at)
|
||||
assert _counts(at) == {"Left": 1, "Include": 0, "Exclude": 0, "Not sure": 0}
|
||||
_assert_adds_up(at)
|
||||
_widget(at, "button", "Not sure").click().run()
|
||||
assert not at.exception, at.exception
|
||||
assert saved.latest("lead-history", "title_abstract", 2) == {
|
||||
@@ -377,7 +401,7 @@ def test_the_label_page_saves_a_decision_and_shows_a_full_text(tmp_path, monkeyp
|
||||
frames = list(fresh.get("iframe"))
|
||||
assert len(frames) == 1
|
||||
assert frames[0].proto.src == "/ui/pdf/AAAAAAAA?protocol=prisma-screen"
|
||||
assert [b.label for b in fresh.button] == ["Include", "Not sure", "Exclude"]
|
||||
assert [b.label for b in fresh.button][-3:] == ["Include", "Not sure", "Exclude"]
|
||||
|
||||
|
||||
def test_a_bare_federal_register_notice_shows_the_link_and_not_an_empty_box(
|
||||
@@ -663,6 +687,136 @@ def test_an_unreadable_attachment_is_a_warning(tmp_path, monkeypatch):
|
||||
assert "no text came out of it" in _blob(at)
|
||||
|
||||
|
||||
def test_a_source_link_opens_in_the_pane_and_can_be_pulled_in(tmp_path, monkeypatch):
|
||||
from lead.explore import review_page
|
||||
from lead.explore.reader import Fetched
|
||||
|
||||
def fake(url: str, **_kwargs):
|
||||
return Fetched(
|
||||
url,
|
||||
"html",
|
||||
b"<p>Hello paper</p>",
|
||||
"text/html",
|
||||
(),
|
||||
"<p>Hello paper</p>",
|
||||
)
|
||||
|
||||
monkeypatch.setattr(review_page, "fetch", fake)
|
||||
monkeypatch.setattr(review_page, "review_highlights", lambda _key: "")
|
||||
_labels(monkeypatch, tmp_path, _zotero(tmp_path, attachment=None))
|
||||
at = _run("from lead.explore.review_page import review\nreview()\n")
|
||||
assert "https://example.test/paper" in _blob(at)
|
||||
_widget(at, "button", "Open the source").click().run()
|
||||
assert not at.exception, at.exception
|
||||
assert "Article" in _blob(at)
|
||||
assert "your browser" in _blob(at)
|
||||
frames = list(at.get("iframe"))
|
||||
assert len(frames) == 1
|
||||
assert frames[0].proto.src == "https://example.test/paper"
|
||||
_widget(at, "button", "Pull this page in").click().run()
|
||||
assert not at.exception, at.exception
|
||||
stored = tmp_path / "sources" / "AAAAAAAA" / "fulltext.html"
|
||||
assert b"Hello paper" in stored.read_bytes()
|
||||
assert "Stored full text" in _blob(at)
|
||||
|
||||
|
||||
def test_include_stores_the_open_page_and_highlights(tmp_path, monkeypatch):
|
||||
from lead.explore import review_page
|
||||
from lead.explore.reader import Fetched
|
||||
|
||||
monkeypatch.setattr(
|
||||
review_page,
|
||||
"fetch",
|
||||
lambda url, **_kwargs: Fetched(
|
||||
url, "html", b"<p>Hello paper</p>", "text/html", (), "<p>Hello paper</p>"
|
||||
),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
review_page,
|
||||
"review_highlights",
|
||||
lambda _key: "include: Exposure precedes the outcome.",
|
||||
)
|
||||
_labels(monkeypatch, tmp_path, _zotero(tmp_path, attachment=None))
|
||||
at = _run("from lead.explore.review_page import review\nreview()\n")
|
||||
_widget(at, "button", "Open the source").click().run()
|
||||
_widget(at, "button", "Include").click().run()
|
||||
assert not at.exception, at.exception
|
||||
folder = tmp_path / "sources" / "AAAAAAAA"
|
||||
assert b"Hello paper" in (folder / "fulltext.html").read_bytes()
|
||||
assert "Exposure precedes" in (folder / "highlights.txt").read_text()
|
||||
|
||||
|
||||
def test_exclude_does_not_store_the_open_page(tmp_path, monkeypatch):
|
||||
from lead.explore import review_page
|
||||
from lead.review.codes import reason_choices
|
||||
|
||||
def boom(*_args, **_kwargs):
|
||||
raise AssertionError("exclude must not fetch the article")
|
||||
|
||||
monkeypatch.setattr(review_page, "fetch", boom)
|
||||
monkeypatch.setattr(review_page, "review_highlights", boom)
|
||||
_labels(monkeypatch, tmp_path, _zotero(tmp_path, attachment=None))
|
||||
at = _run("from lead.explore.review_page import review\nreview()\n")
|
||||
_widget(at, "button", "Open the source").click().run()
|
||||
_widget(at, "button", "Exclude").click().run()
|
||||
sentence = next(
|
||||
text for code, text in reason_choices("lead-history") if code == "off-topic"
|
||||
)
|
||||
_widget(at, "button", sentence).click().run()
|
||||
assert not at.exception, at.exception
|
||||
assert not (tmp_path / "sources").exists()
|
||||
|
||||
|
||||
def test_a_stored_full_text_is_shown_and_include_does_not_replace_it(
|
||||
tmp_path, monkeypatch
|
||||
):
|
||||
from lead.explore import review_page
|
||||
from lead.review.sources import save_dropped
|
||||
|
||||
save_dropped(
|
||||
tmp_path / "labels.sqlite",
|
||||
"AAAAAAAA",
|
||||
"kept.html",
|
||||
b"<p>Kept paper</p>",
|
||||
)
|
||||
|
||||
def boom(*_args, **_kwargs):
|
||||
raise AssertionError("an existing full text is not fetched again")
|
||||
|
||||
monkeypatch.setattr(review_page, "fetch", boom)
|
||||
monkeypatch.setattr(review_page, "review_highlights", lambda _key: "")
|
||||
_labels(monkeypatch, tmp_path, _zotero(tmp_path, attachment=None))
|
||||
at = _run("from lead.explore.review_page import review\nreview()\n")
|
||||
assert "Stored full text" in _blob(at)
|
||||
html = " ".join(str(getattr(item, "value", "")) for item in at.html)
|
||||
assert "Kept paper" in html
|
||||
assert list(at.get("iframe")) == []
|
||||
_widget(at, "button", "Include").click().run()
|
||||
assert not at.exception, at.exception
|
||||
assert (
|
||||
b"Kept paper"
|
||||
in (tmp_path / "sources" / "AAAAAAAA" / "fulltext.html").read_bytes()
|
||||
)
|
||||
|
||||
|
||||
def test_tally_ignores_labels_outside_the_queue():
|
||||
from lead.explore.review_page import tally
|
||||
|
||||
keys = ("a", "b", "c", "d")
|
||||
labeled = {"a": "include", "b": "exclude", "c": "uncertain", "z": "include"}
|
||||
got = tally(keys, labeled)
|
||||
assert (got.left, got.include, got.exclude, got.unsure, got.total) == (
|
||||
1,
|
||||
1,
|
||||
1,
|
||||
1,
|
||||
4,
|
||||
)
|
||||
assert got.left + got.include + got.exclude + got.unsure == got.total
|
||||
empty = tally((), {"a": "include"})
|
||||
assert (empty.left, empty.done, empty.total) == (0, 0, 0)
|
||||
|
||||
|
||||
def test_two_passes_that_disagree_are_counted(tmp_path, monkeypatch):
|
||||
from lead.review.store import Store
|
||||
|
||||
@@ -688,3 +842,6 @@ def test_two_passes_that_disagree_are_counted(tmp_path, monkeypatch):
|
||||
at = _run("from lead.explore.review_page import review\nreview()\n")
|
||||
assert "disagree" in _blob(at)
|
||||
assert "Nothing unlabeled on this pass." in _blob(at)
|
||||
assert _counts(at) == {"Left": 0, "Include": 1, "Exclude": 0, "Not sure": 0}
|
||||
_assert_adds_up(at)
|
||||
assert "1 of 1 items labeled in both passes disagree." in _blob(at)
|
||||
|
||||
133
tests/lead/test_reader.py
Normal file
133
tests/lead/test_reader.py
Normal file
@@ -0,0 +1,133 @@
|
||||
"""The review pane fetches a public page and will not follow a link onto this network."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ipaddress
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from lead.explore.reader import ReaderError, _read_html, fetch, pdf_preview
|
||||
|
||||
|
||||
def _client(handler) -> httpx.Client:
|
||||
return httpx.Client(transport=httpx.MockTransport(handler))
|
||||
|
||||
|
||||
def test_fetch_reads_html_and_keeps_a_real_link():
|
||||
seen = {}
|
||||
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
seen["ua"] = request.headers.get("user-agent")
|
||||
if request.url.path == "/paper":
|
||||
return httpx.Response(302, headers={"location": "https://1.1.1.1/final"})
|
||||
body = (
|
||||
b"<html><body><script>alert(1)</script>"
|
||||
b"<p>The exposure precedes the outcome.</p>"
|
||||
b"<a href='/a.pdf'>The PDF</a>"
|
||||
b"<a href='javascript:alert(1)'>no</a></body></html>"
|
||||
)
|
||||
return httpx.Response(200, headers={"content-type": "text/html"}, content=body)
|
||||
|
||||
got = fetch("https://1.1.1.1/paper", client=_client(handler))
|
||||
assert seen["ua"].startswith("stack-lead-review/")
|
||||
assert got.url == "https://1.1.1.1/final"
|
||||
assert got.kind == "html"
|
||||
assert "The exposure precedes" in got.html
|
||||
assert "alert" not in got.html
|
||||
assert got.links == (("The PDF", "https://1.1.1.1/a.pdf"),)
|
||||
|
||||
|
||||
def test_fetch_stops_when_a_redirect_lands_on_this_network():
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
return httpx.Response(302, headers={"location": "http://127.0.0.1/secret"})
|
||||
|
||||
with pytest.raises(ReaderError, match="this network"):
|
||||
fetch("https://1.1.1.1/start", client=_client(handler))
|
||||
|
||||
|
||||
def test_a_private_address_is_refused_before_a_request():
|
||||
called = {"n": 0}
|
||||
|
||||
def handler(_request: httpx.Request) -> httpx.Response:
|
||||
called["n"] += 1
|
||||
return httpx.Response(200, content=b"no")
|
||||
|
||||
for url in (
|
||||
"http://127.0.0.1/",
|
||||
"http://10.1.1.1/",
|
||||
"http://192.168.1.192/labels",
|
||||
"http://169.254.169.254/latest",
|
||||
"http://1.1.1.1:8501/",
|
||||
"file:///etc/passwd",
|
||||
"http://user:pass@1.1.1.1/",
|
||||
):
|
||||
with pytest.raises(ReaderError):
|
||||
fetch(url, client=_client(handler))
|
||||
assert called["n"] == 0
|
||||
|
||||
|
||||
def test_a_hostname_that_resolves_inside_the_network_is_refused(monkeypatch):
|
||||
def inside(*_args, **_kwargs):
|
||||
return [(2, 1, 6, "", ("127.0.0.1", 0))]
|
||||
|
||||
monkeypatch.setattr("lead.explore.reader.socket.getaddrinfo", inside)
|
||||
with pytest.raises(ReaderError, match="this network"):
|
||||
fetch(
|
||||
"https://example.test/paper", client=_client(lambda _r: httpx.Response(200))
|
||||
)
|
||||
|
||||
|
||||
def test_a_browser_check_is_not_stored_as_the_article():
|
||||
def handler(_request: httpx.Request) -> httpx.Response:
|
||||
return httpx.Response(
|
||||
200,
|
||||
headers={"content-type": "text/html"},
|
||||
content=b"<html><title>Just a moment...</title><body>cloudflare</body></html>",
|
||||
)
|
||||
|
||||
with pytest.raises(ReaderError, match="browser check"):
|
||||
fetch("https://1.1.1.1/paper", client=_client(handler))
|
||||
|
||||
|
||||
def test_a_pdf_is_kept_as_bytes():
|
||||
def handler(_request: httpx.Request) -> httpx.Response:
|
||||
return httpx.Response(
|
||||
200,
|
||||
headers={"content-type": "application/pdf"},
|
||||
content=b"%PDF-1.4\npaper\n",
|
||||
)
|
||||
|
||||
got = fetch("https://1.1.1.1/a.pdf", client=_client(handler))
|
||||
assert got.kind == "pdf"
|
||||
assert got.body.startswith(b"%PDF")
|
||||
assert got.links == ()
|
||||
|
||||
|
||||
def test_pdf_preview_renders_pages_and_rejects_garbage():
|
||||
import io
|
||||
|
||||
import pypdfium2 as pdfium
|
||||
|
||||
document = pdfium.PdfDocument.new()
|
||||
for _ in range(3):
|
||||
document.new_page(80, 60)
|
||||
buffer = io.BytesIO()
|
||||
document.save(buffer)
|
||||
document.close()
|
||||
images, total = pdf_preview(buffer.getvalue(), limit=2, scale=1)
|
||||
assert total == 3
|
||||
assert len(images) == 2
|
||||
assert images[0].startswith(b"\x89PNG")
|
||||
with pytest.raises(ReaderError, match="could not be opened"):
|
||||
pdf_preview(b"%PDF-1.4\nbody\n")
|
||||
|
||||
|
||||
def test_read_html_resolves_a_relative_link_against_the_page():
|
||||
html, links = _read_html(
|
||||
"<p>Note</p><a href='files/a.pdf'>PDF</a>",
|
||||
"https://1.1.1.1/dir/paper",
|
||||
)
|
||||
assert "Note" in html
|
||||
assert links == (("PDF", "https://1.1.1.1/dir/files/a.pdf"),)
|
||||
assert ipaddress.ip_address("1.1.1.1").is_global
|
||||
@@ -78,6 +78,46 @@ def test_a_dropped_full_source_stays_beside_the_labels(tmp_path: Path):
|
||||
save_dropped(labels, "AAAAAAAA", "a.txt", b"")
|
||||
|
||||
|
||||
def test_highlights_stay_when_the_full_text_is_replaced(tmp_path: Path):
|
||||
from lead.review.sources import (
|
||||
dropped_text,
|
||||
format_highlights,
|
||||
save_dropped,
|
||||
save_highlights,
|
||||
)
|
||||
|
||||
labels = tmp_path / "labels.sqlite"
|
||||
save_dropped(labels, "AAAAAAAA", "a.html", b"<p>Exposure first.</p>")
|
||||
note = save_highlights(
|
||||
labels,
|
||||
"AAAAAAAA",
|
||||
format_highlights(
|
||||
[
|
||||
{
|
||||
"provenance": "human",
|
||||
"label": "include",
|
||||
"quote": "Exposure first.",
|
||||
"note": "",
|
||||
"deleted_at": None,
|
||||
},
|
||||
{
|
||||
"provenance": "model",
|
||||
"label": "skip",
|
||||
"quote": "not a person",
|
||||
"deleted_at": None,
|
||||
},
|
||||
]
|
||||
),
|
||||
)
|
||||
assert note is not None and note.name == "highlights.txt"
|
||||
save_dropped(labels, "AAAAAAAA", "a.txt", b"Plain full text.")
|
||||
assert note.is_file()
|
||||
text = dropped_text(labels, "AAAAAAAA")
|
||||
assert "Plain full text." in text
|
||||
assert "include: Exposure first." in text
|
||||
assert "not a person" not in text
|
||||
|
||||
|
||||
def test_exclude_needs_a_codebook_reason_and_a_rationale(tmp_path: Path):
|
||||
store = Store(tmp_path / "labels.sqlite")
|
||||
store.record(
|
||||
|
||||
Reference in New Issue
Block a user