Compare commits

..
4 changed files with 43 additions and 110 deletions

No files matched your search

+9 -16
View File
@@ -1,7 +1,6 @@
from __future__ import annotations
import abc
import filecmp
import hashlib
import json
import os
@@ -167,18 +166,11 @@ class DirectoryExportSink(ExportSink):
@staticmethod
def _content_unchanged(target: Path, new_bytes: bytes) -> bool:
"""
True if ``target`` already holds byte-identical content (BLAKE2b).
The existing file is hashed in chunks rather than read into memory.
"""
if target.stat().st_size != len(new_bytes):
return False
with target.open("rb") as handle:
return (
hashlib.file_digest(handle, "blake2b").hexdigest()
== hashlib.blake2b(new_bytes).hexdigest()
)
"""True if ``target`` already holds byte-identical content (BLAKE2b)."""
return (
hashlib.blake2b(target.read_bytes()).hexdigest()
== hashlib.blake2b(new_bytes).hexdigest()
)
def add_json(self, content: list | dict, arcname: str) -> None:
target = (self._target / arcname).resolve()
@@ -222,9 +214,10 @@ class DirectoryExportSink(ExportSink):
def _commit_streamed_file(self, target: Path, tmp: Path) -> None:
if target in self._snapshot:
self._snapshot.discard(target)
# A streamed manifest can be very large, so compare the two files
# in chunks instead of reading them into memory
if self._compare_json and filecmp.cmp(target, tmp, shallow=False):
if self._compare_json and self._content_unchanged(
target,
tmp.read_bytes(),
):
tmp.unlink()
return
tmp.rename(target)
-78
View File
@@ -91,84 +91,6 @@ class TestDirectoryExportSink:
writer.close()
assert json.loads((target / "manifest.json").read_text()) == [{"pk": 1}]
@pytest.mark.parametrize(
("existing", "unchanged"),
[
pytest.param(_dumps({"version": "x"}), True, id="identical"),
pytest.param(_dumps({"version": "y"}), False, id="same-size-different"),
],
)
def test_add_json_compare_json(
self,
tmp_path: Path,
*,
existing: str,
unchanged: bool,
) -> None:
target: Path = tmp_path / "out"
target.mkdir()
(target / "metadata.json").write_text(existing)
os.utime(target / "metadata.json", (1, 1))
with DirectoryExportSink(
target,
compare_checksums=False,
compare_json=True,
delete=False,
) as sink:
sink.add_json({"version": "x"}, "metadata.json")
assert json.loads((target / "metadata.json").read_text()) == (
json.loads(existing) if unchanged else {"version": "x"}
)
# An unchanged file is not rewritten, so its mtime is left alone
assert ((target / "metadata.json").stat().st_mtime == 1) is unchanged
@pytest.mark.parametrize(
("existing", "unchanged"),
[
pytest.param([{"pk": 1}], True, id="identical"),
pytest.param([{"pk": 2}], False, id="changed"),
],
)
def test_stream_compare_json(
self,
tmp_path: Path,
*,
existing: list[dict],
unchanged: bool,
) -> None:
target: Path = tmp_path / "out"
target.mkdir()
# Write the existing manifest the same way the sink does
with DirectoryExportSink(
target,
compare_checksums=False,
compare_json=False,
delete=False,
) as sink:
with sink.stream("manifest.json") as handle:
writer: StreamingManifestWriter = StreamingManifestWriter(handle)
for record in existing:
writer.write_record(record)
writer.close()
os.utime(target / "manifest.json", (1, 1))
with DirectoryExportSink(
target,
compare_checksums=False,
compare_json=True,
delete=False,
) as sink:
with sink.stream("manifest.json") as handle:
writer = StreamingManifestWriter(handle)
writer.write_record({"pk": 1})
writer.close()
assert json.loads((target / "manifest.json").read_text()) == (
existing if unchanged else [{"pk": 1}]
)
assert ((target / "manifest.json").stat().st_mtime == 1) is unchanged
assert not (target / "manifest.json.tmp").exists()
def test_add_file_skips_when_size_and_mtime_match(
self,
tmp_path: Path,
+18
View File
@@ -12,6 +12,11 @@ from paperless.utils import ocr_to_dateparser_languages
pytest.param("eng", ["en"], id="single-language"),
pytest.param("fra+ita+lao", ["fr", "it", "lo"], id="multiple-languages"),
pytest.param("fil", ["fil"], id="no-two-letter-equivalent"),
pytest.param(
"afr+vie+kan+chr+mkd", # codespell:ignore
["af", "vi", "kn", "chr", "mk"],
id="previously-unmapped-languages",
),
pytest.param(
"aze_cyrl+srp_latn",
["az-Cyrl", "sr-Latn"],
@@ -49,6 +54,19 @@ def test_ocr_to_dateparser_languages(ocr_language: str, expected: list[str]) ->
assert sorted(ocr_to_dateparser_languages(ocr_language)) == sorted(expected)
def test_ocr_to_dateparser_map_values_supported_by_dateparser() -> None:
from dateparser.languages.loader import LocaleDataLoader
loader = LocaleDataLoader()
unsupported = []
for ocr_code, dateparser_code in utils.OCR_TO_DATEPARSER_LANGUAGES.items():
try:
loader.get_locale_map(locales=[dateparser_code])
except Exception:
unsupported.append((ocr_code, dateparser_code))
assert unsupported == []
def test_ocr_to_dateparser_languages_exception(
monkeypatch: pytest.MonkeyPatch,
caplog: pytest.LogCaptureFixture,
+16 -16
View File
@@ -2,19 +2,18 @@ import logging
logger = logging.getLogger("paperless.utils")
# Translation map from languages supported by Tesseract OCR
# to languages supported by dateparser.
# To add a language, make sure it is supported by both libraries.
# The ISO 639-2 will help you link a 3-char to 2-char language code.
# Links:
# - Tesseract languages: https://tesseract-ocr.github.io/tessdoc/Data-Files-in-different-versions.html
# - Python dateparser languages: https://dateparser.readthedocs.io/en/latest/supported_locales.html
# - ISO 639-2: https://www.loc.gov/standards/iso639-2/php/code_list.php
OCR_TO_DATEPARSER_LANGUAGES = {
"""
Translation map from languages supported by Tesseract OCR
to languages supported by dateparser.
To add a language, make sure it is supported by both libraries.
The ISO 639-2 will help you link a 3-char to 2-char language code.
Links:
- Tesseract languages: https://tesseract-ocr.github.io/tessdoc/Data-Files-in-different-versions.html
- Python dateparser languages: https://dateparser.readthedocs.io/en/latest/supported_locales.html
- ISO 639-2: https://www.loc.gov/standards/iso639-2/php/code_list.php
"""
# TODO check these Dateparser languages as they are not referenced on the ISO639-2 standard,
# so we didn't find the equivalent in Tesseract:
# These dateparser languages have no equivalent in any Tesseract release
# (checked against tessdata, tessdata_best and tessdata_fast), so they cannot
# be reached from the OCR language. Set PAPERLESS_DATE_PARSER_LANGUAGES to use them:
# agq, asa, bez, brx, cgg, ckb, dav, dje, dyo, ebu, guz, jgo, jmc, kde, kea, khq, kln,
# ksb, ksf, ksh, lag, lkt, lrc, luy, mer, mfe, mgh, mgo, mua, mzn, naq, nmg, nnh, nus,
# rof, rwk, saq, sbp, she, ses, shi, teo, twq, tzm, vun, wae, xog, yav, yue
@@ -22,7 +21,6 @@ OCR_TO_DATEPARSER_LANGUAGES = {
"amh": "am",
"ara": "ar",
"asm": "as",
"ast": "ast",
"aze": "az",
"bel": "be",
"bul": "bg",
@@ -31,7 +29,7 @@ OCR_TO_DATEPARSER_LANGUAGES = {
"bre": "br",
"bos": "bs",
"cat": "ca",
"cher": "chr",
"chr": "chr",
"ces": "cs",
"cym": "cy",
"dan": "da",
@@ -65,19 +63,21 @@ OCR_TO_DATEPARSER_LANGUAGES = {
"kat": "ka",
"kaz": "kk",
"khm": "km",
"knda": "kn",
"kan": "kn",
"kor": "ko",
"kir": "ky",
"ltz": "lb",
"lao": "lo",
"lit": "lt",
"lav": "lv",
"mkd": "mk",
"mal": "ml",
"mon": "mn",
"mar": "mr",
"msa": "ms",
"mlt": "mt",
"mya": "my",
"nor": "nb",
"nep": "ne",
"nld": "nl",
"ori": "or",
@@ -106,7 +106,7 @@ OCR_TO_DATEPARSER_LANGUAGES = {
"ukr": "uk",
"urd": "ur",
"uzb": "uz",
"via": "vi",
"vie": "vi", # codespell:ignore
"yid": "yi",
"yor": "yo",
"chi": "zh",