Compare commits

..
5 changed files with 41 additions and 64 deletions

No files matched your search

+3 -8
View File
@@ -106,10 +106,6 @@ if TYPE_CHECKING:
logger = logging.getLogger("paperless.serializers") logger = logging.getLogger("paperless.serializers")
# How much of an upload is read to detect its type. libmagic examines at most
# 7 MiB (its default bytes_max), so this is more than it will ever look at.
_MIME_SNIFF_BYTES = 8 * 1024 * 1024
# https://www.django-rest-framework.org/api-guide/serializers/#example # https://www.django-rest-framework.org/api-guide/serializers/#example
class DynamicFieldsModelSerializer(serializers.ModelSerializer[Any]): class DynamicFieldsModelSerializer(serializers.ModelSerializer[Any]):
@@ -2310,9 +2306,8 @@ class PostDocumentSerializer(serializers.Serializer[dict[str, Any]]):
) )
def validate_document(self, document): def validate_document(self, document):
# libmagic only examines a bounded prefix, so an upload of any size is document_data = document.file.read()
# never read into memory just to detect its type mime_type = magic.from_buffer(document_data, mime=True)
mime_type = magic.from_buffer(document.read(_MIME_SNIFF_BYTES), mime=True)
if not is_mime_type_supported(mime_type): if not is_mime_type_supported(mime_type):
if ( if (
@@ -2328,7 +2323,7 @@ class PostDocumentSerializer(serializers.Serializer[dict[str, Any]]):
_("File type %(type)s not supported") % {"type": mime_type}, _("File type %(type)s not supported") % {"type": mime_type},
) )
return document.name, document return document.name, document_data
def validate_correspondent(self, correspondent): def validate_correspondent(self, correspondent):
if correspondent: if correspondent:
-32
View File
@@ -2089,38 +2089,6 @@ class TestDocumentApi(DirectoriesMixin, ConsumeTaskMixin, APITestCase):
self.assertIsNone(overrides.document_type_id) self.assertIsNone(overrides.document_type_id)
self.assertIsNone(overrides.tag_ids) self.assertIsNone(overrides.tag_ids)
def test_upload_type_is_detected_from_a_prefix(self) -> None:
"""
GIVEN:
- An upload larger than the prefix read to detect its type
WHEN:
- The document is posted
THEN:
- The type is detected from the prefix and the upload is accepted
- The file handed to the consumer holds the whole upload
"""
self.consume_file_mock.return_value = celery.result.AsyncResult(
id=str(uuid.uuid4()),
)
content = SIMPLE_DIGITAL_PDF.read_bytes()
with (
mock.patch("documents.serialisers._MIME_SNIFF_BYTES", 1024),
SimpleUploadedFile(
"simple.pdf",
content,
content_type="application/pdf",
) as f,
):
response = self.client.post(
"/api/documents/post_document/",
{"document": f},
)
self.assertEqual(response.status_code, status.HTTP_200_OK)
input_doc, _ = self.assert_queue_consumption_task_call_args()
self.assertEqual(input_doc.original_file.read_bytes(), content)
def test_upload_with_path_traversal_filename_is_reduced_to_basename(self) -> None: def test_upload_with_path_traversal_filename_is_reduced_to_basename(self) -> None:
self.consume_file_mock.return_value = celery.result.AsyncResult( self.consume_file_mock.return_value = celery.result.AsyncResult(
id=str(uuid.uuid4()), id=str(uuid.uuid4()),
+4 -8
View File
@@ -2189,7 +2189,7 @@ class DocumentViewSet(
raise Http404 raise Http404
try: try:
doc_name, doc_file = serializer.validated_data.get("document") doc_name, doc_data = serializer.validated_data.get("document")
version_label = serializer.validated_data.get("version_label") version_label = serializer.validated_data.get("version_label")
t = int(mktime(datetime.now().timetuple())) t = int(mktime(datetime.now().timetuple()))
@@ -2200,9 +2200,7 @@ class DocumentViewSet(
pathvalidate.sanitize_filename(doc_name), pathvalidate.sanitize_filename(doc_name),
) )
with temp_file_path.open("wb") as scratch_file: temp_file_path.write_bytes(doc_data)
for chunk in doc_file.chunks():
scratch_file.write(chunk)
os.utime(temp_file_path, times=(t, t)) os.utime(temp_file_path, times=(t, t))
@@ -3340,7 +3338,7 @@ class PostDocumentView(GenericAPIView[Any]):
serializer = self.get_serializer(data=request.data) serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True) serializer.is_valid(raise_exception=True)
doc_name, doc_file = serializer.validated_data.get("document") doc_name, doc_data = serializer.validated_data.get("document")
doc_name = normalize("NFC", doc_name) doc_name = normalize("NFC", doc_name)
correspondent_id = serializer.validated_data.get("correspondent") correspondent_id = serializer.validated_data.get("correspondent")
document_type_id = serializer.validated_data.get("document_type") document_type_id = serializer.validated_data.get("document_type")
@@ -3360,9 +3358,7 @@ class PostDocumentView(GenericAPIView[Any]):
pathvalidate.sanitize_filename(doc_name), pathvalidate.sanitize_filename(doc_name),
) )
with temp_file_path.open("wb") as scratch_file: temp_file_path.write_bytes(doc_data)
for chunk in doc_file.chunks():
scratch_file.write(chunk)
os.utime(temp_file_path, times=(t, t)) os.utime(temp_file_path, times=(t, t))
+18
View File
@@ -12,6 +12,11 @@ from paperless.utils import ocr_to_dateparser_languages
pytest.param("eng", ["en"], id="single-language"), pytest.param("eng", ["en"], id="single-language"),
pytest.param("fra+ita+lao", ["fr", "it", "lo"], id="multiple-languages"), pytest.param("fra+ita+lao", ["fr", "it", "lo"], id="multiple-languages"),
pytest.param("fil", ["fil"], id="no-two-letter-equivalent"), 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( pytest.param(
"aze_cyrl+srp_latn", "aze_cyrl+srp_latn",
["az-Cyrl", "sr-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) 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( def test_ocr_to_dateparser_languages_exception(
monkeypatch: pytest.MonkeyPatch, monkeypatch: pytest.MonkeyPatch,
caplog: pytest.LogCaptureFixture, caplog: pytest.LogCaptureFixture,
+16 -16
View File
@@ -2,19 +2,18 @@ import logging
logger = logging.getLogger("paperless.utils") 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 = { OCR_TO_DATEPARSER_LANGUAGES = {
""" # These dateparser languages have no equivalent in any Tesseract release
Translation map from languages supported by Tesseract OCR # (checked against tessdata, tessdata_best and tessdata_fast), so they cannot
to languages supported by dateparser. # be reached from the OCR language. Set PAPERLESS_DATE_PARSER_LANGUAGES to use them:
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:
# agq, asa, bez, brx, cgg, ckb, dav, dje, dyo, ebu, guz, jgo, jmc, kde, kea, khq, kln, # 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, # 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 # 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", "amh": "am",
"ara": "ar", "ara": "ar",
"asm": "as", "asm": "as",
"ast": "ast",
"aze": "az", "aze": "az",
"bel": "be", "bel": "be",
"bul": "bg", "bul": "bg",
@@ -31,7 +29,7 @@ OCR_TO_DATEPARSER_LANGUAGES = {
"bre": "br", "bre": "br",
"bos": "bs", "bos": "bs",
"cat": "ca", "cat": "ca",
"cher": "chr", "chr": "chr",
"ces": "cs", "ces": "cs",
"cym": "cy", "cym": "cy",
"dan": "da", "dan": "da",
@@ -65,19 +63,21 @@ OCR_TO_DATEPARSER_LANGUAGES = {
"kat": "ka", "kat": "ka",
"kaz": "kk", "kaz": "kk",
"khm": "km", "khm": "km",
"knda": "kn", "kan": "kn",
"kor": "ko", "kor": "ko",
"kir": "ky", "kir": "ky",
"ltz": "lb", "ltz": "lb",
"lao": "lo", "lao": "lo",
"lit": "lt", "lit": "lt",
"lav": "lv", "lav": "lv",
"mkd": "mk",
"mal": "ml", "mal": "ml",
"mon": "mn", "mon": "mn",
"mar": "mr", "mar": "mr",
"msa": "ms", "msa": "ms",
"mlt": "mt", "mlt": "mt",
"mya": "my", "mya": "my",
"nor": "nb",
"nep": "ne", "nep": "ne",
"nld": "nl", "nld": "nl",
"ori": "or", "ori": "or",
@@ -106,7 +106,7 @@ OCR_TO_DATEPARSER_LANGUAGES = {
"ukr": "uk", "ukr": "uk",
"urd": "ur", "urd": "ur",
"uzb": "uz", "uzb": "uz",
"via": "vi", "vie": "vi", # codespell:ignore
"yid": "yi", "yid": "yi",
"yor": "yo", "yor": "yo",
"chi": "zh", "chi": "zh",