Prompt next sample code after each i1Pro reading
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -20,9 +20,10 @@ average repeated scans, and relate results to ink mix formulas.
|
||||
3. **Scans the samples** — lists the sample names from `samples.txt` in
|
||||
measurement order, then starts `spotread`. You first calibrate on the
|
||||
white tile, then take one reading per sample with the instrument
|
||||
button, and press **Q** when all readings are done. If the number of
|
||||
readings doesn't match `samples.txt`, the scan can be discarded to
|
||||
`archive/` and repeated.
|
||||
button. After each reading the terminal prints the **next sample
|
||||
code** so you know which one to scan next; press **Q** when all
|
||||
readings are done. If the number of readings doesn't match
|
||||
`samples.txt`, the scan can be discarded to `archive/` and repeated.
|
||||
4. **Saves a labelled CSV** — converts the spotread TSV log to
|
||||
`scan_<mode>_<timestamp>.csv` with a `sample_id` column taken from
|
||||
`samples.txt`.
|
||||
@@ -120,6 +121,7 @@ These are used by `auto-scan.sh` but can also be run on their own:
|
||||
|--------|---------|
|
||||
| `measure.sh [mode]` | Just the spotread measurement session (TSV output) |
|
||||
| `run-measurement.sh [mode]` | Measurement session + CSV conversion |
|
||||
| `prompt-next-sample.py -s samples.txt -- spotread …` | Wrap spotread and print the next sample code after each reading |
|
||||
| `tsv-to-csv.py <tsv> [-s samples.txt]` | Convert a spotread TSV to labelled CSV |
|
||||
| `average-results.py <csv...> -o out.csv` | Average Lab across scan CSVs (writes CSV + HTML) |
|
||||
| `build-formula-table.py` | Rebuild `formula.csv` from the averaged CSV |
|
||||
|
||||
@@ -99,7 +99,7 @@ check_dependencies() {
|
||||
fi
|
||||
echo " spotread: $(command -v spotread)"
|
||||
|
||||
for helper in tsv-to-csv.py average-results.py; do
|
||||
for helper in tsv-to-csv.py average-results.py prompt-next-sample.py; do
|
||||
[[ -f "$helper" ]] || fail "Missing helper script: $helper"
|
||||
done
|
||||
|
||||
@@ -149,6 +149,7 @@ scan_samples() {
|
||||
echo " spotread will start now:"
|
||||
echo " - First calibrate: place the i1Pro 2 on its white tile and follow the prompt"
|
||||
echo " - Then take one reading per sample (press the instrument button)"
|
||||
echo " - The next sample code is printed in the terminal after each reading"
|
||||
echo " - After all $count readings, press Q to finish"
|
||||
echo ""
|
||||
read -r -p " Press Enter to start... "
|
||||
@@ -163,7 +164,7 @@ scan_samples() {
|
||||
spotread_args=(-I "$MODE" "${spotread_args[@]}")
|
||||
fi
|
||||
|
||||
spotread "${spotread_args[@]}"
|
||||
python3 prompt-next-sample.py -s "$SAMPLES_FILE" -- spotread "${spotread_args[@]}"
|
||||
|
||||
[[ -f "$TSV" ]] || fail "No readings were saved ($TSV missing)"
|
||||
|
||||
|
||||
@@ -60,7 +60,8 @@ echo " 1. Calibrate on the white tile when prompted"
|
||||
echo " 2. Place i1Pro on each sample and press the button"
|
||||
if [[ "$SAMPLE_COUNT" -gt 0 ]]; then
|
||||
echo " 3. Take exactly $SAMPLE_COUNT readings, in samples.txt order"
|
||||
echo " 4. Press Q to quit when all readings are done"
|
||||
echo " 4. The next sample code is printed in the terminal after each reading"
|
||||
echo " 5. Press Q to quit when all readings are done"
|
||||
else
|
||||
echo " 3. Press Q to quit when done"
|
||||
fi
|
||||
@@ -68,7 +69,11 @@ echo ""
|
||||
echo "Starting spotread..."
|
||||
echo ""
|
||||
|
||||
spotread "${SPOTREAD_ARGS[@]}"
|
||||
if [[ "$SAMPLE_COUNT" -gt 0 && -f prompt-next-sample.py ]]; then
|
||||
python3 prompt-next-sample.py -s samples.txt -- spotread "${SPOTREAD_ARGS[@]}"
|
||||
else
|
||||
spotread "${SPOTREAD_ARGS[@]}"
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo "Done. Convert to CSV with:"
|
||||
|
||||
196
prompt-next-sample.py
Executable file
196
prompt-next-sample.py
Executable file
@@ -0,0 +1,196 @@
|
||||
#!/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())
|
||||
Reference in New Issue
Block a user