- 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:
+302
-106
@@ -1,162 +1,358 @@
|
||||
#!/usr/bin/env python3
|
||||
"""CLI for printing images and text notes to an Epson TM-T20II receipt printer."""
|
||||
|
||||
from escpos import printer
|
||||
from PIL import Image
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import subprocess
|
||||
import random
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import textwrap
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
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 get_T20II_usb():
|
||||
p = printer.Usb(0x04B8, 0x0202) # , profile="TM-T20II")
|
||||
# p.set_with_default(align='center', font='a', bold=False, width=2, height=2, custom_size=True, smooth=True)
|
||||
return p
|
||||
def setup_network() -> None:
|
||||
"""Bring up the printer's network interface via the connect script."""
|
||||
subprocess.run(["bash", str(CONNECT_SCRIPT)], check=True)
|
||||
|
||||
|
||||
def get_T20II_ethernet():
|
||||
p = printer.Network("192.168.192.168", port=9100) # , profile="TM-T20II")
|
||||
# p.set_with_default(align='center', font='a', bold=False, width=2, height=2, custom_size=True, smooth=True)
|
||||
return p
|
||||
def get_printer(args: argparse.Namespace) -> printer.Escpos:
|
||||
if args.usb:
|
||||
return printer.Usb(USB_VENDOR_ID, USB_PRODUCT_ID)
|
||||
return printer.Network(args.ip, port=args.port)
|
||||
|
||||
|
||||
def resize_image_to_fullwidth(img_src_name, target_width=576):
|
||||
# Make fullwidth dir
|
||||
os.makedirs("img_fullwidth", exist_ok=True)
|
||||
def prepare_for_print(img_path: Path) -> Image.Image:
|
||||
"""Load an image resized to full printer width and dithered for thermal output.
|
||||
|
||||
# Open the image
|
||||
img = Image.open(img_src_name)
|
||||
|
||||
# Get original dimensions
|
||||
width, height = img.size
|
||||
|
||||
# Calculate new height to maintain aspect ratio
|
||||
aspect_ratio = height / width
|
||||
new_height = int(target_width * aspect_ratio)
|
||||
|
||||
# Resize the image
|
||||
resized_img = img.resize((target_width, new_height), Image.LANCZOS)
|
||||
|
||||
# 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
|
||||
Transparency is composited onto white (thermal paper), then the image is
|
||||
autocontrast-stretched and Floyd-Steinberg dithered to 1-bit.
|
||||
"""
|
||||
with Image.open(img_path) as img:
|
||||
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_height = round(PRINT_WIDTH_PX * height / width)
|
||||
resized = img.resize((PRINT_WIDTH_PX, new_height), Image.LANCZOS)
|
||||
return ImageOps.autocontrast(resized.convert("L")).convert("1")
|
||||
|
||||
|
||||
def get_random_bant_image():
|
||||
# Create img directory if it doesn't exist
|
||||
os.makedirs("img", exist_ok=True)
|
||||
def wrap_text(text: str) -> str:
|
||||
"""Word-wrap text to the printer's column width, preserving blank lines."""
|
||||
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"
|
||||
response = requests.get(url)
|
||||
|
||||
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()
|
||||
|
||||
# Flatten the list of threads from all pages
|
||||
threads = [thread for page in catalog for thread in page["threads"]]
|
||||
|
||||
# Filter threads that have images (tim and ext fields)
|
||||
image_threads = [
|
||||
thread
|
||||
for thread in threads
|
||||
if "tim" in thread
|
||||
and "ext" in thread
|
||||
and thread["ext"].lower() not in [".gif", ".mp4", ".webm"]
|
||||
t
|
||||
for t in threads
|
||||
if "tim" in t and "ext" in t and t["ext"].lower() not in UNPRINTABLE_EXTENSIONS
|
||||
]
|
||||
|
||||
if not image_threads:
|
||||
return None # No images found
|
||||
return None
|
||||
|
||||
# Choose a random thread with an image
|
||||
thread = random.choice(image_threads)
|
||||
dest = IMG_DIR / f"{thread['tim']}{thread['ext']}"
|
||||
if dest.is_file():
|
||||
return dest
|
||||
|
||||
# Construct image URL
|
||||
image_url = f"https://i.4cdn.org/bant/{thread['tim']}{thread['ext']}"
|
||||
filename = f"img/{thread['tim']}{thread['ext']}"
|
||||
|
||||
# Download and save image
|
||||
img_response = requests.get(image_url)
|
||||
image_url = BANT_IMAGE_URL.format(tim=thread["tim"], ext=thread["ext"])
|
||||
img_response = requests.get(image_url, timeout=HTTP_TIMEOUT)
|
||||
img_response.raise_for_status()
|
||||
dest.write_bytes(img_response.content)
|
||||
|
||||
with open(filename, "wb") as f:
|
||||
f.write(img_response.content)
|
||||
|
||||
return filename
|
||||
return dest
|
||||
|
||||
|
||||
def print_random_bant_image(p, sh_file):
|
||||
img = get_random_bant_image()
|
||||
if img is None:
|
||||
print("No images found on /bant/.")
|
||||
return
|
||||
filename_no_ext = os.path.splitext(os.path.basename(img))[0]
|
||||
p.textln(filename_no_ext)
|
||||
fimg = resize_image_to_fullwidth(img)
|
||||
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 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:
|
||||
p.image(fimg, impl="bitImageColumn")
|
||||
p.image(prepared, impl="bitImageColumn")
|
||||
except Exception as e:
|
||||
print(f"Print failed, reconnecting: {e}")
|
||||
subprocess.run(["bash", sh_file], check=True)
|
||||
p = get_T20II_ethernet()
|
||||
print(f"Print failed ({e}); reconnecting...", file=sys.stderr)
|
||||
if not args.usb:
|
||||
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()
|
||||
return 0
|
||||
|
||||
|
||||
def print_note(p, text):
|
||||
p.textln(text)
|
||||
def cmd_print(p: printer.Escpos, args: argparse.Namespace) -> int:
|
||||
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()
|
||||
return 0
|
||||
|
||||
|
||||
def print_local_image(p, sh_file, img_path, message=None):
|
||||
if not os.path.isfile(img_path):
|
||||
print(f"File not found: {img_path}")
|
||||
return
|
||||
if message:
|
||||
p.textln(message)
|
||||
fimg = resize_image_to_fullwidth(img_path)
|
||||
def cmd_qr(p: printer.Escpos, args: argparse.Namespace) -> int:
|
||||
if args.message:
|
||||
p.textln(wrap_text(args.message))
|
||||
p.qr(args.content, size=8, center=True)
|
||||
p.cut()
|
||||
return 0
|
||||
|
||||
|
||||
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:
|
||||
p.image(fimg, impl="bitImageColumn")
|
||||
if not args.usb:
|
||||
setup_network()
|
||||
p = get_printer(args)
|
||||
p.close()
|
||||
except Exception as e:
|
||||
print(f"Print failed, reconnecting: {e}")
|
||||
subprocess.run(["bash", sh_file], check=True)
|
||||
p = get_T20II_ethernet()
|
||||
p.cut()
|
||||
print(f"Printer unreachable: {e}", file=sys.stderr)
|
||||
return 1
|
||||
target = "USB" if args.usb else f"{args.ip}:{args.port}"
|
||||
print(f"Printer reachable ({target}).")
|
||||
return 0
|
||||
|
||||
|
||||
def main():
|
||||
import argparse
|
||||
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() -> 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.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.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.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.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")
|
||||
|
||||
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__))
|
||||
sh_file = os.path.join(script_dir, "connect_recipt.sh")
|
||||
subprocess.run(["bash", sh_file], check=True)
|
||||
p = get_T20II_ethernet()
|
||||
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)",
|
||||
)
|
||||
|
||||
if args.command == "image":
|
||||
print_random_bant_image(p, sh_file)
|
||||
elif args.command == "note":
|
||||
print_note(p, args.text)
|
||||
elif args.command == "print":
|
||||
print_local_image(p, sh_file, args.path, args.message)
|
||||
subparsers.add_parser("status", help="Check whether the printer is reachable")
|
||||
subparsers.add_parser("list", help="List the downloaded image cache")
|
||||
subparsers.add_parser("clean", help="Delete the downloaded image cache")
|
||||
subparsers.add_parser("tui", help="Open the interactive terminal UI")
|
||||
|
||||
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__":
|
||||
main()
|
||||
sys.exit(main())
|
||||
|
||||
Reference in New Issue
Block a user