Coverage for app / services / knowledge / candidates.py: 86%
69 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
1"""The web sources and documents generative knowledge setup found, as svc-core
2keeps them.
4svc-ai searches and checks (``knowledge/discovery.py`` there); what comes back
5is re-validated here before anything is offered — an address normalised as
6a person's would be, its kind one this service knows, a document within the
7import cap — and kept on the run, in order. The design call chooses among
8them by index, and :func:`resolve` maps a source's indexes back to this copy:
9an address is never taken from a model's reply, and an index of the wrong
10kind for the source (a page for a file source) is dropped with a warning.
11"""
13from __future__ import annotations
15from typing import Any, Iterable, Literal
17from pydantic import BaseModel
19from app.services.knowledge import file_types
20from app.services.knowledge.web_config import normalise_seed_url
22Kind = Literal["page", "feed", "document"]
24#: Which kinds each source type takes: a website source crawls pages and
25#: feeds, a file source keeps documents. Every other type takes none.
26ACCEPTS: dict[str, frozenset[str]] = {
27 "web": frozenset({"page", "feed"}),
28 "file": frozenset({"document"}),
29}
31#: The most candidates of each kind one design is shown.
32MAX_PER_KIND = 12
35class Candidate(BaseModel):
36 """A checked address the designer may choose — and the review shows."""
38 kind: Kind
39 url: str
40 title: str = ""
41 host: str = ""
42 snippet: str = ""
43 published: str | None = None
44 publisher: str | None = None
45 content_type: str | None = None
46 size_bytes: int | None = None
49def from_checked(
50 found: Iterable[dict], checked: Iterable[dict], warnings: list[str]
51) -> list[Candidate]:
52 """The candidates to offer: each found result whose check came back ok,
53 with what the search said of it and what its address is. Normalised as a
54 person's URL would be, de-duplicated by final address, and capped per
55 kind; a document over the import cap is left out."""
56 by_url = {item.get("url"): item for item in found if isinstance(item, dict)}
57 out: list[Candidate] = []
58 seen: set[str] = set()
59 per_kind: dict[str, int] = {}
60 unusable = 0
61 for item in checked:
62 if not isinstance(item, dict) or item.get("status") != "ok":
63 unusable += 1
64 continue
65 kind = item.get("kind")
66 if kind not in ("page", "feed", "document"):
67 unusable += 1
68 continue
69 try:
70 url = normalise_seed_url(str(item.get("url") or item.get("requested_url")))
71 except ValueError:
72 unusable += 1
73 continue
74 size = item.get("size_bytes")
75 if (
76 kind == "document"
77 and isinstance(size, int)
78 and size > file_types.MAX_IMPORT_BYTES
79 ):
80 unusable += 1
81 continue
82 if url in seen or per_kind.get(kind, 0) >= MAX_PER_KIND:
83 continue
84 seen.add(url)
85 per_kind[kind] = per_kind.get(kind, 0) + 1
86 result = by_url.get(item.get("requested_url")) or {}
87 out.append(
88 Candidate(
89 kind=kind,
90 url=url,
91 title=str(item.get("title") or result.get("title") or "")[:300],
92 host=str(result.get("host") or _host(url)),
93 snippet=str(result.get("snippet") or "")[:500],
94 published=result.get("published"),
95 publisher=result.get("publisher"),
96 content_type=item.get("content_type"),
97 size_bytes=size if isinstance(size, int) else None,
98 )
99 )
100 if unusable:
101 warnings.append(
102 f"Left out {unusable} search result(s) that could not be used — "
103 "unreachable, closed to crawlers, or not a page or document."
104 )
105 return out
108def _host(url: str) -> str:
109 from urllib.parse import urlsplit
111 return (urlsplit(url).hostname or "").removeprefix("www.")
114def resolve(
115 source_type: str,
116 indexes: Iterable[Any],
117 candidates: list[Candidate],
118 *,
119 name: str,
120 warnings: list[str],
121) -> list[Candidate]:
122 """The candidates a proposed source chose, from svc-core's own copy: an
123 index outside it is ignored, and one of a kind the source type does not
124 take is dropped with a warning."""
125 accepts = ACCEPTS.get(source_type, frozenset())
126 chosen: list[Candidate] = []
127 wrong = 0
128 for index in indexes:
129 if not isinstance(index, int) or not 0 <= index < len(candidates):
130 continue
131 candidate = candidates[index]
132 if candidate.kind not in accepts:
133 wrong += 1
134 continue
135 if candidate not in chosen:
136 chosen.append(candidate)
137 if wrong:
138 warnings.append(
139 f"'{name}' was given {wrong} link(s) a {source_type} source cannot "
140 "hold; they were left out."
141 )
142 return chosen