wengua 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
wengua/__init__.py ADDED
@@ -0,0 +1,13 @@
1
+ """Wengua 问卦: the accurate, open I Ching for every AI.
2
+
3
+ Code casts, the model reads. 排卦归程序,解卦归模型。
4
+ """
5
+
6
+ __version__ = "0.1.0"
7
+
8
+ from .data import hexagram, trigram, trigrams # noqa: E402
9
+ from .lookup import find, get # noqa: E402
10
+ from .reading import cast, read_cast # noqa: E402
11
+ from .selection import RULES # noqa: E402
12
+
13
+ __all__ = ["__version__", "cast", "read_cast", "find", "get", "hexagram", "trigram", "trigrams", "RULES"]
wengua/casting.py ADDED
@@ -0,0 +1,98 @@
1
+ """Casting methods. Each returns six line values, bottom to top, and a record of
2
+ every coin or stalk so the cast can be audited and replayed.
3
+
4
+ Line values: 6 old yin (changing), 7 young yang, 8 young yin, 9 old yang (changing).
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from .rng import randbelow
10
+
11
+ VALID_VALUES = (6, 7, 8, 9)
12
+
13
+
14
+ def cast_coins(rng) -> tuple[list[int], list[dict]]:
15
+ """Three coins per line. Heads count 3, tails 2.
16
+
17
+ P(6, 7, 8, 9) = 1/8, 3/8, 3/8, 1/8.
18
+ """
19
+ values, record = [], []
20
+ for _ in range(6):
21
+ coins = [3 if randbelow(rng, 2) else 2 for _ in range(3)]
22
+ value = sum(coins)
23
+ values.append(value)
24
+ record.append({"coins": coins, "value": value})
25
+ return values, record
26
+
27
+
28
+ def _remainder(n: int) -> int:
29
+ """Count a heap off by fours: the remainder is 1 to 4 (4 when it divides evenly)."""
30
+ return 0 if n == 0 else (n - 1) % 4 + 1
31
+
32
+
33
+ def cast_yarrow(rng) -> tuple[list[int], list[dict]]:
34
+ """The 大衍筮法: 50 stalks, one set aside, three changes per line.
35
+
36
+ Each change divides the stalks into two heaps at random, hangs one stalk
37
+ from the right heap (掛一), and counts both heaps off by fours (揲四), setting
38
+ the remainders aside (歸奇). After three changes the remaining stalks divided
39
+ by four give the line value.
40
+
41
+ The left heap is drawn uniformly from 1 to the largest multiple of four
42
+ that still leaves the right heap a stalk after hanging one. Every remainder
43
+ is then equally likely, both heaps are never empty, and the line values come
44
+ out with exactly the classical odds P(6, 7, 8, 9) = 1/16, 5/16, 7/16, 3/16.
45
+ """
46
+ values, record = [], []
47
+ for _ in range(6):
48
+ stalks = 49
49
+ changes = []
50
+ for _ in range(3):
51
+ left = randbelow(rng, 4 * ((stalks - 2) // 4)) + 1
52
+ right = stalks - left - 1 # one stalk hung between the fingers
53
+ rl, rr = _remainder(left), _remainder(right)
54
+ removed = 1 + rl + rr
55
+ changes.append({"stalks": stalks, "left": left, "right": right + 1,
56
+ "left_remainder": rl, "right_remainder": rr, "removed": removed})
57
+ stalks -= removed
58
+ value = stalks // 4
59
+ values.append(value)
60
+ record.append({"changes": changes, "remaining": stalks, "value": value})
61
+ return values, record
62
+
63
+
64
+ def parse_manual(values) -> tuple[list[int], list[dict]]:
65
+ """Six values from a physical cast, bottom to top.
66
+
67
+ Each item is a line value (6, 7, 8, 9) or the three coin faces of that line,
68
+ given as numbers (2 or 3) or as "h"/"t" (heads 3, tails 2).
69
+ """
70
+ if len(values) != 6:
71
+ raise ValueError("a cast has exactly six lines, bottom to top")
72
+ out, record = [], []
73
+ for v in values:
74
+ if isinstance(v, (list, tuple)):
75
+ coins = [_coin(c) for c in v]
76
+ if len(coins) != 3:
77
+ raise ValueError("each line needs three coins")
78
+ out.append(sum(coins))
79
+ record.append({"coins": coins, "value": sum(coins)})
80
+ else:
81
+ n = int(v)
82
+ if n not in VALID_VALUES:
83
+ raise ValueError(f"line value must be 6, 7, 8 or 9, got {v!r}")
84
+ out.append(n)
85
+ record.append({"value": n})
86
+ return out, record
87
+
88
+
89
+ def _coin(c) -> int:
90
+ if isinstance(c, str):
91
+ c = c.strip().lower()
92
+ if c in ("h", "heads", "3"):
93
+ return 3
94
+ if c in ("t", "tails", "2"):
95
+ return 2
96
+ elif c in (2, 3):
97
+ return int(c)
98
+ raise ValueError(f"a coin is heads (3) or tails (2), got {c!r}")
wengua/cli.py ADDED
@@ -0,0 +1,114 @@
1
+ """wengua command line: cast, read a physical cast, look up, or run the MCP server."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import sys
8
+
9
+ from . import __version__
10
+ from .lookup import find
11
+ from .reading import METHODS, cast, read_cast
12
+ from .selection import RULES
13
+
14
+ YANG, YIN = "━━━━━━━━━", "━━━ ━━━"
15
+
16
+
17
+ def draw(values: list[int]) -> list[str]:
18
+ rows = []
19
+ for i in range(5, -1, -1):
20
+ v = values[i]
21
+ mark = {9: " ○ 9", 6: " ✕ 6"}.get(v, f" {v}")
22
+ rows.append(f" {YANG if v in (7, 9) else YIN}{mark}")
23
+ return rows
24
+
25
+
26
+ def both(t: dict) -> str:
27
+ """Traditional and simplified, shown once when they are the same."""
28
+ return t["zh_hant"] if t["zh_hant"] == t["zh_hans"] else f"{t['zh_hant']} / {t['zh_hans']}"
29
+
30
+
31
+ def title(h: dict) -> str:
32
+ n = h["name"]
33
+ return f"{h['unicode']} {h['number']} {both(n)} {n['pinyin']} · {n['en']}"
34
+
35
+
36
+ def render(r: dict) -> str:
37
+ out = []
38
+ if r["question"]:
39
+ out.append(f"Question: {r['question']}")
40
+ out.append(title(r["primary"]) + (f" → {title(r['relating'])}" if r["relating"] else ""))
41
+ out += draw(r["values"])
42
+ sel = r["selection"]
43
+ out += ["", sel["explanation"]["zh_hant"], sel["explanation"]["zh_hans"], sel["explanation"]["en"]]
44
+ for t in sel["texts"]:
45
+ label = both(t["label"]) if t["label"] else "卦辭 / 卦辞"
46
+ out.append(f" [{t['hexagram']} {label}] ({t['role']})")
47
+ out.append(f" {t['text']['zh_hant']}")
48
+ if t["text"]["zh_hans"] != t["text"]["zh_hant"]:
49
+ out.append(f" {t['text']['zh_hans']}")
50
+ a = r["audit"]
51
+ out.append("")
52
+ out.append(f"互 {both(r['nuclear']['name'])} · 錯/错 {both(r['opposite']['name'])} · 綜/综 {both(r['inverse']['name'])}")
53
+ out.append(f"{r['method']} · rng {a['rng']}{' (TEST, not a real reading)' if a['test'] else ''} · {a['library']} · {a['dataset']}")
54
+ return "\n".join(out)
55
+
56
+
57
+ def main(argv=None) -> int:
58
+ p = argparse.ArgumentParser(prog="wengua", description="Wengua 问卦: consult the I Ching. Code casts, the model reads.")
59
+ p.add_argument("--version", action="version", version=f"wengua {__version__}")
60
+ sub = p.add_subparsers(dest="cmd")
61
+
62
+ def common(sp):
63
+ sp.add_argument("-q", "--question")
64
+ sp.add_argument("--rule", choices=RULES, default="zhuxi")
65
+ sp.add_argument("--json", action="store_true", help="print the full Reading as JSON")
66
+
67
+ c = sub.add_parser("cast", help="cast a hexagram")
68
+ common(c)
69
+ c.add_argument("-m", "--method", choices=METHODS, default="coins")
70
+ c.add_argument("--seed", type=int, help="replay with a seed (test mode, not a real reading)")
71
+
72
+ rd = sub.add_parser("read", help="read a physical cast: six values bottom to top, e.g. 7 8 9 7 6 8")
73
+ common(rd)
74
+ rd.add_argument("values", nargs=6)
75
+
76
+ lk = sub.add_parser("lookup", help="look up a hexagram by number, name, pinyin, symbol, bits or trigrams")
77
+ lk.add_argument("query", nargs="+")
78
+ lk.add_argument("--json", action="store_true")
79
+
80
+ sub.add_parser("mcp", help="run the MCP server over stdio")
81
+
82
+ a = p.parse_args(argv)
83
+ try:
84
+ if a.cmd in (None, "mcp"): # bare `wengua` (as `uvx wengua` in an MCP client) runs the server
85
+ from .mcp import serve
86
+ serve()
87
+ return 0
88
+ if a.cmd == "lookup":
89
+ found = find(" ".join(a.query))
90
+ if not found:
91
+ print("No hexagram matches.", file=sys.stderr)
92
+ return 1
93
+ if a.json:
94
+ print(json.dumps(found if len(found) > 1 else found[0], ensure_ascii=False, indent=2))
95
+ else:
96
+ for h in found:
97
+ print(title(h))
98
+ print(f" {h['judgment']['zh_hant']}")
99
+ if h["judgment"]["zh_hans"] != h["judgment"]["zh_hant"]:
100
+ print(f" {h['judgment']['zh_hans']}")
101
+ return 0
102
+ if a.cmd == "cast":
103
+ r = cast(a.question, a.method, rule=a.rule, seed=a.seed, mode="test" if a.seed is not None else None)
104
+ else:
105
+ r = read_cast(a.values, a.question, rule=a.rule)
106
+ except ValueError as e:
107
+ print(f"wengua: {e}", file=sys.stderr)
108
+ return 2
109
+ print(json.dumps(r, ensure_ascii=False, indent=2) if a.json else render(r))
110
+ return 0
111
+
112
+
113
+ if __name__ == "__main__":
114
+ sys.exit(main())