diff --git a/deeptutor/tools/vision/ggb_validator.py b/deeptutor/tools/vision/ggb_validator.py index f65672aba..c4602b20b 100644 --- a/deeptutor/tools/vision/ggb_validator.py +++ b/deeptutor/tools/vision/ggb_validator.py @@ -202,33 +202,56 @@ def _split_command_args(arg_string: str) -> list[str]: return args -def validate_text_command(command: str) -> tuple[str, list[str]]: +def _is_boolean_argument(arg: str) -> bool: + return arg.lower() in {"true", "false"} + + +def _is_point_argument(arg: str) -> bool: + """Return whether an argument is a syntactic two-coordinate point.""" + stripped = arg.strip() + if not (stripped.startswith("(") and stripped.endswith(")")): + return False + coordinates = _split_command_args(stripped[1:-1]) + return len(coordinates) == 2 and all(coordinates) + + +def _is_scalar_argument(arg: str) -> bool: + """Recognize conservative scalar expressions used for coordinate repair.""" + stripped = arg.strip() + if not stripped or _is_boolean_argument(stripped) or _is_point_argument(stripped): + return False + if stripped.startswith('"'): + return False + # Plain uppercase names follow GeoGebra's point convention. Do not turn + # Text["label", P, Q] into a point when P and Q may both be point objects. + if re.fullmatch(r"[A-Z][A-Za-z0-9_]*", stripped): + return False + return True + + +def validate_text_command(command: str) -> tuple[str, list[str], list[str]]: """Validate a ``Text`` command for arity and LaTeX balance. - GeoGebra accepts ``Text[, ]`` (2 args) or - ``Text[, , , ]`` (4 args) but **not** - ``Text[, , ]`` (3 args) — that last form is the one - reasoning models most often invent, and GeoGebra answers with - "illegal argument" rather than a structured error. + GeoGebra accepts ``Text[, ]`` (2 args), + ``Text[, , ]`` (3 args), or + ``Text[, , , ]`` (4 args). The common invented + form ``Text[, , ]`` is repaired into a two-argument point + when both trailing values are scalar expressions. Also checks that ``$`` LaTeX delimiters are balanced inside string arguments; an unbalanced ``$`` silently renders raw markup. Returns: - Tuple of (command, list of error descriptions). + Tuple of (fixed command, warnings, and error descriptions). """ + fixed = command + warnings: list[str] = [] errors: list[str] = [] match = re.search(r"\bText\s*\[(.*)\]\s*$", command, re.DOTALL) if match is None: - return command, errors + return fixed, warnings, errors args = _split_command_args(match.group(1)) - if len(args) == 3: - errors.append( - "Text[] has no 3-argument signature. Use Text[, ] " - "(2 args) or Text[, , , ] (4 args); " - "never Text[, , ]." - ) for arg in args: if arg.startswith('"'): @@ -238,7 +261,26 @@ def validate_text_command(command: str) -> tuple[str, list[str]]: if arg.count("$") % 2 != 0: errors.append(f"Text[] argument {arg} has unbalanced $ LaTeX delimiters.") - return command, errors + if len(args) == 3 and not errors: + second, third = args[1], args[2] + if _is_scalar_argument(second) and _is_scalar_argument(third): + args[1] = f"({second},{third})" + del args[2] + fixed = command[: match.start(1)] + ",".join(args) + command[match.end(1) :] + warnings.append("Combined scalar x and y arguments into a Text[] point argument") + elif not _is_boolean_argument(third): + errors.append( + "Invalid 3-argument Text[] signature. Use " + "Text[, , ] with a boolean third argument, " + "or combine scalar coordinates into Text[, (, )]." + ) + + if len(args) > 4: + errors.append( + "Text[] supports at most four arguments. Use Text[, , , ]." + ) + + return fixed, warnings, errors def validate_command(command: str) -> ValidationResult: @@ -277,7 +319,9 @@ def validate_command(command: str) -> ValidationResult: result.warnings.extend(warnings) # Check Text command arity and LaTeX balance - _, errors = validate_text_command(result.fixed) + fixed, warnings, errors = validate_text_command(result.fixed) + result.fixed = fixed + result.warnings.extend(warnings) result.errors.extend(errors) if result.errors: diff --git a/deeptutor/visualizers/builtin.py b/deeptutor/visualizers/builtin.py index e0f4dcef0..a6838da06 100644 --- a/deeptutor/visualizers/builtin.py +++ b/deeptutor/visualizers/builtin.py @@ -327,6 +327,13 @@ SetPointSize, SetLabelVisible and SetLabelMode sparingly to make the teaching focus obvious. Choose view bounds that contain the whole construction with margin. Never fake a diagram with unrelated fixed coordinates when a dependent construction is possible. +Use Text only with Text[, ], +Text[, , ], or +Text[, , , ]. A point must be one argument; +for computed coordinates write Text["$x^2$", ((a+b)/2, a+b+0.8)], never +Text["$x^2$", (a+b)/2, a+b+0.8]. Keep LaTeX dollar delimiters balanced and set +the substitution and LaTeX-formula booleans explicitly when using the +four-argument form. """, ), origin="bundled", diff --git a/tests/visualizers/test_ggb_validator.py b/tests/visualizers/test_ggb_validator.py index cf6eede6e..a981743c4 100644 --- a/tests/visualizers/test_ggb_validator.py +++ b/tests/visualizers/test_ggb_validator.py @@ -1,18 +1,23 @@ """Tests for GeoGebra command validator fatal-pattern checks.""" +import json + from deeptutor.tools.vision.ggb_validator import ( validate_command, validate_ggbscript, ) +from deeptutor.visualizers.builtin import bundled_visualizers class TestTextArity: - def test_text_with_3_args_is_rejected(self): + def test_scalar_text_coordinates_are_combined(self): # The fatal pattern from #1324: Text["str", expr, expr] command = 'T9=Text["$(a+b)^2=a^2+2ab+b^2$",(a+b)/2,a+b+0.8]' result = validate_command(command) assert not result.is_valid - assert any("no 3-argument signature" in e for e in result.errors) + assert result.errors == [] + assert result.fixed == ('T9=Text["$(a+b)^2=a^2+2ab+b^2$",((a+b)/2,a+b+0.8)]') + assert any("Combined scalar" in warning for warning in result.warnings) def test_text_with_2_args_passes(self): command = 'T1=Text["$a^2$",(a/2,a/2)]' @@ -26,12 +31,37 @@ class TestTextArity: assert result.is_valid assert result.errors == [] + def test_text_with_object_point_and_boolean_passes(self): + command = 'T1=Text["$a^2$",P,true]' + result = validate_command(command) + assert result.is_valid + assert result.errors == [] + def test_non_text_commands_unaffected(self): command = "S1=Segment[E,F]" result = validate_command(command) assert result.is_valid assert result.errors == [] + def test_text_with_point_and_non_boolean_third_argument_is_rejected(self): + command = 'T1=Text["$a^2$",(1,2),3]' + result = validate_command(command) + assert not result.is_valid + assert any("Invalid 3-argument Text[] signature" in error for error in result.errors) + + def test_uppercase_point_arguments_are_not_combined(self): + command = 'T1=Text["label",P,Q]' + result = validate_command(command) + assert not result.is_valid + assert result.fixed == command + assert any("Invalid 3-argument Text[] signature" in error for error in result.errors) + + def test_text_with_more_than_four_arguments_is_rejected(self): + command = 'T1=Text["$a^2$",(1,2),true,true,5]' + result = validate_command(command) + assert not result.is_valid + assert any("at most four arguments" in error for error in result.errors) + class TestLaTeXBalance: def test_unbalanced_dollar_is_rejected(self): @@ -48,7 +78,41 @@ class TestLaTeXBalance: class TestScriptLevel: - def test_mixed_script_reports_line_number(self): + def test_visualizer_payload_normalizes_repaired_text_command(self): + visualizer = next( + plugin for plugin in bundled_visualizers() if plugin.manifest.id == "geogebra" + ) + payload = json.dumps( + { + "app_name": "geometry", + "commands": [ + "A=(0,0)", + 'T9=Text["$(a+b)^2$",(a+b)/2,a+b+0.8]', + ], + "view": {"x_min": -1, "x_max": 2, "y_min": -1, "y_max": 2}, + } + ) + + is_valid, normalized, error = visualizer.validator(payload) + + assert is_valid + assert error == "" + assert normalized["commands"][-1] == ('T9=Text["$(a+b)^2$",((a+b)/2,a+b+0.8)]') + assert normalized["validation_warnings"] == [ + "Line 2: Combined scalar x and y arguments into a Text[] point argument" + ] + + def test_geogebra_prompt_documents_text_signatures(self): + visualizer = next( + plugin for plugin in bundled_visualizers() if plugin.manifest.id == "geogebra" + ) + prompt = visualizer.manifest.prompt + + assert "Text[, , ]" in prompt + assert 'Text["$x^2$", ((a+b)/2, a+b+0.8)]' in prompt + assert 'Text["$x^2$", (a+b)/2, a+b+0.8]' in prompt + + def test_scalar_coordinates_are_repaired_with_line_warning(self): script = "\n".join( [ "a=Slider(1,5,0.1)", @@ -56,6 +120,21 @@ class TestScriptLevel: 'T9=Text["$(a+b)^2$",(a+b)/2,a+b+0.8]', ] ) + fixed, warnings, errors = validate_ggbscript(script) + assert errors == [] + assert 'T9=Text["$(a+b)^2$",((a+b)/2,a+b+0.8)]' in fixed.splitlines() + assert warnings == [ + "Line 3: Combined scalar x and y arguments into a Text[] point argument" + ] + + def test_mixed_script_reports_line_number(self): + script = "\n".join( + [ + "a=Slider(1,5,0.1)", + "b=Slider(1,5,0.1)", + 'T9=Text["$(a+b)^2$",P,Q]', + ] + ) _, _, errors = validate_ggbscript(script) assert len(errors) == 1 assert errors[0].startswith("Line 3:")