A fast, helpful, and open-source document parser
chore: dry refactor
Clelia (Astra) Bertelli3c857e935439
diff --git a/packages/python/liteparse/parser.py b/packages/python/liteparse/parser.pyindex 4b3fcfa..ba6e210 100644--- a/packages/python/liteparse/parser.py+++ b/packages/python/liteparse/parser.py@@ -7,7 +7,7 @@ import shutilimport subprocessimport tempfilefrom pathlib import Path-from typing import List, Optional, Union+from typing import Any, List, Literal, Optional, Union, castfrom .types import (BatchResult,@@ -225,10 +225,136 @@ class LiteParse:self._cli_path = _find_cli()return self._cli_path+ def _prepare_command(+ self,+ subcommand: Literal["parse", "batch-parse", "screenshot"],+ *positional: Any,+ **options: Any,+ ) -> list[str]:+ cmd_parts = self.cli_path.split()+ cmd = cmd_parts + [subcommand, *positional]+ if subcommand == "parse":+ cmd.extend(_build_parse_cli_args(**options))+ elif subcommand == "batch-parse":+ cmd.extend(_build_batch_cli_args(**options))+ return cmd++ @staticmethod+ def _extract_path_and_bytes(+ file_data: Union[str, Path, bytes],+ ) -> tuple[str, Union[bytes, None]]:+ if not isinstance(file_data, bytes):+ file_path = Path(file_data)+ if not file_path.exists():+ raise FileNotFoundError(f"File not found: {file_path}")+ file_path = str(file_path.absolute())+ file_bytes = None+ else:+ file_path = "-"+ file_bytes = file_data+ return file_path, file_bytes++ @staticmethod+ def _extract_batch_params(+ input_dir: Union[str, Path],+ output_dir: Union[str, Path],+ output_format: Union[OutputFormat, str],+ ) -> tuple[Path, Path, OutputFormat]:+ indir = Path(input_dir)+ outdir = Path(output_dir)++ if not indir.exists():+ raise FileNotFoundError(f"Input directory not found: {input_dir}")++ if isinstance(output_format, str):+ output_format = OutputFormat(output_format)++ return indir, outdir, output_format++ @staticmethod+ def _extract_screenshot_params(+ file_path: Union[str, Path],+ image_format: Union[ImageFormat, str],+ output_dir: Union[str, Path, None],+ ) -> tuple[Path, ImageFormat, Path]:+ file_path = Path(file_path)+ if not file_path.exists():+ raise FileNotFoundError(f"File not found: {file_path}")++ if isinstance(image_format, str):+ image_format = ImageFormat(image_format)++ # Use temp dir if output_dir not provided+ if output_dir is None:+ output_dir = Path(tempfile.mkdtemp(prefix="liteparse_screenshots_"))+ else:+ output_dir = Path(output_dir)+ output_dir.mkdir(parents=True, exist_ok=True)+ return file_path, image_format, output_dir++ @staticmethod+ def _get_parse_result(+ returncode: int,+ stdout: bytes,+ stderr: bytes,+ ) -> ParseResult:+ if returncode != 0:+ raise ParseError(+ f"Parsing failed with exit code {returncode}",+ stderr=stderr.decode("utf-8"),+ )+ try:+ json_data = json.loads(stdout.decode("utf-8"))+ return _parse_json_result(json_data)+ except json.JSONDecodeError as e:+ raise ParseError(f"Failed to parse CLI output: {e}")++ @staticmethod+ def _get_screenshot_result(+ returncode: int,+ stderr: str,+ output_dir: Path,+ image_format: ImageFormat,+ load_bytes: bool,+ ) -> ScreenshotBatchResult:+ if returncode != 0:+ raise ParseError(+ f"Screenshot generation failed with exit code {returncode}",+ stderr=stderr,+ )+ screenshots: List[ScreenshotResult] = []+ ext = f".{image_format.value}"++ for img_file in sorted(output_dir.glob(f"*{ext}")):+ # Parse page number from filename (page_N.png)+ filename = img_file.stem+ if filename.startswith("page_"):+ try:+ page_num = int(filename.replace("page_", ""))+ except ValueError:+ continue++ # Optionally load bytes+ image_bytes = None+ if load_bytes:+ image_bytes = img_file.read_bytes()++ screenshots.append(+ ScreenshotResult(+ page_num=page_num,+ image_path=str(img_file),+ image_bytes=image_bytes,+ )+ )++ return ScreenshotBatchResult(+ screenshots=screenshots,+ output_dir=str(output_dir),+ )+def parse(self,- file_path: Union[str, Path, None] = None,- file_bytes: Union[bytes, None] = None,+ file_data: Union[str, Path, bytes],*,ocr_enabled: bool = True,ocr_server_url: Optional[str] = None,@@ -268,32 +394,23 @@ class LiteParse:FileNotFoundError: If the file doesn't existTimeoutError: If parsing times out"""- if file_path is not None:- file_path = Path(file_path)- if not file_path.exists():- raise FileNotFoundError(f"File not found: {file_path}")- file_path = str(file_path.absolute())- elif file_bytes is not None:- file_path = "-"- else:- raise ValueError("One of `file_path` or `file_bytes` should be provided")++ file_path, file_bytes = self._extract_path_and_bytes(file_data)# Build command- cmd_parts = self.cli_path.split()- cmd = cmd_parts + ["parse", file_path]- cmd.extend(- _build_parse_cli_args(- ocr_enabled=ocr_enabled,- ocr_server_url=ocr_server_url,- ocr_language=ocr_language,- num_workers=num_workers,- max_pages=max_pages,- target_pages=target_pages,- dpi=dpi,- precise_bounding_box=precise_bounding_box,- preserve_very_small_text=preserve_very_small_text,- password=password,- )+ cmd = self._prepare_command(+ "parse",+ file_path,+ ocr_enabled=ocr_enabled,+ ocr_server_url=ocr_server_url,+ ocr_language=ocr_language,+ num_workers=num_workers,+ max_pages=max_pages,+ target_pages=target_pages,+ dpi=dpi,+ precise_bounding_box=precise_bounding_box,+ preserve_very_small_text=preserve_very_small_text,+ password=password,)try:@@ -305,25 +422,16 @@ class LiteParse:input=file_bytes,)- if result.returncode != 0:- raise ParseError(- f"Parsing failed with exit code {result.returncode}",- stderr=result.stderr.decode("utf-8"),- )-- # Parse JSON output- json_data = json.loads(result.stdout.decode("utf-8"))- return _parse_json_result(json_data)+ return self._get_parse_result(+ result.returncode, result.stdout, result.stderr+ )except subprocess.TimeoutExpired:raise TimeoutError(f"Parsing timed out after {timeout} seconds")- except json.JSONDecodeError as e:- raise ParseError(f"Failed to parse CLI output: {e}")async def parse_async(self,- file_path: Union[str, Path, None] = None,- file_bytes: Union[bytes, None] = None,+ file_data: Union[str, Path, bytes],*,ocr_enabled: bool = True,ocr_server_url: Optional[str] = None,@@ -363,32 +471,22 @@ class LiteParse:FileNotFoundError: If the file doesn't existTimeoutError: If parsing times out"""- if file_path is not None:- file_path = Path(file_path)- if not file_path.exists():- raise FileNotFoundError(f"File not found: {file_path}")- file_path = str(file_path.absolute())- elif file_bytes is not None:- file_path = "-"- else:- raise ValueError("One of `file_path` or `file_bytes` should be provided")+ file_path, file_bytes = self._extract_path_and_bytes(file_data)# Build command- cmd_parts = self.cli_path.split()- cmd = cmd_parts + ["parse", file_path]- cmd.extend(- _build_parse_cli_args(- ocr_enabled=ocr_enabled,- ocr_server_url=ocr_server_url,- ocr_language=ocr_language,- num_workers=num_workers,- max_pages=max_pages,- target_pages=target_pages,- dpi=dpi,- precise_bounding_box=precise_bounding_box,- preserve_very_small_text=preserve_very_small_text,- password=password,- )+ cmd = self._prepare_command(+ "parse",+ file_path,+ ocr_enabled=ocr_enabled,+ ocr_server_url=ocr_server_url,+ ocr_language=ocr_language,+ num_workers=num_workers,+ max_pages=max_pages,+ target_pages=target_pages,+ dpi=dpi,+ precise_bounding_box=precise_bounding_box,+ preserve_very_small_text=preserve_very_small_text,+ password=password,)try:@@ -403,20 +501,10 @@ class LiteParse:process.communicate(input=file_bytes), timeout=timeout)- if process.returncode != 0:- raise ParseError(- f"Parsing failed with exit code {process.returncode}",- stderr=stderr.decode("utf-8"),- )-- # Parse JSON output- json_data = json.loads(stdout.decode("utf-8"))- return _parse_json_result(json_data)+ return self._get_parse_result(cast(int, process.returncode), stdout, stderr)except TimeoutError:raise TimeoutError(f"Parsing timed out after {timeout} seconds")- except json.JSONDecodeError as e:- raise ParseError(f"Failed to parse CLI output: {e}")def batch_parse(self,@@ -465,36 +553,27 @@ class LiteParse:FileNotFoundError: If the input directory doesn't existTimeoutError: If the batch operation times out"""- input_dir = Path(input_dir)- output_dir = Path(output_dir)- if not input_dir.exists():- raise FileNotFoundError(f"Input directory not found: {input_dir}")-- if isinstance(output_format, str):- output_format = OutputFormat(output_format)+ input_dir, output_dir, output_format = self._extract_batch_params(+ input_dir, output_dir, output_format+ )# Build command- cmd_parts = self.cli_path.split()- cmd = cmd_parts + [+ cmd = self._prepare_command("batch-parse",str(input_dir.absolute()),str(output_dir.absolute()),- ]- cmd.extend(- _build_batch_cli_args(- output_format=output_format,- ocr_enabled=ocr_enabled,- ocr_server_url=ocr_server_url,- ocr_language=ocr_language,- num_workers=num_workers,- max_pages=max_pages,- dpi=dpi,- precise_bounding_box=precise_bounding_box,- recursive=recursive,- extension_filter=extension_filter,- password=password,- )+ output_format=output_format,+ ocr_enabled=ocr_enabled,+ ocr_server_url=ocr_server_url,+ ocr_language=ocr_language,+ num_workers=num_workers,+ max_pages=max_pages,+ dpi=dpi,+ precise_bounding_box=precise_bounding_box,+ recursive=recursive,+ extension_filter=extension_filter,+ password=password,)try:@@ -558,36 +637,26 @@ class LiteParse:FileNotFoundError: If the input directory doesn't existTimeoutError: If the batch operation times out"""- input_dir = Path(input_dir)- output_dir = Path(output_dir)-- if not input_dir.exists():- raise FileNotFoundError(f"Input directory not found: {input_dir}")-- if isinstance(output_format, str):- output_format = OutputFormat(output_format)+ input_dir, output_dir, output_format = self._extract_batch_params(+ input_dir, output_dir, output_format+ )# Build command- cmd_parts = self.cli_path.split()- cmd = cmd_parts + [+ cmd = self._prepare_command("batch-parse",str(input_dir.absolute()),str(output_dir.absolute()),- ]- cmd.extend(- _build_batch_cli_args(- output_format=output_format,- ocr_enabled=ocr_enabled,- ocr_server_url=ocr_server_url,- ocr_language=ocr_language,- num_workers=num_workers,- max_pages=max_pages,- dpi=dpi,- precise_bounding_box=precise_bounding_box,- recursive=recursive,- extension_filter=extension_filter,- password=password,- )+ output_format=output_format,+ ocr_enabled=ocr_enabled,+ ocr_server_url=ocr_server_url,+ ocr_language=ocr_language,+ num_workers=num_workers,+ max_pages=max_pages,+ dpi=dpi,+ precise_bounding_box=precise_bounding_box,+ recursive=recursive,+ extension_filter=extension_filter,+ password=password,)try:@@ -634,23 +703,12 @@ class LiteParse:FileNotFoundError: If the file doesn't existTimeoutError: If the operation times out"""- file_path = Path(file_path)- if not file_path.exists():- raise FileNotFoundError(f"File not found: {file_path}")-- if isinstance(image_format, str):- image_format = ImageFormat(image_format)-- # Use temp dir if output_dir not provided- if output_dir is None:- output_dir = Path(tempfile.mkdtemp(prefix="liteparse_screenshots_"))- else:- output_dir = Path(output_dir)- output_dir.mkdir(parents=True, exist_ok=True)+ file_path, image_format, output_dir = self._extract_screenshot_params(+ file_path, image_format, output_dir+ )# Build command- cmd_parts = self.cli_path.split()- cmd = cmd_parts + [+ cmd = self._prepare_command("screenshot",str(file_path.absolute()),"-o",@@ -660,7 +718,7 @@ class LiteParse:"--dpi",str(dpi),"-q",- ]+ )if target_pages:cmd.extend(["--target-pages", target_pages])@@ -677,41 +735,12 @@ class LiteParse:check=False,)- if result.returncode != 0:- raise ParseError(- f"Screenshot generation failed with exit code {result.returncode}",- stderr=result.stderr,- )-- # Find generated screenshots- screenshots: List[ScreenshotResult] = []- ext = f".{image_format.value}"-- for img_file in sorted(output_dir.glob(f"*{ext}")):- # Parse page number from filename (page_N.png)- filename = img_file.stem- if filename.startswith("page_"):- try:- page_num = int(filename.replace("page_", ""))- except ValueError:- continue-- # Optionally load bytes- image_bytes = None- if load_bytes:- image_bytes = img_file.read_bytes()-- screenshots.append(- ScreenshotResult(- page_num=page_num,- image_path=str(img_file),- image_bytes=image_bytes,- )- )-- return ScreenshotBatchResult(- screenshots=screenshots,- output_dir=str(output_dir),+ return self._get_screenshot_result(+ result.returncode,+ result.stderr,+ output_dir,+ image_format,+ load_bytes,)except subprocess.TimeoutExpired:@@ -751,23 +780,12 @@ class LiteParse:FileNotFoundError: If the file doesn't existTimeoutError: If the operation times out"""- file_path = Path(file_path)- if not file_path.exists():- raise FileNotFoundError(f"File not found: {file_path}")-- if isinstance(image_format, str):- image_format = ImageFormat(image_format)-- # Use temp dir if output_dir not provided- if output_dir is None:- output_dir = Path(tempfile.mkdtemp(prefix="liteparse_screenshots_"))- else:- output_dir = Path(output_dir)- output_dir.mkdir(parents=True, exist_ok=True)+ file_path, image_format, output_dir = self._extract_screenshot_params(+ file_path, image_format, output_dir+ )# Build command- cmd_parts = self.cli_path.split()- cmd = cmd_parts + [+ cmd = self._prepare_command("screenshot",str(file_path.absolute()),"-o",@@ -777,7 +795,7 @@ class LiteParse:"--dpi",str(dpi),"-q",- ]+ )if target_pages:cmd.extend(["--target-pages", target_pages])@@ -788,45 +806,14 @@ class LiteParse:try:process = await asyncio.subprocess.create_subprocess_exec(cmd[0], *cmd[1:])- stdout, stderr = await asyncio.wait_for(- process.communicate(), timeout=timeout- )-- if process.returncode != 0:- raise ParseError(- f"Screenshot generation failed with exit code {process.returncode}",- stderr=stderr.decode("utf-8"),- )-- # Find generated screenshots- screenshots: List[ScreenshotResult] = []- ext = f".{image_format.value}"-- for img_file in sorted(output_dir.glob(f"*{ext}")):- # Parse page number from filename (page_N.png)- filename = img_file.stem- if filename.startswith("page_"):- try:- page_num = int(filename.replace("page_", ""))- except ValueError:- continue-- # Optionally load bytes- image_bytes = None- if load_bytes:- image_bytes = img_file.read_bytes()-- screenshots.append(- ScreenshotResult(- page_num=page_num,- image_path=str(img_file),- image_bytes=image_bytes,- )- )+ _, stderr = await asyncio.wait_for(process.communicate(), timeout=timeout)- return ScreenshotBatchResult(- screenshots=screenshots,- output_dir=str(output_dir),+ return self._get_screenshot_result(+ cast(int, process.returncode),+ (stderr or b"").decode("utf-8"),+ output_dir,+ image_format,+ load_bytes,)except TimeoutError:diff --git a/packages/python/tests/test_parse_e2e.py b/packages/python/tests/test_parse_e2e.pyindex 4546a91..11b9334 100644--- a/packages/python/tests/test_parse_e2e.py+++ b/packages/python/tests/test_parse_e2e.py@@ -38,7 +38,7 @@ class TestParseBasic:def test_parse_bytest_input(self, parser: LiteParse, invoice_pdf: Path):file_bytes = invoice_pdf.read_bytes()- result = parser.parse(file_bytes=file_bytes)+ result = parser.parse(file_bytes)assert result.json is not Noneassert "pages" in result.json@@ -51,7 +51,7 @@ class TestParseBasic:@pytest.mark.asyncioasync def test_parse_async_bytes_input(self, parser: LiteParse, invoice_pdf: Path):file_bytes = invoice_pdf.read_bytes()- result = await parser.parse_async(file_bytes=file_bytes)+ result = await parser.parse_async(file_bytes)assert result.json is not Noneassert "pages" in result.jsondiff --git a/packages/python/uv.lock b/packages/python/uv.lockindex e9de07c..fedb213 100644--- a/packages/python/uv.lock+++ b/packages/python/uv.lock@@ -128,7 +128,7 @@ wheels = [[[package]]name = "liteparse"-version = "1.0.1"+version = "1.0.2"source = { editable = "." }[package.optional-dependencies]