File size: 2,868 Bytes
2f94119
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
70
71
72
73
74
75
76
77
78
\
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:
        # 1) 如果像 "2x+3=11" 或 "x+y=3; x-y=1"
        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
                left, right = s.split("=", 1)
                eq = sp.Eq(sp.sympify(left), sp.sympify(right))
                eqs.append(eq)
                syms |= eq.free_symbols
                syms |= eq.rhs.free_symbols if hasattr(eq, "rhs") else set()
            if not syms:
                # 預設一個 x
                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)

        # 2) 非方程:嘗試自動辨識可做的操作(簡化/因式分解/微分/積分…)
        expr = sp.sympify(q)
        # 嘗試:若像 “diff(sin(x), x)” 就直接回傳求導;否則做一輪常見操作建議
        try:
            simplified = sp.simplify(expr)
        except Exception:
            simplified = expr

        tips = []
        tips.append(f"簡化:{simplified}")
        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貼上算式(可多行 / 用分號 `;` 分隔):")
    with gr.Row():
        q = gr.Textbox(lines=6, label="題目 / 算式(可含聯立方程)")
    with gr.Row():
        out = gr.Textbox(lines=10, label="輸出")
    btn = gr.Button("送出 🚀")
    btn.click(fn=solve_math, inputs=q, outputs=out)

if __name__ == "__main__":
    # 在 Colab 本機預覽一定要 share=True 才會印出 public URL
    demo.launch(share=True)