shukdevdattaEX commited on
Commit
1ec950d
Β·
verified Β·
1 Parent(s): 431b5dc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +18 -31
app.py CHANGED
@@ -12,7 +12,6 @@ from datetime import datetime
12
  import tempfile
13
  import weasyprint
14
  from pathlib import Path
15
-
16
  # Function to convert markdown to HTML with styling
17
  def markdown_to_html(markdown_text, problem_text="", include_problem=True):
18
  """Convert markdown to styled HTML"""
@@ -20,6 +19,14 @@ def markdown_to_html(markdown_text, problem_text="", include_problem=True):
20
  html_content = markdown.markdown(markdown_text, extensions=['tables', 'fenced_code'])
21
  # Get current timestamp
22
  timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
 
 
 
 
 
 
 
 
23
  # Create styled HTML document
24
  styled_html = f"""<!DOCTYPE html>
25
  <html lang="en">
@@ -226,10 +233,7 @@ def markdown_to_html(markdown_text, problem_text="", include_problem=True):
226
  <div class="subtitle">Step-by-Step Mathematical Solution</div>
227
  </div>
228
  <button class="print-button" onclick="printPage()">πŸ–¨οΈ Print to PDF</button>
229
- {f'''<div class="problem-section">
230
- <h2>πŸ“ Problem Statement</h2>
231
- <p><strong>{problem_text}</strong></p>
232
- </div>''' if include_problem and problem_text.strip() else ''}
233
  <div class="solution-content">
234
  <h2>πŸ” Solution</h2>
235
  {html_content}
@@ -239,7 +243,6 @@ def markdown_to_html(markdown_text, problem_text="", include_problem=True):
239
  </body>
240
  </html>"""
241
  return styled_html
242
-
243
  # Function to save HTML to file
244
  def save_html_to_file(html_content, filename_prefix="math_solution"):
245
  """Save HTML content to a temporary file and return the file path"""
@@ -251,7 +254,6 @@ def save_html_to_file(html_content, filename_prefix="math_solution"):
251
  with open(file_path, 'w', encoding='utf-8') as f:
252
  f.write(html_content)
253
  return file_path
254
-
255
  # Function to convert HTML to PDF
256
  def html_to_pdf(html_content, filename_prefix="math_solution"):
257
  """Convert HTML content to PDF and return the file path"""
@@ -267,7 +269,6 @@ def html_to_pdf(html_content, filename_prefix="math_solution"):
267
  except Exception as e:
268
  print(f"Error converting to PDF: {str(e)}")
269
  return None
270
-
271
  # Enhanced function to generate math solution using OpenRouter with HTML output
272
  def generate_math_solution_openrouter(api_key, problem_text, history=None):
273
  if not api_key.strip():
@@ -328,7 +329,6 @@ Do not use [ ] or code blocks for math expressions; use math delimiters instead.
328
  except Exception as e:
329
  error_message = f"Error: {str(e)}"
330
  return error_message, None, None, history
331
-
332
  # Enhanced function to generate math solution using Together AI with HTML output
333
  def generate_math_solution_together(api_key, problem_text, image_path=None, history=None):
334
  if not api_key.strip():
@@ -420,7 +420,6 @@ Do not use [ ] or code blocks for math expressions; use math delimiters instead.
420
  except Exception as e:
421
  error_message = f"Error: {str(e)}"
422
  return error_message, None, None, history
423
-
424
  # Function to convert image to base64
425
  def image_to_base64(image_path):
426
  if image_path is None:
@@ -431,7 +430,6 @@ def image_to_base64(image_path):
431
  except Exception as e:
432
  print(f"Error converting image to base64: {str(e)}")
433
  return None
434
-
435
  # Define the Gradio interface
436
  def create_demo():
437
  with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue")) as demo:
@@ -493,7 +491,6 @@ def create_demo():
493
  gr.update(value=html_file, visible=html_file is not None),
494
  gr.update(value=pdf_file, visible=pdf_file is not None)
495
  )
496
-
497
  openrouter_submit_btn.click(
498
  fn=handle_openrouter_submit,
499
  inputs=[openrouter_api_key, text_problem_input, openrouter_conversation_history],
@@ -504,7 +501,6 @@ def create_demo():
504
  openrouter_pdf_download
505
  ]
