Compare commits

..
4 changed files with 61 additions and 82 deletions

No files matched your search

+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",
@@ -1256,36 +1256,3 @@ class TestIndexPageSize:
assert page_size_of(legacy_page_size_db) == DB_PAGE_SIZE
assert DocumentChunksTable.count(store.client) == 2
def test_open_connection_closes_connection_when_setup_fails(
tmp_path: Path,
mocker: MockerFixture,
) -> None:
"""
GIVEN a table setup step that fails after the connection was opened
WHEN the store is created
THEN the setup error propagates
AND the connection that was opened is closed, not leaked
"""
opened: list[sqlite3.Connection] = []
real_connect = sqlite3.connect
def recording_connect(*args, **kwargs) -> sqlite3.Connection:
conn = real_connect(*args, **kwargs)
opened.append(conn)
return conn
mocker.patch("paperless_ai.vector_store.sqlite3.connect", recording_connect)
mocker.patch.object(
DocumentMetaTable,
"create",
side_effect=RuntimeError("setup failed"),
)
with pytest.raises(RuntimeError, match="setup failed"):
PaperlessSqliteVecVectorStore(uri=str(tmp_path))
assert len(opened) == 1
with pytest.raises(sqlite3.ProgrammingError):
opened[0].execute("SELECT 1")
+27 -33
View File
@@ -4,7 +4,6 @@ import sqlite3
import struct
from collections.abc import Iterator
from collections.abc import Sequence
from contextlib import ExitStack
from contextlib import contextmanager
from pathlib import Path
from types import TracebackType
@@ -213,38 +212,33 @@ class PaperlessSqliteVecVectorStore(BasePydanticVectorStore):
@staticmethod
def _open_connection(db_path: str) -> sqlite3.Connection:
with ExitStack() as stack:
conn = sqlite3.connect(
db_path,
timeout=30,
isolation_level=None, # autocommit; explicit transactions below
)
# Closes the connection (and its WAL/SHM handles) if any setup step
# below raises. pop_all() disarms it once setup has succeeded.
stack.callback(conn.close)
conn.row_factory = sqlite3.Row
conn.enable_load_extension(True) # noqa: FBT003
sqlite_vec.load(conn)
conn.enable_load_extension(False) # noqa: FBT003
conn.execute(f"PRAGMA page_size={DB_PAGE_SIZE}")
conn.execute("PRAGMA journal_mode=WAL")
conn.execute("PRAGMA synchronous=NORMAL")
IndexMetaTable.create(conn)
# vec0 metadata columns only get an efficient lookup path inside a
# KNN (MATCH) query; a plain `WHERE document_id = ?` is a full table
# scan regardless of index size. This plain, indexed table is how
# delete()/upsert_document() find a document's chunk ids without
# that scan.
DocumentChunksTable.create(conn)
# modified used to be a vec0 metadata column, but vec0 only inlines
# TEXT metadata up to 12 bytes -- an ISO timestamp is always longer,
# so every read recompiled and stepped a fresh SQL statement per row.
# It was never filtered on inside a KNN query either, so it never
# needed to be a vec0 column at all. One row per document here (not
# per chunk, like document_chunks), since every chunk of a document
# shares the same modified value -- see get_modified_times().
DocumentMetaTable.create(conn)
stack.pop_all()
conn = sqlite3.connect(
db_path,
timeout=30,
isolation_level=None, # autocommit; explicit transactions below
)
conn.row_factory = sqlite3.Row
conn.enable_load_extension(True) # noqa: FBT003
sqlite_vec.load(conn)
conn.enable_load_extension(False) # noqa: FBT003
conn.execute(f"PRAGMA page_size={DB_PAGE_SIZE}")
conn.execute("PRAGMA journal_mode=WAL")
conn.execute("PRAGMA synchronous=NORMAL")
IndexMetaTable.create(conn)
# vec0 metadata columns only get an efficient lookup path inside a
# KNN (MATCH) query; a plain `WHERE document_id = ?` is a full table
# scan regardless of index size. This plain, indexed table is how
# delete()/upsert_document() find a document's chunk ids without
# that scan.
DocumentChunksTable.create(conn)
# modified used to be a vec0 metadata column, but vec0 only inlines
# TEXT metadata up to 12 bytes -- an ISO timestamp is always longer,
# so every read recompiled and stepped a fresh SQL statement per row.
# It was never filtered on inside a KNN query either, so it never
# needed to be a vec0 column at all. One row per document here (not
# per chunk, like document_chunks), since every chunk of a document
# shares the same modified value -- see get_modified_times().
DocumentMetaTable.create(conn)
return conn
@property