Files
scan-color-samples/prompt-next-sample.py
2026-08-25 18:21:36 +03:30

197 lines
5.5 KiB
Python
Executable File

#!/usr/bin/env python3
"""Wrap spotread and print the next samples.txt code after each reading."""
from __future__ import annotations
import argparse
import os
import sys
from pathlib import Path
TAKE_READING = b"take a reading:"
RESULT_XYZ = b"Result is XYZ"
TAIL = 64
YELLOW = "\033[1;33m"
RESET = "\033[0m"
def load_sample_names(path: Path) -> list[str]:
# A leading "*" marks the Delta-E reference sample; strip it to get the name.
names = []
for line in path.read_text(encoding="utf-8").splitlines():
line = line.strip()
if line and not line.startswith("#"):
if line.startswith("*"):
line = line[1:].strip()
names.append(line)
return names
def _tty_write(text: str) -> None:
try:
with open("/dev/tty", "w", encoding="utf-8") as tty:
tty.write(text)
tty.flush()
return
except OSError:
pass
sys.stderr.write(text)
sys.stderr.flush()
def write_banner(message: str) -> None:
bar = "=" * 40
_tty_write(f"\n{YELLOW}{bar}\n {message}\n{bar}{RESET}\n")
def set_title(title: str) -> None:
_tty_write(f"\033]0;{title}\007")
def waitstatus_to_exitcode(status: int) -> int:
if hasattr(os, "waitstatus_to_exitcode"):
return os.waitstatus_to_exitcode(status)
if os.WIFEXITED(status):
return os.WEXITSTATUS(status)
if os.WIFSIGNALED(status):
return 128 + os.WTERMSIG(status)
return 1
class Watcher:
"""Scan spotread output and announce the next sample at each prompt."""
def __init__(self, samples: list[str]) -> None:
self.samples = samples
self.n = len(samples)
self.next_idx = 0
self.buf = bytearray()
self.announced_idx = -1
self.done_announced = False
def feed(self, data: bytes) -> None:
if not data:
return
self.buf.extend(data)
while True:
take = self.buf.find(TAKE_READING)
result = self.buf.find(RESULT_XYZ)
if take < 0 and result < 0:
if len(self.buf) > TAIL:
del self.buf[:-TAIL]
return
if result >= 0 and (take < 0 or result < take):
self._on_result()
del self.buf[: result + len(RESULT_XYZ)]
else:
self._on_take_reading()
del self.buf[: take + len(TAKE_READING)]
def _on_result(self) -> None:
self.next_idx += 1
self.done_announced = False
def _on_take_reading(self) -> None:
if self.next_idx < self.n:
if self.announced_idx != self.next_idx:
name = self.samples[self.next_idx]
write_banner(f"NEXT ({self.next_idx + 1}/{self.n}): {name}")
set_title(f"NEXT: {name} ({self.next_idx + 1}/{self.n})")
self.announced_idx = self.next_idx
return
if self.next_idx == self.n:
if not self.done_announced:
write_banner(f"All {self.n} samples scanned. Press Q to finish.")
set_title(f"All {self.n} scanned — press Q")
self.done_announced = True
return
write_banner(
f"EXTRA reading ({self.next_idx} taken, expected {self.n}). "
"Press Q to finish."
)
set_title(f"EXTRA {self.next_idx}/{self.n} — press Q")
def warn_fallback(reason: str) -> None:
print(
f"WARNING: next-sample prompts unavailable ({reason}); "
"running spotread without them",
file=sys.stderr,
)
def run(argv: list[str], samples: list[str]) -> int:
if not argv:
print("Error: no command to run", file=sys.stderr)
return 2
if not samples:
os.execvp(argv[0], argv)
try:
import pty
except ImportError as exc:
warn_fallback(str(exc))
os.execvp(argv[0], argv)
watcher = Watcher(samples)
def master_read(fd: int) -> bytes:
data = os.read(fd, 4096)
try:
watcher.feed(data)
except OSError:
pass
return data
try:
status = pty.spawn(argv, master_read)
except OSError as exc:
warn_fallback(str(exc))
os.execvp(argv[0], argv)
return waitstatus_to_exitcode(status)
def main() -> int:
parser = argparse.ArgumentParser(
description=(
"Run a spotread session and print the next sample code from "
"samples.txt after each reading."
)
)
parser.add_argument(
"-s",
"--samples",
type=Path,
required=True,
help="Text file with one sample name per line (measurement order)",
)
parser.add_argument(
"argv",
nargs=argparse.REMAINDER,
metavar="COMMAND",
help="Command to run (e.g. -- spotread -i D50 -s scan.tsv)",
)
args = parser.parse_args()
if not args.samples.exists():
print(f"Error: {args.samples} not found", file=sys.stderr)
return 1
argv = list(args.argv)
if argv and argv[0] == "--":
argv = argv[1:]
try:
samples = load_sample_names(args.samples)
except OSError as exc:
print(f"Error: cannot read {args.samples}: {exc}", file=sys.stderr)
return 1
return run(argv, samples)
if __name__ == "__main__":
raise SystemExit(main())