Files
ISSSTELEON/Extraction/extraction/testing.py
T
2026-11-13 11:53:06 -06:00

135 lines
5.4 KiB
Python

"""Synthetic documents for tests: typed and scanned PDFs, EDF recordings.
`text_pdf` needs reportlab (a dev dependency)."""
import io
import numpy as np
from PIL import Image, ImageDraw, ImageFont
def text_pdf(
pages: list[list[str | list[tuple[int, str]]]],
*,
image_on_page: int | None = None,
overprint: int = 1,
background_page: bytes | None = None,
) -> bytes:
"""One list of lines per page, typed (real text layer). A line may be
a list of `(x, text)` cells, for layouts in columns. `overprint` draws
every line that many times a fraction of a point apart, the way some
generators fake bold. `background_page` (PNG or JPEG bytes) is drawn
under the text over the whole page, like a scan with a stamped header."""
from reportlab.lib.pagesizes import letter
from reportlab.lib.utils import ImageReader
from reportlab.pdfgen import canvas
buffer = io.BytesIO()
pdf = canvas.Canvas(buffer, pagesize=letter)
for number, lines in enumerate(pages, start=1):
if background_page is not None:
pdf.drawImage(ImageReader(io.BytesIO(background_page)), 0, 0, width=letter[0], height=letter[1])
y = 740
for line in lines:
cells = [(60, line)] if isinstance(line, str) else line
for x, text in cells:
for copy in range(overprint):
pdf.drawString(x + 0.25 * copy, y, text)
y -= 20
if image_on_page == number:
picture = Image.new("RGB", (200, 150), (180, 60, 60))
pdf.drawImage(ImageReader(picture), 300, 300, width=200, height=150)
pdf.showPage()
pdf.save()
return buffer.getvalue()
def scanned_pdf(pages: list[list[str]], *, rotate: int = 0) -> bytes:
"""Same as `text_pdf` but every page is a picture of text — no text
layer. `rotate` turns each picture that many degrees counterclockwise,
like a sheet scanned sideways or upside down."""
images = [page_image(lines).rotate(rotate, expand=True) for lines in pages]
buffer = io.BytesIO()
images[0].save(buffer, format="PDF", save_all=True, append_images=images[1:], resolution=150)
return buffer.getvalue()
def page_image(lines: list[str]) -> Image.Image:
"""A letter-size page at 150 dpi with the lines written on it."""
image = Image.new("L", (1275, 1650), 255)
draw = ImageDraw.Draw(image)
font = _font(34)
y = 120
for line in lines:
draw.text((110, y), line, fill=0, font=font)
y += 60
return image.convert("RGB")
def _font(size: int):
for path in ("/System/Library/Fonts/Supplemental/Arial.ttf", "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"):
try:
return ImageFont.truetype(path, size)
except OSError:
continue
return ImageFont.load_default(size=size)
def edf_file(
*,
signals: dict[str, np.ndarray],
sample_rate: int,
patient: str = "EXP-0042 F 02-MAY-2019 Ana_Perez",
recording: str = "Startdate 15-JAN-2024 LAB-778 Tec_Ruiz Nihon_Kohden",
annotations: list[tuple[float, str]] = (),
) -> bytes:
"""A valid EDF+ file with one second per data record."""
labels = list(signals)
seconds = len(next(iter(signals.values()))) // sample_rate
has_annotations = bool(annotations)
total_signals = len(labels) + (1 if has_annotations else 0)
annotation_samples = 60
width = 2
digital_max = 32767
digital_min = -digital_max - 1
def field(value, size):
return str(value).ljust(size)[:size].encode("latin-1")
header = field("0", 8)
header += field(patient, 80) + field(recording, 80)
header += field("15.01.24", 8) + field("10.30.00", 8)
header += field(256 * (total_signals + 1), 8)
header += field("EDF+C", 44)
header += field(seconds, 8) + field(1, 8) + field(total_signals, 4)
all_labels = labels + (["EDF Annotations"] if has_annotations else [])
per_record = [sample_rate] * len(labels) + ([annotation_samples] if has_annotations else [])
columns = [
[field(label, 16) for label in all_labels],
[field("AgAgCl electrode" if label != "EDF Annotations" else "", 80) for label in all_labels],
[field("uV" if i < len(labels) else "", 8) for i in range(total_signals)],
[field(-500 if i < len(labels) else -1, 8) for i in range(total_signals)],
[field(500 if i < len(labels) else 1, 8) for i in range(total_signals)],
[field(digital_min, 8) for _ in range(total_signals)],
[field(digital_max, 8) for _ in range(total_signals)],
[field("HP:0.1Hz LP:75Hz" if i < len(labels) else "", 80) for i in range(total_signals)],
[field(n, 8) for n in per_record],
[field("", 32) for _ in range(total_signals)],
]
for column in columns:
header += b"".join(column)
gain = (digital_max - digital_min) / 1000.0
body = b""
for second in range(seconds):
for label in labels:
chunk = signals[label][second * sample_rate : (second + 1) * sample_rate]
digital = np.clip(np.round((chunk + 500) * gain + digital_min), digital_min, digital_max).astype(np.int32)
body += digital.astype("<i2").tobytes()
if has_annotations:
tal = f"+{second}\x14\x14\x00".encode()
for onset, text in annotations:
if int(onset) == second:
tal += f"+{onset}\x14{text}\x14\x00".encode()
body += tal.ljust(annotation_samples * width, b"\x00")
return header + body