aciang commited on
Commit
776f525
·
verified ·
1 Parent(s): 2f94119

Upload folder using huggingface_hub

Browse files
Files changed (2) hide show
  1. README.md +1 -1
  2. app.py +42 -31
README.md CHANGED
@@ -9,4 +9,4 @@ app_file: app.py
9
  pinned: false
10
  ---
11
 
12
- 純 SymPy 的數學推理代理(不依賴 LLM),支援一次貼上長式、簡化、解一元/聯立方程。
 
9
  pinned: false
10
  ---
11
 
12
+ **SymPy** 的數學推理代理(不依賴 LLM)。支援一次貼上長式、簡化、解一元/聯立方程與基本微積分。
app.py CHANGED
@@ -8,70 +8,81 @@ def solve_math(q: str):
8
  q = (q or "").strip()
9
  if not q:
10
  return "請輸入算式或方程,例如:2x+3=11;或:sin(x)**2 + cos(x)**2;或:factor(x**2-9)"
 
11
  try:
12
- # 1) 如果像 "2x+3=11" "x+y=3; x-y=1"
13
  if "=" in q:
14
- # 支援多行/分號;同時支援聯立
15
- parts = [s.strip() for seg in q.split(";") for s in seg.split("\n")]
 
 
 
 
16
  eqs = []
17
  syms = set()
18
  for s in parts:
19
- if not s:
20
  continue
21
  left, right = s.split("=", 1)
22
- eq = sp.Eq(sp.sympify(left), sp.sympify(right))
 
 
23
  eqs.append(eq)
24
- syms |= eq.free_symbols
25
- syms |= eq.rhs.free_symbols if hasattr(eq, "rhs") else set()
 
 
26
  if not syms:
27
- # 預設一個 x
28
- x = sp.symbols("x")
29
- syms = {x}
30
  sol = sp.solve(eqs, list(syms), dict=True)
31
  if not sol:
32
  return "無解或需要更多條件。"
33
- # 格式化
34
  lines = []
35
  for i, s in enumerate(sol, 1):
36
- lines.append(f"解 {i}: " + ", ".join([f"{k} = {sp.simplify(v)}" for k, v in s.items()]))
 
 
37
  return "\n".join(lines)
38
 
39
- # 2) 非方程:嘗試自動辨識可做的操作(簡化/因式分解/微分/積分…)
40
  expr = sp.sympify(q)
41
- # 嘗試:若像 “diff(sin(x), x)” 就直接回傳求導;否則做一輪常見操作建議
 
42
  try:
43
- simplified = sp.simplify(expr)
 
44
  except Exception:
45
- simplified = expr
46
 
47
- tips = []
48
- tips.append(f"簡化:{simplified}")
49
  try:
50
- fact = sp.factor(expr)
51
- if fact != expr:
52
- tips.append(f"因式分解:{fact}")
53
  except Exception:
54
  pass
 
55
  try:
56
  x = list(expr.free_symbols)[0] if expr.free_symbols else sp.symbols("x")
57
- tips.append(f"對 {x} 微分:{sp.diff(expr, x)}")
58
- tips.append(f"對 {x} 積分:{sp.integrate(expr, x)}")
59
  except Exception:
60
  pass
61
- return "\n".join(tips) if tips else f"結果:{expr}"
 
62
 
63
  except Exception as e:
64
  return f"解析失敗:{e}"
65
 
66
  with gr.Blocks(title=TITLE) as demo:
67
- gr.Markdown(f"## {TITLE}\n貼上算式(可多行 / 用分號 `;` 分隔):")
68
- with gr.Row():
69
- q = gr.Textbox(lines=6, label="題目 / 算式(可含聯立方程)")
70
- with gr.Row():
71
- out = gr.Textbox(lines=10, label="輸出")
72
  btn = gr.Button("送出 🚀")
73
- btn.click(fn=solve_math, inputs=q, outputs=out)
74
 
75
  if __name__ == "__main__":
76
- # 在 Colab 本機預覽一定要 share=True 才會印出 public URL
77
  demo.launch(share=True)
 
8
  q = (q or "").strip()
9
  if not q:
10
  return "請輸入算式或方程,例如:2x+3=11;或:sin(x)**2 + cos(x)**2;或:factor(x**2-9)"
11
+
12
  try:
13
+ # 情境 A:含 '=' 視為(可能多條)方程,支援分號/換行分隔
14
  if "=" in q:
15
+ # 將多行與分號斷開
16
+ parts = []
17
+ for seg in q.split(";"):
18
+ parts += [s.strip() for s in seg.split("\n")]
19
+ parts = [s for s in parts if s]
20
+
21
  eqs = []
22
  syms = set()
23
  for s in parts:
24
+ if "=" not in s:
25
  continue
26
  left, right = s.split("=", 1)
27
+ L = sp.sympify(left)
28
+ R = sp.sympify(right)
29
+ eq = sp.Eq(L, R)
30
  eqs.append(eq)
31
+ syms |= L.free_symbols | R.free_symbols
32
+
33
+ if not eqs:
34
+ return "沒有可解析的方程式。"
35
  if not syms:
36
+ syms = {sp.symbols("x")}
37
+
38
+ # 解聯立(回傳 dict 列表)
39
  sol = sp.solve(eqs, list(syms), dict=True)
40
  if not sol:
41
  return "無解或需要更多條件。"
42
+
43
  lines = []
44
  for i, s in enumerate(sol, 1):
45
+ lines.append(
46
+ "解 {}: ".format(i) + ", ".join(f"{k} = {sp.simplify(v)}" for k, v in s.items())
47
+ )
48
  return "\n".join(lines)
49
 
50
+ # 情境 B:純表達式 → 嘗試簡化、因式、微分、積分
51
  expr = sp.sympify(q)
52
+ out = []
53
+
54
  try:
55
+ simp = sp.simplify(expr)
56
+ out.append(f"簡化:{simp}")
57
  except Exception:
58
+ pass
59
 
 
 
60
  try:
61
+ fac = sp.factor(expr)
62
+ if fac != expr:
63
+ out.append(f"因式分解:{fac}")
64
  except Exception:
65
  pass
66
+
67
  try:
68
  x = list(expr.free_symbols)[0] if expr.free_symbols else sp.symbols("x")
69
+ out.append(f"對 {x} 微分:{sp.diff(expr, x)}")
70
+ out.append(f"對 {x} 積分:{sp.integrate(expr, x)}")
71
  except Exception:
72
  pass
73
+
74
+ return "\n".join(out) if out else f"結果:{expr}"
75
 
76
  except Exception as e:
77
  return f"解析失敗:{e}"
78
 
79
  with gr.Blocks(title=TITLE) as demo:
80
+ gr.Markdown(f"## {TITLE}\n- 貼上**算式/方程**(可多行;或用分號 `;` 分隔聯立)\n- 範例:`2x+3=11`、`x+y=3; x-y=1`、`sin(x)**2 + cos(x)**2`、`factor(x**2-9)`")
81
+ q = gr.Textbox(lines=6, label="題目 / 算式(可含聯立方程)")
82
+ out = gr.Textbox(lines=12, label="輸出")
 
 
83
  btn = gr.Button("送出 🚀")
84
+ btn.click(solve_math, q, out)
85
 
86
  if __name__ == "__main__":
87
+ # 在 Colab 預覽:一定要 share=True 才會印出 public URL
88
  demo.launch(share=True)