pyocr-toolkit 0.3.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pyocr_toolkit/__init__.py +3 -0
- pyocr_toolkit/__main__.py +3 -0
- pyocr_toolkit/api.py +603 -0
- pyocr_toolkit/cli.py +315 -0
- pyocr_toolkit/compare.py +142 -0
- pyocr_toolkit/config.py +86 -0
- pyocr_toolkit/credentials.py +108 -0
- pyocr_toolkit/documents.py +326 -0
- pyocr_toolkit/env.example +48 -0
- pyocr_toolkit/jobs.py +205 -0
- pyocr_toolkit/llm/__init__.py +44 -0
- pyocr_toolkit/llm/anthropic_provider.py +188 -0
- pyocr_toolkit/llm/base.py +126 -0
- pyocr_toolkit/llm/catalog.py +337 -0
- pyocr_toolkit/llm/gemini_provider.py +98 -0
- pyocr_toolkit/llm/openai_provider.py +183 -0
- pyocr_toolkit/llm/prompts.py +61 -0
- pyocr_toolkit/search.py +88 -0
- pyocr_toolkit/service.py +269 -0
- pyocr_toolkit/static/common.js +538 -0
- pyocr_toolkit/static/compare.js +157 -0
- pyocr_toolkit/static/document.js +89 -0
- pyocr_toolkit/static/jobs.js +13 -0
- pyocr_toolkit/static/library.js +28 -0
- pyocr_toolkit/static/models.js +98 -0
- pyocr_toolkit/static/providers.js +44 -0
- pyocr_toolkit/static/reader.js +78 -0
- pyocr_toolkit/static/search.js +34 -0
- pyocr_toolkit/static/styles.css +819 -0
- pyocr_toolkit/static/workspace.js +420 -0
- pyocr_toolkit/static/workspaces.js +81 -0
- pyocr_toolkit/templates/_doc_card.html +30 -0
- pyocr_toolkit/templates/_doctabs.html +14 -0
- pyocr_toolkit/templates/_icons.html +55 -0
- pyocr_toolkit/templates/_llm_picker.html +12 -0
- pyocr_toolkit/templates/base.html +97 -0
- pyocr_toolkit/templates/compare.html +84 -0
- pyocr_toolkit/templates/document.html +80 -0
- pyocr_toolkit/templates/error.html +11 -0
- pyocr_toolkit/templates/help.html +244 -0
- pyocr_toolkit/templates/home.html +90 -0
- pyocr_toolkit/templates/jobs.html +15 -0
- pyocr_toolkit/templates/library.html +44 -0
- pyocr_toolkit/templates/models.html +67 -0
- pyocr_toolkit/templates/providers.html +104 -0
- pyocr_toolkit/templates/reader.html +28 -0
- pyocr_toolkit/templates/search.html +22 -0
- pyocr_toolkit/templates/workspace.html +109 -0
- pyocr_toolkit/templates/workspace_detail.html +42 -0
- pyocr_toolkit/templates/workspaces.html +42 -0
- pyocr_toolkit/web.py +186 -0
- pyocr_toolkit/workspaces.py +330 -0
- pyocr_toolkit-0.3.0.dist-info/METADATA +483 -0
- pyocr_toolkit-0.3.0.dist-info/RECORD +57 -0
- pyocr_toolkit-0.3.0.dist-info/WHEEL +4 -0
- pyocr_toolkit-0.3.0.dist-info/entry_points.txt +3 -0
- pyocr_toolkit-0.3.0.dist-info/licenses/LICENSE +201 -0
pyocr_toolkit/web.py
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
"""Server-rendered HTML pages.
|
|
2
|
+
|
|
3
|
+
Each page is a normal URL you can bookmark, share or open in a new tab. The
|
|
4
|
+
templates render the layout and anything cheap to compute; interactive parts
|
|
5
|
+
(running OCR/LLMs, diffs, search) are small per-page scripts talking to the
|
|
6
|
+
JSON API in :mod:`pyocr_toolkit.api`.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import shutil
|
|
12
|
+
import subprocess
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
from fastapi import APIRouter, Request
|
|
16
|
+
from fastapi.responses import HTMLResponse, RedirectResponse
|
|
17
|
+
from fastapi.templating import Jinja2Templates
|
|
18
|
+
|
|
19
|
+
from . import __version__
|
|
20
|
+
from .config import Settings
|
|
21
|
+
from .documents import DocumentStore
|
|
22
|
+
from .jobs import JobManager
|
|
23
|
+
from .llm import catalog
|
|
24
|
+
from .service import Services
|
|
25
|
+
from .workspaces import WorkspaceStore
|
|
26
|
+
|
|
27
|
+
TEMPLATES = Jinja2Templates(directory=str(Path(__file__).parent / "templates"))
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _filesize(n: int) -> str:
|
|
31
|
+
size = float(n)
|
|
32
|
+
for unit in ("B", "KB", "MB", "GB"):
|
|
33
|
+
if size < 1024 or unit == "GB":
|
|
34
|
+
return f"{size:.0f} {unit}" if unit == "B" else f"{size:.1f} {unit}"
|
|
35
|
+
size /= 1024
|
|
36
|
+
return f"{n} B"
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _datetime(ts: float) -> str:
|
|
40
|
+
import datetime as dt
|
|
41
|
+
|
|
42
|
+
return dt.datetime.fromtimestamp(ts).strftime("%Y-%m-%d %H:%M")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
TEMPLATES.env.filters["filesize"] = _filesize
|
|
46
|
+
TEMPLATES.env.filters["datetime"] = _datetime
|
|
47
|
+
TEMPLATES.env.globals["version"] = __version__
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def render_error(request: Request, status: int, message: str) -> HTMLResponse:
|
|
51
|
+
return TEMPLATES.TemplateResponse(request, "error.html", {"status": status, "message": message, "nav": ""},
|
|
52
|
+
status_code=status)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def build_web(settings: Settings, store: DocumentStore, services: Services, jobs: JobManager,
|
|
56
|
+
workspaces: WorkspaceStore) -> APIRouter:
|
|
57
|
+
web = APIRouter(include_in_schema=False)
|
|
58
|
+
|
|
59
|
+
def page(request: Request, template: str, nav: str, **ctx) -> HTMLResponse:
|
|
60
|
+
return TEMPLATES.TemplateResponse(request, template, {"nav": nav, **ctx})
|
|
61
|
+
|
|
62
|
+
# Pages with a usable embedded text layer never change for a stored file,
|
|
63
|
+
# so remember them per document instead of re-reading every page.
|
|
64
|
+
native_cache: dict[str, frozenset[int]] = {}
|
|
65
|
+
|
|
66
|
+
def summary(doc_id: str, memberships: dict | None = None) -> dict:
|
|
67
|
+
doc = store.get(doc_id)
|
|
68
|
+
n = doc.meta.page_count
|
|
69
|
+
if doc_id not in native_cache:
|
|
70
|
+
native_cache[doc_id] = frozenset(p for p in range(n) if not doc.page_info(p)["looks_scanned"])
|
|
71
|
+
native = native_cache[doc_id]
|
|
72
|
+
ocr = {p for p in range(n) if doc.cached_ocr_text(p) is not None}
|
|
73
|
+
llm = {p for p in range(n) if doc.list_llm_results(p)}
|
|
74
|
+
missing = n - len(native | ocr | llm) # pages with no text from any source
|
|
75
|
+
status = "complete" if missing == 0 else "scanned" if not native else "partial"
|
|
76
|
+
if memberships is None:
|
|
77
|
+
memberships = workspaces.memberships()
|
|
78
|
+
in_ws = [{"id": w.id, "name": w.name} for w in memberships.get(doc_id, [])]
|
|
79
|
+
return {**doc.meta.__dict__, "native_pages": len(native), "ocr_pages": len(ocr),
|
|
80
|
+
"llm_pages": len(llm), "missing_pages": missing, "status": status, "workspaces": in_ws}
|
|
81
|
+
|
|
82
|
+
def ws_summary(ws, memberships: dict) -> dict:
|
|
83
|
+
docs = [summary(d, memberships) for d in ws.doc_ids]
|
|
84
|
+
return {"id": ws.id, "name": ws.name, "created_at": ws.created_at, "updated_at": ws.updated_at,
|
|
85
|
+
"docs": docs, "page_count": sum(d["page_count"] for d in docs),
|
|
86
|
+
"missing_pages": sum(d["missing_pages"] for d in docs),
|
|
87
|
+
"size_bytes": sum(d["size_bytes"] for d in docs)}
|
|
88
|
+
|
|
89
|
+
@web.get("/", response_class=HTMLResponse)
|
|
90
|
+
def home(request: Request):
|
|
91
|
+
recent = [summary(m.id) for m in store.list()[:6]]
|
|
92
|
+
memberships = workspaces.memberships()
|
|
93
|
+
recent_ws = [ws_summary(w, memberships) for w in workspaces.list()[:4]]
|
|
94
|
+
configured = [p for p in services.providers.values() if p.configured]
|
|
95
|
+
return page(request, "home.html", "home", recent=recent, configured=configured,
|
|
96
|
+
providers=list(services.providers.values()),
|
|
97
|
+
tesseract=shutil.which("tesseract") is not None, total_docs=len(store.list()),
|
|
98
|
+
recent_ws=recent_ws)
|
|
99
|
+
|
|
100
|
+
@web.get("/documents", response_class=HTMLResponse)
|
|
101
|
+
def library(request: Request):
|
|
102
|
+
memberships = workspaces.memberships()
|
|
103
|
+
return page(request, "library.html", "library", docs=[summary(m.id, memberships) for m in store.list()],
|
|
104
|
+
spaces=workspaces.list())
|
|
105
|
+
|
|
106
|
+
@web.get("/workspaces", response_class=HTMLResponse)
|
|
107
|
+
def workspaces_view(request: Request):
|
|
108
|
+
memberships = workspaces.memberships()
|
|
109
|
+
return page(request, "workspaces.html", "workspaces",
|
|
110
|
+
spaces=[ws_summary(w, memberships) for w in workspaces.list()])
|
|
111
|
+
|
|
112
|
+
@web.get("/workspaces/{ws_id}", response_class=HTMLResponse)
|
|
113
|
+
def workspace_detail(request: Request, ws_id: str):
|
|
114
|
+
memberships = workspaces.memberships()
|
|
115
|
+
return page(request, "workspace_detail.html", "workspaces",
|
|
116
|
+
ws=ws_summary(workspaces.get(ws_id), memberships))
|
|
117
|
+
|
|
118
|
+
@web.get("/documents/{doc_id}", response_class=HTMLResponse)
|
|
119
|
+
def overview(request: Request, doc_id: str):
|
|
120
|
+
doc = store.get(doc_id)
|
|
121
|
+
return page(request, "document.html", "library", doc=summary(doc_id),
|
|
122
|
+
sources=services.list_sources(doc), doc_tab="overview")
|
|
123
|
+
|
|
124
|
+
@web.get("/documents/{doc_id}/pages/{page_no}", response_class=HTMLResponse)
|
|
125
|
+
def workspace(request: Request, doc_id: str, page_no: int):
|
|
126
|
+
doc = store.get(doc_id)
|
|
127
|
+
page_no = max(1, min(page_no, doc.meta.page_count))
|
|
128
|
+
return page(request, "workspace.html", "library", doc=summary(doc_id), page_no=page_no,
|
|
129
|
+
doc_tab="pages")
|
|
130
|
+
|
|
131
|
+
@web.get("/documents/{doc_id}/pages")
|
|
132
|
+
def workspace_first(doc_id: str):
|
|
133
|
+
store.get(doc_id)
|
|
134
|
+
return RedirectResponse(f"/documents/{doc_id}/pages/1")
|
|
135
|
+
|
|
136
|
+
@web.get("/documents/{doc_id}/text", response_class=HTMLResponse)
|
|
137
|
+
def reader(request: Request, doc_id: str):
|
|
138
|
+
doc = store.get(doc_id)
|
|
139
|
+
return page(request, "reader.html", "library", doc=summary(doc_id),
|
|
140
|
+
sources=services.list_sources(doc), doc_tab="text")
|
|
141
|
+
|
|
142
|
+
@web.get("/documents/{doc_id}/compare", response_class=HTMLResponse)
|
|
143
|
+
def compare_view(request: Request, doc_id: str):
|
|
144
|
+
doc = store.get(doc_id)
|
|
145
|
+
return page(request, "compare.html", "library", doc=summary(doc_id),
|
|
146
|
+
sources=services.list_sources(doc), doc_tab="compare")
|
|
147
|
+
|
|
148
|
+
@web.get("/search", response_class=HTMLResponse)
|
|
149
|
+
def search_view(request: Request, q: str = ""):
|
|
150
|
+
return page(request, "search.html", "search", q=q)
|
|
151
|
+
|
|
152
|
+
@web.get("/jobs", response_class=HTMLResponse)
|
|
153
|
+
def jobs_view(request: Request):
|
|
154
|
+
names = {m.id: m.filename for m in store.list()}
|
|
155
|
+
return page(request, "jobs.html", "jobs", jobs=[j.to_json() for j in jobs.list()], names=names)
|
|
156
|
+
|
|
157
|
+
@web.get("/providers", response_class=HTMLResponse)
|
|
158
|
+
def providers_view(request: Request):
|
|
159
|
+
tesseract = shutil.which("tesseract")
|
|
160
|
+
langs: list[str] = []
|
|
161
|
+
version = ""
|
|
162
|
+
if tesseract:
|
|
163
|
+
try:
|
|
164
|
+
out = subprocess.run([tesseract, "--list-langs"], capture_output=True, text=True, timeout=10)
|
|
165
|
+
langs = [ln.strip() for ln in out.stdout.splitlines()[1:] if ln.strip()]
|
|
166
|
+
ver = subprocess.run([tesseract, "--version"], capture_output=True, text=True, timeout=10)
|
|
167
|
+
version = (ver.stdout or ver.stderr).splitlines()[0] if (ver.stdout or ver.stderr) else ""
|
|
168
|
+
except (OSError, subprocess.SubprocessError):
|
|
169
|
+
pass
|
|
170
|
+
provs = list(services.providers.values())
|
|
171
|
+
return page(request, "providers.html", "providers", providers=provs,
|
|
172
|
+
cred_status={p.id: services.credentials.status(p) for p in provs},
|
|
173
|
+
credentials_path=services.credentials.path,
|
|
174
|
+
tesseract=tesseract, tesseract_langs=langs, tesseract_version=version, settings=settings)
|
|
175
|
+
|
|
176
|
+
@web.get("/models", response_class=HTMLResponse)
|
|
177
|
+
def models_view(request: Request, provider: str = "", q: str = ""):
|
|
178
|
+
provs = list(services.providers.values())
|
|
179
|
+
return page(request, "models.html", "models", providers=provs, provider=provider, q=q,
|
|
180
|
+
ratings=catalog.RATINGS, sources=catalog.SOURCES, updated=catalog.CATALOG_UPDATED)
|
|
181
|
+
|
|
182
|
+
@web.get("/help", response_class=HTMLResponse)
|
|
183
|
+
def help_view(request: Request):
|
|
184
|
+
return page(request, "help.html", "help")
|
|
185
|
+
|
|
186
|
+
return web
|
|
@@ -0,0 +1,330 @@
|
|
|
1
|
+
"""Workspaces: named groups of documents, plus batch and zip ingestion.
|
|
2
|
+
|
|
3
|
+
People rarely check one file. They get a folder of invoices or a zip of
|
|
4
|
+
scans. A workspace keeps such a batch together under one name the user can
|
|
5
|
+
change, so it can be found and handled as a set.
|
|
6
|
+
|
|
7
|
+
Workspaces don't change the document layout. A document stays in
|
|
8
|
+
``data/documents/<id>/`` and workspaces only *reference* document ids::
|
|
9
|
+
|
|
10
|
+
data/workspaces/<workspace_id>.json # {"id", "name", "doc_ids", ...}
|
|
11
|
+
|
|
12
|
+
So existing data folders keep working, a workspace can be deleted without
|
|
13
|
+
losing its documents, and a document can be in more than one workspace.
|
|
14
|
+
Ids that point at deleted documents are dropped when a workspace is read.
|
|
15
|
+
|
|
16
|
+
Name suggestions follow the ``adjective-scientist`` pattern (``festive-albattani``),
|
|
17
|
+
the way Claude Code and Docker name things: short, readable and unlikely to
|
|
18
|
+
clash. When the uploaded files share a name (``invoices-2024.zip``), that name
|
|
19
|
+
comes first.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import json
|
|
25
|
+
import os
|
|
26
|
+
import random
|
|
27
|
+
import re
|
|
28
|
+
import threading
|
|
29
|
+
import time
|
|
30
|
+
import uuid
|
|
31
|
+
import zipfile
|
|
32
|
+
from collections.abc import Iterable
|
|
33
|
+
from dataclasses import asdict, dataclass, field
|
|
34
|
+
from io import BytesIO
|
|
35
|
+
from pathlib import Path, PurePosixPath
|
|
36
|
+
|
|
37
|
+
from .documents import SUPPORTED_EXTENSIONS, DocumentError, DocumentMeta, DocumentStore
|
|
38
|
+
|
|
39
|
+
_WS_ID_RE = re.compile(r"^[0-9a-f]{32}$")
|
|
40
|
+
MAX_NAME_LEN = 80
|
|
41
|
+
#: Zip safety limits: number of members, and total unpacked size as a multiple of MAX_UPLOAD_MB.
|
|
42
|
+
MAX_ARCHIVE_MEMBERS = 500
|
|
43
|
+
ARCHIVE_TOTAL_FACTOR = 5
|
|
44
|
+
ARCHIVE_EXTENSIONS = {".zip"} # .cbz is a zip too, but PyMuPDF opens it as a comic book document
|
|
45
|
+
|
|
46
|
+
ADJECTIVES = [
|
|
47
|
+
"agile", "amber", "bold", "brave", "bright", "calm", "clever", "cosmic", "crisp", "curious", "daring",
|
|
48
|
+
"eager", "elegant", "festive", "fluent", "gentle", "gleaming", "golden", "happy", "humble", "intelligent",
|
|
49
|
+
"jolly", "keen", "kind", "lively", "lucid", "merry", "modest", "nimble", "noble", "patient", "peaceful",
|
|
50
|
+
"quiet", "quick", "radiant", "serene", "sharp", "steady", "sunny", "swift", "tidy", "tranquil", "upbeat",
|
|
51
|
+
"vibrant", "vigilant", "vivid", "warm", "wise", "witty", "zealous",
|
|
52
|
+
]
|
|
53
|
+
# Scientists, mathematicians and printing / computing pioneers.
|
|
54
|
+
SURNAMES = [
|
|
55
|
+
"albattani", "babbage", "bohr", "boole", "cannon", "curie", "darwin", "dijkstra", "einstein", "euclid",
|
|
56
|
+
"faraday", "fermi", "franklin", "galileo", "gauss", "goodall", "gutenberg", "hamilton", "hopper", "hypatia",
|
|
57
|
+
"johnson", "kepler", "knuth", "lamarr", "lovelace", "maxwell", "meitner", "mirzakhani", "newton", "noether",
|
|
58
|
+
"pascal", "pasteur", "planck", "ramanujan", "ride", "sagan", "shannon", "tesla", "turing", "wozniak",
|
|
59
|
+
]
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class WorkspaceError(DocumentError):
|
|
63
|
+
"""User-facing workspace problem (unknown id, bad name, bad archive)."""
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@dataclass
|
|
67
|
+
class Workspace:
|
|
68
|
+
id: str
|
|
69
|
+
name: str
|
|
70
|
+
created_at: float
|
|
71
|
+
updated_at: float
|
|
72
|
+
doc_ids: list[str] = field(default_factory=list)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
@dataclass
|
|
76
|
+
class IngestResult:
|
|
77
|
+
"""What a batch upload produced: new documents and files that were skipped (with why)."""
|
|
78
|
+
|
|
79
|
+
documents: list[DocumentMeta] = field(default_factory=list)
|
|
80
|
+
skipped: list[dict[str, str]] = field(default_factory=list)
|
|
81
|
+
|
|
82
|
+
def to_json(self) -> dict:
|
|
83
|
+
return {"documents": [m.__dict__ for m in self.documents], "skipped": self.skipped}
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
# ---------------------------------------------------------------- names
|
|
87
|
+
def slugify(text: str) -> str:
|
|
88
|
+
"""``"Invoices 2024 (final).zip"`` -> ``"invoices-2024-final"``."""
|
|
89
|
+
stem = PurePosixPath(text).stem if "." in text else text
|
|
90
|
+
return re.sub(r"[^a-z0-9]+", "-", stem.lower()).strip("-")[:MAX_NAME_LEN]
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def random_name(rng: random.Random | None = None) -> str:
|
|
94
|
+
rng = rng or random
|
|
95
|
+
return f"{rng.choice(ADJECTIVES)}-{rng.choice(SURNAMES)}"
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _name_from_files(filenames: list[str]) -> str | None:
|
|
99
|
+
"""A name the files themselves suggest: a single file's stem, or a common prefix."""
|
|
100
|
+
stems = [slugify(PurePosixPath(f).name) for f in filenames if f]
|
|
101
|
+
stems = [s for s in stems if s]
|
|
102
|
+
if not stems:
|
|
103
|
+
return None
|
|
104
|
+
if len(stems) == 1:
|
|
105
|
+
return stems[0]
|
|
106
|
+
prefix = os.path.commonprefix(stems).strip("-_ ")
|
|
107
|
+
# cut back to a whole word so "invoice-jan", "invoice-feb" gives "invoice", not "invoice-"
|
|
108
|
+
if prefix and not all(len(s) == len(prefix) or s[len(prefix)] == "-" for s in stems):
|
|
109
|
+
prefix = prefix.rsplit("-", 1)[0] if "-" in prefix else prefix
|
|
110
|
+
return prefix if len(prefix) >= 3 else None
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def suggest_names(filenames: Iterable[str] = (), taken: Iterable[str] = (), count: int = 4,
|
|
114
|
+
rng: random.Random | None = None) -> list[str]:
|
|
115
|
+
"""Up to ``count`` distinct workspace names not in ``taken`` (case-insensitive)."""
|
|
116
|
+
rng = rng or random.Random()
|
|
117
|
+
used = {t.lower() for t in taken}
|
|
118
|
+
out: list[str] = []
|
|
119
|
+
|
|
120
|
+
def add(name: str) -> None:
|
|
121
|
+
if name and name.lower() not in used:
|
|
122
|
+
used.add(name.lower())
|
|
123
|
+
out.append(name)
|
|
124
|
+
|
|
125
|
+
base = _name_from_files(list(filenames))
|
|
126
|
+
if base:
|
|
127
|
+
if base.lower() in used:
|
|
128
|
+
base = f"{base}-{rng.choice(SURNAMES)}"
|
|
129
|
+
add(base)
|
|
130
|
+
for _ in range(200):
|
|
131
|
+
if len(out) >= count:
|
|
132
|
+
break
|
|
133
|
+
add(random_name(rng))
|
|
134
|
+
return out[:count]
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def clean_name(name: str) -> str:
|
|
138
|
+
name = " ".join((name or "").split())
|
|
139
|
+
if not name:
|
|
140
|
+
raise WorkspaceError("workspace name can't be empty")
|
|
141
|
+
if len(name) > MAX_NAME_LEN:
|
|
142
|
+
raise WorkspaceError(f"workspace name is too long (max {MAX_NAME_LEN} characters)")
|
|
143
|
+
return name
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
# ---------------------------------------------------------------- store
|
|
147
|
+
class WorkspaceStore:
|
|
148
|
+
"""One JSON file per workspace under ``root``. Writes are atomic and serialised by a lock."""
|
|
149
|
+
|
|
150
|
+
def __init__(self, root: Path, documents: DocumentStore) -> None:
|
|
151
|
+
self.root = Path(root)
|
|
152
|
+
self.root.mkdir(parents=True, exist_ok=True)
|
|
153
|
+
self.documents = documents
|
|
154
|
+
self._lock = threading.RLock()
|
|
155
|
+
|
|
156
|
+
def _path(self, ws_id: str) -> Path:
|
|
157
|
+
if not _WS_ID_RE.match(ws_id or ""):
|
|
158
|
+
raise WorkspaceError("unknown workspace")
|
|
159
|
+
return self.root / f"{ws_id}.json"
|
|
160
|
+
|
|
161
|
+
def _write(self, ws: Workspace) -> None:
|
|
162
|
+
path = self._path(ws.id)
|
|
163
|
+
tmp = path.with_suffix(".json.tmp")
|
|
164
|
+
tmp.write_text(json.dumps(asdict(ws), ensure_ascii=False, indent=1))
|
|
165
|
+
tmp.replace(path)
|
|
166
|
+
|
|
167
|
+
def _read(self, path: Path) -> Workspace:
|
|
168
|
+
ws = Workspace(**json.loads(path.read_text()))
|
|
169
|
+
# drop documents that were deleted outside a workspace
|
|
170
|
+
ws.doc_ids = [d for d in ws.doc_ids if (self.documents.root / d / "meta.json").exists()]
|
|
171
|
+
return ws
|
|
172
|
+
|
|
173
|
+
def _check_unique(self, name: str, except_id: str | None = None) -> None:
|
|
174
|
+
for ws in self.list():
|
|
175
|
+
if ws.id != except_id and ws.name.lower() == name.lower():
|
|
176
|
+
raise WorkspaceError(f"a workspace called '{name}' already exists; pick another name")
|
|
177
|
+
|
|
178
|
+
def list(self) -> list[Workspace]:
|
|
179
|
+
out = []
|
|
180
|
+
for path in self.root.glob("*.json"):
|
|
181
|
+
try:
|
|
182
|
+
out.append(self._read(path))
|
|
183
|
+
except (ValueError, TypeError):
|
|
184
|
+
continue
|
|
185
|
+
return sorted(out, key=lambda w: w.created_at, reverse=True)
|
|
186
|
+
|
|
187
|
+
def get(self, ws_id: str) -> Workspace:
|
|
188
|
+
path = self._path(ws_id)
|
|
189
|
+
if not path.exists():
|
|
190
|
+
raise WorkspaceError("unknown workspace")
|
|
191
|
+
return self._read(path)
|
|
192
|
+
|
|
193
|
+
def create(self, name: str | None = None, doc_ids: Iterable[str] = ()) -> Workspace:
|
|
194
|
+
with self._lock:
|
|
195
|
+
if name is None or not name.strip():
|
|
196
|
+
name = suggest_names(taken=[w.name for w in self.list()], count=1)[0]
|
|
197
|
+
name = clean_name(name)
|
|
198
|
+
self._check_unique(name)
|
|
199
|
+
now = time.time()
|
|
200
|
+
ws = Workspace(uuid.uuid4().hex, name, now, now)
|
|
201
|
+
ws.doc_ids = self._valid_ids(doc_ids)
|
|
202
|
+
self._write(ws)
|
|
203
|
+
return ws
|
|
204
|
+
|
|
205
|
+
def _valid_ids(self, doc_ids: Iterable[str]) -> list[str]:
|
|
206
|
+
ids = []
|
|
207
|
+
for d in doc_ids:
|
|
208
|
+
self.documents.get(d) # raises "unknown document"
|
|
209
|
+
if d not in ids:
|
|
210
|
+
ids.append(d)
|
|
211
|
+
return ids
|
|
212
|
+
|
|
213
|
+
def rename(self, ws_id: str, name: str) -> Workspace:
|
|
214
|
+
with self._lock:
|
|
215
|
+
ws = self.get(ws_id)
|
|
216
|
+
name = clean_name(name)
|
|
217
|
+
self._check_unique(name, except_id=ws_id)
|
|
218
|
+
ws.name, ws.updated_at = name, time.time()
|
|
219
|
+
self._write(ws)
|
|
220
|
+
return ws
|
|
221
|
+
|
|
222
|
+
def add_documents(self, ws_id: str, doc_ids: Iterable[str]) -> Workspace:
|
|
223
|
+
with self._lock:
|
|
224
|
+
ws = self.get(ws_id)
|
|
225
|
+
for d in self._valid_ids(doc_ids):
|
|
226
|
+
if d not in ws.doc_ids:
|
|
227
|
+
ws.doc_ids.append(d)
|
|
228
|
+
ws.updated_at = time.time()
|
|
229
|
+
self._write(ws)
|
|
230
|
+
return ws
|
|
231
|
+
|
|
232
|
+
def remove_document(self, ws_id: str, doc_id: str) -> Workspace:
|
|
233
|
+
with self._lock:
|
|
234
|
+
ws = self.get(ws_id)
|
|
235
|
+
ws.doc_ids = [d for d in ws.doc_ids if d != doc_id]
|
|
236
|
+
ws.updated_at = time.time()
|
|
237
|
+
self._write(ws)
|
|
238
|
+
return ws
|
|
239
|
+
|
|
240
|
+
def forget_document(self, doc_id: str) -> None:
|
|
241
|
+
"""Called when a document is deleted: remove it from every workspace."""
|
|
242
|
+
with self._lock:
|
|
243
|
+
for ws in self.list():
|
|
244
|
+
if doc_id in ws.doc_ids:
|
|
245
|
+
self.remove_document(ws.id, doc_id)
|
|
246
|
+
|
|
247
|
+
def delete(self, ws_id: str, *, delete_documents: bool = False) -> None:
|
|
248
|
+
with self._lock:
|
|
249
|
+
ws = self.get(ws_id)
|
|
250
|
+
self._path(ws_id).unlink()
|
|
251
|
+
if delete_documents:
|
|
252
|
+
for d in ws.doc_ids:
|
|
253
|
+
self.documents.delete(d)
|
|
254
|
+
self.forget_document(d)
|
|
255
|
+
|
|
256
|
+
def memberships(self) -> dict[str, list[Workspace]]:
|
|
257
|
+
"""doc_id -> workspaces that contain it (for badges and breadcrumbs)."""
|
|
258
|
+
out: dict[str, list[Workspace]] = {}
|
|
259
|
+
for ws in self.list():
|
|
260
|
+
for d in ws.doc_ids:
|
|
261
|
+
out.setdefault(d, []).append(ws)
|
|
262
|
+
return out
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
# ---------------------------------------------------------------- ingestion
|
|
266
|
+
def is_archive(filename: str) -> bool:
|
|
267
|
+
return PurePosixPath(filename).suffix.lower() in ARCHIVE_EXTENSIONS
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def _archive_members(filename: str, data: bytes, max_bytes: int, result: IngestResult):
|
|
271
|
+
"""Yield ``(name, bytes)`` for each supported file in a zip, recording the rest in ``result.skipped``."""
|
|
272
|
+
try:
|
|
273
|
+
zf = zipfile.ZipFile(BytesIO(data))
|
|
274
|
+
except zipfile.BadZipFile as exc:
|
|
275
|
+
raise WorkspaceError(f"'{filename}' is not a valid zip file ({exc})") from exc
|
|
276
|
+
with zf:
|
|
277
|
+
infos = [i for i in zf.infolist() if not i.is_dir()]
|
|
278
|
+
if len(infos) > MAX_ARCHIVE_MEMBERS:
|
|
279
|
+
raise WorkspaceError(f"'{filename}' has {len(infos)} files; the limit is {MAX_ARCHIVE_MEMBERS} per zip. "
|
|
280
|
+
"Split it into smaller zips.")
|
|
281
|
+
total = 0
|
|
282
|
+
for info in infos:
|
|
283
|
+
path = PurePosixPath(info.filename)
|
|
284
|
+
label = f"{filename}/{info.filename}"
|
|
285
|
+
# macOS resource forks, dotfiles and anything inside hidden folders are noise, not documents
|
|
286
|
+
if any(part.startswith(".") or part == "__MACOSX" for part in path.parts):
|
|
287
|
+
continue
|
|
288
|
+
ext = path.suffix.lower()
|
|
289
|
+
if ext in ARCHIVE_EXTENSIONS:
|
|
290
|
+
result.skipped.append({"name": label, "reason": "zip inside a zip; unzip it first"})
|
|
291
|
+
continue
|
|
292
|
+
if ext not in SUPPORTED_EXTENSIONS:
|
|
293
|
+
result.skipped.append({"name": label, "reason": f"unsupported file type '{ext or '(none)'}'"})
|
|
294
|
+
continue
|
|
295
|
+
if info.flag_bits & 0x1:
|
|
296
|
+
result.skipped.append({"name": label, "reason": "encrypted zip entry"})
|
|
297
|
+
continue
|
|
298
|
+
if info.file_size > max_bytes:
|
|
299
|
+
result.skipped.append({"name": label, "reason": f"larger than {max_bytes // (1024 * 1024)} MB"})
|
|
300
|
+
continue
|
|
301
|
+
total += info.file_size
|
|
302
|
+
if total > max_bytes * ARCHIVE_TOTAL_FACTOR:
|
|
303
|
+
raise WorkspaceError(f"'{filename}' unpacks to more than {ARCHIVE_TOTAL_FACTOR * max_bytes // (1024 * 1024)} MB. "
|
|
304
|
+
"Split it or raise MAX_UPLOAD_MB.")
|
|
305
|
+
yield path.name, zf.read(info)
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def ingest(store: DocumentStore, files: Iterable[tuple[str, bytes]], *, max_bytes: int) -> IngestResult:
|
|
309
|
+
"""Add every file to ``store``, expanding zip archives. Bad files are skipped, not fatal.
|
|
310
|
+
|
|
311
|
+
Only a broken archive or one over the safety limits raises, because then
|
|
312
|
+
nothing in it can be trusted.
|
|
313
|
+
"""
|
|
314
|
+
result = IngestResult()
|
|
315
|
+
|
|
316
|
+
def add_one(name: str, data: bytes) -> None:
|
|
317
|
+
try:
|
|
318
|
+
result.documents.append(store.add(name, data))
|
|
319
|
+
except DocumentError as exc:
|
|
320
|
+
result.skipped.append({"name": name, "reason": str(exc)})
|
|
321
|
+
|
|
322
|
+
for filename, data in files:
|
|
323
|
+
if len(data) > max_bytes:
|
|
324
|
+
result.skipped.append({"name": filename, "reason": f"larger than {max_bytes // (1024 * 1024)} MB"})
|
|
325
|
+
elif is_archive(filename):
|
|
326
|
+
for name, member in _archive_members(filename, data, max_bytes, result):
|
|
327
|
+
add_one(name, member)
|
|
328
|
+
else:
|
|
329
|
+
add_one(filename, data)
|
|
330
|
+
return result
|