Spaces:
Running
Running
| """ | |
| Knowledge Base and Math Solver Components | |
| """ | |
| import re | |
| import sympy as sp | |
| from sympy import symbols, Eq, solve | |
| class KnowledgeBase: | |
| def __init__(self): | |
| self.knowledge = { | |
| "Biology": { | |
| "photosynthesis": { | |
| "definition": "Photosynthesis is the process by which plants, algae, and some bacteria convert light energy into chemical energy stored in glucose molecules.", | |
| "equation": "6CO₂ + 6H₂O + light energy → C₆H₁₂O₆ + 6O₂", | |
| "key_concepts": ["Light-dependent reactions", "Calvin cycle", "Chlorophyll absorption", "Glucose production"], | |
| "applications": "Essential for life on Earth as it produces oxygen and forms the base of food chains.", | |
| "detailed_explanation": "Photosynthesis occurs in two main stages: light reactions and Calvin cycle." | |
| }, | |
| "genetics": { | |
| "definition": "Genetics is the study of heredity and variation in living organisms through genes and DNA.", | |
| "key_concepts": ["DNA", "Genes", "Chromosomes", "Inheritance", "Mutations"], | |
| "applications": "Critical for medicine, agriculture, and evolutionary biology.", | |
| "detailed_explanation": "Genetics explains how traits are passed from parents to offspring through DNA." | |
| } | |
| }, | |
| "Mathematics": { | |
| "algebra": { | |
| "definition": "Algebra uses symbols to represent unknown numbers in equations and expressions.", | |
| "key_concepts": ["Variables", "Equations", "Functions", "Linear equations", "Quadratic equations"], | |
| "applications": "Used in engineering, finance, science, and everyday problem-solving.", | |
| "detailed_explanation": "Algebra starts with simple equations and progresses to complex systems.", | |
| "examples": ["2x + 5 = 15 → x = 5", "x² - 5x + 6 = 0 → x = 2 or x = 3"] | |
| }, | |
| "calculus": { | |
| "definition": "Calculus is the study of continuous change, involving derivatives and integrals.", | |
| "key_concepts": ["Limits", "Derivatives", "Integrals", "Chain Rule", "Optimization"], | |
| "applications": "Essential for physics, engineering, economics, and rates of change.", | |
| "detailed_explanation": "Calculus has differential and integral branches for studying change and accumulation." | |
| } | |
| }, | |
| "Physics": { | |
| "mechanics": { | |
| "definition": "Mechanics deals with motion and forces acting on bodies.", | |
| "key_concepts": ["Force", "Motion", "Energy", "Momentum", "Newton's Laws"], | |
| "applications": "Foundation for engineering, robotics, and understanding motion.", | |
| "detailed_explanation": "Mechanics studies how objects move based on Newton's three laws." | |
| } | |
| }, | |
| "Chemistry": { | |
| "organic_chemistry": { | |
| "definition": "Organic chemistry studies carbon-containing compounds and their reactions.", | |
| "key_concepts": ["Hydrocarbons", "Functional Groups", "Reactions", "Stereochemistry"], | |
| "applications": "Essential for pharmaceuticals, plastics, and biochemistry.", | |
| "detailed_explanation": "Organic chemistry focuses on carbon compounds forming life's basis." | |
| } | |
| } | |
| } | |
| def find_topic_match(self, query: str, subject: str) -> str: | |
| """Find the best matching topic for a query""" | |
| query_lower = query.lower() | |
| subject_data = self.knowledge.get(subject, {}) | |
| for topic in subject_data.keys(): | |
| if topic in query_lower: | |
| return topic | |
| keyword_mapping = { | |
| "photosynthesis": ["photosynthesis", "plant", "chlorophyll", "light"], | |
| "genetics": ["genetics", "dna", "gene", "heredity", "inheritance"], | |
| "algebra": ["algebra", "equation", "variable", "solve", "x", "linear"], | |
| "calculus": ["calculus", "derivative", "integral", "limit"], | |
| "mechanics": ["mechanics", "force", "motion", "newton", "velocity"], | |
| "organic_chemistry": ["organic", "carbon", "hydrocarbon"] | |
| } | |
| for topic, keywords in keyword_mapping.items(): | |
| if any(keyword in query_lower for keyword in keywords): | |
| if topic in subject_data: | |
| return topic | |
| return None | |
| def get_accurate_info(self, query: str, subject: str) -> dict: | |
| """Get accurate information about a topic""" | |
| topic = self.find_topic_match(query, subject) | |
| if topic and subject in self.knowledge and topic in self.knowledge[subject]: | |
| return self.knowledge[subject][topic] | |
| return { | |
| "definition": f"This is an important concept in {subject} requiring systematic study.", | |
| "key_concepts": ["Fundamental principles", "Core theories", "Practical applications"], | |
| "applications": f"This concept has various real-world applications in {subject}.", | |
| "detailed_explanation": f"Understanding this concept requires studying underlying principles in {subject}." | |
| } | |
| class MathSolver: | |
| def __init__(self): | |
| self.x, self.y, self.z = symbols('x y z') | |
| def is_algebraic_equation(self, problem: str) -> bool: | |
| """Check if the problem is an algebraic equation""" | |
| patterns = [ | |
| r'\d*[a-z]\s*[\+\-\*\/]\s*\d+\s*=\s*\d+', | |
| r'solve.*for.*[a-z]', | |
| r'find.*[a-z]', | |
| r'[a-z]\s*=' | |
| ] | |
| return any(re.search(pattern, problem.lower()) for pattern in patterns) | |
| def solve_algebraic_equation(self, problem: str) -> str: | |
| """Solve algebraic equations step by step""" | |
| try: | |
| problem_clean = problem.lower().replace('find', '').replace('solve for', '').replace('solve', '').strip() | |
| if '=' in problem_clean: | |
| left_side, right_side = problem_clean.split('=') | |
| left_side, right_side = left_side.strip(), right_side.strip() | |
| left_expr = sp.sympify(left_side) | |
| right_expr = sp.sympify(right_side) | |
| equation = Eq(left_expr, right_expr) | |
| solution = solve(equation, self.x) | |
| solution_text = f"**🔢 Algebraic Equation Solution**\n\n" | |
| solution_text += f"**Problem:** {problem}\n\n" | |
| solution_text += f"**Equation:** {left_side} = {right_side}\n\n" | |
| solution_text += f"**Answer:** x = {solution[0]}\n\n" | |
| verification = left_expr.subs(self.x, solution[0]) | |
| solution_text += f"**Verification:** {verification} = {right_expr} ✓\n\n" | |
| solution_text += "**Key Principles:** Isolation, inverse operations, balance, verification" | |
| return solution_text | |
| except Exception as e: | |
| return self.handle_algebraic_error(problem, str(e)) | |
| def handle_algebraic_error(self, problem: str, error: str) -> str: | |
| """Handle errors in algebraic equation solving""" | |
| return f"""**🔢 Algebraic Equation Analysis** | |
| **Problem:** {problem} | |
| **Solution Approach:** | |
| For Linear Equations (like ax + b = c): | |
| 1. Identify the equation and variable | |
| 2. Isolate the variable term | |
| 3. Solve for the variable | |
| 4. Check your answer | |
| **Example:** 2x + 5 = 15 → x = 5 | |
| """ | |
| def solve_arithmetic_expression(self, problem: str) -> str: | |
| """Solve arithmetic expressions""" | |
| try: | |
| problem_clean = re.sub(r'[^\d+\-*/().\s]', '', problem) | |
| if problem_clean.strip(): | |
| result = eval(problem_clean) | |
| return f"**🧮 Arithmetic Solution**\n\n**Problem:** {problem}\n**Answer:** {result}\n\n**Key:** Follow PEMDAS/BODMAS order of operations" | |
| except: | |
| return f"**🧮 Arithmetic Analysis**\n\n**Problem:** {problem}\n\n**Approach:** Break into steps, follow order of operations, verify answer" | |