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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Knowledge Base and Math Solver Components
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import re
|
| 6 |
+
import sympy as sp
|
| 7 |
+
from sympy import symbols, Eq, solve
|
| 8 |
+
|
| 9 |
+
class KnowledgeBase:
|
| 10 |
+
def __init__(self):
|
| 11 |
+
self.knowledge = {
|
| 12 |
+
"Biology": {
|
| 13 |
+
"photosynthesis": {
|
| 14 |
+
"definition": "Photosynthesis is the process by which plants, algae, and some bacteria convert light energy into chemical energy stored in glucose molecules.",
|
| 15 |
+
"equation": "6CO₂ + 6H₂O + light energy → C₆H₁₂O₆ + 6O₂",
|
| 16 |
+
"key_concepts": ["Light-dependent reactions", "Calvin cycle", "Chlorophyll absorption", "Glucose production"],
|
| 17 |
+
"applications": "Essential for life on Earth as it produces oxygen and forms the base of food chains.",
|
| 18 |
+
"detailed_explanation": "Photosynthesis occurs in two main stages: light reactions and Calvin cycle."
|
| 19 |
+
},
|
| 20 |
+
"genetics": {
|
| 21 |
+
"definition": "Genetics is the study of heredity and variation in living organisms through genes and DNA.",
|
| 22 |
+
"key_concepts": ["DNA", "Genes", "Chromosomes", "Inheritance", "Mutations"],
|
| 23 |
+
"applications": "Critical for medicine, agriculture, and evolutionary biology.",
|
| 24 |
+
"detailed_explanation": "Genetics explains how traits are passed from parents to offspring through DNA."
|
| 25 |
+
}
|
| 26 |
+
},
|
| 27 |
+
"Mathematics": {
|
| 28 |
+
"algebra": {
|
| 29 |
+
"definition": "Algebra uses symbols to represent unknown numbers in equations and expressions.",
|
| 30 |
+
"key_concepts": ["Variables", "Equations", "Functions", "Linear equations", "Quadratic equations"],
|
| 31 |
+
"applications": "Used in engineering, finance, science, and everyday problem-solving.",
|
| 32 |
+
"detailed_explanation": "Algebra starts with simple equations and progresses to complex systems.",
|
| 33 |
+
"examples": ["2x + 5 = 15 → x = 5", "x² - 5x + 6 = 0 → x = 2 or x = 3"]
|
| 34 |
+
},
|
| 35 |
+
"calculus": {
|
| 36 |
+
"definition": "Calculus is the study of continuous change, involving derivatives and integrals.",
|
| 37 |
+
"key_concepts": ["Limits", "Derivatives", "Integrals", "Chain Rule", "Optimization"],
|
| 38 |
+
"applications": "Essential for physics, engineering, economics, and rates of change.",
|
| 39 |
+
"detailed_explanation": "Calculus has differential and integral branches for studying change and accumulation."
|
| 40 |
+
}
|
| 41 |
+
},
|
| 42 |
+
"Physics": {
|
| 43 |
+
"mechanics": {
|
| 44 |
+
"definition": "Mechanics deals with motion and forces acting on bodies.",
|
| 45 |
+
"key_concepts": ["Force", "Motion", "Energy", "Momentum", "Newton's Laws"],
|
| 46 |
+
"applications": "Foundation for engineering, robotics, and understanding motion.",
|
| 47 |
+
"detailed_explanation": "Mechanics studies how objects move based on Newton's three laws."
|
| 48 |
+
}
|
| 49 |
+
},
|
| 50 |
+
"Chemistry": {
|
| 51 |
+
"organic_chemistry": {
|
| 52 |
+
"definition": "Organic chemistry studies carbon-containing compounds and their reactions.",
|
| 53 |
+
"key_concepts": ["Hydrocarbons", "Functional Groups", "Reactions", "Stereochemistry"],
|
| 54 |
+
"applications": "Essential for pharmaceuticals, plastics, and biochemistry.",
|
| 55 |
+
"detailed_explanation": "Organic chemistry focuses on carbon compounds forming life's basis."
|
| 56 |
+
}
|
| 57 |
+
}
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
def find_topic_match(self, query: str, subject: str) -> str:
|
| 61 |
+
"""Find the best matching topic for a query"""
|
| 62 |
+
query_lower = query.lower()
|
| 63 |
+
subject_data = self.knowledge.get(subject, {})
|
| 64 |
+
|
| 65 |
+
for topic in subject_data.keys():
|
| 66 |
+
if topic in query_lower:
|
| 67 |
+
return topic
|
| 68 |
+
|
| 69 |
+
keyword_mapping = {
|
| 70 |
+
"photosynthesis": ["photosynthesis", "plant", "chlorophyll", "light"],
|
| 71 |
+
"genetics": ["genetics", "dna", "gene", "heredity", "inheritance"],
|
| 72 |
+
"algebra": ["algebra", "equation", "variable", "solve", "x", "linear"],
|
| 73 |
+
"calculus": ["calculus", "derivative", "integral", "limit"],
|
| 74 |
+
"mechanics": ["mechanics", "force", "motion", "newton", "velocity"],
|
| 75 |
+
"organic_chemistry": ["organic", "carbon", "hydrocarbon"]
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
+
for topic, keywords in keyword_mapping.items():
|
| 79 |
+
if any(keyword in query_lower for keyword in keywords):
|
| 80 |
+
if topic in subject_data:
|
| 81 |
+
return topic
|
| 82 |
+
return None
|
| 83 |
+
|
| 84 |
+
def get_accurate_info(self, query: str, subject: str) -> dict:
|
| 85 |
+
"""Get accurate information about a topic"""
|
| 86 |
+
topic = self.find_topic_match(query, subject)
|
| 87 |
+
|
| 88 |
+
if topic and subject in self.knowledge and topic in self.knowledge[subject]:
|
| 89 |
+
return self.knowledge[subject][topic]
|
| 90 |
+
|
| 91 |
+
return {
|
| 92 |
+
"definition": f"This is an important concept in {subject} requiring systematic study.",
|
| 93 |
+
"key_concepts": ["Fundamental principles", "Core theories", "Practical applications"],
|
| 94 |
+
"applications": f"This concept has various real-world applications in {subject}.",
|
| 95 |
+
"detailed_explanation": f"Understanding this concept requires studying underlying principles in {subject}."
|
| 96 |
+
}
|
| 97 |
+
|
| 98 |
+
class MathSolver:
|
| 99 |
+
def __init__(self):
|
| 100 |
+
self.x, self.y, self.z = symbols('x y z')
|
| 101 |
+
|
| 102 |
+
def is_algebraic_equation(self, problem: str) -> bool:
|
| 103 |
+
"""Check if the problem is an algebraic equation"""
|
| 104 |
+
patterns = [
|
| 105 |
+
r'\d*[a-z]\s*[\+\-\*\/]\s*\d+\s*=\s*\d+',
|
| 106 |
+
r'solve.*for.*[a-z]',
|
| 107 |
+
r'find.*[a-z]',
|
| 108 |
+
r'[a-z]\s*='
|
| 109 |
+
]
|
| 110 |
+
return any(re.search(pattern, problem.lower()) for pattern in patterns)
|
| 111 |
+
|
| 112 |
+
def solve_algebraic_equation(self, problem: str) -> str:
|
| 113 |
+
"""Solve algebraic equations step by step"""
|
| 114 |
+
try:
|
| 115 |
+
problem_clean = problem.lower().replace('find', '').replace('solve for', '').replace('solve', '').strip()
|
| 116 |
+
|
| 117 |
+
if '=' in problem_clean:
|
| 118 |
+
left_side, right_side = problem_clean.split('=')
|
| 119 |
+
left_side, right_side = left_side.strip(), right_side.strip()
|
| 120 |
+
|
| 121 |
+
left_expr = sp.sympify(left_side)
|
| 122 |
+
right_expr = sp.sympify(right_side)
|
| 123 |
+
equation = Eq(left_expr, right_expr)
|
| 124 |
+
solution = solve(equation, self.x)
|
| 125 |
+
|
| 126 |
+
solution_text = f"**🔢 Algebraic Equation Solution**\n\n"
|
| 127 |
+
solution_text += f"**Problem:** {problem}\n\n"
|
| 128 |
+
solution_text += f"**Equation:** {left_side} = {right_side}\n\n"
|
| 129 |
+
solution_text += f"**Answer:** x = {solution[0]}\n\n"
|
| 130 |
+
|
| 131 |
+
verification = left_expr.subs(self.x, solution[0])
|
| 132 |
+
solution_text += f"**Verification:** {verification} = {right_expr} ✓\n\n"
|
| 133 |
+
solution_text += "**Key Principles:** Isolation, inverse operations, balance, verification"
|
| 134 |
+
|
| 135 |
+
return solution_text
|
| 136 |
+
except Exception as e:
|
| 137 |
+
return self.handle_algebraic_error(problem, str(e))
|
| 138 |
+
|
| 139 |
+
def handle_algebraic_error(self, problem: str, error: str) -> str:
|
| 140 |
+
"""Handle errors in algebraic equation solving"""
|
| 141 |
+
return f"""**🔢 Algebraic Equation Analysis**
|
| 142 |
+
|
| 143 |
+
**Problem:** {problem}
|
| 144 |
+
|
| 145 |
+
**Solution Approach:**
|
| 146 |
+
For Linear Equations (like ax + b = c):
|
| 147 |
+
1. Identify the equation and variable
|
| 148 |
+
2. Isolate the variable term
|
| 149 |
+
3. Solve for the variable
|
| 150 |
+
4. Check your answer
|
| 151 |
+
|
| 152 |
+
**Example:** 2x + 5 = 15 → x = 5
|
| 153 |
+
"""
|
| 154 |
+
|
| 155 |
+
def solve_arithmetic_expression(self, problem: str) -> str:
|
| 156 |
+
"""Solve arithmetic expressions"""
|
| 157 |
+
try:
|
| 158 |
+
problem_clean = re.sub(r'[^\d+\-*/().\s]', '', problem)
|
| 159 |
+
if problem_clean.strip():
|
| 160 |
+
result = eval(problem_clean)
|
| 161 |
+
return f"**🧮 Arithmetic Solution**\n\n**Problem:** {problem}\n**Answer:** {result}\n\n**Key:** Follow PEMDAS/BODMAS order of operations"
|
| 162 |
+
except:
|
| 163 |
+
return f"**🧮 Arithmetic Analysis**\n\n**Problem:** {problem}\n\n**Approach:** Break into steps, follow order of operations, verify answer"
|