506
  )
507
-
508
  def clear_openrouter():
509
  return (
510
  "",
@@ -512,7 +508,6 @@ def create_demo():
512
  gr.update(value=None, visible=False),
513
  gr.update(value=None, visible=False)
514
  )
515
-
516
  openrouter_clear_btn.click(
517
  fn=clear_openrouter,
518
  inputs=[],
@@ -523,7 +518,6 @@ def create_demo():
523
  openrouter_pdf_download
524
  ]
525
  )
526
-
527
  # Image-based problem solver (Together AI)
528
  with gr.TabItem("Image Problem Solver (Together AI)"):
529
  with gr.Row():
@@ -570,7 +564,6 @@ def create_demo():
570
  gr.update(value=html_file, visible=html_file is not None),
571
  gr.update(value=pdf_file, visible=pdf_file is not None)
572
  )
573
-
574
  together_submit_btn.click(
575
  fn=handle_together_submit,
576
  inputs=[together_api_key, together_problem_input, together_image_input, together_conversation_history],
@@ -581,7 +574,6 @@ def create_demo():
581
  together_pdf_download
582
  ]
583
  )
584
-
585
  def clear_together():
586
  return (
587
  "",
@@ -589,7 +581,6 @@ def create_demo():
589
  gr.update(value=None, visible=False),
590
  gr.update(value=None, visible=False)
591
  )
592
-
593
  together_clear_btn.click(
594
  fn=clear_together,
595
  inputs=[],
@@ -600,47 +591,45 @@ def create_demo():
600
  together_pdf_download
601
  ]
602
  )
603
-
604
  # Help tab
605
  with gr.TabItem("Help"):
606
  gr.Markdown(
607
  """## How to Use the Advanced Math Tutor
608
-
609
  ### New Features πŸŽ‰
610
  - **HTML-formatted solutions**: All responses are now generated in beautiful HTML format with MathJax for proper math rendering
611
  - **Download HTML**: Download the complete solution as an HTML file (math renders perfectly)
612
  - **Download PDF**: Convert and download solutions as PDF files (note: math may appear as raw LaTeX in server-generated PDF due to limitations; use browser print for best results)
613
  - **Print functionality**: Use the "Print to PDF" button in the HTML output to print directly (renders math via MathJax)
614
-
615
  ### Getting Started
616
  #### For Text-Based Problems (OpenRouter)
617
  1. You'll need an API key from OpenRouter
618
  2. Sign up at [OpenRouter](https://openrouter.ai/) to get your API key
619
  3. Enter your API key in the designated field in the "Text Problem Solver" tab
620
-
621
  #### For Image-Based Problems (Together AI)
622
  1. You'll need an API key from Together AI
623
  2. Sign up at [Together AI](https://www.together.ai/) to get your API key
624
  3. Enter your API key in the designated field in the "Image Problem Solver" tab
625
  4. Upload an image of your math problem
626
  5. Optionally add text to provide additional context
627
-
628
  ### Solving Math Problems
629
  - For text problems: Type or paste your math problem in the input field
630
  - For image problems: Upload a clear image of the math problem
631
  - Click "Solve Problem" to get a detailed step-by-step solution in HTML format
632
  - Use the download buttons to save HTML or PDF versions
633
  - Click "Print to PDF" within the solution to print directly from your browser
634
-
635
  ### HTML Output Features
636
  - **Professional styling**: Clean, readable format with proper typography
637
  - **Mathematical expressions**: Rendered with MathJax for beautiful LaTeX support
638
  - **Step-by-step sections**: Clearly organized solution steps
639
  - **Print-friendly**: Optimized for printing and PDF conversion
640
  - **Timestamps**: Each solution includes generation timestamp
641
-
642
  **Note**: For best math rendering in PDF, open the HTML in your browser and use "Print to PDF" – this executes MathJax for perfect equations. The server-generated PDF may show raw math delimiters.
643
-
644
  ### Tips for Best Results
645
  - Be specific in your problem description
646
  - Include all necessary information
@@ -648,7 +637,7 @@ def create_demo():
648
  - For algebraic expressions, describe clearly (AI will format math properly)
649
  - Use parentheses to group terms clearly
650
  - For images, ensure the math problem is clearly visible and well-lit
651
-
652
  ### Types of Problems You Can Solve
653
  - Algebra (equations, inequalities, systems of equations)
654
  - Calculus (derivatives, integrals, limits)
@@ -657,16 +646,14 @@ def create_demo():
657
  - Statistics and Probability
658
  - Number Theory
659
  - And many more!
660
-
661
  ### Required Dependencies
662
  To run this application, you'll need to install:
663
  ```bash
664
  pip install gradio openai together pillow markdown weasyprint
665
-
666
  MathJax is loaded via CDN – no additional install needed."""
667
  )
