File size: 2,498 Bytes
374899e
a94c11b
 
208dcde
374899e
208dcde
374899e
fce8f29
a94c11b
374899e
 
 
 
42cead7
 
 
 
 
374899e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42cead7
374899e
42cead7
374899e
42cead7
374899e
 
 
 
 
 
 
 
 
 
 
 
cb4a7d6
374899e
208dcde
1aa9377
374899e
 
 
 
a94c11b
cb4a7d6
fce8f29
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
\
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()