quote-vetter 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,22 @@
1
+ name: test
2
+ on: [push, pull_request]
3
+ jobs:
4
+ test:
5
+ runs-on: ubuntu-latest
6
+ strategy:
7
+ matrix:
8
+ python: ["3.10", "3.13"]
9
+ steps:
10
+ - uses: actions/checkout@v4
11
+ - uses: actions/setup-python@v5
12
+ with:
13
+ python-version: ${{ matrix.python }}
14
+ - run: pip install -e ".[dev,mcp]"
15
+ - run: pytest -q
16
+ - name: Dogfood - mcp-ship-check on this repo (live; it needs Python 3.11+)
17
+ if: matrix.python != '3.10'
18
+ run: |
19
+ pip install mcp-ship-check
20
+ mcp-ship-check . --command quote-vetter-mcp --json > report.json || true
21
+ - if: matrix.python != '3.10'
22
+ run: python -c "import json;r=json.load(open('report.json'));print(r['score'],r['grade']);assert r['counts']['fail']==0,[x for x in r['results'] if x['status']=='fail']"
@@ -0,0 +1,5 @@
1
+ .venv/
2
+ __pycache__/
3
+ dist/
4
+ *.egg-info/
5
+ .pytest_cache/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Saad Ali Khan
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,100 @@
1
+ Metadata-Version: 2.5
2
+ Name: quote-vetter
3
+ Version: 0.1.0
4
+ Summary: Vet a quote or poem before you publish it: public-domain check, known misattributions, Wikiquote source check and a credit line. CLI, MCP server and Claude Code skill.
5
+ Project-URL: Homepage, https://github.com/ali-saad-khan/quote-vetter
6
+ Project-URL: Source, https://github.com/ali-saad-khan/quote-vetter
7
+ Project-URL: Issues, https://github.com/ali-saad-khan/quote-vetter/issues
8
+ License: MIT
9
+ License-File: LICENSE
10
+ Keywords: claude-code,copyright,mcp,misattribution,poetry,public-domain,quotes,shorts,wikiquote
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: End Users/Desktop
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Topic :: Text Processing
16
+ Requires-Python: >=3.10
17
+ Provides-Extra: dev
18
+ Requires-Dist: pytest>=8; extra == 'dev'
19
+ Provides-Extra: mcp
20
+ Requires-Dist: mcp>=1.2; extra == 'mcp'
21
+ Description-Content-Type: text/markdown
22
+
23
+ # quote-vetter
24
+
25
+ **Vet a quote or poem before you publish it.** One command tells you whether it is public domain where you publish, whether the person really said it, and what credit line to add. Verdict: **safe**, **review** or **avoid**, with every reason.
26
+
27
+ Quote channels trip over two quiet problems: misattributed quotes ("Be the change you wish to see in the world" is not Gandhi's) and copyright on newer authors. This is the check I run by hand on every quote before it goes into a Short, as a CLI with no dependencies, an MCP server and a Claude Code skill. It reads [versereel](https://github.com/ali-saad-khan/versereel) specs directly.
28
+
29
+ ```console
30
+ $ pip install quote-vetter
31
+
32
+ $ quote-vetter "Be the change you wish to see in the world" --author "Mahatma Gandhi" --death 1948
33
+ AVOID Be the change you wish to see in the world — Mahatma Gandhi
34
+ [avoid] misattributed: commonly credited to Mahatma Gandhi. No record of Gandhi saying this; the closest real passage
35
+ is a longer, different sentence from 1913. (Wikiquote: Mahatma Gandhi > Misattributed)
36
+
37
+ $ quote-vetter "Hope is the thing with feathers" --author "Emily Dickinson" \
38
+ --death 1886 --born 1830 --published 1890 --source "Poems (1890)"
39
+ SAFE Hope is the thing with feathers — Emily Dickinson
40
+ [ok] verbatim source stated by you: Poems (1890)
41
+ credit: Emily Dickinson (1830–1886), public domain. Source: Poems (1890)
42
+ ```
43
+
44
+ ## What it checks
45
+ | Check | How |
46
+ |---|---|
47
+ | **Public domain** | Date maths from the author's death year and the work's publication year: life + 70 (EU, UK and many others), life + 50 (older or other terms), and the US rule for works published 95+ years ago. `--profiles` picks which apply to you. |
48
+ | **Known misattributions** | A short, curated, cited list that works offline: never said, misattributed, altered, unverified, with the likely true source. |
49
+ | **Source check** (`--online`) | Looks the quote up on the author's Wikiquote page and sorts it into sourced, unsourced, disputed or misattributed, with fuzzy matching so punctuation and spacing do not matter. Wikidata supplies the death year if you did not give it. |
50
+ | **Credit line** | A ready attribution for the description, only produced when the verdict is not *avoid*. |
51
+
52
+ ### The honesty rule
53
+ `safe` means **public domain in the chosen profiles and the exact wording was checked against a source** (Wikiquote's sourced list, or a source you state with `--source`). Anything not verified is `review`. Known misattributions and still-protected works are `avoid`. If the network fails, the answer degrades to `review`, never to `safe`.
54
+
55
+ **Not legal advice.** Copyright terms vary by country and by work, and posthumous publication can change the dates. Wikiquote is community edited. The offline list is short on purpose and is not exhaustive. A close match is reported with its similarity so you can compare word for word.
56
+
57
+ ## Use it
58
+ ```bash
59
+ quote-vetter "text" --author "Name" [--death YEAR] [--born YEAR] [--published YEAR] [--source "where you checked it"] [--online]
60
+ quote-vetter --file quotes.json # a list of {quote, author, death_year, published_year, source}
61
+ quote-vetter --file versereel-spec.json # vets a versereel poem spec (author and stanzas)
62
+ quote-vetter ... --json --strict # JSON out; exit 2 on avoid, and 1 on review with --strict
63
+ ```
64
+ Exit codes: `0` ok, `2` at least one *avoid*, `1` at least one *review* when `--strict`.
65
+
66
+ ### Python
67
+ ```python
68
+ from quote_vetter import vet_quote
69
+ v = vet_quote("Hope is the thing with feathers", "Emily Dickinson", death_year=1886, published_year=1890, source="Poems (1890)")
70
+ v.verdict, v.credit
71
+ ```
72
+
73
+ ## As an MCP server
74
+ ```bash
75
+ pip install "quote-vetter[mcp]"
76
+ ```
77
+ ```json
78
+ { "mcpServers": { "quote-vetter": { "command": "quote-vetter-mcp" } } }
79
+ ```
80
+ Tools: `vet_quote` (optional network), `pd_status` (dates only), `check_known_misattribution` (offline).
81
+
82
+ ## As a Claude Code skill
83
+ Copy `skill/quote-vetter/` to `~/.claude/skills/quote-vetter/`. It makes the assistant vet every quote before rendering or posting, record the verdict and use the credit line.
84
+
85
+ ## Known limits
86
+ - The Wikiquote lookup follows Wikiquote's documented section layout (Quotes, Disputed, Misattributed) and is tested against fixtures written in that layout. It has not yet been verified against live pages in the development environment, so treat `--online` as beta and report any page it misreads.
87
+ - The US rule uses the publication date only; renewal and notice rules for works from 1931 to 1977 are not modelled.
88
+ - Author matching on Wikidata picks the first person found; the output names who it found so you can confirm.
89
+
90
+ ## Develop
91
+ ```bash
92
+ git clone https://github.com/ali-saad-khan/quote-vetter && cd quote-vetter
93
+ uv venv && uv pip install -e ".[dev,mcp]" && pytest
94
+ ```
95
+
96
+ ## Author
97
+ Built by Saad Ali Khan, a full stack and AI engineer. Portfolio: [saadconsulting.tech](https://saadconsulting.tech). Available for freelance work on AI tooling, MCP servers and automation.
98
+
99
+ ## Licence
100
+ MIT
@@ -0,0 +1,78 @@
1
+ # quote-vetter
2
+
3
+ **Vet a quote or poem before you publish it.** One command tells you whether it is public domain where you publish, whether the person really said it, and what credit line to add. Verdict: **safe**, **review** or **avoid**, with every reason.
4
+
5
+ Quote channels trip over two quiet problems: misattributed quotes ("Be the change you wish to see in the world" is not Gandhi's) and copyright on newer authors. This is the check I run by hand on every quote before it goes into a Short, as a CLI with no dependencies, an MCP server and a Claude Code skill. It reads [versereel](https://github.com/ali-saad-khan/versereel) specs directly.
6
+
7
+ ```console
8
+ $ pip install quote-vetter
9
+
10
+ $ quote-vetter "Be the change you wish to see in the world" --author "Mahatma Gandhi" --death 1948
11
+ AVOID Be the change you wish to see in the world — Mahatma Gandhi
12
+ [avoid] misattributed: commonly credited to Mahatma Gandhi. No record of Gandhi saying this; the closest real passage
13
+ is a longer, different sentence from 1913. (Wikiquote: Mahatma Gandhi > Misattributed)
14
+
15
+ $ quote-vetter "Hope is the thing with feathers" --author "Emily Dickinson" \
16
+ --death 1886 --born 1830 --published 1890 --source "Poems (1890)"
17
+ SAFE Hope is the thing with feathers — Emily Dickinson
18
+ [ok] verbatim source stated by you: Poems (1890)
19
+ credit: Emily Dickinson (1830–1886), public domain. Source: Poems (1890)
20
+ ```
21
+
22
+ ## What it checks
23
+ | Check | How |
24
+ |---|---|
25
+ | **Public domain** | Date maths from the author's death year and the work's publication year: life + 70 (EU, UK and many others), life + 50 (older or other terms), and the US rule for works published 95+ years ago. `--profiles` picks which apply to you. |
26
+ | **Known misattributions** | A short, curated, cited list that works offline: never said, misattributed, altered, unverified, with the likely true source. |
27
+ | **Source check** (`--online`) | Looks the quote up on the author's Wikiquote page and sorts it into sourced, unsourced, disputed or misattributed, with fuzzy matching so punctuation and spacing do not matter. Wikidata supplies the death year if you did not give it. |
28
+ | **Credit line** | A ready attribution for the description, only produced when the verdict is not *avoid*. |
29
+
30
+ ### The honesty rule
31
+ `safe` means **public domain in the chosen profiles and the exact wording was checked against a source** (Wikiquote's sourced list, or a source you state with `--source`). Anything not verified is `review`. Known misattributions and still-protected works are `avoid`. If the network fails, the answer degrades to `review`, never to `safe`.
32
+
33
+ **Not legal advice.** Copyright terms vary by country and by work, and posthumous publication can change the dates. Wikiquote is community edited. The offline list is short on purpose and is not exhaustive. A close match is reported with its similarity so you can compare word for word.
34
+
35
+ ## Use it
36
+ ```bash
37
+ quote-vetter "text" --author "Name" [--death YEAR] [--born YEAR] [--published YEAR] [--source "where you checked it"] [--online]
38
+ quote-vetter --file quotes.json # a list of {quote, author, death_year, published_year, source}
39
+ quote-vetter --file versereel-spec.json # vets a versereel poem spec (author and stanzas)
40
+ quote-vetter ... --json --strict # JSON out; exit 2 on avoid, and 1 on review with --strict
41
+ ```
42
+ Exit codes: `0` ok, `2` at least one *avoid*, `1` at least one *review* when `--strict`.
43
+
44
+ ### Python
45
+ ```python
46
+ from quote_vetter import vet_quote
47
+ v = vet_quote("Hope is the thing with feathers", "Emily Dickinson", death_year=1886, published_year=1890, source="Poems (1890)")
48
+ v.verdict, v.credit
49
+ ```
50
+
51
+ ## As an MCP server
52
+ ```bash
53
+ pip install "quote-vetter[mcp]"
54
+ ```
55
+ ```json
56
+ { "mcpServers": { "quote-vetter": { "command": "quote-vetter-mcp" } } }
57
+ ```
58
+ Tools: `vet_quote` (optional network), `pd_status` (dates only), `check_known_misattribution` (offline).
59
+
60
+ ## As a Claude Code skill
61
+ Copy `skill/quote-vetter/` to `~/.claude/skills/quote-vetter/`. It makes the assistant vet every quote before rendering or posting, record the verdict and use the credit line.
62
+
63
+ ## Known limits
64
+ - The Wikiquote lookup follows Wikiquote's documented section layout (Quotes, Disputed, Misattributed) and is tested against fixtures written in that layout. It has not yet been verified against live pages in the development environment, so treat `--online` as beta and report any page it misreads.
65
+ - The US rule uses the publication date only; renewal and notice rules for works from 1931 to 1977 are not modelled.
66
+ - Author matching on Wikidata picks the first person found; the output names who it found so you can confirm.
67
+
68
+ ## Develop
69
+ ```bash
70
+ git clone https://github.com/ali-saad-khan/quote-vetter && cd quote-vetter
71
+ uv venv && uv pip install -e ".[dev,mcp]" && pytest
72
+ ```
73
+
74
+ ## Author
75
+ Built by Saad Ali Khan, a full stack and AI engineer. Portfolio: [saadconsulting.tech](https://saadconsulting.tech). Available for freelance work on AI tooling, MCP servers and automation.
76
+
77
+ ## Licence
78
+ MIT
@@ -0,0 +1,24 @@
1
+ # quote-vetter: plan
2
+
3
+ **Goal:** before you publish a quote or poem, find out in one command whether it is safe: is it public domain where you publish, did that person really say it, and what credit line should you add. Free MIT first; pricing only on demand (see the channel repo's `docs/tools-roadmap.md`, item 2).
4
+
5
+ **Why it is needed:** quote channels get hit by two quiet problems: misattributed quotes ("Be the change..." is not Gandhi's) and copyright on newer authors. I vetted 30 quotes for the art-journal Shorts by hand and skipped several popular misattributions. This automates that, and plugs into versereel.
6
+
7
+ **Honesty rule:** a tool about truth must not overclaim. `safe` is only returned when the exact text is confirmed against a cited source (Wikiquote's sourced list, or a source the user states); anything unverified is `review`; known misattributions and still-protected works are `avoid`. It is not legal advice, and says so.
8
+
9
+ ## What it does
10
+ - **Public-domain check** for the author's death year and/or publication year: life+70 (EU/UK style), life+50 (older/other terms, check local law) and the US publication-date rule (works published 95+ years ago). Pure date maths, `--as-of` year for tests.
11
+ - **Known misattributions**: a small curated, cited list that works offline (never said, misattributed, altered, unverified), with the likely true source.
12
+ - **Online source check (opt-in):** Wikiquote's page for the author, sorted into Quotes (with citations), Disputed and Misattributed; fuzzy matching so punctuation and spacing do not matter. Wikidata supplies the author's death year when not given.
13
+ - **Verdict** `safe` / `review` / `avoid` with every reason, plus a ready credit line.
14
+ - **Interfaces:** dependency-free CLI (single quote, batch JSON, versereel specs), MCP server (`vet_quote`, `pd_status`, `check_known_misattribution`) and a Claude skill.
15
+
16
+ ## Phases (one at a time, each shippable)
17
+ 1. **Core:** text normalising, public-domain maths, known list, verdict logic, CLI, tests.
18
+ 2. **Online:** Wikiquote and Wikidata clients with an injectable fetcher, tests with canned responses (no network in tests).
19
+ 3. **MCP server + skill:** annotated, parameter-documented, checked with mcp-ship-check.
20
+ 4. **Ship:** GitHub, CI, PyPI, Glama claim and release, case study, drafts.
21
+ 5. **Advertise:** post drafts for owner approval, directories after Glama scores.
22
+
23
+ ## Limits (stated in the README)
24
+ Copyright terms vary by country and by work; this is a screen, not legal advice. Wikiquote is community-edited. The offline list is short and curated, not exhaustive. Matching is fuzzy, so a close paraphrase is reported as a match with its similarity.
@@ -0,0 +1,39 @@
1
+ [project]
2
+ name = "quote-vetter"
3
+ version = "0.1.0"
4
+ description = "Vet a quote or poem before you publish it: public-domain check, known misattributions, Wikiquote source check and a credit line. CLI, MCP server and Claude Code skill."
5
+ readme = "README.md"
6
+ license = { text = "MIT" }
7
+ requires-python = ">=3.10"
8
+ dependencies = []
9
+ keywords = ["quotes", "misattribution", "public-domain", "copyright", "wikiquote", "mcp", "claude-code", "shorts", "poetry"]
10
+ classifiers = [
11
+ "Development Status :: 4 - Beta",
12
+ "Intended Audience :: End Users/Desktop",
13
+ "License :: OSI Approved :: MIT License",
14
+ "Programming Language :: Python :: 3",
15
+ "Topic :: Text Processing",
16
+ ]
17
+
18
+ [project.urls]
19
+ Homepage = "https://github.com/ali-saad-khan/quote-vetter"
20
+ Source = "https://github.com/ali-saad-khan/quote-vetter"
21
+ Issues = "https://github.com/ali-saad-khan/quote-vetter/issues"
22
+
23
+ [project.optional-dependencies]
24
+ mcp = ["mcp>=1.2"]
25
+ dev = ["pytest>=8"]
26
+
27
+ [project.scripts]
28
+ quote-vetter = "quote_vetter.cli:main"
29
+ quote-vetter-mcp = "quote_vetter.mcp_server:main"
30
+
31
+ [build-system]
32
+ requires = ["hatchling"]
33
+ build-backend = "hatchling.build"
34
+
35
+ [tool.hatch.build.targets.wheel]
36
+ packages = ["src/quote_vetter"]
37
+
38
+ [tool.pytest.ini_options]
39
+ testpaths = ["tests"]
@@ -0,0 +1,34 @@
1
+ ---
2
+ name: quote-vetter
3
+ description: Vet a quote, poem line or caption before publishing it: is it public domain where it will be posted, did the credited person really say it, and what credit line to add. Runs the quote-vetter CLI or MCP tools and reports safe, review or avoid with reasons. Use for "is this quote real", "is this misattributed", "can I use this poem on YouTube", "is it public domain", "credit line for this quote", and before rendering quote or poetry videos.
4
+ ---
5
+
6
+ # quote-vetter
7
+
8
+ Never publish a quote you have not vetted. Result is **safe**, **review** or **avoid**. This is a screen, not legal advice.
9
+
10
+ ## 0. Install
11
+ ```bash
12
+ pip install "quote-vetter[mcp]" # CLI plus the optional MCP server (quote-vetter-mcp)
13
+ ```
14
+
15
+ ## 1. Gather facts
16
+ For each quote you need: the exact text, who it is credited to, the author's death year and, if known, the year the work was first published. Ask the user for the source they copied it from. If you do not have the dates, use `--online` (Wikidata, Wikiquote) or the MCP tool with `online=true` and tell the user which person it matched.
17
+
18
+ ## 2. Vet
19
+ ```bash
20
+ quote-vetter "exact text" --author "Name" --death 1886 --published 1890 --source "Poems (1890)"
21
+ quote-vetter --file quotes.json --json # many at once; a versereel spec works too
22
+ ```
23
+ MCP: `vet_quote`, `pd_status`, `check_known_misattribution`.
24
+
25
+ ## 3. Act on the verdict
26
+ - **avoid**: do not use it. Known misattribution, or still protected. Offer a verified alternative by the same author, or the real source if the result names one.
27
+ - **review**: say exactly why (dates missing, wording not checked, disputed, close but not identical match). Fix by finding the primary source, stating it with `--source`, and running again.
28
+ - **safe**: public domain in the chosen profiles and the wording was checked against a source. Use the credit line in the video description or end card.
29
+
30
+ ## Rules
31
+ - Never upgrade a `review` to safe on your own; a human or a stated source must verify the wording.
32
+ - Verbatim only. Do not paraphrase a vetted quote or "fix" its wording.
33
+ - Quote the policy of the platform where it will be posted if the user asks; copyright terms differ by country.
34
+ - Record the verdict, source and credit line next to the video's metadata.
@@ -0,0 +1,7 @@
1
+ """quote-vetter: vet a quote or poem before you publish it."""
2
+ from .known import all_known, match_known
3
+ from .pd import pd_status
4
+ from .vet import Verdict, vet_quote
5
+
6
+ __version__ = "0.1.0"
7
+ __all__ = ["vet_quote", "Verdict", "pd_status", "match_known", "all_known", "__version__"]
@@ -0,0 +1,78 @@
1
+ """Command line interface."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import json
6
+ import sys
7
+
8
+ from . import __version__
9
+ from .vet import Verdict, vet_quote
10
+
11
+ ICON = {"safe": "SAFE ", "review": "REVIEW", "avoid": "AVOID "}
12
+ COLOR = {"safe": "32", "review": "33", "avoid": "31"}
13
+
14
+
15
+ def items_from_file(path: str) -> list[dict]:
16
+ """A list of {quote, author, death_year, published_year, source}, or one versereel spec ({title, author, stanzas})."""
17
+ data = json.load(sys.stdin if path == "-" else open(path, encoding="utf-8"))
18
+ if isinstance(data, dict) and "stanzas" in data: # versereel spec
19
+ text = "\n".join(line for st in data["stanzas"] for line in st)
20
+ return [{"quote": text, "author": data.get("author", ""), **{k: data[k] for k in ("death_year", "born_year", "published_year", "source") if k in data}}]
21
+ if isinstance(data, dict):
22
+ data = data.get("quotes", [])
23
+ return list(data)
24
+
25
+
26
+ def render(v: Verdict, color: bool) -> str:
27
+ tag = ICON[v.verdict]
28
+ if color:
29
+ tag = f"\033[{COLOR[v.verdict]}m{tag}\033[0m"
30
+ first = v.quote.splitlines()[0] if v.quote else ""
31
+ head = f"{tag} {first[:70]}{'…' if len(v.quote) > 70 or len(v.quote.splitlines()) > 1 else ''}" + (f" — {v.author}" if v.author else "")
32
+ lines = [head] + [f" {r}" for r in v.reasons]
33
+ if v.credit:
34
+ lines.append(f" credit: {v.credit}")
35
+ return "\n".join(lines)
36
+
37
+
38
+ def main(argv: list[str] | None = None) -> int:
39
+ ap = argparse.ArgumentParser(prog="quote-vetter", description="Vet a quote or poem before you publish it. Not legal advice.")
40
+ ap.add_argument("quote", nargs="?", help="the quote text")
41
+ ap.add_argument("--author", default="")
42
+ ap.add_argument("--death", type=int, dest="death_year", help="author's death year")
43
+ ap.add_argument("--born", type=int, dest="born_year")
44
+ ap.add_argument("--published", type=int, dest="published_year", help="year the work was first published")
45
+ ap.add_argument("--source", default="", help="the source you checked the exact wording against (counts as verified)")
46
+ ap.add_argument("--online", action="store_true", help="check Wikiquote and Wikidata (network)")
47
+ ap.add_argument("--profiles", default="life70,us", help="comma list from: life70, life50, us (default life70,us)")
48
+ ap.add_argument("--as-of", type=int, dest="as_of", help="evaluate as of this year (default: this year)")
49
+ ap.add_argument("--file", help="JSON file (or - for stdin): a list of quotes or a versereel spec")
50
+ ap.add_argument("--json", action="store_true")
51
+ ap.add_argument("--strict", action="store_true", help="exit 1 on review as well as 2 on avoid")
52
+ ap.add_argument("--version", action="version", version=__version__)
53
+ a = ap.parse_args(argv)
54
+ profiles = tuple(p.strip() for p in a.profiles.split(",") if p.strip())
55
+ jobs: list[dict] = []
56
+ if a.file:
57
+ jobs = items_from_file(a.file)
58
+ if a.quote:
59
+ jobs.append({"quote": a.quote, "author": a.author, "death_year": a.death_year, "born_year": a.born_year,
60
+ "published_year": a.published_year, "source": a.source})
61
+ if not jobs:
62
+ ap.error("give a quote or --file")
63
+ verdicts = []
64
+ for j in jobs:
65
+ kw = {k: j.get(k) for k in ("death_year", "born_year", "published_year") if j.get(k) is not None}
66
+ verdicts.append(vet_quote(j["quote"], j.get("author") or a.author, source=j.get("source") or a.source,
67
+ online=a.online, profiles=profiles, as_of=a.as_of, **kw))
68
+ if a.json:
69
+ print(json.dumps([v.as_dict() for v in verdicts], indent=2, ensure_ascii=False))
70
+ else:
71
+ print("\n\n".join(render(v, sys.stdout.isatty()) for v in verdicts))
72
+ print("\nNot legal advice. SAFE means public domain and the wording was checked against a source; REVIEW means a human must check.")
73
+ worst = max((("safe", "review", "avoid").index(v.verdict) for v in verdicts), default=0)
74
+ return 2 if worst == 2 else (1 if worst == 1 and a.strict else 0)
75
+
76
+
77
+ if __name__ == "__main__":
78
+ sys.exit(main())
@@ -0,0 +1,106 @@
1
+ {
2
+ "_note": "Curated, short, not exhaustive. Verify before relying; entries cite where to check, they are not legal or scholarly proof.",
3
+ "items": [
4
+ {
5
+ "fragment": "be the change you wish to see in the world",
6
+ "attributed_to": "Mahatma Gandhi",
7
+ "status": "misattributed",
8
+ "confidence": "high",
9
+ "note": "No record of Gandhi saying this; the closest real passage is a longer, different sentence from 1913.",
10
+ "hint": "Wikiquote: Mahatma Gandhi > Misattributed"
11
+ },
12
+ {
13
+ "fragment": "insanity is doing the same thing over and over again and expecting different results",
14
+ "attributed_to": "Albert Einstein",
15
+ "status": "misattributed",
16
+ "confidence": "high",
17
+ "note": "No evidence Einstein said it; the wording appears in 1980s recovery literature.",
18
+ "hint": "Wikiquote: Albert Einstein > Misattributed"
19
+ },
20
+ {
21
+ "fragment": "well behaved women seldom make history",
22
+ "attributed_to": "Marilyn Monroe",
23
+ "status": "misattributed",
24
+ "confidence": "high",
25
+ "true_source": "Laurel Thatcher Ulrich, 1976 scholarly article",
26
+ "note": "Often credited to Monroe; Ulrich wrote it, and it was not a call to misbehave.",
27
+ "hint": "Wikiquote: Laurel Thatcher Ulrich"
28
+ },
29
+ {
30
+ "fragment": "i disapprove of what you say but i will defend to the death your right to say it",
31
+ "attributed_to": "Voltaire",
32
+ "status": "misattributed",
33
+ "confidence": "high",
34
+ "true_source": "Evelyn Beatrice Hall, The Friends of Voltaire (1906), summarising his attitude",
35
+ "note": "Hall's paraphrase, not a Voltaire quotation.",
36
+ "hint": "Wikiquote: Voltaire > Misattributed"
37
+ },
38
+ {
39
+ "fragment": "let them eat cake",
40
+ "attributed_to": "Marie Antoinette",
41
+ "status": "misattributed",
42
+ "confidence": "high",
43
+ "note": "No evidence she said it; a similar story predates her arrival in France.",
44
+ "hint": "Wikiquote: Marie Antoinette > Misattributed"
45
+ },
46
+ {
47
+ "fragment": "elementary my dear watson",
48
+ "attributed_to": "Sherlock Holmes / Arthur Conan Doyle",
49
+ "status": "never-said",
50
+ "confidence": "high",
51
+ "note": "The exact phrase does not appear in Conan Doyle's stories (it appears in later adaptations).",
52
+ "hint": "Wikiquote: Arthur Conan Doyle"
53
+ },
54
+ {
55
+ "fragment": "the only thing necessary for the triumph of evil is for good men to do nothing",
56
+ "attributed_to": "Edmund Burke",
57
+ "status": "unverified",
58
+ "confidence": "medium",
59
+ "note": "Not found in Burke's writings; close variants appear later. Treat as unverified.",
60
+ "hint": "Wikiquote: Edmund Burke > Misattributed"
61
+ },
62
+ {
63
+ "fragment": "we are what we repeatedly do excellence then is not an act but a habit",
64
+ "attributed_to": "Aristotle",
65
+ "status": "misattributed",
66
+ "confidence": "high",
67
+ "true_source": "Will Durant, The Story of Philosophy (1926), summarising Aristotle",
68
+ "note": "Durant's summary of Aristotle's ideas, not Aristotle's words.",
69
+ "hint": "Wikiquote: Aristotle > Misattributed"
70
+ },
71
+ {
72
+ "fragment": "what lies behind us and what lies before us are tiny matters compared to what lies within us",
73
+ "attributed_to": "Ralph Waldo Emerson",
74
+ "status": "misattributed",
75
+ "confidence": "medium",
76
+ "true_source": "Henry Stanley Haskins, Meditations in Wall Street (1940)",
77
+ "note": "Widely credited to Emerson; researchers trace it to Haskins.",
78
+ "hint": "Wikiquote: Ralph Waldo Emerson > Misattributed"
79
+ },
80
+ {
81
+ "fragment": "go confidently in the direction of your dreams live the life you have imagined",
82
+ "attributed_to": "Henry David Thoreau",
83
+ "status": "altered",
84
+ "confidence": "high",
85
+ "true_source": "Walden (1854): 'If one advances confidently in the direction of his dreams, and endeavors to live the life which he has imagined...'",
86
+ "note": "A reworded version of the Walden sentence, not what Thoreau wrote.",
87
+ "hint": "Wikiquote: Henry David Thoreau"
88
+ },
89
+ {
90
+ "fragment": "adopt the pace of nature her secret is patience",
91
+ "attributed_to": "Ralph Waldo Emerson",
92
+ "status": "unverified",
93
+ "confidence": "medium",
94
+ "note": "Often credited to Emerson; I could not confirm it in his published works. Treat as unverified.",
95
+ "hint": "Wikiquote: Ralph Waldo Emerson"
96
+ },
97
+ {
98
+ "fragment": "if you cant explain it simply you dont understand it well enough",
99
+ "attributed_to": "Albert Einstein",
100
+ "status": "unverified",
101
+ "confidence": "medium",
102
+ "note": "No reliable source; the idea is older and the wording varies. Treat as unverified.",
103
+ "hint": "Wikiquote: Albert Einstein > Misattributed"
104
+ }
105
+ ]
106
+ }
@@ -0,0 +1,45 @@
1
+ """Offline list of well-known misattributed or unverified quotes."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ from dataclasses import dataclass
6
+ from functools import lru_cache
7
+ from pathlib import Path
8
+
9
+ from .textnorm import best_match, normalize, similarity
10
+
11
+ BAD = {"misattributed", "never-said", "altered"}
12
+
13
+
14
+ @dataclass
15
+ class KnownHit:
16
+ fragment: str
17
+ attributed_to: str
18
+ status: str # misattributed | never-said | altered | unverified
19
+ confidence: str
20
+ note: str
21
+ hint: str
22
+ true_source: str = ""
23
+ similarity: float = 1.0
24
+
25
+
26
+ @lru_cache(maxsize=1)
27
+ def _items() -> list[dict]:
28
+ path = Path(__file__).parent / "data" / "misattributions.json"
29
+ return json.loads(path.read_text(encoding="utf-8"))["items"]
30
+
31
+
32
+ def all_known() -> list[dict]:
33
+ return list(_items())
34
+
35
+
36
+ def match_known(quote: str, threshold: float = 0.86) -> list[KnownHit]:
37
+ q = normalize(quote)
38
+ hits = []
39
+ for it in _items():
40
+ frag = normalize(it["fragment"])
41
+ score = best_match(frag, q) if len(q) >= len(frag) else similarity(q, frag)
42
+ if score >= threshold:
43
+ hits.append(KnownHit(it["fragment"], it["attributed_to"], it["status"], it.get("confidence", ""),
44
+ it.get("note", ""), it.get("hint", ""), it.get("true_source", ""), round(score, 2)))
45
+ return hits
@@ -0,0 +1,64 @@
1
+ """MCP server (stdio). `pip install "quote-vetter[mcp]"`, run `quote-vetter-mcp`."""
2
+ # No `from __future__ import annotations` here: pydantic must resolve the Annotated aliases below.
3
+ from typing import Annotated
4
+
5
+ from .known import all_known, match_known
6
+ from .pd import pd_status as _pd_status
7
+ from .vet import vet_quote as _vet
8
+
9
+
10
+ def _hints(read_only: bool, destructive: bool = False, idempotent: bool = True, open_world: bool = False) -> dict:
11
+ """Explicit MCP tool annotations (all four hints)."""
12
+ return {"readOnlyHint": read_only, "destructiveHint": destructive,
13
+ "idempotentHint": idempotent, "openWorldHint": open_world}
14
+
15
+
16
+ def build_server():
17
+ try: # mcp >= 2
18
+ from mcp.server.mcpserver import MCPServer as _Server
19
+ except ImportError: # mcp 1.x
20
+ from mcp.server.fastmcp import FastMCP as _Server
21
+ from pydantic import Field
22
+
23
+ mcp = _Server("quote-vetter")
24
+ Quote = Annotated[str, Field(description="The exact quote or poem text to vet.")]
25
+ Author = Annotated[str, Field(description="Who it is credited to, e.g. 'Emily Dickinson'.")]
26
+ Death = Annotated[int | None, Field(description="Author's death year, if known. Needed for the public-domain check.")]
27
+ Pub = Annotated[int | None, Field(description="Year the work was first published, if known (used by the US rule).")]
28
+
29
+ @mcp.tool(annotations=_hints(read_only=True, open_world=True))
30
+ def vet_quote(
31
+ quote: Quote,
32
+ author: Author = "",
33
+ death_year: Death = None,
34
+ published_year: Pub = None,
35
+ source: Annotated[str, Field(description="Source you checked the exact wording against; counts as verified.")] = "",
36
+ online: Annotated[bool, Field(description="Also check Wikiquote and Wikidata over the network.")] = False,
37
+ ) -> dict:
38
+ """Vet a quote or poem before publishing: public-domain status, known misattributions, optional Wikiquote check and a credit line.
39
+ Verdict is safe, review or avoid with reasons. A screen, not legal advice."""
40
+ return _vet(quote, author, death_year=death_year, published_year=published_year, source=source, online=online).as_dict()
41
+
42
+ @mcp.tool(annotations=_hints(read_only=True))
43
+ def pd_status(
44
+ death_year: Death = None,
45
+ published_year: Pub = None,
46
+ as_of_year: Annotated[int | None, Field(description="Evaluate as of this year; default this year.")] = None,
47
+ ) -> dict:
48
+ """Public-domain status by life+70, life+50 and the US publication-date rule, from dates alone. No network."""
49
+ return _pd_status(death_year, published_year, as_of_year)
50
+
51
+ @mcp.tool(annotations=_hints(read_only=True))
52
+ def check_known_misattribution(quote: Quote) -> dict:
53
+ """Check a quote against the built-in list of well-known misattributed, altered or unverified quotes. Offline; the list is short, not exhaustive."""
54
+ return {"matches": [vars(h) for h in match_known(quote)], "list_size": len(all_known())}
55
+
56
+ return mcp
57
+
58
+
59
+ def main() -> None:
60
+ build_server().run()
61
+
62
+
63
+ if __name__ == "__main__":
64
+ main()
@@ -0,0 +1,39 @@
1
+ """Public-domain arithmetic. Pure date maths; not legal advice."""
2
+ from __future__ import annotations
3
+
4
+ from datetime import date
5
+
6
+ PROFILES = {
7
+ "life70": "Life + 70 years (EU, UK and many others)",
8
+ "life50": "Life + 50 years (older or other terms; check your local law)",
9
+ "us": "United States: works published 95+ years ago (published before 1 Jan of the year 95 years back)",
10
+ }
11
+
12
+
13
+ def _life(death_year: int | None, term: int, as_of: int) -> dict:
14
+ if death_year is None:
15
+ return {"status": "unknown", "why": "death year not known"}
16
+ free_from = death_year + term + 1
17
+ if as_of >= free_from:
18
+ return {"status": "public_domain", "why": f"author died {death_year}; free since {free_from}"}
19
+ return {"status": "protected", "why": f"author died {death_year}; protected until the end of {free_from - 1}"}
20
+
21
+
22
+ def _us(pub_year: int | None, death_year: int | None, as_of: int) -> dict:
23
+ cutoff = as_of - 96 # works published in or before this year are free (95-year term)
24
+ if pub_year is not None:
25
+ if pub_year <= cutoff:
26
+ return {"status": "public_domain", "why": f"published {pub_year}; free in the US since {pub_year + 96}"}
27
+ return {"status": "protected", "why": f"published {pub_year}; US term runs until the end of {pub_year + 95}"}
28
+ if death_year is not None and death_year <= cutoff:
29
+ return {"status": "likely_public_domain",
30
+ "why": f"author died {death_year}, before the {cutoff + 1} cutoff, so anything published in their lifetime is free; "
31
+ "work first published after death may differ"}
32
+ return {"status": "unknown", "why": "publication year not given"}
33
+
34
+
35
+ def pd_status(death_year: int | None = None, published_year: int | None = None, as_of: int | None = None) -> dict:
36
+ """Status per profile: public_domain | likely_public_domain | protected | unknown."""
37
+ as_of = as_of or date.today().year
38
+ return {"life70": _life(death_year, 70, as_of), "life50": _life(death_year, 50, as_of),
39
+ "us": _us(published_year, death_year, as_of), "as_of": as_of}
@@ -0,0 +1,154 @@
1
+ """Wikiquote and Wikidata lookups (opt-in network). The fetcher is injectable so tests use canned data."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import re
6
+ import urllib.parse
7
+ import urllib.request
8
+ from dataclasses import dataclass, field
9
+ from typing import Callable
10
+
11
+ from .textnorm import best_match, normalize
12
+
13
+ UA = "quote-vetter/0.1 (+https://github.com/ali-saad-khan/quote-vetter)"
14
+ Fetcher = Callable[[str], dict]
15
+
16
+ CATEGORY = {"quotes": "sourced", "sourced": "sourced", "unsourced": "unsourced", "disputed": "disputed",
17
+ "attributed": "disputed", "misattributed": "misattributed"}
18
+
19
+
20
+ def http_fetch(url: str, timeout: float = 15.0) -> dict:
21
+ req = urllib.request.Request(url, headers={"User-Agent": UA, "Accept": "application/json"})
22
+ with urllib.request.urlopen(req, timeout=timeout) as r: # noqa: S310 - fixed https hosts only
23
+ return json.loads(r.read().decode("utf-8"))
24
+
25
+
26
+ def _clean(s: str) -> str:
27
+ s = re.sub(r"<ref[^>]*>.*?</ref>|<ref[^>]*/>", "", s, flags=re.S)
28
+ for _ in range(4):
29
+ s = re.sub(r"\{\{[^{}]*\}\}", "", s)
30
+ s = re.sub(r"\[\[(?:[^\]|]*\|)?([^\]]*)\]\]", r"\1", s)
31
+ s = re.sub(r"\[https?://\S+\s+([^\]]+)\]", r"\1", s)
32
+ s = re.sub(r"<[^>]+>", "", s)
33
+ s = s.replace("'''", "").replace("''", "")
34
+ return re.sub(r"\s+", " ", s).strip()
35
+
36
+
37
+ @dataclass
38
+ class WQEntry:
39
+ text: str
40
+ category: str # sourced | unsourced | disputed | misattributed
41
+ heading: str = ""
42
+ cite: str = ""
43
+
44
+
45
+ def parse_wikiquote(wikitext: str) -> list[WQEntry]:
46
+ """Split a Wikiquote author page into entries tagged by their top-level section."""
47
+ entries: list[WQEntry] = []
48
+ cat, heading, cur = None, "", None
49
+ for raw in wikitext.splitlines():
50
+ m2 = re.match(r"^==\s*([^=].*?)\s*==\s*$", raw)
51
+ m3 = re.match(r"^===\s*([^=].*?)\s*===\s*$", raw)
52
+ if m2:
53
+ name = _clean(m2.group(1)).lower()
54
+ cat = next((v for k, v in CATEGORY.items() if name == k), None)
55
+ heading, cur = "", None
56
+ continue
57
+ if m3:
58
+ heading, cur = _clean(m3.group(1)), None
59
+ continue
60
+ if cat is None:
61
+ continue
62
+ if re.match(r"^\*[^*]", raw):
63
+ cur = WQEntry(_clean(raw[1:]), cat, heading)
64
+ if cur.text:
65
+ entries.append(cur)
66
+ elif re.match(r"^\*\*[^*]", raw) and cur is not None:
67
+ c = _clean(raw[2:])
68
+ if c:
69
+ cur.cite = (cur.cite + " " + c).strip()
70
+ return entries
71
+
72
+
73
+ @dataclass
74
+ class WQResult:
75
+ found: bool
76
+ page: str = ""
77
+ category: str = "" # sourced | unsourced | disputed | misattributed | "" when not found
78
+ similarity: float = 0.0
79
+ cite: str = ""
80
+ heading: str = ""
81
+ matched_text: str = ""
82
+ error: str = ""
83
+
84
+
85
+ def _wq_page(author: str, fetch: Fetcher) -> tuple[str, str]:
86
+ base = "https://en.wikiquote.org/w/api.php?"
87
+ def parse(title: str) -> dict:
88
+ return fetch(base + urllib.parse.urlencode({"action": "parse", "page": title, "prop": "wikitext", "redirects": 1, "format": "json"}))
89
+ data = parse(author.replace(" ", "_"))
90
+ if "error" in data:
91
+ s = fetch(base + urllib.parse.urlencode({"action": "opensearch", "search": author, "limit": 1, "format": "json"}))
92
+ titles = s[1] if isinstance(s, list) and len(s) > 1 else []
93
+ if not titles:
94
+ return "", ""
95
+ data = parse(titles[0].replace(" ", "_"))
96
+ if "error" in data:
97
+ return "", ""
98
+ p = data.get("parse", {})
99
+ return p.get("title", author), p.get("wikitext", {}).get("*", "")
100
+
101
+
102
+ def wikiquote_check(quote: str, author: str, fetch: Fetcher = http_fetch, threshold: float = 0.88) -> WQResult:
103
+ try:
104
+ title, text = _wq_page(author, fetch)
105
+ except Exception as e: # network or API failure must not crash a vetting run
106
+ return WQResult(False, error=f"{type(e).__name__}: {e}")
107
+ if not text:
108
+ return WQResult(False, error=f"no Wikiquote page found for {author!r}")
109
+ q = normalize(quote)
110
+ best, best_e = 0.0, None
111
+ for e in parse_wikiquote(text):
112
+ s = best_match(q, normalize(e.text))
113
+ if s > best or (s == best and best_e is not None and e.category in ("misattributed", "disputed")):
114
+ best, best_e = s, e
115
+ if best_e is None or best < threshold:
116
+ return WQResult(False, page=title, similarity=round(best, 2))
117
+ return WQResult(True, title, best_e.category, round(best, 2), best_e.cite, best_e.heading, best_e.text[:160])
118
+
119
+
120
+ @dataclass
121
+ class AuthorInfo:
122
+ name: str = ""
123
+ description: str = ""
124
+ born: int | None = None
125
+ died: int | None = None
126
+ error: str = ""
127
+
128
+
129
+ def _year(claims: dict, prop: str) -> int | None:
130
+ try:
131
+ t = claims[prop][0]["mainsnak"]["datavalue"]["value"]["time"] # "+1886-05-15T00:00:00Z"
132
+ return int(re.match(r"[+-]?(\d+)", t).group(1))
133
+ except (KeyError, IndexError, AttributeError, TypeError, ValueError):
134
+ return None
135
+
136
+
137
+ def wikidata_author(name: str, fetch: Fetcher = http_fetch) -> AuthorInfo:
138
+ base = "https://www.wikidata.org/w/api.php?"
139
+ try:
140
+ s = fetch(base + urllib.parse.urlencode({"action": "wbsearchentities", "search": name, "language": "en", "limit": 5, "format": "json"}))
141
+ ids = [h["id"] for h in s.get("search", [])]
142
+ if not ids:
143
+ return AuthorInfo(error=f"no Wikidata entry for {name!r}")
144
+ ent = fetch(base + urllib.parse.urlencode({"action": "wbgetentities", "ids": "|".join(ids), "props": "claims|labels|descriptions", "languages": "en", "format": "json"}))
145
+ for i in ids:
146
+ e = ent.get("entities", {}).get(i, {})
147
+ claims = e.get("claims", {})
148
+ is_human = any(c.get("mainsnak", {}).get("datavalue", {}).get("value", {}).get("id") == "Q5" for c in claims.get("P31", []))
149
+ if is_human:
150
+ return AuthorInfo(e.get("labels", {}).get("en", {}).get("value", name), e.get("descriptions", {}).get("en", {}).get("value", ""),
151
+ _year(claims, "P569"), _year(claims, "P570"))
152
+ return AuthorInfo(error=f"no person found for {name!r} on Wikidata")
153
+ except Exception as e:
154
+ return AuthorInfo(error=f"{type(e).__name__}: {e}")
@@ -0,0 +1,52 @@
1
+ """Text normalising and fuzzy matching, standard library only."""
2
+ from __future__ import annotations
3
+
4
+ import difflib
5
+ import re
6
+ import unicodedata
7
+
8
+ _PUNCT = re.compile(r"[^\w\s]", re.UNICODE)
9
+ _WS = re.compile(r"\s+")
10
+
11
+
12
+ def normalize(text: str) -> str:
13
+ """Lowercase, strip accents, punctuation and extra whitespace so 'Hope' and 'hope,' match."""
14
+ t = unicodedata.normalize("NFKD", text)
15
+ t = "".join(c for c in t if not unicodedata.combining(c))
16
+ t = t.replace("’", "'").replace("‘", "'").replace("’", "'")
17
+ t = t.replace("'", "") # don't -> dont, so curly and straight quotes agree
18
+ t = _PUNCT.sub(" ", t.lower())
19
+ return _WS.sub(" ", t).strip()
20
+
21
+
22
+ def similarity(a: str, b: str) -> float:
23
+ """0..1 similarity of two normalized strings."""
24
+ if not a or not b:
25
+ return 0.0
26
+ if a == b:
27
+ return 1.0
28
+ sm = difflib.SequenceMatcher(None, a, b, autojunk=False)
29
+ if sm.real_quick_ratio() < 0.5 or sm.quick_ratio() < 0.5:
30
+ return 0.0
31
+ return sm.ratio()
32
+
33
+
34
+ def best_match(needle: str, haystack: str) -> float:
35
+ """How well `needle` (normalized) is contained in `haystack` (normalized): 1.0 if a substring, else the best
36
+ fuzzy ratio against same-length windows (word aligned)."""
37
+ if not needle or not haystack:
38
+ return 0.0
39
+ if needle in haystack:
40
+ return 1.0
41
+ if needle.startswith(haystack) or haystack in needle:
42
+ # the listed text is a fragment of the quote we were given: partial, scale by coverage
43
+ return len(haystack) / len(needle) if len(haystack) / len(needle) >= 0.6 else 0.0
44
+ nw, hw = needle.split(), haystack.split()
45
+ if len(hw) < len(nw):
46
+ return similarity(needle, haystack)
47
+ best = 0.0
48
+ for i in range(0, len(hw) - len(nw) + 1):
49
+ best = max(best, similarity(needle, " ".join(hw[i:i + len(nw)])))
50
+ if best >= 0.99:
51
+ break
52
+ return best
@@ -0,0 +1,118 @@
1
+ """Combine the checks into one verdict."""
2
+ from __future__ import annotations
3
+
4
+ from dataclasses import asdict, dataclass, field
5
+
6
+ from . import pd as pdmod
7
+ from .known import BAD, match_known
8
+ from .sources import Fetcher, http_fetch, wikidata_author, wikiquote_check
9
+ from .textnorm import normalize
10
+
11
+ ORDER = {"safe": 0, "review": 1, "avoid": 2}
12
+ OK_PD = ("public_domain", "likely_public_domain")
13
+
14
+
15
+ @dataclass
16
+ class Verdict:
17
+ verdict: str = "safe" # safe | review | avoid
18
+ quote: str = ""
19
+ author: str = ""
20
+ reasons: list[str] = field(default_factory=list)
21
+ pd: dict = field(default_factory=dict)
22
+ known: list[dict] = field(default_factory=list)
23
+ source_check: dict = field(default_factory=dict)
24
+ author_info: dict = field(default_factory=dict)
25
+ credit: str = ""
26
+ disclaimer: str = "A screen, not legal advice. Copyright terms vary by country and work."
27
+
28
+ def raise_to(self, level: str, reason: str) -> None:
29
+ if ORDER[level] > ORDER[self.verdict]:
30
+ self.verdict = level
31
+ self.reasons.append(f"[{level}] {reason}")
32
+
33
+ def as_dict(self) -> dict:
34
+ return asdict(self)
35
+
36
+
37
+ def vet_quote(quote: str, author: str = "", *, death_year: int | None = None, born_year: int | None = None,
38
+ published_year: int | None = None, source: str = "", online: bool = False,
39
+ profiles: tuple[str, ...] = ("life70", "us"), as_of: int | None = None, fetch: Fetcher = http_fetch) -> Verdict:
40
+ v = Verdict(quote=quote.strip(), author=author.strip())
41
+ if not normalize(quote):
42
+ v.raise_to("avoid", "empty quote")
43
+ return v
44
+ verified = bool(source.strip())
45
+
46
+ # 1. known misattributions (offline)
47
+ for h in match_known(quote):
48
+ v.known.append(vars(h))
49
+ same_author = bool(author) and normalize(h.attributed_to.split("/")[0]) in normalize(author) or (bool(author) and normalize(author) in normalize(h.attributed_to))
50
+ who = f"commonly credited to {h.attributed_to}"
51
+ extra = f"; likely source: {h.true_source}" if h.true_source else ""
52
+ if h.status in BAD:
53
+ if same_author or not author:
54
+ v.raise_to("avoid", f"{h.status}: {who}{extra}. {h.note} ({h.hint})")
55
+ else:
56
+ v.raise_to("review", f"matches a known {h.status} quote ({who}{extra}); check that {author!r} is the real source. {h.note}")
57
+ else:
58
+ v.raise_to("review", f"unverified attribution: {who}. {h.note} ({h.hint})")
59
+
60
+ # 2. author facts (online only if the caller did not give them)
61
+ if online and author and death_year is None:
62
+ info = wikidata_author(author, fetch)
63
+ v.author_info = vars(info)
64
+ if info.died is not None:
65
+ death_year = info.died
66
+ born_year = born_year or info.born
67
+ v.reasons.append(f"[info] death year {info.died} from Wikidata ({info.description or info.name}); confirm it is the right person")
68
+ elif info.error:
69
+ v.reasons.append(f"[info] Wikidata: {info.error}")
70
+
71
+ # 3. public domain
72
+ v.pd = pdmod.pd_status(death_year, published_year, as_of)
73
+ for p in profiles:
74
+ st = v.pd[p]
75
+ if st["status"] == "protected":
76
+ v.raise_to("avoid", f"{p}: still protected ({st['why']})")
77
+ elif st["status"] == "unknown":
78
+ v.raise_to("review", f"{p}: cannot tell ({st['why']}); give death_year / published_year or use online")
79
+ elif st["status"] == "likely_public_domain":
80
+ v.reasons.append(f"[info] {p}: likely public domain ({st['why']})")
81
+
82
+ # 4. is this really what they wrote?
83
+ if online and author:
84
+ r = wikiquote_check(quote, author, fetch)
85
+ v.source_check = vars(r)
86
+ if r.error and not r.found:
87
+ v.raise_to("review", f"Wikiquote check failed: {r.error}")
88
+ elif not r.found:
89
+ v.raise_to("review", f"not found on Wikiquote's page for {r.page or author} (best similarity {r.similarity}); verbatim text unverified")
90
+ elif r.category == "misattributed":
91
+ v.raise_to("avoid", f"Wikiquote lists it as misattributed to {r.page} (similarity {r.similarity})")
92
+ elif r.category == "disputed":
93
+ v.raise_to("review", f"Wikiquote lists it as disputed or attributed only (similarity {r.similarity})")
94
+ elif r.category == "unsourced":
95
+ v.raise_to("review", f"on Wikiquote but without a source (similarity {r.similarity})")
96
+ elif not r.cite:
97
+ v.raise_to("review", f"listed on Wikiquote but without a citation line (similarity {r.similarity}); find the original source")
98
+ else:
99
+ verified = True
100
+ v.reasons.append(f"[ok] found on Wikiquote under sourced quotes (similarity {r.similarity}); cite: {r.cite or 'none shown'}")
101
+ if r.similarity < 0.97:
102
+ v.raise_to("review", f"wording differs slightly from Wikiquote (similarity {r.similarity}); compare word for word")
103
+ elif source.strip():
104
+ v.reasons.append(f"[ok] verbatim source stated by you: {source.strip()}")
105
+ if not verified:
106
+ v.raise_to("review", "verbatim text not verified: use --online or state your source (--source)")
107
+
108
+ # 5. credit line
109
+ if author and v.verdict != "avoid":
110
+ span = f" ({born_year}–{death_year})" if born_year and death_year else (f" (d. {death_year})" if death_year else "")
111
+ pd_ok = all(v.pd[p]["status"] in OK_PD for p in profiles)
112
+ bits = [f"{author}{span}" + (", public domain" if pd_ok else "")]
113
+ if source.strip():
114
+ bits.append(f"Source: {source.strip()}")
115
+ elif v.source_check.get("found") and v.source_check.get("page"):
116
+ bits.append(f"Source: Wikiquote ({v.source_check['page']})")
117
+ v.credit = ". ".join(bits)
118
+ return v
@@ -0,0 +1,224 @@
1
+ import json
2
+ from pathlib import Path
3
+
4
+ import pytest
5
+
6
+ from quote_vetter import match_known, pd_status, vet_quote
7
+ from quote_vetter.cli import items_from_file, main
8
+ from quote_vetter.sources import parse_wikiquote, wikidata_author, wikiquote_check
9
+ from quote_vetter.textnorm import best_match, normalize
10
+
11
+ # --- text ---------------------------------------------------------------------
12
+
13
+ def test_normalize_ignores_case_punctuation_accents_and_curly_quotes():
14
+ assert normalize("Don’t stop—believing!") == normalize("dont stop believing")
15
+ assert normalize("Café") == "cafe"
16
+
17
+
18
+ def test_best_match_substring_and_fuzzy():
19
+ assert best_match("hope is the thing", "emily said hope is the thing with feathers") == 1.0
20
+ assert best_match("hope is the thing with feathers", "hope is a thing with feathers") > 0.85
21
+ assert best_match("completely different words here", "hope is the thing with feathers") < 0.5
22
+
23
+
24
+ # --- public domain ---------------------------------------------------------------
25
+
26
+ def test_life_terms_boundaries():
27
+ # died 1955: life+70 frees it on 1 Jan 2026 ( 1955 + 71 )
28
+ assert pd_status(1955, None, 2026)["life70"]["status"] == "public_domain"
29
+ assert pd_status(1956, None, 2026)["life70"]["status"] == "protected"
30
+ assert pd_status(1975, None, 2026)["life50"]["status"] == "public_domain"
31
+ assert pd_status(None, None, 2026)["life70"]["status"] == "unknown"
32
+
33
+
34
+ def test_us_rule():
35
+ assert pd_status(None, 1930, 2026)["us"]["status"] == "public_domain" # published 1930 is free from 1 Jan 2026
36
+ assert pd_status(None, 1931, 2026)["us"]["status"] == "protected"
37
+ assert pd_status(1880, None, 2026)["us"]["status"] == "likely_public_domain"
38
+ assert pd_status(1960, None, 2026)["us"]["status"] == "unknown"
39
+
40
+
41
+ # --- known list ---------------------------------------------------------------------
42
+
43
+ def test_known_misattribution_matches_despite_punctuation():
44
+ hits = match_known("“Be the change you wish to see in the world.”")
45
+ assert hits and hits[0].attributed_to == "Mahatma Gandhi" and hits[0].status == "misattributed"
46
+ assert match_known("Hope is the thing with feathers") == []
47
+
48
+
49
+ # --- verdicts ---------------------------------------------------------------------------
50
+
51
+ def test_safe_needs_pd_and_a_verified_source():
52
+ v = vet_quote("Hope is the thing with feathers", "Emily Dickinson", death_year=1886, born_year=1830, published_year=1890,
53
+ source="Poems (1890)", as_of=2026)
54
+ assert v.verdict == "safe"
55
+ assert v.credit == "Emily Dickinson (1830–1886), public domain. Source: Poems (1890)"
56
+
57
+
58
+ def test_unverified_text_is_review_not_safe():
59
+ v = vet_quote("Hope is the thing with feathers", "Emily Dickinson", death_year=1886, published_year=1890, as_of=2026)
60
+ assert v.verdict == "review" and any("not verified" in r for r in v.reasons)
61
+
62
+
63
+ def test_known_misattribution_is_avoid_and_has_no_credit():
64
+ v = vet_quote("Be the change you wish to see in the world", "Mahatma Gandhi", death_year=1948, published_year=1920, source="x", as_of=2026)
65
+ assert v.verdict == "avoid" and v.credit == ""
66
+
67
+
68
+ def test_true_source_is_not_flagged_as_misattribution():
69
+ v = vet_quote("Well behaved women seldom make history", "Laurel Thatcher Ulrich", death_year=None, published_year=1976, source="Ulrich 1976", as_of=2026)
70
+ assert not any(r.startswith("[avoid] misattributed") for r in v.reasons)
71
+ assert any("check that" in r for r in v.reasons)
72
+
73
+
74
+ def test_protected_work_is_avoid():
75
+ v = vet_quote("Some modern line", "Modern Author", death_year=2015, published_year=2001, source="book", as_of=2026)
76
+ assert v.verdict == "avoid" and any("protected" in r for r in v.reasons)
77
+
78
+
79
+ def test_unknown_dates_are_review():
80
+ v = vet_quote("A line", "Somebody", source="a book", as_of=2026)
81
+ assert v.verdict == "review"
82
+
83
+
84
+ def test_empty_quote_is_avoid():
85
+ assert vet_quote(" ", "x").verdict == "avoid"
86
+
87
+
88
+ # --- wikiquote parsing (fixture written in Wikiquote's section layout; not copied from any page) ---------
89
+
90
+ WIKITEXT = """\
91
+ {{Wikipedia}}
92
+ == Quotes ==
93
+ === Poems (1890) ===
94
+ * Hope is the thing with feathers<br />That perches in the soul
95
+ ** ''Poems'', Series 1 (1890), "Hope" <ref>note</ref>
96
+ * A line without a citation
97
+ === Letters ===
98
+ * Tell all the truth but tell it slant
99
+ ** Letter to a friend (1862)
100
+ == Disputed ==
101
+ * A disputed saying about hope
102
+ ** Often attributed; no source
103
+ == Misattributed ==
104
+ * Be kind to everyone you meet
105
+ ** Not hers; widely repeated
106
+ == Quotes about Author ==
107
+ * A fine poet - Someone
108
+ """
109
+
110
+
111
+ def test_parse_wikiquote_sections_and_cites():
112
+ es = parse_wikiquote(WIKITEXT)
113
+
114
+ def find(prefix):
115
+ return next(e for e in es if e.text.startswith(prefix))
116
+ h = find("Hope is the thing")
117
+ assert (h.category, h.heading, bool(h.cite)) == ("sourced", "Poems (1890)", True)
118
+ assert find("A line without").category == "sourced" and not find("A line without").cite
119
+ assert find("A disputed").category == "disputed"
120
+ assert find("Be kind").category == "misattributed"
121
+ assert not any("fine poet" in e.text for e in es) # 'Quotes about' is ignored
122
+ assert "<ref>" not in h.text and "''" not in h.cite and "<br" not in h.text
123
+
124
+
125
+ def fake_fetch(wikitext=WIKITEXT, died="+1886-05-15T00:00:00Z"):
126
+ def f(url: str):
127
+ if "wikiquote" in url and "action=parse" in url:
128
+ return {"parse": {"title": "Emily Dickinson", "wikitext": {"*": wikitext}}}
129
+ if "wbsearchentities" in url:
130
+ return {"search": [{"id": "Q1"}, {"id": "Q2"}]}
131
+ if "wbgetentities" in url:
132
+ human = {"P31": [{"mainsnak": {"datavalue": {"value": {"id": "Q5"}}}}],
133
+ "P569": [{"mainsnak": {"datavalue": {"value": {"time": "+1830-12-10T00:00:00Z"}}}}],
134
+ "P570": [{"mainsnak": {"datavalue": {"value": {"time": died}}}}]}
135
+ return {"entities": {"Q1": {"claims": {"P31": [{"mainsnak": {"datavalue": {"value": {"id": "Q486972"}}}}]}}, # a place, skipped
136
+ "Q2": {"claims": human, "labels": {"en": {"value": "Emily Dickinson"}}, "descriptions": {"en": {"value": "American poet"}}}}}
137
+ raise AssertionError(url)
138
+ return f
139
+
140
+
141
+ def test_wikiquote_check_sourced_and_fuzzy():
142
+ r = wikiquote_check("Hope is the thing with feathers that perches in the soul", "Emily Dickinson", fake_fetch())
143
+ assert r.found and r.category == "sourced" and r.cite and r.similarity >= 0.95
144
+
145
+
146
+ def test_wikiquote_check_disputed_misattributed_and_missing():
147
+ assert wikiquote_check("A disputed saying about hope", "E D", fake_fetch()).category == "disputed"
148
+ assert wikiquote_check("Be kind to everyone you meet", "E D", fake_fetch()).category == "misattributed"
149
+ assert not wikiquote_check("Totally unrelated sentence about cheese", "E D", fake_fetch()).found
150
+
151
+
152
+ def test_wikidata_skips_non_humans_and_reads_years():
153
+ a = wikidata_author("Emily Dickinson", fake_fetch())
154
+ assert (a.name, a.born, a.died) == ("Emily Dickinson", 1830, 1886)
155
+
156
+
157
+ def test_online_safe_path_uses_wikidata_and_wikiquote():
158
+ v = vet_quote("Hope is the thing with feathers that perches in the soul", "Emily Dickinson", published_year=1890, online=True,
159
+ as_of=2026, fetch=fake_fetch())
160
+ assert v.verdict == "safe" and "Wikiquote" in v.credit and "(1830–1886)" in v.credit
161
+
162
+
163
+ def test_sourced_without_citation_is_review():
164
+ v = vet_quote("A line without a citation", "Emily Dickinson", published_year=1890, online=True, as_of=2026, fetch=fake_fetch())
165
+ assert v.verdict == "review" and any("without a citation" in r for r in v.reasons)
166
+
167
+
168
+ def test_online_misattributed_is_avoid():
169
+ v = vet_quote("Be kind to everyone you meet", "Emily Dickinson", published_year=1890, online=True, as_of=2026, fetch=fake_fetch())
170
+ assert v.verdict == "avoid" and any("misattributed" in r for r in v.reasons)
171
+
172
+
173
+ def test_online_disputed_is_review():
174
+ v = vet_quote("A disputed saying about hope", "Emily Dickinson", published_year=1890, online=True, as_of=2026, fetch=fake_fetch())
175
+ assert v.verdict == "review"
176
+
177
+
178
+ def test_network_failure_degrades_to_review_never_safe():
179
+ def boom(url):
180
+ raise OSError("network down")
181
+ v = vet_quote("Hope is the thing with feathers", "Emily Dickinson", death_year=1886, published_year=1890, online=True, as_of=2026, fetch=boom)
182
+ assert v.verdict == "review" and any("failed" in r for r in v.reasons)
183
+
184
+
185
+ # --- CLI ----------------------------------------------------------------------------------------
186
+
187
+ def test_cli_exit_codes_and_json(capsys):
188
+ assert main(["Be the change you wish to see in the world", "--author", "Mahatma Gandhi", "--death", "1948", "--json"]) == 2
189
+ data = json.loads(capsys.readouterr().out)
190
+ assert data[0]["verdict"] == "avoid"
191
+ assert main(["A line", "--author", "Somebody", "--source", "a book", "--as-of", "2026"]) == 0 # review, not strict
192
+ assert main(["A line", "--author", "Somebody", "--source", "a book", "--as-of", "2026", "--strict"]) == 1
193
+
194
+
195
+ def test_cli_reads_versereel_spec_and_list(tmp_path, capsys):
196
+ spec = tmp_path / "s.json"
197
+ spec.write_text(json.dumps({"title": "Hope", "author": "Emily Dickinson", "death_year": 1886, "published_year": 1890,
198
+ "source": "Poems (1890)", "stanzas": [["Hope is the thing with feathers"], ["That perches in the soul"]]}))
199
+ assert items_from_file(str(spec))[0]["quote"].count("\n") == 1
200
+ assert main(["--file", str(spec), "--json"]) == 0
201
+ assert json.loads(capsys.readouterr().out)[0]["verdict"] == "safe"
202
+ lst = tmp_path / "l.json"
203
+ lst.write_text(json.dumps([{"quote": "Let them eat cake", "author": "Marie Antoinette", "death_year": 1793}]))
204
+ assert main(["--file", str(lst), "--json"]) == 2
205
+
206
+
207
+ # --- MCP server (names the tools on purpose: vet_quote, pd_status, check_known_misattribution) ----------------
208
+
209
+ def test_mcp_tools_registered_and_callable():
210
+ pytest.importorskip("mcp")
211
+ import asyncio
212
+ from quote_vetter.mcp_server import build_server
213
+ srv = build_server()
214
+ lister = getattr(srv, "list_tools", None) or srv._tool_manager.list_tools
215
+ tools = lister()
216
+ tools = asyncio.run(tools) if asyncio.iscoroutine(tools) else tools
217
+ assert {t.name for t in tools} == {"vet_quote", "pd_status", "check_known_misattribution"}
218
+
219
+ def call(name, args):
220
+ r = srv.call_tool(name, args)
221
+ return asyncio.run(r) if asyncio.iscoroutine(r) else r
222
+ assert call("pd_status", {"death_year": 1886}) is not None
223
+ assert call("check_known_misattribution", {"quote": "Let them eat cake"}) is not None
224
+ assert call("vet_quote", {"quote": "Let them eat cake", "author": "Marie Antoinette", "death_year": 1793}) is not None