668
- return demo
669
-
670
  # Launch the app
671
  if __name__ == "__main__":
672
  demo = create_demo()
 
12
  import tempfile
13
  import weasyprint
14
  from pathlib import Path
 
15
  # Function to convert markdown to HTML with styling
16
  def markdown_to_html(markdown_text, problem_text="", include_problem=True):
17
  """Convert markdown to styled HTML"""
 
19
  html_content = markdown.markdown(markdown_text, extensions=['tables', 'fenced_code'])
20
  # Get current timestamp
21
  timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
22
+ # Prepare problem section
23
+ if include_problem and problem_text.strip():
24
+ problem_section = f'''<div class="problem-section">
25
+ <h2>πŸ“ Problem Statement</h2>
26
+ <p><strong>{problem_text}</strong></p>
27
+ </div>'''
28
+ else:
29
+ problem_section = ''
30
  # Create styled HTML document
31
  styled_html = f"""<!DOCTYPE html>
32
  <html lang="en">
 
233
  <div class="subtitle">Step-by-Step Mathematical Solution</div>
234
  </div>
235
  <button class="print-button" onclick="printPage()">πŸ–¨οΈ Print to PDF</button>
236
+ {problem_section}
 
 
 
237
  <div class="solution-content">
238
  <h2>πŸ” Solution</h2>
239
  {html_content}
 
243
  </body>
244
  </html>"""
245
  return styled_html
 
246
  # Function to save HTML to file
247
  def save_html_to_file(html_content, filename_prefix="math_solution"):
248
  """Save HTML content to a temporary file and return the file path"""
 
254
  with open(file_path, 'w', encoding='utf-8') as f:
255
  f.write(html_content)
256
  return file_path
 
257
  # Function to convert HTML to PDF
258
  def html_to_pdf(html_content, filename_prefix="math_solution"):
259
  """Convert HTML content to PDF and return the file path"""
 
269
  except Exception as e:
270
  print(f"Error converting to PDF: {str(e)}")
271
  return None
 
272
  # Enhanced function to generate math solution using OpenRouter with HTML output
273
  def generate_math_solution_openrouter(api_key, problem_text, history=None):
274
  if not api_key.strip():
 
329
  except Exception as e:
330
  error_message = f"Error: {str(e)}"
331
  return error_message, None, None, history
 
332
  # Enhanced function to generate math solution using Together AI with HTML output
333
  def generate_math_solution_together(api_key, problem_text, image_path=None, history=None):
334
  if not api_key.strip():
 
420
  except Exception as e:
421
  error_message = f"Error: {str(e)}"
422
  return error_message, None, None, history
 
423
  # Function to convert image to base64
424
  def image_to_base64(image_path):
425
  if image_path is None:
 
430
  except Exception as e:
431
  print(f"Error converting image to base64: {str(e)}")
432
  return None
 
433
  # Define the Gradio interface
434
  def create_demo():
435
  with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue")) as demo:
 
491
  gr.update(value=html_file, visible=html_file is not None),
492
  gr.update(value=pdf_file, visible=pdf_file is not None)
493
  )
 
494
  openrouter_submit_btn.click(
495
  fn=handle_openrouter_submit,
496
  inputs=[openrouter_api_key, text_problem_input, openrouter_conversation_history],
 
501
  openrouter_pdf_download
502
  ]
503
  )
 
504
  def clear_openrouter():
505
  return (
506
  "",
 
508
  gr.update(value=None, visible=False),
509
  gr.update(value=None, visible=False)
510
  )
 
