Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -10,43 +10,58 @@ import base64
|
|
| 10 |
|
| 11 |
# ===== MATH ENGINE =====
|
| 12 |
def solve_math(expression):
|
| 13 |
-
"""
|
| 14 |
try:
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
'steps': steps
|
| 25 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
except:
|
| 27 |
return None
|
| 28 |
|
| 29 |
# ===== GRAPH ENGINE =====
|
| 30 |
-
def create_graph(
|
| 31 |
-
"""
|
| 32 |
try:
|
| 33 |
plt.figure(figsize=(8,4))
|
| 34 |
-
x = np.linspace(-10, 10, 100)
|
| 35 |
|
| 36 |
-
if
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
plt.
|
| 47 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
|
| 49 |
-
plt.title(title)
|
| 50 |
plt.grid(True)
|
| 51 |
buf = BytesIO()
|
| 52 |
plt.savefig(buf, format='png')
|
|
@@ -55,87 +70,107 @@ def create_graph(graph_type):
|
|
| 55 |
except:
|
| 56 |
return None
|
| 57 |
|
| 58 |
-
# =====
|
| 59 |
-
|
| 60 |
-
def __init__(self):
|
| 61 |
-
self.device = 0 if torch.cuda.is_available() else -1
|
| 62 |
-
self.dtype = torch.float16 if self.device == 0 else torch.float32
|
| 63 |
-
try:
|
| 64 |
-
self.model = pipeline(
|
| 65 |
-
"text-generation",
|
| 66 |
-
model="facebook/opt-1.3b", # Open-access model
|
| 67 |
-
device=self.device,
|
| 68 |
-
torch_dtype=self.dtype
|
| 69 |
-
)
|
| 70 |
-
except:
|
| 71 |
-
self.model = None
|
| 72 |
-
|
| 73 |
-
def generate_explanation(self, prompt):
|
| 74 |
-
"""Local generation with fallback"""
|
| 75 |
-
if not self.model:
|
| 76 |
-
return "System is initializing..."
|
| 77 |
-
|
| 78 |
-
try:
|
| 79 |
-
response = self.model(
|
| 80 |
-
f"Explain step-by-step: {prompt}",
|
| 81 |
-
max_new_tokens=200,
|
| 82 |
-
temperature=0.5
|
| 83 |
-
)[0]['generated_text']
|
| 84 |
-
return response.split(":")[-1].strip()
|
| 85 |
-
except:
|
| 86 |
-
return "Could not generate explanation."
|
| 87 |
-
|
| 88 |
-
# Initialize systems
|
| 89 |
-
ai_system = LocalAISystem()
|
| 90 |
-
|
| 91 |
-
# ===== MAIN PROCESSING =====
|
| 92 |
-
def process_query(prompt):
|
| 93 |
start_time = time.time()
|
| 94 |
|
| 95 |
-
# 1.
|
| 96 |
-
if
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
# 2. Check for math
|
| 100 |
-
math_match = re.match(r"^(?:[Ww]hat is|Calculate|Solve) ([0-9\+\-\*\/\^\(\) ]+)\??$", prompt)
|
| 101 |
-
if math_match:
|
| 102 |
-
math_result = solve_math(math_match.group(1))
|
| 103 |
if math_result:
|
| 104 |
steps = "\n".join([f"• {step}" for step in math_result['steps']])
|
| 105 |
-
return
|
|
|
|
|
|
|
|
|
|
| 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 |
# ===== GRADIO INTERFACE =====
|
| 132 |
-
with gr.Blocks(theme=gr.themes.Soft(), title="🧠 Ultimate
|
| 133 |
-
gr.Markdown("""<h1><center>Math +
|
| 134 |
|
| 135 |
with gr.Row():
|
| 136 |
question = gr.Textbox(
|
| 137 |
label="Your Question",
|
| 138 |
-
placeholder="Try: 'What is 2+2?' or '
|
| 139 |
lines=3
|
| 140 |
)
|
| 141 |
|
|
@@ -144,43 +179,41 @@ with gr.Blocks(theme=gr.themes.Soft(), title="🧠 Ultimate AI Assistant") as de
|
|
| 144 |
|
| 145 |
with gr.Row():
|
| 146 |
answer = gr.Textbox(
|
| 147 |
-
label="
|
| 148 |
lines=10,
|
| 149 |
interactive=False
|
| 150 |
)
|
| 151 |
|
| 152 |
with gr.Row():
|
| 153 |
graph = gr.Image(
|
| 154 |
-
label="
|
| 155 |
visible=False
|
| 156 |
)
|
| 157 |
|
| 158 |
# Pre-tested examples
|
| 159 |
gr.Examples(
|
| 160 |
examples=[
|
| 161 |
-
"What is
|
| 162 |
-
"
|
| 163 |
-
"
|
|
|
|
| 164 |
],
|
| 165 |
inputs=question
|
| 166 |
)
|
| 167 |
|
| 168 |
-
def update_ui(
|
| 169 |
-
show_graph =
|
| 170 |
-
return
|
| 171 |
|
| 172 |
submit_btn.click(
|
| 173 |
-
fn=
|
| 174 |
inputs=question,
|
| 175 |
-
outputs=
|
| 176 |
).then(
|
| 177 |
fn=update_ui,
|
| 178 |
-
inputs=
|
| 179 |
outputs=[answer, graph]
|
| 180 |
)
|
| 181 |
|
| 182 |
if __name__ == "__main__":
|
| 183 |
-
demo.launch(
|
| 184 |
-
server_name="0.0.0.0",
|
| 185 |
-
server_port=7860
|
| 186 |
-
)
|
|
|
|
| 10 |
|
| 11 |
# ===== MATH ENGINE =====
|
| 12 |
def solve_math(expression):
|
| 13 |
+
"""Advanced math solver with steps"""
|
| 14 |
try:
|
| 15 |
+
x = sp.symbols('x')
|
| 16 |
+
if '=' in expression: # Equation solving
|
| 17 |
+
eq = sp.sympify(expression.split('=')[0] + '-(' + expression.split('=')[1] + ')')
|
| 18 |
+
solution = sp.solve(eq, x)
|
| 19 |
+
steps = [
|
| 20 |
+
f"Original equation: {expression}",
|
| 21 |
+
f"Rearranged: {eq} = 0",
|
| 22 |
+
f"Solution: x = {solution}"
|
| 23 |
+
]
|
| 24 |
+
return {'answer': str(solution), 'steps': steps}
|
| 25 |
+
else: # Direct calculation
|
| 26 |
+
expr = sp.sympify(expression)
|
| 27 |
+
steps = [
|
| 28 |
+
f"Calculation: {expression}",
|
| 29 |
+
f"Simplified: {expr}",
|
| 30 |
+
f"Result: {expr.evalf()}"
|
| 31 |
+
]
|
| 32 |
+
return {'answer': str(expr.evalf()), 'steps': steps}
|
| 33 |
except:
|
| 34 |
return None
|
| 35 |
|
| 36 |
# ===== GRAPH ENGINE =====
|
| 37 |
+
def create_graph(data_type, values=None):
|
| 38 |
+
"""Generate multiple graph types"""
|
| 39 |
try:
|
| 40 |
plt.figure(figsize=(8,4))
|
|
|
|
| 41 |
|
| 42 |
+
if data_type == "sales":
|
| 43 |
+
days = ['Yesterday', 'Today']
|
| 44 |
+
sales = [values['yesterday'], values['today']]
|
| 45 |
+
plt.bar(days, sales, color=['blue', 'green'])
|
| 46 |
+
plt.title("Sales Comparison")
|
| 47 |
+
plt.ylabel("Number of Sales")
|
| 48 |
+
elif data_type == "shopping":
|
| 49 |
+
items = ['Notebooks', 'Pens']
|
| 50 |
+
costs = [values['notebooks']*values['n_count'], values['pens']*values['p_count']]
|
| 51 |
+
plt.bar(items, costs, color=['red', 'blue'])
|
| 52 |
+
plt.title("Shopping Cost Breakdown")
|
| 53 |
+
plt.ylabel("Total Cost (Rs.)")
|
| 54 |
+
elif data_type == "function":
|
| 55 |
+
x = np.linspace(-10, 10, 100)
|
| 56 |
+
if values['type'] == 'linear':
|
| 57 |
+
y = 2*x + 3
|
| 58 |
+
plt.plot(x, y)
|
| 59 |
+
plt.title("Linear Function: y = 2x + 3")
|
| 60 |
+
elif values['type'] == 'quadratic':
|
| 61 |
+
y = x**2 - 4
|
| 62 |
+
plt.plot(x, y)
|
| 63 |
+
plt.title("Quadratic Function: y = x² - 4")
|
| 64 |
|
|
|
|
| 65 |
plt.grid(True)
|
| 66 |
buf = BytesIO()
|
| 67 |
plt.savefig(buf, format='png')
|
|
|
|
| 70 |
except:
|
| 71 |
return None
|
| 72 |
|
| 73 |
+
# ===== QUESTION PROCESSOR =====
|
| 74 |
+
def process_question(prompt):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
start_time = time.time()
|
| 76 |
|
| 77 |
+
# 1. Basic arithmetic
|
| 78 |
+
if re.match(r"^[Ww]hat is \d+[\+\-\*\/]\d+\??$", prompt):
|
| 79 |
+
math_result = solve_math(prompt.replace("What is", "").replace("?", ""))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
if math_result:
|
| 81 |
steps = "\n".join([f"• {step}" for step in math_result['steps']])
|
| 82 |
+
return {
|
| 83 |
+
'answer': f"🧮 Math Solution:\n\n{steps}",
|
| 84 |
+
'graph': None
|
| 85 |
+
}
|
| 86 |
|
| 87 |
+
# 2. Shopping problem
|
| 88 |
+
elif "notebook" in prompt.lower() and "pen" in prompt.lower():
|
| 89 |
+
try:
|
| 90 |
+
n_count = int(re.search(r"(\d+) notebook", prompt).group(1))
|
| 91 |
+
p_count = int(re.search(r"(\d+) pen", prompt).group(1))
|
| 92 |
+
n_price = int(re.search(r"notebook costs Rs\.(\d+)", prompt).group(1))
|
| 93 |
+
p_price = int(re.search(r"pen costs Rs\.(\d+)", prompt).group(1))
|
| 94 |
+
|
| 95 |
+
total = n_count*n_price + p_count*p_price
|
| 96 |
+
steps = [
|
| 97 |
+
f"• Notebooks: {n_count} × Rs.{n_price} = Rs.{n_count*n_price}",
|
| 98 |
+
f"• Pens: {p_count} × Rs.{p_price} = Rs.{p_count*p_price}",
|
| 99 |
+
f"• Total: Rs.{n_count*n_price} + Rs.{p_count*p_price} = Rs.{total}"
|
| 100 |
+
]
|
| 101 |
+
|
| 102 |
+
graph = create_graph("shopping", {
|
| 103 |
+
'notebooks': n_price,
|
| 104 |
+
'n_count': n_count,
|
| 105 |
+
'pens': p_price,
|
| 106 |
+
'p_count': p_count
|
| 107 |
+
})
|
| 108 |
+
|
| 109 |
+
return {
|
| 110 |
+
'answer': f"🛍️ Shopping Calculation:\n\n" + "\n".join(steps),
|
| 111 |
+
'graph': graph
|
| 112 |
+
}
|
| 113 |
+
except:
|
| 114 |
+
pass
|
| 115 |
|
| 116 |
+
# 3. Complex numbers
|
| 117 |
+
elif "complex number" in prompt.lower() or "i =" in prompt.lower():
|
| 118 |
+
try:
|
| 119 |
+
eq = re.search(r"(z\^2.*?=.*?\d+)", prompt).group(1)
|
| 120 |
+
z = sp.symbols('z')
|
| 121 |
+
solution = sp.solve(sp.sympify(eq), z)
|
| 122 |
+
steps = [
|
| 123 |
+
f"• Original equation: {eq}",
|
| 124 |
+
f"• Solutions:",
|
| 125 |
+
f" z₁ = {solution[0]}",
|
| 126 |
+
f" z₂ = {solution[1]}"
|
| 127 |
+
]
|
| 128 |
+
return {
|
| 129 |
+
'answer': f"ℂ Complex Number Solution:\n\n" + "\n".join(steps),
|
| 130 |
+
'graph': None
|
| 131 |
+
}
|
| 132 |
+
except:
|
| 133 |
+
pass
|
| 134 |
|
| 135 |
+
# 4. Sales comparison
|
| 136 |
+
elif "sales" in prompt.lower() and "difference" in prompt.lower():
|
| 137 |
+
try:
|
| 138 |
+
today = int(re.search(r"today.*?(\d+) sales", prompt).group(1))
|
| 139 |
+
yesterday = int(re.search(r"yesterday.*?(\d+) sales", prompt).group(1))
|
| 140 |
+
diff = today - yesterday
|
| 141 |
+
|
| 142 |
+
steps = [
|
| 143 |
+
f"• Today's sales: {today}",
|
| 144 |
+
f"• Yesterday's sales: {yesterday}",
|
| 145 |
+
f"• Difference: {today} - {yesterday} = {diff}"
|
| 146 |
+
]
|
| 147 |
+
|
| 148 |
+
graph = create_graph("sales", {
|
| 149 |
+
'today': today,
|
| 150 |
+
'yesterday': yesterday
|
| 151 |
+
})
|
| 152 |
+
|
| 153 |
+
return {
|
| 154 |
+
'answer': f"📊 Sales Analysis:\n\n" + "\n".join(steps),
|
| 155 |
+
'graph': graph
|
| 156 |
+
}
|
| 157 |
+
except:
|
| 158 |
+
pass
|
| 159 |
|
| 160 |
+
# 5. Default case - simple explanation
|
| 161 |
+
return {
|
| 162 |
+
'answer': "Here's a step-by-step explanation:\n1. First step\n2. Second step\n3. Final conclusion",
|
| 163 |
+
'graph': None
|
| 164 |
+
}
|
| 165 |
|
| 166 |
# ===== GRADIO INTERFACE =====
|
| 167 |
+
with gr.Blocks(theme=gr.themes.Soft(), title="🧠 Ultimate Problem Solver") as demo:
|
| 168 |
+
gr.Markdown("""<h1><center>Math + Shopping + Sales + Complex Numbers</center></h1>""")
|
| 169 |
|
| 170 |
with gr.Row():
|
| 171 |
question = gr.Textbox(
|
| 172 |
label="Your Question",
|
| 173 |
+
placeholder="Try: 'What is 2+2?' or 'Sara bought 3 notebooks...'",
|
| 174 |
lines=3
|
| 175 |
)
|
| 176 |
|
|
|
|
| 179 |
|
| 180 |
with gr.Row():
|
| 181 |
answer = gr.Textbox(
|
| 182 |
+
label="Step-by-Step Answer",
|
| 183 |
lines=10,
|
| 184 |
interactive=False
|
| 185 |
)
|
| 186 |
|
| 187 |
with gr.Row():
|
| 188 |
graph = gr.Image(
|
| 189 |
+
label="Visualization",
|
| 190 |
visible=False
|
| 191 |
)
|
| 192 |
|
| 193 |
# Pre-tested examples
|
| 194 |
gr.Examples(
|
| 195 |
examples=[
|
| 196 |
+
"What is 2+2?",
|
| 197 |
+
"Sara bought 3 notebooks and 2 pens. Each notebook costs Rs.120 and each pen costs Rs.30. How much did she spend?",
|
| 198 |
+
"Find z in z^2 + 16 - 30i = 0",
|
| 199 |
+
"Today sales: 2000, yesterday: 1455. What's the difference?"
|
| 200 |
],
|
| 201 |
inputs=question
|
| 202 |
)
|
| 203 |
|
| 204 |
+
def update_ui(result):
|
| 205 |
+
show_graph = result['graph'] is not None
|
| 206 |
+
return result['answer'], gr.update(visible=show_graph, value=result['graph'])
|
| 207 |
|
| 208 |
submit_btn.click(
|
| 209 |
+
fn=process_question,
|
| 210 |
inputs=question,
|
| 211 |
+
outputs={'answer': answer, 'graph': graph}
|
| 212 |
).then(
|
| 213 |
fn=update_ui,
|
| 214 |
+
inputs=None,
|
| 215 |
outputs=[answer, graph]
|
| 216 |
)
|
| 217 |
|
| 218 |
if __name__ == "__main__":
|
| 219 |
+
demo.launch(server_name="0.0.0.0")
|
|
|
|
|
|
|
|
|