shukdevdattaEX commited on
Commit
2789611
·
verified ·
1 Parent(s): ed2c5a7

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +278 -0
app.py ADDED
@@ -0,0 +1,278 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ import re
4
+ import time
5
+ import base64 # image has to be converted to base64
6
+ from openai import OpenAI #openrouter access
7
+ from together import Together
8
+ from PIL import Image #pillow for image processing
9
+ import io
10
+
11
+ ### function to create math solution from math problem text
12
+ def generate_math_solution_openrouter(api_key, problem_text, history=None):
13
+ if not api_key.strip():
14
+ return "Please enter your OpenRouter API key.", history
15
+
16
+ if not problem_text.strip():
17
+ return "Please enter a math problem so that I can solve it for you!",
18
+
19
+ try:
20
+
21
+ client=OpenAI(
22
+ base_url="https://openrouter.ai/api/v1",
23
+ api_key=api_key,
24
+ )
25
+
26
+ messages= [
27
+ {"role": "system", "content":
28
+ """You are an expert math tutor who explains concepts clearly and thoroughly.
29
+ Analyze the given math problem and provide a detailed step-by-step solution.
30
+ For each step:
31
+ 1. Show the mathematical operation
32
+ 2. Explain why this step is necessary
33
+ 3. Connect it to relevant mathematical concepts
34
+
35
+ Format your response with clear section headers using markdown.
36
+ Begin with an "Initial Analysis" section, follow with numbered steps,
37
+ and conclude with a "Final Answer" section."""},
38
+ ]
39
+
40
+ if history: #conversation history maintain and update
41
+ for exchange in history:
42
+ messages.append({"role": "user", "content": exchange[0]}) #asks a math prob
43
+ if exchange[1]: # Check if there's a response
44
+ messages.append({"role": "assistant", "content": exchange[1]}) #AI responses with a solution
45
+
46
+ # Add the current problem
47
+ messages.append({"role": "user", "content": f"Solve this math problem step-by-step: {problem_text}"}) ## Solve this math problem step-by-step: {what is 2+2?}
48
+
49
+ completion=client.chat.completions.create(
50
+ model="minimax/minimax-m2:free",
51
+ messages=messages,
52
+ extra_headers={
53
+ "HTTP-Referer": "https://advancedmathtutor.edu",
54
+ "X-Title": "Advanced Math Tutor",
55
+ }
56
+ )
57
+
58
+ solution=completion.choices[0].message.content
59
+
60
+ # Update history
61
+ if history is None: #no convo (new open)
62
+ history = [] #my all convo saved here
63
+ history.append((problem_text, solution)) #now i update my convo history
64
+
65
+ return solution, history
66
+
67
+ except Exception as e:
68
+ error_message = f"Error: {str(e)}"
69
+ return error_message, history
70
+
71
+ #image processing
72
+
73
+ def image_to_base64(image_path):
74
+ if image_path is None:
75
+ return None
76
+
77
+ try:
78
+ with open(image_path, "rb") as img_file:
79
+ return base64.b64encode(img_file.read()).decode("utf-8")
80
+ except Exception as e:
81
+ print(f"Error converting image to base64: {str(e)}")
82
+ return None
83
+
84
+ def generate_math_solution_together(api_key, problem_text, image_path=None, history=None):
85
+ if not api_key.strip():
86
+ return "Please enter your Together AI API key.", history
87
+
88
+ if not problem_text.strip() and image_path is None:
89
+ return "Please enter a math problem or upload an image of a math problem.", history
90
+
91
+ try:
92
+ client = Together(api_key=api_key)
93
+
94
+ messages= [
95
+ {"role": "system", "content":
96
+ """You are an expert math tutor who explains concepts clearly and thoroughly.
97
+ Analyze the given math problem and provide a detailed step-by-step solution.
98
+ For each step:
99
+ 1. Show the mathematical operation
100
+ 2. Explain why this step is necessary
101
+ 3. Connect it to relevant mathematical concepts
102
+
103
+ Format your response with clear section headers using markdown.
104
+ Begin with an "Initial Analysis" section, follow with numbered steps,
105
+ and conclude with a "Final Answer" section."""},
106
+ ]
107
+
108
+ # Add conversation history if it exists
109
+ if history:
110
+ for exchange in history:
111
+ messages.append({"role": "user", "content": exchange[0]})
112
+ if exchange[1]: # Check if there's a response
113
+ messages.append({"role": "assistant", "content": exchange[1]})
114
+
115
+ # Prepare the user message content
116
+ user_message_content = [] # We are going to add some instructions regarding how to solve the math problem in the image #image+instruction, image
117
+
118
+ # calculate the area of a circle with radius 6 cm (Image of a problem)
119
+
120
+ #problem text / user message = Before calculating area convert radius of 6 cm to meter first
121
+
122
+ # Add text content if provided
123
+ if problem_text.strip(): #image+instruction
124
+ user_message_content.append({
125
+ "type": "text",
126
+ "text": f"Solve this math problem: {problem_text}" #Before calculating area convert radius of 6 cm to meter first (image + #Before calculating area convert radius of 6 cm to meter first)
127
+ })
128
+ else: #image
129
+ user_message_content.append({
130
+ "type": "text",
131
+ "text": "Solve this math problem from the image:"
132
+ })
133
+
134
+ # Add image if provided
135
+ if image_path:
136
+ # Convert image to base64
137
+ base64_image = image_to_base64(image_path)
138
+ if base64_image:
139
+ user_message_content.append({
140
+ "type": "image_url",
141
+ "image_url": {
142
+ "url": f"data:image/jpeg;base64,{base64_image}"
143
+ }
144
+ })
145
+
146
+ # Add the user message with content
147
+ messages.append({
148
+ "role": "user", #conversation saved with image data+usermessage/instruction
149
+ "content": user_message_content
150
+ })
151
+
152
+ response=client.chat.completions.create( #Together
153
+ model="ServiceNow-AI/Apriel-1.5-15b-Thinker",
154
+ messages=messages,
155
+ stream=False
156
+ )
157
+
158
+ solution=response.choices[0].message.content #problem----> ans syntax
159
+
160
+ # Update history - for simplicity, just store the text problem
161
+ if history is None:
162
+ history = []
163
+ history.append((problem_text if problem_text.strip() else "Image problem", solution))
164
+
165
+ return solution, history
166
+
167
+ except Exception as e:
168
+ error_message = f"Error: {str(e)}"
169
+ return error_message, history
170
+
171
+ def create_demo(): #interface design complete
172
+ with gr.Blocks(theme=gr.themes.Ocean(primary_hue="blue")) as demo:
173
+ gr.Markdown("# 📚 Advanced Math Tutor")
174
+ gr.Markdown("""
175
+ This application provides step-by-step solutions to math problems using advanced AI models.
176
+ """)
177
+
178
+ with gr.Tabs():
179
+ with gr.TabItem("Text Problem Solver (OpenRouter)"):
180
+ with gr.Row():
181
+ with gr.Column(scale=1): #left side column design complete
182
+ openrouter_api_key = gr.Textbox(
183
+ label="OpenRouter API Key",
184
+ placeholder="Enter your OpenRouter API key (starts with sk-or-)",
185
+ type="password"
186
+ )
187
+ text_problem_input = gr.Textbox(
188
+ label="Math Problem",
189
+ placeholder="Enter your math problem here...", #Solve the quadratic equation: 3x² + 5x - 2 = 0"
190
+ lines=5
191
+ )
192
+ example_problems = gr.Examples(
193
+ examples=[
194
+ ["Solve the quadratic equation: 3x² + 5x - 2 = 0"],
195
+ ["Find the derivative of f(x) = x³ln(x)"],
196
+ ["Calculate the area of a circle with radius 5 cm"],
197
+ ["Find all values of x that satisfy the equation: log₂(x-1) + log₂(x+3) = 5"]
198
+ ],
199
+ inputs=[text_problem_input],
200
+ label="Example Problems"
201
+ )
202
+ with gr.Row():
203
+ openrouter_submit_btn = gr.Button("Solve Problem", variant="primary")
204
+ openrouter_clear_btn = gr.Button("Clear")
205
+
206
+ with gr.Column(scale=2):
207
+ openrouter_solution_output = gr.Markdown(label="Solution")
208
+
209
+ # Store conversation history (invisible to user)
210
+ openrouter_conversation_history = gr.State(value=None)
211
+
212
+ # Button actions
213
+ openrouter_submit_btn.click(
214
+ fn=generate_math_solution_openrouter, #text problem solve
215
+ inputs=[openrouter_api_key, text_problem_input, openrouter_conversation_history],
216
+ outputs=[openrouter_solution_output, openrouter_conversation_history]
217
+ )
218
+
219
+ openrouter_clear_btn.click(
220
+ fn=lambda: ("", None),
221
+ inputs=[],
222
+ outputs=[openrouter_solution_output, openrouter_conversation_history]
223
+ )
224
+
225
+ with gr.TabItem("Image Problem Solver (Together AI)"):
226
+ with gr.Row():
227
+ with gr.Column(scale=1):
228
+ together_api_key = gr.Textbox(
229
+ label="Together AI API Key",
230
+ placeholder="Enter your Together AI API key",
231
+ type="password"
232
+ )
233
+ together_problem_input = gr.Textbox(
234
+ label="Problem Description/Instruction (Optional)",
235
+ placeholder="Enter additional context for the image problem...",
236
+ lines=3
237
+ )
238
+ together_image_input = gr.Image(
239
+ label="Upload Math Problem Image",
240
+ type="filepath"
241
+ )
242
+ with gr.Row():
243
+ together_submit_btn = gr.Button("Solve Problem", variant="primary")
244
+ together_clear_btn = gr.Button("Clear")
245
+
246
+ with gr.Column(scale=2):
247
+ together_solution_output = gr.Markdown(label="Solution")
248
+
249
+ # Store conversation history (invisible to user)
250
+ together_conversation_history = gr.State(value=None)
251
+
252
+ # Button actions
253
+ together_submit_btn.click(
254
+ fn=generate_math_solution_together,
255
+ inputs=[together_api_key, together_problem_input, together_image_input, together_conversation_history],
256
+ outputs=[together_solution_output, together_conversation_history]
257
+ )
258
+
259
+ together_clear_btn.click(
260
+ fn=lambda: ("", None),
261
+ inputs=[],
262
+ outputs=[together_solution_output, together_conversation_history]
263
+ )
264
+
265
+
266
+ # Footer
267
+ gr.Markdown("""
268
+ ---
269
+ ### About
270
+ blah blah
271
+ """)
272
+
273
+ return demo
274
+
275
+ # Launch the app
276
+ if __name__ == "__main__":
277
+ demo = create_demo()
278
+ demo.launch()