Spaces:
Build error
Build error
Update image.py
Browse files
image.py
CHANGED
|
@@ -16,6 +16,15 @@ logger = logging.getLogger(__name__)
|
|
| 16 |
# Define symbolic variables
|
| 17 |
x, y = sp.symbols('x y')
|
| 18 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
# Initialize Pix2Text model globally
|
| 20 |
try:
|
| 21 |
p2t_model = Pix2Text.from_config()
|
|
@@ -28,7 +37,7 @@ def clean_latex_expression(latex_str):
|
|
| 28 |
"""Clean and normalize LaTeX expression for SymPy parsing"""
|
| 29 |
if not latex_str:
|
| 30 |
return ""
|
| 31 |
-
|
| 32 |
latex_str = latex_str.strip()
|
| 33 |
latex_str = re.sub(r'^\$\$|\$\$$', '', latex_str) # Remove $$ delimiters
|
| 34 |
latex_str = re.sub(r'\\[a-zA-Z]+\{([^}]*)\}', r'\1', latex_str) # Remove LaTeX commands
|
|
@@ -37,9 +46,23 @@ def clean_latex_expression(latex_str):
|
|
| 37 |
latex_str = re.sub(r'\^{([^}]+)}', r'**\1', latex_str) # Convert x^{n} to x**n
|
| 38 |
latex_str = re.sub(r'(\d*\.?\d+)\s*([xy])', r'\1*\2', latex_str) # Add multiplication: 1.0x -> 1.0*x
|
| 39 |
latex_str = re.sub(r'\s*([+\-*/=])\s*', r'\1', latex_str) # Remove spaces around operators
|
|
|
|
| 40 |
if '=' in latex_str:
|
| 41 |
left, right = latex_str.split('=')
|
| 42 |
latex_str = f"{left} - ({right})" # Move right-hand side to left
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
return latex_str.strip()
|
| 44 |
|
| 45 |
def parse_equation_type(latex_str):
|
|
@@ -62,13 +85,13 @@ def parse_equation_type(latex_str):
|
|
| 62 |
degree = sp.degree(expr, x)
|
| 63 |
return 'polynomial' if degree > 0 else 'linear'
|
| 64 |
elif x not in expr.free_symbols and y in expr.free_symbols:
|
| 65 |
-
return 'polynomial'
|
| 66 |
else:
|
| 67 |
-
return 'polynomial'
|
| 68 |
except:
|
| 69 |
if 'x**' in cleaned or '^' in latex_str:
|
| 70 |
return 'polynomial'
|
| 71 |
-
return 'polynomial'
|
| 72 |
except Exception as e:
|
| 73 |
logger.error(f"Error determining equation type: {e}")
|
| 74 |
return 'polynomial'
|
|
@@ -79,12 +102,12 @@ def extract_polynomial_coefficients(latex_str):
|
|
| 79 |
expr = sp.sympify(cleaned, evaluate=False)
|
| 80 |
if x not in expr.free_symbols and y not in expr.free_symbols:
|
| 81 |
raise ValueError("No variable (x or y) found in expression")
|
| 82 |
-
variable =
|
| 83 |
degree = sp.degree(expr, variable)
|
| 84 |
if degree < 1 or degree > 8:
|
| 85 |
raise ValueError(f"Polynomial degree {degree} is out of supported range (1-8)")
|
| 86 |
poly = sp.Poly(expr, variable)
|
| 87 |
-
coeffs = [
|
| 88 |
return {
|
| 89 |
"type": "polynomial",
|
| 90 |
"degree": degree,
|
|
@@ -105,103 +128,17 @@ def extract_polynomial_coefficients(latex_str):
|
|
| 105 |
"variable": "x"
|
| 106 |
}
|
| 107 |
|
| 108 |
-
def
|
| 109 |
-
try:
|
| 110 |
-
cleaned = clean_latex_expression(latex_str)
|
| 111 |
-
equations = re.split(r'\\\\|\n|;', latex_str)
|
| 112 |
-
if len(equations) < 2:
|
| 113 |
-
equations = re.split(r'(?<=[0-9])\s*(?=[+-]?\s*[0-9]*[xy])', cleaned)
|
| 114 |
-
if len(equations) < 2 or 'y' not in cleaned or 'x' not in cleaned:
|
| 115 |
-
raise ValueError("Could not find two equations or two variables (x, y) in system")
|
| 116 |
-
eq1_str = equations[0].strip()
|
| 117 |
-
eq2_str = equations[1].strip()
|
| 118 |
-
def parse_linear_eq(eq_str):
|
| 119 |
-
if '-' not in eq_str:
|
| 120 |
-
raise ValueError("No equals sign (converted to '-') found")
|
| 121 |
-
left, right = eq_str.split('-')
|
| 122 |
-
expr = sp.sympify(left) - sp.sympify(right or '0')
|
| 123 |
-
a = float(expr.coeff(x, 1)) if expr.coeff(x, 1) else 0
|
| 124 |
-
b = float(expr.coeff(y, 1)) if expr.coeff(y, 1) else 0
|
| 125 |
-
c = float(-expr.as_coefficients_dict()[1]) if 1 in expr.as_coefficients_dict() else 0
|
| 126 |
-
return f"{a} {b} {c}"
|
| 127 |
-
eq1_coeffs = parse_linear_eq(eq1_str)
|
| 128 |
-
eq2_coeffs = parse_linear_eq(eq2_str)
|
| 129 |
-
return {
|
| 130 |
-
"type": "linear",
|
| 131 |
-
"eq1_coeffs": eq1_coeffs,
|
| 132 |
-
"eq2_coeffs": eq2_coeffs,
|
| 133 |
-
"latex": latex_str,
|
| 134 |
-
"success": True
|
| 135 |
-
}
|
| 136 |
-
except Exception as e:
|
| 137 |
-
logger.error(f"Error extracting linear system coefficients: {e}")
|
| 138 |
-
return {
|
| 139 |
-
"type": "linear",
|
| 140 |
-
"eq1_coeffs": "1 1 3",
|
| 141 |
-
"eq2_coeffs": "1 -1 1",
|
| 142 |
-
"latex": latex_str,
|
| 143 |
-
"success": False,
|
| 144 |
-
"error": str(e)
|
| 145 |
-
}
|
| 146 |
-
|
| 147 |
-
def extract_equation_from_image(image_file):
|
| 148 |
-
try:
|
| 149 |
-
if p2t_model is None:
|
| 150 |
-
return {
|
| 151 |
-
"type": "error",
|
| 152 |
-
"latex": "Pix2Text model not loaded. Please check installation.",
|
| 153 |
-
"success": False
|
| 154 |
-
}
|
| 155 |
-
if image_file is None:
|
| 156 |
-
return {
|
| 157 |
-
"type": "error",
|
| 158 |
-
"latex": "No image file provided.",
|
| 159 |
-
"success": False
|
| 160 |
-
}
|
| 161 |
-
if isinstance(image_file, str):
|
| 162 |
-
image = Image.open(image_file)
|
| 163 |
-
else:
|
| 164 |
-
image = Image.open(image_file.name)
|
| 165 |
-
if image.mode != 'RGB':
|
| 166 |
-
image = image.convert('RGB')
|
| 167 |
-
logger.info(f"Processing image of size: {image.size}")
|
| 168 |
-
result = p2t_model.recognize_text_formula(image)
|
| 169 |
-
if not result or result.strip() == "":
|
| 170 |
-
return {
|
| 171 |
-
"type": "error",
|
| 172 |
-
"latex": "No text or formulas detected in the image.",
|
| 173 |
-
"success": False
|
| 174 |
-
}
|
| 175 |
-
logger.info(f"Extracted text: {result}")
|
| 176 |
-
eq_type = parse_equation_type(result)
|
| 177 |
-
if eq_type == 'polynomial':
|
| 178 |
-
return extract_polynomial_coefficients(result)
|
| 179 |
-
elif eq_type == 'linear_system':
|
| 180 |
-
return extract_linear_system_coefficients(result)
|
| 181 |
-
else:
|
| 182 |
-
return {
|
| 183 |
-
"type": "error",
|
| 184 |
-
"latex": f"Unsupported equation type detected: {eq_type}",
|
| 185 |
-
"success": False
|
| 186 |
-
}
|
| 187 |
-
except Exception as e:
|
| 188 |
-
logger.error(f"Error processing image: {e}")
|
| 189 |
-
return {
|
| 190 |
-
"type": "error",
|
| 191 |
-
"latex": f"Error processing image: {str(e)}",
|
| 192 |
-
"success": False
|
| 193 |
-
}
|
| 194 |
-
|
| 195 |
-
def solve_polynomial(degree, coeff_string, real_only):
|
| 196 |
try:
|
| 197 |
coeffs = list(map(float, coeff_string.strip().split()))
|
| 198 |
if len(coeffs) != degree + 1:
|
| 199 |
return f"⚠️ Please enter exactly {degree + 1} coefficients.", None, None
|
| 200 |
|
| 201 |
-
|
|
|
|
| 202 |
simplified = sp.simplify(poly)
|
| 203 |
factored = sp.factor(simplified)
|
| 204 |
-
roots = sp.solve(sp.Eq(simplified, 0),
|
| 205 |
|
| 206 |
if real_only:
|
| 207 |
roots = [r for r in roots if sp.im(r) == 0]
|
|
@@ -238,6 +175,48 @@ $$ {sp.latex(factored)} = 0 $$
|
|
| 238 |
except Exception as e:
|
| 239 |
return f"❌ Error: {e}", None, ""
|
| 240 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 241 |
def solve_linear_system_from_coeffs(eq1_str, eq2_str):
|
| 242 |
try:
|
| 243 |
coeffs1 = list(map(float, eq1_str.strip().split()))
|
|
@@ -293,9 +272,64 @@ def solve_linear_system_from_coeffs(eq1_str, eq2_str):
|
|
| 293 |
except Exception as e:
|
| 294 |
return f"❌ Error: {e}", None, None, None
|
| 295 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 296 |
def solve_extracted_equation(eq_data, real_only):
|
| 297 |
if eq_data["type"] == "polynomial":
|
| 298 |
-
return solve_polynomial(eq_data["degree"], eq_data["coeffs"], real_only)
|
| 299 |
elif eq_data["type"] == "linear":
|
| 300 |
return "❌ Single linear equation not supported. Please upload a system of equations.", None, ""
|
| 301 |
elif eq_data["type"] == "linear_system":
|
|
@@ -307,7 +341,7 @@ def image_tab():
|
|
| 307 |
"""Create the Image Upload Solver tab"""
|
| 308 |
with gr.Tab("Image Upload Solver"):
|
| 309 |
gr.Markdown("## Solve Equations from Image")
|
| 310 |
-
|
| 311 |
with gr.Row():
|
| 312 |
image_input = gr.File(
|
| 313 |
label="Upload Question Image",
|
|
@@ -315,7 +349,7 @@ def image_tab():
|
|
| 315 |
file_count="single"
|
| 316 |
)
|
| 317 |
image_upload_btn = gr.Button("Process Image")
|
| 318 |
-
|
| 319 |
gr.Markdown("**Supported Formats:** .pdf, .png, .jpg, .jpeg")
|
| 320 |
|
| 321 |
with gr.Row():
|
|
@@ -323,7 +357,7 @@ def image_tab():
|
|
| 323 |
preview_image_btn = gr.Button("Preview Equation")
|
| 324 |
|
| 325 |
image_equation_display = gr.Markdown()
|
| 326 |
-
|
| 327 |
with gr.Row():
|
| 328 |
confirm_image_btn = gr.Button("Display Solution", visible=False)
|
| 329 |
edit_image_btn = gr.Button("Make Changes Manually", visible=False)
|
|
@@ -335,7 +369,6 @@ def image_tab():
|
|
| 335 |
image_plot_output = gr.Plot()
|
| 336 |
extracted_eq_state = gr.State()
|
| 337 |
|
| 338 |
-
# ✅ Added for LLM explanation
|
| 339 |
llm_url_input = gr.Textbox(label="LLM Microservice URL (optional)", placeholder="https://your-llm.ngrok.app")
|
| 340 |
explain_image_btn = gr.Button("Explain with LLM")
|
| 341 |
image_solution_txt = gr.Textbox(visible=False)
|
|
@@ -352,7 +385,7 @@ def image_tab():
|
|
| 352 |
image_upload_btn.click(
|
| 353 |
fn=handle_image_upload,
|
| 354 |
inputs=[image_input],
|
| 355 |
-
outputs=[image_equation_display, extracted_eq_state, image_steps_md,
|
| 356 |
image_plot_output, edit_latex_input]
|
| 357 |
)
|
| 358 |
|
|
@@ -371,7 +404,7 @@ def image_tab():
|
|
| 371 |
preview_image_btn.click(
|
| 372 |
fn=preview_image_equation,
|
| 373 |
inputs=[extracted_eq_state, real_image_checkbox],
|
| 374 |
-
outputs=[image_equation_display, confirm_image_btn, edit_image_btn,
|
| 375 |
image_steps_md, image_plot_output]
|
| 376 |
)
|
| 377 |
|
|
@@ -393,9 +426,9 @@ def image_tab():
|
|
| 393 |
def enable_manual_edit(eq_data):
|
| 394 |
latex_value = eq_data.get("latex", "") if eq_data and eq_data["type"] != "error" else "Error in extraction."
|
| 395 |
return (
|
| 396 |
-
gr.update(visible=True, value=latex_value),
|
| 397 |
-
gr.update(visible=True),
|
| 398 |
-
gr.update(visible=False),
|
| 399 |
gr.update(visible=False)
|
| 400 |
)
|
| 401 |
|
|
@@ -412,7 +445,7 @@ def image_tab():
|
|
| 412 |
eq_type = parse_equation_type(latex_input)
|
| 413 |
if eq_type == 'polynomial':
|
| 414 |
eq_data = extract_polynomial_coefficients(latex_input)
|
| 415 |
-
steps, plot, _ = solve_polynomial(eq_data["degree"], eq_data["coeffs"], real_only)
|
| 416 |
elif eq_type == 'linear_system':
|
| 417 |
eq_data = extract_linear_system_coefficients(latex_input)
|
| 418 |
_, steps, plot, _ = solve_linear_system_from_coeffs(eq_data["eq1_coeffs"], eq_data["eq2_coeffs"])
|
|
@@ -428,7 +461,6 @@ def image_tab():
|
|
| 428 |
outputs=[image_steps_md, image_plot_output, image_solution_txt]
|
| 429 |
)
|
| 430 |
|
| 431 |
-
# ✅ Button to send solution to LLM
|
| 432 |
explain_image_btn.click(
|
| 433 |
fn=lambda sol, url: explain_with_llm(sol, "image", url),
|
| 434 |
inputs=[image_solution_txt, llm_url_input],
|
|
@@ -439,5 +471,5 @@ def image_tab():
|
|
| 439 |
image_input, image_upload_btn, real_image_checkbox, preview_image_btn,
|
| 440 |
image_equation_display, confirm_image_btn, edit_image_btn, edit_latex_input,
|
| 441 |
save_edit_btn, image_steps_md, image_plot_output, extracted_eq_state,
|
| 442 |
-
llm_url_input, explain_image_btn, image_solution_txt
|
| 443 |
)
|
|
|
|
| 16 |
# Define symbolic variables
|
| 17 |
x, y = sp.symbols('x y')
|
| 18 |
|
| 19 |
+
# ✅ Helper to get safe variable symbol
|
| 20 |
+
def get_variable_symbol(varname):
|
| 21 |
+
if varname in {"pi", "e", "I", "i"}:
|
| 22 |
+
return x
|
| 23 |
+
try:
|
| 24 |
+
return sp.Symbol(varname)
|
| 25 |
+
except Exception:
|
| 26 |
+
return x
|
| 27 |
+
|
| 28 |
# Initialize Pix2Text model globally
|
| 29 |
try:
|
| 30 |
p2t_model = Pix2Text.from_config()
|
|
|
|
| 37 |
"""Clean and normalize LaTeX expression for SymPy parsing"""
|
| 38 |
if not latex_str:
|
| 39 |
return ""
|
| 40 |
+
|
| 41 |
latex_str = latex_str.strip()
|
| 42 |
latex_str = re.sub(r'^\$\$|\$\$$', '', latex_str) # Remove $$ delimiters
|
| 43 |
latex_str = re.sub(r'\\[a-zA-Z]+\{([^}]*)\}', r'\1', latex_str) # Remove LaTeX commands
|
|
|
|
| 46 |
latex_str = re.sub(r'\^{([^}]+)}', r'**\1', latex_str) # Convert x^{n} to x**n
|
| 47 |
latex_str = re.sub(r'(\d*\.?\d+)\s*([xy])', r'\1*\2', latex_str) # Add multiplication: 1.0x -> 1.0*x
|
| 48 |
latex_str = re.sub(r'\s*([+\-*/=])\s*', r'\1', latex_str) # Remove spaces around operators
|
| 49 |
+
|
| 50 |
if '=' in latex_str:
|
| 51 |
left, right = latex_str.split('=')
|
| 52 |
latex_str = f"{left} - ({right})" # Move right-hand side to left
|
| 53 |
+
|
| 54 |
+
# ✅ Insert missing multiplication
|
| 55 |
+
latex_str = re.sub(r'(\))([a-zA-Z])', r'\1*\2', latex_str)
|
| 56 |
+
latex_str = re.sub(r'(\d|\w)\(', r'\1*(', latex_str)
|
| 57 |
+
|
| 58 |
+
# ✅ Replace LaTeX constants with sympy
|
| 59 |
+
latex_str = latex_str.replace(r'\pi', 'pi')
|
| 60 |
+
latex_str = latex_str.replace(r'\mathrm{e}', 'e')
|
| 61 |
+
latex_str = latex_str.replace(r'\cdot', '*')
|
| 62 |
+
latex_str = latex_str.replace(r'\times', '*')
|
| 63 |
+
latex_str = latex_str.replace(r'\\', '')
|
| 64 |
+
latex_str = re.sub(r'\\sqrt\{([^}]+)\}', r'sqrt(\1)', latex_str)
|
| 65 |
+
|
| 66 |
return latex_str.strip()
|
| 67 |
|
| 68 |
def parse_equation_type(latex_str):
|
|
|
|
| 85 |
degree = sp.degree(expr, x)
|
| 86 |
return 'polynomial' if degree > 0 else 'linear'
|
| 87 |
elif x not in expr.free_symbols and y in expr.free_symbols:
|
| 88 |
+
return 'polynomial'
|
| 89 |
else:
|
| 90 |
+
return 'polynomial'
|
| 91 |
except:
|
| 92 |
if 'x**' in cleaned or '^' in latex_str:
|
| 93 |
return 'polynomial'
|
| 94 |
+
return 'polynomial'
|
| 95 |
except Exception as e:
|
| 96 |
logger.error(f"Error determining equation type: {e}")
|
| 97 |
return 'polynomial'
|
|
|
|
| 102 |
expr = sp.sympify(cleaned, evaluate=False)
|
| 103 |
if x not in expr.free_symbols and y not in expr.free_symbols:
|
| 104 |
raise ValueError("No variable (x or y) found in expression")
|
| 105 |
+
variable = next(iter(expr.free_symbols))
|
| 106 |
degree = sp.degree(expr, variable)
|
| 107 |
if degree < 1 or degree > 8:
|
| 108 |
raise ValueError(f"Polynomial degree {degree} is out of supported range (1-8)")
|
| 109 |
poly = sp.Poly(expr, variable)
|
| 110 |
+
coeffs = [poly.coeff_monomial(variable**i).evalf() for i in range(degree, -1, -1)]
|
| 111 |
return {
|
| 112 |
"type": "polynomial",
|
| 113 |
"degree": degree,
|
|
|
|
| 128 |
"variable": "x"
|
| 129 |
}
|
| 130 |
|
| 131 |
+
def solve_polynomial(degree, coeff_string, real_only, variable="x"):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 132 |
try:
|
| 133 |
coeffs = list(map(float, coeff_string.strip().split()))
|
| 134 |
if len(coeffs) != degree + 1:
|
| 135 |
return f"⚠️ Please enter exactly {degree + 1} coefficients.", None, None
|
| 136 |
|
| 137 |
+
var = get_variable_symbol(variable)
|
| 138 |
+
poly = sum([coeffs[i] * var**(degree - i) for i in range(degree + 1)])
|
| 139 |
simplified = sp.simplify(poly)
|
| 140 |
factored = sp.factor(simplified)
|
| 141 |
+
roots = sp.solve(sp.Eq(simplified, 0), var)
|
| 142 |
|
| 143 |
if real_only:
|
| 144 |
roots = [r for r in roots if sp.im(r) == 0]
|
|
|
|
| 175 |
except Exception as e:
|
| 176 |
return f"❌ Error: {e}", None, ""
|
| 177 |
|
| 178 |
+
def extract_linear_system_coefficients(latex_str):
|
| 179 |
+
try:
|
| 180 |
+
cleaned = clean_latex_expression(latex_str)
|
| 181 |
+
equations = re.split(r'\\\\|\n|;', latex_str)
|
| 182 |
+
if len(equations) < 2:
|
| 183 |
+
equations = re.split(r'(?<=[0-9])\s*(?=[+-]?\s*[0-9]*[xy])', cleaned)
|
| 184 |
+
if len(equations) < 2 or 'y' not in cleaned or 'x' not in cleaned:
|
| 185 |
+
raise ValueError("Could not find two equations or two variables (x, y) in system")
|
| 186 |
+
|
| 187 |
+
eq1_str = equations[0].strip()
|
| 188 |
+
eq2_str = equations[1].strip()
|
| 189 |
+
|
| 190 |
+
def parse_linear_eq(eq_str):
|
| 191 |
+
if '-' not in eq_str:
|
| 192 |
+
raise ValueError("No equals sign (converted to '-') found")
|
| 193 |
+
left, right = eq_str.split('-')
|
| 194 |
+
expr = sp.sympify(left) - sp.sympify(right or '0')
|
| 195 |
+
a = float(expr.coeff(x, 1)) if expr.coeff(x, 1) else 0
|
| 196 |
+
b = float(expr.coeff(y, 1)) if expr.coeff(y, 1) else 0
|
| 197 |
+
c = float(-expr.as_coefficients_dict()[1]) if 1 in expr.as_coefficients_dict() else 0
|
| 198 |
+
return f"{a} {b} {c}"
|
| 199 |
+
|
| 200 |
+
eq1_coeffs = parse_linear_eq(eq1_str)
|
| 201 |
+
eq2_coeffs = parse_linear_eq(eq2_str)
|
| 202 |
+
return {
|
| 203 |
+
"type": "linear",
|
| 204 |
+
"eq1_coeffs": eq1_coeffs,
|
| 205 |
+
"eq2_coeffs": eq2_coeffs,
|
| 206 |
+
"latex": latex_str,
|
| 207 |
+
"success": True
|
| 208 |
+
}
|
| 209 |
+
except Exception as e:
|
| 210 |
+
logger.error(f"Error extracting linear system coefficients: {e}")
|
| 211 |
+
return {
|
| 212 |
+
"type": "linear",
|
| 213 |
+
"eq1_coeffs": "1 1 3",
|
| 214 |
+
"eq2_coeffs": "1 -1 1",
|
| 215 |
+
"latex": latex_str,
|
| 216 |
+
"success": False,
|
| 217 |
+
"error": str(e)
|
| 218 |
+
}
|
| 219 |
+
|
| 220 |
def solve_linear_system_from_coeffs(eq1_str, eq2_str):
|
| 221 |
try:
|
| 222 |
coeffs1 = list(map(float, eq1_str.strip().split()))
|
|
|
|
| 272 |
except Exception as e:
|
| 273 |
return f"❌ Error: {e}", None, None, None
|
| 274 |
|
| 275 |
+
def extract_equation_from_image(image_file):
|
| 276 |
+
try:
|
| 277 |
+
if p2t_model is None:
|
| 278 |
+
return {
|
| 279 |
+
"type": "error",
|
| 280 |
+
"latex": "Pix2Text model not loaded. Please check installation.",
|
| 281 |
+
"success": False
|
| 282 |
+
}
|
| 283 |
+
if image_file is None:
|
| 284 |
+
return {
|
| 285 |
+
"type": "error",
|
| 286 |
+
"latex": "No image file provided.",
|
| 287 |
+
"success": False
|
| 288 |
+
}
|
| 289 |
+
|
| 290 |
+
if isinstance(image_file, str):
|
| 291 |
+
image = Image.open(image_file)
|
| 292 |
+
else:
|
| 293 |
+
image = Image.open(image_file.name)
|
| 294 |
+
|
| 295 |
+
if image.mode != 'RGB':
|
| 296 |
+
image = image.convert('RGB')
|
| 297 |
+
|
| 298 |
+
logger.info(f"Processing image of size: {image.size}")
|
| 299 |
+
result = p2t_model.recognize_text_formula(image)
|
| 300 |
+
|
| 301 |
+
if not result or result.strip() == "":
|
| 302 |
+
return {
|
| 303 |
+
"type": "error",
|
| 304 |
+
"latex": "No text or formulas detected in the image.",
|
| 305 |
+
"success": False
|
| 306 |
+
}
|
| 307 |
+
|
| 308 |
+
logger.info(f"Extracted text: {result}")
|
| 309 |
+
eq_type = parse_equation_type(result)
|
| 310 |
+
|
| 311 |
+
if eq_type == 'polynomial':
|
| 312 |
+
return extract_polynomial_coefficients(result)
|
| 313 |
+
elif eq_type == 'linear_system':
|
| 314 |
+
return extract_linear_system_coefficients(result)
|
| 315 |
+
else:
|
| 316 |
+
return {
|
| 317 |
+
"type": "error",
|
| 318 |
+
"latex": f"Unsupported equation type detected: {eq_type}",
|
| 319 |
+
"success": False
|
| 320 |
+
}
|
| 321 |
+
|
| 322 |
+
except Exception as e:
|
| 323 |
+
logger.error(f"Error processing image: {e}")
|
| 324 |
+
return {
|
| 325 |
+
"type": "error",
|
| 326 |
+
"latex": f"Error processing image: {str(e)}",
|
| 327 |
+
"success": False
|
| 328 |
+
}
|
| 329 |
+
|
| 330 |
def solve_extracted_equation(eq_data, real_only):
|
| 331 |
if eq_data["type"] == "polynomial":
|
| 332 |
+
return solve_polynomial(eq_data["degree"], eq_data["coeffs"], real_only, eq_data.get("variable", "x"))
|
| 333 |
elif eq_data["type"] == "linear":
|
| 334 |
return "❌ Single linear equation not supported. Please upload a system of equations.", None, ""
|
| 335 |
elif eq_data["type"] == "linear_system":
|
|
|
|
| 341 |
"""Create the Image Upload Solver tab"""
|
| 342 |
with gr.Tab("Image Upload Solver"):
|
| 343 |
gr.Markdown("## Solve Equations from Image")
|
| 344 |
+
|
| 345 |
with gr.Row():
|
| 346 |
image_input = gr.File(
|
| 347 |
label="Upload Question Image",
|
|
|
|
| 349 |
file_count="single"
|
| 350 |
)
|
| 351 |
image_upload_btn = gr.Button("Process Image")
|
| 352 |
+
|
| 353 |
gr.Markdown("**Supported Formats:** .pdf, .png, .jpg, .jpeg")
|
| 354 |
|
| 355 |
with gr.Row():
|
|
|
|
| 357 |
preview_image_btn = gr.Button("Preview Equation")
|
| 358 |
|
| 359 |
image_equation_display = gr.Markdown()
|
| 360 |
+
|
| 361 |
with gr.Row():
|
| 362 |
confirm_image_btn = gr.Button("Display Solution", visible=False)
|
| 363 |
edit_image_btn = gr.Button("Make Changes Manually", visible=False)
|
|
|
|
| 369 |
image_plot_output = gr.Plot()
|
| 370 |
extracted_eq_state = gr.State()
|
| 371 |
|
|
|
|
| 372 |
llm_url_input = gr.Textbox(label="LLM Microservice URL (optional)", placeholder="https://your-llm.ngrok.app")
|
| 373 |
explain_image_btn = gr.Button("Explain with LLM")
|
| 374 |
image_solution_txt = gr.Textbox(visible=False)
|
|
|
|
| 385 |
image_upload_btn.click(
|
| 386 |
fn=handle_image_upload,
|
| 387 |
inputs=[image_input],
|
| 388 |
+
outputs=[image_equation_display, extracted_eq_state, image_steps_md,
|
| 389 |
image_plot_output, edit_latex_input]
|
| 390 |
)
|
| 391 |
|
|
|
|
| 404 |
preview_image_btn.click(
|
| 405 |
fn=preview_image_equation,
|
| 406 |
inputs=[extracted_eq_state, real_image_checkbox],
|
| 407 |
+
outputs=[image_equation_display, confirm_image_btn, edit_image_btn,
|
| 408 |
image_steps_md, image_plot_output]
|
| 409 |
)
|
| 410 |
|
|
|
|
| 426 |
def enable_manual_edit(eq_data):
|
| 427 |
latex_value = eq_data.get("latex", "") if eq_data and eq_data["type"] != "error" else "Error in extraction."
|
| 428 |
return (
|
| 429 |
+
gr.update(visible=True, value=latex_value),
|
| 430 |
+
gr.update(visible=True),
|
| 431 |
+
gr.update(visible=False),
|
| 432 |
gr.update(visible=False)
|
| 433 |
)
|
| 434 |
|
|
|
|
| 445 |
eq_type = parse_equation_type(latex_input)
|
| 446 |
if eq_type == 'polynomial':
|
| 447 |
eq_data = extract_polynomial_coefficients(latex_input)
|
| 448 |
+
steps, plot, _ = solve_polynomial(eq_data["degree"], eq_data["coeffs"], real_only, eq_data.get("variable", "x"))
|
| 449 |
elif eq_type == 'linear_system':
|
| 450 |
eq_data = extract_linear_system_coefficients(latex_input)
|
| 451 |
_, steps, plot, _ = solve_linear_system_from_coeffs(eq_data["eq1_coeffs"], eq_data["eq2_coeffs"])
|
|
|
|
| 461 |
outputs=[image_steps_md, image_plot_output, image_solution_txt]
|
| 462 |
)
|
| 463 |
|
|
|
|
| 464 |
explain_image_btn.click(
|
| 465 |
fn=lambda sol, url: explain_with_llm(sol, "image", url),
|
| 466 |
inputs=[image_solution_txt, llm_url_input],
|
|
|
|
| 471 |
image_input, image_upload_btn, real_image_checkbox, preview_image_btn,
|
| 472 |
image_equation_display, confirm_image_btn, edit_image_btn, edit_latex_input,
|
| 473 |
save_edit_btn, image_steps_md, image_plot_output, extracted_eq_state,
|
| 474 |
+
llm_url_input, explain_image_btn, image_solution_txt
|
| 475 |
)
|