"""
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'
'
# 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\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\n'
else:
# Use a more informative placeholder that shows we tried to generate an image
return f"""
"""
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