8000 Full-screen flahax mix in the terminal (standard library only) by rafatahmed · Pull Request #124 · rafatahmed/Flahax · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

## Unreleased

- `flahax mix` opens full screen in a terminal (owner design 2026-10-23), with Python's standard library only: arrow keys and Enter choose, typing filters long lists, Space ticks the fertilizers available, Esc asks before quitting. The five steps go forward only; at 100 columns or more the answers so far stay in a left pane. The result opens on Tanks (tank A, tank B, the acid container), with Nutrients and Notes on Tab; a blocked batch opens on Notes. Every value comes from the same summary and rounding as the batch sheet, and the sheets are written exactly as before. The line-by-line questions stay for `flahax mix --plain`, scripts, pipes and editor panels, with byte-identical output (`tests/fixtures/mix/owner-session-plain.txt`). New modules: `flahax.terminal` (Windows `msvcrt`/`ctypes`, POSIX `termios`/`tty`/`select`; the console is always restored), `flahax.mix_tui` and `flahax.mix_results`.
- Security policy (`SECURITY.md`): supported versions, private reporting through GitHub or info@flaha.org, and what counts as a security problem. Coverage: the Python 3.13 CI job runs the tests under `coverage` (a CI tool only, pinned 7.17.0) and uploads the report to Codecov with the pinned `codecov/codecov-action` v7.1.1; `codecov.yml` makes the Codecov checks informational. The README gains Tests, Documentation (Read the Docs) and Codecov badges.
- Code of conduct: the Contributor Covenant 2.1, unchanged apart from the reporting contact (Flaha Agri Tech, info@flaha.org), linked from CONTRIBUTING.
- PEP 8 style and file headers (hardening 3a/4; owner decisions 2026-10-23: line length 99, header template). All Python code is formatted with `ruff format` (PEP 8, 99 columns; quote style kept), which leaves the code's meaning unchanged; one statement per line, PEP 8 spacing and blank lines throughout. Every Python file (161) starts with the header in PEP 8 order: a shebang only on runnable tools and examples, the SPDX copyright and license lines and the disclaimer, then the module docstring (36 test files gained one). `flahax/__init__.py` now lists `__all__` (135 names, unchanged) and `__version__` before its imports, instead of 13 `__all__ +=` lines between them. Unused imports and variables are removed (including an unused H3PO4 term in the phosphate loop; H3PO4 is still in the mass balance), two lambdas assigned to names became functions, and the ambiguous name `l` became `line`. Style settings live in `pyproject.toml` (ruff is a development tool, not a runtime dependency); a new CI `style` job runs `ruff check` and `ruff format --check`, and `tests/test_file_headers.py` checks the header order. Line length is enforced after the remaining long strings and comments are rewrapped (3b). CONTRIBUTING.md documents the conventions.
Expand Down
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,11 @@ flahax mix # first time: answer the five steps
flahax mix sessions/my-tomato # next time: no questions
```

In a terminal it opens full screen: arrow keys and Enter choose, typing filters a
long list, Space ticks your fertilizers, and the result has three views (Tanks,
Nutrients, Notes) switched with Tab. `flahax mix --plain` asks line by line
instead, and scripts and pipes get the line-by-line mode automatically.

`flahax mix` is on `main` and ships in the next release. Until then:
`python -m pip install --upgrade "git+https://github.com/rafatahmed/Flahax.git@main"`.
See [For growers and agronomists](https://flahax.readthedocs.io/en/latest/growers.html).
Expand Down
13 changes: 13 additions & 0 deletions docs/site/growers.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,19 @@ flahax mix # first time: answers the five steps
flahax mix sessions/tomato-ro # next time: no questions
```

