Scaryscar commited on
Commit
d540dda
·
verified ·
1 Parent(s): a32b332

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +90 -198
app.py CHANGED
@@ -1,219 +1,111 @@
1
- import gradio as gr
2
  import torch
 
 
3
  import time
4
  import matplotlib.pyplot as plt
5
  import numpy as np
6
- import re
7
- import sympy as sp
8
  from io import BytesIO
9
  import base64
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')
68
- plt.close()
69
- return f"data:image/png;base64,{base64.b64encode(buf.getvalue()).decode('utf-8')}"
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
 
177
- with gr.Row():
178
- submit_btn = gr.Button("Get Answer", variant="primary")
 
 
 
 
 
 
 
 
 
 
 
 
 
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")
 
 
1
  import torch
2
+ from transformers import AutoTokenizer, AutoModelForCausalLM
3
+ import gradio as gr
4
  import time
5
  import matplotlib.pyplot as plt
6
  import numpy as np
 
 
7
  from io import BytesIO
8
  import base64
9
 
10
+ # Check for GPU availability and set device
11
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
12
+ print(f"Using device: {device}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
 
14
+ # Load model and tokenizer with error handling
15
+ try:
16
+ tokenizer = AutoTokenizer.from_pretrained("google/gemma-2-2b-it")
17
+ model = AutoModelForCausalLM.from_pretrained(
18
+ "google/gemma-2-2b-it",
19
+ torch_dtype=torch.float16 if device.type == "cuda" else torch.float32,
20
+ device_map="auto"
21
+ )
22
+ print("Model and tokenizer loaded successfully")
23
+ except Exception as e:
24
+ print(f"Error loading model: {e}")
25
+ raise
26
+
27
+ def generate_response(prompt):
28
  try:
29
+ start_time = time.time()
30
 
31
+ # Format the prompt for step-by-step explanation
32
+ formatted_prompt = f"📝 Provide a detailed, step-by-step solution to the following:\n{prompt}\n\nStep-by-Step Solution:"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
 
34
+ input_ids = tokenizer(formatted_prompt, return_tensors="pt").to(device)
35
+
36
+ # Generate response with optimized parameters for speed
37
+ outputs = model.generate(
38
+ **input_ids,
39
+ max_new_tokens=1000,
40
+ temperature=0.7,
41
+ do_sample=True,
42
+ top_k=50,
43
+ top_p=0.95,
44
+ pad_token_id=tokenizer.eos_token_id
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
  )
46
+
47
+ response = tokenizer.decode(outputs[0], skip_special_tokens=True)
48
+
49
+ # Remove the input prompt from the response
50
+ response = response.replace(formatted_prompt, "").strip()
51
+
52
+ # Generate time measurement
53
+ gen_time = time.time() - start_time
54
+
55
+ # Add visualization for numerical comparisons
56
+ if "difference between" in prompt.lower() or "compare" in prompt.lower():
57
+ try:
58
+ # Extract numbers from prompt
59
+ numbers = [int(s) for s in prompt.split() if s.isdigit()]
60
+ if len(numbers) >= 2:
61
+ labels = ['Today', 'Yesterday'] if 'today' in prompt.lower() else ['Value 1', 'Value 2']
62
+ plt.figure(figsize=(6,4))
63
+ plt.bar(labels, numbers, color=['blue', 'orange'])
64
+ plt.title("Comparison Visualization")
65
+ plt.ylabel("Count")
66
+
67
+ # Save plot to bytes
68
+ buf = BytesIO()
69
+ plt.savefig(buf, format='png')
70
+ buf.seek(0)
71
+ img_str = base64.b64encode(buf.read()).decode('utf-8')
72
+ plt.close()
73
+
74
+ # Add image to response
75
+ response += f"\n\n![Comparison Chart](data:image/png;base64,{img_str})"
76
+ except:
77
+ pass
78
+
79
+ return f"{response}\n\n⏱️ Generated in {gen_time:.2f} seconds"
80
 
81
+ except Exception as e:
82
+ return f"Error generating response: {str(e)}"
83
+
84
+ # Example questions
85
+ examples = [
86
+ "What is 2+2? Give answer step by step.",
87
+ "Sara bought 3 notebooks and two pens. Each notebook costs Rs.120 and each pen costs Rs.30. How much money did Sara spend in total?",
88
+ "Find the value of z in the equation z^2 + 16 - 30i = 0, where z is a complex number in the form a + bi.",
89
+ "If today a company makes 2000 sales and yesterday it made 1455 sales, what is the difference between them? Explain with a graph."
90
+ ]
91
+
92
+ # Create Gradio interface
93
+ with gr.Blocks(title="Step-by-Step Problem Solver") as demo:
94
+ gr.Markdown("# 📝 Step-by-Step Problem Solver")
95
+ gr.Markdown("Get detailed, step-by-step solutions to math, word, and complex problems.")
96
 
97
  with gr.Row():
98
+ input_prompt = gr.Textbox(label="Enter your problem", placeholder="Type your question here...", lines=3)
99
+ output_response = gr.Markdown(label="Step-by-Step Solution")
 
 
 
100
 
101
  with gr.Row():
102
+ submit_btn = gr.Button("Generate Solution", variant="primary")
103
+ clear_btn = gr.Button("Clear")
 
 
104
 
105
+ gr.Examples(examples=examples, inputs=input_prompt, label="Example Questions")
 
 
 
 
 
 
 
 
 
 
 
 
 
106
 
107
+ submit_btn.click(fn=generate_response, inputs=input_prompt, outputs=output_response)
108
+ clear_btn.click(lambda: ("", ""), outputs=[input_prompt, output_response])
 
 
 
 
 
 
 
109
 
110
  if __name__ == "__main__":
111
+ demo.launch(server_name="0.0.0.0", server_port=7860)