newsrag 0.2.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,21 @@
1
+ name: Quality checks
2
+ on:
3
+ push:
4
+ pull_request:
5
+ jobs:
6
+ verify:
7
+ runs-on: ubuntu-latest
8
+ strategy:
9
+ matrix:
10
+ python-version: ['3.10', '3.11', '3.12', '3.13']
11
+ steps:
12
+ - uses: actions/checkout@v4
13
+ - uses: actions/setup-python@v5
14
+ with:
15
+ python-version: ${{ matrix.python-version }}
16
+ - run: python -m pip install -U pip ruff mypy pytest build "pypdf>=5,<7"
17
+ - run: python -m pip install -e .
18
+ - run: ruff check src tests examples setup.py
19
+ - run: mypy src/newsrag
20
+ - run: pytest -q
21
+ - run: python -m build
@@ -0,0 +1,42 @@
1
+ name: Publish to PyPI
2
+
3
+ on:
4
+ push:
5
+ tags:
6
+ - 'v*'
7
+
8
+ jobs:
9
+ build:
10
+ runs-on: ubuntu-latest
11
+ permissions:
12
+ contents: read
13
+ steps:
14
+ - uses: actions/checkout@v4
15
+ - uses: actions/setup-python@v5
16
+ with:
17
+ python-version: '3.12'
18
+ - run: python -m pip install -U build twine pytest ruff mypy 'pypdf>=5,<7'
19
+ - run: python -m pip install -e .
20
+ - run: ruff check src tests examples setup.py
21
+ - run: mypy src/newsrag
22
+ - run: pytest -q
23
+ - run: python -m build
24
+ - run: python -m twine check dist/*
25
+ - uses: actions/upload-artifact@v4
26
+ with:
27
+ name: python-package-distributions
28
+ path: dist/
29
+ if-no-files-found: error
30
+
31
+ publish:
32
+ needs: build
33
+ runs-on: ubuntu-latest
34
+ environment: pypi
35
+ permissions:
36
+ id-token: write
37
+ steps:
38
+ - uses: actions/download-artifact@v4
39
+ with:
40
+ name: python-package-distributions
41
+ path: dist/
42
+ - uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,20 @@
1
+ # Changelog
2
+
3
+ ## 0.2.0 - 2026-09-26
4
+
5
+ - Added caller-supplied HTML and optional pypdf text extraction.
6
+ - Added local JSON source snapshots with atomic writes and restricted POSIX permissions.
7
+ - Expanded automated checks and source metadata documentation.
8
+
9
+ ## 0.1.0 - 2026-09-26
10
+
11
+ - Initial provider-neutral in-memory retrieval with Arabic and English lexical matching.
12
+ - Added source metadata, exact offsets, date filters, optional embeddings and generation adapters.
13
+ - Added citation reference validation, abstention on no matches and review warnings.
14
+
15
+ ## Unreleased
16
+
17
+ - Normalize common Arabic letter variants after Unicode NFKC normalization (including Persian keyboard variants).
18
+ - Allow an optional caller-supplied reranker to reorder retrieved evidence without changing or injecting passages; citation IDs are reassigned after reranking.
19
+ - Add tests for Arabic variants, reranking, citation IDs and rejected adapter output.
20
+ - Add a small deterministic retrieval evaluation harness with source-level recall@k, hit rate@k, mean reciprocal rank and missed queries; document its limits.
@@ -0,0 +1,14 @@
1
+ # Contributing
2
+
3
+ Open an issue before proposing a large change. For a small fix, include a test that fails before the fix and passes afterward. Please do not commit private reporting notes, unpublished sources, credentials or API tokens.
4
+
5
+ ```bash
6
+ python -m venv .venv
7
+ . .venv/bin/activate
8
+ python -m pip install -e . pytest ruff mypy 'pypdf>=5,<7'
9
+ ruff check src tests examples setup.py
10
+ mypy src/newsrag
11
+ pytest -q
12
+ ```
13
+
14
+ Keep adapters optional and avoid hidden network calls. API additions should preserve source IDs and exact offsets. Include tests with Arabic and English input, missing dates and malformed provider output where relevant. Document backward-incompatible changes in CHANGELOG.md.
newsrag-0.2.0/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,5 @@
1
+ include README.md LICENSE NOTICE CHANGELOG.md CONTRIBUTING.md SECURITY.md
2
+ recursive-include docs *.md
3
+ recursive-include examples *.py
4
+ recursive-include tests *.py
5
+ recursive-include .github *.yml
newsrag-0.2.0/NOTICE ADDED
@@ -0,0 +1,5 @@
1
+ NewsRAG
2
+ Copyright 2026 Shehata El-sayed
3
+
4
+ This product is licensed under the Apache License, Version 2.0.
5
+ See the LICENSE file for the complete terms.
newsrag-0.2.0/PKG-INFO ADDED
@@ -0,0 +1,100 @@
1
+ Metadata-Version: 2.4
2
+ Name: newsrag
3
+ Version: 0.2.0
4
+ Summary: Auditable, provider-neutral RAG for newsroom research
5
+ Author: Shehata El-sayed
6
+ License: Apache-2.0
7
+ Classifier: Programming Language :: Python :: 3
8
+ Requires-Python: >=3.10
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ License-File: NOTICE
12
+ Provides-Extra: pdf
13
+ Requires-Dist: pypdf<7,>=5; extra == "pdf"
14
+ Dynamic: author
15
+ Dynamic: classifier
16
+ Dynamic: description
17
+ Dynamic: description-content-type
18
+ Dynamic: license
19
+ Dynamic: license-file
20
+ Dynamic: provides-extra
21
+ Dynamic: requires-python
22
+ Dynamic: summary
23
+
24
+ # NewsRAG by Shehata El-sayed
25
+
26
+ A small, auditable Python RAG toolkit for journalistic research. This v0.2 pre-release is a research prototype; check PyPI for publication status. Python 3.10+; standard library core. Licensed under Apache-2.0 (see LICENSE and NOTICE).
27
+
28
+ ## Example
29
+
30
+ ```python
31
+ from datetime import datetime, timezone
32
+ from newsrag import NewsroomRAG, Source
33
+
34
+ rag = NewsroomRAG(recency_half_life_days=30).add(
35
+ Source(id="1", title="Official statement", text="A limited pilot began in September. No public launch was announced.",
36
+ url="https://example.org/statement", published_at=datetime(2026, 9, 10, tzinfo=timezone.utc))
37
+ )
38
+ print(rag.ask("Was there a public launch?").as_dict())
39
+ ```
40
+
41
+ Save a source's actual URL and publication date. The default `ask` retrieves evidence without generating prose. Add provider functions when you want answer generation:
42
+
43
+ ```python
44
+ rag = NewsroomRAG(
45
+ embed=lambda texts: embedding_provider(texts), # list[str] -> list[list[float]]
46
+ generate=lambda prompt: llm_provider(prompt), # str -> str
47
+ ).add(...)
48
+ answer = rag.ask("ما الذي أُعلن؟")
49
+ print(answer.text, answer.evidence, answer.warnings)
50
+ ```
51
+
52
+ Install locally with `python -m pip install .`; run tests with `PYTHONPATH=src python -m unittest discover -s tests -v`, and run `PYTHONPATH=src python examples/quickstart.py` from this directory. No network calls occur unless your adapters make them.
53
+
54
+ ## Newsroom-specific controls
55
+
56
+ - Every source carries an ID, title, original URL, publisher, type, timestamp with timezone, and original text. Search results retain exact offsets and excerpts for audit.
57
+ - Arabic orthographic normalization and English token search work locally. Optional provider embeddings improve semantic search and cross-language matching, but an appropriate multilingual model is required for Arabic-English semantic retrieval.
58
+ - Optional publication date range filters (`before`, `after`) and a modest recency ranking boost. Unknown publication dates are excluded when filtering by date; they remain eligible otherwise. The timestamp means publication time, not event time.
59
+ - Generator prompt asks for bracketed evidence IDs (`[E1]`). IDs are checked against retrieved passages and unknown IDs flagged. This does **not** verify the claims, the source's truth, or whether cited passages support each sentence.
60
+ - No-match answers abstain. Source text is marked untrusted, but prompt injection remains a risk with any model. Do not feed confidential material to a third-party provider without permission. Review original sources, licensing, quotes, dates, and contested claims before publishing.
61
+
62
+ ## Scope and limitations
63
+
64
+ This v0.2 is an in-memory retrieval prototype with local JSON source snapshots, not a production crawler or fact-checker. It handles plain text and synchronous callable adapters; automatic fetching of URLs, OCR for scanned PDFs, database connectors, persistent vector indexes, source deduplication, named provider packages, automated entailment checking, and benchmark-based tuning are future work. Lexical Arabic tokenization is basic, not morphological. No claim that this works with every provider out of the box: providers must offer embeddings with stable vector dimensions and/or text generation and be wrapped in the two simple callables. The toy example.org URLs are not real news sources.
65
+
66
+
67
+ ## Quality checks
68
+
69
+ Run `python -m pip install -e . pytest ruff mypy build "pypdf>=5,<7"`, then `ruff check src tests examples setup.py`, `mypy src/newsrag`, `pytest -q`, and `python -m build`. CI is configured to run these checks on Python 3.10–3.13; this local package was checked on Python 3.10 only. A passing suite reduces risk but cannot guarantee zero bugs or factual accuracy.
70
+
71
+ ## Local ingestion and snapshots
72
+
73
+ ```python
74
+ from newsrag import source_from_html, source_from_pdf, save_sources, load_sources
75
+
76
+ # You fetch the original page yourself. This library does not fetch URLs or bypass site terms.
77
+ source = source_from_html(id="story-1", title="Original article", url="https://example.org/story",
78
+ html="<article><p>An independently confirmed report.</p></article>")
79
+ rag.add(source)
80
+ save_sources(rag, "research.json") # source content, mode 0600; no API keys or model code
81
+ restored = load_sources("research.json")
82
+ # PDF extraction, optional: pip install 'newsrag[pdf]'
83
+ # document = source_from_pdf(id="file-1", title="Report", pdf_bytes=pdf_data)
84
+ ```
85
+
86
+ For web ingestion, the caller is responsible for fetching, verifying the URL, handling redirects, authentication, robots/licensing rules and SSRF protection. Passing HTML does not prove its authorship. HTML extraction is simple and may include navigation text; review the output. PDF extraction is text-only and may require OCR for scans. Snapshots store unencrypted source text, so keep them in a secure location; the writer uses 0600 permissions on POSIX. There is no network fetcher or hosted persistence. The latest source content should be rechecked at the original publisher before publication.
87
+
88
+ Further reading: [architecture and provider contract](docs/architecture.md), [release checklist](docs/release-checklist.md), [contributing](CONTRIBUTING.md), [security](SECURITY.md), and [changelog](CHANGELOG.md). These are preparation for a public release, not evidence it has been published or reviewed independently.
89
+
90
+ An optional provider illustration is in [`examples/openai_adapter.py`](examples/openai_adapter.py). It requires a separately installed SDK and the user's own provider credentials; no credentials belong in this repository. Model names and SDK behavior can change, so validate an adapter against its provider's current documentation before using it.
91
+
92
+ For release mechanics, see [PyPI Trusted Publishing setup](docs/publishing.md). No API token is needed in GitHub Actions. A GitHub release or a pending publisher alone is not proof that PyPI published the package; check the PyPI project and install before relying on it.
93
+
94
+ ### Optional evidence reranking
95
+
96
+ Pass `rerank=lambda query, evidence: ...` when you have a trusted reranking function. The function receives the initially retrieved evidence and must return a permutation of those same objects; new or rewritten passages are rejected. Citation IDs are reassigned after the new order. Reranking cannot recover evidence absent from the initial `top_k`, and does not check whether an answer is true. Arabic normalization includes common hamza, ta marbuta, alef maqsura and Persian keyboard letter variants; it is still not Arabic stemming or morphological analysis.
97
+
98
+ ### Retrieval evaluation
99
+
100
+ Use `RetrievalCase` and `evaluate_retrieval` with independently labeled relevant source IDs to measure recall@k, hit rate@k, and reciprocal rank. See [evaluation guide](docs/evaluation.md). These metrics do not validate generated claims or source credibility.
@@ -0,0 +1,77 @@
1
+ # NewsRAG by Shehata El-sayed
2
+
3
+ A small, auditable Python RAG toolkit for journalistic research. This v0.2 pre-release is a research prototype; check PyPI for publication status. Python 3.10+; standard library core. Licensed under Apache-2.0 (see LICENSE and NOTICE).
4
+
5
+ ## Example
6
+
7
+ ```python
8
+ from datetime import datetime, timezone
9
+ from newsrag import NewsroomRAG, Source
10
+
11
+ rag = NewsroomRAG(recency_half_life_days=30).add(
12
+ Source(id="1", title="Official statement", text="A limited pilot began in September. No public launch was announced.",
13
+ url="https://example.org/statement", published_at=datetime(2026, 9, 10, tzinfo=timezone.utc))
14
+ )
15
+ print(rag.ask("Was there a public launch?").as_dict())
16
+ ```
17
+
18
+ Save a source's actual URL and publication date. The default `ask` retrieves evidence without generating prose. Add provider functions when you want answer generation:
19
+
20
+ ```python
21
+ rag = NewsroomRAG(
22
+ embed=lambda texts: embedding_provider(texts), # list[str] -> list[list[float]]
23
+ generate=lambda prompt: llm_provider(prompt), # str -> str
24
+ ).add(...)
25
+ answer = rag.ask("ما الذي أُعلن؟")
26
+ print(answer.text, answer.evidence, answer.warnings)
27
+ ```
28
+
29
+ Install locally with `python -m pip install .`; run tests with `PYTHONPATH=src python -m unittest discover -s tests -v`, and run `PYTHONPATH=src python examples/quickstart.py` from this directory. No network calls occur unless your adapters make them.
30
+
31
+ ## Newsroom-specific controls
32
+
33
+ - Every source carries an ID, title, original URL, publisher, type, timestamp with timezone, and original text. Search results retain exact offsets and excerpts for audit.
34
+ - Arabic orthographic normalization and English token search work locally. Optional provider embeddings improve semantic search and cross-language matching, but an appropriate multilingual model is required for Arabic-English semantic retrieval.
35
+ - Optional publication date range filters (`before`, `after`) and a modest recency ranking boost. Unknown publication dates are excluded when filtering by date; they remain eligible otherwise. The timestamp means publication time, not event time.
36
+ - Generator prompt asks for bracketed evidence IDs (`[E1]`). IDs are checked against retrieved passages and unknown IDs flagged. This does **not** verify the claims, the source's truth, or whether cited passages support each sentence.
37
+ - No-match answers abstain. Source text is marked untrusted, but prompt injection remains a risk with any model. Do not feed confidential material to a third-party provider without permission. Review original sources, licensing, quotes, dates, and contested claims before publishing.
38
+
39
+ ## Scope and limitations
40
+
41
+ This v0.2 is an in-memory retrieval prototype with local JSON source snapshots, not a production crawler or fact-checker. It handles plain text and synchronous callable adapters; automatic fetching of URLs, OCR for scanned PDFs, database connectors, persistent vector indexes, source deduplication, named provider packages, automated entailment checking, and benchmark-based tuning are future work. Lexical Arabic tokenization is basic, not morphological. No claim that this works with every provider out of the box: providers must offer embeddings with stable vector dimensions and/or text generation and be wrapped in the two simple callables. The toy example.org URLs are not real news sources.
42
+
43
+
44
+ ## Quality checks
45
+
46
+ Run `python -m pip install -e . pytest ruff mypy build "pypdf>=5,<7"`, then `ruff check src tests examples setup.py`, `mypy src/newsrag`, `pytest -q`, and `python -m build`. CI is configured to run these checks on Python 3.10–3.13; this local package was checked on Python 3.10 only. A passing suite reduces risk but cannot guarantee zero bugs or factual accuracy.
47
+
48
+ ## Local ingestion and snapshots
49
+
50
+ ```python
51
+ from newsrag import source_from_html, source_from_pdf, save_sources, load_sources
52
+
53
+ # You fetch the original page yourself. This library does not fetch URLs or bypass site terms.
54
+ source = source_from_html(id="story-1", title="Original article", url="https://example.org/story",
55
+ html="<article><p>An independently confirmed report.</p></article>")
56
+ rag.add(source)
57
+ save_sources(rag, "research.json") # source content, mode 0600; no API keys or model code
58
+ restored = load_sources("research.json")
59
+ # PDF extraction, optional: pip install 'newsrag[pdf]'
60
+ # document = source_from_pdf(id="file-1", title="Report", pdf_bytes=pdf_data)
61
+ ```
62
+
63
+ For web ingestion, the caller is responsible for fetching, verifying the URL, handling redirects, authentication, robots/licensing rules and SSRF protection. Passing HTML does not prove its authorship. HTML extraction is simple and may include navigation text; review the output. PDF extraction is text-only and may require OCR for scans. Snapshots store unencrypted source text, so keep them in a secure location; the writer uses 0600 permissions on POSIX. There is no network fetcher or hosted persistence. The latest source content should be rechecked at the original publisher before publication.
64
+
65
+ Further reading: [architecture and provider contract](docs/architecture.md), [release checklist](docs/release-checklist.md), [contributing](CONTRIBUTING.md), [security](SECURITY.md), and [changelog](CHANGELOG.md). These are preparation for a public release, not evidence it has been published or reviewed independently.
66
+
67
+ An optional provider illustration is in [`examples/openai_adapter.py`](examples/openai_adapter.py). It requires a separately installed SDK and the user's own provider credentials; no credentials belong in this repository. Model names and SDK behavior can change, so validate an adapter against its provider's current documentation before using it.
68
+
69
+ For release mechanics, see [PyPI Trusted Publishing setup](docs/publishing.md). No API token is needed in GitHub Actions. A GitHub release or a pending publisher alone is not proof that PyPI published the package; check the PyPI project and install before relying on it.
70
+
71
+ ### Optional evidence reranking
72
+
73
+ Pass `rerank=lambda query, evidence: ...` when you have a trusted reranking function. The function receives the initially retrieved evidence and must return a permutation of those same objects; new or rewritten passages are rejected. Citation IDs are reassigned after the new order. Reranking cannot recover evidence absent from the initial `top_k`, and does not check whether an answer is true. Arabic normalization includes common hamza, ta marbuta, alef maqsura and Persian keyboard letter variants; it is still not Arabic stemming or morphological analysis.
74
+
75
+ ### Retrieval evaluation
76
+
77
+ Use `RetrievalCase` and `evaluate_retrieval` with independently labeled relevant source IDs to measure recall@k, hit rate@k, and reciprocal rank. See [evaluation guide](docs/evaluation.md). These metrics do not validate generated claims or source credibility.
@@ -0,0 +1,5 @@
1
+ # Security
2
+
3
+ Do not submit secrets or unpublished material in a public issue. Contact the maintainer privately through their verified repository profile for a suspected vulnerability. No private security contact address has been supplied yet.
4
+
5
+ Source text is untrusted. A generator may still obey instructions embedded in retrieved passages despite prompt wording; review outputs and avoid passing confidential data to external providers without permission. The library does not fetch URLs; applications that do must defend against server-side request forgery, unexpected redirects, oversized responses and licensing restrictions. JSON snapshots contain original text without encryption, so store them only on secured devices and back them up according to newsroom policy.
@@ -0,0 +1,26 @@
1
+ # Architecture and contract
2
+
3
+ `Source` is an immutable record with required ID, title and text. Optional metadata includes original URL, publisher, source type, language, timezone-aware publication and access timestamps. Journalists should keep the source document separately; `Source` metadata is a claim about provenance, not a signature proving authorship.
4
+
5
+ `NewsroomRAG.add` chunks the text and keeps exact Python character offsets. It tokenizes basic Arabic and English, then scores matching chunks with a BM25-style lexical score. An optional caller-provided embedding function provides vectors for cosine ranking. A bounded, optional recency boost uses the publication date only; an unknown publication date is never filled in. `search` returns top passages with references (`E1`, `E2`) assigned per request. References are not durable IDs; persist the source ID, URL and offsets for an audit trail.
6
+
7
+ `ask` retrieves first. With no generator it returns passages only. With a generator it sends excerpts and citation instructions to the caller's model and checks whether bracketed reference numbers in the returned text exist in the retrieved set. It does not decide whether claims follow from evidence. A reviewer must open the original source, check date and context, inspect the quote and get independent corroboration for consequential claims.
8
+
9
+ `source_from_html` accepts already-fetched HTML and strips basic script/style content. It does not fetch or verify websites. `source_from_pdf` extracts text from caller-supplied bytes using optional pypdf; it is not OCR. `save_sources` stores original text and metadata as JSON, not embeddings. `load_sources` recomputes embeddings when given a configured rag instance. Storage is local and unencrypted.
10
+
11
+ ## Provider adapter shape
12
+
13
+ ```python
14
+ from newsrag import NewsroomRAG
15
+
16
+ rag = NewsroomRAG(
17
+ embed=lambda texts: embedding_api(texts), # list[str] -> list[list[float]]
18
+ generate=lambda prompt: generation_api(prompt), # str -> str
19
+ )
20
+ ```
21
+
22
+ A provider must return one vector per input and use stable vector dimensions. Avoid changing the embedding model for a partially indexed corpus; build a fresh index if the model changes. Calls are synchronous and exceptions from providers propagate. Do not send source text to a provider without a valid editorial and privacy basis.
23
+
24
+ ## Optional reranker
25
+
26
+ Pass `rerank=lambda query, evidence: ...` to `NewsroomRAG` to reorder the retrieved top-k passages. It receives a tuple of `Evidence` and must return a permutation of those exact objects; it cannot add or rewrite evidence. References are reassigned to `E1`, `E2`, etc. after reordering. Reranking applies only to the initially retrieved candidates; increase `top_k` when a larger candidate pool is needed. A reranker may send passages to an outside provider, so treat that adapter as a separate privacy and trust decision. Reordering does not verify any claim.
@@ -0,0 +1,17 @@
1
+ # Evaluate retrieval on labeled questions
2
+
3
+ This small harness measures whether manually labeled source IDs appear in the first `k` distinct sources. It reports recall@k, hit rate@k, mean reciprocal rank, and missed queries. Labels need to be made by a human independently of the model's ranking. Keep an evaluation set separate from tuning. These scores say nothing about whether generated prose is true, citations support claims, sources are credible, or the dataset represents a real newsroom.
4
+
5
+ ```python
6
+ from newsrag import NewsroomRAG, Source, RetrievalCase, evaluate_retrieval
7
+
8
+ rag = NewsroomRAG().add(
9
+ Source("original", "Original statement", "The ministry announced a pilot."),
10
+ Source("followup", "Follow-up", "The pilot was extended in October."),
11
+ )
12
+ cases = [RetrievalCase("What was announced?", frozenset({"original"})),
13
+ RetrievalCase("What happened in October?", frozenset({"followup"}))]
14
+ print(evaluate_retrieval(rag, cases, top_k=2).as_dict())
15
+ ```
16
+
17
+ Use source IDs that exist in the corpus; missing IDs count as misses. An embedding or reranking adapter configured on the RAG object is used during scoring and may make external calls, including transmitting queries and source text. Do not put confidential test material in an external provider without permission. Compare against an independent held-out set, track failures by topic and language, and inspect original sources before drawing editorial conclusions.
@@ -0,0 +1,15 @@
1
+ # Publishing with PyPI Trusted Publishing
2
+
3
+ This repository includes `.github/workflows/release.yml`. A version tag beginning with `v` triggers checks, builds a wheel and source distribution, then asks PyPI to publish through GitHub OIDC. No API token is stored in the repository.
4
+
5
+ The owner must complete these first:
6
+
7
+ 1. Confirm the public repository under the correct GitHub account, its exact `owner/newsrag` path, and the desired license. The account/owner cannot be guessed from a similar name.
8
+ 2. In GitHub, create an environment named `pypi`. Protect it with required reviewers if appropriate, and restrict deployment to version tags if possible. Do not approve a release until the code and artifacts have been reviewed.
9
+ 3. Sign into the intended PyPI account. In the account sidebar, open **Publishing** and add a **pending GitHub publisher** for project `newsrag`: owner is the exact GitHub account or organization name, repository `newsrag`, workflow filename `release.yml`, environment `pypi`. A pending publisher does not reserve the name.
10
+ 4. Review the release, ensure the version in `setup.py` and `src/newsrag/__init__.py` matches the intended tag, then create and push an annotated tag such as `v0.2.0` on the reviewed commit. The release workflow will ask for the `pypi` environment approval and publish only after approval.
11
+ 5. Verify the workflow succeeded and check the actual project on PyPI. An accepted pending publisher or a green build alone is not proof of publication.
12
+
13
+ Official PyPI instructions: https://docs.pypi.org/trusted-publishers/creating-a-project-through-oidc/ and https://docs.pypi.org/trusted-publishers/using-a-publisher/ .
14
+
15
+ If a token was created for a previous manual-upload plan, it is not used by this workflow. The owner can revoke it in PyPI account settings after this route works.
@@ -0,0 +1,11 @@
1
+ # Release checklist
2
+
3
+ - [ ] Confirm package name, repository visibility, maintainer identity and license with the owner.
4
+ - [ ] Review code and dependencies for secrets and unintended private content.
5
+ - [ ] Run Ruff, mypy, tests and build on all supported Python versions.
6
+ - [ ] Verify source distribution and wheel install in clean environments.
7
+ - [ ] Test real multilingual corpora, long files, citation failure cases and source-date edge cases.
8
+ - [ ] Inspect dependency advisories, package metadata and README rendering.
9
+ - [ ] Publish a signed/tagged release and verify the public repository and package index pages.
10
+
11
+ The locally tested prototype is not a substitute for this release review. Do not claim automated fact checking or universal provider compatibility without tests for those claims.
@@ -0,0 +1,9 @@
1
+ from newsrag import NewsroomRAG, load_sources, save_sources, source_from_html
2
+
3
+ source = source_from_html(id="example", title="Demo", url="https://example.org/demo",
4
+ html="<article><p>The pilot has not launched publicly.</p></article>")
5
+ rag = NewsroomRAG().add(source)
6
+ print(rag.search("pilot"))
7
+ save_sources(rag, "newsroom-sources.json")
8
+ restored = load_sources("newsroom-sources.json")
9
+ print(restored.ask("Was there a public launch?").as_dict())
@@ -0,0 +1,25 @@
1
+ """Optional OpenAI SDK example. Install `openai` separately and set OPENAI_API_KEY.
2
+
3
+ This is an example adapter, not a bundled dependency or an endorsement.
4
+ Only use it with sources you may send to a third-party service.
5
+ """
6
+ from newsrag import NewsroomRAG
7
+
8
+
9
+ def make_rag(client):
10
+ def embed(texts: list[str]) -> list[list[float]]:
11
+ result = client.embeddings.create(model="text-embedding-3-small", input=texts)
12
+ return [item.embedding for item in sorted(result.data, key=lambda item: item.index)]
13
+
14
+ def generate(prompt: str) -> str:
15
+ result = client.responses.create(model="gpt-4.1-mini", input=prompt)
16
+ return result.output_text
17
+
18
+ return NewsroomRAG(embed=embed, generate=generate)
19
+
20
+
21
+ if __name__ == "__main__":
22
+ from openai import OpenAI
23
+
24
+ rag = make_rag(OpenAI())
25
+ print("Adapter ready. Add your authorized Source records before calling ask().")
@@ -0,0 +1,13 @@
1
+ from datetime import datetime, timezone
2
+
3
+ from newsrag import NewsroomRAG, Source
4
+
5
+ rag = NewsroomRAG(recency_half_life_days=30).add(
6
+ Source(id="press-release", title="Official announcement", text="The company announced a pilot on 10 September. It did not announce a public launch.", url="https://example.org/official", publisher="Example Corp", published_at=datetime(2026, 9, 10, tzinfo=timezone.utc)),
7
+ Source(id="interview", title="Reporter notes", text="In an interview, the editor said the pilot still needs independent testing.", source_type="interview"),
8
+ )
9
+ print(rag.ask("Was there a public launch?").as_dict())
10
+ # Plug in ANY synchronous provider with two callables:
11
+ # rag = NewsroomRAG(embed=lambda texts: your_embedding_client(texts),
12
+ # generate=lambda prompt: your_llm_client(prompt))
13
+ # print(rag.add(...).ask("What changed? [in Arabic or English]").as_dict())
@@ -0,0 +1,3 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"