Spaces:
Sleeping
Sleeping
File size: 14,969 Bytes
6cff14b a41632c 6cff14b 4a31143 a41632c 469f820 a41632c 469f820 6cff14b a41632c 6cff14b a41632c 6cff14b 4a31143 6cff14b 4a31143 6cff14b 469f820 6cff14b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 | """
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'<div style="text-align: center; margin: 10px 0; padding: 10px; background: #f8f9fa; border-radius: 5px; font-family: \'Times New Roman\', serif; font-size: 1.1em;">\1</div>', text)
# Convert \( ... \) to inline math
text = re.sub(r'\\\(([^)]+)\\\)', r'<span style="font-family: \'Times New Roman\', serif; font-size: 1.05em; background: #f0f0f0; padding: 2px 4px; border-radius: 3px;">\1</span>', text)
# Handle fractions: \frac{a}{b}
text = re.sub(r'\\frac\{([^}]+)\}\{([^}]+)\}', r'<div style="display: inline-block; text-align: center; vertical-align: middle; margin: 0 5px;"><div style="border-bottom: 1px solid #333; padding-bottom: 2px; font-size: 0.9em;">\1</div><div style="padding-top: 2px; font-size: 0.9em;">\2</div></div>', text)
# Handle simple fractions like 120/2
text = re.sub(r'(\d+)/(\d+)', r'<div style="display: inline-block; text-align: center; vertical-align: middle; margin: 0 3px;"><div style="border-bottom: 1px solid #333; padding-bottom: 1px; font-size: 0.9em;">\1</div><div style="padding-top: 1px; font-size: 0.9em;">\2</div></div>', text)
# Handle superscripts: ^{text}
text = re.sub(r'\^\{([^}]+)\}', r'<sup>\1</sup>', text)
text = re.sub(r'\^(\w)', r'<sup>\1</sup>', text)
# Handle subscripts: _{text}
text = re.sub(r'_\{([^}]+)\}', r'<sub>\1</sub>', text)
text = re.sub(r'_(\w)', r'<sub>\1</sub>', 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'<span style="border: 2px solid #333; padding: 2px 4px; background: #f0f0f0; border-radius: 3px;">\1</span>', text)
# Handle underscore patterns that are not subscripts (like \_\_\_)
text = re.sub(r'\\_+', r'<span style="border-bottom: 2px solid #333; min-width: 20px; display: inline-block;"> </span>', text)
# Re-process fractions after text commands are handled
text = re.sub(r'\\frac\{([^}]+)\}\{([^}]+)\}', r'<div style="display: inline-block; text-align: center; vertical-align: middle; margin: 0 5px;"><div style="border-bottom: 1px solid #333; padding-bottom: 2px; font-size: 0.9em;">\1</div><div style="padding-top: 2px; font-size: 0.9em;">\2</div></div>', 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'<div style>.*?</div>', '', content)
content = re.sub(r'stylelazy">', 'loading="lazy">', content)
content = re.sub(r'<img[^>]*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'<input typeready-check"', '<input type="checkbox" id="ready-check"', content)
content = re.sub(r'styleSolve"', 'onclick="solveSpeed()"', content)
# Clean up any remaining malformed attributes
content = re.sub(r'="[^"]*"[^"]*"', '', content)
# Return content as-is for Markdown rendering
styled_content = content
# Apply Markdown-friendly styling
styled_content = re.sub(r'\[ANSWER: ([^\]]+)\]', r'**Answer:** \1', styled_content)
styled_content = re.sub(r'___+', r'_________________', styled_content)
styled_content = re.sub(r'\[ \]', r'☐', styled_content)
styled_content = re.sub(r'☑', r'☑', styled_content)
styled_content = re.sub(r'\[(\d+)\]', r'**\1**', styled_content)
return styled_content
def process_content_with_images(content, topic, content_type):
"""Process generated content to include real images and multimedia elements"""
from ai_services import get_educational_image_url, generate_image_placeholder
print(f"🖼️ Processing content for topic: {topic}, type: {content_type}")
print(f"🖼️ Content length: {len(content)} characters")
print(f"🖼️ First 500 chars: {content[:500]}")
# Replace image placeholders with actual images
# Convert LaTeX-style math expressions to HTML first
content = convert_math_to_html(content)
# Fix LaTeX math rendering by converting to HTML
def fix_latex_math(match):
latex_formula = match.group(1)
# Handle fractions first (most complex) - improved regex
def process_fraction(match):
numerator = match.group(1)
denominator = match.group(2)
return f'<div style="display: inline-block; text-align: center; vertical-align: middle; margin: 0 5px;"><div style="border-bottom: 1px solid #333; padding-bottom: 2px; font-size: 0.9em;">{numerator}</div><div style="padding-top: 2px; font-size: 0.9em;">{denominator}</div></div>'
# 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{', '<span style="font-style: normal;">')
# 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'<sup>\1</sup>', latex_formula)
latex_formula = re.sub(r'_(\w+)', r'<sub>\1</sub>', latex_formula)
# Clean up any remaining unmatched braces
latex_formula = latex_formula.replace('{', '').replace('}', '')
return f'<div style="text-align: center; margin: 20px 0; padding: 15px; background: #f8f9fa; border-radius: 8px; border-left: 4px solid #667eea; font-family: \'Times New Roman\', serif; font-size: 1.1em;">{latex_formula}</div>'
# 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<img src="{image_url}" alt="{description}" style="max-width: 100%; height: auto; border-radius: 8px; margin: 20px 0; box-shadow: 0 4px 6px rgba(0,0,0,0.1);">\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<img src="{image_url}" alt="{description}" style="max-width: 100%; height: auto; border-radius: 8px; margin: 20px 0; box-shadow: 0 4px 6px rgba(0,0,0,0.1);">\n'
else:
# Use a more informative placeholder that shows we tried to generate an image
return f"""
<div style="border: 2px dashed #667eea; padding: 20px; margin: 20px 0; text-align: center; background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%); border-radius: 12px;">
<div style="font-size: 48px; margin-bottom: 10px;">🖼️</div>
<h3 style="color: #667eea; margin: 10px 0;">📸 {description}</h3>
<p style="color: #4a5568; margin: 10px 0;">Educational diagram related to: <strong>{topic}</strong></p>
<div style="background: #667eea; color: white; padding: 8px 16px; border-radius: 6px; display: inline-block; margin-top: 10px; font-size: 12px;">
💡 AI-generated image would appear here
</div>
</div>
"""
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"""
<div style="border: 2px solid #4f46e5; padding: 20px; margin: 20px 0; text-align: center; background: linear-gradient(135deg, #e0e7ff 0%, #c7d2fe 100%); border-radius: 12px;">
<div style="font-size: 48px; margin-bottom: 10px;">🎮</div>
<h3 style="color: #4f46e5; margin: 10px 0;">{description}</h3>
<p style="color: #3730a3; margin: 10px 0;">Interactive educational element</p>
<div style="background: #4f46e5; color: white; padding: 8px 16px; border-radius: 6px; display: inline-block; margin-top: 10px; font-size: 12px;">
🎯 Interactive content would be implemented here
</div>
</div>
"""
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
|