Spaces:
Sleeping
Sleeping
Download utils.py from brightmind-ai/test: direct link, hf CLI and curl.
- Browser
- Download file 15 kB
-
https://huggingface.co/spaces/brightmind-ai/test/resolve/main/utils.py
- Command line
-
hf download hf://spaces/brightmind-ai/test/utils.py
-
curl -L -o utils.py https://huggingface.co/spaces/brightmind-ai/test/resolve/main/utils.py
15 kB
| """ | |
| 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 | |