511
  openrouter_clear_btn.click(
512
  fn=clear_openrouter,
513
  inputs=[],
 
518
  openrouter_pdf_download
519
  ]
520
  )
 
521
  # Image-based problem solver (Together AI)
522
  with gr.TabItem("Image Problem Solver (Together AI)"):
523
  with gr.Row():
 
564
  gr.update(value=html_file, visible=html_file is not None),
565
  gr.update(value=pdf_file, visible=pdf_file is not None)
566
  )
 
567
  together_submit_btn.click(
568
  fn=handle_together_submit,
569
  inputs=[together_api_key, together_problem_input, together_image_input, together_conversation_history],
 
574
  together_pdf_download
575
  ]
576
  )
 
577
  def clear_together():
578
  return (
579
  "",
 
581
  gr.update(value=None, visible=False),
582
  gr.update(value=None, visible=False)
583
  )
 
584
  together_clear_btn.click(
585
  fn=clear_together,
586
  inputs=[],
 
591
  together_pdf_download
592
  ]
593
  )
 
594
  # Help tab
595
  with gr.TabItem("Help"):
596
  gr.Markdown(
597
  """## How to Use the Advanced Math Tutor
 
598
  ### New Features πŸŽ‰
599
  - **HTML-formatted solutions**: All responses are now generated in beautiful HTML format with MathJax for proper math rendering
600
  - **Download HTML**: Download the complete solution as an HTML file (math renders perfectly)
601
  - **Download PDF**: Convert and download solutions as PDF files (note: math may appear as raw LaTeX in server-generated PDF due to limitations; use browser print for best results)
602
  - **Print functionality**: Use the "Print to PDF" button in the HTML output to print directly (renders math via MathJax)
603
+
604
  ### Getting Started
605
  #### For Text-Based Problems (OpenRouter)
606
  1. You'll need an API key from OpenRouter
607
  2. Sign up at [OpenRouter](https://openrouter.ai/) to get your API key
608
  3. Enter your API key in the designated field in the "Text Problem Solver" tab
609
+
610
  #### For Image-Based Problems (Together AI)
611
  1. You'll need an API key from Together AI
612
  2. Sign up at [Together AI](https://www.together.ai/) to get your API key
613
  3. Enter your API key in the designated field in the "Image Problem Solver" tab
614
  4. Upload an image of your math problem
615
  5. Optionally add text to provide additional context
616
+
617
  ### Solving Math Problems
618
  - For text problems: Type or paste your math problem in the input field
619
  - For image problems: Upload a clear image of the math problem
620
  - Click "Solve Problem" to get a detailed step-by-step solution in HTML format
621
  - Use the download buttons to save HTML or PDF versions
622
  - Click "Print to PDF" within the solution to print directly from your browser
623
+
624
  ### HTML Output Features
625
  - **Professional styling**: Clean, readable format with proper typography
626
  - **Mathematical expressions**: Rendered with MathJax for beautiful LaTeX support
627
  - **Step-by-step sections**: Clearly organized solution steps
628
  - **Print-friendly**: Optimized for printing and PDF conversion
629
  - **Timestamps**: Each solution includes generation timestamp
630
+
631
  **Note**: For best math rendering in PDF, open the HTML in your browser and use "Print to PDF" – this executes MathJax for perfect equations. The server-generated PDF may show raw math delimiters.
632
+
633
  ### Tips for Best Results
634
  - Be specific in your problem description
635
  - Include all necessary information
 
637
  - For algebraic expressions, describe clearly (AI will format math properly)
638
  - Use parentheses to group terms clearly
639
  - For images, ensure the math problem is clearly visible and well-lit
640
+
641
  ### Types of Problems You Can Solve
642
  - Algebra (equations, inequalities, systems of equations)
643
  - Calculus (derivatives, integrals, limits)
 
646
  - Statistics and Probability
647
  - Number Theory
648
  - And many more!
649
+
650
  ### Required Dependencies
651
  To run this application, you'll need to install:
652
  ```bash
653
  pip install gradio openai together pillow markdown weasyprint
 
654
  MathJax is loaded via CDN – no additional install needed."""
655
  )
656
+ return demo
 
657
  # Launch the app
658
  if __name__ == "__main__":
659
  demo = create_demo()