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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
|
|
|
|
| 20 |
base_url="https://openrouter.ai/api/v1",
|
| 21 |
api_key=api_key,
|
| 22 |
)
|
| 23 |
+
messages= [
|
| 24 |
+
{ "role": "system", "content":
|
| 25 |
+
"""You are a very smart math tutor who can able to solve math and give proper explanations clearly and in a precise manner.
|
| 26 |
+
You can analyze the math problem given to you and provide the details solution step by step.
|
| 27 |
+
For every step:
|
| 28 |
+
1. Show all the mathematical explanations.
|
| 29 |
+
2. Explain each step and its necessity.
|
| 30 |
+
3. Connect it to the relevant mathematical concept.
|
| 31 |
+
Format your response with clear section of headers using markdown and comment if necessary.
|
| 32 |
+
Begin with a section of analysis named "Initail step" and followed number of step and conclude with "Final step" section.
|
| 33 |
+
"""},
|
| 34 |
+
]
|
| 35 |
+
|
| 36 |
+
if history:
|
| 37 |
+
for exchange in history:
|
| 38 |
+
messages.append({"role":"user","content":exchange[0]}) #@ task a math problem
|
| 39 |
+
if exchange[1]: # check if there is a problem
|
| 40 |
+
messages.append({"role": "assistant","content": exchange[1]}) # AI response with solution.
|
| 41 |
+
|
| 42 |
+
messages.append({"role":"user","content":f"Solve the given math problem step-by-step: {prob_text}"}) # math problem
|
| 43 |
+
|
| 44 |
+
completion = client.chat.completions.create(
|
| 45 |
+
model= "openai/gpt-4o",
|
| 46 |
+
message= messages,
|
| 47 |
+
extra_headers={
|
| 48 |
+
"HTTP-Referer": "https://smartmathtutor.edu", # Optional. Site URL for rankings on openrouter.ai.
|
| 49 |
+
"X-Title": "Smart Math Tutor", # Optional. Site title for rankings on openrouter.ai.
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
solution = completion.choices[0].message.content
|
| 55 |
+
|
| 56 |
+
#update history
|
| 57 |
+
if history is None:
|
| 58 |
+
history=[]
|
| 59 |
+
history.append((prob_text, solution ))
|
| 60 |
+
|
| 61 |
+
return solution, history
|
| 62 |
+
|
| 63 |
+
except Exception as e:
|
| 64 |
+
error_message= f"Error:{str(e)}"
|
| 65 |
+
|
| 66 |
+
return error_message, history
|
| 67 |
+
|
| 68 |
|
| 69 |
+
#image processing
|
| 70 |
+
def img_conv_base64(img_path):
|
| 71 |
+
if img_path is None:
|
| 72 |
+
return None
|
| 73 |
+
|
| 74 |
+
try:
|
| 75 |
+
with open(img_path,"rb") as img_file:
|
| 76 |
+
return base64.b64encode(img_file.read()).decode("utf-8")
|
| 77 |
+
|
| 78 |
+
except Exception as e:
|
| 79 |
+
print(f"Error converting image to base64:{str(e)}")
|
| 80 |
+
return None
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
# function for a given math problem for image data[Togetherai]
|
| 84 |
+
def gen_math_sol_together(api_key, prob_text, img_path=None, history=None):
|
| 85 |
+
if not api_key.strip():
|
| 86 |
+
return "Please enter your Valid Together API key",history
|
| 87 |
+
|
| 88 |
+
if not prob_text.strip() and img_path is None:
|
| 89 |
+
return "please enter a valid math problem or upload an image of a math problem", history
|
| 90 |
|
| 91 |
+
try:
|
| 92 |
+
client= Together(api_key=api_key)
|
| 93 |
+
messages=[{ "role": "system", "content":
|
| 94 |
+
"""You are a very smart math tutor who can able to solve math and give proper explanations clearly and in a precise manner.
|
| 95 |
+
You can analyze the math problem from image given to you and provide the details solution step by step.
|
| 96 |
+
For every step:
|
| 97 |
+
1. Show all the mathematical explanations.
|
| 98 |
+
2. Explain each step and its necessity.
|
| 99 |
+
3. Connect it to the relevant mathematical concept.
|
| 100 |
+
Format your response with clear section of headers using markdown and comment if necessary.
|
| 101 |
+
Begin with a section of analysis named "Initail step" and followed number of step and conclude with "Final step" section.
|
| 102 |
+
"""},]
|
| 103 |
+
|
| 104 |
+
if history:
|
| 105 |
+
for exchange in history:
|
| 106 |
+
messages.append({"role":"user","content":exchange[0]}) #@ task a math problem
|
| 107 |
+
if exchange[1]: # check if there is a problem
|
| 108 |
+
messages.append({"role": "assistant","content": exchange[1]}) # AI response with solution.
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
user_message_content= [] # if we want to add some instructions regaring how to solve the math from given image
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
if prob_text.strip(): # for text
|
| 116 |
+
user_message_content.append({
|
| 117 |
+
"type": "text"
|
| 118 |
+
"text": f"Solve this math problem:{prob_text}"
|
| 119 |
+
})
|
| 120 |
+
else: #image
|
| 121 |
+
user_message_content.append({
|
| 122 |
+
"type": "text"
|
| 123 |
+
"text": "Solve this math problem from the given image"
|
| 124 |
+
})
|
| 125 |
+
if img_path:
|
| 126 |
+
base64_image= img_conv_base64(img_path)
|
| 127 |
+
if base64_image:
|
| 128 |
+
user_message_content.append({
|
| 129 |
+
"type": "image_url",
|
| 130 |
+
"image_url": {
|
| 131 |
+
"url": f"data:image/jpeg;base64,{base64_image}"
|
| 132 |
+
}
|
| 133 |
+
})
|
| 134 |
+
messages.append({
|
| 135 |
+
"role": "user", #conversation saved with image data
|
| 136 |
+
"content": user_message_content
|
| 137 |
+
|
| 138 |
+
})
|
| 139 |
+
|
| 140 |
+
response = client.chat.completions.create(
|
| 141 |
+
model= "meta-llama/Llama-Vision-Free",
|
| 142 |
+
message= messages,
|
| 143 |
+
stram= False
|
| 144 |
+
)
|
| 145 |
+
solution= response.choices[0].message.content
|
| 146 |
+
|
| 147 |
+
if history is None:
|
| 148 |
+
history=[]
|
| 149 |
+
history.append(prob_text if prob_text.strip() else "Image problem ..", solution)
|
| 150 |
+
|
| 151 |
+
return solution, history
|
| 152 |
|
| 153 |
+
except Exception as e:
|
| 154 |
+
error_msg= f"Error: {str(e)}"
|
| 155 |
+
return error_msg, history
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def create_demo():
|
| 159 |
+
with gr.Blocks(theme=gr.themes.Ocean(primary_hue="blue")) as demo:
|
| 160 |
+
gr.Markdown("# Smart Math Tutor")
|
| 161 |
+
gr.Markdown("""This applications provide step by step solution to a math paroblem using AI Tools.
|
| 162 |
+
Choose between OpenPouter's Phi-4-reasoning-plus for text based analysis and Together AI's Llama-Vision for problem with images""")\
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
with gr.Tabs():
|
| 167 |
+
with gr.TabItem("Text problem solver (OpenRouter)"):
|
| 168 |
+
with gr.Row():
|
| 169 |
+
with gr.Column(Scale=1): #left side
|
| 170 |
+
openrouter_api_key= gr.Textbox(
|
| 171 |
+
label= "Oenouter API key",
|
| 172 |
+
placeholder= "enter your API key here",
|
| 173 |
+
type= "password"
|
| 174 |
+
)
|
| 175 |
+
text_prob_input= gr.Textbox(
|
| 176 |
+
label="Math Problem",
|
| 177 |
+
placeholder= "Enter ypur math problem here..",
|
| 178 |
+
lines= 5
|
| 179 |
+
)
|
| 180 |
+
example_problems= gr.Examples(
|
| 181 |
+
examples=[
|
| 182 |
+
["Solve the quadratic equation: 3x² + 5x - 2 = 0"],
|
| 183 |
+
["Find the derivative of f(x) = x²ln(x)"],
|
| 184 |
+
["Calculate the area of a circle with radius 5 cm"],
|
| 185 |
+
["Find all values of x that satisfy the equation: log₁₀(x+1) + log₁₀(x²) = 5"]
|
| 186 |
+
],
|
| 187 |
+
input=[text_problem_input],
|
| 188 |
+
label="Example Problems"
|
| 189 |
+
)
|
| 190 |
+
with gr.Row():
|
| 191 |
+
openrouter_submit_btn= gr.Button("solve problem", variant= "primary")
|
| 192 |
+
openrouter_clear_btn= gr.Button("Clear")
|
| 193 |
+
|
| 194 |
+
with gr.Column(Scale=2): #right side
|
| 195 |
+
openrouter_solution_output= gr.Markdown(label="Solution")
|
| 196 |
+
|
| 197 |
+
openrouter_conversation_history= gr.State(value=None)
|
| 198 |
+
openrouter_submit_btn.click(
|
| 199 |
+
fn= generate_math_solution, openrouter,
|
| 200 |
+
inputs= [openrouter_api_key, text_problem_input, openrouter_conversation_history],
|
| 201 |
+
outputs=[openrouter_solution_output, openrouter_conversation_history]
|
| 202 |
+
)
|
| 203 |
+
|
| 204 |
+
openrouter_clear_btn.click(
|
| 205 |
+
fn=lambda: ("",None),
|
| 206 |
+
inputs=[],
|
| 207 |
+
outputs=[openrouter_solution_output, openrouter_conversation_history]
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
with gr.TabItem("Text problem solver (OpenRouter)"):
|
| 211 |
+
with gr.Row():
|
| 212 |
+
with gr.Column(Scale=1): #left side
|
| 213 |
+
together_api_key= gr.Textbox(
|
| 214 |
+
label= "Together API key",
|
| 215 |
+
placeholder= "enter your API key here",
|
| 216 |
+
type= "password"
|
| 217 |
+
)
|
| 218 |
+
together_prob_input= gr.Textbox(
|
| 219 |
+
label="Math Problem Description",
|
| 220 |
+
placeholder= "Enter additional math problem here..",
|
| 221 |
+
lines= 3
|
| 222 |
+
)
|
| 223 |
+
together_image_input= gr.Image(
|
| 224 |
+
label="upload math problem image",
|
| 225 |
+
type="filepath"
|
| 226 |
+
)
|
| 227 |
+
with gr.Row():
|
| 228 |
+
together_submit_btn= gr.Button("Solve Problem", variant="primary")
|
| 229 |
+
together_clear_btn = gr.Button("clear")
|
| 230 |
+
|
| 231 |
+
with gr.Column(Scale=2):
|
| 232 |
+
together_solution_output= gr.Markdown(label="Solution")
|
| 233 |
+
|
| 234 |
+
together_conversation_history= gr.State(value=None)
|
| 235 |
+
# Button actions
|
| 236 |
+
together_submit_btn.click(
|
| 237 |
+
fn=generate_math_solution_together,
|
| 238 |
+
inputs=[together_api_key, together_problem_input, together_image_input, together_conversation_history],
|
| 239 |
+
outputs=[together_solution_output, together_conversation_history]
|
| 240 |
+
)
|
| 241 |
+
together_clear_btn.click(
|
| 242 |
+
fn=lambda: ("", None),
|
| 243 |
+
inputs=[],
|
| 244 |
+
outputs=[together_solution_output, together_conversation_history]
|
| 245 |
+
)
|
| 246 |
+
|
| 247 |
+
# Footer
|
| 248 |
+
gr.Markdown("""
|
| 249 |
+
---
|
| 250 |
+
### About
|
| 251 |
+
This application uses Microsoft's Phi-4-reasoning-plus model via OpenRouter for text-based problems
|
| 252 |
+
and Llama-Vision-Free via Together AI for image-based problems.
|
| 253 |
+
Your API keys are required but not stored permanently.
|
| 254 |
+
""")
|
| 255 |
+
|
| 256 |
+
return demo
|
| 257 |
+
# Launch the app
|
| 258 |
+
if __name__ == "__main__":
|
| 259 |
+
demo = create_demo()
|
| 260 |
+
demo.launch()
|
| 261 |
|