Update app.py
Browse files
app.py
CHANGED
|
@@ -1,738 +1,42 @@
|
|
| 1 |
-
|
|
|
|
| 2 |
import os
|
| 3 |
-
import re
|
| 4 |
-
import time
|
| 5 |
-
import base64
|
| 6 |
-
from openai import OpenAI
|
| 7 |
-
from together import Together
|
| 8 |
-
from PIL import Image
|
| 9 |
-
import io
|
| 10 |
-
import markdown
|
| 11 |
-
from datetime import datetime
|
| 12 |
import tempfile
|
| 13 |
-
import
|
| 14 |
-
from pathlib import Path
|
| 15 |
|
| 16 |
-
#
|
| 17 |
-
def markdown_to_html(markdown_text, problem_text="", include_problem=True):
|
| 18 |
-
"""Convert markdown to styled HTML"""
|
| 19 |
-
|
| 20 |
-
# Convert markdown to HTML
|
| 21 |
-
html_content = markdown.markdown(markdown_text, extensions=['tables', 'fenced_code'])
|
| 22 |
-
|
| 23 |
-
# Get current timestamp
|
| 24 |
-
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
| 25 |
-
|
| 26 |
-
# Create styled HTML document
|
| 27 |
-
styled_html = f"""
|
| 28 |
-
<!DOCTYPE html>
|
| 29 |
-
<html lang="en">
|
| 30 |
-
<head>
|
| 31 |
-
<meta charset="UTF-8">
|
| 32 |
-
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 33 |
-
<title>Math Solution - Advanced Math Tutor</title>
|
| 34 |
-
<style>
|
| 35 |
-
body {{
|
| 36 |
-
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
|
| 37 |
-
line-height: 1.6;
|
| 38 |
-
color: #333;
|
| 39 |
-
max-width: 800px;
|
| 40 |
-
margin: 0 auto;
|
| 41 |
-
padding: 20px;
|
| 42 |
-
background-color: #f9f9f9;
|
| 43 |
-
}}
|
| 44 |
-
.container {{
|
| 45 |
-
background-color: white;
|
| 46 |
-
padding: 40px;
|
| 47 |
-
border-radius: 10px;
|
| 48 |
-
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
|
| 49 |
-
}}
|
| 50 |
-
.header {{
|
| 51 |
-
text-align: center;
|
| 52 |
-
border-bottom: 3px solid #4CAF50;
|
| 53 |
-
padding-bottom: 20px;
|
| 54 |
-
margin-bottom: 30px;
|
| 55 |
-
}}
|
| 56 |
-
.header h1 {{
|
| 57 |
-
color: #2c3e50;
|
| 58 |
-
margin: 0;
|
| 59 |
-
font-size: 2.5em;
|
| 60 |
-
}}
|
| 61 |
-
.header .subtitle {{
|
| 62 |
-
color: #7f8c8d;
|
| 63 |
-
font-style: italic;
|
| 64 |
-
margin-top: 10px;
|
| 65 |
-
}}
|
| 66 |
-
.problem-section {{
|
| 67 |
-
background-color: #e8f5e8;
|
| 68 |
-
padding: 20px;
|
| 69 |
-
border-radius: 8px;
|
| 70 |
-
margin-bottom: 30px;
|
| 71 |
-
border-left: 5px solid #4CAF50;
|
| 72 |
-
}}
|
| 73 |
-
.problem-section h2 {{
|
| 74 |
-
color: #2c3e50;
|
| 75 |
-
margin-top: 0;
|
| 76 |
-
}}
|
| 77 |
-
.solution-content {{
|
| 78 |
-
background-color: #f8f9fa;
|
| 79 |
-
padding: 25px;
|
| 80 |
-
border-radius: 8px;
|
| 81 |
-
border-left: 5px solid #007bff;
|
| 82 |
-
}}
|
| 83 |
-
h1, h2, h3, h4, h5, h6 {{
|
| 84 |
-
color: #2c3e50;
|
| 85 |
-
margin-top: 25px;
|
| 86 |
-
margin-bottom: 15px;
|
| 87 |
-
}}
|
| 88 |
-
h2 {{
|
| 89 |
-
border-bottom: 2px solid #eee;
|
| 90 |
-
padding-bottom: 10px;
|
| 91 |
-
}}
|
| 92 |
-
code {{
|
| 93 |
-
background-color: #f1f1f1;
|
| 94 |
-
padding: 2px 6px;
|
| 95 |
-
border-radius: 3px;
|
| 96 |
-
font-family: 'Courier New', monospace;
|
| 97 |
-
color: #d63384;
|
| 98 |
-
}}
|
| 99 |
-
pre {{
|
| 100 |
-
background-color: #f8f8f8;
|
| 101 |
-
padding: 15px;
|
| 102 |
-
border-radius: 5px;
|
| 103 |
-
overflow-x: auto;
|
| 104 |
-
border: 1px solid #ddd;
|
| 105 |
-
}}
|
| 106 |
-
pre code {{
|
| 107 |
-
background-color: transparent;
|
| 108 |
-
padding: 0;
|
| 109 |
-
color: inherit;
|
| 110 |
-
}}
|
| 111 |
-
.math-expression {{
|
| 112 |
-
background-color: #fff3cd;
|
| 113 |
-
padding: 10px;
|
| 114 |
-
border-radius: 5px;
|
| 115 |
-
border: 1px solid #ffeaa7;
|
| 116 |
-
margin: 10px 0;
|
| 117 |
-
font-family: 'Times New Roman', serif;
|
| 118 |
-
font-size: 1.1em;
|
| 119 |
-
}}
|
| 120 |
-
.step {{
|
| 121 |
-
margin: 20px 0;
|
| 122 |
-
padding: 15px;
|
| 123 |
-
background-color: #ffffff;
|
| 124 |
-
border-radius: 8px;
|
| 125 |
-
border: 1px solid #dee2e6;
|
| 126 |
-
}}
|
| 127 |
-
.final-answer {{
|
| 128 |
-
background-color: #d4edda;
|
| 129 |
-
border: 2px solid #4CAF50;
|
| 130 |
-
padding: 20px;
|
| 131 |
-
border-radius: 8px;
|
| 132 |
-
margin-top: 30px;
|
| 133 |
-
text-align: center;
|
| 134 |
-
font-weight: bold;
|
| 135 |
-
font-size: 1.2em;
|
| 136 |
-
}}
|
| 137 |
-
.timestamp {{
|
| 138 |
-
text-align: right;
|
| 139 |
-
color: #6c757d;
|
| 140 |
-
font-size: 0.9em;
|
| 141 |
-
margin-top: 30px;
|
| 142 |
-
padding-top: 20px;
|
| 143 |
-
border-top: 1px solid #eee;
|
| 144 |
-
}}
|
| 145 |
-
ul, ol {{
|
| 146 |
-
padding-left: 25px;
|
| 147 |
-
}}
|
| 148 |
-
li {{
|
| 149 |
-
margin: 8px 0;
|
| 150 |
-
}}
|
| 151 |
-
table {{
|
| 152 |
-
border-collapse: collapse;
|
| 153 |
-
width: 100%;
|
| 154 |
-
margin: 20px 0;
|
| 155 |
-
}}
|
| 156 |
-
th, td {{
|
| 157 |
-
border: 1px solid #ddd;
|
| 158 |
-
padding: 12px;
|
| 159 |
-
text-align: left;
|
| 160 |
-
}}
|
| 161 |
-
th {{
|
| 162 |
-
background-color: #f8f9fa;
|
| 163 |
-
font-weight: bold;
|
| 164 |
-
}}
|
| 165 |
-
.print-button {{
|
| 166 |
-
background-color: #007bff;
|
| 167 |
-
color: white;
|
| 168 |
-
border: none;
|
| 169 |
-
padding: 10px 20px;
|
| 170 |
-
border-radius: 5px;
|
| 171 |
-
cursor: pointer;
|
| 172 |
-
font-size: 16px;
|
| 173 |
-
margin: 10px 5px;
|
| 174 |
-
display: inline-block;
|
| 175 |
-
text-decoration: none;
|
| 176 |
-
}}
|
| 177 |
-
.print-button:hover {{
|
| 178 |
-
background-color: #0056b3;
|
| 179 |
-
}}
|
| 180 |
-
@media print {{
|
| 181 |
-
body {{
|
| 182 |
-
background-color: white;
|
| 183 |
-
}}
|
| 184 |
-
.container {{
|
| 185 |
-
box-shadow: none;
|
| 186 |
-
border: none;
|
| 187 |
-
}}
|
| 188 |
-
.print-button {{
|
| 189 |
-
display: none;
|
| 190 |
-
}}
|
| 191 |
-
}}
|
| 192 |
-
</style>
|
| 193 |
-
<script>
|
| 194 |
-
function printPage() {{
|
| 195 |
-
window.print();
|
| 196 |
-
}}
|
| 197 |
-
</script>
|
| 198 |
-
</head>
|
| 199 |
-
<body>
|
| 200 |
-
<div class="container">
|
| 201 |
-
<div class="header">
|
| 202 |
-
<h1>📚 Advanced Math Tutor</h1>
|
| 203 |
-
<div class="subtitle">Step-by-Step Mathematical Solution</div>
|
| 204 |
-
</div>
|
| 205 |
-
|
| 206 |
-
<button class="print-button" onclick="printPage()">🖨️ Print to PDF</button>
|
| 207 |
-
|
| 208 |
-
{f'''
|
| 209 |
-
<div class="problem-section">
|
| 210 |
-
<h2>📝 Problem Statement</h2>
|
| 211 |
-
<p><strong>{problem_text}</strong></p>
|
| 212 |
-
</div>
|
| 213 |
-
''' if include_problem and problem_text.strip() else ''}
|
| 214 |
-
|
| 215 |
-
<div class="solution-content">
|
| 216 |
-
<h2>🔍 Solution</h2>
|
| 217 |
-
{html_content}
|
| 218 |
-
</div>
|
| 219 |
-
|
| 220 |
-
<div class="timestamp">
|
| 221 |
-
Generated on: {timestamp}
|
| 222 |
-
</div>
|
| 223 |
-
</div>
|
| 224 |
-
</body>
|
| 225 |
-
</html>
|
| 226 |
-
"""
|
| 227 |
-
|
| 228 |
-
return styled_html
|
| 229 |
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
"""Save HTML content to a temporary file and return the file path"""
|
| 233 |
-
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 234 |
-
filename = f"{filename_prefix}_{timestamp}.html"
|
| 235 |
-
|
| 236 |
-
# Create a temporary file
|
| 237 |
-
temp_dir = tempfile.gettempdir()
|
| 238 |
-
file_path = os.path.join(temp_dir, filename)
|
| 239 |
-
|
| 240 |
-
with open(file_path, 'w', encoding='utf-8') as f:
|
| 241 |
-
f.write(html_content)
|
| 242 |
-
|
| 243 |
-
return file_path
|
| 244 |
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
# Create a temporary file for PDF
|
| 252 |
-
temp_dir = tempfile.gettempdir()
|
| 253 |
-
pdf_path = os.path.join(temp_dir, filename)
|
| 254 |
-
|
| 255 |
-
try:
|
| 256 |
-
# Convert HTML to PDF using WeasyPrint
|
| 257 |
-
weasyprint.HTML(string=html_content).write_pdf(pdf_path)
|
| 258 |
-
return pdf_path
|
| 259 |
-
except Exception as e:
|
| 260 |
-
print(f"Error converting to PDF: {str(e)}")
|
| 261 |
-
return None
|
| 262 |
|
| 263 |
-
|
| 264 |
-
def generate_math_solution_openrouter(api_key, problem_text, history=None):
|
| 265 |
-
if not api_key.strip():
|
| 266 |
-
return "Please enter your OpenRouter API key.", None, None, history
|
| 267 |
-
|
| 268 |
-
if not problem_text.strip():
|
| 269 |
-
return "Please enter a math problem.", None, None, history
|
| 270 |
-
|
| 271 |
-
try:
|
| 272 |
-
client = OpenAI(
|
| 273 |
-
base_url="https://openrouter.ai/api/v1",
|
| 274 |
-
api_key=api_key,
|
| 275 |
-
)
|
| 276 |
-
|
| 277 |
-
messages = [
|
| 278 |
-
{"role": "system", "content":
|
| 279 |
-
"""You are an expert math tutor who explains concepts clearly and thoroughly.
|
| 280 |
-
Analyze the given math problem and provide a detailed step-by-step solution.
|
| 281 |
-
For each step:
|
| 282 |
-
1. Show the mathematical operation
|
| 283 |
-
2. Explain why this step is necessary
|
| 284 |
-
3. Connect it to relevant mathematical concepts
|
| 285 |
-
|
| 286 |
-
Format your response using markdown with clear section headers.
|
| 287 |
-
Begin with an "Initial Analysis" section, follow with numbered steps,
|
| 288 |
-
and conclude with a "Final Answer" section.
|
| 289 |
-
|
| 290 |
-
Use proper markdown formatting including:
|
| 291 |
-
- Headers (##, ###)
|
| 292 |
-
- **Bold text** for important points
|
| 293 |
-
- `Code blocks` for mathematical expressions
|
| 294 |
-
- Lists and numbered steps
|
| 295 |
-
- Tables if needed for comparisons or data"""},
|
| 296 |
-
]
|
| 297 |
-
|
| 298 |
-
# Add conversation history if it exists
|
| 299 |
-
if history:
|
| 300 |
-
for exchange in history:
|
| 301 |
-
messages.append({"role": "user", "content": exchange[0]})
|
| 302 |
-
if len(exchange) > 1 and exchange[1]: # Check if there's a response
|
| 303 |
-
messages.append({"role": "assistant", "content": exchange[1]})
|
| 304 |
-
|
| 305 |
-
# Add the current problem
|
| 306 |
-
messages.append({"role": "user", "content": f"Solve this math problem step-by-step: {problem_text}"})
|
| 307 |
-
|
| 308 |
-
# Create the completion with streaming
|
| 309 |
-
stream = client.chat.completions.create(
|
| 310 |
-
model="deepseek/deepseek-r1-0528:free",
|
| 311 |
-
messages=messages,
|
| 312 |
-
stream=True,
|
| 313 |
-
extra_headers={
|
| 314 |
-
"HTTP-Referer": "https://advancedmathtutor.edu",
|
| 315 |
-
"X-Title": "Advanced Math Tutor",
|
| 316 |
-
}
|
| 317 |
-
)
|
| 318 |
-
|
| 319 |
-
# Collect streamed content
|
| 320 |
-
markdown_solution = ""
|
| 321 |
-
for chunk in stream:
|
| 322 |
-
if hasattr(chunk, 'choices') and chunk.choices:
|
| 323 |
-
delta = chunk.choices[0].delta
|
| 324 |
-
if hasattr(delta, 'content') and delta.content:
|
| 325 |
-
markdown_solution += delta.content
|
| 326 |
-
|
| 327 |
-
# Convert to HTML
|
| 328 |
-
html_solution = markdown_to_html(markdown_solution, problem_text)
|
| 329 |
-
|
| 330 |
-
# Save HTML file
|
| 331 |
-
html_file_path = save_html_to_file(html_solution, "openrouter_solution")
|
| 332 |
-
|
| 333 |
-
# Convert to PDF
|
| 334 |
-
pdf_file_path = html_to_pdf(html_solution, "openrouter_solution")
|
| 335 |
-
|
| 336 |
-
# Update history
|
| 337 |
-
if history is None:
|
| 338 |
-
history = []
|
| 339 |
-
history.append((problem_text, markdown_solution))
|
| 340 |
-
|
| 341 |
-
return html_solution, html_file_path, pdf_file_path, history
|
| 342 |
-
|
| 343 |
-
except Exception as e:
|
| 344 |
-
error_message = f"Error: {str(e)}"
|
| 345 |
-
return error_message, None, None, history
|
| 346 |
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
if not api_key.strip():
|
| 350 |
-
return "Please enter your Together AI API key.", None, None, history
|
| 351 |
-
|
| 352 |
-
if not problem_text.strip() and image_path is None:
|
| 353 |
-
return "Please enter a math problem or upload an image of a math problem.", None, None, history
|
| 354 |
-
|
| 355 |
-
try:
|
| 356 |
-
client = Together(api_key=api_key)
|
| 357 |
-
|
| 358 |
-
# Create the base message structure
|
| 359 |
-
messages = [
|
| 360 |
-
{
|
| 361 |
-
"role": "system",
|
| 362 |
-
"content": """You are an expert math tutor who explains concepts clearly and thoroughly.
|
| 363 |
-
Analyze the given math problem and provide a detailed step-by-step solution.
|
| 364 |
-
For each step:
|
| 365 |
-
1. Show the mathematical operation
|
| 366 |
-
2. Explain why this step is necessary
|
| 367 |
-
3. Connect it to relevant mathematical concepts
|
| 368 |
-
|
| 369 |
-
Format your response using markdown with clear section headers.
|
| 370 |
-
Begin with an "Initial Analysis" section, follow with numbered steps,
|
| 371 |
-
and conclude with a "Final Answer" section.
|
| 372 |
-
|
| 373 |
-
Use proper markdown formatting including:
|
| 374 |
-
- Headers (##, ###)
|
| 375 |
-
- **Bold text** for important points
|
| 376 |
-
- `Code blocks` for mathematical expressions
|
| 377 |
-
- Lists and numbered steps
|
| 378 |
-
- Tables if needed for comparisons or data"""
|
| 379 |
-
}
|
| 380 |
-
]
|
| 381 |
-
|
| 382 |
-
# Add conversation history if it exists
|
| 383 |
-
if history:
|
| 384 |
-
for exchange in history:
|
| 385 |
-
messages.append({"role": "user", "content": exchange[0]})
|
| 386 |
-
if len(exchange) > 1 and exchange[1]: # Check if there's a response
|
| 387 |
-
messages.append({"role": "assistant", "content": exchange[1]})
|
| 388 |
-
|
| 389 |
-
# Prepare the user message content
|
| 390 |
-
user_message_content = []
|
| 391 |
-
|
| 392 |
-
# Add text content if provided
|
| 393 |
-
if problem_text.strip():
|
| 394 |
-
user_message_content.append({
|
| 395 |
-
"type": "text",
|
| 396 |
-
"text": f"Solve this math problem: {problem_text}"
|
| 397 |
-
})
|
| 398 |
-
else:
|
| 399 |
-
user_message_content.append({
|
| 400 |
-
"type": "text",
|
| 401 |
-
"text": "Solve this math problem from the image:"
|
| 402 |
-
})
|
| 403 |
-
|
| 404 |
-
# Add image if provided
|
| 405 |
-
if image_path:
|
| 406 |
-
# Convert image to base64
|
| 407 |
-
base64_image = image_to_base64(image_path)
|
| 408 |
-
if base64_image:
|
| 409 |
-
user_message_content.append({
|
| 410 |
-
"type": "image_url",
|
| 411 |
-
"image_url": {
|
| 412 |
-
"url": f"data:image/jpeg;base64,{base64_image}"
|
| 413 |
-
}
|
| 414 |
-
})
|
| 415 |
-
|
| 416 |
-
# Add the user message with content
|
| 417 |
-
messages.append({
|
| 418 |
-
"role": "user",
|
| 419 |
-
"content": user_message_content
|
| 420 |
-
})
|
| 421 |
-
|
| 422 |
-
# Create the completion with streaming
|
| 423 |
-
stream = client.chat.completions.create(
|
| 424 |
-
model="meta-llama/Llama-Vision-Free",
|
| 425 |
-
messages=messages,
|
| 426 |
-
stream=True
|
| 427 |
-
)
|
| 428 |
-
|
| 429 |
-
# Collect streamed content
|
| 430 |
-
markdown_solution = ""
|
| 431 |
-
for chunk in stream:
|
| 432 |
-
if hasattr(chunk, 'choices') and chunk.choices:
|
| 433 |
-
delta = chunk.choices[0].delta
|
| 434 |
-
if hasattr(delta, 'content') and delta.content:
|
| 435 |
-
markdown_solution += delta.content
|
| 436 |
-
|
| 437 |
-
# Convert to HTML
|
| 438 |
-
problem_display = problem_text if problem_text.strip() else "Image-based problem"
|
| 439 |
-
html_solution = markdown_to_html(markdown_solution, problem_display)
|
| 440 |
-
|
| 441 |
-
# Save HTML file
|
| 442 |
-
html_file_path = save_html_to_file(html_solution, "together_solution")
|
| 443 |
-
|
| 444 |
-
# Convert to PDF
|
| 445 |
-
pdf_file_path = html_to_pdf(html_solution, "together_solution")
|
| 446 |
-
|
| 447 |
-
# Update history
|
| 448 |
-
if history is None:
|
| 449 |
-
history = []
|
| 450 |
-
history.append((problem_display, markdown_solution))
|
| 451 |
-
|
| 452 |
-
return html_solution, html_file_path, pdf_file_path, history
|
| 453 |
-
|
| 454 |
-
except Exception as e:
|
| 455 |
-
error_message = f"Error: {str(e)}"
|
| 456 |
-
return error_message, None, None, history
|
| 457 |
|
| 458 |
-
|
| 459 |
-
|
| 460 |
-
|
| 461 |
-
return None
|
| 462 |
-
|
| 463 |
-
try:
|
| 464 |
-
with open(image_path, "rb") as img_file:
|
| 465 |
-
return base64.b64encode(img_file.read()).decode("utf-8")
|
| 466 |
-
except Exception as e:
|
| 467 |
-
print(f"Error converting image to base64: {str(e)}")
|
| 468 |
-
return None
|
| 469 |
|
| 470 |
-
|
| 471 |
-
|
| 472 |
-
|
| 473 |
-
|
| 474 |
-
|
| 475 |
-
|
| 476 |
-
|
| 477 |
-
|
| 478 |
-
|
| 479 |
-
""
|
| 480 |
-
|
| 481 |
-
# Main tabs
|
| 482 |
-
with gr.Tabs():
|
| 483 |
-
# Text-based problem solver (OpenRouter)
|
| 484 |
-
with gr.TabItem("Text Problem Solver (OpenRouter)"):
|
| 485 |
-
with gr.Row():
|
| 486 |
-
with gr.Column(scale=1):
|
| 487 |
-
openrouter_api_key = gr.Textbox(
|
| 488 |
-
label="OpenRouter API Key",
|
| 489 |
-
placeholder="Enter your OpenRouter API key (starts with sk-or-)",
|
| 490 |
-
type="password"
|
| 491 |
-
)
|
| 492 |
-
text_problem_input = gr.Textbox(
|
| 493 |
-
label="Math Problem",
|
| 494 |
-
placeholder="Enter your math problem here...",
|
| 495 |
-
lines=5
|
| 496 |
-
)
|
| 497 |
-
example_problems = gr.Examples(
|
| 498 |
-
examples=[
|
| 499 |
-
["Solve the quadratic equation: 3x² + 5x - 2 = 0"],
|
| 500 |
-
["Find the derivative of f(x) = x³ln(x)"],
|
| 501 |
-
["Calculate the area of a circle with radius 5 cm"],
|
| 502 |
-
["Find all values of x that satisfy the equation: log₂(x-1) + log₂(x+3) = 5"]
|
| 503 |
-
],
|
| 504 |
-
inputs=[text_problem_input],
|
| 505 |
-
label="Example Problems"
|
| 506 |
-
)
|
| 507 |
-
with gr.Row():
|
| 508 |
-
openrouter_submit_btn = gr.Button("Solve Problem", variant="primary")
|
| 509 |
-
openrouter_clear_btn = gr.Button("Clear")
|
| 510 |
-
|
| 511 |
-
with gr.Column(scale=2):
|
| 512 |
-
openrouter_solution_output = gr.HTML(label="Solution (HTML Format)")
|
| 513 |
-
|
| 514 |
-
with gr.Row():
|
| 515 |
-
openrouter_html_download = gr.File(
|
| 516 |
-
label="📄 Download HTML Solution",
|
| 517 |
-
visible=False
|
| 518 |
-
)
|
| 519 |
-
openrouter_pdf_download = gr.File(
|
| 520 |
-
label="📄 Download PDF Solution",
|
| 521 |
-
visible=False
|
| 522 |
-
)
|
| 523 |
-
|
| 524 |
-
# Store conversation history (invisible to user)
|
| 525 |
-
openrouter_conversation_history = gr.State(value=None)
|
| 526 |
-
|
| 527 |
-
# Button actions
|
| 528 |
-
def handle_openrouter_submit(api_key, problem_text, history):
|
| 529 |
-
html_solution, html_file, pdf_file, updated_history = generate_math_solution_openrouter(
|
| 530 |
-
api_key, problem_text, history
|
| 531 |
-
)
|
| 532 |
-
|
| 533 |
-
# Return outputs including file updates
|
| 534 |
-
return (
|
| 535 |
-
html_solution,
|
| 536 |
-
updated_history,
|
| 537 |
-
gr.update(value=html_file, visible=html_file is not None),
|
| 538 |
-
gr.update(value=pdf_file, visible=pdf_file is not None)
|
| 539 |
-
)
|
| 540 |
-
|
| 541 |
-
openrouter_submit_btn.click(
|
| 542 |
-
fn=handle_openrouter_submit,
|
| 543 |
-
inputs=[openrouter_api_key, text_problem_input, openrouter_conversation_history],
|
| 544 |
-
outputs=[
|
| 545 |
-
openrouter_solution_output,
|
| 546 |
-
openrouter_conversation_history,
|
| 547 |
-
openrouter_html_download,
|
| 548 |
-
openrouter_pdf_download
|
| 549 |
-
]
|
| 550 |
-
)
|
| 551 |
-
|
| 552 |
-
def clear_openrouter():
|
| 553 |
-
return (
|
| 554 |
-
"",
|
| 555 |
-
None,
|
| 556 |
-
gr.update(value=None, visible=False),
|
| 557 |
-
gr.update(value=None, visible=False)
|
| 558 |
-
)
|
| 559 |
-
|
| 560 |
-
openrouter_clear_btn.click(
|
| 561 |
-
fn=clear_openrouter,
|
| 562 |
-
inputs=[],
|
| 563 |
-
outputs=[
|
| 564 |
-
openrouter_solution_output,
|
| 565 |
-
openrouter_conversation_history,
|
| 566 |
-
openrouter_html_download,
|
| 567 |
-
openrouter_pdf_download
|
| 568 |
-
]
|
| 569 |
-
)
|
| 570 |
-
|
| 571 |
-
# Image-based problem solver (Together AI)
|
| 572 |
-
with gr.TabItem("Image Problem Solver (Together AI)"):
|
| 573 |
-
with gr.Row():
|
| 574 |
-
with gr.Column(scale=1):
|
| 575 |
-
together_api_key = gr.Textbox(
|
| 576 |
-
label="Together AI API Key",
|
| 577 |
-
placeholder="Enter your Together AI API key",
|
| 578 |
-
type="password"
|
| 579 |
-
)
|
| 580 |
-
together_problem_input = gr.Textbox(
|
| 581 |
-
label="Problem Description (Optional)",
|
| 582 |
-
placeholder="Enter additional context for the image problem...",
|
| 583 |
-
lines=3
|
| 584 |
-
)
|
| 585 |
-
together_image_input = gr.Image(
|
| 586 |
-
label="Upload Math Problem Image",
|
| 587 |
-
type="filepath"
|
| 588 |
-
)
|
| 589 |
-
with gr.Row():
|
| 590 |
-
together_submit_btn = gr.Button("Solve Problem", variant="primary")
|
| 591 |
-
together_clear_btn = gr.Button("Clear")
|
| 592 |
-
|
| 593 |
-
with gr.Column(scale=2):
|
| 594 |
-
together_solution_output = gr.HTML(label="Solution (HTML Format)")
|
| 595 |
-
|
| 596 |
-
with gr.Row():
|
| 597 |
-
together_html_download = gr.File(
|
| 598 |
-
label="📄 Download HTML Solution",
|
| 599 |
-
visible=False
|
| 600 |
-
)
|
| 601 |
-
together_pdf_download = gr.File(
|
| 602 |
-
label="📄 Download PDF Solution",
|
| 603 |
-
visible=False
|
| 604 |
-
)
|
| 605 |
-
|
| 606 |
-
# Store conversation history (invisible to user)
|
| 607 |
-
together_conversation_history = gr.State(value=None)
|
| 608 |
-
|
| 609 |
-
# Button actions
|
| 610 |
-
def handle_together_submit(api_key, problem_text, image_path, history):
|
| 611 |
-
html_solution, html_file, pdf_file, updated_history = generate_math_solution_together(
|
| 612 |
-
api_key, problem_text, image_path, history
|
| 613 |
-
)
|
| 614 |
-
|
| 615 |
-
# Return outputs including file updates
|
| 616 |
-
return (
|
| 617 |
-
html_solution,
|
| 618 |
-
updated_history,
|
| 619 |
-
gr.update(value=html_file, visible=html_file is not None),
|
| 620 |
-
gr.update(value=pdf_file, visible=pdf_file is not None)
|
| 621 |
-
)
|
| 622 |
-
|
| 623 |
-
together_submit_btn.click(
|
| 624 |
-
fn=handle_together_submit,
|
| 625 |
-
inputs=[together_api_key, together_problem_input, together_image_input, together_conversation_history],
|
| 626 |
-
outputs=[
|
| 627 |
-
together_solution_output,
|
| 628 |
-
together_conversation_history,
|
| 629 |
-
together_html_download,
|
| 630 |
-
together_pdf_download
|
| 631 |
-
]
|
| 632 |
-
)
|
| 633 |
-
|
| 634 |
-
def clear_together():
|
| 635 |
-
return (
|
| 636 |
-
"",
|
| 637 |
-
None,
|
| 638 |
-
gr.update(value=None, visible=False),
|
| 639 |
-
gr.update(value=None, visible=False)
|
| 640 |
-
)
|
| 641 |
-
|
| 642 |
-
together_clear_btn.click(
|
| 643 |
-
fn=clear_together,
|
| 644 |
-
inputs=[],
|
| 645 |
-
outputs=[
|
| 646 |
-
together_solution_output,
|
| 647 |
-
together_conversation_history,
|
| 648 |
-
together_html_download,
|
| 649 |
-
together_pdf_download
|
| 650 |
-
]
|
| 651 |
-
)
|
| 652 |
-
|
| 653 |
-
# Help tab
|
| 654 |
-
with gr.TabItem("Help"):
|
| 655 |
-
gr.Markdown("""
|
| 656 |
-
## How to Use the Advanced Math Tutor
|
| 657 |
-
|
| 658 |
-
### New Features 🎉
|
| 659 |
-
- **HTML-formatted solutions**: All responses are now generated in beautiful HTML format
|
| 660 |
-
- **Download HTML**: Download the complete solution as an HTML file
|
| 661 |
-
- **Download PDF**: Convert and download solutions as PDF files
|
| 662 |
-
- **Print functionality**: Use the "Print to PDF" button in the HTML output to print directly
|
| 663 |
-
|
| 664 |
-
### Getting Started
|
| 665 |
-
|
| 666 |
-
#### For Text-Based Problems (OpenRouter)
|
| 667 |
-
1. You'll need an API key from OpenRouter
|
| 668 |
-
2. Sign up at [OpenRouter](https://openrouter.ai/) to get your API key
|
| 669 |
-
3. Enter your API key in the designated field in the "Text Problem Solver" tab
|
| 670 |
-
|
| 671 |
-
#### For Image-Based Problems (Together AI)
|
| 672 |
-
1. You'll need an API key from Together AI
|
| 673 |
-
2. Sign up at [Together AI](https://www.together.ai/) to get your API key
|
| 674 |
-
3. Enter your API key in the designated field in the "Image Problem Solver" tab
|
| 675 |
-
4. Upload an image of your math problem
|
| 676 |
-
5. Optionally add text to provide additional context
|
| 677 |
-
|
| 678 |
-
### Solving Math Problems
|
| 679 |
-
- For text problems: Type or paste your math problem in the input field
|
| 680 |
-
- For image problems: Upload a clear image of the math problem
|
| 681 |
-
- Click "Solve Problem" to get a detailed step-by-step solution in HTML format
|
| 682 |
-
- Use the download buttons to save HTML or PDF versions
|
| 683 |
-
- Click "Print to PDF" within the solution to print directly from your browser
|
| 684 |
-
|
| 685 |
-
### HTML Output Features
|
| 686 |
-
- **Professional styling**: Clean, readable format with proper typography
|
| 687 |
-
- **Mathematical expressions**: Highlighted math expressions and code blocks
|
| 688 |
-
- **Step-by-step sections**: Clearly organized solution steps
|
| 689 |
-
- **Print-friendly**: Optimized for printing and PDF conversion
|
| 690 |
-
- **Timestamps**: Each solution includes generation timestamp
|
| 691 |
-
|
| 692 |
-
### Tips for Best Results
|
| 693 |
-
- Be specific in your problem description
|
| 694 |
-
- Include all necessary information
|
| 695 |
-
- For complex equations, use clear notation
|
| 696 |
-
- For algebraic expressions, use ^ for exponents (e.g., x^2 for x²)
|
| 697 |
-
- Use parentheses to group terms clearly
|
| 698 |
-
- For images, ensure the math problem is clearly visible and well-lit
|
| 699 |
-
|
| 700 |
-
### Types of Problems You Can Solve
|
| 701 |
-
- Algebra (equations, inequalities, systems of equations)
|
| 702 |
-
- Calculus (derivatives, integrals, limits)
|
| 703 |
-
- Trigonometry
|
| 704 |
-
- Geometry
|
| 705 |
-
- Statistics and Probability
|
| 706 |
-
- Number Theory
|
| 707 |
-
- And many more!
|
| 708 |
-
|
| 709 |
-
### Required Dependencies
|
| 710 |
-
To run this application, you'll need to install:
|
| 711 |
-
```bash
|
| 712 |
-
pip install gradio openai together pillow markdown weasyprint
|
| 713 |
-
```
|
| 714 |
-
""")
|
| 715 |
-
|
| 716 |
-
# Footer
|
| 717 |
-
gr.Markdown("""
|
| 718 |
-
---
|
| 719 |
-
### About
|
| 720 |
-
This enhanced application uses Microsoft's Phi-4-reasoning-plus model via OpenRouter for text-based problems
|
| 721 |
-
and Llama-Vision-Free via Together AI for image-based problems.
|
| 722 |
-
|
| 723 |
-
**New Features:**
|
| 724 |
-
- HTML-formatted responses with professional styling
|
| 725 |
-
- Download solutions as HTML files
|
| 726 |
-
- Convert and download solutions as PDF files
|
| 727 |
-
- Print-to-PDF functionality
|
| 728 |
-
- Enhanced formatting with mathematical expressions highlighting
|
| 729 |
-
|
| 730 |
-
Your API keys are required but not stored permanently.
|
| 731 |
-
""")
|
| 732 |
-
|
| 733 |
-
return demo
|
| 734 |
|
| 735 |
-
# Launch the app
|
| 736 |
if __name__ == "__main__":
|
| 737 |
-
|
| 738 |
-
|
|
|
|
|
|
|
|
|
| 1 |
+
from Crypto.Cipher import AES
|
| 2 |
+
from Crypto.Protocol.KDF import PBKDF2
|
| 3 |
import os
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
import tempfile
|
| 5 |
+
from dotenv import load_dotenv
|
|
|
|
| 6 |
|
| 7 |
+
load_dotenv() # Load all environment variables
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
+
if not password:
|
| 16 |
+
raise ValueError("PASSWORD secret not found in environment variables")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
+
password = password.encode()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
|
| 20 |
+
with open("code.enc", "rb") as f:
|
| 21 |
+
encrypted = f.read()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
|
| 23 |
+
salt = encrypted[:16]
|
| 24 |
+
iv = encrypted[16:32]
|
| 25 |
+
ciphertext = encrypted[32:]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
|
| 27 |
+
key = PBKDF2(password, salt, dkLen=32, count=1000000)
|
| 28 |
+
cipher = AES.new(key, AES.MODE_CBC, iv)
|
| 29 |
+
|
| 30 |
+
plaintext = unpad(cipher.decrypt(ciphertext))
|
| 31 |
+
|
| 32 |
+
with tempfile.NamedTemporaryFile(suffix=".py", delete=False, mode='wb') as tmp:
|
| 33 |
+
tmp.write(plaintext)
|
| 34 |
+
tmp.flush()
|
| 35 |
+
print(f"[INFO] Running decrypted code from {tmp.name}")
|
| 36 |
+
os.system(f"python {tmp.name}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
|
|
|
|
| 38 |
if __name__ == "__main__":
|
| 39 |
+
decrypt_and_run()
|
| 40 |
+
|
| 41 |
+
# This script decrypts the encrypted code and runs it.
|
| 42 |
+
# Ensure you have the PASSWORD secret set in your Hugging Face Secrets
|