""" Utility functions module for BrightMind AI Contains helper functions for content processing, math conversion, and styling """ import re from algebra_solver import AlgebraSolver # Initialize algebra solver algebra_solver = AlgebraSolver() def convert_math_to_html(text): """Convert LaTeX-style math expressions to HTML""" # Handle LaTeX math delimiters first # Convert \[ ... \] to display math text = re.sub(r'\\\[([^\]]+)\\\]', r'
\1
', text) # Convert \( ... \) to inline math text = re.sub(r'\\\(([^)]+)\\\)', r'\1', text) # Handle fractions: \frac{a}{b} text = re.sub(r'\\frac\{([^}]+)\}\{([^}]+)\}', r'
\1
\2
', text) # Handle simple fractions like 120/2 text = re.sub(r'(\d+)/(\d+)', r'
\1
\2
', text) # Handle superscripts: ^{text} text = re.sub(r'\^\{([^}]+)\}', r'\1', text) text = re.sub(r'\^(\w)', r'\1', text) # Handle subscripts: _{text} text = re.sub(r'_\{([^}]+)\}', r'\1', text) text = re.sub(r'_(\w)', r'\1', text) # Handle \text{} commands first (before other processing) text = re.sub(r'\\text\{([^}]+)\}', r'\1', text) # Handle \boxed{} commands text = re.sub(r'\\boxed\{([^}]+)\}', r'\1', text) # Handle underscore patterns that are not subscripts (like \_\_\_) text = re.sub(r'\\_+', r' ', text) # Re-process fractions after text commands are handled text = re.sub(r'\\frac\{([^}]+)\}\{([^}]+)\}', r'
\1
\2
', text) # Handle common math symbols text = text.replace('\\times', '×') text = text.replace('\\rightarrow', '→') text = text.replace('\\leftarrow', '←') text = text.replace('\\leq', '≤') text = text.replace('\\geq', '≥') text = text.replace('\\neq', '≠') text = text.replace('\\approx', '≈') text = text.replace('\\pm', '±') text = text.replace('\\sqrt', '√') text = text.replace('\\pi', 'π') return text def solve_algebra_problem(problem_type, *args): """Solve algebra problems interactively""" try: if problem_type == "speed": distance, time = args result = algebra_solver.solve_speed_problem(float(distance), float(time)) elif problem_type == "volume": mass, density = args result = algebra_solver.solve_volume_problem(float(mass), float(density)) elif problem_type == "linear": a, b, c = args result = algebra_solver.solve_linear_equation(float(a), float(b), float(c)) elif problem_type == "quadratic": h, coefficient = args result = algebra_solver.solve_quadratic_equation(float(h), float(coefficient)) else: return "❌ Unknown problem type" if "error" in result: return f"❌ Error: {result['error']}" # Format the solution nicely solution_text = f"✅ **{result['solution']}**\n\n" if "steps" in result: solution_text += "**Steps:**\n" for i, step in enumerate(result["steps"], 1): solution_text += f"{i}. {step}\n" elif "formula" in result: solution_text += f"**Formula:** {result['formula']}\n" solution_text += f"**Calculation:** {result['calculation']}\n" return solution_text except Exception as e: return f"❌ Error solving problem: {str(e)}" def apply_content_styling(content, content_type): """Apply simple and robust styling to educational content""" # Clean up any malformed HTML first content = re.sub(r'="[^"]*style="[^"]*"[^"]*"', '', content) content = re.sub(r'="[^"]*color: [^"]*"[^"]*"', '', content) content = re.sub(r'="[^"]*background: [^"]*"[^"]*"', '', content) content = re.sub(r'="[^"]*border: [^"]*"[^"]*"', '', content) content = re.sub(r'="[^"]*padding: [^"]*"[^"]*"', '', content) content = re.sub(r'="[^"]*margin: [^"]*"[^"]*"', '', content) # Fix broken image tags and malformed HTML content = re.sub(r'
.*?
', '', content) content = re.sub(r'stylelazy">', 'loading="lazy">', content) content = re.sub(r']*style[^>]*>', '', content) # Fix malformed button attributes content = re.sub(r'styleselectRating\(\d+\)"', '', content) content = re.sub(r'styletext"', '', content) content = re.sub(r'style="[^"]*"[^"]*style="[^"]*"', 'style="margin-right: 8px; transform: scale(1.2);"', content) # Fix broken input attributes content = re.sub(r'
{numerator}
{denominator}
' # Process fractions: \frac{numerator}{denominator} - more robust regex latex_formula = re.sub(r'\\frac\{([^{}]+)\}\{([^{}]+)\}', process_fraction, latex_formula) # Handle text commands more carefully latex_formula = latex_formula.replace('\\text{', '') # Handle math symbols latex_formula = latex_formula.replace('\\times', '×') latex_formula = latex_formula.replace('\\rightarrow', '→') latex_formula = latex_formula.replace('\\leftarrow', '←') latex_formula = latex_formula.replace('\\leq', '≤') latex_formula = latex_formula.replace('\\geq', '≥') latex_formula = latex_formula.replace('\\neq', '≠') latex_formula = latex_formula.replace('\\approx', '≈') latex_formula = latex_formula.replace('\\pm', '±') latex_formula = latex_formula.replace('\\sqrt{', '√(') latex_formula = latex_formula.replace('\\pi', 'π') latex_formula = latex_formula.replace('\\alpha', 'α') latex_formula = latex_formula.replace('\\beta', 'β') latex_formula = latex_formula.replace('\\gamma', 'γ') latex_formula = latex_formula.replace('\\delta', 'δ') latex_formula = latex_formula.replace('\\theta', 'θ') latex_formula = latex_formula.replace('\\lambda', 'λ') latex_formula = latex_formula.replace('\\mu', 'μ') latex_formula = latex_formula.replace('\\sigma', 'σ') latex_formula = latex_formula.replace('\\tau', 'τ') latex_formula = latex_formula.replace('\\phi', 'φ') latex_formula = latex_formula.replace('\\omega', 'ω') # Handle superscripts and subscripts latex_formula = re.sub(r'\^(\w+)', r'\1', latex_formula) latex_formula = re.sub(r'_(\w+)', r'\1', latex_formula) # Clean up any remaining unmatched braces latex_formula = latex_formula.replace('{', '').replace('}', '') return f'
{latex_formula}
' # Find LaTeX math formulas and convert them (both [formula] and (formula) formats) # Updated patterns to be more specific to LaTeX commands latex_patterns = [ re.compile(r'\[([^\[\]]*\\[a-zA-Z]+[^\[\]]*)\]', re.MULTILINE), # [formula with LaTeX commands] re.compile(r'\(([^()]*\\[a-zA-Z]+[^()]*)\)', re.MULTILINE) # (formula with LaTeX commands) ] for pattern in latex_patterns: content = pattern.sub(fix_latex_math, content) # Find all IMAGE: description patterns (both [IMAGE: description] and IMAGE: description) image_patterns = [ re.compile(r'\[IMAGE:\s*([^\]]+)\]', re.IGNORECASE), re.compile(r'IMAGE:\s*([^\n]+)', re.IGNORECASE), re.compile(r'\*\*\[📸\s*Image:\s*([^\]]+)\]\*\*', re.IGNORECASE), re.compile(r'\[📸\s*Image:\s*([^\]]+)\]', re.IGNORECASE), re.compile(r'📸\s*Image:\s*([^\n]+)', re.IGNORECASE), re.compile(r'\*\*\[📸\s*Image:\s*([^\]]+)\]\*\*\s*\*Visual content would appear here\*', re.IGNORECASE), re.compile(r'\[📸\s*Image:\s*([^\]]+)\]\s*Visual content would appear here', re.IGNORECASE), re.compile(r'📸\s*Image:\s*([^\n]+)\s*Visual content would appear here', re.IGNORECASE) ] for i, pattern in enumerate(image_patterns): def replace_image(match): description = match.group(1).strip() print(f"🖼️ Processing image with pattern {i+1}: {description}") # Try to get a real image URL image_url = get_educational_image_url(topic, description, content_type) if image_url and image_url.startswith('data:image'): # Real generated image (base64 data) return f'\n{description}\n' elif image_url and (image_url.startswith('https://picsum.photos') or image_url.startswith('https://via.placeholder.com')): # Fallback placeholder image return f'\n{description}\n' else: # Use a more informative placeholder that shows we tried to generate an image return f"""
🖼️

📸 {description}

Educational diagram related to: {topic}

💡 AI-generated image would appear here
""" content = pattern.sub(replace_image, content) # Find all INTERACTIVE: description patterns interactive_patterns = [ re.compile(r'\[INTERACTIVE:\s*([^\]]+)\]', re.IGNORECASE), re.compile(r'INTERACTIVE:\s*([^\n]+)', re.IGNORECASE) ] for pattern in interactive_patterns: def replace_interactive(match): description = match.group(1).strip() print(f"🎮 Processing interactive element: {description}") return f"""
🎮

{description}

Interactive educational element

🎯 Interactive content would be implemented here
""" content = pattern.sub(replace_interactive, content) return content def typewriter_effect(text, status_message): """Create a typewriter effect for text display""" import time if not text: return status_message # Split text into words for smoother effect words = text.split() result = "" for i, word in enumerate(words): result += word + " " if i % 10 == 0: # Yield every 10 words yield result, status_message time.sleep(0.05) # Small delay for effect yield result, status_message