Verified Commit d41c1e83 authored by Jakob Moser's avatar Jakob Moser
Browse files

Avoid using temporary files

parent a5abeb3c
Loading
Loading
Loading
Loading
+26 −24
Original line number Diff line number Diff line
import csv
import subprocess
from pathlib import Path
from typing import Sequence
from tempfile import NamedTemporaryFile
from collections.abc import Sequence, Iterable


from .BudgetPlan import BudgetPlan
@@ -14,9 +13,8 @@ def _is_budgetary_item_row(row: Sequence[str]) -> bool:
    return len(row) >= 3 and row[0] and row[1] and row[2]


def load_csv(csv_path: Path | str) -> BudgetPlan:
    with open(csv_path, newline="") as f:
        reader = csv.reader(f)
def _load_csv_lines(csv_lines: Iterable[str]) -> BudgetPlan:
    reader = csv.reader(csv_lines)
    items = [
        BudgetaryItem(id=row[0], name=row[1], amount=parse_euro_amount(row[2]))
        for row in reader
@@ -26,21 +24,25 @@ def load_csv(csv_path: Path | str) -> BudgetPlan:
    return BudgetPlan({item.id: item for item in items})


def load_csv(csv_path: Path | str) -> BudgetPlan:
    with open(csv_path, newline="") as f:
        return _load_csv_lines(f)


def load_pdf(pdf_path: Path | str) -> BudgetPlan:
    if isinstance(pdf_path, str):
        pdf_path = Path(pdf_path)

    with NamedTemporaryFile() as f:
        print(f.name)
        subprocess.run(
    result = subprocess.run(
        [
            "tabula",
            pdf_path.absolute(),
            "--pages",
            "all",
                "--out",
                f.name,
            "--lattice",
            ]
        ],
        check=True,
        capture_output=True,
        encoding="utf-8",
    )
        return load_csv(f.name)
    return _load_csv_lines(result.stdout.split("\n"))