"""A model's settings, read from its entry in the API's catalogue. The page draws what the catalogue publishes, the way the web app's Model settings does: the controls, their order, their ranges and the line of help under each all come from the entry, so a setting that changes there changes here. Kept apart from the page so it can be read and tested without it. """ from __future__ import annotations import math # Not drawn. A region is chosen on the photo itself, and the demo returns the file type and # quality the model chooses by default. NOT_DRAWN = ("roi", "output_format", "quality") class Problem(ValueError): """A setting as typed cannot be sent. The message is for the visitor.""" def label(key: str) -> str: words = key.replace("_", " ") return words[0].upper() + words[1:] def option_label(value) -> str: """A choice as a person reads it. One with a digit in it, 2x2, is shown as sent.""" value = str(value) if any(character.isdigit() for character in value): return value return label(value.replace("-", " ")) def shown(value: float) -> str: """A number as a person reads it: 4/3 as 1.33.""" return f"{round(float(value), 2):g}" def held(value: float) -> float: """A slider's value as the page holds and shows it, to two places. `to_send` gives the range's own end back where the held value is that end rounded.""" return round(float(value), 2) def kind(spec: dict) -> str: """Which control a setting's declaration draws.""" if spec.get("type") == "boolean": return "switch" if "enum" in spec: return "choice" numeric = spec.get("type") in ("number", "integer") if spec.get("type") == "integer" and "maximum" in spec and spec["maximum"] - spec["minimum"] > 1000: return "number" if numeric and "maximum" in spec: return "slider" return "text" def drawn(entry: dict) -> list[str]: """The settings the page draws, in the catalogue's order.""" declared = entry["params_schema"].get("properties", {}) return [key for key in entry.get("params_order", []) if key in declared and key not in NOT_DRAWN] def properties_for(schema: dict, values: dict) -> dict: """Each setting's declaration as it stands for `values`: the bounds and default of every condition that holds are laid over it. Enhance's binning at 3x3 takes its scale to 1-1.33.""" declared = {key: dict(spec) for key, spec in schema.get("properties", {}).items()} for condition in schema.get("allOf", []): tests = list(condition.get("if", {}).get("properties", {}).items()) if not tests: continue key, test = tests[0] value = values.get(key) if isinstance(test.get("const"), bool): holds = test["const"] is True and value is True else: holds = value is not None and str(value) == str(test.get("const")) if holds: for changed, spec in condition.get("then", {}).get("properties", {}).items(): declared[changed] = {**declared.get(changed, {}), **spec} return declared def switches(schema: dict) -> set[str]: """The settings whose value changes another's range.""" return {key for condition in schema.get("allOf", []) for key in condition.get("if", {}).get("properties", {})} def rivals(schema: dict, key: str) -> set[str]: """The settings that may not be sent beside `key`: a width, a height or a scale, only one.""" found: set[str] = set() for pair in schema.get("not", {}).get("anyOf", []): if key in pair.get("required", []): found.update(pair["required"]) return found - {key} def step(spec: dict) -> float: """A slider's step: a half on a short range, and always one that lands on the maximum. 4/3, Enhance's largest scale binned 3x3, is no multiple of a half.""" if spec.get("type") == "integer": return 1 span = spec["maximum"] - spec["minimum"] wanted = 0.5 if span <= 4 else 1 return span / math.ceil(span / wanted - 1e-9) if span > 0 else wanted def to_send(entry: dict, values: dict, worked: tuple[int, int]) -> dict: """The parameters to submit for `values`, the drawn settings as the page holds them. `worked` is the size in pixels of the photo, or of the part chosen. Raises `Problem`.""" schema = entry["params_schema"] declared = properties_for(schema, values) typed: dict = {} for key in drawn(entry): if kind(declared[key]) != "text": continue text = str(values.get(key) or "").strip() if not text: continue if declared[key].get("type") == "integer": if not text.isdigit(): raise Problem(f"{label(key)} is a whole number of pixels.") typed[key] = int(text) else: typed[key] = text for key, pixels in typed.items(): scale = declared.get("scale") if key not in ("width", "height") or not scale: continue side = worked[0] if key == "width" else worked[1] least, most = math.ceil(side * scale["minimum"]), math.floor(side * scale["maximum"]) if not least <= pixels <= most: raise Problem(f"{label(key)} is from {least} to {most} px for this photo: " f"{entry['title']} enlarges {shown(scale['minimum'])} to " f"{shown(scale['maximum'])} times.") params: dict = dict(typed) for key in drawn(entry): spec = declared[key] drawn_as = kind(spec) if drawn_as == "text" or values.get(key) is None: continue if drawn_as == "slider": # A typed size stands in for the slider, as the settings say. if rivals(schema, key) & typed.keys(): continue value = min(max(float(values[key]), spec["minimum"]), spec["maximum"]) if held(value) == held(spec["maximum"]): value = spec["maximum"] params[key] = int(value) if spec.get("type") == "integer" else value elif drawn_as == "number": params[key] = int(values[key]) else: params[key] = values[key] return params