arabic-rag-bench 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.
- arabic_rag_bench-0.1.0/LICENSE +21 -0
- arabic_rag_bench-0.1.0/PKG-INFO +91 -0
- arabic_rag_bench-0.1.0/README.md +72 -0
- arabic_rag_bench-0.1.0/pyproject.toml +30 -0
- arabic_rag_bench-0.1.0/setup.cfg +4 -0
- arabic_rag_bench-0.1.0/src/arabic_rag_bench/__init__.py +11 -0
- arabic_rag_bench-0.1.0/src/arabic_rag_bench/cli.py +53 -0
- arabic_rag_bench-0.1.0/src/arabic_rag_bench/evaluator.py +53 -0
- arabic_rag_bench-0.1.0/src/arabic_rag_bench/metrics.py +63 -0
- arabic_rag_bench-0.1.0/src/arabic_rag_bench/models.py +117 -0
- arabic_rag_bench-0.1.0/src/arabic_rag_bench/report.py +41 -0
- arabic_rag_bench-0.1.0/src/arabic_rag_bench.egg-info/PKG-INFO +91 -0
- arabic_rag_bench-0.1.0/src/arabic_rag_bench.egg-info/SOURCES.txt +18 -0
- arabic_rag_bench-0.1.0/src/arabic_rag_bench.egg-info/dependency_links.txt +1 -0
- arabic_rag_bench-0.1.0/src/arabic_rag_bench.egg-info/entry_points.txt +2 -0
- arabic_rag_bench-0.1.0/src/arabic_rag_bench.egg-info/requires.txt +5 -0
- arabic_rag_bench-0.1.0/src/arabic_rag_bench.egg-info/top_level.txt +1 -0
- arabic_rag_bench-0.1.0/tests/test_cli.py +32 -0
- arabic_rag_bench-0.1.0/tests/test_evaluator.py +77 -0
- arabic_rag_bench-0.1.0/tests/test_metrics.py +37 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Abdelwahab Mahmoud Gharib
|
|
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,91 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: arabic-rag-bench
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Reproducible, offline evaluation for Arabic retrieval-augmented generation systems
|
|
5
|
+
Author: Abdelwahab Gharib
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Keywords: arabic,rag,evaluation,retrieval,citations,benchmarking
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: Natural Language :: Arabic
|
|
10
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
11
|
+
Requires-Python: >=3.10
|
|
12
|
+
Description-Content-Type: text/markdown
|
|
13
|
+
License-File: LICENSE
|
|
14
|
+
Provides-Extra: dev
|
|
15
|
+
Requires-Dist: pytest>=8; extra == "dev"
|
|
16
|
+
Requires-Dist: pytest-cov>=5; extra == "dev"
|
|
17
|
+
Requires-Dist: ruff>=0.6; extra == "dev"
|
|
18
|
+
Dynamic: license-file
|
|
19
|
+
|
|
20
|
+
# Arabic RAG Bench
|
|
21
|
+
|
|
22
|
+
[](https://github.com/abdogarep64/arabic-rag-bench/actions/workflows/ci.yml)
|
|
23
|
+
|
|
24
|
+
**An open-source, offline benchmark toolkit for Arabic retrieval-augmented generation (RAG) systems.**
|
|
25
|
+
|
|
26
|
+
Arabic RAG Bench evaluates *previously generated* answers and their retrieved source documents using deterministic, explainable metrics. It helps engineering teams detect retrieval regressions and citation problems while avoiding the cost and unreliability of an LLM judge in baseline CI.
|
|
27
|
+
|
|
28
|
+
## Features
|
|
29
|
+
|
|
30
|
+
- Retrieval Recall@k against labeled relevant documents.
|
|
31
|
+
- Citation precision and recall against reference relevance labels.
|
|
32
|
+
- Unknown-document citation detection with hard failure.
|
|
33
|
+
- Token-level F1 with normalization of common Arabic orthographic variants.
|
|
34
|
+
- JSONL benchmark ingestion with descriptive validation errors.
|
|
35
|
+
- Python SDK and CLI with JSON or Markdown reports.
|
|
36
|
+
- Baseline-versus-candidate regression comparison and nonzero CI exit codes.
|
|
37
|
+
- Zero runtime dependencies; supports Python 3.10+.
|
|
38
|
+
- Reproducible synthetic Arabic examples, useful for getting started.
|
|
39
|
+
|
|
40
|
+
## Install (from source)
|
|
41
|
+
|
|
42
|
+
```sh
|
|
43
|
+
python -m pip install -e .
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
> This project has not yet been published on PyPI. Do not assume `pip install arabic-rag-bench` will work from PyPI.
|
|
47
|
+
|
|
48
|
+
## Quickstart
|
|
49
|
+
|
|
50
|
+
```sh
|
|
51
|
+
arabic-rag-bench audit examples/sample.jsonl --format markdown --fail-under 0.7
|
|
52
|
+
arabic-rag-bench audit examples/sample.jsonl --format json
|
|
53
|
+
arabic-rag-bench compare examples/sample.jsonl examples/sample.jsonl
|
|
54
|
+
python -m unittest discover -s tests -v
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
## Python SDK
|
|
58
|
+
|
|
59
|
+
```python
|
|
60
|
+
from arabic_rag_bench import BenchmarkCase, evaluate_case
|
|
61
|
+
|
|
62
|
+
case = BenchmarkCase.from_dict({
|
|
63
|
+
"id": "return-policy",
|
|
64
|
+
"question": "ينفع أرجّع الطلب؟",
|
|
65
|
+
"answer": "تقدر ترجّعه خلال أسبوع.",
|
|
66
|
+
"reference_answer": "تقدر ترجّعه خلال أسبوع.",
|
|
67
|
+
"documents": [{"id": "policy", "text": "الاسترجاع خلال 7 أيام."}],
|
|
68
|
+
"relevant_ids": ["policy"],
|
|
69
|
+
"cited_ids": ["policy"],
|
|
70
|
+
"target_dialect": "egyptian",
|
|
71
|
+
})
|
|
72
|
+
print(evaluate_case(case).as_dict())
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
## Benchmark format
|
|
76
|
+
|
|
77
|
+
Each JSONL line must be a JSON object containing `id`, `question`, `answer`, `documents` (ordered retrieval results, each with `id` and `text`), `relevant_ids`, and `cited_ids`. Optional: `reference_answer` and `target_dialect` (`msa`, `egyptian`, `gulf`, `levantine`).
|
|
78
|
+
|
|
79
|
+
**Important:** `cited_ids` are structured references supplied by your RAG pipeline, not inferred from answer prose. If no reference answer or relevance labels exist, some metrics take neutral values and emit warnings. This does **not** prove answer quality.
|
|
80
|
+
|
|
81
|
+
## Limitations and research ethics
|
|
82
|
+
|
|
83
|
+
This first release **does not** verify factual grounding or faithful claim-level citation support, and it does **not** yet measure dialect consistency. Lexical overlap is not semantic equivalence. The examples are synthetic; no real-world adoption, validated accuracy, downloads, contributors, external dependents, or Anthropic eligibility is claimed. See [evaluation methodology](docs/METHODOLOGY.md).
|
|
84
|
+
|
|
85
|
+
## Contributing
|
|
86
|
+
|
|
87
|
+
See [CONTRIBUTING.md](CONTRIBUTING.md) for reproducing tests and proposing improvements. Code was developed with AI assistance and should be reviewed by human maintainers.
|
|
88
|
+
|
|
89
|
+
## License
|
|
90
|
+
|
|
91
|
+
MIT — Copyright (c) 2026 Abdelwahab Gharib.
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
# Arabic RAG Bench
|
|
2
|
+
|
|
3
|
+
[](https://github.com/abdogarep64/arabic-rag-bench/actions/workflows/ci.yml)
|
|
4
|
+
|
|
5
|
+
**An open-source, offline benchmark toolkit for Arabic retrieval-augmented generation (RAG) systems.**
|
|
6
|
+
|
|
7
|
+
Arabic RAG Bench evaluates *previously generated* answers and their retrieved source documents using deterministic, explainable metrics. It helps engineering teams detect retrieval regressions and citation problems while avoiding the cost and unreliability of an LLM judge in baseline CI.
|
|
8
|
+
|
|
9
|
+
## Features
|
|
10
|
+
|
|
11
|
+
- Retrieval Recall@k against labeled relevant documents.
|
|
12
|
+
- Citation precision and recall against reference relevance labels.
|
|
13
|
+
- Unknown-document citation detection with hard failure.
|
|
14
|
+
- Token-level F1 with normalization of common Arabic orthographic variants.
|
|
15
|
+
- JSONL benchmark ingestion with descriptive validation errors.
|
|
16
|
+
- Python SDK and CLI with JSON or Markdown reports.
|
|
17
|
+
- Baseline-versus-candidate regression comparison and nonzero CI exit codes.
|
|
18
|
+
- Zero runtime dependencies; supports Python 3.10+.
|
|
19
|
+
- Reproducible synthetic Arabic examples, useful for getting started.
|
|
20
|
+
|
|
21
|
+
## Install (from source)
|
|
22
|
+
|
|
23
|
+
```sh
|
|
24
|
+
python -m pip install -e .
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
> This project has not yet been published on PyPI. Do not assume `pip install arabic-rag-bench` will work from PyPI.
|
|
28
|
+
|
|
29
|
+
## Quickstart
|
|
30
|
+
|
|
31
|
+
```sh
|
|
32
|
+
arabic-rag-bench audit examples/sample.jsonl --format markdown --fail-under 0.7
|
|
33
|
+
arabic-rag-bench audit examples/sample.jsonl --format json
|
|
34
|
+
arabic-rag-bench compare examples/sample.jsonl examples/sample.jsonl
|
|
35
|
+
python -m unittest discover -s tests -v
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
## Python SDK
|
|
39
|
+
|
|
40
|
+
```python
|
|
41
|
+
from arabic_rag_bench import BenchmarkCase, evaluate_case
|
|
42
|
+
|
|
43
|
+
case = BenchmarkCase.from_dict({
|
|
44
|
+
"id": "return-policy",
|
|
45
|
+
"question": "ينفع أرجّع الطلب؟",
|
|
46
|
+
"answer": "تقدر ترجّعه خلال أسبوع.",
|
|
47
|
+
"reference_answer": "تقدر ترجّعه خلال أسبوع.",
|
|
48
|
+
"documents": [{"id": "policy", "text": "الاسترجاع خلال 7 أيام."}],
|
|
49
|
+
"relevant_ids": ["policy"],
|
|
50
|
+
"cited_ids": ["policy"],
|
|
51
|
+
"target_dialect": "egyptian",
|
|
52
|
+
})
|
|
53
|
+
print(evaluate_case(case).as_dict())
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
## Benchmark format
|
|
57
|
+
|
|
58
|
+
Each JSONL line must be a JSON object containing `id`, `question`, `answer`, `documents` (ordered retrieval results, each with `id` and `text`), `relevant_ids`, and `cited_ids`. Optional: `reference_answer` and `target_dialect` (`msa`, `egyptian`, `gulf`, `levantine`).
|
|
59
|
+
|
|
60
|
+
**Important:** `cited_ids` are structured references supplied by your RAG pipeline, not inferred from answer prose. If no reference answer or relevance labels exist, some metrics take neutral values and emit warnings. This does **not** prove answer quality.
|
|
61
|
+
|
|
62
|
+
## Limitations and research ethics
|
|
63
|
+
|
|
64
|
+
This first release **does not** verify factual grounding or faithful claim-level citation support, and it does **not** yet measure dialect consistency. Lexical overlap is not semantic equivalence. The examples are synthetic; no real-world adoption, validated accuracy, downloads, contributors, external dependents, or Anthropic eligibility is claimed. See [evaluation methodology](docs/METHODOLOGY.md).
|
|
65
|
+
|
|
66
|
+
## Contributing
|
|
67
|
+
|
|
68
|
+
See [CONTRIBUTING.md](CONTRIBUTING.md) for reproducing tests and proposing improvements. Code was developed with AI assistance and should be reviewed by human maintainers.
|
|
69
|
+
|
|
70
|
+
## License
|
|
71
|
+
|
|
72
|
+
MIT — Copyright (c) 2026 Abdelwahab Gharib.
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "arabic-rag-bench"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Reproducible, offline evaluation for Arabic retrieval-augmented generation systems"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
authors = [{name = "Abdelwahab Gharib"}]
|
|
13
|
+
keywords = ["arabic", "rag", "evaluation", "retrieval", "citations", "benchmarking"]
|
|
14
|
+
classifiers = ["Programming Language :: Python :: 3", "Natural Language :: Arabic", "Topic :: Scientific/Engineering :: Artificial Intelligence"]
|
|
15
|
+
dependencies = []
|
|
16
|
+
|
|
17
|
+
[project.optional-dependencies]
|
|
18
|
+
dev = ["pytest>=8", "pytest-cov>=5", "ruff>=0.6"]
|
|
19
|
+
|
|
20
|
+
[project.scripts]
|
|
21
|
+
arabic-rag-bench = "arabic_rag_bench.cli:main"
|
|
22
|
+
|
|
23
|
+
[tool.setuptools.packages.find]
|
|
24
|
+
where = ["src"]
|
|
25
|
+
|
|
26
|
+
[tool.ruff]
|
|
27
|
+
line-length = 100
|
|
28
|
+
|
|
29
|
+
[tool.pytest.ini_options]
|
|
30
|
+
testpaths = ["tests"]
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"""Arabic RAG Bench: deterministic RAG quality evaluation."""
|
|
2
|
+
|
|
3
|
+
from .models import BenchmarkCase, Document, EvaluationConfig, EvaluationResult
|
|
4
|
+
from .evaluator import evaluate_case, evaluate_dataset
|
|
5
|
+
from .report import aggregate_results, render_markdown
|
|
6
|
+
|
|
7
|
+
__version__ = "0.1.0"
|
|
8
|
+
__all__ = [
|
|
9
|
+
"BenchmarkCase", "Document", "EvaluationConfig", "EvaluationResult",
|
|
10
|
+
"evaluate_case", "evaluate_dataset", "aggregate_results", "render_markdown",
|
|
11
|
+
]
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""CLI for reproducible JSONL audits and release regression checks."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import json
|
|
6
|
+
import sys
|
|
7
|
+
|
|
8
|
+
from .evaluator import evaluate_dataset, read_cases
|
|
9
|
+
from .models import EvaluationConfig
|
|
10
|
+
from .report import aggregate_results, compare_summaries, render_markdown
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
14
|
+
parser = argparse.ArgumentParser(prog="arabic-rag-bench", description="Audit Arabic RAG outputs offline")
|
|
15
|
+
commands = parser.add_subparsers(dest="command", required=True)
|
|
16
|
+
audit = commands.add_parser("audit", help="Audit a benchmark JSONL file")
|
|
17
|
+
audit.add_argument("input", help="JSONL path")
|
|
18
|
+
audit.add_argument("--format", choices=("markdown", "json"), default="markdown")
|
|
19
|
+
audit.add_argument("--fail-under", type=float, default=0.7, help="Minimum mean score, 0..1")
|
|
20
|
+
audit.add_argument("--retrieval-k", type=int, default=5)
|
|
21
|
+
compare = commands.add_parser("compare", help="Compare two benchmark JSONL outputs")
|
|
22
|
+
compare.add_argument("baseline")
|
|
23
|
+
compare.add_argument("candidate")
|
|
24
|
+
compare.add_argument("--tolerance", type=float, default=0.0)
|
|
25
|
+
return parser
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def main(argv: list[str] | None = None) -> int:
|
|
29
|
+
args = build_parser().parse_args(argv)
|
|
30
|
+
if hasattr(sys.stdout, "reconfigure"):
|
|
31
|
+
sys.stdout.reconfigure(encoding="utf-8")
|
|
32
|
+
try:
|
|
33
|
+
if args.command == "audit":
|
|
34
|
+
cfg = EvaluationConfig(min_score=args.fail_under, retrieval_k=args.retrieval_k)
|
|
35
|
+
results = evaluate_dataset(read_cases(args.input), cfg)
|
|
36
|
+
summary = aggregate_results(results)
|
|
37
|
+
if args.format == "markdown":
|
|
38
|
+
print(render_markdown(results))
|
|
39
|
+
else:
|
|
40
|
+
print(json.dumps({"summary": summary, "cases": [r.as_dict() for r in results]}, ensure_ascii=False, indent=2))
|
|
41
|
+
return 0 if summary["mean_score"] is not None and summary["mean_score"] >= args.fail_under else 1
|
|
42
|
+
baseline = aggregate_results(evaluate_dataset(read_cases(args.baseline)))
|
|
43
|
+
candidate = aggregate_results(evaluate_dataset(read_cases(args.candidate)))
|
|
44
|
+
comparison = compare_summaries(baseline, candidate, args.tolerance)
|
|
45
|
+
print(json.dumps(comparison, ensure_ascii=False, indent=2))
|
|
46
|
+
return 1 if comparison["regression"] else 0
|
|
47
|
+
except (OSError, ValueError, TypeError) as exc:
|
|
48
|
+
print(f"Error: {exc}", file=sys.stderr)
|
|
49
|
+
return 2
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
if __name__ == "__main__":
|
|
53
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""Deterministic evaluation pipeline for already-produced RAG responses."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Iterable, Iterator
|
|
7
|
+
|
|
8
|
+
from .metrics import citation_precision, citation_recall, overlap_f1, retrieval_recall
|
|
9
|
+
from .models import BenchmarkCase, EvaluationConfig, EvaluationResult
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def evaluate_case(case: BenchmarkCase, config: EvaluationConfig | None = None) -> EvaluationResult:
|
|
13
|
+
"""Evaluate retrieval and citation labels without calling an external model."""
|
|
14
|
+
cfg = config or EvaluationConfig()
|
|
15
|
+
ids = [document.id for document in case.documents]
|
|
16
|
+
metrics = {
|
|
17
|
+
"retrieval_recall": retrieval_recall(ids, case.relevant_ids, cfg.retrieval_k),
|
|
18
|
+
"citation_precision": citation_precision(case.cited_ids, case.relevant_ids),
|
|
19
|
+
"citation_recall": citation_recall(case.cited_ids, case.relevant_ids),
|
|
20
|
+
"answer_overlap": overlap_f1(case.answer, case.reference_answer),
|
|
21
|
+
}
|
|
22
|
+
score = sum(metrics[name] * weight for name, weight in cfg.weights.items())
|
|
23
|
+
warnings: list[str] = []
|
|
24
|
+
unknown = case.cited_ids - set(ids)
|
|
25
|
+
if unknown:
|
|
26
|
+
warnings.append("Unknown citation IDs: " + ", ".join(sorted(unknown)))
|
|
27
|
+
if not case.reference_answer.strip():
|
|
28
|
+
warnings.append("No reference_answer: answer_overlap is neutral, not measured")
|
|
29
|
+
if not case.relevant_ids:
|
|
30
|
+
warnings.append("No relevant_ids: retrieval/citation recall are neutral")
|
|
31
|
+
if case.target_dialect != "msa":
|
|
32
|
+
warnings.append("Dialect requested but dialect consistency is not yet measured")
|
|
33
|
+
if unknown:
|
|
34
|
+
score = 0.0 # Invalid citations are a hard failure.
|
|
35
|
+
return EvaluationResult(case.id, score, score >= cfg.min_score, metrics, tuple(warnings))
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def read_cases(path: str | Path) -> Iterator[BenchmarkCase]:
|
|
39
|
+
"""Read and validate JSONL benchmark records with useful error locations."""
|
|
40
|
+
with Path(path).open(encoding="utf-8") as handle:
|
|
41
|
+
for line_number, line in enumerate(handle, 1):
|
|
42
|
+
if not line.strip():
|
|
43
|
+
continue
|
|
44
|
+
try:
|
|
45
|
+
raw = json.loads(line)
|
|
46
|
+
yield BenchmarkCase.from_dict(raw)
|
|
47
|
+
except (json.JSONDecodeError, ValueError, TypeError) as exc:
|
|
48
|
+
raise ValueError(f"Invalid benchmark at line {line_number}: {exc}") from exc
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def evaluate_dataset(cases: Iterable[BenchmarkCase], config: EvaluationConfig | None = None) -> list[EvaluationResult]:
|
|
52
|
+
cfg = config or EvaluationConfig()
|
|
53
|
+
return [evaluate_case(case, cfg) for case in cases]
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""Reference-free and reference-based metrics with explicit limitations.
|
|
2
|
+
|
|
3
|
+
No metric here is a factuality or clinical safety verifier. Token overlap is
|
|
4
|
+
only a cheap lexical proxy for answer consistency with a reference answer.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import re
|
|
9
|
+
import unicodedata
|
|
10
|
+
from collections import Counter
|
|
11
|
+
|
|
12
|
+
_ARABIC_DIACRITICS = re.compile(r"[\u064b-\u065f\u0670\u0640]")
|
|
13
|
+
_TOKEN = re.compile(r"[\u0621-\u064a]+|[a-z0-9]+", re.IGNORECASE)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def normalize(text: str) -> str:
|
|
17
|
+
if not isinstance(text, str):
|
|
18
|
+
raise TypeError("text must be a string")
|
|
19
|
+
text = unicodedata.normalize("NFKC", text).lower()
|
|
20
|
+
text = _ARABIC_DIACRITICS.sub("", text)
|
|
21
|
+
return text.translate(str.maketrans({"أ": "ا", "إ": "ا", "آ": "ا", "ٱ": "ا", "ى": "ي"}))
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def tokens(text: str) -> list[str]:
|
|
25
|
+
return _TOKEN.findall(normalize(text))
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def retrieval_recall(retrieved_ids: list[str], relevant_ids: frozenset[str], k: int) -> float:
|
|
29
|
+
"""Recall@k, with no relevant documents defined as 1.0."""
|
|
30
|
+
if k < 1:
|
|
31
|
+
raise ValueError("k must be positive")
|
|
32
|
+
if not relevant_ids:
|
|
33
|
+
return 1.0
|
|
34
|
+
return len(set(retrieved_ids[:k]) & relevant_ids) / len(relevant_ids)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def citation_precision(cited_ids: frozenset[str], relevant_ids: frozenset[str]) -> float:
|
|
38
|
+
"""Precision of declared citations relative to labeled relevant documents."""
|
|
39
|
+
if not cited_ids:
|
|
40
|
+
return 1.0 if not relevant_ids else 0.0
|
|
41
|
+
return len(cited_ids & relevant_ids) / len(cited_ids)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def citation_recall(cited_ids: frozenset[str], relevant_ids: frozenset[str]) -> float:
|
|
45
|
+
if not relevant_ids:
|
|
46
|
+
return 1.0
|
|
47
|
+
return len(cited_ids & relevant_ids) / len(relevant_ids)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def overlap_f1(prediction: str, reference: str) -> float:
|
|
51
|
+
"""Unigram token F1; equals 1.0 when no reference is provided.
|
|
52
|
+
|
|
53
|
+
This metric is not suitable for inferring semantic equivalence.
|
|
54
|
+
"""
|
|
55
|
+
if not reference.strip():
|
|
56
|
+
return 1.0
|
|
57
|
+
predicted, expected = Counter(tokens(prediction)), Counter(tokens(reference))
|
|
58
|
+
if not predicted or not expected:
|
|
59
|
+
return 0.0
|
|
60
|
+
shared = sum((predicted & expected).values())
|
|
61
|
+
precision = shared / sum(predicted.values())
|
|
62
|
+
recall = shared / sum(expected.values())
|
|
63
|
+
return 2 * precision * recall / (precision + recall) if precision + recall else 0.0
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
"""Typed benchmark records and strict data validation."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from dataclasses import dataclass, field
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@dataclass(frozen=True)
|
|
9
|
+
class Document:
|
|
10
|
+
id: str
|
|
11
|
+
text: str
|
|
12
|
+
|
|
13
|
+
@classmethod
|
|
14
|
+
def from_dict(cls, data: dict[str, Any]) -> "Document":
|
|
15
|
+
if not isinstance(data, dict):
|
|
16
|
+
raise ValueError("Document must be an object")
|
|
17
|
+
identifier, text = data.get("id"), data.get("text")
|
|
18
|
+
if not isinstance(identifier, str) or not identifier.strip():
|
|
19
|
+
raise ValueError("Document.id must be a non-empty string")
|
|
20
|
+
if not isinstance(text, str):
|
|
21
|
+
raise ValueError("Document.text must be a string")
|
|
22
|
+
return cls(id=identifier, text=text)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True)
|
|
26
|
+
class BenchmarkCase:
|
|
27
|
+
id: str
|
|
28
|
+
question: str
|
|
29
|
+
answer: str
|
|
30
|
+
documents: tuple[Document, ...]
|
|
31
|
+
relevant_ids: frozenset[str]
|
|
32
|
+
cited_ids: frozenset[str]
|
|
33
|
+
reference_answer: str = ""
|
|
34
|
+
target_dialect: str = "msa"
|
|
35
|
+
|
|
36
|
+
@classmethod
|
|
37
|
+
def from_dict(cls, data: dict[str, Any]) -> "BenchmarkCase":
|
|
38
|
+
if not isinstance(data, dict):
|
|
39
|
+
raise ValueError("Benchmark case must be an object")
|
|
40
|
+
case_id = data.get("id")
|
|
41
|
+
question = data.get("question")
|
|
42
|
+
answer = data.get("answer")
|
|
43
|
+
if not isinstance(case_id, str) or not case_id.strip():
|
|
44
|
+
raise ValueError("Case.id must be a non-empty string")
|
|
45
|
+
if not isinstance(question, str) or not question.strip():
|
|
46
|
+
raise ValueError(f"Case {case_id}: question must be a non-empty string")
|
|
47
|
+
if not isinstance(answer, str):
|
|
48
|
+
raise ValueError(f"Case {case_id}: answer must be a string")
|
|
49
|
+
docs_raw = data.get("documents", [])
|
|
50
|
+
if not isinstance(docs_raw, list):
|
|
51
|
+
raise ValueError(f"Case {case_id}: documents must be a list")
|
|
52
|
+
docs = tuple(Document.from_dict(item) for item in docs_raw)
|
|
53
|
+
ids = [doc.id for doc in docs]
|
|
54
|
+
if len(ids) != len(set(ids)):
|
|
55
|
+
raise ValueError(f"Case {case_id}: duplicate document IDs")
|
|
56
|
+
|
|
57
|
+
def id_set(field_name: str) -> frozenset[str]:
|
|
58
|
+
value = data.get(field_name, [])
|
|
59
|
+
if not isinstance(value, list) or any(not isinstance(x, str) for x in value):
|
|
60
|
+
raise ValueError(f"Case {case_id}: {field_name} must be a list of strings")
|
|
61
|
+
return frozenset(value)
|
|
62
|
+
|
|
63
|
+
relevant_ids = id_set("relevant_ids")
|
|
64
|
+
cited_ids = id_set("cited_ids")
|
|
65
|
+
if not relevant_ids.issubset(set(ids)):
|
|
66
|
+
raise ValueError(f"Case {case_id}: relevant_ids must refer to supplied documents")
|
|
67
|
+
reference = data.get("reference_answer", "")
|
|
68
|
+
if not isinstance(reference, str):
|
|
69
|
+
raise ValueError(f"Case {case_id}: reference_answer must be a string")
|
|
70
|
+
dialect = data.get("target_dialect", "msa")
|
|
71
|
+
if dialect not in {"msa", "egyptian", "gulf", "levantine"}:
|
|
72
|
+
raise ValueError(f"Case {case_id}: unsupported target_dialect")
|
|
73
|
+
return cls(
|
|
74
|
+
id=case_id, question=question, answer=answer, documents=docs,
|
|
75
|
+
relevant_ids=relevant_ids, cited_ids=cited_ids,
|
|
76
|
+
reference_answer=reference, target_dialect=dialect,
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
@dataclass(frozen=True)
|
|
81
|
+
class EvaluationConfig:
|
|
82
|
+
retrieval_k: int = 5
|
|
83
|
+
min_score: float = 0.7
|
|
84
|
+
weights: dict[str, float] = field(default_factory=lambda: {
|
|
85
|
+
"retrieval_recall": 0.30,
|
|
86
|
+
"citation_precision": 0.25,
|
|
87
|
+
"citation_recall": 0.15,
|
|
88
|
+
"answer_overlap": 0.30,
|
|
89
|
+
})
|
|
90
|
+
|
|
91
|
+
def __post_init__(self) -> None:
|
|
92
|
+
if self.retrieval_k < 1:
|
|
93
|
+
raise ValueError("retrieval_k must be at least 1")
|
|
94
|
+
if not 0 <= self.min_score <= 1:
|
|
95
|
+
raise ValueError("min_score must be in [0, 1]")
|
|
96
|
+
if not self.weights or any(w < 0 for w in self.weights.values()):
|
|
97
|
+
raise ValueError("weights must be non-negative")
|
|
98
|
+
if abs(sum(self.weights.values()) - 1) > 1e-9:
|
|
99
|
+
raise ValueError("weights must sum to 1")
|
|
100
|
+
if set(self.weights) != {
|
|
101
|
+
"retrieval_recall", "citation_precision", "citation_recall", "answer_overlap"
|
|
102
|
+
}:
|
|
103
|
+
raise ValueError("weights must specify all supported metrics")
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
@dataclass(frozen=True)
|
|
107
|
+
class EvaluationResult:
|
|
108
|
+
id: str
|
|
109
|
+
score: float
|
|
110
|
+
passed: bool
|
|
111
|
+
metrics: dict[str, float]
|
|
112
|
+
warnings: tuple[str, ...] = ()
|
|
113
|
+
|
|
114
|
+
def as_dict(self) -> dict[str, Any]:
|
|
115
|
+
return {"id": self.id, "score": round(self.score, 4), "passed": self.passed,
|
|
116
|
+
"metrics": {k: round(v, 4) for k, v in self.metrics.items()},
|
|
117
|
+
"warnings": list(self.warnings)}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
"""Human-readable reporting and summary for RAG quality regressions."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from .models import EvaluationResult
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def aggregate_results(results: list[EvaluationResult]) -> dict:
|
|
8
|
+
"""Aggregate scores without inventing measurements for empty datasets."""
|
|
9
|
+
if not results:
|
|
10
|
+
return {"total": 0, "passed": 0, "pass_rate": None, "mean_score": None, "metrics": {}}
|
|
11
|
+
metric_keys = sorted(results[0].metrics)
|
|
12
|
+
return {
|
|
13
|
+
"total": len(results),
|
|
14
|
+
"passed": sum(item.passed for item in results),
|
|
15
|
+
"pass_rate": sum(item.passed for item in results) / len(results),
|
|
16
|
+
"mean_score": sum(item.score for item in results) / len(results),
|
|
17
|
+
"metrics": {key: sum(item.metrics[key] for item in results) / len(results) for key in metric_keys},
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def render_markdown(results: list[EvaluationResult], title: str = "Arabic RAG Benchmark") -> str:
|
|
22
|
+
summary = aggregate_results(results)
|
|
23
|
+
avg = "N/A" if summary["mean_score"] is None else f'{summary["mean_score"]:.3f}'
|
|
24
|
+
lines = [f"# {title}", "", f'- Cases: {summary["total"]}',
|
|
25
|
+
f'- Passed: {summary["passed"]}', f'- Mean score: {avg}', "",
|
|
26
|
+
"| Case | Score | Passed | Warnings |", "| --- | ---: | :---: | --- |"]
|
|
27
|
+
for item in results:
|
|
28
|
+
warning = "; ".join(item.warnings).replace("|", "\\|")
|
|
29
|
+
lines.append(f"| {item.id} | {item.score:.3f} | {'Yes' if item.passed else 'No'} | {warning} |")
|
|
30
|
+
return "\n".join(lines) + "\n"
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def compare_summaries(baseline: dict, candidate: dict, tolerance: float = 0.0) -> dict:
|
|
34
|
+
"""Compare independently computed summaries, measuring score change."""
|
|
35
|
+
if tolerance < 0:
|
|
36
|
+
raise ValueError("tolerance must be non-negative")
|
|
37
|
+
if baseline.get("mean_score") is None or candidate.get("mean_score") is None:
|
|
38
|
+
raise ValueError("Both benchmarks must have at least one case")
|
|
39
|
+
change = candidate["mean_score"] - baseline["mean_score"]
|
|
40
|
+
return {"baseline": baseline["mean_score"], "candidate": candidate["mean_score"],
|
|
41
|
+
"delta": change, "regression": change < -tolerance}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: arabic-rag-bench
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Reproducible, offline evaluation for Arabic retrieval-augmented generation systems
|
|
5
|
+
Author: Abdelwahab Gharib
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Keywords: arabic,rag,evaluation,retrieval,citations,benchmarking
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: Natural Language :: Arabic
|
|
10
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
11
|
+
Requires-Python: >=3.10
|
|
12
|
+
Description-Content-Type: text/markdown
|
|
13
|
+
License-File: LICENSE
|
|
14
|
+
Provides-Extra: dev
|
|
15
|
+
Requires-Dist: pytest>=8; extra == "dev"
|
|
16
|
+
Requires-Dist: pytest-cov>=5; extra == "dev"
|
|
17
|
+
Requires-Dist: ruff>=0.6; extra == "dev"
|
|
18
|
+
Dynamic: license-file
|
|
19
|
+
|
|
20
|
+
# Arabic RAG Bench
|
|
21
|
+
|
|
22
|
+
[](https://github.com/abdogarep64/arabic-rag-bench/actions/workflows/ci.yml)
|
|
23
|
+
|
|
24
|
+
**An open-source, offline benchmark toolkit for Arabic retrieval-augmented generation (RAG) systems.**
|
|
25
|
+
|
|
26
|
+
Arabic RAG Bench evaluates *previously generated* answers and their retrieved source documents using deterministic, explainable metrics. It helps engineering teams detect retrieval regressions and citation problems while avoiding the cost and unreliability of an LLM judge in baseline CI.
|
|
27
|
+
|
|
28
|
+
## Features
|
|
29
|
+
|
|
30
|
+
- Retrieval Recall@k against labeled relevant documents.
|
|
31
|
+
- Citation precision and recall against reference relevance labels.
|
|
32
|
+
- Unknown-document citation detection with hard failure.
|
|
33
|
+
- Token-level F1 with normalization of common Arabic orthographic variants.
|
|
34
|
+
- JSONL benchmark ingestion with descriptive validation errors.
|
|
35
|
+
- Python SDK and CLI with JSON or Markdown reports.
|
|
36
|
+
- Baseline-versus-candidate regression comparison and nonzero CI exit codes.
|
|
37
|
+
- Zero runtime dependencies; supports Python 3.10+.
|
|
38
|
+
- Reproducible synthetic Arabic examples, useful for getting started.
|
|
39
|
+
|
|
40
|
+
## Install (from source)
|
|
41
|
+
|
|
42
|
+
```sh
|
|
43
|
+
python -m pip install -e .
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
> This project has not yet been published on PyPI. Do not assume `pip install arabic-rag-bench` will work from PyPI.
|
|
47
|
+
|
|
48
|
+
## Quickstart
|
|
49
|
+
|
|
50
|
+
```sh
|
|
51
|
+
arabic-rag-bench audit examples/sample.jsonl --format markdown --fail-under 0.7
|
|
52
|
+
arabic-rag-bench audit examples/sample.jsonl --format json
|
|
53
|
+
arabic-rag-bench compare examples/sample.jsonl examples/sample.jsonl
|
|
54
|
+
python -m unittest discover -s tests -v
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
## Python SDK
|
|
58
|
+
|
|
59
|
+
```python
|
|
60
|
+
from arabic_rag_bench import BenchmarkCase, evaluate_case
|
|
61
|
+
|
|
62
|
+
case = BenchmarkCase.from_dict({
|
|
63
|
+
"id": "return-policy",
|
|
64
|
+
"question": "ينفع أرجّع الطلب؟",
|
|
65
|
+
"answer": "تقدر ترجّعه خلال أسبوع.",
|
|
66
|
+
"reference_answer": "تقدر ترجّعه خلال أسبوع.",
|
|
67
|
+
"documents": [{"id": "policy", "text": "الاسترجاع خلال 7 أيام."}],
|
|
68
|
+
"relevant_ids": ["policy"],
|
|
69
|
+
"cited_ids": ["policy"],
|
|
70
|
+
"target_dialect": "egyptian",
|
|
71
|
+
})
|
|
72
|
+
print(evaluate_case(case).as_dict())
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
## Benchmark format
|
|
76
|
+
|
|
77
|
+
Each JSONL line must be a JSON object containing `id`, `question`, `answer`, `documents` (ordered retrieval results, each with `id` and `text`), `relevant_ids`, and `cited_ids`. Optional: `reference_answer` and `target_dialect` (`msa`, `egyptian`, `gulf`, `levantine`).
|
|
78
|
+
|
|
79
|
+
**Important:** `cited_ids` are structured references supplied by your RAG pipeline, not inferred from answer prose. If no reference answer or relevance labels exist, some metrics take neutral values and emit warnings. This does **not** prove answer quality.
|
|
80
|
+
|
|
81
|
+
## Limitations and research ethics
|
|
82
|
+
|
|
83
|
+
This first release **does not** verify factual grounding or faithful claim-level citation support, and it does **not** yet measure dialect consistency. Lexical overlap is not semantic equivalence. The examples are synthetic; no real-world adoption, validated accuracy, downloads, contributors, external dependents, or Anthropic eligibility is claimed. See [evaluation methodology](docs/METHODOLOGY.md).
|
|
84
|
+
|
|
85
|
+
## Contributing
|
|
86
|
+
|
|
87
|
+
See [CONTRIBUTING.md](CONTRIBUTING.md) for reproducing tests and proposing improvements. Code was developed with AI assistance and should be reviewed by human maintainers.
|
|
88
|
+
|
|
89
|
+
## License
|
|
90
|
+
|
|
91
|
+
MIT — Copyright (c) 2026 Abdelwahab Gharib.
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
src/arabic_rag_bench/__init__.py
|
|
5
|
+
src/arabic_rag_bench/cli.py
|
|
6
|
+
src/arabic_rag_bench/evaluator.py
|
|
7
|
+
src/arabic_rag_bench/metrics.py
|
|
8
|
+
src/arabic_rag_bench/models.py
|
|
9
|
+
src/arabic_rag_bench/report.py
|
|
10
|
+
src/arabic_rag_bench.egg-info/PKG-INFO
|
|
11
|
+
src/arabic_rag_bench.egg-info/SOURCES.txt
|
|
12
|
+
src/arabic_rag_bench.egg-info/dependency_links.txt
|
|
13
|
+
src/arabic_rag_bench.egg-info/entry_points.txt
|
|
14
|
+
src/arabic_rag_bench.egg-info/requires.txt
|
|
15
|
+
src/arabic_rag_bench.egg-info/top_level.txt
|
|
16
|
+
tests/test_cli.py
|
|
17
|
+
tests/test_evaluator.py
|
|
18
|
+
tests/test_metrics.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
arabic_rag_bench
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import tempfile
|
|
3
|
+
import unittest
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from contextlib import redirect_stdout, redirect_stderr
|
|
6
|
+
from io import StringIO
|
|
7
|
+
|
|
8
|
+
from arabic_rag_bench.cli import main
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class CLITests(unittest.TestCase):
|
|
12
|
+
def test_cli_audit(self):
|
|
13
|
+
with tempfile.TemporaryDirectory() as folder:
|
|
14
|
+
path = Path(folder) / "benchmark.jsonl"
|
|
15
|
+
path.write_text(json.dumps({"id": "1", "question": "test", "answer": "نعم",
|
|
16
|
+
"documents": [{"id": "d1", "text": "نعم"}], "relevant_ids": ["d1"],
|
|
17
|
+
"cited_ids": ["d1"], "reference_answer": "نعم"}, ensure_ascii=False), encoding="utf-8")
|
|
18
|
+
stdout = StringIO()
|
|
19
|
+
with redirect_stdout(stdout):
|
|
20
|
+
self.assertEqual(main(["audit", str(path), "--format", "json"]), 0)
|
|
21
|
+
self.assertEqual(json.loads(stdout.getvalue())["summary"]["total"], 1)
|
|
22
|
+
|
|
23
|
+
def test_cli_bad_file(self):
|
|
24
|
+
stderr = StringIO()
|
|
25
|
+
with redirect_stderr(stderr):
|
|
26
|
+
self.assertEqual(main(["audit", "/no/such/file.jsonl"]), 2)
|
|
27
|
+
self.assertIn("Error:", stderr.getvalue())
|
|
28
|
+
|
|
29
|
+
def test_cli_invalid_threshold(self):
|
|
30
|
+
stderr = StringIO()
|
|
31
|
+
with redirect_stderr(stderr):
|
|
32
|
+
self.assertEqual(main(["audit", "irrelevant", "--fail-under", "1.2"]), 2)
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import tempfile
|
|
2
|
+
import unittest
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
from arabic_rag_bench import BenchmarkCase, EvaluationConfig, evaluate_case, evaluate_dataset
|
|
6
|
+
from arabic_rag_bench.evaluator import read_cases
|
|
7
|
+
from arabic_rag_bench.report import aggregate_results, render_markdown, compare_summaries
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def sample(**overrides):
|
|
11
|
+
data = {"id": "eg-1", "question": "إيه سياسة الاسترجاع؟", "answer": "الاسترجاع خلال أسبوع",
|
|
12
|
+
"documents": [{"id": "p1", "text": "الاسترجاع خلال أسبوع"}, {"id": "p2", "text": "التوصيل خلال يومين"}],
|
|
13
|
+
"relevant_ids": ["p1"], "cited_ids": ["p1"], "reference_answer": "الاسترجاع خلال أسبوع", "target_dialect": "egyptian"}
|
|
14
|
+
data.update(overrides)
|
|
15
|
+
return BenchmarkCase.from_dict(data)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class EvaluationTests(unittest.TestCase):
|
|
19
|
+
def test_perfect_case(self):
|
|
20
|
+
result = evaluate_case(sample())
|
|
21
|
+
self.assertEqual(result.score, 1)
|
|
22
|
+
self.assertTrue(result.passed)
|
|
23
|
+
|
|
24
|
+
def test_bad_citation(self):
|
|
25
|
+
result = evaluate_case(sample(cited_ids=["nonexistent"]))
|
|
26
|
+
self.assertEqual(result.score, 0)
|
|
27
|
+
self.assertFalse(result.passed)
|
|
28
|
+
self.assertIn("Unknown citation IDs", result.warnings[0])
|
|
29
|
+
|
|
30
|
+
def test_missing_relevant_id(self):
|
|
31
|
+
with self.assertRaisesRegex(ValueError, "relevant_ids"):
|
|
32
|
+
sample(relevant_ids=["not-in-documents"])
|
|
33
|
+
|
|
34
|
+
def test_duplicate_document_ids(self):
|
|
35
|
+
with self.assertRaisesRegex(ValueError, "duplicate"):
|
|
36
|
+
sample(documents=[{"id": "a", "text": "x"}, {"id": "a", "text": "y"}])
|
|
37
|
+
|
|
38
|
+
def test_invalid_weights(self):
|
|
39
|
+
with self.assertRaisesRegex(ValueError, "sum to 1"):
|
|
40
|
+
EvaluationConfig(weights={"retrieval_recall": 1.0, "citation_precision": 0.2,
|
|
41
|
+
"citation_recall": 0.1, "answer_overlap": 0.1})
|
|
42
|
+
|
|
43
|
+
def test_aggregate(self):
|
|
44
|
+
results = evaluate_dataset([sample(), sample(id="eg-2", answer="لا", cited_ids=["bad"])])
|
|
45
|
+
summary = aggregate_results(results)
|
|
46
|
+
self.assertEqual(summary["total"], 2)
|
|
47
|
+
self.assertEqual(summary["passed"], 1)
|
|
48
|
+
self.assertAlmostEqual(summary["mean_score"], 0.5)
|
|
49
|
+
|
|
50
|
+
def test_empty_summary(self):
|
|
51
|
+
self.assertIsNone(aggregate_results([])["mean_score"])
|
|
52
|
+
|
|
53
|
+
def test_markdown(self):
|
|
54
|
+
self.assertIn("eg-1", render_markdown([evaluate_case(sample())]))
|
|
55
|
+
|
|
56
|
+
def test_regression(self):
|
|
57
|
+
result = compare_summaries({"mean_score": 0.9}, {"mean_score": 0.6})
|
|
58
|
+
self.assertTrue(result["regression"])
|
|
59
|
+
|
|
60
|
+
def test_read_bad_json(self):
|
|
61
|
+
with tempfile.TemporaryDirectory() as folder:
|
|
62
|
+
path = Path(folder) / "dataset.jsonl"
|
|
63
|
+
path.write_text('{broken json}', encoding="utf-8")
|
|
64
|
+
with self.assertRaisesRegex(ValueError, "line 1"):
|
|
65
|
+
list(read_cases(path))
|
|
66
|
+
|
|
67
|
+
def test_read_good_json(self):
|
|
68
|
+
import json
|
|
69
|
+
with tempfile.TemporaryDirectory() as folder:
|
|
70
|
+
path = Path(folder) / "dataset.jsonl"
|
|
71
|
+
path.write_text(json.dumps({"id": "1", "question": "س", "answer": "ج"}, ensure_ascii=False), encoding="utf-8")
|
|
72
|
+
records = list(read_cases(path))
|
|
73
|
+
self.assertEqual(len(records), 1)
|
|
74
|
+
self.assertEqual(records[0].id, "1")
|
|
75
|
+
|
|
76
|
+
def test_empty_citation_with_relevant_docs(self):
|
|
77
|
+
self.assertFalse(evaluate_case(sample(cited_ids=[])).passed)
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import unittest
|
|
2
|
+
from arabic_rag_bench.metrics import (
|
|
3
|
+
normalize, tokens, retrieval_recall, citation_precision, citation_recall, overlap_f1,
|
|
4
|
+
)
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class MetricsTests(unittest.TestCase):
|
|
8
|
+
def test_arabic_normalization(self):
|
|
9
|
+
self.assertEqual(normalize("أَسْئِلَة وإجابات"), "اسئلة واجابات")
|
|
10
|
+
|
|
11
|
+
def test_arabic_tokenizer(self):
|
|
12
|
+
self.assertEqual(tokens("سؤال! جواب 42"), ["سؤال", "جواب", "42"])
|
|
13
|
+
|
|
14
|
+
def test_retrieval_recall_at_k(self):
|
|
15
|
+
self.assertEqual(retrieval_recall(["a", "b", "c"], frozenset({"b", "c"}), 2), 0.5)
|
|
16
|
+
|
|
17
|
+
def test_retrieval_empty_relevance(self):
|
|
18
|
+
self.assertEqual(retrieval_recall([], frozenset(), 5), 1)
|
|
19
|
+
|
|
20
|
+
def test_citation_precision(self):
|
|
21
|
+
self.assertEqual(citation_precision(frozenset({"a", "x"}), frozenset({"a"})), 0.5)
|
|
22
|
+
|
|
23
|
+
def test_citation_recall(self):
|
|
24
|
+
self.assertEqual(citation_recall(frozenset({"a"}), frozenset({"a", "b"})), 0.5)
|
|
25
|
+
|
|
26
|
+
def test_overlap_exact(self):
|
|
27
|
+
self.assertEqual(overlap_f1("الجواب صحيح", "الجواب صحيح"), 1)
|
|
28
|
+
|
|
29
|
+
def test_overlap_disjoint(self):
|
|
30
|
+
self.assertEqual(overlap_f1("نعم", "لا"), 0)
|
|
31
|
+
|
|
32
|
+
def test_overlap_neutral_when_missing_reference(self):
|
|
33
|
+
self.assertEqual(overlap_f1("الجواب", ""), 1)
|
|
34
|
+
|
|
35
|
+
def test_negative_k(self):
|
|
36
|
+
with self.assertRaises(ValueError):
|
|
37
|
+
retrieval_recall(["a"], frozenset({"a"}), 0)
|