#!/usr/bin/env python3 """CLI for printing images and text notes to an Epson TM-T20II receipt printer.""" from __future__ import annotations import argparse import contextlib import io import ipaddress import os import random import subprocess import sys import textwrap from collections.abc import Callable, Sequence from dataclasses import dataclass, field from datetime import datetime from pathlib import Path from typing import BinaryIO import requests from escpos import exceptions as escpos_exceptions from escpos import printer from PIL import Image, ImageOps FALLBACK_PRINTER_IP = "192.168.192.168" def _env_ip() -> str: raw = os.environ.get("RECEIPT_PRINTER_IP", FALLBACK_PRINTER_IP).strip() try: ipaddress.ip_address(raw) except ValueError: print(f"Ignoring invalid RECEIPT_PRINTER_IP={raw!r}.", file=sys.stderr) return FALLBACK_PRINTER_IP return raw def _env_port() -> int: raw = os.environ.get("RECEIPT_PRINTER_PORT", "9100") try: return int(raw) except ValueError: print(f"Ignoring invalid RECEIPT_PRINTER_PORT={raw!r}; using 9100.", file=sys.stderr) return 9100 DEFAULT_PRINTER_IP = _env_ip() DEFAULT_PRINTER_PORT = _env_port() USB_VENDOR_ID = 0x04B8 USB_PRODUCT_ID = 0x0202 PRINTER_PROFILE = "TM-T20II" # python-escpos profile; its 576px media width lets center= work PRINT_WIDTH_PX = 576 # printable width of the TM-T20II at 203 dpi TEXT_COLUMNS = 48 # font A columns on 80mm paper TEXT_SIZES = (1, 2, 3) # note character magnifications; columns shrink to match LINE_HEIGHT_DOTS = 30 # default line spacing (3.75 mm) at size 1 DOTS_PER_MM = 8 # 203 dpi QR_MODULE_DOTS = 8 # the largest module size that reliably fits 576px with quiet zones MAX_PRINT_HEIGHT_DOTS = 8000 # about 1 m of paper; longer jobs are shrunk or refused HTTP_TIMEOUT = 15 # seconds MAX_IMAGE_BYTES = 16 * 1024 * 1024 # cap on a single downloaded or uploaded image DEFAULT_WEB_LISTEN = "127.0.0.1:8765" # deployments set RECEIPT_WEB_LISTEN to their Tailscale IP BASE_DIR = Path(__file__).resolve().parent IMG_DIR = BASE_DIR / "img" LEGACY_FULLWIDTH_DIR = BASE_DIR / "img_fullwidth" # no longer written; removed by `clean` CONNECT_SCRIPT = BASE_DIR / "connect_receipt.sh" BANT_CATALOG_URL = "https://a.4cdn.org/bant/catalog.json" BANT_IMAGE_URL = "https://i.4cdn.org/bant/{tim}{ext}" PRINTABLE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp", ".bmp"} # Untrusted 4chan bytes: refuse absurd pixel counts (decode bomb) before Image.open. Image.MAX_IMAGE_PIXELS = 32_000_000 class InvalidJob(Exception): """The job itself can't be printed (nothing to print, too long, not an image).""" class PrinterUnavailable(Exception): """The printer couldn't be reached, or the link dropped during a job.""" class PrinterDropped(PrinterUnavailable): """The link dropped after a job's bytes started going out; never retry it.""" @dataclass(frozen=True) class PrinterConfig: """How to reach the printer; built from the CLI's global options.""" ip: str = DEFAULT_PRINTER_IP port: int = DEFAULT_PRINTER_PORT usb: bool = False no_setup: bool = False quiet_setup: bool = False # capture the connect script's output (TUI); no sudo prompt @classmethod def from_args(cls, args: argparse.Namespace) -> PrinterConfig: return cls( ip=getattr(args, "ip", DEFAULT_PRINTER_IP), port=getattr(args, "port", DEFAULT_PRINTER_PORT), usb=getattr(args, "usb", False), no_setup=getattr(args, "no_setup", False), quiet_setup=getattr(args, "quiet_setup", False), ) @property def needs_setup(self) -> bool: """Ethernet needs the connect script, unless no_setup says the link is already up.""" return not self.usb and not self.no_setup @property def target(self) -> str: return "USB" if self.usb else f"{self.ip}:{self.port}" def setup_network(config: PrinterConfig) -> None: """Bring up the printer's network interface via the connect script. With quiet_setup the output is captured and re-printed, so callers that redirect stdout (the TUI) see it instead of it landing on the terminal. """ env = os.environ.copy() env["RECEIPT_PRINTER_IP"] = config.ip env["RECEIPT_PRINTER_PORT"] = str(config.port) if not config.quiet_setup: subprocess.run(["bash", str(CONNECT_SCRIPT)], env=env, check=True) # noqa: S603, S607 return bash_path = str(CONNECT_SCRIPT) # noqa: S607 - fixed project script result = subprocess.run( # noqa: S603 ["/bin/bash", bash_path], env=env, capture_output=True, text=True, stdin=subprocess.DEVNULL, timeout=60, ) if result.stdout: print(result.stdout, end="") if result.stderr: print(result.stderr, end="") if result.returncode != 0: raise RuntimeError(f"connect script failed (exit {result.returncode})") def get_printer(config: PrinterConfig) -> printer.Escpos: if config.usb: return printer.Usb(USB_VENDOR_ID, USB_PRODUCT_ID) return printer.Network(config.ip, port=config.port) def close_quietly(p: printer.Escpos) -> None: """Close a printer handle, ignoring errors from an already-dead socket.""" with contextlib.suppress(Exception): p.close() def connect(config: PrinterConfig) -> printer.Escpos: """Open a printer connection, rerunning setup and retrying once on failure. escpos connects lazily on first write, so open() is called here: a connection failure must surface before any of a job's bytes are sent. """ for attempt in (1, 2): try: if config.needs_setup: setup_network(config) p = get_printer(config) p.open() return p except (OSError, escpos_exceptions.Error, subprocess.SubprocessError, RuntimeError) as e: if attempt == 2: raise PrinterUnavailable(f"can't reach {config.target}: {e}") from e print(f"Connect failed ({e}); retrying...", file=sys.stderr) raise AssertionError("unreachable") def send(config: PrinterConfig, payload: bytes) -> None: """Send one rendered job over a fresh connection. Only the connect is retried. Once bytes have gone out, a failure is reported rather than replayed, so a dropped link can't print a job twice. """ p = connect(config) try: p._raw(payload) # escpos's raw-write hook; the payload is already complete ESC/POS except (OSError, escpos_exceptions.Error) as e: raise PrinterDropped( f"the link to {config.target} dropped mid-job, so it may have printed partially ({e})" ) from e finally: close_quietly(p) def render(build: Callable[[printer.Escpos], None]) -> bytes: """Render a job to bytes: printer reset, the job, then a cut. ESC @ comes first so no mode an earlier job left set (e.g. text size) leaks in. """ job = printer.Dummy(profile=PRINTER_PROFILE) job.hw("INIT") build(job) job.cut() return job.output def prepare_for_print( img_path: Path | BinaryIO, max_height: int = MAX_PRINT_HEIGHT_DOTS ) -> Image.Image: """Load an image resized to full printer width and dithered for thermal output. Transparency is composited onto white (thermal paper), then the image is autocontrast-stretched and Floyd-Steinberg dithered to 1-bit. An image that would print taller than max_height is shrunk to that height and centered instead. """ with Image.open(img_path) as img: img.load() # DecompressionBombError and truncated files surface here, inside `with` if img.mode in ("RGBA", "LA") or (img.mode == "P" and "transparency" in img.info): rgba = img.convert("RGBA") background = Image.new("RGBA", rgba.size, "white") img = Image.alpha_composite(background, rgba) width, height = img.size new_width = PRINT_WIDTH_PX new_height = max(1, round(PRINT_WIDTH_PX * height / width)) if new_height > max_height: new_width = max(1, round(max_height * width / height)) new_height = max_height resized = img.resize((new_width, new_height), Image.LANCZOS) gray = ImageOps.autocontrast(resized.convert("L")) if new_width < PRINT_WIDTH_PX: canvas = Image.new("L", (PRINT_WIDTH_PX, new_height), 255) canvas.paste(gray, ((PRINT_WIDTH_PX - new_width) // 2, 0)) gray = canvas return gray.convert("1") def wrap_text(text: str, columns: int = TEXT_COLUMNS) -> str: """Word-wrap text to the printer's column width, preserving blank lines.""" lines = [] for line in text.splitlines(): lines.append(textwrap.fill(line, columns) if line.strip() else "") return "\n".join(lines) @dataclass class Block: """One piece of a receipt: the paper it takes, its ESC/POS, and what it looks like. parts describe the block for previews: {"text", "size", "bold", "center"} dicts and {"image": PIL.Image} dicts, top to bottom. """ height: int # dots build: Callable[[printer.Escpos], None] parts: list[dict] = field(default_factory=list) def text_block( text: str, size: int = 1, timestamp: bool = False, bold: bool = False, center: bool = False, ) -> Block: if not text.strip(): raise InvalidJob("Nothing to print.") lines = wrap_text(text, TEXT_COLUMNS // size).split("\n") header_lines = 2 if timestamp else 0 if (len(lines) * size + header_lines) * LINE_HEIGHT_DOTS > MAX_PRINT_HEIGHT_DOTS: max_lines = (MAX_PRINT_HEIGHT_DOTS // LINE_HEIGHT_DOTS - header_lines) // size raise InvalidJob( f"Note is too long: {len(lines)} lines at size {size}, the limit is {max_lines}." ) header = [datetime.now().strftime("%Y-%m-%d %H:%M"), "-" * TEXT_COLUMNS] if timestamp else [] def build(p: printer.Escpos) -> None: for line in header: p.textln(line) if size > 1: p.set(custom_size=True, width=size, height=size) if bold or center: p.set(bold=bold or None, align="center" if center else None) p.textln("\n".join(lines)) # Leave the defaults for whatever block comes next. if bold or center: p.set(bold=False if bold else None, align="left" if center else None) if size > 1: p.set(normal_textsize=True) parts = [{"text": "\n".join(header), "size": 1}] if header else [] parts.append({"text": "\n".join(lines), "size": size, "bold": bold, "center": center}) return Block((len(lines) * size + header_lines) * LINE_HEIGHT_DOTS, build, parts) def _caption_lines(caption: str | None) -> list[str]: return wrap_text(caption).split("\n") if caption else [] def image_block(source: Path | BinaryIO | Image.Image, caption: str | None = None) -> Block: """A full-width dithered image; a prepared 1-bit image is used as it is.""" lines = _caption_lines(caption) caption_dots = len(lines) * LINE_HEIGHT_DOTS if isinstance(source, Image.Image): prepared = source else: try: prepared = prepare_for_print(source, MAX_PRINT_HEIGHT_DOTS - caption_dots) except (OSError, SyntaxError, ValueError, Image.DecompressionBombError) as e: raise InvalidJob(f"Not a printable image: {e}") from e def build(p: printer.Escpos) -> None: if lines: p.textln("\n".join(lines)) p.image(prepared, impl="bitImageColumn") parts = [{"text": "\n".join(lines), "size": 1}] if lines else [] parts.append({"image": prepared}) return Block(caption_dots + prepared.height, build, parts) def qr_image(content: str) -> Image.Image: """The QR code exactly as escpos rasterizes it (module size 8, one-module border).""" import qrcode # escpos's own dependency for non-native QR code = qrcode.QRCode( version=None, box_size=QR_MODULE_DOTS, border=1, error_correction=qrcode.constants.ERROR_CORRECT_L, ) code.add_data(content) try: code.make(fit=True) except ValueError as e: # qrcode's DataOverflowError raise InvalidJob(f"Too much to fit in a QR code: {e}") from e return code.make_image()._img.convert("1") def qr_block(content: str, caption: str | None = None) -> Block: if not content: raise InvalidJob("Nothing to encode.") img = qr_image(content) if img.width > PRINT_WIDTH_PX: raise InvalidJob( f"Too much to fit in a QR code: {len(content)} characters make it wider than the paper." ) lines = _caption_lines(caption) def build(p: printer.Escpos) -> None: if lines: p.textln("\n".join(lines)) p.qr(content, size=QR_MODULE_DOTS, center=True) parts = [{"text": "\n".join(lines), "size": 1}] if lines else [] parts.append({"image": img}) # escpos prints a blank line above the code and two below it. return Block((len(lines) + 3) * LINE_HEIGHT_DOTS + img.height, build, parts) def divider_block() -> Block: rule = "-" * TEXT_COLUMNS return Block(LINE_HEIGHT_DOTS, lambda p: p.textln(rule), [{"text": rule, "size": 1}]) def receipt_height(blocks: Sequence[Block]) -> int: return sum(b.height for b in blocks) def render_blocks(blocks: Sequence[Block]) -> bytes: """Render blocks as one job, refusing one longer than MAX_PRINT_HEIGHT_DOTS.""" if not blocks: raise InvalidJob("Nothing to print.") height = receipt_height(blocks) if height > MAX_PRINT_HEIGHT_DOTS: raise InvalidJob( f"Receipt is too long: about {height // DOTS_PER_MM} mm, " f"the limit is {MAX_PRINT_HEIGHT_DOTS // DOTS_PER_MM} mm." ) def build(p: printer.Escpos) -> None: for block in blocks: block.build(p) return render(build) def render_note(text: str, timestamp: bool = False, size: int = 1) -> bytes: return render_blocks([text_block(text, size, timestamp)]) def render_image(source: Path | BinaryIO, caption: str | None = None) -> bytes: return render_blocks([image_block(source, caption)]) def render_qr(content: str, caption: str | None = None) -> bytes: return render_blocks([qr_block(content, caption)]) def _printable(thread: dict) -> bool: """True when the thread's OP image is safe to cache and print. Whitelist the extension (remote data, never trusted) and require a positive integer tim so the filename can't escape IMG_DIR. """ tim, ext = thread.get("tim"), thread.get("ext", "") return ( isinstance(tim, int) and tim > 0 and isinstance(ext, str) and ext.lower() in PRINTABLE_EXTENSIONS ) def fetch_capped(url: str, max_bytes: int, headers: dict | None = None) -> bytes | None: """GET a URL into memory; None if the body is over max_bytes. The body is streamed so the cap fires before a huge response is fully in memory. HTTP errors raise requests exceptions. """ extra = {"headers": headers} if headers else {} with requests.get(url, timeout=HTTP_TIMEOUT, stream=True, **extra) as response: response.raise_for_status() buf = io.BytesIO() size = 0 for chunk in response.iter_content(64 * 1024): size += len(chunk) if size > max_bytes: return None buf.write(chunk) return buf.getvalue() def download_random_bant_image() -> Path | None: """Download a random OP image from 4chan's /bant/ catalog. Reuses the local copy if the chosen image is already cached. """ IMG_DIR.mkdir(exist_ok=True) response = requests.get(BANT_CATALOG_URL, timeout=HTTP_TIMEOUT) response.raise_for_status() catalog = response.json() threads = [thread for page in catalog for thread in page["threads"]] image_threads = [t for t in threads if _printable(t)] if not image_threads: return None # noqa: S311 — random pick is a convenience choice among catalog entries, not a security decision thread = random.choice(image_threads) # noqa: S311 - non-security choice ext = thread["ext"].lower() dest = IMG_DIR / f"{thread['tim']}{ext}" if dest.is_file(): return dest data = fetch_capped(BANT_IMAGE_URL.format(tim=thread["tim"], ext=ext), MAX_IMAGE_BYTES) if data is None: print( f"Skipping {dest.name}: exceeds the {MAX_IMAGE_BYTES // 1024} KB cap.", file=sys.stderr, ) return None dest.write_bytes(data) return dest def cached_images() -> list[Path]: """Cached images, newest first.""" if not IMG_DIR.is_dir(): return [] return sorted( (f for f in IMG_DIR.iterdir() if f.is_file()), key=lambda f: f.stat().st_mtime, reverse=True, ) def cmd_image(config: PrinterConfig, args: argparse.Namespace) -> int: printed = 0 for _ in range(args.count): img = download_random_bant_image() if img is None: # Keep going: one skipped image shouldn't discard the rest of the run. print("No printable image found; skipping.", file=sys.stderr) continue try: payload = render_image(img, caption=img.stem) except InvalidJob as e: print(f"Skipping {img.name}: {e}", file=sys.stderr) continue send(config, payload) printed += 1 if printed == 0: print("No images printed.", file=sys.stderr) return 1 return 0 def cmd_note(config: PrinterConfig, args: argparse.Namespace) -> int: text = args.text if text is None or text == "-": text = sys.stdin.read().rstrip("\n") send(config, render_note(text, args.timestamp, getattr(args, "size", 1))) return 0 def cmd_print(config: PrinterConfig, args: argparse.Namespace) -> int: # `data` is in-memory image bytes; it is never written to disk. data = getattr(args, "data", None) if data is not None: source: Path | BinaryIO = io.BytesIO(data) elif args.path.is_file(): source = args.path else: raise InvalidJob(f"File not found: {args.path}") send(config, render_image(source, args.message)) return 0 def cmd_qr(config: PrinterConfig, args: argparse.Namespace) -> int: send(config, render_qr(args.content, args.message)) return 0 def cmd_reprint(config: PrinterConfig, args: argparse.Namespace) -> int: images = cached_images() if not images: raise InvalidJob("Image cache is empty.") if args.name: matches = [f for f in images if f.name == args.name or f.stem == args.name] if not matches: raise InvalidJob(f"No cached image named {args.name!r}. Try './receipt.py list'.") target = matches[0] else: target = images[0] send(config, render_image(target, caption=target.stem)) return 0 def cmd_status(config: PrinterConfig) -> int: close_quietly(connect(config)) print(f"Printer reachable ({config.target}).") return 0 def cmd_list() -> int: images = cached_images() if not images: print("Image cache is empty.") return 0 total_bytes = 0 for f in images: size = f.stat().st_size total_bytes += size print(f"{f.name} ({size // 1024} KB)") print(f"\n{len(images)} image(s), {total_bytes / 1024 / 1024:.1f} MB total") return 0 def cmd_clean(yes: bool = False) -> int: """Remove cached images and the legacy full-width directory. Unlinks files instead of rmtree so a stray file outside the cache can never be deleted; the dirs are left in place. """ images = cached_images() legacy_files = ( [f for f in LEGACY_FULLWIDTH_DIR.iterdir() if f.is_file()] if LEGACY_FULLWIDTH_DIR.is_dir() else [] ) if not images and not legacy_files: print("Nothing to clean.") return 0 if not yes: reply = input( f"Delete {len(images) + len(legacy_files)} cached image(s)? [y/N] " ) if reply.strip().lower() not in ("y", "yes"): print("Aborted.") return 1 for f in images: f.unlink() for f in legacy_files: f.unlink() print(f"Removed {len(images) + len(legacy_files)} cached image(s).") return 0 PRINT_COMMANDS = { "image": cmd_image, "note": cmd_note, "print": cmd_print, "qr": cmd_qr, "reprint": cmd_reprint, } def run_command(command: str, args: argparse.Namespace) -> int: """Run one subcommand. InvalidJob, PrinterUnavailable and download errors propagate.""" if command == "list": return cmd_list() if command == "clean": return cmd_clean(getattr(args, "yes", False)) config = PrinterConfig.from_args(args) if command == "status": return cmd_status(config) return PRINT_COMMANDS[command](config, args) @dataclass(frozen=True) class ActionResult: rc: int output: str error: str | None = None # "invalid", "unavailable" or "failed" whenever rc != 0 def run_action(command: str, base: argparse.Namespace, **params) -> ActionResult: """Run a command with its terminal output captured (used by the TUI). Every action connects fresh, so a dropped printer never leaves the caller holding a dead handle. redirect_stdout is process-global, so concurrent callers must serialize. """ # No TTY to prompt on: the button press is the confirmation. defaults = {"yes": True} if command == "clean" else {} args = argparse.Namespace( **{**vars(base), **defaults, **params, "command": command, "quiet_setup": True} ) buf = io.StringIO() error = None with contextlib.redirect_stdout(buf), contextlib.redirect_stderr(buf): try: rc = run_command(command, args) except InvalidJob as e: print(e) rc, error = 1, "invalid" except PrinterUnavailable as e: print(f"Printer unavailable: {e}") rc, error = 1, "unavailable" except Exception as e: print(f"Error: {e}") rc, error = 1, "failed" if rc != 0 and error is None: error = "failed" return ActionResult(rc, buf.getvalue().rstrip(), error) def _valid_ip(value: str) -> str: # The IP is interpolated into the connect script's environment; reject shell metacharacters. try: ipaddress.ip_address(value.strip()) except ValueError: raise argparse.ArgumentTypeError(f"not a valid IP address: {value!r}") from None return value.strip() def positive_int(value: str) -> int: n = int(value) if n < 1: raise argparse.ArgumentTypeError("count must be at least 1") return n def build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(description="Receipt printer CLI") parser.add_argument( "--usb", action="store_true", help="Connect over USB instead of Ethernet (skips network setup)", ) parser.add_argument( "--ip", type=_valid_ip, default=DEFAULT_PRINTER_IP, help=f"Printer IP address (default: {DEFAULT_PRINTER_IP}, env RECEIPT_PRINTER_IP)", ) parser.add_argument( "--port", type=int, default=DEFAULT_PRINTER_PORT, help=f"Printer port (default: {DEFAULT_PRINTER_PORT}, env RECEIPT_PRINTER_PORT)", ) parser.add_argument( "--no-setup", action="store_true", help="Don't run the connect script (the printer link is already configured)", ) subparsers = parser.add_subparsers(dest="command", required=True) image_p = subparsers.add_parser("image", help="Print random /bant/ images") image_p.add_argument( "count", nargs="?", type=positive_int, default=1, help="Number of images to print (default: 1)", ) note_p = subparsers.add_parser("note", help="Print a text note") note_p.add_argument( "text", nargs="?", default=None, help="The note to print ('-' or omitted to read from stdin)", ) note_p.add_argument( "-t", "--timestamp", action="store_true", help="Print a date/time header above the note", ) note_p.add_argument( "-s", "--size", type=int, choices=TEXT_SIZES, default=1, help="Text magnification (default: 1, 48 columns; 2 is 24, 3 is 16)", ) print_p = subparsers.add_parser("print", help="Print a local image") print_p.add_argument("path", type=Path, help="Path to the image file") print_p.add_argument("message", nargs="?", default=None, help="Optional caption") qr_p = subparsers.add_parser("qr", help="Print a QR code") qr_p.add_argument("content", help="Text or URL to encode") qr_p.add_argument("message", nargs="?", default=None, help="Optional caption") reprint_p = subparsers.add_parser("reprint", help="Reprint a cached image") reprint_p.add_argument( "name", nargs="?", default=None, help="Cached image filename or stem (default: most recent)", ) subparsers.add_parser("status", help="Check whether the printer is reachable") subparsers.add_parser("list", help="List the downloaded image cache") clean_p = subparsers.add_parser("clean", help="Delete the downloaded image cache") clean_p.add_argument( "-y", "--yes", action="store_true", help="Skip the confirmation prompt" ) subparsers.add_parser("tui", help="Open the interactive terminal UI") serve_p = subparsers.add_parser("serve", help="Run the web server for printing from the site") serve_p.add_argument( "--listen", default=os.environ.get("RECEIPT_WEB_LISTEN", DEFAULT_WEB_LISTEN), help=f"host:port to bind (default: {DEFAULT_WEB_LISTEN}, env RECEIPT_WEB_LISTEN)", ) return parser def main() -> int: args = build_parser().parse_args() if args.command == "tui": try: from receipt_tui import run_tui except ModuleNotFoundError as e: print( f"The TUI needs the 'textual' package ({e}). " "Install it with: pip install 'receipt-maker[tui]' or pip install textual", file=sys.stderr, ) return 1 return run_tui(args) if args.command == "serve": try: from receipt_web import serve except ModuleNotFoundError as e: print( f"The web server needs extra packages ({e}). " "Install them with: pip install 'receipt-maker[web]'", file=sys.stderr, ) return 1 return serve(args) try: return run_command(args.command, args) except InvalidJob as e: print(e, file=sys.stderr) return 1 except PrinterUnavailable as e: print(f"Printer unavailable: {e}", file=sys.stderr) return 1 except requests.RequestException as e: print(f"Download failed: {e}", file=sys.stderr) return 1 except KeyboardInterrupt: print("Aborted.", file=sys.stderr) return 130 if __name__ == "__main__": sys.exit(main())