""" Jinja Templates and MDX Components for MiniMind Max2 Enhanced code generation with rich formatting support. """ from dataclasses import dataclass, field from typing import List, Optional, Dict, Any, Union import re import json from enum import Enum class MDXComponentType(Enum): """Supported MDX component types.""" LINEAR_PROCESS_FLOW = "LinearProcessFlow" QUIZ = "Quiz" MATH = "math" THINKING = "Thinking" CODE_BLOCK = "CodeBlock" MERMAID = "Mermaid" CALLOUT = "Callout" TABS = "Tabs" ACCORDION = "Accordion" @dataclass class CodeBlockMeta: """Metadata for extended code blocks.""" project: str = "" file: str = "" block_type: str = "code" # react, nodejs, html, markdown, diagram, code language: str = "python" title: str = "" show_line_numbers: bool = True highlight_lines: List[int] = field(default_factory=list) executable: bool = False @dataclass class ThinkingBlock: """Represents a thinking/reasoning block.""" content: str step: int = 0 is_final: bool = False confidence: float = 1.0 class JinjaTemplateEngine: """ Jinja-style template engine for code generation. Supports variables, loops, conditionals, and filters. """ def __init__(self): self.filters = { "upper": str.upper, "lower": str.lower, "capitalize": str.capitalize, "title": str.title, "strip": str.strip, "length": len, "default": lambda x, d: x if x else d, "join": lambda x, sep=", ": sep.join(str(i) for i in x), "first": lambda x: x[0] if x else None, "last": lambda x: x[-1] if x else None, "json": json.dumps, } self.globals = {} def register_filter(self, name: str, func): """Register a custom filter.""" self.filters[name] = func def register_global(self, name: str, value): """Register a global variable.""" self.globals[name] = value def render(self, template: str, context: Dict[str, Any]) -> str: """ Render a Jinja-style template. Args: template: Template string with {{ }} and {% %} blocks context: Variables to substitute Returns: Rendered string """ # Merge context with globals full_context = {**self.globals, **context} # Process control structures first result = self._process_control_structures(template, full_context) # Then substitute variables result = self._substitute_variables(result, full_context) return result def _substitute_variables(self, template: str, context: Dict[str, Any]) -> str: """Substitute {{ variable }} expressions.""" pattern = r'\{\{\s*(.+?)\s*\}\}' def replace(match): expr = match.group(1) return str(self._evaluate_expression(expr, context)) return re.sub(pattern, replace, template) def _evaluate_expression(self, expr: str, context: Dict[str, Any]) -> Any: """Evaluate a Jinja expression.""" # Handle filters (e.g., name|upper) if '|' in expr: parts = expr.split('|') value = self._evaluate_expression(parts[0].strip(), context) for filter_expr in parts[1:]: filter_expr = filter_expr.strip() # Handle filter with arguments if '(' in filter_expr: filter_name = filter_expr[:filter_expr.index('(')] args_str = filter_expr[filter_expr.index('(')+1:-1] if filter_name in self.filters: value = self.filters[filter_name](value, args_str.strip('"\'')) else: if filter_expr in self.filters: value = self.filters[filter_expr](value) return value # Handle attribute access (e.g., user.name) if '.' in expr: parts = expr.split('.') value = context.get(parts[0]) for part in parts[1:]: if isinstance(value, dict): value = value.get(part) elif hasattr(value, part): value = getattr(value, part) else: return None return value # Handle index access (e.g., items[0]) if '[' in expr: match = re.match(r'(\w+)\[(.+)\]', expr) if match: var_name = match.group(1) index = match.group(2) value = context.get(var_name) if value: try: idx = int(index) return value[idx] except (ValueError, IndexError): return None return None # Simple variable lookup return context.get(expr, '') def _process_control_structures(self, template: str, context: Dict[str, Any]) -> str: """Process {% for %}, {% if %}, etc.""" result = template # Process for loops for_pattern = r'\{%\s*for\s+(\w+)\s+in\s+(\w+)\s*%\}(.*?)\{%\s*endfor\s*%\}' while True: match = re.search(for_pattern, result, re.DOTALL) if not match: break var_name = match.group(1) iterable_name = match.group(2) body = match.group(3) iterable = context.get(iterable_name, []) rendered_parts = [] for item in iterable: item_context = {**context, var_name: item} rendered_parts.append(self._substitute_variables(body, item_context)) result = result[:match.start()] + ''.join(rendered_parts) + result[match.end():] # Process if statements if_pattern = r'\{%\s*if\s+(.+?)\s*%\}(.*?)(?:\{%\s*else\s*%\}(.*?))?\{%\s*endif\s*%\}' while True: match = re.search(if_pattern, result, re.DOTALL) if not match: break condition = match.group(1) true_block = match.group(2) false_block = match.group(3) or '' if self._evaluate_condition(condition, context): replacement = true_block else: replacement = false_block result = result[:match.start()] + replacement + result[match.end():] return result def _evaluate_condition(self, condition: str, context: Dict[str, Any]) -> bool: """Evaluate a condition expression.""" # Simple conditions if ' == ' in condition: left, right = condition.split(' == ', 1) left_val = self._evaluate_expression(left.strip(), context) right_val = right.strip().strip('"\'') return str(left_val) == right_val if ' != ' in condition: left, right = condition.split(' != ', 1) left_val = self._evaluate_expression(left.strip(), context) right_val = right.strip().strip('"\'') return str(left_val) != right_val if ' > ' in condition: left, right = condition.split(' > ', 1) left_val = self._evaluate_expression(left.strip(), context) right_val = float(right.strip()) return float(left_val) > right_val if ' < ' in condition: left, right = condition.split(' < ', 1) left_val = self._evaluate_expression(left.strip(), context) right_val = float(right.strip()) return float(left_val) < right_val # Truthiness check value = self._evaluate_expression(condition.strip(), context) return bool(value) class MDXRenderer: """ Render MDX components for rich documentation and UI. """ def __init__(self): self.components = {} self._register_default_components() def _register_default_components(self): """Register default MDX components.""" self.components = { MDXComponentType.LINEAR_PROCESS_FLOW: self._render_linear_process_flow, MDXComponentType.QUIZ: self._render_quiz, MDXComponentType.MATH: self._render_math, MDXComponentType.THINKING: self._render_thinking, MDXComponentType.MERMAID: self._render_mermaid, MDXComponentType.CALLOUT: self._render_callout, MDXComponentType.TABS: self._render_tabs, } def render(self, component_type: MDXComponentType, props: Dict[str, Any]) -> str: """Render an MDX component.""" if component_type in self.components: return self.components[component_type](props) return f"" def _render_linear_process_flow(self, props: Dict[str, Any]) -> str: """Render a linear process flow diagram.""" steps = props.get("steps", []) title = props.get("title", "Process Flow") html = f'
{step.get("description", "")}
\n' html += '{q.get("question", "")}
\n' html += ' \n' if q.get("explanation"): html += f'\n{code}\n \n'
html += '