shukdevdatta123 commited on
Commit
871e4ec
·
verified ·
1 Parent(s): 8911be7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +66 -52
app.py CHANGED
@@ -2,8 +2,11 @@ import gradio as gr
2
  import os
3
  import re
4
  import time
 
5
  from openai import OpenAI
6
  from together import Together
 
 
7
 
8
  # Function to generate math solution using the Phi-4-reasoning-plus model via OpenRouter
9
  def generate_math_solution_openrouter(api_key, problem_text, history=None):
@@ -66,53 +69,85 @@ def generate_math_solution_openrouter(api_key, problem_text, history=None):
66
  error_message = f"Error: {str(e)}"
67
  return error_message, history
68
 
 
 
 
 
 
 
 
 
 
 
 
 
69
  # Function to generate math solution using Together AI with support for images
70
- def generate_math_solution_together(api_key, problem_text, image=None, history=None):
71
  if not api_key.strip():
72
  return "Please enter your Together AI API key.", history
73
 
74
- if not problem_text.strip() and image is None:
75
  return "Please enter a math problem or upload an image of a math problem.", history
76
 
77
  try:
78
  client = Together(api_key=api_key)
79
 
80
- system_message = {
81
- "role": "system",
82
- "content": """You are an expert math tutor who explains concepts clearly and thoroughly.
83
- Analyze the given math problem and provide a detailed step-by-step solution.
84
- For each step:
85
- 1. Show the mathematical operation
86
- 2. Explain why this step is necessary
87
- 3. Connect it to relevant mathematical concepts
88
-
89
- Format your response with clear section headers using markdown.
90
- Begin with an "Initial Analysis" section, follow with numbered steps,
91
- and conclude with a "Final Answer" section."""
92
- }
93
-
94
- # Start with text content
95
- user_content = [{"type": "text", "text": f"Solve this math problem: {problem_text}"}]
96
-
97
- # Add image if provided
98
- if image is not None:
99
- user_content.append({
100
- "type": "image_url",
101
- "image_url": {"url": image}
102
- })
103
-
104
- messages = [system_message]
105
 
106
  # Add conversation history if it exists
107
  if history:
108
  for exchange in history:
109
- # For simplicity, we're assuming text-only history here
110
  messages.append({"role": "user", "content": exchange[0]})
111
  if exchange[1]: # Check if there's a response
112
  messages.append({"role": "assistant", "content": exchange[1]})
113
 
114
- # Add the current problem
115
- messages.append({"role": "user", "content": user_content})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
116
 
117
  # Create the completion
118
  response = client.chat.completions.create(
@@ -126,7 +161,7 @@ def generate_math_solution_together(api_key, problem_text, image=None, history=N
126
  # Update history - for simplicity, just store the text problem
127
  if history is None:
128
  history = []
129
- history.append((problem_text, solution))
130
 
131
  return solution, history
132
 
@@ -134,27 +169,6 @@ def generate_math_solution_together(api_key, problem_text, image=None, history=N
134
  error_message = f"Error: {str(e)}"
135
  return error_message, history
136
 
137
- # Function to verify API key format
138
- def validate_openrouter_key(api_key):
139
- # This is a simple check - OpenRouter keys typically start with "sk-or-"
140
- if api_key.startswith("sk-or-") and len(api_key) > 20:
141
- return True
142
- return False
143
-
144
- # Function to validate Together AI API key (basic format check)
145
- def validate_together_key(api_key):
146
- # Together API keys usually have a specific format
147
- # This is just a simple length check for now
148
- if len(api_key) > 20:
149
- return True
150
- return False
151
-
152
- # Function to process LaTeX in the solution
153
- def process_solution(solution):
154
- # Replace $...$ with $$...$$ for better rendering in Gradio markdown
155
- solution = re.sub(r'(?<!\$)\$(?!\$)(.+?)(?<!\$)\$(?!\$)', r'$$\1$$', solution)
156
- return solution
157
-
158
  # Define the Gradio interface
159
  def create_demo():
160
  with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue")) as demo:
 
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
 
11
  # Function to generate math solution using the Phi-4-reasoning-plus model via OpenRouter
12
  def generate_math_solution_openrouter(api_key, problem_text, history=None):
 
69
  error_message = f"Error: {str(e)}"
70
  return error_message, history
71
 
72
+ # Function to convert image to base64
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
  # Function to generate math solution using Together AI with support for images
85
+ def generate_math_solution_together(api_key, problem_text, image_path=None, history=None):
86
  if not api_key.strip():
87
  return "Please enter your Together AI API key.", history
88
 
89
+ if not problem_text.strip() and image_path is None:
90
  return "Please enter a math problem or upload an image of a math problem.", history
91
 
92
  try:
93
  client = Together(api_key=api_key)
94
 
95
+ # Create the base message structure
96
+ messages = [
97
+ {
98
+ "role": "system",
99
+ "content": """You are an expert math tutor who explains concepts clearly and thoroughly.
100
+ Analyze the given math problem and provide a detailed step-by-step solution.
101
+ For each step:
102
+ 1. Show the mathematical operation
103
+ 2. Explain why this step is necessary
104
+ 3. Connect it to relevant mathematical concepts
105
+
106
+ Format your response with clear section headers using markdown.
107
+ Begin with an "Initial Analysis" section, follow with numbered steps,
108
+ and conclude with a "Final Answer" section."""
109
+ }
110
+ ]
 
 
 
 
 
 
 
 
 
111
 
112
  # Add conversation history if it exists
113
  if history:
114
  for exchange in history:
 
115
  messages.append({"role": "user", "content": exchange[0]})
116
  if exchange[1]: # Check if there's a response
117
  messages.append({"role": "assistant", "content": exchange[1]})
118
 
119
+ # Prepare the user message content
120
+ user_message_content = []
121
+
122
+ # Add text content if provided
123
+ if problem_text.strip():
124
+ user_message_content.append({
125
+ "type": "text",
126
+ "text": f"Solve this math problem: {problem_text}"
127
+ })
128
+ else:
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",
149
+ "content": user_message_content
150
+ })
151
 
152
  # Create the completion
153
  response = client.chat.completions.create(
 
161
  # Update history - for simplicity, just store the text problem
162
  if history is None:
163
  history = []
164
+ history.append((problem_text if problem_text.strip() else "Image problem", solution))
165
 
166
  return solution, history
167
 
 
169
  error_message = f"Error: {str(e)}"
170
  return error_message, history
171
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
172
  # Define the Gradio interface
173
  def create_demo():
174
  with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue")) as demo: