Spaces:
Sleeping
Sleeping
File size: 10,016 Bytes
df4f47c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 | """Tests pour les nouvelles fonctionnalités du sprint 12 :
1. Filtrage des fichiers cachés macOS (._*) dans corpus et ZIP
2. Profils de normalisation avec exclusion de caractères
3. Vue Analyses — Chart.js inline (plus de CDN)
4. Métriques robustes dans le rapport HTML
"""
from __future__ import annotations
import io
import zipfile
import pytest
# ---------------------------------------------------------------------------
# 1. Filtrage des fichiers cachés macOS
# ---------------------------------------------------------------------------
FAKE_PNG = (
b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01"
b"\x00\x00\x00\x01\x08\x02\x00\x00\x00\x90wS\xde\x00\x00"
b"\x00\x0cIDATx\x9cc\xf8\x0f\x00\x00\x01\x01\x00\x05\x18"
b"\xd8N\x00\x00\x00\x00IEND\xaeB`\x82"
)
class TestMacOSHiddenFilesFiltering:
def test_hidden_images_ignored_in_corpus(self, tmp_path):
"""Les fichiers ._* ne doivent pas être comptés comme images valides."""
from picarones.core.corpus import load_corpus_from_directory
# Image réelle avec GT
(tmp_path / "page_001.png").write_bytes(FAKE_PNG)
(tmp_path / "page_001.gt.txt").write_text("Texte réel", encoding="utf-8")
# Fichiers AppleDouble macOS (sans GT associé)
(tmp_path / "._page_001.png").write_bytes(b"\x00\x05\x16\x07")
(tmp_path / ".DS_Store").write_bytes(b"\x00\x00\x00\x01Bud1")
corpus = load_corpus_from_directory(tmp_path)
assert len(corpus) == 1
assert corpus.documents[0].doc_id == "page_001"
def test_hidden_files_not_extracted_from_zip(self, tmp_path):
"""_flatten_zip_to_dir doit ignorer les entrées ._* dans le ZIP."""
from picarones.web.app import _flatten_zip_to_dir
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w") as zf:
zf.writestr("page_001.png", FAKE_PNG)
zf.writestr("page_001.gt.txt", "Texte réel")
zf.writestr("._page_001.png", b"\x00\x05\x16\x07")
zf.writestr("__MACOSX/._page_001.png", b"\x00\x05\x16\x07")
buf.seek(0)
dest = tmp_path / "corpus"
dest.mkdir()
with zipfile.ZipFile(buf) as zf:
_flatten_zip_to_dir(zf, dest)
files = {f.name for f in dest.iterdir()}
assert "._page_001.png" not in files
assert "page_001.png" in files
assert "page_001.gt.txt" in files
# ---------------------------------------------------------------------------
# 2. Profils de normalisation avec exclusion de caractères
# ---------------------------------------------------------------------------
class TestExcludeCharsNormalization:
def test_parse_exclude_chars_from_comma_string(self):
from picarones.core.normalization import _parse_exclude_chars
result = _parse_exclude_chars("', -, –")
assert "'" in result
assert "-" in result
assert "–" in result
def test_parse_exclude_chars_from_plain_string(self):
from picarones.core.normalization import _parse_exclude_chars
result = _parse_exclude_chars(".,;:!?")
assert "." in result
assert "," in result
assert "?" in result
def test_parse_exclude_chars_empty(self):
from picarones.core.normalization import _parse_exclude_chars
assert _parse_exclude_chars("") == frozenset()
assert _parse_exclude_chars(None) == frozenset()
def test_normalize_strips_excluded_chars(self):
from picarones.core.normalization import NormalizationProfile
profile = NormalizationProfile(
name="test",
exclude_chars=frozenset([".", ","]),
)
assert profile.normalize("Bonjour, monde.") == "Bonjour monde"
def test_sans_ponctuation_profile_exists(self):
from picarones.core.normalization import NORMALIZATION_PROFILES
assert "sans_ponctuation" in NORMALIZATION_PROFILES
p = NORMALIZATION_PROFILES["sans_ponctuation"]
assert "." in p.exclude_chars
assert "," in p.exclude_chars
assert "?" in p.exclude_chars
def test_sans_apostrophes_profile_exists(self):
from picarones.core.normalization import NORMALIZATION_PROFILES
assert "sans_apostrophes" in NORMALIZATION_PROFILES
p = NORMALIZATION_PROFILES["sans_apostrophes"]
assert "'" in p.exclude_chars
assert "\u2019" in p.exclude_chars # apostrophe typographique
def test_compute_metrics_with_char_exclude(self):
from picarones.core.metrics import compute_metrics
ref = "Bonjour, monde!"
hyp = "Bonjour monde"
# Sans exclusion, CER > 0 (virgule et ! manquants)
metrics_raw = compute_metrics(ref, hyp)
assert metrics_raw.cer > 0
# Avec exclusion de la ponctuation, les deux textes deviennent identiques
metrics_excl = compute_metrics(ref, hyp, char_exclude=frozenset([",", "!", " "]))
# CER devrait être 0 ou très faible maintenant (Bonjourmonde == Bonjourmonde)
assert metrics_excl.cer == 0.0
def test_char_exclude_propagated_in_run_benchmark(self, tmp_path):
"""char_exclude doit être transmis à run_benchmark et réduire le CER."""
from picarones.core.corpus import Corpus, Document
from picarones.core.runner import run_benchmark
from picarones.engines.base import BaseOCREngine, EngineResult
class MockEngine(BaseOCREngine):
name = "mock"
version = "0.0"
def _run_ocr(self, image_path):
return EngineResult(text="Bonjour monde", success=True)
doc = Document(image_path=tmp_path / "page.png", ground_truth="Bonjour, monde!")
(tmp_path / "page.png").write_bytes(FAKE_PNG)
corpus = Corpus(name="test", documents=[doc])
result_raw = run_benchmark(corpus, [MockEngine()])
cer_raw = result_raw.engine_reports[0].document_results[0].metrics.cer
result_excl = run_benchmark(corpus, [MockEngine()], char_exclude=frozenset([",", "!"]))
cer_excl = result_excl.engine_reports[0].document_results[0].metrics.cer
assert cer_excl <= cer_raw
# ---------------------------------------------------------------------------
# 3. Vue Analyses — Chart.js inline
# ---------------------------------------------------------------------------
class TestChartJsInline:
def test_chartjs_embedded_inline(self, sample_generator, tmp_path):
"""Le rapport HTML doit embarquer Chart.js inline (pas de CDN)."""
out = tmp_path / "rapport.html"
sample_generator.generate(out)
html = out.read_text(encoding="utf-8")
assert "cdnjs.cloudflare.com/ajax/libs/Chart.js" not in html
assert "Chart.js v" in html or "new Chart(" in html
def test_no_diff2html_cdn(self, sample_generator, tmp_path):
"""Le rapport ne doit plus référencer diff2html (CDN supprimé)."""
out = tmp_path / "rapport.html"
sample_generator.generate(out)
html = out.read_text(encoding="utf-8")
assert "diff2html" not in html
def test_build_charts_function_present(self, sample_generator, tmp_path):
out = tmp_path / "rapport.html"
sample_generator.generate(out)
html = out.read_text(encoding="utf-8")
assert "function buildCharts()" in html
assert "buildCerHistogram" in html
assert "buildRadar" in html
@pytest.fixture
def sample_generator():
"""Fixture partagée : crée un ReportGenerator avec des données fictives."""
from picarones.report.generator import ReportGenerator
from picarones.core.results import BenchmarkResult, DocumentResult, EngineReport
from picarones.core.metrics import MetricsResult
def _make_metric(cer=0.1):
return MetricsResult(
cer=cer, cer_nfc=cer, cer_caseless=cer,
wer=cer, wer_normalized=cer, mer=cer, wil=cer,
reference_length=100, hypothesis_length=100,
)
docs = [
DocumentResult(
doc_id=f"doc_{i}", image_path="", ground_truth="GT text",
hypothesis="Hyp text", metrics=_make_metric(0.1 + i * 0.01),
duration_seconds=0.1,
)
for i in range(3)
]
report = EngineReport(engine_name="tesseract", engine_version="5.0", engine_config={}, document_results=docs)
bm = BenchmarkResult(
corpus_name="TestCorpus", corpus_source=None, document_count=3,
engine_reports=[report],
)
return ReportGenerator(bm)
# ---------------------------------------------------------------------------
# 4. Métriques robustes — présence dans le rapport HTML
# ---------------------------------------------------------------------------
class TestRobustMetrics:
def test_robust_metrics_card_present(self, sample_generator, tmp_path):
"""La carte Métriques robustes doit être présente dans le rapport."""
out = tmp_path / "rapport.html"
sample_generator.generate(out)
html = out.read_text(encoding="utf-8")
assert "robust-metrics-card" in html
assert "robust-anchor" in html
assert "robust-ratio" in html
assert "renderRobustMetrics" in html
def test_robust_metrics_js_syntax_valid(self, sample_generator, tmp_path):
"""La fonction renderRobustMetrics ne doit pas introduire de SyntaxError JS."""
import re
import subprocess
out = tmp_path / "rapport.html"
sample_generator.generate(out)
html = out.read_text(encoding="utf-8")
scripts = re.findall(r"<script>(.*?)</script>", html, re.DOTALL)
# Le bloc applicatif est le dernier script
app_js = tmp_path / "app.js"
app_js.write_text(scripts[-1], encoding="utf-8")
result = subprocess.run(
["node", "--check", str(app_js)],
capture_output=True, text=True,
)
assert result.returncode == 0, f"Erreur JS : {result.stderr}"
|