-
Notifications
You must be signed in to change notification settings - Fork 116
Expand file tree
/
Copy pathapp.py
More file actions
1593 lines (1452 loc) · 53.1 KB
/
Copy pathapp.py
File metadata and controls
1593 lines (1452 loc) · 53.1 KB
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import sys
import json
import random
import urllib.request
# Ensure the src directory is on the Python path so that the ichingshifa
# package can be imported when the app is launched from the project root
# (e.g. ``streamlit run app.py``).
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "src"))
import streamlit as st
import streamlit.components.v1 as components
import pendulum as pdlm
from contextlib import contextmanager, redirect_stdout
from io import StringIO
from ichingshifa import ichingshifa
from ichingshifa.cerebras_client import (
CerebrasClient,
OpenAICompatibleClient,
DEFAULT_MODEL,
CEREBRAS_MODEL_OPTIONS,
CEREBRAS_MODEL_DESCRIPTIONS,
)
# ---------------------------------------------------------------------------
# Helper utilities
# ---------------------------------------------------------------------------
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
SYSTEM_PROMPTS_FILE = os.path.join(BASE_DIR, "system_prompts.json")
DEFAULT_MAX_TOKENS = 200000
DEFAULT_TEMPERATURE = 0.7
DEFAULT_CUSTOM_SERVER = "https://api.openai.com/v1"
DEFAULT_CUSTOM_MODEL = "gpt-4o-mini"
YAO_LABELS = {"6": "老陰", "7": "少陽", "8": "少陰", "9": "老陽"}
YAO_SYMBOLS = {"6": "▅▅ ▅▅ X", "7": "▅▅▅▅▅ ", "8": "▅▅ ▅▅ ", "9": "▅▅▅▅▅ O"}
YAO_POSITIONS = ["初爻", "二爻", "三爻", "四爻", "五爻", "上爻"]
XI_CI_QUOTE = (
"「大衍之數五十,其用四十有九。分而為二以象兩,掛一以象三,"
"揲之以四以象四,歸奇於扐以象閏。五歲再閏,故再扐而後掛。」"
"——《周易·繫辭傳》"
)
@contextmanager
def st_capture(output_func):
with StringIO() as stdout, redirect_stdout(stdout):
old_write = stdout.write
def new_write(string):
ret = old_write(string)
output_func(stdout.getvalue())
return ret
stdout.write = new_write
yield
def read_local_file(path):
"""Read a text file relative to the project root."""
full = os.path.join(BASE_DIR, path)
with open(full, "r", encoding="utf-8") as f:
return f.read()
def get_remote_file(url):
"""Fetch a remote text file."""
response = urllib.request.urlopen(url)
return response.read().decode("utf-8")
def get_ai_provider_settings():
provider = st.session_state.get("ai_provider_selector", "Cerebras")
if provider == "Cerebras":
api_key = (
st.session_state.get("cerebras_api_key_input", "").strip()
or st.secrets.get("CEREBRAS_API_KEY", "")
or os.getenv("CEREBRAS_API_KEY", "")
)
model = st.session_state.get("cerebras_model_selector", DEFAULT_MODEL)
if not api_key:
raise ValueError("CEREBRAS API Key 未設置,請在側邊欄或 secrets/環境變量中設置。")
return provider, model, CerebrasClient(api_key=api_key)
api_key = st.session_state.get("custom_ai_api_key_input", "").strip()
server = st.session_state.get("custom_ai_server_input", "").strip()
model = st.session_state.get("custom_ai_model_input", "").strip()
if not api_key:
raise ValueError("請輸入自定義 AI 的 API Key。")
if not server:
raise ValueError("請輸入自定義 AI 的 Server URL。")
if not model:
raise ValueError("請輸入自定義 AI 的模型名稱。")
return provider, model, OpenAICompatibleClient(api_key=api_key, base_url=server)
def request_ai_response(messages, max_tokens, temperature):
provider, model, client = get_ai_provider_settings()
api_params = {
"messages": messages,
"model": model,
"max_tokens": max_tokens,
"temperature": temperature,
}
if provider == "Cerebras":
response = client.get_chat_completion(**api_params)
return response.choices[0].message.content
response = client.get_chat_completion(**api_params)
choices = response.get("choices", [])
if not choices:
raise ValueError("AI 未返回任何回應。")
message = choices[0].get("message", {})
content = message.get("content")
if not content:
raise ValueError("AI 回應內容為空。")
return content
# ---------------------------------------------------------------------------
# System prompt persistence
# ---------------------------------------------------------------------------
def load_system_prompts():
"""Load system prompts from JSON file, creating defaults if needed."""
default_content = (
"你是一位精通周易六爻的大師,熟悉《增刪卜易》、《卜筮正宗》、《黃金策》及歷史占例。"
"請根據提供的六爻排盤數據,進行以下操作:\n\n"
"1. 解釋卦象的關鍵要素(本卦、之卦、世應、六親、動爻、伏神等)。\n"
"2. 結合六爻理論,分析卦象的吉凶和潛在影響。\n"
"3. 根據用神、原神、忌神、仇神的旺衰及動靜,詳細評估事情的發展趨勢。\n"
"4. 提供實用的建議或應對策略。\n\n"
"請以清晰的結構(分段、標題)呈現,語言專業且易懂,適當引用經典理論或歷史占例。"
)
try:
with open(SYSTEM_PROMPTS_FILE, "r", encoding="utf-8") as f:
return json.load(f)
except (FileNotFoundError, json.JSONDecodeError):
default_data = {
"prompts": [{"name": "六爻大師", "content": default_content}],
"selected": "六爻大師",
}
with open(SYSTEM_PROMPTS_FILE, "w", encoding="utf-8") as f:
json.dump(default_data, f, indent=2, ensure_ascii=False)
return default_data
def save_system_prompts(prompts_data):
"""Persist system prompts to JSON file."""
try:
with open(SYSTEM_PROMPTS_FILE, "w", encoding="utf-8") as f:
json.dump(prompts_data, f, indent=2, ensure_ascii=False)
return True
except Exception as e:
st.error(f"儲存提示時發生錯誤:{e}")
return False
# ---------------------------------------------------------------------------
# 大衍筮法狀態機
# ---------------------------------------------------------------------------
#
# 狀態機設計:
# phase: idle → active → completed
# yao: 1..6(當前爻位,由下而上)
# change: 1..3(當前爻內之變)
# step: divide → hang_one → count_four → change_done → (下一變或 yao_done)
#
# 每爻獨立以 49 策起算;三變後餘策 ÷ 4 = 爻值 (6/7/8/9)
def init_dayan_state():
defaults = {
"dayan_phase": "idle",
"dayan_yao": 0,
"dayan_change": 0,
"dayan_step": "ready",
"dayan_stalks": 49,
"dayan_changes_data": [],
"dayan_lines": [],
"dayan_left": 24,
"dayan_right": 25,
"dayan_hung": 0,
"dayan_left_rem": 0,
"dayan_right_rem": 0,
"dayan_removed": 0,
"dayan_pan_text": "",
"dayan_combine": "",
"dayan_show_pan": False,
"dayan_shuffle": False,
}
for key, val in defaults.items():
if key not in st.session_state:
st.session_state[key] = val
def remainder_four(n):
r = n % 4
return 4 if r == 0 else r
def random_split(stalks):
lo = max(1, stalks // 3)
hi = max(lo + 1, (stalks * 2) // 3)
left = random.randint(lo, hi)
return left, stalks - left
DAYAN_STAGE_HEIGHT = 208
DAYAN_FONT = '"Noto Serif TC", "Songti SC", "STSong", serif'
DAYAN_MONO = '"Noto Serif TC", "Courier New", monospace'
DAYAN_SCENE_CSS = f"""
* {{ box-sizing: border-box; margin: 0; padding: 0; }}
.dayan-scene {{
font-family: {DAYAN_FONT};
background:
radial-gradient(ellipse at 50% 0%, rgba(201,168,76,0.08) 0%, transparent 60%),
linear-gradient(165deg, #1a1612 0%, #221c16 50%, #181410 100%);
border: 1px solid rgba(201,168,76,0.25);
border-radius: 14px;
padding: 20px 22px;
color: #d8c8a8;
position: relative;
overflow: hidden;
}}
.dayan-scene::before {{
content: "";
position: absolute;
inset: 0;
background: url("data:image/svg+xml,%3Csvg width='40' height='40' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M0 20h40M20 0v40' stroke='%23c9a84c' stroke-width='0.3' opacity='0.04'/%3E%3C/svg%3E");
pointer-events: none;
}}
.dayan-scene .phase {{
text-align: center;
font-size: 12px;
color: #a89060;
margin-bottom: 16px;
letter-spacing: 3px;
position: relative;
}}
.dayan-scene .split-wrap {{
display: flex;
align-items: stretch;
gap: 0;
height: 88px;
position: relative;
}}
.dayan-scene .pile-side {{
flex: 1;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
border-radius: 8px;
transition: flex-grow 0.5s cubic-bezier(.4,0,.2,1);
min-width: 56px;
position: relative;
overflow: hidden;
}}
.dayan-scene .pile-side::after {{
content: "";
position: absolute;
bottom: 8px; left: 12px; right: 12px;
height: 3px;
background: repeating-linear-gradient(90deg, #8b7355 0px, #8b7355 2px, transparent 2px, transparent 5px);
opacity: 0.35;
border-radius: 2px;
}}
.dayan-scene .pile-side.left {{
background: linear-gradient(160deg, rgba(90,70,40,0.35) 0%, rgba(40,34,24,0.6) 100%);
border: 1px solid rgba(201,168,76,0.2);
margin-right: 3px;
}}
.dayan-scene .pile-side.right {{
background: linear-gradient(200deg, rgba(90,70,40,0.35) 0%, rgba(40,34,24,0.6) 100%);
border: 1px solid rgba(201,168,76,0.2);
margin-left: 3px;
}}
.dayan-scene .pile-num {{
font-size: 32px;
font-weight: 200;
color: #f0e0c0;
line-height: 1;
text-shadow: 0 0 20px rgba(201,168,76,0.3);
}}
.dayan-scene .pile-tag {{
font-size: 10px;
color: #7a6e50;
margin-top: 6px;
letter-spacing: 2px;
}}
.dayan-scene .split-divider {{
width: 1px;
background: linear-gradient(180deg, transparent 5%, #c9a84c 50%, transparent 95%);
align-self: stretch;
flex-shrink: 0;
box-shadow: 0 0 8px rgba(201,168,76,0.4);
z-index: 1;
}}
.dayan-scene .hung-chip {{
display: block;
width: fit-content;
margin: 14px auto 0;
padding: 4px 16px;
background: rgba(201,168,76,0.1);
border: 1px solid rgba(201,168,76,0.35);
border-radius: 20px;
font-size: 11px;
color: #d4b060;
letter-spacing: 2px;
}}
.dayan-scene .count-row {{
display: flex;
justify-content: center;
gap: 48px;
}}
.dayan-scene .count-item {{ text-align: center; }}
.dayan-scene .count-item .n {{
font-size: 28px;
font-weight: 200;
color: #f0e0c0;
}}
.dayan-scene .count-item .t {{
font-size: 10px;
color: #7a6e50;
letter-spacing: 2px;
margin-top: 4px;
}}
.dayan-scene .count-detail {{
text-align: center;
font-size: 11px;
color: #7a9a6a;
margin-top: 14px;
letter-spacing: 1px;
font-family: {DAYAN_MONO};
}}
.dayan-scene .total {{
text-align: center;
font-size: 11px;
color: #6a5e48;
margin-top: 14px;
letter-spacing: 2px;
}}
.dayan-scene.shuffle .pile-side {{
animation: shuffle 0.5s cubic-bezier(.4,0,.2,1);
}}
@keyframes shuffle {{
0% {{ opacity: 1; transform: translateY(0); }}
35% {{ opacity: 0.3; transform: translateY(-6px); }}
100% {{ opacity: 1; transform: translateY(0); }}
}}
"""
def yao_line_html(val):
if not val:
return '<div class="yl ghost"><span class="bar"></span></div>'
yin = val in ("6", "8")
mark = "×" if val == "6" else ("○" if val == "9" else "")
cls = "yl yin" if yin else "yl yang"
if yin:
inner = '<span class="seg"></span><span class="mid"></span><span class="seg"></span>'
else:
inner = '<span class="seg full"></span>'
m = f'<span class="mk">{mark}</span>' if mark else ""
return f'<div class="{cls}">{inner}{m}</div>'
HEX_PREVIEW_CSS = f"""
.hex-preview {{
font-family: {DAYAN_FONT};
background:
radial-gradient(ellipse at 50% 100%, rgba(201,168,76,0.06) 0%, transparent 70%),
linear-gradient(165deg, #1a1612, #201a14);
border: 1px solid rgba(201,168,76,0.22);
border-radius: 14px;
padding: 16px 18px;
color: #d8c8a8;
}}
.hex-preview .hd {{
text-align: center;
font-size: 11px;
color: #8a7850;
letter-spacing: 4px;
margin-bottom: 14px;
}}
.hex-preview .rows {{ display: flex; flex-direction: column; gap: 7px; }}
.hex-preview .row {{
display: grid;
grid-template-columns: 36px 1fr 40px;
align-items: center;
gap: 8px;
}}
.hex-preview .pos {{
font-size: 10px;
color: #5a5040;
text-align: right;
}}
.hex-preview .lbl {{
font-size: 10px;
color: #9a8456;
text-align: left;
}}
.hex-preview .yl {{
display: flex;
align-items: center;
height: 10px;
position: relative;
}}
.hex-preview .yl .seg {{
height: 3px;
background: #c9a84c;
border-radius: 1px;
flex: 1;
box-shadow: 0 0 6px rgba(201,168,76,0.25);
}}
.hex-preview .yl .seg.full {{ flex: 1; }}
.hex-preview .yl .mid {{ width: 14px; flex-shrink: 0; }}
.hex-preview .yl.ghost .bar {{
width: 100%; height: 1px;
background: rgba(201,168,76,0.12);
}}
.hex-preview .yl .mk {{
position: absolute;
right: -18px;
font-size: 9px;
color: #d4a060;
}}
.hex-preview .names {{
text-align: center;
margin-top: 14px;
padding-top: 12px;
border-top: 1px solid rgba(201,168,76,0.12);
font-size: 13px;
color: #d4b060;
letter-spacing: 1px;
}}
.hex-preview .dots {{
display: flex;
justify-content: center;
gap: 6px;
margin-top: 12px;
}}
.hex-preview .dot {{
width: 6px; height: 6px;
border-radius: 50%;
background: rgba(201,168,76,0.15);
border: 1px solid rgba(201,168,76,0.2);
}}
.hex-preview .dot.done {{
background: #c9a84c;
box-shadow: 0 0 6px rgba(201,168,76,0.5);
}}
.hex-preview .dot.cur {{
background: transparent;
border-color: #d4b060;
box-shadow: 0 0 8px rgba(212,176,96,0.4);
}}
"""
PROGRESS_PANEL_CSS = f"""
.prog-panel {{
font-family: {DAYAN_FONT};
background: linear-gradient(165deg, #1a1612, #201a14);
border: 1px solid rgba(201,168,76,0.22);
border-radius: 14px;
padding: 18px 20px;
color: #d8c8a8;
height: 100%;
}}
.prog-panel .title {{
font-size: 15px;
color: #d4b060;
letter-spacing: 6px;
margin-bottom: 16px;
}}
.prog-panel .stats {{
display: flex;
gap: 12px;
margin-bottom: 18px;
}}
.prog-panel .stat {{
flex: 1;
text-align: center;
padding: 10px 6px;
background: rgba(201,168,76,0.06);
border: 1px solid rgba(201,168,76,0.15);
border-radius: 8px;
}}
.prog-panel .stat .v {{
font-size: 20px;
font-weight: 300;
color: #f0e0c0;
}}
.prog-panel .stat .l {{
font-size: 10px;
color: #7a6e50;
margin-top: 4px;
letter-spacing: 1px;
}}
.prog-panel .pipeline {{
display: flex;
align-items: center;
gap: 0;
margin-top: 4px;
}}
.prog-panel .pipe-step {{
flex: 1;
text-align: center;
font-size: 10px;
color: #5a5040;
letter-spacing: 1px;
padding: 6px 2px;
position: relative;
}}
.prog-panel .pipe-step.active {{
color: #d4b060;
}}
.prog-panel .pipe-step.done {{
color: #8a9a6a;
}}
.prog-panel .pipe-step::after {{
content: "";
position: absolute;
bottom: 0; left: 20%; right: 20%;
height: 2px;
background: rgba(201,168,76,0.1);
border-radius: 1px;
}}
.prog-panel .pipe-step.active::after {{
background: linear-gradient(90deg, transparent, #c9a84c, transparent);
box-shadow: 0 0 6px rgba(201,168,76,0.4);
}}
.prog-panel .pipe-step.done::after {{
background: rgba(201,168,76,0.3);
}}
.prog-panel .quote {{
margin-top: 16px;
font-size: 11px;
color: #5a5040;
line-height: 1.7;
border-left: 2px solid rgba(201,168,76,0.2);
padding-left: 10px;
}}
.prog-panel .result {{
font-size: 22px;
font-weight: 300;
color: #f0e0c0;
letter-spacing: 3px;
margin-bottom: 6px;
}}
.prog-panel .result-sub {{
font-size: 12px;
color: #9a8456;
}}
"""
def render_progress_panel(phase, yao, change, step, lines, combine=""):
step_order = ["divide", "hang_one", "count_four", "change_done", "yao_done"]
step_names = ["分堆", "掛一", "揲四", "歸奇", "成爻"]
cur_idx = step_order.index(step) if step in step_order else 0
pipe = ""
for i, name in enumerate(step_names):
if phase != "active":
cls = ""
elif i < cur_idx:
cls = "done"
elif i == cur_idx:
cls = "active"
else:
cls = ""
pipe += f'<div class="pipe-step {cls}">{name}</div>'
if phase == "idle":
body = f"""
<div class="stats">
<div class="stat"><div class="v">49</div><div class="l">蓍草</div></div>
<div class="stat"><div class="v">0</div><div class="l">成爻</div></div>
</div>
<div class="quote">大衍之數五十,其用四十有九。</div>
"""
height = 195
elif phase == "active":
body = f"""
<div class="stats">
<div class="stat"><div class="v">{yao}</div><div class="l">爻 / 6</div></div>
<div class="stat"><div class="v">{change}</div><div class="l">變 / 3</div></div>
<div class="stat"><div class="v">{len(lines)}</div><div class="l">已成</div></div>
</div>
<div class="pipeline">{pipe}</div>
"""
height = 210
else:
ben, zhi = "", ""
if combine:
d = ichingshifa.Iching().mget_bookgua_details(combine)
ben, zhi = d[1], d[2]
body = f"""
<div class="result">{combine}</div>
<div class="result-sub">{ben} → {zhi}</div>
"""
height = 160
html = f"""
<style>{PROGRESS_PANEL_CSS}</style>
<div class="prog-panel">
<div class="title">大衍筮法</div>
{body}
</div>
"""
components.html(html, height=height, scrolling=False)
def render_result_card(title, subtitle="", variant="default"):
colors = {
"default": ("#d4b060", "rgba(201,168,76,0.08)"),
"success": ("#8aba7a", "rgba(120,180,100,0.08)"),
}
color, bg = colors.get(variant, colors["default"])
html = f"""
<style>
.rcard-wrap {{
font-family: {DAYAN_FONT};
height: 100%;
display: flex;
align-items: center;
justify-content: center;
background:
radial-gradient(ellipse at 50% 0%, rgba(201,168,76,0.06) 0%, transparent 60%),
linear-gradient(165deg, #1a1612, #201a14);
border: 1px solid rgba(201,168,76,0.22);
border-radius: 14px;
}}
.rcard {{
text-align: center;
padding: 20px;
background: {bg};
border: 1px solid rgba(201,168,76,0.18);
border-radius: 10px;
min-width: 60%;
}}
.rcard .t {{ font-size: 15px; color: {color}; letter-spacing: 2px; }}
.rcard .s {{ font-size: 12px; color: #6a5e48; margin-top: 8px; letter-spacing: 1px; }}
</style>
<div class="rcard-wrap">
<div class="rcard">
<div class="t">{title}</div>
{"<div class='s'>" + subtitle + "</div>" if subtitle else ""}
</div>
</div>
"""
components.html(html, height=DAYAN_STAGE_HEIGHT, scrolling=False)
def render_completion_stage(combine):
ben, zhi = "", ""
if combine:
d = ichingshifa.Iching().mget_bookgua_details(combine)
ben, zhi = d[1], d[2]
html = f"""
<style>
.done-wrap {{
font-family: {DAYAN_FONT};
height: 100%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
background:
radial-gradient(ellipse at 50% 30%, rgba(201,168,76,0.1) 0%, transparent 70%),
linear-gradient(165deg, #1a1612, #201a14);
border: 1px solid rgba(201,168,76,0.22);
border-radius: 14px;
color: #d8c8a8;
}}
.done-wrap .code {{
font-size: 26px;
font-weight: 200;
color: #f0e0c0;
letter-spacing: 6px;
}}
.done-wrap .name {{
font-size: 13px;
color: #9a8456;
margin-top: 10px;
letter-spacing: 2px;
}}
</style>
<div class="done-wrap">
<div class="code">{combine}</div>
<div class="name">{ben} → {zhi}</div>
</div>
"""
components.html(html, height=DAYAN_STAGE_HEIGHT, scrolling=False)
def render_divide_scene(left, right, total, shuffle=False):
lp = max(left / total * 100, 8)
rp = max(right / total * 100, 8)
shuffle_cls = "shuffle" if shuffle else ""
html = f"""
<style>{DAYAN_SCENE_CSS}</style>
<div class="dayan-scene {shuffle_cls}">
<div class="phase">分而為二 · 共 {total} 策</div>
<div class="split-wrap">
<div class="pile-side left" style="flex-grow:{lp}">
<div class="pile-num">{left}</div>
<div class="pile-tag">左堆</div>
</div>
<div class="split-divider"></div>
<div class="pile-side right" style="flex-grow:{rp}">
<div class="pile-num">{right}</div>
<div class="pile-tag">右堆</div>
</div>
</div>
<div class="total">分而為二以象兩</div>
</div>
"""
components.html(html, height=DAYAN_STAGE_HEIGHT, scrolling=False)
def render_yarrow_scene(left, right, hung=0, phase_label="", mode="default"):
hung_html = (
f'<div style="text-align:center"><span class="hung-chip">掛一 · {hung}</span></div>'
if hung else ""
)
if mode == "count":
lg, lr = left // 4, right // 4
lrem, rrem = remainder_four(left), remainder_four(right)
detail = f"左 {left} → {lg}×4+{lrem} · 右 {right} → {lr}×4+{rrem}"
body = f"""
<div class="count-row">
<div class="count-item"><div class="n">{left}</div><div class="t">左堆</div></div>
<div class="count-item"><div class="n">{right}</div><div class="t">右堆</div></div>
</div>
<div class="count-detail">{detail}</div>
{hung_html}
"""
else:
body = f"""
<div class="count-row">
<div class="count-item"><div class="n">{left}</div><div class="t">左堆</div></div>
<div class="count-item"><div class="n">{right}</div><div class="t">右堆</div></div>
</div>
{hung_html}
<div class="total">合計 {left + right + hung} 策</div>
"""
html = f"""
<style>{DAYAN_SCENE_CSS}</style>
<div class="dayan-scene">
<div class="phase">{phase_label}</div>
{body}
</div>
"""
components.html(html, height=DAYAN_STAGE_HEIGHT, scrolling=False)
def render_hexagram_preview(lines, title="卦象"):
"""lines: list of '6'/'7'/'8'/'9' from bottom to top."""
padded = list(lines) + [""] * (6 - len(lines))
zhi_gua = "".join(
v.replace("6", "7").replace("9", "8") for v in lines
) if lines else ""
ben_name = ""
zhi_name = ""
if len(lines) == 6:
details = ichingshifa.Iching().mget_bookgua_details("".join(lines))
ben_name = details[1] if details else ""
zhi_name = details[2] if details else ""
rows = ""
for i in range(5, -1, -1):
val = padded[i]
rows += (
f'<div class="row">'
f'<span class="pos">{YAO_POSITIONS[i]}</span>'
f'{yao_line_html(val)}'
f'<span class="lbl">{YAO_LABELS.get(val, "")}</span>'
f'</div>'
)
dots = ""
for i in range(6):
if i < len(lines):
cls = "dot done"
elif i == len(lines) and lines:
cls = "dot cur"
else:
cls = "dot"
dots += f'<span class="{cls}"></span>'
name_line = ""
if ben_name:
name_line = ben_name
if zhi_name and zhi_gua != "".join(lines):
name_line += f" → {zhi_name}"
html = f"""
<style>{HEX_PREVIEW_CSS}</style>
<div class="hex-preview">
<div class="hd">{title}</div>
<div class="rows">{rows}</div>
<div class="dots">{dots}</div>
{"<div class='names'>" + name_line + "</div>" if name_line else ""}
</div>
"""
h = 280 if ben_name else 250
components.html(html, height=h, scrolling=False)
def reset_dayan():
st.session_state.dayan_phase = "idle"
st.session_state.dayan_yao = 0
st.session_state.dayan_change = 0
st.session_state.dayan_step = "ready"
st.session_state.dayan_stalks = 49
st.session_state.dayan_changes_data = []
st.session_state.dayan_lines = []
st.session_state.dayan_left = 24
st.session_state.dayan_right = 25
st.session_state.dayan_hung = 0
st.session_state.dayan_pan_text = ""
st.session_state.dayan_combine = ""
st.session_state.dayan_show_pan = False
st.session_state.dayan_shuffle = False
def start_yao(yao_num):
st.session_state.dayan_phase = "active"
st.session_state.dayan_yao = yao_num
st.session_state.dayan_change = 1
st.session_state.dayan_step = "divide"
st.session_state.dayan_stalks = 49
st.session_state.dayan_changes_data = []
left, right = random_split(49)
st.session_state.dayan_left = left
st.session_state.dayan_right = right
st.session_state.dayan_hung = 0
st.session_state.dayan_shuffle = True
def apply_divide(left_count):
total = st.session_state.dayan_stalks
left_count = max(1, min(total - 1, left_count))
st.session_state.dayan_left = left_count
st.session_state.dayan_right = total - left_count
st.session_state.dayan_step = "hang_one"
def apply_hang_one():
if st.session_state.dayan_right < 1:
return
st.session_state.dayan_hung = 1
st.session_state.dayan_right -= 1
st.session_state.dayan_step = "count_four"
def apply_count_four():
left = st.session_state.dayan_left
right = st.session_state.dayan_right
left_rem = remainder_four(left)
right_rem = remainder_four(right)
removed = left_rem + right_rem + st.session_state.dayan_hung
st.session_state.dayan_left_rem = left_rem
st.session_state.dayan_right_rem = right_rem
st.session_state.dayan_removed = removed
st.session_state.dayan_changes_data.append({
"change": st.session_state.dayan_change,
"left": left,
"right": right,
"hung": st.session_state.dayan_hung,
"left_rem": left_rem,
"right_rem": right_rem,
"removed": removed,
})
st.session_state.dayan_step = "change_done"
def advance_after_change():
if st.session_state.dayan_change < 3:
removed_so_far = sum(c["removed"] for c in st.session_state.dayan_changes_data)
st.session_state.dayan_stalks = 49 - removed_so_far
st.session_state.dayan_change += 1
st.session_state.dayan_step = "divide"
left, right = random_split(st.session_state.dayan_stalks)
st.session_state.dayan_left = left
st.session_state.dayan_right = right
st.session_state.dayan_hung = 0
st.session_state.dayan_shuffle = True
else:
total_removed = sum(c["removed"] for c in st.session_state.dayan_changes_data)
remaining = 49 - total_removed
yao_val = str(remaining // 4)
st.session_state.dayan_lines.append(yao_val)
st.session_state.dayan_step = "yao_done"
if len(st.session_state.dayan_lines) >= 6:
st.session_state.dayan_phase = "completed"
st.session_state.dayan_combine = "".join(st.session_state.dayan_lines)
def _render_dayan_stage(phase, step, yao, change, lines, combine, stalks):
"""固定高度內容區,避免按鈕隨步驟跳動。"""
if phase == "idle":
render_divide_scene(24, 25, 49)
elif phase == "active":
if step == "divide":
render_divide_scene(
st.session_state.dayan_left,
st.session_state.dayan_right,
stalks,
shuffle=st.session_state.dayan_shuffle,
)
st.session_state.dayan_shuffle = False
elif step == "hang_one":
render_yarrow_scene(
st.session_state.dayan_left,
st.session_state.dayan_right,
0,
f"第{yao}爻 · 第{change}變 · 掛一以象三",
)
elif step == "count_four":
render_yarrow_scene(
st.session_state.dayan_left,
st.session_state.dayan_right,
st.session_state.dayan_hung,
f"第{yao}爻 · 第{change}變 · 揲之以四",
mode="count",
)
elif step == "change_done":
last = st.session_state.dayan_changes_data[-1]
render_result_card(
f"第 {change} 變 歸奇 {last['removed']} 策",
f"{last['left_rem']} + {last['right_rem']} + {last['hung']}",
)
elif step == "yao_done":
yao_val = lines[-1]
render_result_card(
f"第 {yao} 爻 {YAO_LABELS[yao_val]}",
YAO_SYMBOLS[yao_val].strip(),
variant="success",
)
elif phase == "completed":
render_completion_stage(combine)
def _render_dayan_action(phase, step, yao, change, lines, combine):
"""固定位置操作列。"""
if phase == "idle":
if st.button("開始起卦", type="primary", use_container_width=True):
start_yao(1)
st.rerun()
elif phase == "active":
if step == "divide":
if st.button("分堆", type="primary", use_container_width=True):
apply_divide(st.session_state.dayan_left)
st.rerun()
elif step == "hang_one":
if st.button("掛一", type="primary", use_container_width=True):
apply_hang_one()
st.rerun()
elif step == "count_four":
if st.button("揲四", type="primary", use_container_width=True):
apply_count_four()
st.rerun()
elif step == "change_done":
label = f"第 {change + 1} 變" if change < 3 else "成爻"
if st.button(label, type="primary", use_container_width=True):
advance_after_change()
st.rerun()
elif step == "yao_done" and yao < 6:
if st.button(f"第 {yao + 1} 爻", type="primary", use_container_width=True):
start_yao(yao + 1)
st.rerun()
elif phase == "completed":
c1, c2 = st.columns(2)
with c1:
if st.button("生成排盤", type="primary", use_container_width=True):
st.session_state.dayan_show_pan = True
st.session_state.classic_combine = combine
st.session_state.classic_mode = "dayan_manual"
st.rerun()
with c2:
if st.button("重新起卦", use_container_width=True):
reset_dayan()
st.rerun()
def render_dayan_tab():
init_dayan_state()