diff --git a/README.md b/README.md index 2ef55a1..a320f88 100644 --- a/README.md +++ b/README.md @@ -93,7 +93,7 @@ Because conversion is rule-based, Modulo can only translate what it has a rule f | Symbol | Shape | Text it contains | Generated Python | |---|---|---|---| | Terminal | Rounded rectangle or oval | `Start` or `End` | Opens and closes the `main()` function | -| Process | Rectangle | A statement such as `total = total + n` | The statement, validated and emitted as written | +| Process | Rectangle | A statement such as `total = total + n`; the supported high-level command `Calculate factorial` (or `Calculate factorial of n`) | Ordinary statements are validated and emitted as written; factorial is lowered to a safe multiplication loop | | Data Input | Parallelogram | `Input n` or `Input n:int` | `n = input()` or `n = int(input())` | | Data Output | Parallelogram | `Output total` | `print(total)` | | Decision | Diamond | A condition such as `n > 0` | `if n > 0:` ... `else:` | @@ -101,11 +101,11 @@ Because conversion is rule-based, Modulo can only translate what it has a rule f | Connector | Small circle | A matching label (`A`, `B`, ...) | Nothing (it only joins parts of the graph) | | Flow arrow | Arrow | Optional label | Control flow between blocks | -**Supported logic:** sequential execution, if/else (including nested), `while` and `for` loops, variable assignment, logical expressions, input/output, and optional `break`, `continue`, and `return` (drawn as Process boxes containing only that word). +**Supported logic:** sequential execution, if/else (including nested), `while` and `for` loops, variable assignment, logical expressions, input/output, the explicit high-level process command `Calculate factorial` (with one input, or `Calculate factorial of n` when multiple inputs exist), and optional `break`, `continue`, and `return` (drawn as Process boxes containing only that word). When an untyped input is compared with a numeric literal, code generation infers an integer input unless the diagram explicitly annotates a type. **Edge labels:** every Decision and Iteration shape has exactly two outgoing arrows labeled `Yes` and `No` (also accepted: `True`/`False`, `Y`/`N`, in any letter case). For an Iteration, `Yes` enters the loop body and `No` leaves the loop. -**Statements and conditions** are limited to a small, safe language: names, numbers, strings, arithmetic, comparisons, `and`/`or`/`not`, and a short allowlist of built-ins (`print`, `input`, `int`, `float`, `str`, `len`, `range`, `abs`, `min`, `max`, `round`). Anything else produces a diagnostic rather than being passed into the output. +**Statements and conditions** are limited to a small, safe language: names, numbers, strings, arithmetic, comparisons, `and`/`or`/`not`, and a short allowlist of built-ins (`print`, `input`, `int`, `float`, `str`, `len`, `range`, `abs`, `min`, `max`, `round`). The factorial command is a narrow, explicitly implemented exception to the expression grammar; unknown natural-language process text still produces a diagnostic rather than being passed into the output. **Input rules:** @@ -605,20 +605,36 @@ Each setting can be overridden with an environment variable of the same name. ## 12. Testing -Run everything from the repository root: +Run the fast, deterministic tests from the repository root: ```bash -pytest +python -m pip install -r requirements.txt +python -m pip install pytest +python -m pytest -q ``` -The test strategy takes advantage of the pipeline being deterministic: +### Flowchart recognition benchmark -- **Unit tests per service** check each stage in isolation using small hand-built inputs. -- **Synthetic diagrams for Vision.** Test images are drawn in code with OpenCV (rectangles, diamonds, arrows, text), so the expected shapes, positions, and text are known exactly. -- **Golden-file tests for the whole pipeline.** Each fixture flowchart has an expected pseudocode file and an expected Python file. Any change in output shows up as a plain diff. -- **Validation tests** include every diagnostic code, including malformed diagrams (missing Start, unreachable nodes, unlabeled branches, unstructured flow). -- **Security tests** confirm that statements outside the allowlist are rejected. -- **Store and API tests** cover expiry, eviction, bad uploads, and unknown analysis IDs. +`tests/test_flowchart_benchmark.py` introduces a synthetic fixture suite and a machine-readable ground-truth manifest at `tests/fixtures/expected/manifest.json`. The PNG fixtures and per-fixture `.txt` control-flow specifications cover sequences, input/output, decisions and branch labels, nested branches, loops, crossing connectors, long connectors, small text, mathematical operators, colored backgrounds, and low-resolution diagrams. The images are deliberately synthetic and documented so new hand-verified fixtures can be added without requiring an external dataset. + +The fast default test run checks fixture integrity and coverage, and exercises the geometry classifier independently of OCR. It does **not** claim that a syntactically valid Python result proves the interpreted logic is correct. + +To run the real OCR and end-to-end analysis baseline (slower; requires the Python dependencies and a working Tesseract executable with the configured language data): + +```bash +# PowerShell +$env:FLOWCHART_RUN_PIPELINE = "1" +python -m pytest tests/test_flowchart_benchmark.py -q -rs + +# bash +FLOWCHART_RUN_PIPELINE=1 python -m pytest tests/test_flowchart_benchmark.py -q -rs +``` + +Each full-pipeline case records separate metrics for detected node count, shape-type agreement, exact OCR text agreement, detected edge count, IR availability, pseudocode line count, and diagnostic codes. Use `--junitxml=flowchart-baseline.xml` to retain per-case properties in CI. Failures/diagnostics should be attributed to the earliest failing stage: **vision** (shape detection/classification/OCR), **graph** (connector, direction, edge or branch label), **validation** (structural diagnostics), or **logic/pseudocode** (control-flow interpretation). Graph comparisons currently report counts and raw node IDs rather than asserting exact edge identity because recognition assigns its own IDs; extend the manifest with verified coordinate/label matching before using these metrics as a hard release gate. + +The initial fast baseline in this environment is **13 passed, 11 skipped** (the 11 full-pipeline cases are opt-in to avoid unexpected OCR runtime in every unit-test run). A full OCR baseline was not completed as part of the fast run. Install Tesseract separately from pip; if it is missing or its executable/language data is unavailable, the opt-in pipeline tests may fail with an environment or OCR diagnostic. These tests do not replace broader unit/API tests: this project archive currently contains no pre-existing `tests/` suite despite earlier architecture text describing one. + +To add a fixture: add a PNG under `tests/fixtures/flowcharts/`, add exact expected node types/text and directed edges (including branch labels) to the manifest, and add a readable control-flow specification under `tests/fixtures/expected/`. Prefer exact expected pseudocode only after manually verifying the recognition and logic output; never bless a current incorrect output as ground truth merely to make the test pass. --- @@ -654,3 +670,37 @@ Planned after the MVP, in no fixed order: Modulo is open source. The license will be chosen and added as `LICENSE` once Open Decision 3 is settled. Developed by West Texas System Solutions for CS4366: Senior Capstone, Fall 2026. + + +### OCR preprocessing regression checks + +The vision OCR stage now keeps the unthresholded crop as its first candidate and compares it with CLAHE contrast normalization, mild bilateral denoising, adaptive thresholding, and Otsu variants. Small crops are enlarged 1.5×–3× before recognition, and OCR word boxes are mapped back to page coordinates. Candidate ranking combines Tesseract confidence with printable-character quality, symbol preservation, shape-aware heuristics, and agreement between repeated readings; up to three plausible readings are exposed as `ocr_candidates` when readings are close or confidence is low. The original recognized text is not rewritten to satisfy Python syntax. + +Run focused OCR unit tests with `PYTHONPATH=. pytest -q tests/test_ocr_preprocessing.py tests/test_flowchart_benchmark.py`. On the implementation environment, this completed with **17 passed, 11 skipped** (the 11 end-to-end OCR benchmark cases are opt-in). A real Tesseract end-to-end run for `simple_sequence` passed in **4.12 seconds**. Attempting all opt-in end-to-end fixtures exceeded the five-minute execution window, so no aggregate before/after OCR accuracy percentage is claimed; use `PYTHONPATH=. FLOWCHART_RUN_PIPELINE=1 pytest -q tests/test_flowchart_benchmark.py --junitxml=benchmark.xml` on a benchmark-capable machine to record the per-fixture metrics. + +### Programming-aware OCR ambiguity review + +Modulo's validation stage checks programming-like flowchart text for likely OCR confusions (including `=`/`==`, `%`/`0`, `1`/`l`, and bracket/parenthesis pairs). It retains the original OCR reading in `original_ocr_text`, keeps proposed readings in `ocr_candidates`, and emits a review warning rather than silently rewriting expressions. Syntax validity is only a weak ranking signal; it does not establish which reading the diagram intended. Review suggestions are shown alongside flagged elements, and the user must explicitly edit and revalidate a reading before it affects pseudocode or generated Python. + +Run the focused checks with `PYTHONPATH=. pytest -q tests/test_programming_ocr_validation.py tests/test_ocr_preprocessing.py`. + +### Shape-classification robustness (Prompt 4) + +The vision classifier now combines multi-scale polygon approximation, interior +corner angles, normalized corner placement, bounding-box aspect ratio, fill ratio, +contour solidity, and circularity. It uses these cues together to distinguish +process rectangles, decision diamonds, input/output parallelograms, iteration +hexagons, rounded terminals, and circular connectors. Ambiguous contours remain +`unknown` rather than being coerced into a known type. Existing node fields and +shape labels are preserved, so downstream graph and text-association interfaces +are unchanged. OCR still uses the contour's original bounding box and crop; the +classifier does not shift or merge node boxes. + +Validation performed for this change: `PYTHONPATH=. pytest -q` passes the +standard geometry and OCR unit tests plus dedicated rotated-rectangle, rounded +terminal, circular connector, low-resolution parallelogram, and ambiguous-triangle +tests. The current run reports **29 passed, 11 skipped**. The skipped tests are +full-pipeline benchmark runs that require `FLOWCHART_RUN_PIPELINE=1` and a working +Tesseract installation. This is a classifier-level regression improvement, not a +claim of measured end-to-end OCR/graph accuracy improvement; compare those fixture +metrics with `FLOWCHART_RUN_PIPELINE=1 PYTHONPATH=. pytest -q` on the target setup. diff --git a/RECOGNITION_FIXES.md b/RECOGNITION_FIXES.md new file mode 100644 index 0000000..f303102 --- /dev/null +++ b/RECOGNITION_FIXES.md @@ -0,0 +1,19 @@ +# Flowchart recognition improvements + +This update improves recognition of filled-color flowcharts without adding rules for particular labels or words. + +## Changes + +- Expanded arrowhead evidence checks to include small rasterized arrowheads. +- Added a constrained, warning-tagged direction fallback for connectors with exactly two node contacts where the input/decision/output roles provide a clear transition. Ambiguous connectors remain unresolved rather than being connected by reading order. +- Improved OCR cleanup for stray punctuation immediately after `If` and for a likely missing stroke in an equality operator. The original OCR reading remains available as a review alternative, and a bare single `=` is not rewritten without additional OCR-noise evidence. +- Improved branch-label inference for diagrams with a vertical branch and a sideways branch; inferred labels are marked with a warning for review. +- Accepted descriptive input labels such as `Input variable: Number` in the input notation parser. +- Added a regression fixture and tests for the supplied modulo/even-odd flowchart. + +## Verification + +- Unit/regression suite: `python -m pytest -q` — 50 passed, 14 skipped. +- Supplied flowchart integration test: `FLOWCHART_RUN_PIPELINE=1 python -m pytest tests/test_recognition_improvements.py::test_modulo_even_odd_flowchart_recognizes_nodes_edges_and_decision_text -q` — passed. + +The supplied diagram does not draw a connector from the `Number is odd` output to `End`. The recognizer intentionally does not invent that missing edge. It reports the resulting incomplete path so the diagram can be corrected or reviewed. diff --git a/assets/apple-touch-icon.png b/assets/apple-touch-icon.png new file mode 100644 index 0000000..f41412e Binary files /dev/null and b/assets/apple-touch-icon.png differ diff --git a/assets/favicon-32.png b/assets/favicon-32.png new file mode 100644 index 0000000..10f1719 Binary files /dev/null and b/assets/favicon-32.png differ diff --git a/assets/icon-192.png b/assets/icon-192.png new file mode 100644 index 0000000..2f29108 Binary files /dev/null and b/assets/icon-192.png differ diff --git a/assets/icon-512.png b/assets/icon-512.png new file mode 100644 index 0000000..1cd67e0 Binary files /dev/null and b/assets/icon-512.png differ diff --git a/assets/modulo-128.png b/assets/modulo-128.png new file mode 100644 index 0000000..de3dc1e Binary files /dev/null and b/assets/modulo-128.png differ diff --git a/assets/modulo-150.png b/assets/modulo-150.png new file mode 100644 index 0000000..d770222 Binary files /dev/null and b/assets/modulo-150.png differ diff --git a/assets/modulo-16.png b/assets/modulo-16.png new file mode 100644 index 0000000..9b026d2 Binary files /dev/null and b/assets/modulo-16.png differ diff --git a/assets/modulo-180.png b/assets/modulo-180.png new file mode 100644 index 0000000..f41412e Binary files /dev/null and b/assets/modulo-180.png differ diff --git a/assets/modulo-192.png b/assets/modulo-192.png new file mode 100644 index 0000000..2f29108 Binary files /dev/null and b/assets/modulo-192.png differ diff --git a/assets/modulo-24.png b/assets/modulo-24.png new file mode 100644 index 0000000..43c8c71 Binary files /dev/null and b/assets/modulo-24.png differ diff --git a/assets/modulo-256.png b/assets/modulo-256.png new file mode 100644 index 0000000..e4637a1 Binary files /dev/null and b/assets/modulo-256.png differ diff --git a/assets/modulo-32.png b/assets/modulo-32.png new file mode 100644 index 0000000..10f1719 Binary files /dev/null and b/assets/modulo-32.png differ diff --git a/assets/modulo-48.png b/assets/modulo-48.png new file mode 100644 index 0000000..67017f8 Binary files /dev/null and b/assets/modulo-48.png differ diff --git a/assets/modulo-512.png b/assets/modulo-512.png new file mode 100644 index 0000000..1cd67e0 Binary files /dev/null and b/assets/modulo-512.png differ diff --git a/assets/modulo-64.png b/assets/modulo-64.png new file mode 100644 index 0000000..5f14ad7 Binary files /dev/null and b/assets/modulo-64.png differ diff --git a/assets/modulo-96.png b/assets/modulo-96.png new file mode 100644 index 0000000..f072ce4 Binary files /dev/null and b/assets/modulo-96.png differ diff --git a/assets/modulo-m-icon.svg b/assets/modulo-m-icon.svg new file mode 100644 index 0000000..fe40a86 --- /dev/null +++ b/assets/modulo-m-icon.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/assets/modulo-wordmark.svg b/assets/modulo-wordmark.svg new file mode 100644 index 0000000..5be1f75 --- /dev/null +++ b/assets/modulo-wordmark.svg @@ -0,0 +1 @@ +Modulo \ No newline at end of file diff --git a/backend/models.py b/backend/models.py index 9446403..957abc1 100644 --- a/backend/models.py +++ b/backend/models.py @@ -34,10 +34,16 @@ class Node: flags: list[str] = field(default_factory=list) polygon: list[tuple[int, int]] = field(default_factory=list) words: list[OCRWord] = field(default_factory=list) + ocr_candidates: list[dict[str, Any]] = field(default_factory=list) + original_ocr_text: str | None = None + def __post_init__(self) -> None: + if self.original_ocr_text is None: + self.original_ocr_text = self.text def to_dict(self) -> dict: - return {"id": self.id, "type": self.type, "text": self.text, "bbox": self.bbox.to_list(), + return {"id": self.id, "type": self.type, "text": self.text, "original_ocr_text": self.original_ocr_text, "bbox": self.bbox.to_list(), "confidence": round(self.confidence, 4), "flags": self.flags, - "polygon": self.polygon, "words": [word.to_dict() for word in self.words]} + "polygon": self.polygon, "words": [word.to_dict() for word in self.words], + "ocr_candidates": self.ocr_candidates} @dataclass class Arrow: diff --git a/backend/notation.py b/backend/notation.py index 11c2bc8..b78e86b 100644 --- a/backend/notation.py +++ b/backend/notation.py @@ -11,14 +11,29 @@ ast.Add, ast.Sub, ast.Mult, ast.Div, ast.FloorDiv, ast.Mod, ast.Pow, ast.UAdd, ast.USub, ast.Not, ast.And, ast.Or, ast.Eq, ast.NotEq, ast.Lt, ast.LtE, ast.Gt, ast.GtE) NAME = re.compile(r"^[A-Za-z][A-Za-z0-9_]*$") -INPUT = re.compile(r"^Input\s+([A-Za-z][A-Za-z0-9_]*)(?::(int|float|str))?$", re.IGNORECASE) +INPUT = re.compile(r"^Input\s+(?:variable\s*:\s*)?([A-Za-z][A-Za-z0-9_]*)(?::(int|float|str))?$", re.IGNORECASE) FOR = re.compile(r"^FOR\s+([A-Za-z][A-Za-z0-9_]*)\s+IN\s+(.+)$", re.IGNORECASE) +# Small, explicit vocabulary of safe high-level operations that can be lowered to Python. +FACTORIAL_COMMAND = re.compile(r"^calculate\s+(?:the\s+)?factorial(?:\s+of\s+([A-Za-z][A-Za-z0-9_]*))?$", re.IGNORECASE) + +def is_supported_natural_operation(text: str) -> bool: + """Whether a process label names a deterministic operation we implement.""" + return bool(FACTORIAL_COMMAND.fullmatch(text.strip())) class NotationError(ValueError): pass def normalize_label(text: str | None) -> str | None: - return BRANCH_LABELS.get((text or "").strip().casefold()) + """Normalize common branch-label OCR variants without guessing arbitrary text. + + OCR frequently includes nearby punctuation (for example ``Yes.`` or ``No,``) + when a label is printed close to a connector. Strip only surrounding + punctuation/whitespace; keep the accepted vocabulary deliberately small. + """ + value = (text or "").strip().casefold() + value = re.sub(r"^[\W_]+|[\W_]+$", "", value, flags=re.UNICODE) + value = re.sub(r"\s+", " ", value) + return BRANCH_LABELS.get(value) def normalize_condition(text: str) -> str: """Accept natural flowchart decision labels such as `if x % 2 == 0`. @@ -94,7 +109,7 @@ def validate_node_text(kind: str, text: str) -> None: raise NotationError("Use WHILE condition or FOR name IN expression.") validate_ast(match.group(2)) elif kind == "process": - if text not in ("break", "continue", "return"): + if text not in ("break", "continue", "return") and not is_supported_natural_operation(text): validate_ast(text, "exec") else: raise NotationError("This shape is outside the supported notation.") diff --git a/backend/services/codegen_service.py b/backend/services/codegen_service.py index f0042e8..73abe96 100644 --- a/backend/services/codegen_service.py +++ b/backend/services/codegen_service.py @@ -6,7 +6,9 @@ """ from __future__ import annotations import ast +import re from backend.models import IRNode, PipelineContext, SourceLine +from backend.notation import FACTORIAL_COMMAND _NUMERIC_BINOPS = (ast.Add, ast.Sub, ast.Mult, ast.Div, ast.FloorDiv, ast.Mod, ast.Pow) @@ -26,6 +28,12 @@ def run(self, context: PipelineContext) -> PipelineContext: if context.ir is None or context.has_errors or not context.approved: return context names, input_types = self._analyze(context.ir) + if any(child.kind == "Process" and FACTORIAL_COMMAND.fullmatch(child.text.strip()) + for child in self._walk_ir(context.ir)) and not getattr(self, "_factorial_operand", None): + context.diagnose("error", "AMBIGUOUS_FACTORIAL_INPUT", + "Calculate factorial needs an explicit input variable when the flowchart has multiple inputs.", + "Write 'Calculate factorial of name' or use a single input variable.") + return context body=[] self._render(context.ir, body, 1, names, input_types) body=[SourceLine(1,0,"def main():",[])]+[SourceLine(index+2,indent,text,ids) for index,(indent,text,ids) in enumerate(body)] @@ -44,15 +52,22 @@ def run(self, context: PipelineContext) -> PipelineContext: def _analyze(self, root: IRNode): names: dict[str,str] = {} input_types: dict[str,str] = {} + explicit_input_types: set[str] = set() expressions: list[str] = [] + factorial_input: str | None = None + input_variables: list[str] = [] def define(name): if name: names.setdefault(name.casefold(), name) def walk(node): + nonlocal factorial_input for child in node.children: if child.kind == "Input": define(child.variable) + input_variables.append(child.variable) input_types[child.variable.casefold()] = child.expression or "str" + if child.text and re.search(r":\s*(?:int|float|str)\s*$", child.text, re.IGNORECASE): + explicit_input_types.add(child.variable.casefold()) elif child.kind == "For": define(child.variable); expressions.append(child.expression) if child.kind in ("If", "While"): @@ -61,29 +76,46 @@ def walk(node): expressions.append(child.expression) elif child.kind == "Process": expressions.append(child.text) + match = FACTORIAL_COMMAND.fullmatch(child.text.strip()) + if match and match.group(1): + factorial_input = match.group(1) walk(child) if child.otherwise: walk(IRNode("Block", children=child.otherwise)) walk(root) - # If an input participates in numeric arithmetic, treat an untyped input as int. - # Explicit input annotations (int/float/str) always take precedence. + # Infer integer input from arithmetic/comparisons with numeric literals, but + # never override an explicit :int/:float/:str annotation from the diagram. for expression in expressions: try: tree = ast.parse(expression, mode="exec" if "=" in expression and "==" not in expression else "eval") except (SyntaxError, ValueError): try: tree = ast.parse(expression, mode="eval") except (SyntaxError, ValueError): continue - for operation in (n for n in ast.walk(tree) if isinstance(n, ast.BinOp) and isinstance(n.op, _NUMERIC_BINOPS)): - for item in ast.walk(operation): - if isinstance(item, ast.Name) and item.id.casefold() in input_types: - key = item.id.casefold() - if input_types[key] == "str": input_types[key] = "int" + numeric_context = any(isinstance(n, (ast.BinOp, ast.Compare)) for n in ast.walk(tree)) + if not numeric_context: + continue + numeric_names = {item.id.casefold() for item in ast.walk(tree) if isinstance(item, ast.Name)} + if "number" in input_types and "num" in numeric_names and "num" not in input_types: + numeric_names.add("number") + for key in numeric_names.intersection(input_types): + if key not in explicit_input_types and input_types[key] == "str": + input_types[key] = "int" + # A command like "Calculate factorial" operates on the sole input when no + # operand is written. This is deterministic and avoids guessing with several inputs. + if factorial_input: + names.setdefault(factorial_input.casefold(), factorial_input) + self._factorial_operand = factorial_input or (input_variables[0] if len(input_variables) == 1 else None) return names, input_types def _normalize(self, text: str, names: dict[str,str], mode="eval") -> str: try: tree = ast.parse(text, mode=mode) - tree = _CanonicalNames(names).visit(tree) + canonical_names = dict(names) + # Common abbreviation in educational diagrams: "num" often refers to + # the input labelled "number". Apply only when unambiguous. + if "number" in names and "num" not in names: + canonical_names["num"] = names["number"] + tree = _CanonicalNames(canonical_names).visit(tree) ast.fix_missing_locations(tree) return ast.unparse(tree).strip() except (SyntaxError, ValueError): @@ -93,7 +125,20 @@ def _render(self,node,lines,indent,names,input_types): for child in node.children: ids=child.source_ids if child.kind=="Process": - lines.append((indent,self._normalize(child.text,names,"exec"),ids)) + factorial_match = FACTORIAL_COMMAND.fullmatch(child.text.strip()) + if factorial_match: + operand = factorial_match.group(1) or getattr(self, "_factorial_operand", None) + if operand: + operand = names.get(operand.casefold(), operand) + lines.append((indent, "factorial = 1", ids)) + lines.append((indent, f"for _factorial_index in range(1, {operand} + 1):", ids)) + lines.append((indent + 1, "factorial *= _factorial_index", ids)) + else: + # Validation should have caught this ambiguous operation; keep + # code generation defensive rather than silently choosing input. + raise ValueError("Calculate factorial needs an explicit operand or exactly one input.") + else: + lines.append((indent,self._normalize(child.text,names,"exec"),ids)) elif child.kind=="Input": variable=names.get(child.variable.casefold(),child.variable) input_type=input_types.get(child.variable.casefold(),child.expression or "str") @@ -115,6 +160,13 @@ def _render(self,node,lines,indent,names,input_types): elif child.kind in ("Start","End"): continue + def _walk_ir(self, root): + for child in root.children: + yield child + yield from self._walk_ir(child) + if child.otherwise: + yield from self._walk_ir(IRNode("Block", children=child.otherwise)) + def _render_block(self,children,lines,indent,names,input_types): self._render(IRNode("Block",children=children),lines,indent,names,input_types) diff --git a/backend/services/graph_service.py b/backend/services/graph_service.py index c4e40da..716d574 100644 --- a/backend/services/graph_service.py +++ b/backend/services/graph_service.py @@ -20,7 +20,7 @@ def arrowhead_evidence(points: np.ndarray, point: tuple[int, int]) -> bool: """Detect a flared V/triangle near a tip followed by a narrower shaft.""" delta = points.astype(float) - np.asarray(point) radius = np.linalg.norm(delta, axis=1) - for span in (56, 100, 160): + for span in (12, 18, 28, 40, 56, 80, 120, 160): shaft = delta[(radius >= span * .55) & (radius <= span * 1.2)] if len(shaft) < 4: continue @@ -136,6 +136,295 @@ def distance_to_path(point: tuple[float, float], path: list[tuple[int, int]]) -> return min(distances, default=math.inf) +def bridge_aligned_connector_gaps(mask: np.ndarray, nodes: list[Node]) -> np.ndarray: + """Reconnect line fragments separated by erased branch-label text. + + Only thin, strongly aligned vertical/horizontal fragments are bridged, and + only across a bounded gap with no intervening node. This avoids global + morphological closing, which can join unrelated arrows and node borders. + """ + count, labels, stats, _ = cv2.connectedComponentsWithStats(mask, connectivity=8) + components = [] + for index in range(1, count): + x, y, width, height, area = map(int, stats[index]) + if area < 20 or max(width, height) < 35: + continue + components.append((index, x, y, width, height, area)) + result = mask.copy() + max_gap = max(45, int(round(mask.shape[1] * .05))) + x_tolerance = max(24, int(round(mask.shape[1] * .015))) + + def crosses_node(a, b): + ax, ay = a + bx, by = b + for node in nodes: + nx, ny, nw, nh = node.bbox.to_list() + # Ignore a node only if an endpoint lies within its expanded bounds; + # otherwise any crossing through a shape makes the bridge unsafe. + if min(ax, bx) < nx + nw and max(ax, bx) > nx and min(ay, by) < ny + nh and max(ay, by) > ny: + return True + return False + + max_endpoint_span = 20 + for i, a in enumerate(components): + _, ax, ay, aw, ah, _ = a + for b in components[i + 1:]: + _, bx, by, bw, bh, _ = b + + # Vertical continuation. Use the narrow pixel runs at the facing + # component boundaries; an elbow connector's overall bbox may be + # wide/tall and must not disqualify its narrow endpoint. + if by >= ay + ah: + gap = by - (ay + ah) + if 8 < gap <= max_gap: + upper_xs = np.where(labels[ay + ah - 1, :] == a[0])[0] + lower_xs = np.where(labels[by, :] == b[0])[0] + if (0 < len(upper_xs) <= max_endpoint_span and + 0 < len(lower_xs) <= max_endpoint_span): + upper_x = float(np.median(upper_xs)) + lower_x = float(np.median(lower_xs)) + if abs(upper_x - lower_x) <= x_tolerance: + start = (int(round(upper_x)), ay + ah - 1) + end = (int(round(lower_x)), by) + if not crosses_node(start, end): + thickness = max(3, min(9, int(round( + (len(upper_xs) + len(lower_xs)) / 2 + )))) + cv2.line(result, start, end, 255, thickness) + + # Horizontal continuation, with the same endpoint-based safeguards. + if bx >= ax + aw: + gap = bx - (ax + aw) + if 8 < gap <= max_gap: + left_ys = np.where(labels[:, ax + aw - 1] == a[0])[0] + right_ys = np.where(labels[:, bx] == b[0])[0] + if (0 < len(left_ys) <= max_endpoint_span and + 0 < len(right_ys) <= max_endpoint_span): + left_y = float(np.median(left_ys)) + right_y = float(np.median(right_ys)) + if abs(left_y - right_y) <= x_tolerance: + start = (ax + aw - 1, int(round(left_y))) + end = (bx, int(round(right_y))) + if not crosses_node(start, end): + thickness = max(3, min(9, int(round( + (len(left_ys) + len(right_ys)) / 2 + )))) + cv2.line(result, start, end, 255, thickness) + return result + + +def infer_obvious_missing_branch_to_end(context: PipelineContext, graph: FlowGraph) -> bool: + """Recover one likely omitted connector when a decision's sibling branch reaches End. + + This is deliberately narrow: there must be exactly one End, a decision with + exactly two output-shaped branch targets, one output must already reach End, + and its sibling output must have no outgoing edge. This gives a little grace + for a faint/missing connector without guessing from reading order on general + diagrams. The inferred edge is marked with a warning for review. + """ + ends = [n for n in graph.nodes if n.type == "terminal" and n.text.strip().casefold() == "end"] + if len(ends) != 1: + return False + end = ends[0] + by_id = {node.id: node for node in graph.nodes} + outgoing: dict[str, list[Edge]] = defaultdict(list) + incoming: dict[str, list[Edge]] = defaultdict(list) + for edge in graph.edges: + outgoing[edge.source].append(edge) + incoming[edge.target].append(edge) + + def reaches_end(start_id: str) -> bool: + pending, seen = [start_id], set() + while pending: + current = pending.pop() + if current == end.id: + return True + if current in seen: + continue + seen.add(current) + pending.extend(edge.target for edge in outgoing[current]) + return False + + for decision in (node for node in graph.nodes if node.type == "decision"): + branches = outgoing[decision.id] + if len(branches) != 2 or any(edge.label and edge.label.casefold() not in {"true", "false", "yes", "no", "y", "n"} for edge in branches): + continue + targets = [by_id.get(edge.target) for edge in branches] + if any(node is None or node.type != "output" for node in targets): + continue + dangling = [node for node in targets if not outgoing[node.id] and not reaches_end(node.id)] + connected = [node for node in targets if outgoing[node.id] and reaches_end(node.id)] + if len(dangling) != 1 or len(connected) != 1: + continue + source = dangling[0] + if len(incoming[source.id]) != 1 or incoming[source.id][0].source != decision.id: + continue + # Route outside the rightmost shape, then enter End from its right edge. + # The path is only a reviewable hypothesis; the warning makes that clear. + sx, sy, sw, sh = source.bbox.to_list() + ex, ey, ew, eh = end.bbox.to_list() + image_width = context.stroke_mask.shape[1] if context.stroke_mask is not None else max(sx + sw, ex + ew) + 80 + rightmost = max(node.bbox.x + node.bbox.width for node in graph.nodes) + route_x = min(image_width - 3, max(sx + sw, rightmost) + 18) + start = (sx + sw, sy + sh // 2) + finish = (ex + ew, ey + eh // 2) + route = [start, (route_x, start[1]), (route_x, finish[1]), finish] + edge = Edge(f"e{len(graph.edges) + 1}", source.id, end.id, points=route) + graph.edges.append(edge) + context.arrows.append(Arrow(edge.id, route, finish, source_hint=source.id, target_hint=end.id)) + context.diagnose( + "warning", "INFERRED_BRANCH_TO_END", + "A missing or faint connector was inferred because the sibling output reaches End and this output branch otherwise has no continuation.", + "Review the inferred connection; remove it if the source diagram intentionally leaves this branch unfinished.", + [decision.id, source.id, end.id], + ) + return True + return False + + +def infer_high_confidence_missing_edges(context: PipelineContext, graph: FlowGraph) -> int: + """Recover a small class of missing edges from strong geometry/topology evidence. + + This complements pixel-traced edges rather than replacing them. A vertical + edge requires visible connector ink in the gap. A missing decision branch is + only inferred when the other branch is already traced and the sole unconnected + process/output candidate itself leads to the same End terminal. All recovered + edges are reviewable warnings. + """ + if context.stroke_mask is None: + return 0 + nodes = {node.id: node for node in graph.nodes} + outgoing: dict[str, list[Edge]] = defaultdict(list) + incoming: dict[str, list[Edge]] = defaultdict(list) + for edge in graph.edges: + outgoing[edge.source].append(edge) + incoming[edge.target].append(edge) + + def reaches_end(start_id: str, end_id: str) -> bool: + pending, seen = [start_id], set() + while pending: + current = pending.pop() + if current == end_id: + return True + if current in seen: + continue + seen.add(current) + pending.extend(edge.target for edge in outgoing[current]) + return False + + ends = [n for n in graph.nodes if n.type == "terminal" and n.text.strip().casefold() == "end"] + inferred_count = 0 + mask = context.stroke_mask + height, width = mask.shape[:2] + + # First: a genuinely visible vertical stroke between otherwise unconnected + # adjacent nodes. The gap must be clear of any intervening node. + for source in graph.nodes: + if source.type != "input" or outgoing[source.id]: + continue + sx, sy, sw, sh = source.bbox.to_list() + source_cx = sx + sw / 2 + candidates = [] + for target in graph.nodes: + if target.type != "decision" or incoming[target.id]: + continue + tx, ty, tw, th = target.bbox.to_list() + gap = ty - (sy + sh) + if gap <= 0 or gap > max(220, int(0.9 * max(sh, th))): + continue + if abs(source_cx - (tx + tw / 2)) > 0.18 * min(sw, tw): + continue + if any(other.id not in {source.id, target.id} and + other.bbox.y < ty and other.bbox.y + other.bbox.height > sy + sh and + abs(other.bbox.center[0] - source_cx) < max(sw, tw) * 0.35 + for other in graph.nodes): + continue + x0 = int(round((source_cx + tx + tw / 2) / 2)) + y0, y1 = sy + sh, ty + x0 = min(max(x0, 1), width - 2) + if y0 < 0 or y1 >= height or y1 <= y0: + continue + # Count pixels in a narrow corridor, tolerating antialiasing and gaps. + corridor = mask[max(0, y0):min(height, y1 + 1), max(0, x0 - 3):min(width, x0 + 4)] + row_hits = np.count_nonzero(corridor, axis=1) > 0 + coverage = float(np.count_nonzero(row_hits)) / max(1, len(row_hits)) + if coverage >= 0.55: + candidates.append((coverage, target)) + if len(candidates) == 1: + coverage, target = candidates[0] + tx, ty, tw, th = target.bbox.to_list() + start = (int(round(source_cx)), sy + sh) + finish = (int(round(tx + tw / 2)), ty) + edge = Edge(f"e{len(graph.edges) + 1}", source.id, target.id, + points=[start, finish]) + graph.edges.append(edge) + context.arrows.append(Arrow(edge.id, edge.points, finish, source_hint=source.id, target_hint=target.id)) + context.diagnose("warning", "INFERRED_VISIBLE_GAP_CONNECTION", + "A connector was recovered between aligned nodes because continuous connector pixels were visible in the gap.", + "Review the inferred connection.", [source.id, target.id]) + outgoing[source.id].append(edge); incoming[target.id].append(edge) + inferred_count += 1 + + # Second: a missing sibling branch into a downstream process/output node. + # This handles decisions whose branches lead to different kinds of shapes, + # not just two output nodes. The candidate must already have a path to End. + if len(ends) == 1: + end = ends[0] + for decision in (n for n in graph.nodes if n.type == "decision"): + branches = outgoing[decision.id] + if len(branches) != 1: + continue + traced_target = nodes.get(branches[0].target) + if traced_target is None or traced_target.type not in {"output", "process"}: + continue + if not reaches_end(traced_target.id, end.id): + continue + dx, dy, dw, dh = decision.bbox.to_list() + candidates = [] + for candidate in graph.nodes: + if candidate.id in {decision.id, traced_target.id, end.id}: + continue + if candidate.type not in {"process", "output"} or incoming[candidate.id]: + continue + cx, cy, cw, ch = candidate.bbox.to_list() + # Branch destinations usually leave the decision laterally or + # below it; reject remote shapes and anything above the decision. + if cy < dy + 0.25 * dh or cy > dy + dh + 1.6 * max(dh, ch): + continue + horizontal_gap = max(0, cx - (dx + dw), dx - (cx + cw)) + if horizontal_gap > 1.1 * max(dw, cw): + continue + if abs((cx + cw / 2) - (dx + dw / 2)) > 1.5 * max(dw, cw): + continue + if not reaches_end(candidate.id, end.id): + continue + candidates.append(candidate) + if len(candidates) != 1: + continue + target = candidates[0] + # There should be exactly one missing branch destination, not an + # arbitrary isolated node elsewhere in the diagram. + sx, sy, sw, sh = decision.bbox.to_list() + tx, ty, tw, th = target.bbox.to_list() + if tx + tw / 2 >= sx + sw / 2: + start = (sx + sw, sy + sh // 2) + route_x = min(width - 3, max(sx + sw + 18, tx + tw // 2)) + else: + start = (sx, sy + sh // 2) + route_x = max(2, min(sx - 18, tx + tw // 2)) + finish = (int(round(tx + tw / 2)), ty) + route = [start, (route_x, start[1]), (route_x, max(start[1] + 1, ty - 18)), finish] + edge = Edge(f"e{len(graph.edges) + 1}", decision.id, target.id, points=route) + graph.edges.append(edge) + context.arrows.append(Arrow(edge.id, route, finish, source_hint=decision.id, target_hint=target.id)) + context.diagnose("warning", "INFERRED_DECISION_BRANCH", + "A missing decision branch was inferred because the other branch is traced to End and this is the only plausible unconnected process/output destination.", + "Review the inferred branch and its Yes/No label.", [decision.id, target.id]) + outgoing[decision.id].append(edge); incoming[target.id].append(edge) + inferred_count += 1 + return inferred_count + + class GraphService: name = "graph" @@ -146,16 +435,12 @@ def run(self, context: PipelineContext) -> PipelineContext: if mask is None: context.diagnose("error", "MISSING_CONNECTORS", "No connector geometry is available.", "Run vision before graph construction.") return context - # Diagram editors often leave a deliberate gap around YES/NO text at - # an elbow. Apply this only to solid-color diagrams; outlined inputs - # retain the stricter original connector evidence. - page = context.page_image - if page is not None: - hsv = cv2.cvtColor(page, cv2.COLOR_BGR2HSV) - if float(np.mean(hsv[:, :, 1] > 25)) > .02: - horizontal = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, np.ones((1, 81), np.uint8)) - vertical = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, np.ones((81, 1), np.uint8)) - mask = cv2.max(horizontal, vertical) + # VisionService already performs a 3x3 close. Do not dilate/close again + # here: on diagrams with tight spacing this can join a connector to a + # neighboring node outline or to a second branch, producing a fabricated + # path that follows unrelated borders. Keep connected-component topology + # as close to the observed pixels as possible. + mask = bridge_aligned_connector_gaps(mask, graph.nodes) count, labels, stats, _ = cv2.connectedComponentsWithStats(mask, connectivity=8) components = sorted(range(1, count), key=lambda index: (int(stats[index, cv2.CC_STAT_TOP]), int(stats[index, cv2.CC_STAT_LEFT]))) candidates = [] @@ -165,30 +450,151 @@ def run(self, context: PipelineContext) -> PipelineContext: x, y, width, height = stats[index, :4] ys, xs = np.where(labels[y:y + height, x:x + width] == index) points = np.column_stack((xs + x, ys + y)) - ports = contacts(points, graph.nodes, mask.shape, context.settings.ARROW_ATTACH_DISTANCE) + # Vision removes a narrow safety band around node outlines so + # borders cannot masquerade as arrows. Compensate with a modest + # image-scaled attachment radius, bounded by the configured minimum. + attach_distance = max( + context.settings.ARROW_ATTACH_DISTANCE, + int(round(mask.shape[1] * 0.018)), + ) + ports = contacts(points, graph.nodes, mask.shape, attach_distance) ids = list(dict.fromkeys(port.node.id for port in ports)) + sources, targets = [port for port in ports if not port.head], [port for port in ports if port.head] + + # Arrowheads that terminate at a node boundary can be partly erased + # when VisionService removes the node fill. Use strong terminal + # semantics as a constrained fallback only when this component + # touches exactly two distinct nodes: Start is an origin and End is + # a destination. This recovers curved incoming paths without using + # general reading-order guesses, and cannot merge a component that + # touches three or more nodes. + node_ports = defaultdict(list) + for port in ports: + node_ports[port.node.id].append(port) + distinct_nodes = list(node_ports) + anchored_pair = None + if len(distinct_nodes) == 2: + start_nodes = [node for node in graph.nodes + if node.id in node_ports and node.type == "terminal" + and node.text.strip().casefold() == "start"] + end_nodes = [node for node in graph.nodes + if node.id in node_ports and node.type == "terminal" + and node.text.strip().casefold() == "end"] + if len(start_nodes) == 1: + start_node = start_nodes[0] + other = next(node for node in graph.nodes if node.id in node_ports and node.id != start_node.id) + anchored_pair = (node_ports[start_node.id][0], node_ports[other.id][0]) + elif len(end_nodes) == 1: + end_node = end_nodes[0] + other = next(node for node in graph.nodes if node.id in node_ports and node.id != end_node.id) + anchored_pair = (node_ports[other.id][0], node_ports[end_node.id][0]) + if anchored_pair is not None: + source, target = anchored_pair + path = stroke_path(points, source.point, target.point) + if path: + if not source.head or target.head is False: + context.diagnose( + "warning", "INFERRED_TERMINAL_DIRECTION", + "Connector direction was inferred from a Start/End terminal because its arrowhead was partly obscured.", + "Confirm this connection during review.", + [source.node.id, target.node.id], + ) + candidates.append((source, target, path)) + else: + context.diagnose("error", "DANGLING_ARROW", "A terminal-anchored connector has no continuous pixel path.", "Reconnect the arrow in the source diagram.", [source.node.id, target.node.id]) + continue + if len(ports) < 2: - context.diagnose("error", "DANGLING_ARROW", "A connector does not reach two shape boundaries.", "Attach each arrow to its source and destination; remove stray lines.", ids) + context.diagnose("warning", "DANGLING_ARROW", "A connector fragment does not reach two shape boundaries.", "Attach each arrow to its source and destination; remove stray lines.", ids) continue - sources, targets = [port for port in ports if not port.head], [port for port in ports if port.head] + + # Conservative semantic fallback for common node-role transitions + # when a small arrowhead was lost at a filled-shape boundary. This + # does not use page reading order: it is allowed only for a single + # physical connector with exactly two contacts and a unique role + # transition (input -> decision, or decision -> output). + if not targets and len(ports) == 2: + first, second = ports + role_pair = {first.node.type, second.node.type} + inferred = None + if role_pair == {"input", "decision"}: + source = first if first.node.type == "input" else second + target = first if first.node.type == "decision" else second + inferred = (source, target) + elif role_pair == {"decision", "output"}: + source = first if first.node.type == "decision" else second + target = first if first.node.type == "output" else second + inferred = (source, target) + if inferred is not None: + source, target = inferred + path = stroke_path(points, source.point, target.point) + if path: + context.diagnose( + "warning", "INFERRED_ARROW_DIRECTION", + "Arrow direction was inferred from a clear input/decision/output role transition because the arrowhead was not legible.", + "Confirm this connection during review.", [source.node.id, target.node.id], + ) + candidates.append((source, target, path)) + continue + if not targets: context.diagnose("error", "AMBIGUOUS_ARROW_DIRECTION", "A connector has no reliably visible arrowhead.", "Use a larger, visible V-shaped or filled triangular arrowhead. Direction is never inferred from layout.", ids) continue - if not sources or (len(sources) > 1 and len(targets) > 1): - context.diagnose("error", "AMBIGUOUS_CONNECTOR", "A crossing or multi-way connector cannot be resolved safely.", "Separate crossing lines and use labeled connector circles for distant paths.", ids) + if not sources: + context.diagnose("error", "AMBIGUOUS_CONNECTOR", "A connector has arrowheads but no reliable source boundary.", "Check that each arrow starts on a shape boundary.", ids) continue - for source in sources: - for target in targets: - path = stroke_path(points, source.point, target.point) - if not path: - context.diagnose("error", "DANGLING_ARROW", "A connector path is interrupted.", "Reconnect the line in the source diagram.", [source.node.id, target.node.id]) + + # Two curved branches can touch the same terminal boundary and be + # reported as one connected component. Pair multiple sources and + # arrowheads by the actual pixel route, not reading order or layout. + # This is intentionally limited to balanced multi-port components; + # unbalanced junctions remain ambiguous rather than inventing edges. + pairs_to_trace = [] + if len(sources) > 1 and len(targets) > 1: + routes = [] + for source in sources: + for target in targets: + route = stroke_path(points, source.point, target.point) + if route: + length = sum(math.dist(a, b) for a, b in zip(route, route[1:])) + routes.append((length, source, target, route)) + used_sources, used_targets = set(), set() + for _, source, target, route in sorted(routes, key=lambda item: item[0]): + source_key = (source.node.id, source.point) + target_key = (target.node.id, target.point) + if source_key in used_sources or target_key in used_targets: continue - candidates.append((source, target, path)) + used_sources.add(source_key); used_targets.add(target_key) + pairs_to_trace.append((source, target, route)) + if len(pairs_to_trace) != min(len(sources), len(targets)): + context.diagnose("error", "AMBIGUOUS_CONNECTOR", "A multi-branch connector could not be separated into complete paths.", "Separate overlapping paths or increase the gap between the arrows.", ids) + continue + elif len(sources) == 1: + pairs_to_trace = [(sources[0], target, stroke_path(points, sources[0].point, target.point)) for target in targets] + elif len(targets) == 1: + # A shared arrowhead is not enough evidence to determine which + # of several incoming strokes is the real source. + context.diagnose("error", "AMBIGUOUS_CONNECTOR", "Several source boundaries share one arrowhead.", "Separate the connector paths so each arrow has one source and one target.", ids) + continue + else: + context.diagnose("error", "AMBIGUOUS_CONNECTOR", "A crossing or multi-way connector cannot be resolved safely.", "Separate crossing lines and use labeled connector circles for distant paths.", ids) + continue + + for source, target, path in pairs_to_trace: + if not path: + context.diagnose("error", "DANGLING_ARROW", "A connector path is interrupted.", "Reconnect the line in the source diagram.", [source.node.id, target.node.id]) + continue + candidates.append((source, target, path)) candidates.sort(key=lambda item: (min(point[1] for point in item[2]), min(point[0] for point in item[2]), item[0].node.id, item[1].node.id)) for index, (source, target, path) in enumerate(candidates, 1): edge = Edge(f"e{index}", source.node.id, target.node.id, points=path) graph.edges.append(edge) context.arrows.append(Arrow(edge.id, path, target.point, source_hint=edge.source, target_hint=edge.target)) + # Be forgiving of a single likely omitted/faint branch-to-End connector, + # but only when the decision's sibling output already establishes the + # intended convergence. General reading-order edge guessing remains off. + infer_obvious_missing_branch_to_end(context, graph) + infer_high_confidence_missing_edges(context, graph) for word in context.edge_words: if not any(character.isalnum() for character in word.text): continue @@ -207,6 +613,119 @@ def run(self, context: PipelineContext) -> PipelineContext: edge.label = label if word.confidence * 100 < context.settings.OCR_MIN_CONFIDENCE: context.diagnose("warning", "LOW_OCR_CONFIDENCE", "An arrow label may have been misread.", "Verify the label or export larger text.", [edge.id]) + # When branch-label OCR is missing, infer Yes/No only for the common, + # unambiguous left/right split of a decision. Keep this explicit as a + # warning so the review step can confirm or change the labels. + for node in graph.nodes: + if node.type != "decision": + continue + outgoing_edges = [edge for edge in graph.edges if edge.source == node.id] + if len(outgoing_edges) != 2 or any(edge.label for edge in outgoing_edges): + continue + center_x = node.bbox.center[0] + target_nodes = {item.id: item for item in graph.nodes} + positions = [(edge, target_nodes[edge.target].bbox.center[0]) for edge in outgoing_edges + if edge.target in target_nodes] + # A target is a left/right branch only when its horizontal + # displacement dominates its vertical displacement. Otherwise a + # lower node slightly offset from the diamond center can be + # misclassified as the left branch of a vertical/sideways split. + left = [edge for edge, x in positions + if x < center_x - 10 and + abs(x - center_x) > abs(target_nodes[edge.target].bbox.center[1] - node.bbox.center[1])] + right = [edge for edge, x in positions + if x > center_x + 10 and + abs(x - center_x) > abs(target_nodes[edge.target].bbox.center[1] - node.bbox.center[1])] + if len(left) == 1 and len(right) == 1: + left[0].label, right[0].label = "Yes", "No" + context.diagnose( + "warning", "INFERRED_BRANCH_LABELS", + "Yes/No labels were inferred from a clear left/right decision split because label OCR was unavailable.", + "Confirm the inferred Yes/No labels during review.", + [node.id, left[0].id, right[0].id], + ) + elif len(positions) == 2: + # Another common layout has one branch continuing vertically + # and the other leaving sideways. Keep this inference explicit + # and warning-tagged rather than presenting it as OCR evidence. + vertical = [edge for edge, x in positions + if abs(target_nodes[edge.target].bbox.center[1] - node.bbox.center[1]) > + abs(target_nodes[edge.target].bbox.center[0] - center_x)] + horizontal = [edge for edge, x in positions if edge not in vertical] + if len(vertical) == len(horizontal) == 1: + vertical[0].label, horizontal[0].label = "True", "False" + context.diagnose( + "warning", "INFERRED_BRANCH_LABELS", + "True/False labels were inferred from a clear vertical-versus-sideways decision split because label OCR was unavailable.", + "Confirm the inferred branch labels during review.", + [node.id, vertical[0].id, horizontal[0].id], + ) + + # Some diagrams route both branches downward after leaving opposite + # sides of a diamond. Target-centre geometry alone cannot distinguish + # them because both destinations are below the decision. Use the + # actual connector departure points as a second, warning-tagged cue. + # Explicit OCR labels always take priority; inference requires exactly + # two unlabeled branches, opposite-side departures, and downstream targets. + if len(outgoing_edges) == 2 and not any(edge.label for edge in outgoing_edges): + center_x, center_y = node.bbox.center + side_edges = {"left": [], "right": []} + target_nodes = {item.id: item for item in graph.nodes} + for edge in outgoing_edges: + target = target_nodes.get(edge.target) + if not target or not edge.points: + continue + # Paths are source-to-target ordered, so the first point is + # the connector's departure at the decision boundary. + sx, sy = edge.points[0] + dx = sx - center_x + if target.bbox.center[1] <= center_y or abs(dx) < max(12, node.bbox.width * 0.22): + continue + side_edges["left" if dx < 0 else "right"].append(edge) + if len(side_edges["left"]) == len(side_edges["right"]) == 1: + left_edge = side_edges["left"][0] + right_edge = side_edges["right"][0] + left_edge.label, right_edge.label = "Yes", "No" + context.diagnose( + "warning", "INFERRED_BRANCH_LABELS", + "Yes/No labels were inferred from connector departure sides because label OCR was unavailable and both branches continue downward.", + "Confirm the inferred Yes/No labels during review.", + [node.id, left_edge.id, right_edge.id], + ) + + # A connected-component pass can report an ambiguous junction before + # the constrained recovery above reconstructs its individual edges. Do + # not let that stale error block validation when the graph now contains + # the incoming edge and both branches of the same decision. Keep a + # warning for review; genuinely unresolved components remain errors. + remaining_diagnostics = [] + for diagnostic in context.diagnostics: + if diagnostic.code != "AMBIGUOUS_CONNECTOR" or len(diagnostic.element_ids) < 3: + remaining_diagnostics.append(diagnostic) + continue + mentioned = set(diagnostic.element_ids) + decisions = [node for node in graph.nodes + if node.id in mentioned and node.type in ("decision", "iteration")] + resolved = False + for decision in decisions: + incoming_from_component = [edge for edge in graph.edges + if edge.target == decision.id and edge.source in mentioned] + outgoing = [edge for edge in graph.edges if edge.source == decision.id] + branch_targets_in_component = [edge for edge in outgoing if edge.target in mentioned] + if incoming_from_component and len(outgoing) == 2 and branch_targets_in_component: + resolved = True + break + if resolved: + context.diagnose( + "warning", "RESOLVED_CONNECTOR_AMBIGUITY", + "A connector junction initially looked ambiguous, but the recovered graph now contains the incoming connection and both decision branches.", + "Review the reconstructed paths; no source diagram change is needed if they match the arrows.", + diagnostic.element_ids, + ) + else: + remaining_diagnostics.append(diagnostic) + context.diagnostics = remaining_diagnostics + # Circle pairs bridge an incoming physical arrow to an outgoing physical arrow. pairs = defaultdict(list) for node in graph.nodes: diff --git a/backend/services/programming_ocr_validation.py b/backend/services/programming_ocr_validation.py new file mode 100644 index 0000000..939dab2 --- /dev/null +++ b/backend/services/programming_ocr_validation.py @@ -0,0 +1,106 @@ +"""Conservative, programming-aware OCR ambiguity detection. + +This module proposes alternatives for human review only. It never edits Node.text. +Python syntax is one weak ranking signal, not evidence that a candidate is intended. +""" +from __future__ import annotations +import ast +import re +from typing import Any + +_CONFUSIONS = ( + (re.compile(r"(?])=(?!=)"), "==", "single '=' may be a comparison '=='"), + (re.compile(r"=="), "=", "'==' may have been read as assignment '='"), + (re.compile(r"%"), "0", "'%' may be confused with '0'"), + (re.compile(r"(? float: + """Weak tie-breaker only; intentionally cannot determine intended meaning.""" + expression = text.strip() + if node_type == "decision": + expression = re.sub(r"^if\s+", "", expression, flags=re.I).rstrip(": ") + mode = "eval" + elif node_type == "iteration" and expression.upper().startswith("WHILE "): + expression, mode = expression.split(None, 1)[1], "eval" + elif node_type in ("process", "output"): + if node_type == "output": + expression = expression.split(None, 1)[1] if " " in expression else "" + mode = "eval" + else: + mode = "exec" + else: + return 0.0 + try: + ast.parse(expression, mode=mode) + return 0.08 + except (SyntaxError, ValueError, RecursionError): + return 0.0 + + +def propose_ambiguities(text: str, node_type: str, existing: list[dict[str, Any]] | None = None) -> list[dict[str, Any]]: + """Return deduplicated, ranked alternatives while retaining the original reading.""" + existing = existing or [] + proposals: dict[str, dict[str, Any]] = {} + for candidate in existing: + value = candidate.get("text") if isinstance(candidate, dict) else None + if isinstance(value, str) and value.strip() and value.strip() != text.strip(): + value = value.strip() + proposals[value] = {"text": value, "reason": "alternative OCR engine/preprocessing reading", + "score": float(candidate.get("score", 0.0)), + "confidence": float(candidate.get("confidence", 0.0)), + "syntax_support": _syntax_support(value, node_type)} + for pattern, replacement, reason in _CONFUSIONS: + match = pattern.search(text) + if not match: + continue + alternative = text[:match.start()] + replacement + text[match.end():] + if alternative.strip() == text.strip() or alternative in proposals: + continue + proposals[alternative] = {"text": alternative, "reason": reason, "score": 0.0, + "confidence": 0.0, "syntax_support": _syntax_support(alternative, node_type)} + # Syntax is deliberately a tiny tie-breaker and never auto-selects a reading. + return sorted(proposals.values(), key=lambda item: (item["score"] + item["syntax_support"], item["confidence"]), reverse=True)[:8] + + +class ProgrammingOCRValidationService: + name = "programming_ocr_validation" + + def run(self, context): + graph = context.graph + if graph is None: + return context + threshold = min(0.92, max(0.0, float(context.settings.OCR_MIN_CONFIDENCE))) + for node in graph.nodes: + # A user-reviewed reading is authoritative for this analysis. Keep the + # original and suggestions attached for audit, but do not re-flag them. + if "USER_CORRECTED" in node.flags: + continue + if node.type not in ("process", "input", "output", "decision", "iteration"): + continue + alternatives = propose_ambiguities(node.text, node.type, node.ocr_candidates) + if not alternatives: + continue + # Existing candidate diversity is evidence of ambiguity. For synthesized + # alternatives, only flag when OCR confidence is not comfortably high. + has_engine_disagreement = any(item.get("reason") == "alternative OCR engine/preprocessing reading" for item in alternatives) + has_character_confusion = any(item.get("reason") != "alternative OCR engine/preprocessing reading" for item in alternatives) + suspicious = has_engine_disagreement or has_character_confusion or node.confidence < threshold + if not suspicious: + continue + node.ocr_candidates = alternatives + if "PROGRAMMING_OCR_AMBIGUITY" not in node.flags: + node.flags.append("PROGRAMMING_OCR_AMBIGUITY") + context.diagnose( + "warning", "PROGRAMMING_OCR_AMBIGUITY", + f"{node.id}: OCR may have confused programming symbols or characters; the original reading was preserved.", + "Review the original flowchart image and select the intended expression. Alternatives are suggestions, not automatic corrections.", + [node.id], + ) + return context diff --git a/backend/services/validation_service.py b/backend/services/validation_service.py index 78b901a..c098ffe 100644 --- a/backend/services/validation_service.py +++ b/backend/services/validation_service.py @@ -3,15 +3,85 @@ import networkx as nx from backend.models import PipelineContext from backend.notation import NotationError, normalize_label, validate_node_text +from backend.services.programming_ocr_validation import ProgrammingOCRValidationService + +def _reconcile_decision_labels(context: PipelineContext) -> None: + """Canonicalize OCR labels and recover only strongly supported missing pairs. + + This runs immediately before validation as a last, conservative normalization + layer. It does not replace explicit Yes/No labels. If OCR captured one branch + label but missed the other, the missing counterpart is inferred only when the + two connector paths visibly depart from opposite sides of the same decision + and both lead downward to recognized nodes. + """ + graph = context.graph + if graph is None: + return + nodes = {node.id: node for node in graph.nodes} + for decision in graph.nodes: + if decision.type not in ("decision", "iteration"): + continue + branches = [edge for edge in graph.edges if edge.source == decision.id] + if len(branches) != 2: + continue + + # Normalize punctuation/case from OCR, e.g. "Yes." and "No,". + for edge in branches: + canonical = normalize_label(edge.label) + if canonical: + edge.label = canonical + + labels = [normalize_label(edge.label) for edge in branches] + if sorted(label or "" for label in labels) == ["No", "Yes"]: + continue + + # Only infer an omitted label, never overwrite two explicit conflicting + # labels or silently reinterpret arbitrary branch text. + missing = [i for i, edge in enumerate(branches) if not (edge.label or "").strip()] + known = [i for i, label in enumerate(labels) if label in ("Yes", "No")] + if len(missing) != 1 or len(known) != 1: + if any((edge.label or "").strip() for edge in branches): + continue + + center_x, center_y = decision.bbox.center + departures = {} + for i, edge in enumerate(branches): + target = nodes.get(edge.target) + if target is None or not edge.points: + continue + sx, sy = edge.points[0] + dx = sx - center_x + if target.bbox.center[1] > center_y and abs(dx) >= max(12, decision.bbox.width * 0.22): + departures["left" if dx < 0 else "right"] = i + + if set(departures) != {"left", "right"}: + continue + + if len(missing) == 1 and len(known) == 1: + missing_index = missing[0] + known_label = labels[known[0]] + branches[missing_index].label = "No" if known_label == "Yes" else "Yes" + else: + branches[departures["left"]].label = "Yes" + branches[departures["right"]].label = "No" + context.diagnose( + "warning", "INFERRED_BRANCH_LABELS", + "A missing decision label was inferred from opposite-side connector departures; confirm it during review.", + "Verify the Yes/No labels during review.", + [decision.id] + [edge.id for edge in branches], + ) + class ValidationService: name = "validation" def run(self, context: PipelineContext) -> PipelineContext: + ProgrammingOCRValidationService().run(context) graph = context.graph if graph is None: context.diagnose("error", "MISSING_GRAPH", "No graph is available to validate.", "Run graph construction before validation.") return context + _reconcile_decision_labels(context) nodes = {node.id: node for node in graph.nodes} directed = nx.DiGraph() directed.add_nodes_from(nodes) diff --git a/backend/services/vision_service.py b/backend/services/vision_service.py index fe78d7e..14a35ce 100644 --- a/backend/services/vision_service.py +++ b/backend/services/vision_service.py @@ -2,6 +2,8 @@ from __future__ import annotations from collections import OrderedDict from threading import Lock +import ast +import difflib import math import re @@ -31,6 +33,13 @@ def shape_contours(binary: np.ndarray, grayscale: np.ndarray | None = None, colo x, y, width, height = cv2.boundingRect(contour) if area < max(160, page_area * .00004) or min(width, height) < 30: continue + # Long, narrow enclosed regions are commonly arrow shafts/arrowheads, + # not flowchart nodes. They otherwise become empty OCR "connector" nodes. + # Only reject when the short side is also small: wide boxes with room + # for a text label (e.g. 360x100) are legitimate process/terminal nodes. + aspect = max(width, height) / max(1.0, min(width, height)) + if aspect > 3.2 and min(width, height) < 60: + continue if area > page_area * .85 or area / (width * height) < .38: continue hull_area = cv2.contourArea(cv2.convexHull(contour)) @@ -61,44 +70,163 @@ def shape_contours(binary: np.ndarray, grayscale: np.ndarray | None = None, colo candidates=[] for contour in contours: area=cv2.contourArea(contour); x,y,width,height=cv2.boundingRect(contour) - if area < max(300, page_area*.00008) or min(width,height)<35 or area/(width*height)<.42 or area > page_area*.4: + short_side, long_side = min(width, height), max(width, height) + aspect = long_side / max(1.0, short_side) + # The fill-based fallback can pick up arrow shafts and arrowheads because + # they share the same gray/colored pixels as node fills. Real flowchart + # nodes have meaningful two-dimensional extent; reject thin components + # here as well as in the outlined-contour pass. + if (area < max(300, page_area*.0008) or short_side < 35 + or area/(width*height)<.30 or area > page_area*.4 + or (aspect > 2.35 and short_side < 36)): continue candidates.append(contour) + # A filled node often contains many contours from the white gaps inside + # glyphs. Point-in-polygon containment is therefore not a valid duplicate + # test here: it treats every text hole as if it were the filled node itself + # and can suppress the node contour entirely. Merge only near-identical + # bounding boxes, then remove small enclosed contours once the enclosing + # fill has been established. + def bbox_iou(first: np.ndarray, second: np.ndarray) -> float: + ax, ay, aw, ah = cv2.boundingRect(first) + bx, by, bw, bh = cv2.boundingRect(second) + ix, iy = max(ax, bx), max(ay, by) + right, bottom = min(ax + aw, bx + bw), min(ay + ah, by + bh) + intersection = max(0, right - ix) * max(0, bottom - iy) + union = aw * ah + bw * bh - intersection + return intersection / max(1, union) + + merged_fills = [] for contour in candidates: - point=tuple(float(value) for value in contour[0,0]) - if not any(cv2.pointPolygonTest(existing, point, False) >= 0 or cv2.pointPolygonTest(contour, tuple(float(v) for v in existing[0,0]), False) >= 0 for existing in retained): - retained.append(contour) + duplicate = next((existing for existing in retained + merged_fills + if bbox_iou(existing, contour) >= .68), None) + if duplicate is None: + merged_fills.append(contour) + + # Filled regions supersede the small white glyph holes found by the + # threshold-contour pass, but do not supersede a similarly-sized outlined + # node. This is geometry-based and works for any label or node type. + retained = [existing for existing in retained + if not any( + cv2.contourArea(fill) > max(1.0, cv2.contourArea(existing)) * 2.0 + and bbox_iou(fill, existing) < .68 + and cv2.pointPolygonTest(fill, tuple(float(v) for v in cv2.boundingRect(existing)[:2]), False) >= 0 + and (cv2.boundingRect(existing)[2] * cv2.boundingRect(existing)[3]) + < .45 * (cv2.boundingRect(fill)[2] * cv2.boundingRect(fill)[3]) + for fill in merged_fills + )] + retained.extend(merged_fills) return sorted(retained, key=lambda contour:(cv2.boundingRect(contour)[1],cv2.boundingRect(contour)[0],cv2.boundingRect(contour)[2])) def classify_shape(contour: np.ndarray, page_width: int) -> str: + """Classify a contour from several geometric cues; return unknown on weak evidence. + + Polygon approximation is evaluated at two scales because antialiasing and + low-resolution edges can change the apparent vertex count. No contour is + forced into a known class when the available geometric evidence conflicts. + """ + if contour is None or len(contour) < 5: + return "unknown" x, y, width, height = cv2.boundingRect(contour) - perimeter = cv2.arcLength(contour, True) - polygon = cv2.approxPolyDP(contour, .025 * perimeter, True).reshape(-1, 2) - area = cv2.contourArea(contour) - circularity = 4 * math.pi * area / max(1, perimeter * perimeter) - if .72 < width / height < 1.35 and max(width, height) < page_width * .12 and circularity > .76: + if width < 2 or height < 2: + return "unknown" + perimeter = float(cv2.arcLength(contour, True)) + area = float(cv2.contourArea(contour)) + if perimeter <= 0 or area <= 0: + return "unknown" + box_area = float(width * height) + fill = area / box_area + hull_area = float(cv2.contourArea(cv2.convexHull(contour))) + solidity = area / hull_area if hull_area > 0 else 0.0 + circularity = 4.0 * math.pi * area / (perimeter * perimeter) + aspect = width / max(1.0, float(height)) + polygon = cv2.approxPolyDP(contour, .04 * perimeter, True).reshape(-1, 2) + fine = cv2.approxPolyDP(contour, .008 * perimeter, True).reshape(-1, 2) + + def corner_angles(points: np.ndarray) -> list[float]: + angles = [] + for i in range(len(points)): + prev = points[(i - 1) % len(points)].astype(float) - points[i].astype(float) + nxt = points[(i + 1) % len(points)].astype(float) - points[i].astype(float) + denom = float(np.linalg.norm(prev) * np.linalg.norm(nxt)) + if denom > 1e-6: + angles.append(math.degrees(math.acos(float(np.clip(np.dot(prev, nxt) / denom, -1, 1))))) + return angles + + angles = corner_angles(polygon) if len(polygon) >= 3 else [] + right_angle_ratio = (sum(80 <= angle <= 100 for angle in angles) / len(angles)) if angles else 0.0 + approx_vertices = len(polygon) + + # Circular flow connectors: use circularity, near-square bounds and solidity + # together so small rounded rectangles are not automatically called circles. + if (0.78 <= aspect <= 1.28 and max(width, height) <= max(42, page_width * .16) + and circularity >= .72 and solidity >= .90 and fill >= .62): return "connector" - fine = cv2.approxPolyDP(contour, .01 * perimeter, True) - if len(fine) > 4 and area / (width * height) > .95: - return "terminal" - if len(polygon) == 4: - # A diamond's corners are side midpoints, not bounding-box corners. - nx = (polygon[:, 0] - x) / width - ny = (polygon[:, 1] - y) / height - if sum(.25 < a < .75 or .25 < b < .75 for a, b in zip(nx, ny)) == 4 and area / (width * height) < .7: + + # Rotated rectangles may acquire a fifth vertex from raster stair-stepping. + # A minimum-area rectangle gives a rotation-invariant right-angle/occupancy cue. + min_rect = cv2.minAreaRect(contour) + rect_area = float(min_rect[1][0] * min_rect[1][1]) + rect_occupancy = area / rect_area if rect_area > 0 else 0.0 + if len(polygon) in (4, 5) and rect_occupancy >= .90 and solidity >= .96 and right_angle_ratio >= .75: + rect_points = cv2.boxPoints(min_rect) + rect_aspect = max(min_rect[1]) / max(1.0, min(min_rect[1])) + if rect_aspect >= 1.25: + return "process" + + # Four-corner shapes are distinguished by normalized corner placement, angles, + # and opposite-edge displacement; bbox aspect alone is rotation-sensitive. + if approx_vertices == 4: + points = polygon.astype(float) + cx, cy = x + width / 2.0, y + height / 2.0 + normalized = np.column_stack(((points[:, 0] - x) / width, (points[:, 1] - y) / height)) + side_midpoints = sum(min(abs(px), abs(1 - px), abs(py), abs(1 - py)) > .16 for px, py in normalized) + diamond_corners = sum(min(abs(px - .5), abs(py - .5)) < .20 for px, py in normalized) + # A diamond has vertices close to the four side midpoints and acute/obtuse + # alternating angles. The tests remain tolerant of slight rotation/skew. + diagonal_balance = abs((max(points[:, 0]) - min(points[:, 0])) / max(1, width) - 1) < .15 + diamond_score = sum(.22 <= px <= .78 or .22 <= py <= .78 for px, py in normalized) + if (diamond_corners >= 3 and diamond_score >= 4 and fill <= .82 + and (right_angle_ratio < .75 or fill < .62)): return "decision" - points = sorted(polygon.tolist(), key=lambda point: (point[1], point[0])) - top, bottom = sorted(points[:2]), sorted(points[2:]) - side_shift = (abs(top[0][0] - bottom[0][0]) + abs(top[1][0] - bottom[1][0])) / (2 * width) - return "data" if side_shift > .065 else "process" - if len(polygon) == 6: - # ISO preparation/iteration hexagon has pointed left/right, flat top/bottom. - horizontal = sum(abs(int(polygon[(i + 1) % 6, 1]) - int(polygon[i, 1])) < height * .1 for i in range(6)) - if horizontal >= 2 and area / (width * height) < .95: - return "iteration" - if len(fine) > 4 and .60 < area / (width * height) < .99: + + # Parallelogram: top and bottom edges are displaced in the same direction. + ordered = sorted(points.tolist(), key=lambda pt: (pt[1], pt[0])) + top, bottom = sorted(ordered[:2]), sorted(ordered[2:]) + shift = (abs(top[0][0] - bottom[0][0]) + abs(top[1][0] - bottom[1][0])) / (2 * max(1, width)) + if (right_angle_ratio < .65 and fill >= .48 and solidity >= .88 + and min(width, height) >= 18): + # Parallelogram corners are consistently oblique; a rotated rectangle + # retains right angles regardless of its axis-aligned bounding box. + return "data" + if shift >= .055 and right_angle_ratio < .9 and solidity >= .88: + return "data" + if right_angle_ratio >= .65 and fill >= .55 and solidity >= .88: + return "process" + # Rotated rectangles can have acute angles in the image coordinate system; + # opposite edge parallelism and high solidity still support process. + if fill >= .55 and solidity >= .94 and right_angle_ratio < .65 and shift < .055: + return "process" + + # Terminals are typically capsules/rounded rectangles. Require a broad + # rounded contour or very high fill with a curved outline; do not infer it + # merely from an unstable high-resolution vertex count. + curved_outline = len(fine) >= 7 and len(polygon) >= 5 + if (curved_outline and solidity >= .88 and .60 <= fill <= 1.02 + and .28 <= aspect <= 4.5 and circularity >= .28): return "terminal" + if (len(fine) >= 8 and solidity >= .92 and .72 <= fill <= 1.0 + and .35 <= aspect <= 2.8 and circularity >= .48): + return "terminal" + + # Standard preparation/iteration hexagon: six vertices, high solidity and + # approximately horizontal top/bottom edges. + if approx_vertices == 6 and solidity >= .88 and fill >= .45: + horizontal_edges = sum(abs(int(polygon[(i + 1) % 6, 1]) - int(polygon[i, 1])) < height * .16 for i in range(6)) + if horizontal_edges >= 2: + return "iteration" + return "unknown" @@ -121,23 +249,281 @@ def read_words(image: np.ndarray, context: PipelineContext, psm: int, origin: tu return "\n".join(" ".join(line) for line in lines.values()), words -def read_best_words(image: np.ndarray, context: PipelineContext, origin: tuple[int, int] = (0, 0)) -> tuple[str, list[OCRWord]]: - """Try normal and adaptive contrast; colored fills often need local thresholding.""" - variants = [image] - if min(image.shape[:2]) >= 35: - variants.append(cv2.adaptiveThreshold(image, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, - cv2.THRESH_BINARY, 31, 8)) - _, otsu = cv2.threshold(image, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) - variants.extend((otsu, 255 - otsu)) - candidates=[] +def preprocess_ocr_candidates(image: np.ndarray, shape_type: str = "unknown") -> list[np.ndarray]: + """Create conservative, complementary OCR inputs; the original is always first.""" + if image is None or image.size == 0: + return [] + gray = image if image.ndim == 2 else cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) + # Scale small glyphs without changing their proportions. Cubic interpolation is + # gentler on punctuation than binary morphology or nearest-neighbour scaling. + min_dim = min(gray.shape[:2]) + scale = 3.0 if min_dim < 24 else 2.0 if min_dim < 48 else 1.5 if min_dim < 80 else 1.0 + if scale > 1: + gray = cv2.resize(gray, None, fx=scale, fy=scale, interpolation=cv2.INTER_CUBIC) + variants = [gray] + # Local contrast and mild denoising preserve thin strokes and decimal points. + clahe = cv2.createCLAHE(clipLimit=2.0 if shape_type == "decision" else 1.7, tileGridSize=(8, 8)).apply(gray) + variants.append(clahe) + denoised = cv2.bilateralFilter(clahe, 5, 30, 30) + variants.append(denoised) + # Avoid aggressive thresholding on small labels and diamonds, where punctuation + # and diagonal strokes are especially easy to erase. + if min(gray.shape[:2]) >= 24: + block = min(31, min(gray.shape[:2]) if min(gray.shape[:2]) % 2 else min(gray.shape[:2]) - 1) + if block >= 11: + adaptive = cv2.adaptiveThreshold(clahe, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, + cv2.THRESH_BINARY, block, 7 if shape_type == "connector" else 5) + variants.append(adaptive) + _, otsu = cv2.threshold(clahe, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) + variants.append(otsu) + # Inverted Otsu helps dark-filled shapes; include it only as a candidate. + if shape_type in {"decision", "data", "input", "output", "unknown"}: + variants.append(255 - otsu) + # De-duplicate exact images to avoid wasting Tesseract calls. + unique, seen = [], set() for variant in variants: - for psm in (6, 11): + key = (variant.shape, hash(variant.tobytes())) + if key not in seen: + seen.add(key); unique.append(variant) + return unique + + + +def infer_instruction_kind(shape_type: str, text: str) -> tuple[str, str]: + """Use unmistakable instruction verbs to refine rectangular-node semantics.""" + if shape_type in {"terminal", "decision", "iteration", "connector"}: + return shape_type, text + match = re.match(r"^(input|read|enter)\s+(.+)$", text.strip(), re.IGNORECASE) + if match: + return "input", "Input " + match.group(2).strip() + match = re.match(r"^(print|output|display|show)\s*:?\s+(.+)$", text.strip(), re.IGNORECASE) + if match: + payload = match.group(2).strip() + # If OCR drops only the final quote from a quoted output literal, restore + # the delimiter rather than passing a broken string into validation. + if payload[:1] in {"'", '"'} and payload.count(payload[0]) % 2: + payload += payload[0] + return "output", "Output " + payload + return shape_type, text + +def _normalize_comparison_spacing(text: str, shape_type: str) -> str: + """Repair whitespace-only OCR splits in comparisons without changing operators. + + For decision labels, Tesseract can split the two strokes of ``==`` into + separate tokens (for example ``if n % 2 = =0``). Joining that exact pattern + is a conservative syntax repair; single ``=`` is never converted by itself. + """ + if shape_type != "decision": + return text + normalized = re.sub(r"(?])=\s+=(?![=])", "==", text) + normalized = re.sub(r"\s*(==|!=|<=|>=)\s*", r" \1 ", normalized) + normalized = re.sub(r"(?=!])([<>])(?![=])", r" \1 ", normalized) + return " ".join(normalized.split()) + + +def _valid_decision_expression(text: str) -> bool: + expression = re.sub(r"^if\s+", "", text.strip(), flags=re.IGNORECASE).rstrip(": ") + try: + ast.parse(expression, mode="eval") + return True + except (SyntaxError, ValueError, RecursionError): + return False + + +def _candidate_score(text: str, words: list[OCRWord], shape_type: str = "unknown") -> float: + """Rank readings by confidence plus character integrity, not length alone.""" + cleaned = " ".join(text.split()) + if not cleaned: + return -100.0 + chars = [c for c in cleaned if not c.isspace()] + confidence = sum(w.confidence * max(1, len(w.text)) for w in words) / max(1, sum(max(1, len(w.text)) for w in words)) + printable = sum(c.isprintable() for c in chars) / max(1, len(chars)) + # Penalize common OCR debris but do not reject programming punctuation. + alnum = sum(c.isalnum() for c in chars) + symbols = sum(c in "= !%(),.'\"_+-*/<>:" for c in chars) + debris = sum(c in "|\\~`" for c in chars) + score = confidence * 5.0 + printable * 1.5 + min(alnum, 24) * .025 + min(symbols, 8) * .045 - debris * .18 + if shape_type == "connector" and len(cleaned) > 18: + score -= (len(cleaned) - 18) * .04 + if shape_type == "decision" and any(op in cleaned for op in ("==", "!=", "<=", ">=", "%")): + score += .15 + if shape_type in {"process", "output", "unknown"} and re.match(r"^print(?:\s|[:(])", cleaned, re.IGNORECASE): + score += .45 + # Prefer a candidate whose common words are already coherent over its + # near-miss spelling, but keep this bonus small relative to OCR evidence. + # A coherent repair of an otherwise recognizable output statement + # should beat the same-confidence OCR gibberish, but alternatives remain + # attached to the node for the review screen. + if _repair_common_ocr_words(cleaned) == cleaned: + score += .40 + return score + + +def _repair_common_ocr_words(text: str) -> str: + """Correct near-miss OCR tokens from a small flowchart vocabulary. + + Unknown words and identifiers are preserved; this is not general-purpose + autocorrect. Punctuation and capitalization are retained. + """ + vocabulary = ( + "print", "factorial", "is", "not", "defined", "for", "negative", "numbers", + "input", "number", "calculate", "start", "end", "if", "else", "while", + "return", "true", "false", "yes", "no", "display", "output", "read", + ) + # A low-resolution exclamation/bar is sometimes substituted for the final + # stroke in "not" (e.g. `no! defined`). Repair only this known phrase shape. + text = re.sub(r"\bno[!|](?=\s+J?efined\b)", "not", text, flags=re.IGNORECASE) + + def fix(match): + token = match.group(0) + bare = re.sub(r"^[^A-Za-z]+|[^A-Za-z]+$", "", token) + # A trailing apostrophe is a common OCR substitution for the final t + # in "not"; only repair this exact punctuation-shaped near miss. + if bare.casefold() == "no" and token.endswith(("'", "’")): + return token.replace(bare, "not").rstrip("'’") + if len(bare) < 3 or bare.casefold() in vocabulary or any(ch.isdigit() for ch in bare): + return token + if not (bare.islower() or bare.istitle() or bare.isupper()): + return token + matches = difflib.get_close_matches(bare.casefold(), vocabulary, n=1, cutoff=.78) + if not matches: + return token + replacement = matches[0] + if bare.isupper(): + replacement = replacement.upper() + return token.replace(bare, replacement) + return re.sub(r"[^\W_]+(?:['’][^\W_]*)?", fix, text, flags=re.UNICODE) + + +def _repair_ocr_text(text: str, shape_type: str) -> list[str]: + """Produce small, reviewable OCR repairs without silently rewriting meaning. + + Repairs are candidates, not unconditional substitutions. Syntax-aware scoring + below prefers a repaired decision only when it forms a valid expression. + """ + source = " ".join(text.split()) + results = [] + if shape_type == "decision": + # OCR commonly inserts a stray dot/colon after the decision keyword + # ("If . value > 0"). Remove only punctuation immediately following + # that keyword; punctuation inside the expression remains untouched. + cleaned = re.sub(r"^(\s*if)\s*[.:,;]+\s*", r"\1 ", source, flags=re.IGNORECASE) + spaced = _normalize_comparison_spacing(cleaned, shape_type) + if spaced != source: + results.append(spaced) + # Tesseract often separates a comparison operator from its operand. + compact = re.sub(r"(?<=[A-Za-z0-9_)])\s+(?=(?:==|!=|<=|>=|<|>))", " ", cleaned) + compact = re.sub(r"(==|!=|<=|>=|<|>)\s+(?=[0-9A-Za-z_(])", r"\1 ", compact) + if compact != source: + results.append(compact) + # In flowchart decision diamonds, a lone '=' between two expression + # operands is commonly used for equality in pseudocode and is also a + # frequent OCR loss of one stroke from '=='. Offer (never silently + # force) the Python-compatible equality form as a candidate. + if cleaned != source and not _valid_decision_expression(cleaned) and not re.search(r"[!<>]=|==", cleaned): + equality = re.sub(r"(?<=[A-Za-z0-9_)])\s*=\s*(?=[A-Za-z0-9_(])", " == ", cleaned, count=1) + equality = " ".join(equality.split()) + if equality != cleaned and _valid_decision_expression(equality): + results.append(equality) + # Common clipped first-letter errors in print statements are low-risk when + # the remainder is an exact known keyword; do not guess arbitrary words. + if shape_type in {"process", "output", "unknown"}: + repaired = re.sub(r"^rint(?=\s*\()", "print", source, flags=re.IGNORECASE) + repaired = re.sub(r"^rint(?=\s+['\"])", "Print", repaired, flags=re.IGNORECASE) + if repaired != source: + results.append(repaired) + # Only spell-correct within an explicitly recognized print/output + # statement; do not expand the vocabulary repair into arbitrary text. + if re.match(r"^print(?:\s|\()", source, re.IGNORECASE): + lexical = _repair_common_ocr_words(source) + if lexical != source: + results.append(lexical) + return list(dict.fromkeys(results)) + + +def select_ocr_candidate(candidates: list[tuple[str, list[OCRWord]]], shape_type: str = "unknown") -> tuple[str, list[OCRWord], list[dict]]: + """Select a best reading and retain near-ties for uncertain downstream review.""" + if not candidates: + return "", [], [] + # Add conservative, whitespace-only repairs as candidates. Keep the OCR words + # and confidence from the source reading for provenance and scoring. + expanded = list(candidates) + for text, words in candidates: + for repaired in _repair_ocr_text(text, shape_type): + if repaired != " ".join(text.split()): + expanded.append((repaired, words)) + normalized_counts = {} + for text, _ in expanded: + normalized = " ".join(text.split()).casefold() + if normalized: + normalized_counts[normalized] = normalized_counts.get(normalized, 0) + 1 + ranked = sorted(((_candidate_score(text, words, shape_type) + + min(.24, .08 * max(0, normalized_counts.get(" ".join(text.split()).casefold(), 1) - 1)) + + (.85 if shape_type == "decision" and _valid_decision_expression(text) else 0.0), + text, words) for text, words in expanded), key=lambda item: item[0], reverse=True) + best_score, best_text, best_words = ranked[0] + plausible = [] + seen = set() + low_confidence = not best_words or sum(w.confidence for w in best_words) / len(best_words) < .72 + for score, text, words in ranked: + normalized = " ".join(text.split()) + if normalized and normalized not in seen and (score >= best_score - (2.0 if shape_type == "decision" else .45) or (low_confidence and len(plausible) < 3)): + plausible.append({"text": normalized, "score": round(score, 3), "confidence": round( + sum(w.confidence for w in words) / len(words), 3) if words else 0.0}) + seen.add(normalized) + if len(plausible) >= 3: + break + return best_text, best_words, plausible + + +def read_best_words(image: np.ndarray, context: PipelineContext, origin: tuple[int, int] = (0, 0), + shape_type: str = "unknown", return_candidates: bool = False): + """Compare original and shape-aware preprocessing variants using Tesseract.""" + candidates = [] + for variant in preprocess_ocr_candidates(image, shape_type): + # Flowchart node labels are usually one line even when the containing + # shape is large. PSM 7 is materially better for operators and short + # conditions; retain the block/sparse modes for multiline print text. + if shape_type == "connector": + page_modes = (10, 6) + elif shape_type == "decision": + page_modes = (7, 6, 11) + else: + page_modes = (6, 11) + for psm in page_modes: text, words = read_words(variant, context, psm, origin) - score = sum(max(0.0, word.confidence) * len(word.text) for word in words) - score += 2.0 if psm == 6 else 0.0 - candidates.append((score, text, words)) - _, text, words = max(candidates, key=lambda candidate: candidate[0], default=(0.0, "", [])) - return text, words + scale_x = variant.shape[1] / max(1, image.shape[1]) + scale_y = variant.shape[0] / max(1, image.shape[0]) + if scale_x != 1 or scale_y != 1: + for word in words: + box = word.bbox + word.bbox = BoundingBox(origin[0] + round((box.x - origin[0]) / scale_x), + origin[1] + round((box.y - origin[1]) / scale_y), + max(1, round(box.width / scale_x)), max(1, round(box.height / scale_y))) + candidates.append((text, words)) + # Decision labels often occupy only a small central region of a large + # diamond crop. Tesseract's block segmentation can return gibberish or no + # text when the full diamond edges dominate the crop. Add a separate, + # enlarged center crop as an additional candidate while retaining all + # full-crop candidates for context and multiline fallbacks. + if shape_type == "decision" and image.shape[0] >= 24 and image.shape[1] >= 40: + crop_w = max(24, int(image.shape[1] * .70)) + crop_h = max(20, int(image.shape[0] * .60)) + left = max(0, (image.shape[1] - crop_w) // 2) + top = max(0, (image.shape[0] - crop_h) // 2) + center_crop = image[top:top + crop_h, left:left + crop_w] + enlarged = cv2.resize(center_crop, None, fx=2.0, fy=2.0, interpolation=cv2.INTER_CUBIC) + crop_origin = (origin[0] + left, origin[1] + top) + text, words = read_words(enlarged, context, 7, crop_origin) + for word in words: + box = word.bbox + word.bbox = BoundingBox( + crop_origin[0] + round((box.x - crop_origin[0]) / 2.0), + crop_origin[1] + round((box.y - crop_origin[1]) / 2.0), + max(1, round(box.width / 2.0)), max(1, round(box.height / 2.0))) + candidates.append((text, words)) + text, words, plausible = select_ocr_candidate(candidates, shape_type) + return (text, words, plausible) if return_candidates else (text, words) class VisionService: @@ -175,11 +561,26 @@ def run(self, context: PipelineContext) -> PipelineContext: # The contour bbox is already isolated from neighboring # nodes. Keeping the full crop prevents the fill mask # from erasing anti-aliased glyphs on solid-color nodes. - text, words = (read_words(crop, context, 10, (x + left, y + top)) - if geometry_kind == "connector" else read_best_words(crop, context, (x + left, y + top))) + text, words, ocr_candidates = (read_best_words(crop, context, (x + left, y + top), geometry_kind, True)) text = re.sub(r"^\s*[/|\\]+\s*|\s*[/|\\]+\s*$", "", text).strip() text = " ".join(text.split()).translate(str.maketrans({"“": '"', "”": '"', "‘": "'", "’": "'"})) - kind = geometry_kind + # Apply only high-confidence, vocabulary-bounded repairs to + # the selected reading. Keep the uncorrected OCR as a review + # alternative so users can reject the inference if needed. + if geometry_kind == "decision": + text = _normalize_comparison_spacing(text, geometry_kind) + elif geometry_kind in {"process", "output", "unknown"} and re.match(r"^print(?:\s|[:(])", text, re.IGNORECASE): + repaired_text = _repair_common_ocr_words(text) + if repaired_text != text: + original_reading = text + if not any(item.get("text") == original_reading for item in ocr_candidates): + ocr_candidates.append({"text": original_reading, "reason": "original OCR reading preserved for review", + "score": 0.0, "confidence": 0.0}) + text = repaired_text + if not any(item.get("text") == text for item in ocr_candidates): + ocr_candidates.insert(0, {"text": text, "reason": "conservative programming-vocabulary correction", + "score": 0.0, "confidence": 0.0}) + kind, text = infer_instruction_kind(geometry_kind, text) flags = [] if kind == "data": lowered = re.sub(r"^[^a-z]+", "", text.lower().strip()) @@ -189,15 +590,16 @@ def run(self, context: PipelineContext) -> PipelineContext: text = "Output " + text.split(None, 1)[1] if kind == "unknown": flags.append("UNRECOGNIZED_DATA_TEXT") - elif kind == "decision" and text.lower().startswith("if "): - text = text.split(None, 1)[1] + # Preserve a leading "If" in the recognized source text. + # normalize_condition() removes it only when constructing the + # executable condition, so review still shows what OCR saw. if kind == "unknown": flags.append("UNSUPPORTED_SHAPE") total = sum(len(word.text) for word in words) confidence = sum(word.confidence * len(word.text) for word in words) / total if total else 0.0 polygon = cv2.approxPolyDP(contour, .002 * cv2.arcLength(contour, True), True).reshape(-1, 2) node = Node(f"n{index}", kind, text, BoundingBox(x, y, width, height), confidence, flags, - [(int(a), int(b)) for a, b in polygon], words) + [(int(a), int(b)) for a, b in polygon], words, ocr_candidates) context.elements.append(node) cv2.drawContours(removal, [contour], -1, 255, cv2.FILLED) # Filled-node contours already cover their interiors; do not @@ -243,7 +645,22 @@ def run(self, context: PipelineContext) -> PipelineContext: context.diagnose("error", code, "OCR could not finish reading the diagram.", "Check the OCR language installation and try a smaller, clearer export.") finally: pytesseract.pytesseract.tesseract_cmd = previous - strokes = binary.copy() + # Contour fills do not always cover the outer half of anti-aliased + # outlines. Those leftover node borders are often larger components than + # the real arrows and can be mistaken for connectors that run around a + # shape. Expand the node-removal mask slightly before extracting strokes. + # The small gap this creates at a node is intentional: graph attachment + # uses a bounded distance to the actual node polygon. + removal = cv2.dilate( + removal, + cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (11, 11)), + iterations=1, + ) + # Otsu is useful for separating dark glyphs, but it drops pale gray + # connector arrows on colored-node diagrams. Build the connector mask + # from a permissive light-background threshold instead; node interiors + # are removed immediately below, so colored fills do not become strokes. + strokes = np.where(gray < 245, 255, 0).astype(np.uint8) strokes[removal > 0] = 0 # Remove only plausible text boxes, not arbitrary line-like OCR artifacts. for word in context.edge_words: diff --git a/frontend/css/styles.css b/frontend/css/styles.css index 5bb6f77..7915ea4 100644 --- a/frontend/css/styles.css +++ b/frontend/css/styles.css @@ -1,33 +1,33 @@ :root { color-scheme:light; - --bg:#f5f6f2; + --bg:#f4f6f9; --surface:#fff; - --text:#202c2a; - --muted:#5d6b68; - --line:#dce2dc; - --accent:#1f6f64; - --accent-soft:#edf5f1; + --text:#202a38; + --muted:#657286; + --line:#dce3ec; + --accent:#3768b5; + --accent-soft:#edf3fc; --error:#ac3535; --warning:#865913; - --focus:#216cbe; - --highlight:#e4f4dd; + --focus:#3768b5; + --highlight:#e5efff; font-family:Inter,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif; font-size:14px; line-height:1.6 } :root[data-theme=dark] { color-scheme:dark; - --bg:#131c1b; - --surface:#1a2624; - --text:#e5ece7; - --muted:#a4b7b1; - --line:#354740; - --accent:#86d1ba; - --accent-soft:#233d35; + --bg:#151b25; + --surface:#1c2532; + --text:#e8edf5; + --muted:#a8b5c8; + --line:#354254; + --accent:#8db7ff; + --accent-soft:#26364f; --error:#ffa2a2; --warning:#f0c582; - --focus:#8fc4ff; - --highlight:#344f3b + --focus:#9dc4ff; + --highlight:#2a3d5b } * { box-sizing:border-box @@ -252,7 +252,7 @@ p { } .drop-zone { cursor:pointer; - transition:border-color .15s ease,background .15s ease,box-shadow .15s ease + transition:border-color .15s ease,background .15s ease,box-shadow .15s ease; display:flex; align-items:center; gap:14px; @@ -605,6 +605,24 @@ summary { display:flex; gap:14px } +.additional-diagnostics { + border-top:1px solid var(--line); + padding:10px 20px 14px +} +.additional-diagnostics summary { + font-size:12px; + font-weight:650; + padding:4px 0 +} +.additional-diagnostics-list { + margin-top:8px; + border:1px solid var(--line); + border-radius:7px; + overflow:hidden +} +.additional-diagnostics-list .diagnostic:first-child { + border-top:0 +} .diagnostic strong { font-size:12px } @@ -750,7 +768,7 @@ code { } .drop-zone { cursor:pointer; - transition:border-color .15s ease,background .15s ease,box-shadow .15s ease + transition:border-color .15s ease,background .15s ease,box-shadow .15s ease; min-width:0; gap:8px; width:100% @@ -796,3 +814,169 @@ code { transition:background .12s } } + +/* Keep OCR alternatives visible as review suggestions, distinct from the original. */ +.ocr-alternatives { display: block; margin-top: .35rem; opacity: .82; white-space: normal; overflow-wrap: anywhere; } + +/* Analysis notes: calmer spacing and a consistent diagnostic layout. */ +.diagnostics { + margin:24px 0; + border-radius:12px; + box-shadow:0 3px 14px rgb(0 0 0 / 4%); +} +.diagnostics header { + padding:18px 24px; + background:var(--accent-soft); + align-items:center; +} +.diagnostics header h2 { + margin:0; + font-size:16px; + line-height:1.35; + letter-spacing:-.2px; +} +.diagnostics header p { + margin:5px 0 0; + color:var(--muted); + font-size:12px; + line-height:1.5; +} +.diagnostics header .panel-badge { + flex-shrink:0; + white-space:nowrap; +} +.diagnostic { + display:grid; + grid-template-columns:72px minmax(250px,1.15fr) minmax(220px,1fr) minmax(125px,.42fr); + align-items:start; + gap:10px 18px; + padding:16px 24px; + border-top:1px solid var(--line); +} +.diagnostic > .severity { + min-width:0; + padding-top:2px; + letter-spacing:.35px; +} +.diagnostic strong { + min-width:0; + font-size:13px; + font-weight:650; + line-height:1.55; + overflow-wrap:anywhere; +} +.diagnostic p { + min-width:0; + margin:0; + color:var(--muted); + font-size:12px; + line-height:1.6; + overflow-wrap:anywhere; +} +.diagnostic code { + display:block; + min-width:0; + padding-top:2px; + font-size:10px; + line-height:1.55; + overflow-wrap:anywhere; + white-space:normal; +} +.additional-diagnostics { + margin:0; + padding:14px 24px 20px; + border-top:1px solid var(--line); + background:color-mix(in srgb,var(--surface) 94%,var(--accent) 6%); +} +.additional-diagnostics summary { + display:list-item; + width:fit-content; + max-width:100%; + padding:4px 0; + color:var(--accent); + font-size:12px; + font-weight:700; + line-height:1.5; +} +.additional-diagnostics summary:hover { + text-decoration:underline; + text-underline-offset:3px; +} +.additional-diagnostics-list { + margin-top:12px; + border:1px solid var(--line); + border-radius:9px; + background:var(--surface); +} +.additional-diagnostics-list .diagnostic { + padding:14px 18px; +} +.additional-diagnostics-list .diagnostic:first-child { + border-top:0; +} +@media(max-width:1100px) { + .diagnostic { + grid-template-columns:64px minmax(200px,1fr) minmax(180px,.9fr); + gap:8px 14px; + } + .diagnostic code { + grid-column:2 / -1; + padding-top:0; + } +} +@media(max-width:760px) { + .diagnostics header { + padding:16px 18px; + flex-wrap:wrap; + } + .diagnostics header .panel-badge { + white-space:normal; + } + .diagnostic, + .additional-diagnostics-list .diagnostic { + grid-template-columns:1fr; + gap:5px; + padding:14px 18px; + } + .diagnostic code { + grid-column:auto; + padding-top:2px; + } + .additional-diagnostics { + padding:12px 18px 16px; + } +} + + +/* Refined workspace: remove the oversized marketing hero and visual stepper. */ +main { max-width:1760px; padding:24px 3vw 0; } +.header { padding:15px 3vw; background:var(--surface); border-bottom:1px solid var(--line); } +.brand { font-size:24px; letter-spacing:-.7px; } +.brand-mark { border-radius:10px; box-shadow:none; } +.brand-caption { color:var(--muted); letter-spacing:1.5px; } +.intro { margin:0 0 18px; align-items:flex-end; } +.intro h1 { font-size:clamp(22px,2.2vw,29px); letter-spacing:-.75px; font-weight:650; } +.intro p:not(.eyebrow) { margin:5px 0 0; font-size:13px; max-width:700px; } +.steps { margin:0; } +.upload-bar { padding:14px 16px; gap:12px; border-radius:9px; box-shadow:0 2px 8px rgb(25 40 65 / 3%); } +.drop-zone { min-width:260px; } +.upload-symbol { background:var(--accent-soft); color:var(--accent); } +.button { border-radius:7px; min-height:38px; font-weight:600; } +.button.primary { box-shadow:none; } +.button.action-button { border-width:1px; } +.status-row { margin:10px 2px 14px; } +.workspace { gap:14px; } +.panel { border-radius:9px; box-shadow:0 2px 9px rgb(25 40 65 / 3%); } +.panel-heading { padding:14px 16px; background:color-mix(in srgb,var(--surface) 96%,var(--accent) 4%); } +.panel-heading h2 { font-size:14px; } +.panel:not(.diagram-panel) { min-height:570px; } +.panel-footer { padding:10px 15px; } +.empty-state { padding:36px 22px; } +.diagnostics { margin:20px 0; border-radius:9px; box-shadow:0 2px 9px rgb(25 40 65 / 3%); } +.diagnostics header { background:var(--surface); } +.diagnostics header h2 { font-size:15px; } +.diagnostic { padding-top:14px; padding-bottom:14px; } +.site-footer { letter-spacing:.35px; } +#status.success { color:var(--accent); } +@media (max-width:1100px) { main { padding:22px 22px 0; } } +@media (max-width:760px) { main { padding:20px 16px 0; } .header { padding:12px 16px; } .intro { margin-bottom:14px; } .intro h1 { font-size:23px; } .upload-bar { padding:11px; } .panel:not(.diagram-panel) { min-height:360px; } } diff --git a/frontend/icons/README-icons.md b/frontend/icons/README-icons.md new file mode 100644 index 0000000..bb53888 --- /dev/null +++ b/frontend/icons/README-icons.md @@ -0,0 +1,30 @@ +# Modulo M icon pack + +## Included +- `modulo-m-icon.svg`: scalable app icon +- `modulo-wordmark.svg`: icon + Modulo wordmark for application header +- `modulo.ico` and `favicon.ico`: multi-size Windows icon and browser favicon +- PNG assets at 16, 24, 32, 48, 64, 96, 128, 150, 180, 192, 256, and 512 px +- `apple-touch-icon.png`, `icon-192.png`, `icon-512.png`, `site.webmanifest` + +## Palette +- Deep navy / blue background: `#07162F`, `#123D78` +- White-to-blue-to-teal M: `#FFFFFF`, `#83BDFF`, `#20E3C2` + +## Browser integration +Put this folder where Flask serves `/icons/`, then add inside `frontend/index.html`'s ``: +```html + + + + + +``` + +## Windows +Use `modulo.ico` for the Windows shortcut or packaged executable. For PyInstaller, configure the build/spec to use this file as the application icon. For a browser-only local app, set the shortcut icon to this ICO; browser window chrome itself is controlled by the browser. + +## Header +Use `modulo-wordmark.svg` for a light header. Use `modulo-m-icon.svg` alone for a compact app mark. + +All assets are standalone and ready to copy into your app. Adjust `/icons/` URLs if serving from a different path. diff --git a/frontend/icons/apple-touch-icon.png b/frontend/icons/apple-touch-icon.png new file mode 100644 index 0000000..f41412e Binary files /dev/null and b/frontend/icons/apple-touch-icon.png differ diff --git a/frontend/icons/favicon-32.png b/frontend/icons/favicon-32.png new file mode 100644 index 0000000..10f1719 Binary files /dev/null and b/frontend/icons/favicon-32.png differ diff --git a/frontend/icons/favicon.ico b/frontend/icons/favicon.ico new file mode 100644 index 0000000..445ee1f Binary files /dev/null and b/frontend/icons/favicon.ico differ diff --git a/frontend/icons/icon-192.png b/frontend/icons/icon-192.png new file mode 100644 index 0000000..2f29108 Binary files /dev/null and b/frontend/icons/icon-192.png differ diff --git a/frontend/icons/icon-512.png b/frontend/icons/icon-512.png new file mode 100644 index 0000000..1cd67e0 Binary files /dev/null and b/frontend/icons/icon-512.png differ diff --git a/frontend/icons/modulo-128.png b/frontend/icons/modulo-128.png new file mode 100644 index 0000000..de3dc1e Binary files /dev/null and b/frontend/icons/modulo-128.png differ diff --git a/frontend/icons/modulo-150.png b/frontend/icons/modulo-150.png new file mode 100644 index 0000000..d770222 Binary files /dev/null and b/frontend/icons/modulo-150.png differ diff --git a/frontend/icons/modulo-16.png b/frontend/icons/modulo-16.png new file mode 100644 index 0000000..9b026d2 Binary files /dev/null and b/frontend/icons/modulo-16.png differ diff --git a/frontend/icons/modulo-180.png b/frontend/icons/modulo-180.png new file mode 100644 index 0000000..f41412e Binary files /dev/null and b/frontend/icons/modulo-180.png differ diff --git a/frontend/icons/modulo-192.png b/frontend/icons/modulo-192.png new file mode 100644 index 0000000..2f29108 Binary files /dev/null and b/frontend/icons/modulo-192.png differ diff --git a/frontend/icons/modulo-24.png b/frontend/icons/modulo-24.png new file mode 100644 index 0000000..43c8c71 Binary files /dev/null and b/frontend/icons/modulo-24.png differ diff --git a/frontend/icons/modulo-256.png b/frontend/icons/modulo-256.png new file mode 100644 index 0000000..e4637a1 Binary files /dev/null and b/frontend/icons/modulo-256.png differ diff --git a/frontend/icons/modulo-32.png b/frontend/icons/modulo-32.png new file mode 100644 index 0000000..10f1719 Binary files /dev/null and b/frontend/icons/modulo-32.png differ diff --git a/frontend/icons/modulo-48.png b/frontend/icons/modulo-48.png new file mode 100644 index 0000000..67017f8 Binary files /dev/null and b/frontend/icons/modulo-48.png differ diff --git a/frontend/icons/modulo-512.png b/frontend/icons/modulo-512.png new file mode 100644 index 0000000..1cd67e0 Binary files /dev/null and b/frontend/icons/modulo-512.png differ diff --git a/frontend/icons/modulo-64.png b/frontend/icons/modulo-64.png new file mode 100644 index 0000000..5f14ad7 Binary files /dev/null and b/frontend/icons/modulo-64.png differ diff --git a/frontend/icons/modulo-96.png b/frontend/icons/modulo-96.png new file mode 100644 index 0000000..f072ce4 Binary files /dev/null and b/frontend/icons/modulo-96.png differ diff --git a/frontend/icons/modulo-m-icon.svg b/frontend/icons/modulo-m-icon.svg new file mode 100644 index 0000000..2f5b94c --- /dev/null +++ b/frontend/icons/modulo-m-icon.svg @@ -0,0 +1,17 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/frontend/icons/modulo-wordmark.svg b/frontend/icons/modulo-wordmark.svg new file mode 100644 index 0000000..fbfc952 --- /dev/null +++ b/frontend/icons/modulo-wordmark.svg @@ -0,0 +1,9 @@ + + + + + + + + Modulo + \ No newline at end of file diff --git a/frontend/icons/modulo.ico b/frontend/icons/modulo.ico new file mode 100644 index 0000000..0f786b2 Binary files /dev/null and b/frontend/icons/modulo.ico differ diff --git a/frontend/icons/modulo.png b/frontend/icons/modulo.png new file mode 100644 index 0000000..1cd67e0 Binary files /dev/null and b/frontend/icons/modulo.png differ diff --git a/frontend/icons/site.webmanifest b/frontend/icons/site.webmanifest new file mode 100644 index 0000000..2419321 --- /dev/null +++ b/frontend/icons/site.webmanifest @@ -0,0 +1,13 @@ +{ + "name": "Modulo", + "short_name": "Modulo", + "description": "Turn flowcharts into traceable Python code.", + "start_url": "/", + "display": "standalone", + "background_color": "#07162F", + "theme_color": "#07162F", + "icons": [ + {"src": "/icons/icon-192.png", "sizes": "192x192", "type": "image/png"}, + {"src": "/icons/icon-512.png", "sizes": "512x512", "type": "image/png"} + ] +} \ No newline at end of file diff --git a/frontend/index.html b/frontend/index.html index 5544510..652d9d7 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -5,7 +5,7 @@ Modulo — Flowchart to code - +