| \ |
| import gradio as gr |
| import sympy as sp |
|
|
| TITLE = "LanguageBridge — Math Fast Agent (SymPy)" |
|
|
| def solve_math(q: str): |
| q = (q or "").strip() |
| if not q: |
| return "請輸入算式或方程,例如:2x+3=11;或:sin(x)**2 + cos(x)**2;或:factor(x**2-9)" |
| try: |
| |
| if "=" in q: |
| parts = [s.strip() for seg in q.split(";") for s in seg.split("\n")] |
| eqs, syms = [], set() |
| for s in parts: |
| if not s: |
| continue |
| if "=" not in s: |
| continue |
| left, right = s.split("=", 1) |
| eq = sp.Eq(sp.sympify(left), sp.sympify(right)) |
| eqs.append(eq) |
| syms |= eq.free_symbols |
| if hasattr(eq, "rhs"): |
| syms |= eq.rhs.free_symbols |
| if not syms: |
| x = sp.symbols("x") |
| syms = {x} |
| sol = sp.solve(eqs, list(syms), dict=True) |
| if not sol: |
| return "無解或需要更多條件。" |
| lines = [] |
| for i, s in enumerate(sol, 1): |
| lines.append(f"解 {i}: " + ", ".join([f"{k} = {sp.simplify(v)}" for k, v in s.items()])) |
| return "\n".join(lines) |
|
|
| |
| expr = sp.sympify(q) |
| tips = [] |
| try: |
| tips.append(f"簡化:{sp.simplify(expr)}") |
| except Exception: |
| tips.append(f"簡化:{expr}") |
| try: |
| fact = sp.factor(expr) |
| if fact != expr: |
| tips.append(f"因式分解:{fact}") |
| except Exception: |
| pass |
| try: |
| x = list(expr.free_symbols)[0] if expr.free_symbols else sp.symbols("x") |
| tips.append(f"對 {x} 微分:{sp.diff(expr, x)}") |
| tips.append(f"對 {x} 積分:{sp.integrate(expr, x)}") |
| except Exception: |
| pass |
| return "\n".join(tips) if tips else f"結果:{expr}" |
| except Exception as e: |
| return f"解析失敗:{e}" |
|
|
| with gr.Blocks(title=TITLE) as demo: |
| gr.Markdown(f"## {TITLE}\n貼上算式(可多行 / 用分號 `;` 分隔):") |
| q = gr.Textbox(lines=6, label="題目 / 算式(可含聯立方程)") |
| out = gr.Textbox(lines=10, label="輸出") |
| gr.Button("送出 🚀").click(fn=solve_math, inputs=q, outputs=out) |
|
|
| if __name__ == "__main__": |
| demo.launch() |
|
|