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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
MathVertex LaTeX Formatter — Flask backend
|
| 3 |
+
Deploy target: Hugging Face Spaces, Docker SDK, CPU Basic (free tier).
|
| 4 |
+
Every conversion function below was tested directly (outside Flask,
|
| 5 |
+
since Flask itself isn't installed in the dev sandbox) against known
|
| 6 |
+
correct outputs before being wrapped in a route. See the test notes
|
| 7 |
+
inline.
|
| 8 |
+
|
| 9 |
+
Endpoints:
|
| 10 |
+
POST /api/sympy — algebraic expression string -> LaTeX
|
| 11 |
+
POST /api/matrix — 2D array + bracket type -> LaTeX
|
| 12 |
+
POST /api/pandas — tabular data + style options -> LaTeX table
|
| 13 |
+
POST /api/stargazer — X, y arrays -> OLS regression LaTeX table
|
| 14 |
+
POST /api/markdown — markdown text -> LaTeX
|
| 15 |
+
POST /api/docx — uploaded .docx file -> LaTeX
|
| 16 |
+
GET /api/health — liveness check
|
| 17 |
+
"""
|
| 18 |
+
import os
|
| 19 |
+
import re
|
| 20 |
+
import signal
|
| 21 |
+
import subprocess
|
| 22 |
+
import tempfile
|
| 23 |
+
import traceback
|
| 24 |
+
|
| 25 |
+
from flask import Flask, request, jsonify
|
| 26 |
+
from flask_cors import CORS
|
| 27 |
+
from flask_limiter import Limiter
|
| 28 |
+
from flask_limiter.util import get_remote_address
|
| 29 |
+
|
| 30 |
+
import sympy
|
| 31 |
+
import numpy as np
|
| 32 |
+
from scipy import stats
|
| 33 |
+
|
| 34 |
+
app = Flask(__name__)
|
| 35 |
+
# Restricted to the production domain plus VS Code Live Server's default
|
| 36 |
+
# local-dev ports (5500/127.0.0.1:5500). Update YOUR-DOMAIN once the real
|
| 37 |
+
# domain is live.
|
| 38 |
+
CORS(app, origins=[
|
| 39 |
+
"https://YOUR-DOMAIN",
|
| 40 |
+
"http://localhost:5500",
|
| 41 |
+
"http://127.0.0.1:5500",
|
| 42 |
+
])
|
| 43 |
+
|
| 44 |
+
# Per-IP rate limiting. In-memory storage is fine for a single free-tier
|
| 45 |
+
# instance (no Redis needed) — limits reset if the Space restarts, which
|
| 46 |
+
# is an acceptable tradeoff at Phase 1 traffic levels.
|
| 47 |
+
limiter = Limiter(
|
| 48 |
+
get_remote_address,
|
| 49 |
+
app=app,
|
| 50 |
+
default_limits=["60 per minute", "1000 per day"],
|
| 51 |
+
storage_uri="memory://",
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
MAX_MATRIX_DIM = 10
|
| 55 |
+
MAX_TABLE_ROWS = 500
|
| 56 |
+
MAX_REGRESSION_ROWS = 5000
|
| 57 |
+
MAX_TEXT_LEN = 200_000
|
| 58 |
+
MAX_UPLOAD_BYTES = 8 * 1024 * 1024 # 8MB
|
| 59 |
+
MAX_EXPR_LEN = 500
|
| 60 |
+
MAX_EXPR_NEST_DEPTH = 15
|
| 61 |
+
SYMPY_TIMEOUT_SECONDS = 5
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def err(msg, code=400):
|
| 65 |
+
return jsonify({"error": msg}), code
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
# ── Expression-safety validator ─────────────────────────────────────
|
| 69 |
+
# CRITICAL: sympy.sympify() is NOT a sandbox. Verified directly in dev:
|
| 70 |
+
# sympify("__import__('os').system('echo PWNED')") ACTUALLY RUNS IT.
|
| 71 |
+
# sympify("(1).__class__.__bases__[0].__subclasses__()") walks the
|
| 72 |
+
# full Python class tree — a classic sandbox-escape technique.
|
| 73 |
+
# Every confirmed exploit requires a literal "__" substring to reach
|
| 74 |
+
# dunder attributes; legitimate math expressions never need "__", so
|
| 75 |
+
# blocking it (plus a keyword blocklist and a strict character
|
| 76 |
+
# allowlist) neutralizes every attack found, while not breaking any
|
| 77 |
+
# real expression (Integral(...), Sum(...), sin(x), Symbol('x'), etc.
|
| 78 |
+
# all parse fine — verified against the existing example expressions).
|
| 79 |
+
_DANGEROUS_SUBSTRINGS = [
|
| 80 |
+
'__', 'import', 'exec', 'eval', 'open(', 'os.', 'sys.', 'subprocess',
|
| 81 |
+
'globals', 'locals', 'getattr', 'setattr', 'delattr', 'compile(',
|
| 82 |
+
'input(', 'breakpoint', 'system', 'builtins', 'lambda', 'class ',
|
| 83 |
+
'def ', '\\x', 'chr(',
|
| 84 |
+
]
|
| 85 |
+
_SAFE_EXPR_CHARS = re.compile(r"^[A-Za-z0-9\s\+\-\*\/\^\(\)\[\]\{\}\,\.\_\=\<\>\!\:\'\"]+$")
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def validate_expr_safety(s):
|
| 89 |
+
if not s or not s.strip():
|
| 90 |
+
raise ValueError("Expression is empty")
|
| 91 |
+
if len(s) > MAX_EXPR_LEN:
|
| 92 |
+
raise ValueError(f"Expression too long (max {MAX_EXPR_LEN} characters)")
|
| 93 |
+
low = s.lower()
|
| 94 |
+
for bad in _DANGEROUS_SUBSTRINGS:
|
| 95 |
+
if bad in low:
|
| 96 |
+
raise ValueError(f"Expression contains a disallowed pattern ({bad!r})")
|
| 97 |
+
if not _SAFE_EXPR_CHARS.match(s):
|
| 98 |
+
raise ValueError("Expression contains a disallowed character")
|
| 99 |
+
depth = 0
|
| 100 |
+
max_depth = 0
|
| 101 |
+
for ch in s:
|
| 102 |
+
if ch in '([{':
|
| 103 |
+
depth += 1
|
| 104 |
+
max_depth = max(max_depth, depth)
|
| 105 |
+
elif ch in ')]}':
|
| 106 |
+
depth -= 1
|
| 107 |
+
if max_depth > MAX_EXPR_NEST_DEPTH:
|
| 108 |
+
raise ValueError("Expression nesting is too deep")
|
| 109 |
+
return True
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
class _TimeoutError(Exception):
|
| 113 |
+
pass
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def _raise_timeout(signum, frame):
|
| 117 |
+
raise _TimeoutError("Computation took too long")
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def sympify_with_timeout(expr_str, seconds=SYMPY_TIMEOUT_SECONDS):
|
| 121 |
+
"""Defense-in-depth against algorithmic-complexity DoS (e.g. deeply
|
| 122 |
+
nested symbolic expansion). SIGALRM-based — Unix only, which is what
|
| 123 |
+
the Docker container runs. Each gunicorn worker handles one request
|
| 124 |
+
at a time, so this cleanly bounds worst-case time per request."""
|
| 125 |
+
old_handler = signal.signal(signal.SIGALRM, _raise_timeout)
|
| 126 |
+
signal.alarm(seconds)
|
| 127 |
+
try:
|
| 128 |
+
validate_expr_safety(expr_str)
|
| 129 |
+
expr = sympy.sympify(expr_str, evaluate=False)
|
| 130 |
+
latex_str = sympy.latex(expr)
|
| 131 |
+
finally:
|
| 132 |
+
signal.alarm(0)
|
| 133 |
+
signal.signal(signal.SIGALRM, old_handler)
|
| 134 |
+
return latex_str
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
# ── /api/sympy ─────────────────────────────���────────────────────────
|
| 138 |
+
@app.route('/api/sympy', methods=['POST'])
|
| 139 |
+
@limiter.limit("30 per minute")
|
| 140 |
+
def api_sympy():
|
| 141 |
+
data = request.get_json(silent=True)
|
| 142 |
+
if not data or 'expression' not in data:
|
| 143 |
+
return err("No expression provided")
|
| 144 |
+
expr_str = str(data['expression'])[:MAX_EXPR_LEN]
|
| 145 |
+
try:
|
| 146 |
+
latex_str = sympify_with_timeout(expr_str)
|
| 147 |
+
return jsonify({"latex": latex_str})
|
| 148 |
+
except _TimeoutError:
|
| 149 |
+
return err("Expression took too long to process — try something simpler", 408)
|
| 150 |
+
except ValueError as e:
|
| 151 |
+
return err(str(e))
|
| 152 |
+
except Exception as e:
|
| 153 |
+
return err(f"Parse error: {e}")
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
# ── /api/matrix ──────────────────────────────────────────────────────
|
| 157 |
+
# Tested directly: sympy.latex(M, mat_str='bmatrix') double-wraps in
|
| 158 |
+
# \left[...\right] AROUND the bmatrix's own brackets — a real bug.
|
| 159 |
+
# Fix: render with mat_delim='' (no wrapper), strip the bare \begin{matrix}
|
| 160 |
+
# tags, then wrap with the literal requested environment ourselves.
|
| 161 |
+
_MAT_ENVS = {'bmatrix', 'pmatrix', 'vmatrix', 'Vmatrix', 'matrix'}
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def matrix_to_latex(rows, bracket):
|
| 165 |
+
if bracket not in _MAT_ENVS:
|
| 166 |
+
bracket = 'bmatrix'
|
| 167 |
+
n = len(rows)
|
| 168 |
+
m = len(rows[0]) if n else 0
|
| 169 |
+
if n == 0 or m == 0:
|
| 170 |
+
raise ValueError("Matrix is empty")
|
| 171 |
+
if n > MAX_MATRIX_DIM or m > MAX_MATRIX_DIM:
|
| 172 |
+
raise ValueError(f"Matrix too large (max {MAX_MATRIX_DIM}x{MAX_MATRIX_DIM})")
|
| 173 |
+
if any(len(r) != m for r in rows):
|
| 174 |
+
raise ValueError("All rows must have the same length")
|
| 175 |
+
old_handler = signal.signal(signal.SIGALRM, _raise_timeout)
|
| 176 |
+
signal.alarm(SYMPY_TIMEOUT_SECONDS)
|
| 177 |
+
try:
|
| 178 |
+
cells = []
|
| 179 |
+
for row in rows:
|
| 180 |
+
for c in row:
|
| 181 |
+
cell_str = str(c)[:100]
|
| 182 |
+
validate_expr_safety(cell_str)
|
| 183 |
+
cells.append(cell_str)
|
| 184 |
+
parsed = [[sympy.sympify(cells[i * m + j], evaluate=False) for j in range(m)] for i in range(n)]
|
| 185 |
+
M = sympy.Matrix(parsed)
|
| 186 |
+
body = sympy.latex(M, mat_str='matrix', mat_delim='')
|
| 187 |
+
finally:
|
| 188 |
+
signal.alarm(0)
|
| 189 |
+
signal.signal(signal.SIGALRM, old_handler)
|
| 190 |
+
inner = body.replace('\\begin{matrix}', '').replace('\\end{matrix}', '')
|
| 191 |
+
return '\\begin{' + bracket + '}' + inner + '\\end{' + bracket + '}'
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
@app.route('/api/matrix', methods=['POST'])
|
| 195 |
+
@limiter.limit("30 per minute")
|
| 196 |
+
def api_matrix():
|
| 197 |
+
data = request.get_json(silent=True)
|
| 198 |
+
if not data or 'rows' not in data:
|
| 199 |
+
return err("No matrix rows provided")
|
| 200 |
+
try:
|
| 201 |
+
latex_str = matrix_to_latex(data['rows'], data.get('bracket', 'bmatrix'))
|
| 202 |
+
return jsonify({"latex": latex_str})
|
| 203 |
+
except _TimeoutError:
|
| 204 |
+
return err("Matrix took too long to process — try fewer/simpler entries", 408)
|
| 205 |
+
except Exception as e:
|
| 206 |
+
return err(f"Matrix error: {e}")
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
# ── /api/pandas ──────────────────────────────────────────────────────
|
| 210 |
+
# 'pandas' style uses REAL pandas.DataFrame.to_latex() — genuine
|
| 211 |
+
# booktabs output with correct LaTeX-escaping of special characters
|
| 212 |
+
# (verified directly: Col_A -> Col\_A, 50% -> 50\%, etc).
|
| 213 |
+
# 'r' style approximates xtable/kable conventions (\hline, not
|
| 214 |
+
# booktabs) — there's no R runtime in this container, so this is a
|
| 215 |
+
# labelled approximation, not real xtable output.
|
| 216 |
+
import pandas as pd
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
def df_table_to_latex(columns, rows, style='pandas', index=False,
|
| 220 |
+
caption=None, label=None, decimals=2, alignment=None):
|
| 221 |
+
if len(rows) > MAX_TABLE_ROWS:
|
| 222 |
+
raise ValueError(f"Too many rows (max {MAX_TABLE_ROWS})")
|
| 223 |
+
if style == 'pandas':
|
| 224 |
+
df = pd.DataFrame(rows, columns=columns)
|
| 225 |
+
return df.to_latex(
|
| 226 |
+
index=index,
|
| 227 |
+
float_format=f"{{:.{decimals}f}}".format,
|
| 228 |
+
column_format=alignment,
|
| 229 |
+
caption=caption,
|
| 230 |
+
label=label,
|
| 231 |
+
escape=True,
|
| 232 |
+
)
|
| 233 |
+
# R/xtable-style approximation (hline borders, no booktabs)
|
| 234 |
+
ncols = len(columns) + (1 if index else 0)
|
| 235 |
+
align = alignment or ('l' + 'r' * (ncols - 1))
|
| 236 |
+
|
| 237 |
+
def fmt(v):
|
| 238 |
+
if isinstance(v, bool):
|
| 239 |
+
return str(v)
|
| 240 |
+
try:
|
| 241 |
+
return f'{float(v):.{decimals}f}'
|
| 242 |
+
except (TypeError, ValueError):
|
| 243 |
+
return str(v)
|
| 244 |
+
|
| 245 |
+
headers = ([''] if index else []) + [str(c) for c in columns]
|
| 246 |
+
body_rows = [(([str(i)] if index else []) + [fmt(v) for v in row]) for i, row in enumerate(rows)]
|
| 247 |
+
out = []
|
| 248 |
+
wrap_table = bool(caption or label)
|
| 249 |
+
if wrap_table:
|
| 250 |
+
out += ['\\begin{table}[h]', '\\centering']
|
| 251 |
+
out.append('\\begin{tabular}{' + align + '}')
|
| 252 |
+
out.append('\\hline')
|
| 253 |
+
out.append(' & '.join(headers) + ' \\\\')
|
| 254 |
+
out.append('\\hline')
|
| 255 |
+
for r in body_rows:
|
| 256 |
+
out.append(' & '.join(r) + ' \\\\')
|
| 257 |
+
out.append('\\hline')
|
| 258 |
+
out.append('\\end{tabular}')
|
| 259 |
+
if caption:
|
| 260 |
+
out.append('\\caption{' + caption + '}')
|
| 261 |
+
if label:
|
| 262 |
+
out.append('\\label{' + label + '}')
|
| 263 |
+
if wrap_table:
|
| 264 |
+
out.append('\\end{table}')
|
| 265 |
+
return '\n'.join(out)
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
@app.route('/api/pandas', methods=['POST'])
|
| 269 |
+
@limiter.limit("20 per minute")
|
| 270 |
+
def api_pandas():
|
| 271 |
+
data = request.get_json(silent=True)
|
| 272 |
+
if not data or 'columns' not in data or 'rows' not in data:
|
| 273 |
+
return err("Provide 'columns' and 'rows'")
|
| 274 |
+
try:
|
| 275 |
+
latex_str = df_table_to_latex(
|
| 276 |
+
data['columns'], data['rows'],
|
| 277 |
+
style=data.get('style', 'pandas'),
|
| 278 |
+
index=bool(data.get('index', False)),
|
| 279 |
+
caption=data.get('caption'),
|
| 280 |
+
label=data.get('label'),
|
| 281 |
+
decimals=int(data.get('decimals', 2)),
|
| 282 |
+
alignment=data.get('alignment'),
|
| 283 |
+
)
|
| 284 |
+
return jsonify({"latex": latex_str})
|
| 285 |
+
except Exception as e:
|
| 286 |
+
return err(f"Table error: {e}")
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
# ── /api/stargazer ──────────────────────────────────────────────────
|
| 290 |
+
# OLS via normal equations (X'X)^-1 X'y, exactly as a textbook
|
| 291 |
+
# derivation, no statsmodels dependency. Cross-checked against
|
| 292 |
+
# numpy.polyfit for a simple-regression case — matched to 4dp.
|
| 293 |
+
def ols_regression(X, y, var_names=None):
|
| 294 |
+
X = np.array(X, dtype=float)
|
| 295 |
+
y = np.array(y, dtype=float)
|
| 296 |
+
if X.ndim == 1:
|
| 297 |
+
X = X.reshape(-1, 1)
|
| 298 |
+
n, k = X.shape
|
| 299 |
+
p = k + 1
|
| 300 |
+
if n <= p:
|
| 301 |
+
raise ValueError(f"Need more observations ({n}) than parameters ({p})")
|
| 302 |
+
Xd = np.column_stack([np.ones(n), X])
|
| 303 |
+
XtX = Xd.T @ Xd
|
| 304 |
+
try:
|
| 305 |
+
XtX_inv = np.linalg.inv(XtX)
|
| 306 |
+
except np.linalg.LinAlgError:
|
| 307 |
+
raise ValueError("X'X is singular — predictors may be collinear")
|
| 308 |
+
beta = XtX_inv @ Xd.T @ y
|
| 309 |
+
resid = y - Xd @ beta
|
| 310 |
+
rss = float(np.sum(resid ** 2))
|
| 311 |
+
df_resid = n - p
|
| 312 |
+
sigma2 = rss / df_resid
|
| 313 |
+
se = np.sqrt(np.diag(sigma2 * XtX_inv))
|
| 314 |
+
t_stats = beta / se
|
| 315 |
+
p_values = 2 * stats.t.sf(np.abs(t_stats), df_resid)
|
| 316 |
+
tss = float(np.sum((y - y.mean()) ** 2))
|
| 317 |
+
r2 = 1 - rss / tss if tss > 0 else float('nan')
|
| 318 |
+
adj_r2 = 1 - (1 - r2) * (n - 1) / (n - p)
|
| 319 |
+
if p > 1 and rss > 0:
|
| 320 |
+
f_stat = (tss - rss) / (p - 1) / (rss / df_resid)
|
| 321 |
+
f_pvalue = stats.f.sf(f_stat, p - 1, df_resid)
|
| 322 |
+
else:
|
| 323 |
+
f_stat, f_pvalue = float('nan'), float('nan')
|
| 324 |
+
names = ['Intercept'] + (var_names or [f'X{i+1}' for i in range(k)])
|
| 325 |
+
return {
|
| 326 |
+
'names': names, 'coef': beta.tolist(), 'se': se.tolist(),
|
| 327 |
+
't': t_stats.tolist(), 'p': p_values.tolist(),
|
| 328 |
+
'r2': r2, 'adj_r2': adj_r2, 'f_stat': f_stat, 'f_pvalue': f_pvalue,
|
| 329 |
+
'n': n, 'df_resid': df_resid,
|
| 330 |
+
}
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
def _stars(p):
|
| 334 |
+
return '***' if p < 0.01 else '**' if p < 0.05 else '*' if p < 0.1 else ''
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
def stargazer_latex(res, dep_var='y', title='Regression Results'):
|
| 338 |
+
L = []
|
| 339 |
+
L += ['\\begin{table}[!htbp] \\centering',
|
| 340 |
+
' \\caption{' + title + '}',
|
| 341 |
+
' \\label{tab:regression}',
|
| 342 |
+
'\\begin{tabular}{@{\\extracolsep{5pt}}lc}',
|
| 343 |
+
'\\\\[-1.8ex]\\hline',
|
| 344 |
+
'\\hline \\\\[-1.8ex]',
|
| 345 |
+
' & \\multicolumn{1}{c}{\\textit{Dependent variable:}} \\\\',
|
| 346 |
+
'\\cline{2-2}',
|
| 347 |
+
' & \\multicolumn{1}{c}{' + dep_var + '} \\\\',
|
| 348 |
+
'\\hline \\\\[-1.8ex]']
|
| 349 |
+
intercept_i = res['names'].index('Intercept')
|
| 350 |
+
for i, name in enumerate(res['names']):
|
| 351 |
+
if name == 'Intercept':
|
| 352 |
+
continue
|
| 353 |
+
c, se, p = res['coef'][i], res['se'][i], res['p'][i]
|
| 354 |
+
L.append(f' {name} & {c:.3f}{_stars(p)} \\\\')
|
| 355 |
+
L.append(f' & ({se:.3f}) \\\\')
|
| 356 |
+
c, se, p = res['coef'][intercept_i], res['se'][intercept_i], res['p'][intercept_i]
|
| 357 |
+
L.append(f' Constant & {c:.3f}{_stars(p)} \\\\')
|
| 358 |
+
L.append(f' & ({se:.3f}) \\\\')
|
| 359 |
+
L.append('\\hline \\\\[-1.8ex]')
|
| 360 |
+
L.append(f'Observations & {res["n"]} \\\\')
|
| 361 |
+
L.append(f'R$^{{2}}$ & {res["r2"]:.3f} \\\\')
|
| 362 |
+
L.append(f'Adjusted R$^{{2}}$ & {res["adj_r2"]:.3f} \\\\')
|
| 363 |
+
if not np.isnan(res['f_stat']):
|
| 364 |
+
L.append(f'F Statistic & {res["f_stat"]:.3f} \\\\')
|
| 365 |
+
L += ['\\hline', '\\hline \\\\[-1.8ex]',
|
| 366 |
+
'\\textit{Note:} & \\multicolumn{1}{r}{$^{*}$p$<$0.1; $^{**}$p$<$0.05; $^{***}$p$<$0.01} \\\\',
|
| 367 |
+
'\\end{tabular}', '\\end{table}']
|
| 368 |
+
return '\n'.join(L)
|
| 369 |
+
|
| 370 |
+
|
| 371 |
+
@app.route('/api/stargazer', methods=['POST'])
|
| 372 |
+
@limiter.limit("15 per minute")
|
| 373 |
+
def api_stargazer():
|
| 374 |
+
data = request.get_json(silent=True)
|
| 375 |
+
if not data or 'X' not in data or 'y' not in data:
|
| 376 |
+
return err("Provide 'X' (2D array) and 'y' (1D array)")
|
| 377 |
+
try:
|
| 378 |
+
X, y = data['X'], data['y']
|
| 379 |
+
if len(X) > MAX_REGRESSION_ROWS:
|
| 380 |
+
return err(f"Too many observations (max {MAX_REGRESSION_ROWS})")
|
| 381 |
+
res = ols_regression(X, y, data.get('var_names'))
|
| 382 |
+
latex_str = stargazer_latex(
|
| 383 |
+
res, dep_var=data.get('dep_var', 'y'),
|
| 384 |
+
title=data.get('title', 'Regression Results'))
|
| 385 |
+
return jsonify({"latex": latex_str, "stats": {
|
| 386 |
+
k: res[k] for k in ('r2', 'adj_r2', 'f_stat', 'f_pvalue', 'n', 'df_resid')
|
| 387 |
+
}})
|
| 388 |
+
except Exception as e:
|
| 389 |
+
return err(f"Regression error: {e}")
|
| 390 |
+
|
| 391 |
+
|
| 392 |
+
# ── /api/markdown ────────────────────────────────────────────────────
|
| 393 |
+
# Direct subprocess call to the pandoc binary — no pypandoc wrapper
|
| 394 |
+
# needed (pypandoc is itself just a subprocess wrapper). Verified
|
| 395 |
+
# directly against the pandoc CLI for headers/bold/italic/lists/
|
| 396 |
+
# tables/blockquotes/code blocks.
|
| 397 |
+
def run_pandoc(args, input_bytes=None, timeout=20):
|
| 398 |
+
try:
|
| 399 |
+
proc = subprocess.run(
|
| 400 |
+
['pandoc'] + args, input=input_bytes,
|
| 401 |
+
capture_output=True, timeout=timeout,
|
| 402 |
+
)
|
| 403 |
+
except FileNotFoundError:
|
| 404 |
+
raise RuntimeError("pandoc is not installed on the server")
|
| 405 |
+
except subprocess.TimeoutExpired:
|
| 406 |
+
raise RuntimeError("Conversion timed out")
|
| 407 |
+
if proc.returncode != 0:
|
| 408 |
+
raise RuntimeError(proc.stderr.decode('utf-8', 'replace')[:1000])
|
| 409 |
+
return proc.stdout.decode('utf-8', 'replace')
|
| 410 |
+
|
| 411 |
+
|
| 412 |
+
@app.route('/api/markdown', methods=['POST'])
|
| 413 |
+
@limiter.limit("15 per minute")
|
| 414 |
+
def api_markdown():
|
| 415 |
+
data = request.get_json(silent=True)
|
| 416 |
+
if not data or 'markdown' not in data:
|
| 417 |
+
return err("No markdown provided")
|
| 418 |
+
md = str(data['markdown'])[:MAX_TEXT_LEN]
|
| 419 |
+
standalone = bool(data.get('standalone', False))
|
| 420 |
+
args = ['-f', 'markdown', '-t', 'latex']
|
| 421 |
+
if standalone:
|
| 422 |
+
args.append('--standalone')
|
| 423 |
+
try:
|
| 424 |
+
latex_str = run_pandoc(args, input_bytes=md.encode('utf-8'))
|
| 425 |
+
return jsonify({"latex": latex_str})
|
| 426 |
+
except RuntimeError as e:
|
| 427 |
+
return err(str(e), 502)
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
# ── /api/docx ────────────────────────────────────────────────────────
|
| 431 |
+
# Multipart file upload -> temp file -> pandoc -> cleanup. Verified
|
| 432 |
+
# directly with a python-docx-generated test file containing headings,
|
| 433 |
+
# bold/italic runs, and a table — all converted correctly.
|
| 434 |
+
@app.route('/api/docx', methods=['POST'])
|
| 435 |
+
@limiter.limit("10 per minute")
|
| 436 |
+
def api_docx():
|
| 437 |
+
if 'file' not in request.files:
|
| 438 |
+
return err("No file uploaded")
|
| 439 |
+
f = request.files['file']
|
| 440 |
+
if not f.filename.lower().endswith('.docx'):
|
| 441 |
+
return err("File must be a .docx")
|
| 442 |
+
raw = f.read()
|
| 443 |
+
if len(raw) > MAX_UPLOAD_BYTES:
|
| 444 |
+
return err("File too large (max 8MB)")
|
| 445 |
+
standalone = request.form.get('standalone', 'true').lower() != 'false'
|
| 446 |
+
|
| 447 |
+
tmp_path = None
|
| 448 |
+
try:
|
| 449 |
+
with tempfile.NamedTemporaryFile(suffix='.docx', delete=False) as tmp:
|
| 450 |
+
tmp.write(raw)
|
| 451 |
+
tmp_path = tmp.name
|
| 452 |
+
args = ['-f', 'docx', '-t', 'latex', tmp_path]
|
| 453 |
+
if standalone:
|
| 454 |
+
args.append('--standalone')
|
| 455 |
+
latex_str = run_pandoc(args)
|
| 456 |
+
return jsonify({"latex": latex_str})
|
| 457 |
+
except RuntimeError as e:
|
| 458 |
+
return err(str(e), 502)
|
| 459 |
+
finally:
|
| 460 |
+
if tmp_path and os.path.exists(tmp_path):
|
| 461 |
+
os.remove(tmp_path)
|
| 462 |
+
|
| 463 |
+
|
| 464 |
+
@app.route('/api/health', methods=['GET'])
|
| 465 |
+
@limiter.exempt
|
| 466 |
+
def api_health():
|
| 467 |
+
return jsonify({"status": "ok"})
|
| 468 |
+
|
| 469 |
+
|
| 470 |
+
# ══════════════════════════════════════════════════════════════════
|
| 471 |
+
# CALCULUS & DIFFERENTIAL EQUATIONS
|
| 472 |
+
# Per the implementation matrix: SymPy for limits/ODEs/Laplace/series/
|
| 473 |
+
# vector calculus/Euler-Lagrange. The doc recommends Maxima for
|
| 474 |
+
# step-by-step integration — Maxima isn't installed in the dev sandbox
|
| 475 |
+
# (no network access to verify it), so /api/integrate uses SymPy's
|
| 476 |
+
# own manualintegrate engine instead, which DOES give real step-by-
|
| 477 |
+
# step rules (PartsRule, URule, ArctanRule, etc.) and was verified
|
| 478 |
+
# directly against 8 cases (power, parts, substitution, arctan, trig
|
| 479 |
+
# product, cyclic parts, sum rule, constant multiple) — every result
|
| 480 |
+
# differentiated back to confirm correctness. Swap to Maxima later if
|
| 481 |
+
# SymPy's manualintegrate hits a wall on a specific edge case.
|
| 482 |
+
#
|
| 483 |
+
# Every endpoint here parses a user-supplied expression string through
|
| 484 |
+
# sympify, so every one of them goes through the SAME validate_expr_
|
| 485 |
+
# safety() + SIGALRM timeout used by /api/sympy — this is exactly the
|
| 486 |
+
# class of input that the confirmed sympify RCE exploited.
|
| 487 |
+
# ══════════════════════════════════════════════════════════════════
|
| 488 |
+
from sympy import (Function, Derivative, Eq, dsolve as sympy_dsolve, laplace_transform,
|
| 489 |
+
limit as sympy_limit, oo, Symbol)
|
| 490 |
+
from sympy.calculus.euler import euler_equations
|
| 491 |
+
from sympy.integrals.manualintegrate import integral_steps, manualintegrate
|
| 492 |
+
|
| 493 |
+
|
| 494 |
+
def _safe_sympify(expr_str, local_syms=None):
|
| 495 |
+
validate_expr_safety(expr_str)
|
| 496 |
+
old_handler = signal.signal(signal.SIGALRM, _raise_timeout)
|
| 497 |
+
signal.alarm(SYMPY_TIMEOUT_SECONDS)
|
| 498 |
+
try:
|
| 499 |
+
return sympy.sympify(expr_str, locals=local_syms or {})
|
| 500 |
+
finally:
|
| 501 |
+
signal.alarm(0)
|
| 502 |
+
signal.signal(signal.SIGALRM, old_handler)
|
| 503 |
+
|
| 504 |
+
|
| 505 |
+
def _explain_integral_rule(rule):
|
| 506 |
+
"""Recursively flatten a manualintegrate Rule object into a list
|
| 507 |
+
of human-readable step strings. Handles the common rule types;
|
| 508 |
+
anything else gets a generic but honest fallback description
|
| 509 |
+
rather than a wrong-looking explanation."""
|
| 510 |
+
name = type(rule).__name__
|
| 511 |
+
steps = []
|
| 512 |
+
if name == 'PowerRule':
|
| 513 |
+
steps.append(f"Power rule: \u222b{rule.base}^{rule.exp} dx = {rule.base}^({rule.exp}+1)/({rule.exp}+1)")
|
| 514 |
+
elif name == 'ExpRule':
|
| 515 |
+
steps.append(f"Exponential rule applied to {rule.base}^({rule.exp})")
|
| 516 |
+
elif name == 'ReciprocalRule':
|
| 517 |
+
steps.append(f"Reciprocal rule: \u222b1/{rule.base} dx = ln|{rule.base}|")
|
| 518 |
+
elif name == 'ArctanRule':
|
| 519 |
+
steps.append("Arctan rule: matches \u222b1/(a\u00b2x\u00b2+c) dx \u2192 arctan form")
|
| 520 |
+
elif name == 'SinRule':
|
| 521 |
+
steps.append("\u222bsin(x) dx = -cos(x)")
|
| 522 |
+
elif name == 'CosRule':
|
| 523 |
+
steps.append("\u222bcos(x) dx = sin(x)")
|
| 524 |
+
elif name == 'ConstantRule':
|
| 525 |
+
steps.append(f"Constant rule: \u222b{rule.integrand} dx = {rule.integrand}\u00b7x")
|
| 526 |
+
elif name == 'ConstantTimesRule':
|
| 527 |
+
steps.append(f"Constant multiple rule: factor out {rule.constant}")
|
| 528 |
+
steps.extend(_explain_integral_rule(rule.substep))
|
| 529 |
+
elif name == 'URule':
|
| 530 |
+
steps.append(f"Substitution: let u = {rule.u_func}")
|
| 531 |
+
steps.extend(_explain_integral_rule(rule.substep))
|
| 532 |
+
elif name == 'PartsRule':
|
| 533 |
+
steps.append(f"Integration by parts: u = {rule.u}, dv = {rule.dv} dx")
|
| 534 |
+
steps.extend(_explain_integral_rule(rule.v_step))
|
| 535 |
+
if rule.second_step is not None:
|
| 536 |
+
steps.append("Then integrate the remaining term:")
|
| 537 |
+
steps.extend(_explain_integral_rule(rule.second_step))
|
| 538 |
+
elif name == 'CyclicPartsRule':
|
| 539 |
+
steps.append("Cyclic integration by parts \u2014 the original integral reappears, solve algebraically")
|
| 540 |
+
for pr in rule.parts_rules:
|
| 541 |
+
steps.extend(_explain_integral_rule(pr))
|
| 542 |
+
elif name == 'AddRule':
|
| 543 |
+
steps.append("Split into a sum of integrals (linearity):")
|
| 544 |
+
for sub in rule.substeps:
|
| 545 |
+
steps.extend(_explain_integral_rule(sub))
|
| 546 |
+
elif name == 'AlternativeRule':
|
| 547 |
+
steps.extend(_explain_integral_rule(rule.alternatives[0]))
|
| 548 |
+
else:
|
| 549 |
+
steps.append(f"Apply the {name.replace('Rule','')} rule to {rule.integrand}")
|
| 550 |
+
return steps
|
| 551 |
+
|
| 552 |
+
|
| 553 |
+
@app.route('/api/integrate', methods=['POST'])
|
| 554 |
+
@limiter.limit("20 per minute")
|
| 555 |
+
def api_integrate():
|
| 556 |
+
data = request.get_json(silent=True)
|
| 557 |
+
if not data or 'expression' not in data:
|
| 558 |
+
return err("Provide 'expression'")
|
| 559 |
+
try:
|
| 560 |
+
var_name = str(data.get('variable', 'x'))[:5]
|
| 561 |
+
if not re.match(r'^[A-Za-z]$', var_name):
|
| 562 |
+
return err("variable must be a single letter")
|
| 563 |
+
x = sympy.Symbol(var_name)
|
| 564 |
+
expr = _safe_sympify(str(data['expression'])[:MAX_EXPR_LEN], {var_name: x})
|
| 565 |
+
rule = integral_steps(expr, x)
|
| 566 |
+
result = manualintegrate(expr, x)
|
| 567 |
+
steps = _explain_integral_rule(rule)
|
| 568 |
+
return jsonify({
|
| 569 |
+
"expression": sympy.latex(expr), "result": sympy.latex(result),
|
| 570 |
+
"result_plain": str(result), "steps": steps,
|
| 571 |
+
})
|
| 572 |
+
except _TimeoutError:
|
| 573 |
+
return err("Integration took too long \u2014 try a simpler expression", 408)
|
| 574 |
+
except ValueError as e:
|
| 575 |
+
return err(str(e))
|
| 576 |
+
except Exception as e:
|
| 577 |
+
return err(f"Integration error: {e}")
|
| 578 |
+
|
| 579 |
+
|
| 580 |
+
@app.route('/api/limit', methods=['POST'])
|
| 581 |
+
@limiter.limit("30 per minute")
|
| 582 |
+
def api_limit():
|
| 583 |
+
data = request.get_json(silent=True)
|
| 584 |
+
if not data or 'expression' not in data or 'point' not in data:
|
| 585 |
+
return err("Provide 'expression' and 'point'")
|
| 586 |
+
try:
|
| 587 |
+
var_name = str(data.get('variable', 'x'))[:5]
|
| 588 |
+
if not re.match(r'^[A-Za-z]$', var_name):
|
| 589 |
+
return err("variable must be a single letter")
|
| 590 |
+
x = sympy.Symbol(var_name)
|
| 591 |
+
expr = _safe_sympify(str(data['expression'])[:MAX_EXPR_LEN], {var_name: x})
|
| 592 |
+
point_str = str(data['point'])[:50]
|
| 593 |
+
validate_expr_safety(point_str)
|
| 594 |
+
point = sympy.oo if point_str.lower() in ('oo', 'inf', 'infinity') else \
|
| 595 |
+
-sympy.oo if point_str.lower() in ('-oo', '-inf') else sympy.sympify(point_str)
|
| 596 |
+
direction = data.get('direction', '+-')
|
| 597 |
+
old_handler = signal.signal(signal.SIGALRM, _raise_timeout)
|
| 598 |
+
signal.alarm(SYMPY_TIMEOUT_SECONDS)
|
| 599 |
+
try:
|
| 600 |
+
result = sympy_limit(expr, x, point, dir=direction if direction in ('+', '-') else '+-')
|
| 601 |
+
finally:
|
| 602 |
+
signal.alarm(0)
|
| 603 |
+
signal.signal(signal.SIGALRM, old_handler)
|
| 604 |
+
direct_sub = expr.subs(x, point)
|
| 605 |
+
is_indeterminate = direct_sub.is_finite is False or str(direct_sub) in ('nan', 'zoo') or \
|
| 606 |
+
(hasattr(direct_sub, 'is_indeterminate') and direct_sub.is_indeterminate)
|
| 607 |
+
return jsonify({
|
| 608 |
+
"expression": sympy.latex(expr), "point": sympy.latex(point),
|
| 609 |
+
"result": sympy.latex(result), "result_plain": str(result),
|
| 610 |
+
"direct_substitution_note": "Direct substitution gives an indeterminate form \u2014 L'H\u00f4pital's rule or algebraic manipulation applies" if is_indeterminate else None,
|
| 611 |
+
})
|
| 612 |
+
except _TimeoutError:
|
| 613 |
+
return err("Limit computation took too long", 408)
|
| 614 |
+
except ValueError as e:
|
| 615 |
+
return err(str(e))
|
| 616 |
+
except Exception as e:
|
| 617 |
+
return err(f"Limit error: {e}")
|
| 618 |
+
|
| 619 |
+
|
| 620 |
+
@app.route('/api/dsolve', methods=['POST'])
|
| 621 |
+
@limiter.limit("20 per minute")
|
| 622 |
+
def api_dsolve():
|
| 623 |
+
data = request.get_json(silent=True)
|
| 624 |
+
if not data or 'equation' not in data:
|
| 625 |
+
return err("Provide 'equation' (e.g. \"f(x).diff(x) + f(x)\" meaning that expression = 0, or use 'rhs' for the right-hand side)")
|
| 626 |
+
try:
|
| 627 |
+
var_name = str(data.get('variable', 'x'))[:5]
|
| 628 |
+
func_name = str(data.get('function', 'f'))[:10]
|
| 629 |
+
if not re.match(r'^[A-Za-z]$', var_name) or not re.match(r'^[A-Za-z]+$', func_name):
|
| 630 |
+
return err("variable/function names must be plain letters")
|
| 631 |
+
x = sympy.Symbol(var_name)
|
| 632 |
+
f = sympy.Function(func_name)
|
| 633 |
+
local_syms = {var_name: x, func_name: f}
|
| 634 |
+
lhs_str = str(data['equation'])[:MAX_EXPR_LEN]
|
| 635 |
+
rhs_str = str(data.get('rhs', '0'))[:MAX_EXPR_LEN]
|
| 636 |
+
lhs = _safe_sympify(lhs_str, local_syms)
|
| 637 |
+
rhs = _safe_sympify(rhs_str, local_syms)
|
| 638 |
+
ode = sympy.Eq(lhs, rhs)
|
| 639 |
+
old_handler = signal.signal(signal.SIGALRM, _raise_timeout)
|
| 640 |
+
signal.alarm(SYMPY_TIMEOUT_SECONDS)
|
| 641 |
+
try:
|
| 642 |
+
hints = sympy.classify_ode(ode, f(x))
|
| 643 |
+
sol = sympy_dsolve(ode, f(x))
|
| 644 |
+
finally:
|
| 645 |
+
signal.alarm(0)
|
| 646 |
+
signal.signal(signal.SIGALRM, old_handler)
|
| 647 |
+
return jsonify({
|
| 648 |
+
"equation": sympy.latex(ode), "solution": sympy.latex(sol),
|
| 649 |
+
"solution_plain": str(sol), "classification": list(hints[:3]) if hints else [],
|
| 650 |
+
})
|
| 651 |
+
except _TimeoutError:
|
| 652 |
+
return err("dsolve took too long \u2014 try a simpler ODE", 408)
|
| 653 |
+
except ValueError as e:
|
| 654 |
+
return err(str(e))
|
| 655 |
+
except Exception as e:
|
| 656 |
+
return err(f"ODE solver error: {e}")
|
| 657 |
+
|
| 658 |
+
|
| 659 |
+
@app.route('/api/laplace', methods=['POST'])
|
| 660 |
+
@limiter.limit("20 per minute")
|
| 661 |
+
def api_laplace():
|
| 662 |
+
data = request.get_json(silent=True)
|
| 663 |
+
if not data or 'expression' not in data:
|
| 664 |
+
return err("Provide 'expression' (in terms of t)")
|
| 665 |
+
try:
|
| 666 |
+
t = sympy.Symbol('t', positive=True)
|
| 667 |
+
s = sympy.Symbol('s', positive=True)
|
| 668 |
+
expr = _safe_sympify(str(data['expression'])[:MAX_EXPR_LEN], {'t': t})
|
| 669 |
+
old_handler = signal.signal(signal.SIGALRM, _raise_timeout)
|
| 670 |
+
signal.alarm(SYMPY_TIMEOUT_SECONDS)
|
| 671 |
+
try:
|
| 672 |
+
result = laplace_transform(expr, t, s, noconds=True)
|
| 673 |
+
finally:
|
| 674 |
+
signal.alarm(0)
|
| 675 |
+
signal.signal(signal.SIGALRM, old_handler)
|
| 676 |
+
return jsonify({
|
| 677 |
+
"expression": sympy.latex(expr), "result": sympy.latex(result),
|
| 678 |
+
"result_plain": str(result),
|
| 679 |
+
})
|
| 680 |
+
except _TimeoutError:
|
| 681 |
+
return err("Laplace transform took too long", 408)
|
| 682 |
+
except ValueError as e:
|
| 683 |
+
return err(str(e))
|
| 684 |
+
except Exception as e:
|
| 685 |
+
return err(f"Laplace transform error: {e}")
|
| 686 |
+
|
| 687 |
+
|
| 688 |
+
@app.route('/api/series', methods=['POST'])
|
| 689 |
+
@limiter.limit("20 per minute")
|
| 690 |
+
def api_series():
|
| 691 |
+
data = request.get_json(silent=True)
|
| 692 |
+
if not data or 'expression' not in data:
|
| 693 |
+
return err("Provide 'expression'")
|
| 694 |
+
try:
|
| 695 |
+
var_name = str(data.get('variable', 'x'))[:5]
|
| 696 |
+
if not re.match(r'^[A-Za-z]$', var_name):
|
| 697 |
+
return err("variable must be a single letter")
|
| 698 |
+
x = sympy.Symbol(var_name)
|
| 699 |
+
expr = _safe_sympify(str(data['expression'])[:MAX_EXPR_LEN], {var_name: x})
|
| 700 |
+
point_str = str(data.get('point', '0'))[:50]
|
| 701 |
+
validate_expr_safety(point_str)
|
| 702 |
+
point = sympy.sympify(point_str)
|
| 703 |
+
n = int(data.get('n', 6))
|
| 704 |
+
if n < 1 or n > 20:
|
| 705 |
+
return err("n (number of terms) must be between 1 and 20")
|
| 706 |
+
old_handler = signal.signal(signal.SIGALRM, _raise_timeout)
|
| 707 |
+
signal.alarm(SYMPY_TIMEOUT_SECONDS)
|
| 708 |
+
try:
|
| 709 |
+
s = expr.series(x, point, n)
|
| 710 |
+
finally:
|
| 711 |
+
signal.alarm(0)
|
| 712 |
+
signal.signal(signal.SIGALRM, old_handler)
|
| 713 |
+
return jsonify({"expression": sympy.latex(expr), "series": sympy.latex(s), "series_plain": str(s)})
|
| 714 |
+
except _TimeoutError:
|
| 715 |
+
return err("Series expansion took too long", 408)
|
| 716 |
+
except ValueError as e:
|
| 717 |
+
return err(str(e))
|
| 718 |
+
except Exception as e:
|
| 719 |
+
return err(f"Series error: {e}")
|
| 720 |
+
|
| 721 |
+
|
| 722 |
+
@app.route('/api/vector-calc', methods=['POST'])
|
| 723 |
+
@limiter.limit("20 per minute")
|
| 724 |
+
def api_vector_calc():
|
| 725 |
+
data = request.get_json(silent=True)
|
| 726 |
+
if not data or 'operation' not in data:
|
| 727 |
+
return err("Provide 'operation' (gradient/divergence/curl) and the relevant field components")
|
| 728 |
+
try:
|
| 729 |
+
from sympy.vector import CoordSys3D, gradient, divergence, curl
|
| 730 |
+
N = CoordSys3D('N')
|
| 731 |
+
op = data['operation']
|
| 732 |
+
local_syms = {'x': N.x, 'y': N.y, 'z': N.z}
|
| 733 |
+
old_handler = signal.signal(signal.SIGALRM, _raise_timeout)
|
| 734 |
+
signal.alarm(SYMPY_TIMEOUT_SECONDS)
|
| 735 |
+
try:
|
| 736 |
+
if op == 'gradient':
|
| 737 |
+
phi_str = str(data.get('scalar', ''))[:MAX_EXPR_LEN]
|
| 738 |
+
phi = _safe_sympify(phi_str, local_syms)
|
| 739 |
+
result = gradient(phi)
|
| 740 |
+
elif op in ('divergence', 'curl'):
|
| 741 |
+
fx = _safe_sympify(str(data.get('fx', '0'))[:MAX_EXPR_LEN], local_syms)
|
| 742 |
+
fy = _safe_sympify(str(data.get('fy', '0'))[:MAX_EXPR_LEN], local_syms)
|
| 743 |
+
fz = _safe_sympify(str(data.get('fz', '0'))[:MAX_EXPR_LEN], local_syms)
|
| 744 |
+
field = fx * N.i + fy * N.j + fz * N.k
|
| 745 |
+
result = divergence(field) if op == 'divergence' else curl(field)
|
| 746 |
+
else:
|
| 747 |
+
return err("operation must be one of: gradient, divergence, curl")
|
| 748 |
+
finally:
|
| 749 |
+
signal.alarm(0)
|
| 750 |
+
signal.signal(signal.SIGALRM, old_handler)
|
| 751 |
+
return jsonify({"operation": op, "result": sympy.latex(result), "result_plain": str(result)})
|
| 752 |
+
except _TimeoutError:
|
| 753 |
+
return err("Vector calculus computation took too long", 408)
|
| 754 |
+
except ValueError as e:
|
| 755 |
+
return err(str(e))
|
| 756 |
+
except Exception as e:
|
| 757 |
+
return err(f"Vector calculus error: {e}")
|
| 758 |
+
|
| 759 |
+
|
| 760 |
+
@app.route('/api/euler-lagrange', methods=['POST'])
|
| 761 |
+
@limiter.limit("20 per minute")
|
| 762 |
+
def api_euler_lagrange():
|
| 763 |
+
data = request.get_json(silent=True)
|
| 764 |
+
if not data or 'lagrangian' not in data:
|
| 765 |
+
return err("Provide 'lagrangian' (in terms of y, y', and x \u2014 use Derivative(y(x),x) for y')")
|
| 766 |
+
try:
|
| 767 |
+
var_name = str(data.get('variable', 'x'))[:5]
|
| 768 |
+
func_name = str(data.get('function', 'y'))[:10]
|
| 769 |
+
if not re.match(r'^[A-Za-z]$', var_name) or not re.match(r'^[A-Za-z]+$', func_name):
|
| 770 |
+
return err("variable/function names must be plain letters")
|
| 771 |
+
x = sympy.Symbol(var_name)
|
| 772 |
+
y = sympy.Function(func_name)
|
| 773 |
+
local_syms = {var_name: x, func_name: y, 'Derivative': sympy.Derivative}
|
| 774 |
+
L = _safe_sympify(str(data['lagrangian'])[:MAX_EXPR_LEN], local_syms)
|
| 775 |
+
old_handler = signal.signal(signal.SIGALRM, _raise_timeout)
|
| 776 |
+
signal.alarm(SYMPY_TIMEOUT_SECONDS)
|
| 777 |
+
try:
|
| 778 |
+
eq = euler_equations(L, y(x), x)
|
| 779 |
+
finally:
|
| 780 |
+
signal.alarm(0)
|
| 781 |
+
signal.signal(signal.SIGALRM, old_handler)
|
| 782 |
+
return jsonify({
|
| 783 |
+
"lagrangian": sympy.latex(L),
|
| 784 |
+
"euler_lagrange_equation": [sympy.latex(e) for e in eq],
|
| 785 |
+
})
|
| 786 |
+
except _TimeoutError:
|
| 787 |
+
return err("Euler-Lagrange derivation took too long", 408)
|
| 788 |
+
except ValueError as e:
|
| 789 |
+
return err(str(e))
|
| 790 |
+
except Exception as e:
|
| 791 |
+
return err(f"Euler-Lagrange error: {e}")
|
| 792 |
+
|
| 793 |
+
|
| 794 |
+
# ══════════════════════════════════════════════════════════════════
|
| 795 |
+
# NUMBER THEORY & CRYPTOGRAPHY
|
| 796 |
+
# Per the implementation matrix: SymPy is the clear winner here —
|
| 797 |
+
# factorint/totient/primitive_root/is_quad_residue/crt all native.
|
| 798 |
+
# These take plain integers, not expression strings, so the sympify-
|
| 799 |
+
# RCE class of attack doesn't apply the same way — but inputs are
|
| 800 |
+
# still bounded to keep factoring/primality-testing fast and to stop
|
| 801 |
+
# someone sending a 500-digit number and tying up a worker.
|
| 802 |
+
# ══════════════════════════════════════════════════════════════════
|
| 803 |
+
MAX_NT_INT = 10**15 # bound for factorization / totient / primitive root / QR
|
| 804 |
+
MAX_RSA_PRIME = 10**6 # demonstrator only — small by design, matches the
|
| 805 |
+
# roadmap's own "SymPy now, SageMath/PARI-GP in
|
| 806 |
+
# Phase 5 for real key sizes" phasing
|
| 807 |
+
|
| 808 |
+
|
| 809 |
+
def _safe_int(v, max_val, name="value"):
|
| 810 |
+
try:
|
| 811 |
+
n = int(v)
|
| 812 |
+
except (TypeError, ValueError):
|
| 813 |
+
raise ValueError(f"{name} must be an integer")
|
| 814 |
+
if abs(n) > max_val:
|
| 815 |
+
raise ValueError(f"{name} is too large (max {max_val})")
|
| 816 |
+
return n
|
| 817 |
+
|
| 818 |
+
|
| 819 |
+
@app.route('/api/factorize', methods=['POST'])
|
| 820 |
+
@limiter.limit("30 per minute")
|
| 821 |
+
def api_factorize():
|
| 822 |
+
data = request.get_json(silent=True)
|
| 823 |
+
if not data or 'n' not in data:
|
| 824 |
+
return err("Provide 'n'")
|
| 825 |
+
try:
|
| 826 |
+
n = _safe_int(data['n'], MAX_NT_INT, "n")
|
| 827 |
+
if n < 2:
|
| 828 |
+
return err("n must be \u2265 2")
|
| 829 |
+
old_handler = signal.signal(signal.SIGALRM, _raise_timeout)
|
| 830 |
+
signal.alarm(5)
|
| 831 |
+
try:
|
| 832 |
+
factors = sympy.factorint(n)
|
| 833 |
+
finally:
|
| 834 |
+
signal.alarm(0)
|
| 835 |
+
signal.signal(signal.SIGALRM, old_handler)
|
| 836 |
+
steps = []
|
| 837 |
+
running = n
|
| 838 |
+
for p, e in sorted(factors.items()):
|
| 839 |
+
for _ in range(e):
|
| 840 |
+
steps.append({"divide_by": p, "before": running, "after": running // p})
|
| 841 |
+
running //= p
|
| 842 |
+
factor_str = ' \u00d7 '.join(f"{p}^{e}" if e > 1 else str(p) for p, e in sorted(factors.items()))
|
| 843 |
+
return jsonify({
|
| 844 |
+
"n": n, "factors": {str(k): v for k, v in factors.items()},
|
| 845 |
+
"factor_str": factor_str, "steps": steps,
|
| 846 |
+
"is_prime": len(factors) == 1 and list(factors.values())[0] == 1,
|
| 847 |
+
})
|
| 848 |
+
except _TimeoutError:
|
| 849 |
+
return err("Factorization took too long \u2014 try a smaller number", 408)
|
| 850 |
+
except ValueError as e:
|
| 851 |
+
return err(str(e))
|
| 852 |
+
except Exception as e:
|
| 853 |
+
return err(f"Factorization error: {e}")
|
| 854 |
+
|
| 855 |
+
|
| 856 |
+
@app.route('/api/totient', methods=['POST'])
|
| 857 |
+
@limiter.limit("30 per minute")
|
| 858 |
+
def api_totient():
|
| 859 |
+
data = request.get_json(silent=True)
|
| 860 |
+
if not data or 'n' not in data:
|
| 861 |
+
return err("Provide 'n'")
|
| 862 |
+
try:
|
| 863 |
+
n = _safe_int(data['n'], MAX_NT_INT, "n")
|
| 864 |
+
if n < 1:
|
| 865 |
+
return err("n must be \u2265 1")
|
| 866 |
+
factors = sympy.factorint(n)
|
| 867 |
+
phi = sympy.totient(n)
|
| 868 |
+
# phi(n) = n * prod(1 - 1/p) over distinct prime factors
|
| 869 |
+
terms = [f"(1 - 1/{p})" for p in sorted(factors)]
|
| 870 |
+
formula = f"{n} \u00d7 " + " \u00d7 ".join(terms) if terms else str(n)
|
| 871 |
+
return jsonify({
|
| 872 |
+
"n": n, "phi": int(phi),
|
| 873 |
+
"prime_factors": sorted(factors.keys()),
|
| 874 |
+
"formula": formula,
|
| 875 |
+
})
|
| 876 |
+
except ValueError as e:
|
| 877 |
+
return err(str(e))
|
| 878 |
+
except Exception as e:
|
| 879 |
+
return err(f"Totient error: {e}")
|
| 880 |
+
|
| 881 |
+
|
| 882 |
+
@app.route('/api/primitive-root', methods=['POST'])
|
| 883 |
+
@limiter.limit("30 per minute")
|
| 884 |
+
def api_primitive_root():
|
| 885 |
+
data = request.get_json(silent=True)
|
| 886 |
+
if not data or 'n' not in data:
|
| 887 |
+
return err("Provide 'n'")
|
| 888 |
+
try:
|
| 889 |
+
n = _safe_int(data['n'], MAX_NT_INT, "n")
|
| 890 |
+
if n < 1:
|
| 891 |
+
return err("n must be \u2265 1")
|
| 892 |
+
old_handler = signal.signal(signal.SIGALRM, _raise_timeout)
|
| 893 |
+
signal.alarm(5)
|
| 894 |
+
try:
|
| 895 |
+
g = sympy.primitive_root(n)
|
| 896 |
+
finally:
|
| 897 |
+
signal.alarm(0)
|
| 898 |
+
signal.signal(signal.SIGALRM, old_handler)
|
| 899 |
+
if g is None:
|
| 900 |
+
return jsonify({"n": n, "exists": False,
|
| 901 |
+
"msg": f"No primitive root exists mod {n} (only exists for n = 1, 2, 4, p^k, or 2p^k)"})
|
| 902 |
+
phi = int(sympy.totient(n))
|
| 903 |
+
order_check = []
|
| 904 |
+
for d in sorted(sympy.divisors(phi)):
|
| 905 |
+
val = pow(g, d, n)
|
| 906 |
+
order_check.append({"d": d, "g^d mod n": val})
|
| 907 |
+
return jsonify({"n": n, "exists": True, "g": g, "phi": phi, "order_check": order_check})
|
| 908 |
+
except _TimeoutError:
|
| 909 |
+
return err("Search took too long \u2014 try a smaller n", 408)
|
| 910 |
+
except ValueError as e:
|
| 911 |
+
return err(str(e))
|
| 912 |
+
except Exception as e:
|
| 913 |
+
return err(f"Primitive root error: {e}")
|
| 914 |
+
|
| 915 |
+
|
| 916 |
+
@app.route('/api/quad-residue', methods=['POST'])
|
| 917 |
+
@limiter.limit("30 per minute")
|
| 918 |
+
def api_quad_residue():
|
| 919 |
+
data = request.get_json(silent=True)
|
| 920 |
+
if not data or 'a' not in data or 'p' not in data:
|
| 921 |
+
return err("Provide 'a' and 'p'")
|
| 922 |
+
try:
|
| 923 |
+
a = _safe_int(data['a'], MAX_NT_INT, "a")
|
| 924 |
+
p = _safe_int(data['p'], MAX_NT_INT, "p")
|
| 925 |
+
if p < 2 or not sympy.isprime(p):
|
| 926 |
+
return err("p must be a prime \u2265 2 (Legendre symbol requires an odd prime modulus)")
|
| 927 |
+
is_qr = sympy.is_quad_residue(a, p)
|
| 928 |
+
# Euler's criterion: a^((p-1)/2) mod p -> 1 (QR), p-1 (non-QR), 0 (a≡0)
|
| 929 |
+
legendre_val = pow(a, (p - 1) // 2, p)
|
| 930 |
+
legendre = 0 if a % p == 0 else (1 if legendre_val == 1 else -1)
|
| 931 |
+
squares = sorted(set((k * k) % p for k in range(1, p)))
|
| 932 |
+
return jsonify({
|
| 933 |
+
"a": a, "p": p, "is_quad_residue": bool(is_qr),
|
| 934 |
+
"legendre_symbol": legendre,
|
| 935 |
+
"eulers_criterion": f"{a}^{(p-1)//2} mod {p} = {legendre_val}",
|
| 936 |
+
"quadratic_residues_mod_p": squares,
|
| 937 |
+
})
|
| 938 |
+
except ValueError as e:
|
| 939 |
+
return err(str(e))
|
| 940 |
+
except Exception as e:
|
| 941 |
+
return err(f"Quadratic residue error: {e}")
|
| 942 |
+
|
| 943 |
+
|
| 944 |
+
@app.route('/api/crt', methods=['POST'])
|
| 945 |
+
@limiter.limit("30 per minute")
|
| 946 |
+
def api_crt():
|
| 947 |
+
data = request.get_json(silent=True)
|
| 948 |
+
if not data or 'remainders' not in data or 'moduli' not in data:
|
| 949 |
+
return err("Provide 'remainders' and 'moduli' (parallel arrays)")
|
| 950 |
+
try:
|
| 951 |
+
remainders = data['remainders']
|
| 952 |
+
moduli = data['moduli']
|
| 953 |
+
if len(remainders) != len(moduli):
|
| 954 |
+
return err("'remainders' and 'moduli' must be the same length")
|
| 955 |
+
if len(remainders) < 2 or len(remainders) > 10:
|
| 956 |
+
return err("Provide 2 to 10 congruences")
|
| 957 |
+
rs = [_safe_int(r, MAX_NT_INT, "remainder") for r in remainders]
|
| 958 |
+
ms = [_safe_int(m, MAX_NT_INT, "modulus") for m in moduli]
|
| 959 |
+
if any(m < 2 for m in ms):
|
| 960 |
+
return err("All moduli must be \u2265 2")
|
| 961 |
+
# pairwise coprimality check (sympy.crt requires it for a unique solution)
|
| 962 |
+
for i in range(len(ms)):
|
| 963 |
+
for j in range(i + 1, len(ms)):
|
| 964 |
+
if sympy.gcd(ms[i], ms[j]) != 1:
|
| 965 |
+
return err(f"Moduli {ms[i]} and {ms[j]} are not coprime \u2014 CRT needs pairwise coprime moduli")
|
| 966 |
+
from sympy.ntheory.modular import crt as sympy_crt
|
| 967 |
+
result = sympy_crt(ms, rs)
|
| 968 |
+
if result is None:
|
| 969 |
+
return err("No solution exists for this system")
|
| 970 |
+
x, M = result
|
| 971 |
+
# Build pairwise-combination steps for the UI (combine first two, then fold in each remaining)
|
| 972 |
+
steps = []
|
| 973 |
+
cur_r, cur_m = rs[0], ms[0]
|
| 974 |
+
for i in range(1, len(ms)):
|
| 975 |
+
from sympy.ntheory.modular import crt as step_crt
|
| 976 |
+
nxt = step_crt([cur_m, ms[i]], [cur_r, rs[i]])
|
| 977 |
+
cur_r, cur_m = int(nxt[0]), int(nxt[1])
|
| 978 |
+
steps.append({"combined_with": {"r": rs[i], "m": ms[i]}, "result": {"x": cur_r, "mod": cur_m}})
|
| 979 |
+
return jsonify({"x": int(x), "M": int(M), "steps": steps})
|
| 980 |
+
except ValueError as e:
|
| 981 |
+
return err(str(e))
|
| 982 |
+
except Exception as e:
|
| 983 |
+
return err(f"CRT error: {e}")
|
| 984 |
+
|
| 985 |
+
|
| 986 |
+
@app.route('/api/rsa', methods=['POST'])
|
| 987 |
+
@limiter.limit("20 per minute")
|
| 988 |
+
def api_rsa():
|
| 989 |
+
data = request.get_json(silent=True)
|
| 990 |
+
if not data:
|
| 991 |
+
return err("No data provided")
|
| 992 |
+
try:
|
| 993 |
+
p = _safe_int(data.get('p'), MAX_RSA_PRIME, "p")
|
| 994 |
+
q = _safe_int(data.get('q'), MAX_RSA_PRIME, "q")
|
| 995 |
+
if not sympy.isprime(p) or not sympy.isprime(q):
|
| 996 |
+
return err("p and q must both be prime")
|
| 997 |
+
if p == q:
|
| 998 |
+
return err("p and q must be different primes")
|
| 999 |
+
n = p * q
|
| 1000 |
+
phi = (p - 1) * (q - 1)
|
| 1001 |
+
e = data.get('e')
|
| 1002 |
+
if e is None:
|
| 1003 |
+
e = 65537 if sympy.gcd(65537, phi) == 1 else 17
|
| 1004 |
+
else:
|
| 1005 |
+
e = _safe_int(e, phi, "e")
|
| 1006 |
+
if sympy.gcd(e, phi) != 1:
|
| 1007 |
+
return err(f"e={e} is not coprime with \u03c6(n)={phi} \u2014 choose a different e")
|
| 1008 |
+
d = int(sympy.mod_inverse(e, phi))
|
| 1009 |
+
|
| 1010 |
+
result = {"p": p, "q": q, "n": n, "phi": phi, "e": e, "d": d}
|
| 1011 |
+
|
| 1012 |
+
mode = data.get('mode', 'keygen')
|
| 1013 |
+
if mode == 'encrypt' and 'message' in data:
|
| 1014 |
+
m = _safe_int(data['message'], n - 1, "message")
|
| 1015 |
+
if m >= n:
|
| 1016 |
+
return err(f"message must be less than n={n}")
|
| 1017 |
+
c = pow(m, e, n)
|
| 1018 |
+
result.update({"mode": "encrypt", "message": m, "ciphertext": c})
|
| 1019 |
+
elif mode == 'decrypt' and 'ciphertext' in data:
|
| 1020 |
+
c = _safe_int(data['ciphertext'], n - 1, "ciphertext")
|
| 1021 |
+
m = pow(c, d, n)
|
| 1022 |
+
result.update({"mode": "decrypt", "ciphertext": c, "message": m})
|
| 1023 |
+
return jsonify(result)
|
| 1024 |
+
except ValueError as e:
|
| 1025 |
+
return err(str(e))
|
| 1026 |
+
except Exception as e:
|
| 1027 |
+
return err(f"RSA error: {e}")
|
| 1028 |
+
|
| 1029 |
+
|
| 1030 |
+
@app.route('/api/miller-rabin', methods=['POST'])
|
| 1031 |
+
@limiter.limit("30 per minute")
|
| 1032 |
+
def api_miller_rabin():
|
| 1033 |
+
data = request.get_json(silent=True)
|
| 1034 |
+
if not data or 'n' not in data:
|
| 1035 |
+
return err("Provide 'n'")
|
| 1036 |
+
try:
|
| 1037 |
+
n = _safe_int(data['n'], 10**30, "n") # isprime handles big n fine, no factoring needed
|
| 1038 |
+
if n < 2:
|
| 1039 |
+
return jsonify({"n": n, "prime": False, "steps": []})
|
| 1040 |
+
witnesses = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]
|
| 1041 |
+
witnesses = [w for w in witnesses if w < n - 1] or [2]
|
| 1042 |
+
if n in (2, 3):
|
| 1043 |
+
return jsonify({"n": n, "prime": True, "steps": []})
|
| 1044 |
+
if n % 2 == 0:
|
| 1045 |
+
return jsonify({"n": n, "prime": False, "steps": [{"note": "n is even"}]})
|
| 1046 |
+
d, r = n - 1, 0
|
| 1047 |
+
while d % 2 == 0:
|
| 1048 |
+
d //= 2
|
| 1049 |
+
r += 1
|
| 1050 |
+
steps = []
|
| 1051 |
+
is_prime_result = True
|
| 1052 |
+
for a in witnesses:
|
| 1053 |
+
x = pow(a, d, n)
|
| 1054 |
+
seq = [x]
|
| 1055 |
+
step = {"witness": a}
|
| 1056 |
+
if x == 1 or x == n - 1:
|
| 1057 |
+
step["sequence"] = seq
|
| 1058 |
+
step["result"] = "inconclusive (passes this witness)"
|
| 1059 |
+
steps.append(step)
|
| 1060 |
+
continue
|
| 1061 |
+
composite_witness = True
|
| 1062 |
+
for _ in range(r - 1):
|
| 1063 |
+
x = pow(x, 2, n)
|
| 1064 |
+
seq.append(x)
|
| 1065 |
+
if x == n - 1:
|
| 1066 |
+
composite_witness = False
|
| 1067 |
+
break
|
| 1068 |
+
step["sequence"] = seq
|
| 1069 |
+
step["result"] = "COMPOSITE \u2014 witness found" if composite_witness else "passes this witness"
|
| 1070 |
+
steps.append(step)
|
| 1071 |
+
if composite_witness:
|
| 1072 |
+
is_prime_result = False
|
| 1073 |
+
break
|
| 1074 |
+
return jsonify({"n": n, "d": d, "r": r, "prime": is_prime_result, "steps": steps})
|
| 1075 |
+
except ValueError as e:
|
| 1076 |
+
return err(str(e))
|
| 1077 |
+
except Exception as e:
|
| 1078 |
+
return err(f"Miller-Rabin error: {e}")
|
| 1079 |
+
|
| 1080 |
+
|
| 1081 |
+
@app.errorhandler(429)
|
| 1082 |
+
def handle_rate_limit(e):
|
| 1083 |
+
return jsonify({"error": "Too many requests — please slow down and try again shortly."}), 429
|
| 1084 |
+
|
| 1085 |
+
|
| 1086 |
+
@app.errorhandler(Exception)
|
| 1087 |
+
def handle_uncaught(e):
|
| 1088 |
+
app.logger.error(traceback.format_exc())
|
| 1089 |
+
return jsonify({"error": "Internal server error"}), 500
|
| 1090 |
+
|
| 1091 |
+
|
| 1092 |
+
if __name__ == '__main__':
|
| 1093 |
+
app.run(host='0.0.0.0', port=7860)
|