In a terminal window (Windows Terminal, the Windows console, or a Linux or macOS
terminal of at least 80 x 24) `flahax mix` opens full screen. The arrow keys
move, Enter chooses, typing narrows a long list such as the crop formulas, Space
ticks the fertilizers you have, and Esc asks before quitting. The steps go
forward only. In a wide window your answers so far stay on the left. When the
batch is calculated the result opens on **Tanks** (tank A, tank B and the acid
container with what to weigh); Tab shows **Nutrients** (the agronomist table and
the pH path) and **Notes** (every review note once). A blocked batch opens on
Notes with the reason. The sheets are written before the result appears, the
same as in the line-by-line mode. `flahax mix --plain` keeps the line-by-line
questions, which are also used automatically when the output is not a terminal
(a script, a pipe or an editor's output panel).

At the end choose who the result is for. **Grower**: the batch sheet with tank
A and tank B (prepared litres and grams to weigh, with tick boxes), the acid
container and the checks after mixing. **Agronomist**: the same, plus the
Expand Down
194 changes: 137 additions & 57 deletions src/flahax/mix_cli.py
8
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

flahax mix ask the five steps, save the answers, write the sheets
flahax mix sessions/NAME run a saved session again without questions
flahax mix --plain ask line by line instead of the full-screen wizard

Steps: 1/5 specification (tanks, injection ratio, temperature, how stock is
prepared), 2/5 water analysis, 3/5 crop formula, 4/5 fertilizers and acids, 5/5
Expand All @@ -19,6 +20,7 @@
from datetime import date
import math
from pathlib import Path
import sys

from . import __version__
from .batch_cli import ACID_FORMULAS, BatchOptions, limit_entry, read_json, render, run_batch
Expand All @@ -39,6 +41,7 @@
from .mix_store import Store, slug
from .mix_water import MICROS, WATER_IONS, ask_analysis, to_elements # noqa: F401 (re-exported)
from .stock_volumes import prepare_stocks
from .terminal import supported

FORMULA_KEYS = ('N_NO3', 'N_NH4', 'P', 'K', 'Ca', 'Mg', 'S', 'Fe', 'Mn', 'Zn', 'Cu', 'B', 'Mo')
COMPOUND_KEYS = (
Expand All @@ -58,6 +61,31 @@
CHELATES = ('EDTA', 'DTPA', 'o,o-EDDHA', None)


def number_answer(answer, default, *, blank=False, low=0.0, high=None, positive=False):
"""(value, None) for an acceptable typed number, else (None, the message to show).

Enter gives the default, or None when ``blank`` allows it.
"""
answer = answer.strip()
if not answer and (default is not None or blank):
return default, None
try:
value = float(answer)
except ValueError:
return None, f' {answer!r} is not a number.'
if (
not math.isfinite(value)
or value < low
or (positive and value <= low)
or (high is not None and value > high)
):
return None, (
f' Enter a number {"above" if positive else "from"} {low:g}'
+ (f' up to {high:g}.' if high is not None else '.')
)
return value, None


class Prompts:
"""The questions of ``flahax mix``; ``ask`` reads an answer and ``say`` prints."""

Expand All @@ -83,26 +111,17 @@ def number(self, prompt, default=None, *, blank=False, low=0.0, high=None, posit
shown = (
f' [{default:g}]' if default is not None else ' (Enter if blank)' if blank else ''
)
answer = self.ask(f'{prompt}{shown}: ').strip()
if not answer and (default is not None or blank):
return default
try:
value = float(answer)
except ValueError:
self.say(f' {answer!r} is not a number.')
continue
if (
not math.isfinite(value)
or value < low
or (positive and value <= low)
or (high is not None and value > high)
):
self.say(
f' Enter a number {"above" if positive else "from"} {low:g}'
+ (f' up to {high:g}.' if high is not None else '.')
)
continue
return value
value, error = number_answer(
self.ask(f'{prompt}{shown}: '),
default,
blank=blank,
low=low,
high=high,
positive=positive,
)
if error is None:
return value
self.say(error)

def choose(self, prompt, options, default=1):
"""0-based index of the chosen option; with ``default=None`` Enter asks again."""
Expand Down Expand Up @@ -134,6 +153,28 @@ def search(self, prompt, names):
return matches[self.choose(f'{len(matches)} match:', matches)]
self.say(f' Nothing matches {query!r}; press Enter to see the whole list.')

def pick_many(self, prompt, names):
"""0-based indices of the names chosen, in the order typed and without repeats."""
for i, name in enumerate(names, 1):
self.say(f' {i:2} {name}')
while True:
picked = (
self.text('Numbers of the products you have, separated by spaces')
.replace(',', ' ')
.split()
)
if all(n.isdigit() and 1 <= int(n) <= len(names) for n in picked):
return [int(n) - 1 for n in dict.fromkeys(picked)]
self.say(f' Use numbers 1 to {len(names)}.')

def step(self, index, heading=None):
"""Step ``index`` of five begins; the line mode shows ``heading`` when there is one."""
if heading:
self.say(heading)

def answered(self, label, value):
"""A finished step's short answer; the line mode shows nothing."""

def new_name(self, store, kind, prompt, default=None):
"""A name for a new saved item; an existing name is used only when the user chooses to
replace it.
Expand Down Expand Up @@ -171,7 +212,7 @@ def ask_spec(p):
"""Step 1: tank and acid container sizes, injection ratio, stock temperature and how the stock
is prepared, as ``prepare_stocks`` options.
"""
p.say('1/5 Specification')
p.step(1, '1/5 Specification')
a = p.number('Tank A capacity, L', 1000, positive=True)
b = p.number('Tank B capacity, L', 1000, positive=True)
tanks = {
Expand Down Expand Up @@ -223,7 +264,7 @@ def ask_water(p, store, pending):
"""Step 2: the water (RO, saved or new), its share and the concentration limits; returns
(reference, share, limits).
"""
p.say('2/5 Water analysis')
p.step(2, '2/5 Water analysis')
saved = store.list('waters')
pick = p.choose('Water', ['RO water (no ions)'] + saved + ['A new analysis'])
ref, share = 'ro', 100.0
Expand All @@ -249,7 +290,7 @@ def ask_formula(p, store, pending, library):
"""Step 3: the crop formula (packaged, changed, saved or typed); returns (reference, targets,
title).
"""
p.say('3/5 Crop formula: the nutrient targets in mg/L (your fertilizers come in step 4)')
p.step(3, '3/5 Crop formula: the nutrient targets in mg/L (your fertilizers come in step 4)')
saved = store.list('formulas')
packaged = {f['name']: f['targets'] for f in library['formulas']}
pick = p.choose(
Expand Down Expand Up @@ -406,7 +447,7 @@ def add_compound(p):

def ask_products(p, store, pending, library):
"""Step 4: the fertilizers available; returns (reference, products)."""
p.say('4/5 Fertilizers available')
p.step(4, '4/5 Fertilizers available')
catalogue, saved = library['salts'], store.list('stores')
pick = p.choose('Fertilizers', ['The whole catalogue'] + saved + ['Tick what I have'])
if pick == 0:
Expand All @@ -416,18 +457,8 @@ def ask_products(p, store, pending, library):
products = store.load('stores', ref)
else:
ref = None
for i, s in enumerate(catalogue, 1):
p.say(f' {i:2} {s["name"]}')
while True:
picked = (
p.text('Numbers of the products you have, separated by spaces')
.replace(',', ' ')
.split()
)
if all(n.isdigit() and 1 <= int(n) <= len(catalogue) for n in picked):
products = [catalogue[int(n) - 1] for n in dict.fromkeys(picked)]
break
p.say(f' Use numbers 1 to {len(catalogue)}.')
names = [s['name'] for s in catalogue]
products = [catalogue[i] for i in p.pick_many('Fertilizers you have', names)]
added = False
while kind := p.choose(
'Add a product?',
Expand Down Expand Up @@ -519,12 +550,24 @@ def interview(p, store):
"""The five steps; returns (session name, session, items to save). Nothing is written here."""
library, pending = load_library(), []
spec = ask_spec(p)
tanks = spec['tank_litres']
p.answered(
'Tanks',
f'A {tanks["A"]:g} L, B {tanks["B"]:g} L, acid {tanks["acid"]:g} L; '
f'1:{spec["ratio"]:g}, {spec["temperature_c"]:g} °C',
)
water, share, limits = ask_water(p, store, pending)
p.answered('Water', 'RO' if water == 'ro' else f'{water} ({share:g} %)')
formula, _, formula_title = ask_formula(p, store, pending, library)
product_store, _ = ask_products(p, store, pending, library)
p.answered('Formula', formula_title)
product_store, products = ask_products(p, store, pending, library)
p.answered('Fertilizers', f'{len(products)} products')
p.step(5)
acids = ask_acids(p, store, pending)
p.say('5/5 pH requirement')
p.answered('Acids', ', '.join(acids) or 'none')
p.step(5, '5/5 pH requirement')
ph = p.number('Target pH of the final solution', 5.8, high=14, positive=True)
p.answered('Target pH', f'{ph:g}')
depth = 1 + p.choose(
'Output depth',
[
Expand Down Expand Up @@ -626,6 +669,46 @@ def summarize(summary, say):
)


def output_folder(output, name):
"""The folder for the sheets: ``output`` or ./flahax-mix-<name>, numbered if it exists."""
folder = Path(output) if output else Path.cwd() / f'flahax-mix-{name}'
stem, n = folder, 1
while folder.exists():
n += 1
folder = stem.with_name(f'{stem.name}-{n}')
return folder


def write_sheets(summary, session, output):
"""Write the batch sheet, the summary and (full depth) the report; returns the file names."""
depth = session.get('depth', 1)
files = {
'batch-sheet.html': render_mix_sheet(summary, depth),
'summary.json': render(summary)['summary.json'],
}
if depth >= 3:
files['report.html'] = render_report(summary)
output.mkdir(parents=True)
for file, content in files.items():
(output / file).write_bytes(content.encode('utf-8'))
return list(files)


def saved_line(store, name):
"""The line that says where the answers were saved and how to run them again."""
return (
f'Saved the answers as {store.path("sessions", name)}; next time: flahax mix '
f'sessions/{name}'
)


def use_tui(plain, ask, say, stdin=None, stdout=None):
"""True when ``flahax mix`` should open the full-screen wizard instead of the line mode."""
if plain or ask is not input or say is not print:
return False
return supported(stdin or sys.stdin, stdout or sys.stdout)


def main(argv=None, *, ask=input, say=print, store=None):
"""The ``flahax mix`` command: interview or saved session, then the sheets; returns the process
exit code.
Expand All @@ -643,6 +726,11 @@ def main(argv=None, *, ask=input, say=print, store=None):
parser.add_argument(
'--output', help='new directory for the sheets (default: ./flahax-mix-<session>)'
)
parser.add_argument(
'--plain',
action='store_true',
help='line-by-line questions instead of the full-screen wizard',
)
args = parser.parse_args(argv)
if args.output and Path(args.output).exists():
say(f'flahax mix: {args.output} already exists; choose a new directory')
Expand All @@ -658,6 +746,14 @@ def main(argv=None, *, ask=input, say=print, store=None):
else 'Nothing is saved yet: run flahax mix'
)
return 0
if use_tui(args.plain, ask, say):
from .mix_tui import run_tui # mix_tui imports this module

code, lines = run_tui(store, args.session or None, args.output)
if code is not None:
for line in lines:
say(line)
return code
try:
if args.session:
path = find_session(store, args.session)
Expand All @@ -670,36 +766,20 @@ def main(argv=None, *, ask=input, say=print, store=None):
name, session, pending = interview(p, store)
for kind, item, data in pending:
store.save(kind, item, data)
say(
f'Saved the answers as {store.path("sessions", name)}; next time: flahax mix '
f'sessions/{name}'
)
say(saved_line(store, name))
except (KeyboardInterrupt, EOFError):
say('Stopped; nothing saved.')
return 1
except (DeliveryError, ValueError, OSError) as exc:
say(f'flahax mix: {exc}')
return 1
output = Path(args.output) if args.output else Path.cwd() / f'flahax-mix-{name}'
stem, n = output, 1
while output.exists():
n += 1
output = stem.with_name(f'{stem.name}-{n}')
output = output_folder(args.output, name)
try:
summary = run_batch(options_for(store, session))
except (DeliveryError, ValueError, OSError, KeyError) as exc:
say(f'flahax mix: {exc}')
return 1
depth = session.get('depth', 1)
files = {
'batch-sheet.html': render_mix_sheet(summary, depth),
'summary.json': render(summary)['summary.json'],
}
if depth >= 3:
files['report.html'] = render_report(summary)
output.mkdir(parents=True)
for file, content in files.items():
(output / file).write_bytes(content.encode('utf-8'))
files = write_sheets(summary, session, output)
summarize(summary, say)
say(f'Wrote {", ".join(files)} to {output}')
return 3 if summary['status'] == 'blocked' else 0
Loading
Loading
0