8000 feat(documents): use the word boxes anytopdf read instead of reading its PDF again by adeelahmad · Pull Request #223 · adeelahmad/lense · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,9 @@ The backend (`fastapi_backend`) and the frontend (`nextjs-frontend`) are version
it then also reads images, flattening a photographed page before OCR. Or set a conversion node, another machine
running `anytopdf queue serve`, and a small server reads Word, PowerPoint and spreadsheet files too
([anytopdf](docs/configuration.md#anytopdf)).
- **Where anytopdf made a document's PDF, Lens uses the words it read.** anytopdf 0.4.0 lists every word it found on
a picture page with where it is, so a photographed or scanned page's text comes from anytopdf's OCR, block by block
with its place on the page, without Lens reading the page again. Pages without those words are read as before.
- **A conversion node gets the token and nothing more.** Lens refuses a node that redirects (so its token never
goes on to another server), caps what the node answers and refuses a PDF that isn't one. Settings › Documents ›
Check it says whether the node answers and takes the token ([anytopdf](docs/configuration.md#anytopdf)).
Expand Down
38 changes: 37 additions & 1 deletion fastapi_backend/app/domain/anytopdf.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@
documents.converter says when: `auto` (the default) uses it only for what Lens can't convert itself, `anytopdf` for
every document and image, `lens` never. Run here, it has no network, no runtime plugins (faces, objects and speech
stay Lens's own steps) and no config file of its own; its PDF has no provenance page, and its search layer holds the
document's text only, so what Lens reads from it is what the document says.
document's text only, so what Lens reads from it is what the document says. Where a page of its PDF is a picture, the
words it read there, each with where it is (page_words), are that page's text: Lens doesn't read it again.

A conversion node gets the document and its token at the address the admin set and nowhere else: only http(s), no
user name or password in the address, and no redirect is followed, so the token never goes on to another server.
Expand Down Expand Up @@ -54,6 +55,7 @@
# its search layer: the document's own text, not the dates, colours and places it would add
QUIET = ["--no-provenance-page", "--no-entities", "--colors", "off", "--location", "off"]
POLL_SECONDS = 1.0
CHUNKS = "anytopdf-chunks.json" # what it read, embedded in each PDF it makes (anytopdf.chunks/1)
MAX_JSON = 1 << 20 # the most of a conversion node's job answer that is read
MAX_PDF = 2 << 30 # the largest PDF taken from a conversion node
JOB_ID = re.compile(r"[A-Za-z0-9_.:-]{1,128}")
Expand Down Expand Up @@ -408,3 +410,37 @@ def analyze(cfg, picture, models=None, seconds=None):
}
)
return out


def page_words(pdf):
"""The words anytopdf read on each page of a PDF it made, from the chunks it embeds in it: {page (from 0): {"words":
[{text, box}] in reading order, box [x, y, w, h] as fractions of the page, "ocr": whether OCR read them}}. Only pages
whose every chunk is a picture with its words are given (an email's own text has no words, so its pages are read as
before); {} for a PDF without them (one anytopdf before 0.4.0 made, or not anytopdf)."""
try:
from pypdf import PdfReader

found = PdfReader(str(pdf)).attachments.get(CHUNKS) or []
chunks = json.loads(found[0])["chunks"] if found else []
except Exception: # noqa: BLE001 - without its chunks, the PDF is read as any other
return {}
out, mixed = {}, set()
for c in chunks if isinstance(chunks, list) else []:
pages = c.get("pages") or {}
first, last = pages.get("first"), pages.get("last")
if not isinstance(first, int) or not isinstance(last, int):
continue
words = c.get("words") if c.get("kind") == "visual" and first == last else None
if not words:
mixed.update(range(first - 1, last))
continue
page = out.setdefault(first - 1, {"words": [], "ocr": False})
page["ocr"] = page["ocr"] or "pdftotext" not in (c.get("providers") or [])
for w in words:
try:
box = [round(float(w[k]), 4) for k in ("x", "y", "width", "height")]
except (KeyError, TypeError, ValueError):
continue
if str(w.get("text") or "").strip() and box[2] > 0 and box[3] > 0:
page["words"].append({"text": str(w["text"]).strip(), "box": box})
return {i: p for i, p in out.items() if i not in mixed and p["words"]}
54 changes: 46 additions & 8 deletions fastapi_backend/app/domain/documents.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,30 @@ def merge_lines(lines):
return [{"text": p["text"], "conf": sum(p["confs"]) / len(p["confs"]), "box": [round(v, 4) for v in p["box"]]} for p in out]


def word_lines(words):
"""Words in reading order ({text, box}) as lines ({text, conf, box}): a word not level with the line before it, or
left of where that line's last word starts, begins a new one."""
out = []
for w in words:
x, y, ww, h = w["box"]
cur = out[-1] if out else None
if cur:
lx, ly, lw, lh = cur["box"]
mid = y + h / 2
if ly <= mid <= ly + lh and x >= cur["x"]:
cur["text"] += " " + w["text"]
cur["box"] = [min(lx, x), min(ly, y), max(lx + lw, x + ww) - min(lx, x), max(ly + lh, y + h) - min(ly, y)]
cur["x"] = x
continue
out.append({"text": w["text"], "conf": 100, "box": list(w["box"]), "x": x})
return [{"text": ln["text"], "conf": ln["conf"], "box": ln["box"]} for ln in out]


def word_blocks(words):
"""Words with where each is on the page (anytopdf's) as blocks: their lines, put together into paragraphs."""
return [{"text": t, "box": p["box"]} for p in merge_lines(word_lines(words)) if (t := _clean(p["text"]))]


def ocr_blocks(engine, path):
"""What an OCR engine reads on a page, as blocks: Tesseract's own paragraphs, else its lines put together."""
found = engine.paragraphs(path) if hasattr(engine, "paragraphs") else merge_lines(engine.lines(path))
Expand Down Expand Up @@ -261,8 +285,10 @@ def _pdf_text(pdftotext, path, first, last):
return {i: [] for i in range(first, last + 1)}


def read_pdf(path, d, opts, engine, say, why="no OCR engine is available"):
"""Draw a PDF's pages into d and read their text: (pages, blocks by page, notes). `why` there's no OCR engine."""
def read_pdf(path, d, opts, engine, say, why="no OCR engine is available", known=None):
"""Draw a PDF's pages into d and read their text: (pages, blocks by page, notes). `why` there's no OCR engine.
`known`: pages whose words anytopdf already read ({page: {words, ocr}}, anytopdf.page_words), not read again."""
known = known or {}
n = page_count(path)
total, n = n, min(n, opts["max_pages"])
pdftoppm, pdftotext = _poppler()
Expand All @@ -273,11 +299,14 @@ def read_pdf(path, d, opts, engine, say, why="no OCR engine is available"):
for first in range(0, n, BATCH):
last = min(n, first + BATCH) - 1
sizes = draw_pages(pdftoppm, path, d, first, last, opts) if pdftoppm else {}
text = _pdf_text(pdftotext, path, first, last)
todo = [i for i in range(first, last + 1) if i not in known]
text = _pdf_text(pdftotext, path, todo[0], todo[-1]) if todo else {}
for i in range(first, last + 1):
found, how = text.get(i) or [], "pdf"
if i in known:
found, how = word_blocks(known[i]["words"]), "ocr" if known[i]["ocr"] else "pdf"
chars = sum(len(b["text"]) for b in found)
if chars < opts["ocr_below_chars"] and engine and pdftoppm:
if i not in known and chars < opts["ocr_below_chars"] and engine and pdftoppm:
with tempfile.TemporaryDirectory(dir=d) as tmp:
sharp = _sharp(pdftoppm, path, i, tmp)
read = ocr_blocks(engine, sharp) if sharp else []
Expand All @@ -302,7 +331,7 @@ def read_pdf(path, d, opts, engine, say, why="no OCR engine is available"):
blocks[i] = found
if n > BATCH:
say(f"read {last + 1} of {n} pages")
scanned = sum(1 for p in pages if p.get("chars", 0) < opts["ocr_below_chars"])
scanned = sum(1 for p in pages if p.get("chars", 0) < opts["ocr_below_chars"] and p["idx"] not in known)
if scanned and not engine:
notes.append(f"{scanned} page(s) without text weren't read: {why}")
if total > n:
Expand Down Expand Up @@ -451,10 +480,14 @@ def transcribe(db, cfg, rid, say):
d = video.frames_dir(cfg, rid)
d.mkdir(parents=True, exist_ok=True)
_clear(d)
read = read_image if source == "image" and not learnt else read_pdf
# where anytopdf made the PDF, the words it read on each page, with where they are, are used as they are
known = anytopdf.page_words(pdf) if learnt.get("by") == "anytopdf" else {}
try:
with keyring.sealing(db, cfg, rec["space"], d): # the pages drawn: encrypted, even if this fails part way
pages, blocks, notes, ocred = read(pdf, d, opts, engine, say, why)
if source == "image" and not learnt:
pages, blocks, notes, ocred = read_image(pdf, d, opts, engine, say, why)
else:
pages, blocks, notes, ocred = read_pdf(pdf, d, opts, engine, say, why, known)
finally:
if learnt: # the rendition, read: kept encrypted from here on, like the file it was made from
keyring.protect(db, cfg, rec["space"], pdf)
Expand All @@ -468,7 +501,9 @@ def transcribe(db, cfg, rid, say):
)
first = next((p for p in pages if p.get("width")), {})
media = store.clean({"kind": rec["source"], "pages": len(pages), "width": first.get("width"), "height": first.get("height")})
how = ("pdf" if rec["source"] == "document" else "image") + (f"+ocr:{engine.name}" if ocred and engine else "")
theirs = sum(1 for p in pages if p["idx"] in known and known[p["idx"]]["ocr"]) # pages anytopdf's OCR read
ocr_by = engine.name if ocred and engine else "anytopdf" if theirs else None
how = ("pdf" if rec["source"] == "document" else "image") + (f"+ocr:{ocr_by}" if ocr_by else "")
patch = {"status": "transcribed", "engine": how, "media": media, "transcribed_at": store.now()}
if learnt:
patch["rendition"] = {"from": convert.ext_of(path), "by": learnt["by"]}
Expand All @@ -481,4 +516,7 @@ def transcribe(db, cfg, rid, say):
if learnt.get("attachments") is not None:
convert.keep_attachments(db, cfg, rid, learnt["attachments"], say)
by_ocr = f", {ocred} read by OCR ({engine.name})" if ocred and engine else ""
by_ocr += f", {theirs} read by anytopdf's OCR" if theirs else ""
if known:
say(f"{len(known)} page(s) read from the words anytopdf found")
say(f"{len(pages)} page(s){by_ocr}, {len(segs)} block(s) of text")
11 changes: 10 additions & 1 deletion fastapi_backend/tests/api/test_anytopdf.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,8 @@ class _Hostile(fake_anytopdf.Node):
mode = ""

def do_POST(self): # noqa: N802
if _Hostile.mode in ("redirect", "long", "odd id"): # the upload read first, or Lens may see a reset instead
self.rfile.read(int(self.headers["Content-Length"]))
if _Hostile.mode == "redirect":
self.send_response(307)
self.send_header("Location", f"http://127.0.0.1:{_Hostile.elsewhere}/v1/jobs")
Expand Down Expand Up @@ -236,7 +238,11 @@ def test_with_anytopdf_chosen_it_reads_images_too(here, client, env, db, cfg, fo
drain(db, settings.effective(db, cfg))
rec = _rec(db, up["recording"])
assert (rec["source"], rec["status"], rec["rendition"]) == ("image", "analyzed", {"from": ".png", "by": "anytopdf"}), rec.get("error")
assert rec["engine"] == "image" and "Photographed page document" in _text(db, up["recording"])
assert rec["engine"] == "image+ocr:anytopdf" and "Photographed page document" in _text(db, up["recording"])
# its words, with where anytopdf's OCR found them, are its text: not read again
segs = db.rows("SELECT text, page, box FROM segment WHERE recording = $r", r=up["recording"])
assert segs == [{"text": "Photographed page document", "page": 0, "box": [0.1, 0.1, 0.55, 0.02]}]
assert db.one("SELECT VALUE text FROM page WHERE recording = $r", r=up["recording"]) == "ocr"
assert "--scan-mode" in fake_anytopdf.runs(here)[-1]["args"]
assert convert.rendition_path(cfg, up["recording"]).is_file()

Expand Down Expand Up @@ -378,6 +384,9 @@ def test_the_real_anytopdf(real, lean, client, env, db, cfg):
rec = _rec(db, up["recording"])
assert (rec["status"], rec["rendition"]["by"]) == ("analyzed", "anytopdf"), rec.get("error")
assert words in _text(db, up["recording"]), _text(db, up["recording"])
# the photographed page: its text from the words anytopdf's OCR found, each block with where it is
assert _rec(db, page["recording"])["engine"] == "image+ocr:anytopdf"
assert all(s["box"] for s in db.rows("SELECT box FROM segment WHERE recording = $r", r=page["recording"]))
pic = pathlib.Path(cfg["data_dir"]) / "page.png"
pic.write_bytes(_png(scan(["Galway harbour"])))
assert anytopdf.analyze(cfg, pic) == [] # its plugins ran, sandboxed, and found no face on a page of text
39 changes: 39 additions & 0 deletions fastapi_backend/tests/domain/test_documents.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,3 +69,42 @@ def test_summaries_of_documents_cite_pages():
assert analyze._cited("p. 9", starts, 9000) is None # no such page
assert analyze._cited("0:12", starts, 99000) == 12000 # times as before
assert analyze._cited("", starts, 9000) is None


def test_words_with_their_boxes_become_lines_and_paragraphs():
def w(text, x, y, width=0.1, height=0.02):
return {"text": text, "box": [x, y, width, height]}

words = [w("The", 0.1, 0.1), w("keeper", 0.25, 0.1), w("wrote", 0.1, 0.125), w("twice.", 0.25, 0.126), w("Later", 0.1, 0.4)]
assert [ln["text"] for ln in documents.word_lines(words)] == ["The keeper", "wrote twice.", "Later"]
assert documents.word_blocks(words) == [
{"text": "The keeper wrote twice.", "box": [0.1, 0.1, 0.25, 0.046]},
{"text": "Later", "box": [0.1, 0.4, 0.1, 0.02]},
]
# a column beside: back to the left, so a new line, then its own paragraph
side = [w("Left", 0.1, 0.1), w("Right", 0.6, 0.1), w("again", 0.1, 0.1)]
assert [ln["text"] for ln in documents.word_lines(side)] == ["Left Right", "again"]


def test_the_words_anytopdf_embeds_in_its_pdf(tmp_path):
from app.domain import anytopdf
from tests.fake_anytopdf import with_chunks
from tests.helpers import text_pdf

word = {"text": "Harbour", "x": 0.1, "y": 0.2, "width": 0.3, "height": 0.05}
chunks = [
{"kind": "visual", "pages": {"first": 1, "last": 1}, "providers": ["pdftotext"], "words": [word, {**word, "text": " "}]},
{"kind": "visual", "pages": {"first": 2, "last": 2}, "providers": ["tesseract"], "words": [word]},
{"kind": "visual", "pages": {"first": 3, "last": 3}, "providers": ["tesseract"], "words": [word]},
{"kind": "text", "pages": {"first": 3, "last": 3}, "text": "an email's own text, without words"},
{"kind": "visual", "pages": {"first": 4, "last": 4}, "providers": ["tesseract"]},
]
pdf = tmp_path / "made.pdf"
pdf.write_bytes(with_chunks(text_pdf([["a"], ["b"], ["c"], ["d"]]), chunks))
got = anytopdf.page_words(pdf)
box = {"text": "Harbour", "box": [0.1, 0.2, 0.3, 0.05]}
assert got == {0: {"words": [box], "ocr": False}, 1: {"words": [box], "ocr": True}}

plain = tmp_path / "plain.pdf"
plain.write_bytes(text_pdf([["a"]]))
assert anytopdf.page_words(plain) == {} and anytopdf.page_words(tmp_path / "missing.pdf") == {}
21 changes: 20 additions & 1 deletion fastapi_backend/tests/fake_anytopdf.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,9 +119,28 @@ def graph_of(name, raw, args):


def pdf_of(name, raw):
"""The PDF of a file: its text; an image's also embeds the words its OCR read, with where they are (0.4.0's
chunks)."""
from tests.helpers import text_pdf

return text_pdf([["\n".join(text_of(name, raw))]])
pdf = text_pdf([["\n".join(text_of(name, raw))]])
if pathlib.Path(str(name)).suffix.lower() not in (".png", ".jpg", ".jpeg"):
return pdf
words = [{"text": w, "x": 0.1 + 0.2 * i, "y": 0.1, "width": 0.15, "height": 0.02} for i, w in enumerate(text_of(name, raw)[0].split())]
return with_chunks(pdf, [{"kind": "visual", "pages": {"first": 1, "last": 1}, "providers": ["tesseract"], "words": words}])


def with_chunks(pdf, chunks):
"""A PDF with these anytopdf.chunks/1 chunks embedded, as anytopdf embeds them."""
import io

from pypdf import PdfReader, PdfWriter

w = PdfWriter(clone_from=PdfReader(io.BytesIO(pdf)))
w.add_attachment("anytopdf-chunks.json", json.dumps({"schema_version": "anytopdf.chunks/1", "chunks": chunks}).encode())
out = io.BytesIO()
w.write(out)
return out.getvalue()


def make(path, log):
Expand Down
Loading
0