71 lines
2.9 KiB
Python
71 lines
2.9 KiB
Python
import io
|
|
|
|
from PIL import Image, ImageDraw
|
|
|
|
from extraction.document import BBox, Document, Line, Page
|
|
from extraction.errors import ExtractionError
|
|
from extraction.readers.base import DocumentReader
|
|
|
|
_LINE_HEIGHT_PX = 18
|
|
|
|
|
|
class TextReader(DocumentReader):
|
|
"""Plain text, one field's content carrying several of its own (a SQL
|
|
column that isn't a scanned PDF, a note pasted as a string). No OCR: the
|
|
bytes already are the text, one page, one line per newline.
|
|
|
|
The fallback reader, last in `extraction.readers.READERS`: it claims
|
|
whatever a format-specific reader didn't, as long as it decodes as
|
|
text, so a source that's neither a PDF nor an image still reaches the
|
|
same field extraction instead of failing as an unsupported format.
|
|
"""
|
|
|
|
media_type = "text/plain"
|
|
extensions = ("txt",)
|
|
|
|
@classmethod
|
|
def matches_content(cls, head: bytes) -> bool:
|
|
"""`head` is only a short prefix (`reader_for` passes 16 bytes), so
|
|
a multi-byte character can be cut mid-sequence; trimming up to 3
|
|
trailing bytes covers any such cut without accepting binary data.
|
|
Printable (plus common whitespace) is required too, so a binary
|
|
signature that happens to be valid UTF-8 (control bytes are) isn't
|
|
mistaken for text."""
|
|
if b"\x00" in head:
|
|
return False
|
|
text = None
|
|
for cut in range(4):
|
|
trimmed = head[: len(head) - cut] if cut else head
|
|
if not trimmed:
|
|
return False
|
|
try:
|
|
text = trimmed.decode("utf-8")
|
|
break
|
|
except UnicodeDecodeError:
|
|
continue
|
|
return text is not None and all(ch.isprintable() or ch in "\t\n\r" for ch in text)
|
|
|
|
def read(self, name: str, raw: bytes) -> Document:
|
|
try:
|
|
text = raw.decode("utf-8")
|
|
except UnicodeDecodeError as exc:
|
|
raise ExtractionError(f"not valid UTF-8 text: {exc}") from exc
|
|
rows = text.splitlines() or [""]
|
|
lines = [
|
|
Line(text=row, bbox=BBox(0, index / len(rows), 1, (index + 1) / len(rows)))
|
|
for index, row in enumerate(rows)
|
|
]
|
|
return Document(name=name, media_type=self.media_type, pages=[Page(number=1, lines=lines, source="text")], raw=raw)
|
|
|
|
def render_page(self, raw: bytes, page_number: int, *, dpi: int = 150) -> bytes:
|
|
if page_number != 1:
|
|
raise ExtractionError(f"page {page_number} out of range (1..1)")
|
|
rows = raw.decode("utf-8", errors="replace").splitlines() or [""]
|
|
image = Image.new("RGB", (900, max(1, len(rows)) * _LINE_HEIGHT_PX + 20), "white")
|
|
draw = ImageDraw.Draw(image)
|
|
for index, row in enumerate(rows):
|
|
draw.text((10, 10 + index * _LINE_HEIGHT_PX), row, fill="black")
|
|
buffer = io.BytesIO()
|
|
image.save(buffer, format="PNG")
|
|
return buffer.getvalue()
|