Add tests, TUI, packaging, and CI
CI / test (push) Failing after 6m11s

- receipt_tui.py: Textual terminal UI (tui subcommand), optional [tui] extra
- tests/: pytest suite for CLI and TUI using fakes; no hardware needed
- pyproject.toml: packaging with dev/tui extras, ruff config
- GitHub Actions CI running ruff and pytest
- Rename connect_recipt.sh -> connect_receipt.sh
- CLAUDE.md project instructions; README updates

Co-Authored-By: Claude Fable 5 <[email protected]>
This commit is contained in:
2026-08-11 19:53:18 +01:00
co-authored by Claude Fable 5
parent 5fdbcb7468
commit 71686e8ad4
11 changed files with 1114 additions and 158 deletions
+17
View File
@@ -0,0 +1,17 @@
name: CI
on:
push:
pull_request:
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: "3.12"
- run: pip install -e '.[dev]'
- run: ruff check .
- run: pytest
+1
View File
@@ -5,3 +5,4 @@ __pycache__/
*.pyc *.pyc
*.pyo *.pyo
.env .env
.venv/
+26
View File
@@ -0,0 +1,26 @@
# Receipt Maker
CLI that prints images, notes, and QR codes to an Epson TM-T20II thermal receipt printer (Ethernet via USB adapter, or direct USB with `--usb`).
## Layout
- `receipt.py` — the CLI; subcommand per `cmd_*` function
- `receipt_tui.py` — Textual TUI (`tui` subcommand); thin layer over the `cmd_*` handlers via `run_action()`, which connects fresh per action and captures stdout/stderr for the log panel. `textual` is an optional dependency (`[tui]` extra); the CLI works without it
- `connect_receipt.sh` — brings up the printer's network interface (needs sudo); run automatically before any print over Ethernet. The TUI runs it with output captured (`setup_network_quiet`) so it can't corrupt the screen
- `tests/` — pytest suite; uses `FakePrinter` + mocked `requests`, never touches hardware or network
## Conventions
- Printer/network constants live at the top of `receipt.py`; IP/port overridable via `--ip`/`--port` or `RECEIPT_PRINTER_IP`/`RECEIPT_PRINTER_PORT`
- Images are prepared in memory (`prepare_for_print`: white-composite alpha → resize to 576px → autocontrast → 1-bit dither); nothing is written except the `img/` download cache
- `print_image()` reconnects and retries once on failure and returns the (possibly new) printer handle — callers must rebind `p`
- Commands that don't need the printer (`list`, `clean`) or handle their own connection (`status`) are dispatched in `main()` before connecting
## Checks
```bash
pytest # required
ruff check . # lint (config in pyproject.toml)
```
Actual printing can only be verified with the physical printer attached.
+62 -19
View File
@@ -1,40 +1,83 @@
# Receipt Maker # Receipt Maker
Prints random images from 4chan's /bant/ board to an Epson TM-T20II thermal receipt printer over Ethernet. Prints images, text notes, and QR codes to an Epson TM-T20II thermal receipt printer, including random images from 4chan's /bant/ board.
## How it works ## How it works
1. `connect_recipt.sh` — configures the network interface and connects to the printer at `192.168.192.168:9100` 1. `connect_receipt.sh` — brings up the USB Ethernet interface, assigns `192.168.192.10/24`, and waits until the printer at `192.168.192.168:9100` is reachable
2. `receipt.py` — CLI with subcommands to print random /bant/ images, text notes, or local images (resized to full printer width, 576px) 2. `receipt.py` — CLI with subcommands; images are resized in memory to the printer's full 576px width before printing
The CLI runs the connect script automatically before printing (unless `--usb` is used).
## Requirements ## Requirements
- Python 3 - Python 3.10+
- `python-escpos` - `python-escpos`, `Pillow`, `requests` (see `pyproject.toml`)
- `Pillow` - `textual` (optional, only for the `tui` subcommand; `pip install '.[tui]'`)
- `requests` - Epson TM-T20II connected via a USB-to-Ethernet adapter (or directly over USB with `--usb`)
- `nmap` (for connection script)
- Epson TM-T20II connected via USB-to-Ethernet adapter Install the dependencies (or `pip install .` to also get a `receipt` command on your PATH):
```bash
pip install python-escpos Pillow requests
```
## Usage ## Usage
```bash ```bash
# Print a random image from /bant/ # Print a random image from /bant/ (optionally more than one)
python receipt.py image ./receipt.py image
./receipt.py image 3
# Print a text note # Print a text note (from an argument or stdin), word-wrapped to 48 columns
python receipt.py note "your message here" ./receipt.py note "your message here"
fortune | ./receipt.py note
./receipt.py note -t "with a date/time header"
# Print a local image (with optional caption) # Print a local image (with optional caption)
python receipt.py print path/to/image.jpg ./receipt.py print path/to/image.jpg
python receipt.py print path/to/image.jpg "optional caption" ./receipt.py print path/to/image.jpg "optional caption"
# Print a QR code (with optional caption)
./receipt.py qr "https://example.com" "scan me"
# Reprint a cached image (most recent, or by name from `list`)
./receipt.py reprint
./receipt.py reprint 1783716801701399
# Check the printer is reachable
./receipt.py status
# List or delete the downloaded image cache
./receipt.py list
./receipt.py clean
# Open the interactive terminal UI (needs `pip install textual`)
./receipt.py tui
# Use a direct USB connection instead of Ethernet
./receipt.py --usb note "hello"
# Point at a different printer (or set RECEIPT_PRINTER_IP / RECEIPT_PRINTER_PORT)
./receipt.py --ip 10.0.0.5 --port 9100 status
``` ```
The script will run `connect_recipt.sh` automatically to bring up the network interface before printing. Images are prepared for thermal output automatically: transparency is composited onto white, then the image is resized to full width, autocontrast-stretched, and Floyd-Steinberg dithered.
## Development
```bash
pip install -e '.[dev]'
pytest # run the tests
ruff check . # lint
```
Both checks also run in CI on every push and pull request (`.github/workflows/ci.yml`).
## Files ## Files
- `receipt.py` — main script - `receipt.py` — main script
- `connect_recipt.sh` — network setup for USB Ethernet adapter - `receipt_tui.py` — Textual terminal UI (`./receipt.py tui`)
- `img/` — downloaded images cache - `connect_receipt.sh` — network setup for the USB Ethernet adapter
- `img_fullwidth/` — resized images ready for printing - `tests/` — pytest suite for the CLI and TUI (no printer or network needed)
- `img/` — downloaded images cache (gitignored; clear with `./receipt.py clean`)
+42
View File
@@ -0,0 +1,42 @@
#!/bin/bash
# Bring up the network interface for the Epson TM-T20II and verify it is reachable.
set -euo pipefail
PRINTER_IP="192.168.192.168"
PRINTER_PORT=9100
HOST_ADDR="192.168.192.10/24"
# Prefer a USB Ethernet interface; fall back to eth0
iface=$(ip -o link | awk -F': ' '/enx|enp.*u/{print $2}' | head -n 1)
if [ -z "$iface" ]; then
if ip link show eth0 &>/dev/null; then
iface="eth0"
echo "USB Ethernet not found. Using eth0."
else
echo "No suitable interface found." >&2
exit 1
fi
else
echo "Using USB Ethernet interface: $iface"
fi
# Bring interface up before assigning IP
sudo ip link set "$iface" up
# Assign our address on the printer's subnet if not already set
if ! ip addr show dev "$iface" | grep -q "${HOST_ADDR%/*}"; then
sudo ip addr add "$HOST_ADDR" dev "$iface"
fi
# Wait for the printer port to become reachable (interface may need a moment)
for attempt in {1..5}; do
if timeout 2 bash -c "exec 3<>/dev/tcp/$PRINTER_IP/$PRINTER_PORT" 2>/dev/null; then
echo "Printer reachable at $PRINTER_IP:$PRINTER_PORT"
exit 0
fi
sleep 1
done
echo "Printer port $PRINTER_PORT is not open at $PRINTER_IP." >&2
exit 1
-33
View File
@@ -1,33 +0,0 @@
#!/bin/bash
set -e
# Try to find the USB Ethernet interface first
iface=$(ip -o link | awk -F': ' '/enx|enp.*u/{print $2}' | head -n 1)
# If no USB interface, fall back to eth0
if [ -z "$iface" ]; then
if ip link show eth0 &>/dev/null; then
iface="eth0"
echo "USB Ethernet not found. Using eth0."
else
echo "No suitable interface found."
exit 1
fi
else
echo "Using USB Ethernet interface: $iface"
fi
# Bring interface up before assigning IP
sudo ip link set "$iface" up
# Assign IP address if not already set
if ! ip addr show dev "$iface" | grep -q "192.168.192.10"; then
sudo ip addr add 192.168.192.10/24 dev "$iface"
fi
# Scan port 9100 on the printer IP and verify it is open
if ! nmap -p 9100 --open 192.168.192.168 | grep -q "9100/tcp open"; then
echo "Printer port 9100 is not open."
exit 1
fi
+40
View File
@@ -0,0 +1,40 @@
[project]
name = "receipt-maker"
version = "1.0.0"
description = "Print images and text notes to an Epson TM-T20II thermal receipt printer"
requires-python = ">=3.10"
dependencies = [
"python-escpos>=3.0",
"Pillow>=10.0",
"requests>=2.31",
]
[project.optional-dependencies]
tui = [
"textual>=1.0",
]
dev = [
"pytest>=8.0",
"ruff>=0.4",
"textual>=1.0",
]
[project.scripts]
receipt = "receipt:main"
[build-system]
requires = ["setuptools>=68"]
build-backend = "setuptools.build_meta"
[tool.setuptools]
py-modules = ["receipt", "receipt_tui"]
[tool.ruff]
line-length = 100
target-version = "py310"
[tool.ruff.lint]
select = ["E", "F", "W", "I", "UP", "B", "SIM"]
[tool.pytest.ini_options]
testpaths = ["tests"]
+302 -106
View File
@@ -1,162 +1,358 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
"""CLI for printing images and text notes to an Epson TM-T20II receipt printer."""
from escpos import printer from __future__ import annotations
from PIL import Image
import argparse
import os import os
import subprocess
import random import random
import shutil
import subprocess
import sys
import textwrap
from datetime import datetime
from pathlib import Path
import requests import requests
from escpos import printer
from PIL import Image, ImageOps
DEFAULT_PRINTER_IP = os.environ.get("RECEIPT_PRINTER_IP", "192.168.192.168")
DEFAULT_PRINTER_PORT = int(os.environ.get("RECEIPT_PRINTER_PORT", "9100"))
USB_VENDOR_ID = 0x04B8
USB_PRODUCT_ID = 0x0202
PRINT_WIDTH_PX = 576 # printable width of the TM-T20II at 203 dpi
TEXT_COLUMNS = 48 # font A columns on 80mm paper
HTTP_TIMEOUT = 15 # seconds
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}"
UNPRINTABLE_EXTENSIONS = {".gif", ".mp4", ".webm"}
# Return T20II printer def setup_network() -> None:
def get_T20II_usb(): """Bring up the printer's network interface via the connect script."""
p = printer.Usb(0x04B8, 0x0202) # , profile="TM-T20II") subprocess.run(["bash", str(CONNECT_SCRIPT)], check=True)
# p.set_with_default(align='center', font='a', bold=False, width=2, height=2, custom_size=True, smooth=True)
return p
def get_T20II_ethernet(): def get_printer(args: argparse.Namespace) -> printer.Escpos:
p = printer.Network("192.168.192.168", port=9100) # , profile="TM-T20II") if args.usb:
# p.set_with_default(align='center', font='a', bold=False, width=2, height=2, custom_size=True, smooth=True) return printer.Usb(USB_VENDOR_ID, USB_PRODUCT_ID)
return p return printer.Network(args.ip, port=args.port)
def resize_image_to_fullwidth(img_src_name, target_width=576): def prepare_for_print(img_path: Path) -> Image.Image:
# Make fullwidth dir """Load an image resized to full printer width and dithered for thermal output.
os.makedirs("img_fullwidth", exist_ok=True)
# Open the image Transparency is composited onto white (thermal paper), then the image is
img = Image.open(img_src_name) autocontrast-stretched and Floyd-Steinberg dithered to 1-bit.
"""
# Get original dimensions with Image.open(img_path) as img:
width, height = img.size if img.mode in ("RGBA", "LA") or (img.mode == "P" and "transparency" in img.info):
rgba = img.convert("RGBA")
# Calculate new height to maintain aspect ratio background = Image.new("RGBA", rgba.size, "white")
aspect_ratio = height / width img = Image.alpha_composite(background, rgba)
new_height = int(target_width * aspect_ratio) width, height = img.size
new_height = round(PRINT_WIDTH_PX * height / width)
# Resize the image resized = img.resize((PRINT_WIDTH_PX, new_height), Image.LANCZOS)
resized_img = img.resize((target_width, new_height), Image.LANCZOS) return ImageOps.autocontrast(resized.convert("L")).convert("1")
# Save the resized image
_, ext = os.path.splitext(img_src_name)
filename_no_ext = os.path.splitext(os.path.basename(img_src_name))[0]
# Build destination filename
dest_name = f"img_fullwidth/{filename_no_ext}_fullwidth{ext}"
resized_img.save(dest_name)
return dest_name
def get_random_bant_image(): def wrap_text(text: str) -> str:
# Create img directory if it doesn't exist """Word-wrap text to the printer's column width, preserving blank lines."""
os.makedirs("img", exist_ok=True) lines = []
for line in text.splitlines():
lines.append(textwrap.fill(line, TEXT_COLUMNS) if line.strip() else "")
return "\n".join(lines)
# Fetch the catalog JSON for /bant/
url = "https://a.4cdn.org/bant/catalog.json" def download_random_bant_image() -> Path | None:
response = requests.get(url) """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() response.raise_for_status()
catalog = response.json() catalog = response.json()
# Flatten the list of threads from all pages
threads = [thread for page in catalog for thread in page["threads"]] threads = [thread for page in catalog for thread in page["threads"]]
# Filter threads that have images (tim and ext fields)
image_threads = [ image_threads = [
thread t
for thread in threads for t in threads
if "tim" in thread if "tim" in t and "ext" in t and t["ext"].lower() not in UNPRINTABLE_EXTENSIONS
and "ext" in thread
and thread["ext"].lower() not in [".gif", ".mp4", ".webm"]
] ]
if not image_threads: if not image_threads:
return None # No images found return None
# Choose a random thread with an image
thread = random.choice(image_threads) thread = random.choice(image_threads)
dest = IMG_DIR / f"{thread['tim']}{thread['ext']}"
if dest.is_file():
return dest
# Construct image URL image_url = BANT_IMAGE_URL.format(tim=thread["tim"], ext=thread["ext"])
image_url = f"https://i.4cdn.org/bant/{thread['tim']}{thread['ext']}" img_response = requests.get(image_url, timeout=HTTP_TIMEOUT)
filename = f"img/{thread['tim']}{thread['ext']}"
# Download and save image
img_response = requests.get(image_url)
img_response.raise_for_status() img_response.raise_for_status()
dest.write_bytes(img_response.content)
with open(filename, "wb") as f: return dest
f.write(img_response.content)
return filename
def print_random_bant_image(p, sh_file): def cached_images() -> list[Path]:
img = get_random_bant_image() """Cached images, newest first."""
if img is None: if not IMG_DIR.is_dir():
print("No images found on /bant/.") return []
return return sorted(
filename_no_ext = os.path.splitext(os.path.basename(img))[0] (f for f in IMG_DIR.iterdir() if f.is_file()),
p.textln(filename_no_ext) key=lambda f: f.stat().st_mtime,
fimg = resize_image_to_fullwidth(img) reverse=True,
)
def print_image(p: printer.Escpos, img_path: Path, args: argparse.Namespace) -> printer.Escpos:
"""Print an image, reconnecting and retrying once if the printer drops.
Returns the (possibly reconnected) printer so the caller keeps a live handle.
"""
prepared = prepare_for_print(img_path)
try: try:
p.image(fimg, impl="bitImageColumn") p.image(prepared, impl="bitImageColumn")
except Exception as e: except Exception as e:
print(f"Print failed, reconnecting: {e}") print(f"Print failed ({e}); reconnecting...", file=sys.stderr)
subprocess.run(["bash", sh_file], check=True) if not args.usb:
p = get_T20II_ethernet() setup_network()
p = get_printer(args)
p.image(prepared, impl="bitImageColumn")
return p
def cmd_image(p: printer.Escpos, args: argparse.Namespace) -> int:
for _ in range(args.count):
img = download_random_bant_image()
if img is None:
print("No images found on /bant/.", file=sys.stderr)
return 1
p.textln(img.stem)
p = print_image(p, img, args)
p.cut()
return 0
def cmd_note(p: printer.Escpos, args: argparse.Namespace) -> int:
text = args.text
if text is None or text == "-":
text = sys.stdin.read().rstrip("\n")
if not text:
print("Nothing to print.", file=sys.stderr)
return 1
if args.timestamp:
p.textln(datetime.now().strftime("%Y-%m-%d %H:%M"))
p.textln("-" * TEXT_COLUMNS)
p.textln(wrap_text(text))
p.cut() p.cut()
return 0
def print_note(p, text): def cmd_print(p: printer.Escpos, args: argparse.Namespace) -> int:
p.textln(text) if not args.path.is_file():
print(f"File not found: {args.path}", file=sys.stderr)
return 1
if args.message:
p.textln(wrap_text(args.message))
p = print_image(p, args.path, args)
p.cut() p.cut()
return 0
def print_local_image(p, sh_file, img_path, message=None): def cmd_qr(p: printer.Escpos, args: argparse.Namespace) -> int:
if not os.path.isfile(img_path): if args.message:
print(f"File not found: {img_path}") p.textln(wrap_text(args.message))
return p.qr(args.content, size=8, center=True)
if message: p.cut()
p.textln(message) return 0
fimg = resize_image_to_fullwidth(img_path)
def cmd_reprint(p: printer.Escpos, args: argparse.Namespace) -> int:
images = cached_images()
if not images:
print("Image cache is empty.", file=sys.stderr)
return 1
if args.name:
matches = [f for f in images if f.name == args.name or f.stem == args.name]
if not matches:
print(f"No cached image named {args.name!r}. Try './receipt.py list'.", file=sys.stderr)
return 1
target = matches[0]
else:
target = images[0]
p.textln(target.stem)
p = print_image(p, target, args)
p.cut()
return 0
def cmd_status(args: argparse.Namespace) -> int:
try: try:
p.image(fimg, impl="bitImageColumn") if not args.usb:
setup_network()
p = get_printer(args)
p.close()
except Exception as e: except Exception as e:
print(f"Print failed, reconnecting: {e}") print(f"Printer unreachable: {e}", file=sys.stderr)
subprocess.run(["bash", sh_file], check=True) return 1
p = get_T20II_ethernet() target = "USB" if args.usb else f"{args.ip}:{args.port}"
p.cut() print(f"Printer reachable ({target}).")
return 0
def main(): def cmd_list() -> int:
import argparse 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() -> int:
removed = 0
if IMG_DIR.is_dir():
removed = sum(1 for f in IMG_DIR.iterdir() if f.is_file())
shutil.rmtree(IMG_DIR)
if LEGACY_FULLWIDTH_DIR.is_dir():
removed += sum(1 for f in LEGACY_FULLWIDTH_DIR.iterdir() if f.is_file())
shutil.rmtree(LEGACY_FULLWIDTH_DIR)
print(f"Removed {removed} cached image(s).")
return 0
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 = 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",
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)",
)
subparsers = parser.add_subparsers(dest="command", required=True) subparsers = parser.add_subparsers(dest="command", required=True)
subparsers.add_parser("image", help="Print a random /bant/ image") 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 = subparsers.add_parser("note", help="Print a text note")
note_p.add_argument("text", help="The note to print") 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",
)
print_p = subparsers.add_parser("print", help="Print a local image") print_p = subparsers.add_parser("print", help="Print a local image")
print_p.add_argument("path", help="Path to the image file") print_p.add_argument("path", type=Path, help="Path to the image file")
print_p.add_argument("message", nargs="?", default=None, help="Optional caption") print_p.add_argument("message", nargs="?", default=None, help="Optional caption")
args = parser.parse_args() 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")
script_dir = os.path.dirname(os.path.abspath(__file__)) reprint_p = subparsers.add_parser("reprint", help="Reprint a cached image")
sh_file = os.path.join(script_dir, "connect_recipt.sh") reprint_p.add_argument(
subprocess.run(["bash", sh_file], check=True) "name",
p = get_T20II_ethernet() nargs="?",
default=None,
help="Cached image filename or stem (default: most recent)",
)
if args.command == "image": subparsers.add_parser("status", help="Check whether the printer is reachable")
print_random_bant_image(p, sh_file) subparsers.add_parser("list", help="List the downloaded image cache")
elif args.command == "note": subparsers.add_parser("clean", help="Delete the downloaded image cache")
print_note(p, args.text) subparsers.add_parser("tui", help="Open the interactive terminal UI")
elif args.command == "print":
print_local_image(p, sh_file, args.path, args.message) 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 == "list":
return cmd_list()
if args.command == "clean":
return cmd_clean()
if args.command == "status":
return cmd_status(args)
try:
if not args.usb:
setup_network()
p = get_printer(args)
except Exception as e:
print(f"Could not connect to printer: {e}", file=sys.stderr)
return 1
commands = {
"image": cmd_image,
"note": cmd_note,
"print": cmd_print,
"qr": cmd_qr,
"reprint": cmd_reprint,
}
try:
return commands[args.command](p, args)
except requests.RequestException as e:
print(f"Download failed: {e}", file=sys.stderr)
return 1
if __name__ == "__main__": if __name__ == "__main__":
main() sys.exit(main())
+271
View File
@@ -0,0 +1,271 @@
#!/usr/bin/env python3
"""Textual TUI for the receipt printer; launched via `./receipt.py tui`."""
from __future__ import annotations
import argparse
import contextlib
import io
import subprocess
from pathlib import Path
from textual import work
from textual.app import App, ComposeResult
from textual.containers import Horizontal, Vertical
from textual.widgets import (
Button,
ContentSwitcher,
Footer,
Header,
Input,
Label,
ListItem,
ListView,
RichLog,
Switch,
TextArea,
)
import receipt
ACTIONS = [
("note", "Note"),
("image", "Random image"),
("print", "Print file"),
("qr", "QR code"),
("reprint", "Reprint cached"),
("status", "Printer status"),
("cache", "Image cache"),
]
def setup_network_quiet() -> None:
"""Run the connect script with output captured so it can't corrupt the TUI."""
result = subprocess.run(
["bash", str(receipt.CONNECT_SCRIPT)], capture_output=True, text=True
)
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 run_action(command: str, base: argparse.Namespace, **params) -> tuple[int, str]:
"""Run a receipt.py command handler, capturing its terminal output.
Mirrors main(): every action connects fresh, so a dropped printer never
leaves the TUI holding a dead handle.
"""
args = argparse.Namespace(**{**vars(base), **params, "command": command})
buf = io.StringIO()
with contextlib.redirect_stdout(buf), contextlib.redirect_stderr(buf):
try:
rc = _dispatch(command, args)
except Exception as e:
print(f"Error: {e}")
rc = 1
return rc, buf.getvalue().rstrip()
def _dispatch(command: str, args: argparse.Namespace) -> int:
if command == "list":
return receipt.cmd_list()
if command == "clean":
return receipt.cmd_clean()
if command == "status":
return receipt.cmd_status(args)
if not args.usb:
setup_network_quiet()
p = receipt.get_printer(args)
handlers = {
"image": receipt.cmd_image,
"note": receipt.cmd_note,
"print": receipt.cmd_print,
"qr": receipt.cmd_qr,
"reprint": receipt.cmd_reprint,
}
return handlers[command](p, args)
class ReceiptApp(App):
TITLE = "Receipt Maker"
BINDINGS = [("q", "quit", "Quit")]
CSS = """
#nav {
width: 22;
border-right: solid $primary;
}
#panes {
padding: 1 2;
}
#panes Label {
margin-top: 1;
}
#panes Button {
margin-top: 1;
}
#note-text {
height: 8;
}
#reprint-list {
height: 10;
border: solid $primary;
}
.row {
height: auto;
margin-top: 1;
}
.row Label {
margin: 1 0 0 2;
}
#log {
dock: bottom;
height: 30%;
border-top: solid $primary;
}
"""
def __init__(self, base_args: argparse.Namespace):
super().__init__()
self.base_args = base_args
def compose(self) -> ComposeResult:
yield Header()
with Horizontal():
yield ListView(
*(ListItem(Label(label), name=key) for key, label in ACTIONS),
id="nav",
)
with ContentSwitcher(initial="pane-note", id="panes"):
with Vertical(id="pane-note"):
yield Label("Note text")
yield TextArea(id="note-text")
with Horizontal(classes="row"):
yield Switch(id="note-timestamp")
yield Label("Date/time header")
yield Button("Print note", id="do-note", variant="primary")
with Vertical(id="pane-image"):
yield Label("How many random /bant/ images")
yield Input(value="1", id="image-count", type="integer")
yield Button("Print", id="do-image", variant="primary")
with Vertical(id="pane-print"):
yield Label("Path to image file")
yield Input(id="print-path", placeholder="/path/to/image.jpg")
yield Label("Caption (optional)")
yield Input(id="print-caption")
yield Button("Print", id="do-print", variant="primary")
with Vertical(id="pane-qr"):
yield Label("Text or URL to encode")
yield Input(id="qr-content", placeholder="https://example.com")
yield Label("Caption (optional)")
yield Input(id="qr-caption")
yield Button("Print QR", id="do-qr", variant="primary")
with Vertical(id="pane-reprint"):
yield Label("Cached images (newest first)")
yield ListView(id="reprint-list")
yield Button("Reprint selected", id="do-reprint", variant="primary")
with Vertical(id="pane-status"):
yield Label("Check whether the printer is reachable")
yield Button("Check status", id="do-status", variant="primary")
with Vertical(id="pane-cache"):
yield Label("Downloaded image cache")
yield Button("List cache", id="do-list", variant="primary")
yield Button("Clean cache", id="do-clean", variant="error")
yield RichLog(id="log", wrap=True, markup=True)
yield Footer()
def on_mount(self) -> None:
target = "USB" if self.base_args.usb else f"{self.base_args.ip}:{self.base_args.port}"
self.log_panel.write(f"[dim]Printer target: {target}[/dim]")
self.refresh_cache_list()
@property
def log_panel(self) -> RichLog:
return self.query_one("#log", RichLog)
def refresh_cache_list(self) -> None:
lv = self.query_one("#reprint-list", ListView)
lv.clear()
lv.extend(ListItem(Label(f.name), name=f.name) for f in receipt.cached_images())
def on_list_view_highlighted(self, event: ListView.Highlighted) -> None:
if event.list_view.id != "nav" or event.item is None:
return
key = event.item.name
self.query_one("#panes", ContentSwitcher).current = f"pane-{key}"
if key == "reprint":
self.refresh_cache_list()
def on_button_pressed(self, event: Button.Pressed) -> None:
button_id = event.button.id
if button_id == "do-note":
text = self.query_one("#note-text", TextArea).text.strip()
if not text:
self.log_panel.write("[red]Nothing to print.[/red]")
return
timestamp = self.query_one("#note-timestamp", Switch).value
self.run_action_worker("note", text=text, timestamp=timestamp)
elif button_id == "do-image":
raw = self.query_one("#image-count", Input).value or "1"
try:
count = receipt.positive_int(raw)
except (ValueError, argparse.ArgumentTypeError):
self.log_panel.write("[red]Count must be a positive integer.[/red]")
return
self.run_action_worker("image", count=count)
elif button_id == "do-print":
path = self.query_one("#print-path", Input).value.strip()
if not path:
self.log_panel.write("[red]Enter a file path.[/red]")
return
caption = self.query_one("#print-caption", Input).value.strip() or None
self.run_action_worker(
"print", path=Path(path).expanduser(), message=caption
)
elif button_id == "do-qr":
content = self.query_one("#qr-content", Input).value.strip()
if not content:
self.log_panel.write("[red]Enter something to encode.[/red]")
return
caption = self.query_one("#qr-caption", Input).value.strip() or None
self.run_action_worker("qr", content=content, message=caption)
elif button_id == "do-reprint":
selected = self.query_one("#reprint-list", ListView).highlighted_child
self.run_action_worker("reprint", name=selected.name if selected else None)
elif button_id == "do-status":
self.run_action_worker("status")
elif button_id == "do-list":
self.run_action_worker("list")
elif button_id == "do-clean":
self.run_action_worker("clean")
def set_buttons_disabled(self, disabled: bool) -> None:
for button in self.query(Button):
button.disabled = disabled
@work(thread=True, exclusive=True)
def run_action_worker(self, command: str, **params) -> None:
self.call_from_thread(self.set_buttons_disabled, True)
self.call_from_thread(self.log_panel.write, f"[bold]$ {command}[/bold]")
try:
rc, output = run_action(command, self.base_args, **params)
finally:
self.call_from_thread(self.set_buttons_disabled, False)
self.call_from_thread(self.report, command, rc, output)
def report(self, command: str, rc: int, output: str) -> None:
if output:
self.log_panel.write(output)
if rc == 0:
self.log_panel.write("[green]done[/green]")
else:
self.log_panel.write(f"[red]failed (exit {rc})[/red]")
if command in ("image", "clean"):
self.refresh_cache_list()
def run_tui(args: argparse.Namespace) -> int:
ReceiptApp(args).run()
return 0
+249
View File
@@ -0,0 +1,249 @@
import argparse
import pytest
from PIL import Image
import receipt
class FakeResponse:
def __init__(self, json_data=None, content=b""):
self._json = json_data
self.content = content
def raise_for_status(self):
pass
def json(self):
return self._json
class FakePrinter:
"""Records escpos calls instead of talking to hardware."""
def __init__(self):
self.calls = []
def textln(self, text=""):
self.calls.append(("textln", text))
def image(self, img, **kwargs):
self.calls.append(("image", img))
def qr(self, content, **kwargs):
self.calls.append(("qr", content))
def cut(self):
self.calls.append(("cut", None))
def make_catalog(threads):
return [{"threads": threads}]
def make_args(**overrides):
defaults = {
"usb": True, # avoids the network setup script in tests
"ip": receipt.DEFAULT_PRINTER_IP,
"port": receipt.DEFAULT_PRINTER_PORT,
"timestamp": False,
"message": None,
"name": None,
}
defaults.update(overrides)
return argparse.Namespace(**defaults)
def test_prepare_for_print_resizes_and_dithers(tmp_path):
src = tmp_path / "wide.png"
Image.new("RGB", (200, 100), "gray").save(src)
prepared = receipt.prepare_for_print(src)
assert prepared.size == (receipt.PRINT_WIDTH_PX, receipt.PRINT_WIDTH_PX // 2)
assert prepared.mode == "1"
def test_prepare_for_print_composites_transparency_onto_white(tmp_path):
src = tmp_path / "transparent.png"
Image.new("RGBA", (100, 100), (0, 0, 0, 0)).save(src)
prepared = receipt.prepare_for_print(src)
# Fully transparent input must come out white (255), not black
assert prepared.getpixel((288, 288)) == 255
def test_wrap_text_wraps_long_lines_and_keeps_blank_lines():
long_line = "word " * 20
wrapped = receipt.wrap_text(f"{long_line}\n\nshort")
lines = wrapped.split("\n")
assert all(len(line) <= receipt.TEXT_COLUMNS for line in lines)
assert "" in lines # blank line preserved
assert lines[-1] == "short"
def test_positive_int_rejects_zero_and_negatives():
with pytest.raises(argparse.ArgumentTypeError):
receipt.positive_int("0")
with pytest.raises(argparse.ArgumentTypeError):
receipt.positive_int("-3")
assert receipt.positive_int("2") == 2
def test_download_saves_image(tmp_path, monkeypatch):
monkeypatch.setattr(receipt, "IMG_DIR", tmp_path / "img")
catalog = make_catalog([{"tim": 12345, "ext": ".jpg"}])
calls = []
def fake_get(url, timeout):
calls.append(url)
if url == receipt.BANT_CATALOG_URL:
return FakeResponse(json_data=catalog)
return FakeResponse(content=b"jpegbytes")
monkeypatch.setattr(receipt.requests, "get", fake_get)
dest = receipt.download_random_bant_image()
assert dest.name == "12345.jpg"
assert dest.read_bytes() == b"jpegbytes"
assert calls == [receipt.BANT_CATALOG_URL, "https://i.4cdn.org/bant/12345.jpg"]
def test_download_reuses_cached_image(tmp_path, monkeypatch):
img_dir = tmp_path / "img"
img_dir.mkdir()
(img_dir / "12345.jpg").write_bytes(b"cached")
monkeypatch.setattr(receipt, "IMG_DIR", img_dir)
catalog = make_catalog([{"tim": 12345, "ext": ".jpg"}])
calls = []
def fake_get(url, timeout):
calls.append(url)
return FakeResponse(json_data=catalog)
monkeypatch.setattr(receipt.requests, "get", fake_get)
dest = receipt.download_random_bant_image()
assert dest.read_bytes() == b"cached"
assert calls == [receipt.BANT_CATALOG_URL] # image itself not re-fetched
def test_download_skips_unprintable_formats(tmp_path, monkeypatch):
monkeypatch.setattr(receipt, "IMG_DIR", tmp_path / "img")
catalog = make_catalog(
[{"tim": 1, "ext": ".gif"}, {"tim": 2, "ext": ".webm"}, {"no_image": True}]
)
monkeypatch.setattr(
receipt.requests, "get", lambda url, timeout: FakeResponse(json_data=catalog)
)
assert receipt.download_random_bant_image() is None
def test_cmd_note_wraps_and_cuts():
p = FakePrinter()
rc = receipt.cmd_note(p, make_args(text="hello " * 20))
assert rc == 0
assert p.calls[0][0] == "textln"
assert all(len(line) <= receipt.TEXT_COLUMNS for line in p.calls[0][1].split("\n"))
assert p.calls[-1] == ("cut", None)
def test_cmd_note_timestamp_header():
p = FakePrinter()
rc = receipt.cmd_note(p, make_args(text="hi", timestamp=True))
assert rc == 0
kinds = [c[0] for c in p.calls]
assert kinds == ["textln", "textln", "textln", "cut"] # date, rule, note, cut
def test_cmd_note_rejects_empty():
p = FakePrinter()
rc = receipt.cmd_note(p, make_args(text=""))
assert rc == 1
assert p.calls == []
def test_cmd_qr_prints_content_and_caption():
p = FakePrinter()
rc = receipt.cmd_qr(p, make_args(content="https://example.com", message="scan me"))
assert rc == 0
assert ("qr", "https://example.com") in p.calls
assert ("textln", "scan me") in p.calls
def test_cmd_reprint_picks_most_recent(tmp_path, monkeypatch):
img_dir = tmp_path / "img"
img_dir.mkdir()
older = img_dir / "old.png"
newer = img_dir / "new.png"
Image.new("RGB", (10, 10)).save(older)
Image.new("RGB", (10, 10)).save(newer)
import os
os.utime(older, (1000, 1000))
os.utime(newer, (2000, 2000))
monkeypatch.setattr(receipt, "IMG_DIR", img_dir)
p = FakePrinter()
rc = receipt.cmd_reprint(p, make_args())
assert rc == 0
assert ("textln", "new") in p.calls
def test_cmd_reprint_by_stem(tmp_path, monkeypatch):
img_dir = tmp_path / "img"
img_dir.mkdir()
Image.new("RGB", (10, 10)).save(img_dir / "12345.png")
monkeypatch.setattr(receipt, "IMG_DIR", img_dir)
p = FakePrinter()
rc = receipt.cmd_reprint(p, make_args(name="12345"))
assert rc == 0
assert ("textln", "12345") in p.calls
def test_cmd_reprint_unknown_name(tmp_path, monkeypatch):
img_dir = tmp_path / "img"
img_dir.mkdir()
Image.new("RGB", (10, 10)).save(img_dir / "12345.png")
monkeypatch.setattr(receipt, "IMG_DIR", img_dir)
p = FakePrinter()
assert receipt.cmd_reprint(p, make_args(name="nope")) == 1
assert p.calls == []
def test_parser_handles_all_subcommands():
parser = receipt.build_parser()
args = parser.parse_args(["image", "3"])
assert args.command == "image" and args.count == 3
args = parser.parse_args(["--usb", "note", "hello", "-t"])
assert args.usb and args.text == "hello" and args.timestamp
args = parser.parse_args(["note"])
assert args.text is None # stdin mode
args = parser.parse_args(["--ip", "10.0.0.5", "--port", "9101", "status"])
assert args.ip == "10.0.0.5" and args.port == 9101
args = parser.parse_args(["qr", "https://example.com", "scan me"])
assert args.content == "https://example.com" and args.message == "scan me"
args = parser.parse_args(["reprint", "12345"])
assert args.name == "12345"
for cmd in ("status", "list", "clean", "reprint"):
assert parser.parse_args([cmd]).command == cmd
+104
View File
@@ -0,0 +1,104 @@
import argparse
import pytest
from PIL import Image
import receipt
receipt_tui = pytest.importorskip("receipt_tui")
class FakePrinter:
def __init__(self):
self.calls = []
def textln(self, text=""):
self.calls.append(("textln", text))
def image(self, img, **kwargs):
self.calls.append(("image", img))
def qr(self, content, **kwargs):
self.calls.append(("qr", content))
def cut(self):
self.calls.append(("cut", None))
def make_base_args(**overrides):
defaults = {
"usb": True, # avoids the network setup script in tests
"ip": receipt.DEFAULT_PRINTER_IP,
"port": receipt.DEFAULT_PRINTER_PORT,
"command": "tui",
}
defaults.update(overrides)
return argparse.Namespace(**defaults)
@pytest.fixture
def fake_printer(monkeypatch):
p = FakePrinter()
monkeypatch.setattr(receipt, "get_printer", lambda args: p)
return p
def test_run_action_note(fake_printer):
rc, output = receipt_tui.run_action(
"note", make_base_args(), text="hello", timestamp=False
)
assert rc == 0
assert ("textln", "hello") in fake_printer.calls
assert fake_printer.calls[-1] == ("cut", None)
def test_run_action_qr(fake_printer):
rc, _ = receipt_tui.run_action(
"qr", make_base_args(), content="https://example.com", message=None
)
assert rc == 0
assert ("qr", "https://example.com") in fake_printer.calls
def test_run_action_reprint_uses_cache(fake_printer, tmp_path, monkeypatch):
img_dir = tmp_path / "img"
img_dir.mkdir()
Image.new("RGB", (10, 10)).save(img_dir / "12345.png")
monkeypatch.setattr(receipt, "IMG_DIR", img_dir)
rc, _ = receipt_tui.run_action("reprint", make_base_args(), name="12345")
assert rc == 0
assert ("textln", "12345") in fake_printer.calls
def test_run_action_captures_output_and_errors(monkeypatch):
def boom(args):
raise OSError("no printer")
monkeypatch.setattr(receipt, "get_printer", boom)
rc, output = receipt_tui.run_action(
"note", make_base_args(), text="hi", timestamp=False
)
assert rc == 1
assert "no printer" in output
def test_run_action_list_needs_no_printer(monkeypatch, tmp_path):
monkeypatch.setattr(receipt, "IMG_DIR", tmp_path / "img")
monkeypatch.setattr(
receipt, "get_printer", lambda args: pytest.fail("should not connect")
)
rc, output = receipt_tui.run_action("list", make_base_args())
assert rc == 0
assert "empty" in output
def test_parser_accepts_tui():
assert receipt.build_parser().parse_args(["tui"]).command == "tui"