AimanGh commited on
Commit
fd807ef
·
1 Parent(s): 17dc1f1

new pages

Browse files
.DS_Store CHANGED
Binary files a/.DS_Store and b/.DS_Store differ
 
.gitignore CHANGED
@@ -3,4 +3,6 @@ upload_csv.py
3
  data
4
  secrets.toml
5
  .streamlit/secrets.toml
6
- 3_🕸️_Character_Network copy.py
 
 
 
3
  data
4
  secrets.toml
5
  .streamlit/secrets.toml
6
+
7
+ 1_🕸️_Character_Network(汉字网络) copy.py
8
+ 5_🎮_Playground.py
__pycache__/db.cpython-312.pyc ADDED
Binary file (1.04 kB). View file
 
__pycache__/utils.cpython-312.pyc ADDED
Binary file (1.98 kB). View file
 
__pycache__/utils.cpython-313.pyc CHANGED
Binary files a/__pycache__/utils.cpython-313.pyc and b/__pycache__/utils.cpython-313.pyc differ
 
i18n/__pycache__/tone_patterns.cpython-313.pyc ADDED
Binary file (13.4 kB). View file
 
i18n/__pycache__/verb_action_coach.cpython-313.pyc ADDED
Binary file (8.57 kB). View file
 
i18n/tone_patterns.py ADDED
@@ -0,0 +1,261 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ TRANSLATIONS = {
2
+ 'en': {
3
+ 'page_title': "Tone Explorer",
4
+ 'load_error': "Data could not be loaded. Please ensure the data file is available.",
5
+ 'settings_header': "⚙️ Settings",
6
+ 'language_select': "Select Language",
7
+ 'controls_header': "🔍 Filters",
8
+ 'filter_by_tonepair': "Tone Pair (src→dst)",
9
+ 'filter_src_tone': "Source Tone",
10
+ 'filter_dst_tone': "Destination Tone",
11
+ 'filter_class': "Classification",
12
+ 'legend_header': "Tone Legend",
13
+ 'tab_network': "🌐 Tone Network",
14
+ 'tab_pathways': "🧭 Tone Pathways",
15
+ 'tab_families': "🗂️ Tone in Families",
16
+ 'tab_minpairs': "🧪 Minimal Tone-Contrast Sets",
17
+ 'tab_charprof': "👤 Character Tone Profiles",
18
+ 'tab_curriculum': "📚 Curriculum Builder",
19
+ 'no_match_warning': "No data to display for the current selection.",
20
+ 'generating_network': "Generating network graph...",
21
+ 'fade_unselected': "Fade unselected tones (instead of hiding)",
22
+ 'network_desc': """
23
+ Explore the character network through tone patterns.
24
+ - **Nodes:** Characters (size by degree).
25
+ - **Edges:** Verbs (A→B means 'AB'), **colored by tone pair (src→dst)**, thickness by frequency.
26
+ Use the filters to focus on specific tone transitions.
27
+ """,
28
+ 'path_target_pair': "Target Tone Pair",
29
+ 'path_start_char': "Start Character",
30
+ 'path_len': "Path length",
31
+ 'path_make': "Make Path",
32
+ 'path_desc': "Build a short learning route that prefers edges matching the chosen tone pair.",
33
+ 'verbs_on_path': "Verbs on this Path",
34
+ 'download_csv': "Download CSV",
35
+ 'families_header': "Word Family Explorer (with tone)",
36
+ 'families_desc': "Select a community to inspect its tone distribution. Edges are colored by tone pair.",
37
+ 'family_select': "Select a Family",
38
+ 'family_members': "Family Members",
39
+ 'tone_distribution': "Tone-Pair Distribution (this family)",
40
+ 'minpairs_header': "Minimal Tone-Contrast Sets",
41
+ 'minpairs_desc': "Find sets where **letters are the same** (pinyin without tone digits), but **tones differ**.",
42
+ 'minpairs_contrast': "Contrast focus",
43
+ 'contrast_any': "Any tone difference",
44
+ 'contrast_src': "Different source tone (first syllable)",
45
+ 'contrast_dst': "Different destination tone (second syllable)",
46
+ 'minpairs_make': "Find Minimal Pairs",
47
+ 'charprof_select': "Select Character",
48
+ 'charprof_desc': "Tone distribution for this character and all its verbs.",
49
+ 'src_count': "As first char",
50
+ 'dst_count': "As second char",
51
+ 'tone_profile': "Tone Profile",
52
+ 'quick_show': "Quick filters",
53
+ 'show_src_to_any': "Show X→* verbs",
54
+ 'show_any_to_dst': "Show *→X verbs",
55
+ 'curriculum_desc': "Build a tone-focused deck from the current filters.",
56
+ 'deck_size': "Deck size",
57
+ 'deck_pairs': "Select tone pairs to include",
58
+ 'weighting': "Selection weighting",
59
+ 'weight_degree': "Favor high-degree characters",
60
+ 'weight_uniform': "Uniform",
61
+ 'make_deck': "Build Deck",
62
+ 'deck_table': "Deck Preview",
63
+
64
+ # NEW: Help expanders (titles + content)
65
+ 'help_network_title': "What is this? How to use it",
66
+ 'help_network_body': """
67
+ **This tab shows the whole character graph through tone.**
68
+ - Use the **Filters** on the left to narrow by **tone pair**, **source/destination tone**, and **classification**.
69
+ - **Node size** reflects how many connections a character has (degree).
70
+ - **Edge color** = tone pair; **thickness** ≈ frequency.
71
+ - **Fade unselected tones** to keep context while focusing your target.
72
+ **How to use:**
73
+ 1) Start broad, then filter to one or two tone pairs (e.g., **3→4**).
74
+ 2) Hover edges to see **verb · pinyin · English**.
75
+ 3) Screenshot a subgraph for class slides, or note high-degree nodes for practice.
76
+ **Tip:** Use the network to pick 1–3 **“hub” characters** to study deeply before drills.
77
+ """,
78
+
79
+ 'help_pathways_title': "What is this? How to use it",
80
+ 'help_pathways_body': """
81
+ **This tab builds a short learning route through the graph** that prefers your chosen **tone pair**.
82
+ - Choose a **Target Tone Pair**, a **Start Character**, and a **Path length**.
83
+ - We score edges that match the target tone pair higher and prefer well-connected next steps.
84
+ **How to use:**
85
+ 1) Pick a **start** you already know.
86
+ 2) Choose a **tone pair** you want to train.
87
+ 3) Generate a route → study the **verbs on the path**; export as CSV for spaced practice.
88
+ **Tip:** If the path is short, try another start character or relax filters.
89
+ """,
90
+
91
+ 'help_families_title': "What is this? How to use it",
92
+ 'help_families_body': """
93
+ **Communities (“families”) are clusters of characters that interconnect densely.**
94
+ - Select a **family** to see its **tone-pair distribution** and an **intra-family graph**.
95
+ **How to use:**
96
+ 1) Pick a family, skim the **top tone pairs** in the bar chart.
97
+ 2) Explore the mini network; hover edges for examples.
98
+ 3) Use this to build a **coherent practice set** within one semantic/morphological neighborhood.
99
+ """,
100
+
101
+ 'help_minpairs_title': "What is this? How to use it",
102
+ 'help_minpairs_body': """
103
+ **Minimal tone-contrast sets** share the same **pinyin letters** (digits removed) but have **different tones**.
104
+ - Choose a contrast focus (any difference / different source tone / different destination tone).
105
+ **How to use:**
106
+ 1) Generate pairs → use them for **listening** or **production** drills.
107
+ 2) Export CSV for a quick in-class worksheet.
108
+ **Tip:** Great for spotlighting **2 vs 3** and **third-tone sandhi** contexts.
109
+ """,
110
+
111
+ 'help_charprof_title': "What is this? How to use it",
112
+ 'help_charprof_body': """
113
+ **Character tone profile** shows how one character appears across tones and which verbs it forms.
114
+ - Bar chart = how often this char carries each tone (as first/second).
115
+ - Tables list all verbs when it’s **first** (A→•) or **second** (•→B).
116
+ **How to use:**
117
+ 1) Pick a character you’re learning.
118
+ 2) Review its common partners and tones.
119
+ 3) Use **Quick filters** to focus e.g. **3→*** or ***→4** sets for targeted practice.
120
+ """,
121
+
122
+ 'help_curriculum_title': "What is this? How to use it",
123
+ 'help_curriculum_body': """
124
+ **Build a tone-focused deck** from your current filters.
125
+ - Choose tone pairs and **deck size**; pick weighting (**Uniform** or **Favor high-degree characters**).
126
+ **How to use:**
127
+ 1) Set filters on the left (topic/tones).
128
+ 2) Generate a deck and **export CSV** (Anki-friendly).
129
+ **Tip:** Favoring high-degree nodes gives broad coverage quickly; Uniform keeps variety.
130
+ """,
131
+ },
132
+
133
+ 'zh': {
134
+ 'page_title': "声调探索",
135
+ 'load_error': "无法加载数据。请确保数据文件可用。",
136
+ 'settings_header': "⚙️ 设置",
137
+ 'language_select': "选择语言",
138
+ 'controls_header': "🔍 筛选",
139
+ 'filter_by_tonepair': "声调模式(首→尾)",
140
+ 'filter_src_tone': "首字声调",
141
+ 'filter_dst_tone': "尾字声调",
142
+ 'filter_class': "动词类别",
143
+ 'legend_header': "声调图例",
144
+ 'tab_network': "🌐 声调网络图",
145
+ 'tab_pathways': "🧭 学习路径",
146
+ 'tab_families': "🗂️ 词族中的声调",
147
+ 'tab_minpairs': "🧪 最小对立组",
148
+ 'tab_charprof': "👤 汉字声调画像",
149
+ 'tab_curriculum': "📚 课程生成器",
150
+ 'no_match_warning': "没有符合当前筛选条件的数据。",
151
+ 'generating_network': "正在生成网络图...",
152
+ 'fade_unselected': "将未选声调淡化显示(不隐藏)",
153
+ 'network_desc': """
154
+ 从声调视角探索汉字网络。
155
+ - **节点:** 汉字(大小=度数)。
156
+ - **边:** 动词(A→B 表示“AB”),**按声调模式着色**,粗细与出现频次相关。
157
+ 使用筛选器来聚焦某些声调转移。
158
+ """,
159
+ 'path_target_pair': "目标声调模式",
160
+ 'path_start_char': "起始汉字",
161
+ 'path_len': "路径长度",
162
+ 'path_make': "生成路径",
163
+ 'path_desc': "优先经过所选声调模式的边,构成一条短学习路线。",
164
+ 'verbs_on_path': "路径上的动词",
165
+ 'download_csv': "下载 CSV",
166
+ 'families_header': "词族浏览(含声调)",
167
+ 'families_desc': "选择一个社群,查看其声调分布。边按声调模式着色。",
168
+ 'family_select': "选择词族",
169
+ 'family_members': "词族成员",
170
+ 'tone_distribution': "该词族的声调分布",
171
+ 'minpairs_header': "最小对立组",
172
+ 'minpairs_desc': "查找 **字母相同**(拼音去掉声调数字),但**声调不同**的词组。",
173
+ 'minpairs_contrast': "对比焦点",
174
+ 'contrast_any': "任意声调差异",
175
+ 'contrast_src': "首字声调不同",
176
+ 'contrast_dst': "尾字声调不同",
177
+ 'minpairs_make': "查找对立组",
178
+ 'charprof_select': "选择汉字",
179
+ 'charprof_desc': "该汉字的声调分布及其所有相关动词。",
180
+ 'src_count': "作首字次数",
181
+ 'dst_count': "作尾字次数",
182
+ 'tone_profile': "声调画像",
183
+ 'quick_show': "快速筛选",
184
+ 'show_src_to_any': "显示 X→* 动词",
185
+ 'show_any_to_dst': "显示 *→X 动词",
186
+ 'curriculum_desc': "基于当前筛选构建声调训练清单。",
187
+ 'deck_size': "清单大小",
188
+ 'deck_pairs': "选择包含的声调模式",
189
+ 'weighting': "选择权重",
190
+ 'weight_degree': "倾向高连接度汉字",
191
+ 'weight_uniform': "均匀",
192
+ 'make_deck': "生成清单",
193
+ 'deck_table': "预览清单",
194
+
195
+ # NEW: Help expanders (titles + content)
196
+ 'help_network_title': "这是做什么的?如何使用",
197
+ 'help_network_body': """
198
+ **本页以“声调”为视角展示整张汉字网络。**
199
+ - 左侧 **筛选** 可按 **声调模式**、**首/尾字声调**、**类别** 精准聚焦。
200
+ - **节点大小** 代表连接多少(度数);**边颜色** 表示声调模式;**粗细** 约等于频次。
201
+ - 选择“**淡化未选声调**”可在保留全貌的同时突出重点。
202
+ **使用建议:**
203
+ 1)先整体浏览,再缩小到 1–2 个重点声调(如 **3→4**)。
204
+ 2)将鼠标悬停查看 **动词·拼音·释义**。
205
+ 3)记录几个 **高连接度** 的汉字,作为后续练习的“枢纽”。
206
+ """,
207
+
208
+ 'help_pathways_title': "这是做什么的?如何使用",
209
+ 'help_pathways_body': """
210
+ **本页根据你的“目标声调模式”生成一条短学习路径。**
211
+ - 选择 **目标声调**、**起始汉字** 和 **路径长度**。
212
+ - 算法优先经过匹配该声调模式的边,并倾向连接度更高的下一步。
213
+ **使用建议:**
214
+ 1)挑选你熟悉的起始字;
215
+ 2)选择想训练的声调模式;
216
+ 3)生成路径 → 学习路径中的动词,并导出 CSV 复习。
217
+ 提示:路径过短可更换起点或放宽筛选。
218
+ """,
219
+
220
+ 'help_families_title': "这是做什么的?如何使用",
221
+ 'help_families_body': """
222
+ **“词族/社群”是网络里彼此紧密相连的汉字群。**
223
+ - 选择一个词族查看其 **声调分布** 和 **内部网络图**。
224
+ **使用建议:**
225
+ 1)先看柱状图里最常见的声调模式;
226
+ 2)在小网络中悬停查看例词;
227
+ 3)据此在同一语义/构词邻域内,构建一组连贯的练习清单。
228
+ """,
229
+
230
+ 'help_minpairs_title': "这是做什么的?如何使用",
231
+ 'help_minpairs_body': """
232
+ **“最小对立”** 指 **拼音字母相同**(去掉声调数字),但 **声调不同** 的词组。
233
+ - 选择对比焦点(任意差异/首字不同/尾字不同)。
234
+ **使用建议:**
235
+ 1)生成对立组 → 做 **听辨** 或 **跟读** 训练;
236
+ 2)导出 CSV 制作课堂练习。
237
+ 提示:特别适合练 **二声 vs 三声** 及 **三声变调** 场景。
238
+ """,
239
+
240
+ 'help_charprof_title': "这是做什么的?如何使用",
241
+ 'help_charprof_body': """
242
+ **“汉字声调画像”** 展示某个汉字在不同声调下的出现频次及其常见搭配。
243
+ - 柱状图显示该字各声调的出现次数;
244
+ - 下方表格列出其作为 **首字** 与 **尾字** 的全部动词。
245
+ **使用建议:**
246
+ 1)选择你在学的汉字;
247
+ 2)查看常见搭配与声调;
248
+ 3)用“快速筛选”生成如 **3→*** 或 ***→4** 的针对性练习集。
249
+ """,
250
+
251
+ 'help_curriculum_title': "这是做什么的?如何使用",
252
+ 'help_curriculum_body': """
253
+ **从当前筛选构建一套“声调训练清单”。**
254
+ - 选择声调模式与 **清单大小**,并设定权重(**倾向高连接度** / **均匀**)。
255
+ **使用建议:**
256
+ 1)先在左侧设定主题/声调;
257
+ 2)生成清单并 **导出 CSV**(兼容 Anki)。
258
+ 提示:倾向高连接度 → 覆盖面更广;均匀 → 多样性更好。
259
+ """,
260
+ }
261
+ }
i18n/verb_action_coach.py ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ TRANSLATIONS = {
3
+ "en": {
4
+ "title": "Verb Action Coach",
5
+ "load_error": "Data could not be loaded. Please ensure the data file is available.",
6
+ "settings": "⚙️ Settings",
7
+ "lang": "Select Language",
8
+ "tab_overview": "📊 Overview",
9
+ "tab_heatmap": "🗺️ Tone Heatmap",
10
+ "tab_coverage": "🎯 Coverage Optimizer",
11
+ "tab_deck": "🗂️ Deck Builder",
12
+ "tab_pitfalls": "🚩 Polyphony & Pitfalls",
13
+
14
+ # OVERVIEW
15
+ "ov_help_title": "What is this? How to use it",
16
+ "ov_help_body": """
17
+ **Overview** summarizes the dataset to guide lesson planning.
18
+
19
+ - **Category distribution** shows which verb categories dominate.
20
+ - **Phonetic breakdown** reveals common initials/finals for 1st vs 2nd characters.
21
+
22
+ **How to use**
23
+ 1) Pick 1–2 categories to focus on this week.
24
+ 2) Note the frequent initials/finals and plan pronunciation drills to match.
25
+ """,
26
+ "cat_dist": "Verb Category Distribution",
27
+ "cat_desc": "Counts of verbs in each functional category.",
28
+ "category": "Category",
29
+ "verb_count": "Number of Verbs",
30
+ "phon_header": "Phonetic Component Analysis (Initials & Finals)",
31
+ "phon_desc": "Most frequent initials (声母) and finals (韵母) for the first and second characters.",
32
+ "initial_1": "First Character — Initial",
33
+ "final_1": "First Character — Final",
34
+ "initial_2": "Second Character — Initial",
35
+ "final_2": "Second Character — Final",
36
+ "frequency": "Frequency",
37
+ "component": "Phonetic Component",
38
+
39
+ # HEATMAP
40
+ "hm_help_title": "What is this? How to use it",
41
+ "hm_help_body": """
42
+ **Tone Heatmap** shows source→destination tone transitions (1–5) as a 5×5 matrix.
43
+
44
+ **How to use**
45
+ 1) Select **All** or a specific category to inspect.
46
+ 2) Identify the **dominant tone pair(s)** (e.g., 3→4).
47
+ 3) Design drills around those transitions and collect examples from the dataset.
48
+ """,
49
+ "hm_header": "Tone-Pair Heatmap by Category",
50
+ "hm_cat": "Category",
51
+ "hm_all": "All",
52
+
53
+ # COVERAGE
54
+ "cov_help_title": "What is this? How to use it",
55
+ "cov_help_body": """
56
+ **Coverage Optimizer** picks a small set of characters that covers the most verbs (greedy set cover).
57
+
58
+ **How to use**
59
+ 1) Choose **how many characters** you can teach soon.
60
+ 2) The optimizer lists the **best characters** and shows **coverage%** of verbs.
61
+ 3) Use the covered verbs table as a quick teaching deck.
62
+ """,
63
+ "cov_header": "Coverage Optimizer",
64
+ "cov_caption": "Pick a small set of characters that covers the most verbs.",
65
+ "cov_how_many": "How many characters?",
66
+ "cov_selected": "Selected chars",
67
+ "cov_list_prefix": "Selected:",
68
+ "cov_coverage": "Coverage",
69
+ "cov_verbs_covered": "Verbs covered",
70
+ "cov_download": "Download covered verbs (CSV)",
71
+
72
+ # DECK
73
+ "deck_help_title": "What is this? How to use it",
74
+ "deck_help_body": """
75
+ **Deck Builder** turns filters (tone pairs, initials/finals) into a study deck.
76
+
77
+ **How to use**
78
+ 1) Choose **tone pairs** and (optionally) **phonetic components**.
79
+ 2) Set **deck size** and generate.
80
+ 3) Export to CSV for Anki or handouts.
81
+ """,
82
+ "deck_header": "Pronunciation / Deck Builder",
83
+ "deck_tone_pairs": "Tone pairs",
84
+ "deck_position": "Position",
85
+ "deck_any": "Any",
86
+ "deck_first_init": "1st: initial",
87
+ "deck_first_final": "1st: final",
88
+ "deck_second_init": "2nd: initial",
89
+ "deck_second_final": "2nd: final",
90
+ "deck_components": "Components",
91
+ "deck_size": "Deck size",
92
+ "deck_no_items": "No items under current filters.",
93
+ "deck_download": "Download deck (CSV)",
94
+
95
+ # PITFALLS
96
+ "pit_help_title": "What is this? How to use it",
97
+ "pit_help_body": """
98
+ **Polyphony & Pitfalls** surfaces characters with many tone roles and 3→3 items (sandhi talking points).
99
+
100
+ **How to use**
101
+ 1) Pre-teach the **polyphonic** characters (many tone roles).
102
+ 2) Show learners the **3→3** list and remind them of third-tone sandhi (speak as 2+3).
103
+ """,
104
+ "pit_header": "Polyphony & Pitfalls",
105
+ "pit_poly_caption": "Characters with many tone roles (watch for confusion)",
106
+ "pit_sandhi_caption": "3→3 (underlying) — remember 2+3 in speech",
107
+ "no_data": "No data available."
108
+ },
109
+
110
+ "zh": {
111
+ "title": "动词教学助理",
112
+ "load_error": "无法加载数据。请确保数据文件可用。",
113
+ "settings": "⚙️ 设置",
114
+ "lang": "选择语言",
115
+ "tab_overview": "📊 概览",
116
+ "tab_heatmap": "🗺️ 声调热图",
117
+ "tab_coverage": "🎯 覆盖率优化",
118
+ "tab_deck": "🗂️ 清单生成",
119
+ "tab_pitfalls": "🚩 多音与易错",
120
+
121
+ # OVERVIEW
122
+ "ov_help_title": "这是做什么的?如何使用",
123
+ "ov_help_body": """
124
+ **概览** 帮你快��了解数据,指导备课。
125
+
126
+ - **类别分布**:哪些动词类别占比高。
127
+ - **语音成分**:第一/第二字常见的声母与韵母。
128
+
129
+ **使用建议**
130
+ 1)选定本周重点的 1–2 个类别;
131
+ 2)根据常见声母/韵母设计对应的发音训练。
132
+ """,
133
+ "cat_dist": "动词类别分布",
134
+ "cat_desc": "各功能类别中的动词数量。",
135
+ "category": "类别",
136
+ "verb_count": "动词数量",
137
+ "phon_header": "语音成分分析(声母/韵母)",
138
+ "phon_desc": "第一、第二字最常见的声母(shēngmǔ)和韵母(yùnmǔ)。",
139
+ "initial_1": "第一字 — 声母",
140
+ "final_1": "第一字 — 韵母",
141
+ "initial_2": "第二字 — 声母",
142
+ "final_2": "第二字 — 韵母",
143
+ "frequency": "频率",
144
+ "component": "语音成分",
145
+
146
+ # HEATMAP
147
+ "hm_help_title": "这是做什么的?如何使用",
148
+ "hm_help_body": """
149
+ **声调热图** 展示首→尾的声调转移(1–5)5×5 矩阵。
150
+
151
+ **使用建议**
152
+ 1)选择 **全部** 或某个类别;
153
+ 2)找出 **主要声调模式**(如 3→4);
154
+ 3)围绕它设计训练并从数据中收集例词。
155
+ """,
156
+ "hm_header": "按类别的声调转移热图",
157
+ "hm_cat": "类别",
158
+ "hm_all": "全部",
159
+
160
+ # COVERAGE
161
+ "cov_help_title": "这是做什么的?如何使用",
162
+ "cov_help_body": """
163
+ **覆盖率优化器** 用少量汉字覆盖尽可能多的动词(贪心集合覆盖)。
164
+
165
+ **使用建议**
166
+ 1)选择你近期可教学的 **汉字数量**;
167
+ 2)查看推荐的 **最优汉字** 及 **覆盖率**;
168
+ 3)使用被覆盖的动词表作为快速教学清单。
169
+ """,
170
+ "cov_header": "覆盖率优化器",
171
+ "cov_caption": "选择少量汉字覆盖尽可能多的动词。",
172
+ "cov_how_many": "选择多少个汉字?",
173
+ "cov_selected": "已选汉字数",
174
+ "cov_list_prefix": "已选:",
175
+ "cov_coverage": "覆盖率",
176
+ "cov_verbs_covered": "覆盖的动词数量",
177
+ "cov_download": "下载覆盖动词(CSV)",
178
+
179
+ # DECK
180
+ "deck_help_title": "这是做什么的?如何使用",
181
+ "deck_help_body": """
182
+ **清单生成器** 将筛选条件(声调、声母/韵母)变成学习清单。
183
+
184
+ **使用建议**
185
+ 1)选择 **声调模式** 与(可选)**语音成分**;
186
+ 2)设定 **清单大小** 并生成;
187
+ 3)导出 CSV 用于 Anki 或讲义。
188
+ """,
189
+ "deck_header": "发音/清单生成器",
190
+ "deck_tone_pairs": "声调模式",
191
+ "deck_position": "位置",
192
+ "deck_any": "任意",
193
+ "deck_first_init": "第一字:声母",
194
+ "deck_first_final": "第一字:韵母",
195
+ "deck_second_init": "第二字:声母",
196
+ "deck_second_final": "第二字:韵母",
197
+ "deck_components": "成分",
198
+ "deck_size": "清单大小",
199
+ "deck_no_items": "当前筛选无结果。",
200
+ "deck_download": "下载清单(CSV)",
201
+
202
+ # PITFALLS
203
+ "pit_help_title": "这是做什么的?如何使用",
204
+ "pit_help_body": """
205
+ **多音与易错**:找出声调角色多的汉字,以及 3→3 词(讲解三声变调)。
206
+
207
+ **使用建议**
208
+ 1)预先讲解 **多音多角色** 的汉字;
209
+ 2)展示 **3→3** 列表,提醒口语常读为 2+3。
210
+ """,
211
+ "pit_header": "多音与易错点",
212
+ "pit_poly_caption": "声调角色多的汉字(易混)",
213
+ "pit_sandhi_caption": "3→3(底层)— 口语一般读作 2+3",
214
+ "no_data": "没有可用数据。"
215
+ }
216
+ }
217
+
218
+
pages/1_🕸️_Character_Network(汉字网络).py CHANGED
@@ -8,6 +8,9 @@ import os
8
  import streamlit.components.v1 as components
9
  import json
10
 
 
 
 
11
  # ----------------------------
12
  # Page Configuration
13
  # ----------------------------
@@ -136,7 +139,11 @@ T = translations[lang]
136
  page_header(T['page_title'], "🕸️")
137
 
138
  # --- Data Loading and Processing ---
139
- df = load_data()
 
 
 
 
140
  if df.empty:
141
  st.error(T['load_error'])
142
  st.stop()
@@ -175,7 +182,7 @@ with tab1:
175
 
176
  if not filtered_df.empty:
177
  with st.spinner(T['generating_network']):
178
- G = nx.DiGraph()
179
  for _, row in filtered_df.iterrows():
180
  if row['char1'] and row['char2']:
181
  G.add_edge(row['char1'], row['char2'], title=row['Verb'])
 
8
  import streamlit.components.v1 as components
9
  import json
10
 
11
+
12
+
13
+
14
  # ----------------------------
15
  # Page Configuration
16
  # ----------------------------
 
139
  page_header(T['page_title'], "🕸️")
140
 
141
  # --- Data Loading and Processing ---
142
+ @st.cache_data
143
+ def get_df():
144
+ return load_data()
145
+ df = get_df()
146
+
147
  if df.empty:
148
  st.error(T['load_error'])
149
  st.stop()
 
182
 
183
  if not filtered_df.empty:
184
  with st.spinner(T['generating_network']):
185
+ #G = nx.DiGraph()
186
  for _, row in filtered_df.iterrows():
187
  if row['char1'] and row['char2']:
188
  G.add_edge(row['char1'], row['char2'], title=row['Verb'])
pages/3_💡_ Verb_ Action_Coach(动词教学助理).py ADDED
@@ -0,0 +1,419 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import numpy as np
4
+ import plotly.express as px
5
+ from utils import page_header, load_data
6
+ from i18n.verb_action_coach import TRANSLATIONS as TX
7
+
8
+
9
+
10
+
11
+ st.markdown("""
12
+ <style>
13
+ /* ===== Expander: Blue header + persistent left stripe on body ===== */
14
+ div[data-testid="stExpander"] > details{
15
+ --accent: #2563eb; /* blue header & stripe */
16
+ --accent-open: #1d4ed8; /* header when open */
17
+ --border: #dbeafe; /* soft outer border */
18
+ --focus: #93c5fd;
19
+ border: 1px solid var(--border);
20
+ border-radius: 12px;
21
+ margin: .25rem 0 1rem 0;
22
+ overflow: hidden;
23
+ background: #fff;
24
+ position: relative;
25
+ }
26
+
27
+ /* Header bar */
28
+ div[data-testid="stExpander"] > details > summary{
29
+ list-style: none;
30
+ background: var(--accent);
31
+ color: #fff;
32
+ padding: .75rem 1rem;
33
+ font-weight: 700;
34
+ cursor: pointer;
35
+ user-select: none;
36
+ }
37
+ div[data-testid="stExpander"] > details > summary::-webkit-details-marker{ display:none; }
38
+ div[data-testid="stExpander"] > details > summary::after{
39
+ content: "▾";
40
+ float: right;
41
+ color: #fff;
42
+ transition: transform .2s ease;
43
+ }
44
+ div[data-testid="stExpander"] > details[open] > summary{
45
+ background: var(--accent-open);
46
+ }
47
+ div[data-testid="stExpander"] > details[open] > summary::after{
48
+ transform: rotate(180deg);
49
+ }
50
+
51
+ /* Body container (cover multiple Streamlit versions) */
52
+ div[data-testid="stExpander"] > details > div[role='group'],
53
+ div[data-testid="stExpander"] > details > div[role='region'],
54
+ div[data-testid="stExpander"] > details > div[data-testid="stExpanderContent"]{
55
+ position: relative; /* needed for the pseudo stripe */
56
+ background: #fff;
57
+ padding: 1rem 1.1rem 1rem 1.1rem; /* base padding; we'll add left offset when open */
58
+ border-top: 1px solid var(--border);
59
+ }
60
+
61
+ /* Left stripe ON the body when open (pseudo-element so it never disappears) */
62
+ div[data-testid="stExpander"] > details[open] > div[role='group']::before,
63
+ div[data-testid="stExpander"] > details[open] > div[role='region']::before,
64
+ div[data-testid="stExpander"] > details[open] > div[data-testid="stExpanderContent"]::before{
65
+ content: "";
66
+ position: absolute;
67
+ left: 0; top: 0; bottom: 0;
68
+ width: 6px;
69
+ background: var(--accent);
70
+ border-radius: 0; /* keep it crisp */
71
+ pointer-events: none;
72
+ }
73
+ /* Add space so text doesn't sit under the stripe */
74
+ div[data-testid="stExpander"] > details[open] > div[role='group'],
75
+ div[data-testid="stExpander"] > details[open] > div[role='region'],
76
+ div[data-testid="stExpander"] > details[open] > div[data-testid="stExpanderContent"]{
77
+ padding-left: calc(1.1rem + 6px);
78
+ }
79
+
80
+ /* Focus ring & hover (accessibility niceties) */
81
+ div[data-testid="stExpander"] > details > summary:hover{ filter: brightness(0.97); }
82
+ div[data-testid="stExpander"] > details > summary:focus{
83
+ outline: 2px solid var(--focus);
84
+ outline-offset: 2px;
85
+ }
86
+ </style>
87
+ """, unsafe_allow_html=True)
88
+
89
+
90
+ # =========================
91
+ # Sidebar: language
92
+ # =========================
93
+ st.sidebar.header(f"{TX['en']['settings']} / {TX['zh']['settings']}")
94
+ lang_options = {"English":"en", "中文 (Chinese)":"zh"}
95
+ lang = st.sidebar.radio("Select Language / 选择语言", options=list(lang_options.keys()), horizontal=True)
96
+ lang = lang_options[lang]
97
+ T = TX[lang]
98
+
99
+ page_header(T["title"], "💡")
100
+
101
+ # =========================
102
+ # Load + prepare data
103
+ # =========================
104
+ @st.cache_data
105
+ def get_df():
106
+ return load_data()
107
+
108
+ df = get_df()
109
+ if df is None or df.empty:
110
+ st.error(T["load_error"])
111
+ st.stop()
112
+
113
+ # Parse bilingual classification "中文(English)"
114
+ def parse_bilingual(text):
115
+ if isinstance(text, str) and "(" in text and ")" in text:
116
+ zh, en = text.split("(", 1)
117
+ en = en.replace(")", "")
118
+ return zh.strip(), en.strip()
119
+ return text, text
120
+
121
+ if "Chinese_Verbs" in df.columns and "Verb" not in df.columns:
122
+ df = df.rename(columns={"Chinese_Verbs":"Verb"})
123
+
124
+ if "分类(Classification)" in df.columns:
125
+ df[["Classification_zh","Classification_en"]] = df["分类(Classification)"].apply(
126
+ lambda x: pd.Series(parse_bilingual(x))
127
+ )
128
+ classification_col_display = "Classification_zh" if lang == "zh" else "Classification_en"
129
+ else:
130
+ classification_col_display = None
131
+
132
+ # Tone pair helpers
133
+ def split_tone_pair(tp: str):
134
+ try:
135
+ a,b = str(tp).split("-")
136
+ return int(a), int(b)
137
+ except Exception:
138
+ return None, None
139
+
140
+ if "tone_pattern" in df.columns:
141
+ df["tone_pattern"] = df["tone_pattern"].astype(str)
142
+ df["src_tone"], df["dst_tone"] = zip(*df["tone_pattern"].map(split_tone_pair))
143
+ else:
144
+ df["tone_pattern"] = None
145
+ df["src_tone"] = None
146
+ df["dst_tone"] = None
147
+
148
+ # Edge-level table (unique AB with one example row)
149
+ edge_cols = [
150
+ "char1","char2","Verb","pinyin","English_Verb","tone_pattern","src_tone","dst_tone",
151
+ "initial_1","final_1","initial_2","final_2","Classification_zh","Classification_en"
152
+ ]
153
+ edge_cols = [c for c in edge_cols if c in df.columns]
154
+ edge_df = df[edge_cols].dropna(subset=["char1","char2"]).drop_duplicates()
155
+
156
+ # =========================
157
+ # Tabs
158
+ # =========================
159
+ TAB_OV, TAB_HM, TAB_COV, TAB_DECK, TAB_PIT = st.tabs([
160
+ T["tab_overview"],
161
+ T["tab_heatmap"],
162
+ T["tab_coverage"],
163
+ T["tab_deck"],
164
+ T["tab_pitfalls"],
165
+ ])
166
+
167
+ # =========================
168
+ # Tab 1 — Overview
169
+ # =========================
170
+ with TAB_OV:
171
+ st.header(T["tab_overview"])
172
+ with st.expander(T["ov_help_title"], expanded=False):
173
+ st.markdown(T["ov_help_body"])
174
+
175
+ # Category Distribution
176
+ st.subheader(T["cat_dist"])
177
+ st.caption(T["cat_desc"])
178
+ if classification_col_display and classification_col_display in df.columns:
179
+ cat_counts = df[classification_col_display].value_counts(dropna=True).reset_index()
180
+ cat_counts.columns = [classification_col_display, "count"]
181
+ fig_cat = px.bar(
182
+ cat_counts,
183
+ x="count",
184
+ y=classification_col_display,
185
+ orientation="h",
186
+ labels={"count": T["verb_count"], classification_col_display: T["category"]},
187
+ )
188
+ fig_cat.update_layout(yaxis={"categoryorder":"total ascending"})
189
+ st.plotly_chart(fig_cat, use_container_width=True)
190
+ else:
191
+ st.info(T["no_data"] if "no_data" in T else "No data.")
192
+
193
+ st.divider()
194
+
195
+ # Phonetic Breakdown
196
+ st.subheader(T["phon_header"])
197
+ st.caption(T["phon_desc"])
198
+ col1, col2 = st.columns(2)
199
+
200
+ def freq_chart(series, title):
201
+ if series is None or series.name not in df.columns:
202
+ st.info(T["no_data"] if "no_data" in T else "No data.")
203
+ return
204
+ freq = df[series.name].value_counts().nlargest(15).reset_index()
205
+ if freq.empty:
206
+ st.info(T["no_data"] if "no_data" in T else "No data.")
207
+ return
208
+ freq.columns = ["component","count"]
209
+ fig = px.bar(
210
+ freq, x="count", y="component", orientation="h",
211
+ labels={"count": T["frequency"], "component": T["component"]}, title=title
212
+ )
213
+ fig.update_layout(yaxis={"categoryorder":"total ascending"})
214
+ st.plotly_chart(fig, use_container_width=True)
215
+
216
+ with col1:
217
+ if "initial_1" in df.columns: freq_chart(df["initial_1"], T["initial_1"])
218
+ if "initial_2" in df.columns: freq_chart(df["initial_2"], T["initial_2"])
219
+ with col2:
220
+ if "final_1" in df.columns: freq_chart(df["final_1"], T["final_1"])
221
+ if "final_2" in df.columns: freq_chart(df["final_2"], T["final_2"])
222
+
223
+ # =========================
224
+ # Tab 2 — Tone Heatmap
225
+ # =========================
226
+ with TAB_HM:
227
+ st.header(T["hm_header"])
228
+ with st.expander(T["hm_help_title"], expanded=False):
229
+ st.markdown(T["hm_help_body"])
230
+
231
+ if edge_df.empty or "src_tone" not in edge_df.columns or "dst_tone" not in edge_df.columns:
232
+ st.info(T["no_data"] if "no_data" in T else "No data.")
233
+ else:
234
+ cats = [T["hm_all"]]
235
+ if classification_col_display and classification_col_display in edge_df.columns:
236
+ cats += sorted(edge_df[classification_col_display].dropna().unique().tolist())
237
+ cat_choice = st.selectbox(T["hm_cat"], options=cats)
238
+ sub = edge_df.copy()
239
+ if cat_choice != T["hm_all"] and classification_col_display:
240
+ sub = sub[sub[classification_col_display] == cat_choice]
241
+
242
+ # 5×5 matrix src→dst
243
+ idx = pd.MultiIndex.from_product([range(1,6), range(1,6)], names=["src_tone","dst_tone"])
244
+ mat = (
245
+ sub.dropna(subset=["src_tone","dst_tone"])
246
+ .groupby(["src_tone","dst_tone"]).size()
247
+ .reindex(idx, fill_value=0).unstack(fill_value=0)
248
+ )
249
+ fig_hm = px.imshow(
250
+ mat.values,
251
+ x=[1,2,3,4,5], y=[1,2,3,4,5], text_auto=True, aspect="equal",
252
+ labels=dict(x="dst tone", y="src tone", color="count"),
253
+ )
254
+ st.plotly_chart(fig_hm, use_container_width=True)
255
+
256
+ # =========================
257
+ # Tab 3 — Coverage Optimizer
258
+ # =========================
259
+ with TAB_COV:
260
+ st.header(T["cov_header"])
261
+ with st.expander(T["cov_help_title"], expanded=False):
262
+ st.markdown(T["cov_help_body"])
263
+ st.caption(T["cov_caption"])
264
+
265
+ if edge_df.empty:
266
+ st.info(T["no_data"] if "no_data" in T else "No data.")
267
+ else:
268
+ k_max = st.slider(T["cov_how_many"], min_value=5, max_value=300, value=15, step=5)
269
+
270
+ edges = edge_df[["char1","char2","Verb","pinyin","English_Verb"]].drop_duplicates().reset_index(drop=True)
271
+ edges["edge_id"] = edges["char1"] + "|" + edges["char2"]
272
+
273
+ uncovered = set(edges["edge_id"])
274
+ selected = []
275
+ # Greedy set cover by characters
276
+ while len(selected) < k_max and uncovered:
277
+ counts = {}
278
+ # count coverage per character over currently uncovered edges
279
+ for _, r in edges.iterrows():
280
+ eid = r["edge_id"]
281
+ if eid not in uncovered:
282
+ continue
283
+ for ch in (r["char1"], r["char2"]):
284
+ counts[ch] = counts.get(ch, 0) + 1
285
+ if not counts:
286
+ break
287
+ best = max(counts.items(), key=lambda kv: kv[1])[0]
288
+ selected.append(best)
289
+ newly = edges[(edges["char1"]==best) | (edges["char2"]==best)]["edge_id"].tolist()
290
+ uncovered -= set(newly)
291
+
292
+ covered = set(edges["edge_id"]) - uncovered
293
+ coverage_pct = 100 * len(covered) / max(1, len(edges))
294
+
295
+ colA, colB = st.columns(2)
296
+ with colA:
297
+ st.metric(T["cov_selected"], len(selected))
298
+ st.write("**" + T["cov_list_prefix"] + "** " + ("、".join(selected) if selected else "—"))
299
+ with colB:
300
+ st.metric(T["cov_coverage"], f"{coverage_pct:.1f}%")
301
+ st.caption(f"{T['cov_verbs_covered']}: {len(covered)} / {len(edges)}")
302
+
303
+ covered_verbs = edges[edges["edge_id"].isin(covered)].drop(columns=["edge_id"])
304
+ st.dataframe(covered_verbs, use_container_width=True, height=340)
305
+ st.download_button(
306
+ T["cov_download"],
307
+ covered_verbs.to_csv(index=False).encode("utf-8"),
308
+ file_name="covered_verbs.csv",
309
+ mime="text/csv"
310
+ )
311
+
312
+ # =========================
313
+ # Tab 4 — Deck Builder
314
+ # =========================
315
+ with TAB_DECK:
316
+ st.header(T["deck_header"])
317
+ with st.expander(T["deck_help_title"], expanded=False):
318
+ st.markdown(T["deck_help_body"])
319
+
320
+ if edge_df.empty:
321
+ st.info(T["no_data"] if "no_data" in T else "No data.")
322
+ else:
323
+ # Tone pairs
324
+ tone_opts = sorted(edge_df["tone_pattern"].dropna().unique().tolist()) if "tone_pattern" in edge_df.columns else []
325
+ tone_pick = st.multiselect(T["deck_tone_pairs"], options=tone_opts, default=tone_opts[:6] if tone_opts else [])
326
+
327
+ # Position & components
328
+ pos_opts = [T["deck_any"], T["deck_first_init"], T["deck_first_final"], T["deck_second_init"], T["deck_second_final"]]
329
+ pos_choice = st.selectbox(T["deck_position"], options=pos_opts)
330
+
331
+ def comp_col_from_choice(choice: str):
332
+ if choice in (T["deck_first_init"],):
333
+ return "initial_1"
334
+ if choice in (T["deck_first_final"],):
335
+ return "final_1"
336
+ if choice in (T["deck_second_init"],):
337
+ return "initial_2"
338
+ if choice in (T["deck_second_final"],):
339
+ return "final_2"
340
+ return None
341
+
342
+ comp_col = comp_col_from_choice(pos_choice)
343
+ comp_choices = sorted(edge_df[comp_col].dropna().unique().tolist()) if comp_col and comp_col in edge_df.columns else []
344
+ components = st.multiselect(T["deck_components"], options=comp_choices, default=[])
345
+
346
+ deck_size = st.slider(T["deck_size"], 10, 200, 40, 5)
347
+
348
+ # Build deck
349
+ deck = edge_df.copy()
350
+ if tone_pick:
351
+ deck = deck[deck["tone_pattern"].isin(tone_pick)]
352
+ if comp_col and components:
353
+ deck = deck[deck[comp_col].isin(components)]
354
+
355
+ if deck.empty:
356
+ st.info(T["deck_no_items"])
357
+ else:
358
+ # Weight by frequency in raw df (how often AB occurs)
359
+ freq = df.groupby(["char1","char2"]).size().rename("f").reset_index()
360
+ deck = deck.merge(freq, on=["char1","char2"], how="left")
361
+ deck["f"] = deck["f"].fillna(1)
362
+
363
+ k = min(deck_size, len(deck))
364
+ # weighted sample without replacement
365
+ deck = deck.sample(n=k, weights=deck["f"], replace=False, random_state=42)
366
+
367
+ keep_cols = ["Verb","pinyin","English_Verb","tone_pattern","char1","char2"]
368
+ if "Classification_zh" in deck.columns and "Classification_en" in deck.columns:
369
+ deck["Classification"] = deck["Classification_zh"] if lang=="zh" else deck["Classification_en"]
370
+ keep_cols.append("Classification")
371
+
372
+ deck = deck[keep_cols].reset_index(drop=True)
373
+
374
+ st.dataframe(deck, use_container_width=True, height=340)
375
+ st.download_button(
376
+ T["deck_download"],
377
+ deck.to_csv(index=False).encode("utf-8"),
378
+ file_name="study_deck.csv",
379
+ mime="text/csv"
380
+ )
381
+
382
+ # =========================
383
+ # Tab 5 — Polyphony & Pitfalls
384
+ # =========================
385
+ with TAB_PIT:
386
+ st.header(T["pit_header"])
387
+ with st.expander(T["pit_help_title"], expanded=False):
388
+ st.markdown(T["pit_help_body"])
389
+
390
+ if df.empty:
391
+ st.info(T["no_data"] if "no_data" in T else "No data.")
392
+ else:
393
+ col1, col2 = st.columns(2)
394
+
395
+ # Polyphony: distinct tone roles per character
396
+ if "src_tone" in df.columns and "dst_tone" in df.columns:
397
+ poly_src = df.groupby("char1")["src_tone"].nunique(dropna=True).rename("src_var")
398
+ poly_dst = df.groupby("char2")["dst_tone"].nunique(dropna=True).rename("dst_var")
399
+ poly = pd.concat([poly_src, poly_dst], axis=1).fillna(0).astype(int)
400
+ poly["polyphony"] = poly["src_var"] + poly["dst_var"]
401
+ poly_chars = poly[poly["polyphony"] >= 3].sort_values("polyphony", ascending=False).head(40)
402
+ with col1:
403
+ st.caption(T["pit_poly_caption"])
404
+ st.dataframe(poly_chars, use_container_width=True, height=360)
405
+ else:
406
+ with col1:
407
+ st.info(T["no_data"] if "no_data" in T else "No data.")
408
+
409
+ # 3→3 sandhi list
410
+ with col2:
411
+ if "tone_pattern" in df.columns:
412
+ sandhi = df[df["tone_pattern"] == "3-3"][["Verb","pinyin","English_Verb"]].drop_duplicates().head(80)
413
+ st.caption(T["pit_sandhi_caption"])
414
+ if sandhi.empty:
415
+ st.info(T["no_data"] if "no_data" in T else "No data.")
416
+ else:
417
+ st.dataframe(sandhi, use_container_width=True, height=360)
418
+ else:
419
+ st.info(T["no_data"] if "no_data" in T else "No data.")
pages/3_💡_Verb_Analytics( 动词分析).py DELETED
@@ -1,147 +0,0 @@
1
- import streamlit as st
2
- import pandas as pd
3
- import plotly.express as px
4
- from utils import page_header, load_data
5
-
6
- # ----------------------------
7
- # Page Configuration & Header
8
- # ----------------------------
9
- st.set_page_config(layout="wide")
10
-
11
- # ----------------------------
12
- # Translation Strings
13
- # ----------------------------
14
- translations = {
15
- 'en': {
16
- 'page_title': "Verb Analytics",
17
- 'load_error': "Data could not be loaded. Please ensure the data file is available.",
18
- 'settings_header': "⚙️ Settings",
19
- 'language_select': "Select Language",
20
- 'category_dist_header': "Verb Category Distribution",
21
- 'category_dist_desc': "This chart shows the number of verbs in each functional category, providing an overview of the dataset's composition.",
22
- 'category': "Category",
23
- 'verb_count': "Number of Verbs",
24
- 'phonetic_header': "Phonetic Component Analysis (Initials & Finals)",
25
- 'phonetic_desc': "These charts display the most frequent initials (声母 shēngmǔ) and finals (韵母 yùnmǔ) for the first and second characters in the verbs. This helps identify common phonetic building blocks in verb formation.",
26
- 'initial_1': "First Character - Initial",
27
- 'final_1': "First Character - Final",
28
- 'initial_2': "Second Character - Initial",
29
- 'final_2': "Second Character - Final",
30
- 'frequency': "Frequency",
31
- 'component': "Phonetic Component"
32
- },
33
- 'zh': {
34
- 'page_title': "动词分析",
35
- 'load_error': "无法加载数据。请确保数据文件可用。",
36
- 'settings_header': "⚙️ 设置",
37
- 'language_select': "选择语言",
38
- 'category_dist_header': "动词类别分布",
39
- 'category_dist_desc': "此图表显示了每个功能类别中的动词数量,提供了数据集构成的概览。",
40
- 'category': "类别",
41
- 'verb_count': "动词数量",
42
- 'phonetic_header': "语音成分分析 (声母和韵母)",
43
- 'phonetic_desc': "这些图表显示了动词中第一和第二汉字最常见的声母 (shēngmǔ) 和韵母 (yùnmǔ)。这有助于识别动词构成中常见的语音构件。",
44
- 'initial_1': "第一字 - 声母",
45
- 'final_1': "第一字 - 韵母",
46
- 'initial_2': "第二字 - 声母",
47
- 'final_2': "第二字 - 韵母",
48
- 'frequency': "频率",
49
- 'component': "语音成分"
50
- }
51
- }
52
-
53
- # ----------------------------
54
- # Sidebar Language Selector
55
- # ----------------------------
56
- st.sidebar.header("⚙️ Settings / 设置")
57
- lang_options = {'English': 'en', '中文 (Chinese)': 'zh'}
58
- selected_lang_display = st.sidebar.radio(
59
- "Select Language / 选择语言",
60
- options=lang_options.keys(),
61
- horizontal=True
62
- )
63
- lang = lang_options[selected_lang_display]
64
- T = translations[lang]
65
-
66
- page_header(T['page_title'], "💡")
67
-
68
- # ----------------------------
69
- # Load and Process Data
70
- # ----------------------------
71
- df = load_data()
72
-
73
- if df.empty:
74
- st.error(T['load_error'])
75
- st.stop()
76
-
77
- # Function to parse bilingual column like "中文(English)"
78
- def parse_bilingual(text):
79
- if isinstance(text, str) and '(' in text and ')' in text:
80
- parts = text.split('(')
81
- zh = parts[0]
82
- en = parts[1].replace(')', '')
83
- return zh.strip(), en.strip()
84
- return text, text
85
-
86
- # Apply parsing to the classification column
87
- df[['Classification_zh', 'Classification_en']] = df['分类(Classification)'].apply(lambda x: pd.Series(parse_bilingual(x)))
88
- classification_col_display = 'Classification_zh' if lang == 'zh' else 'Classification_en'
89
-
90
- # ----------------------------
91
- # Main Content
92
- # ----------------------------
93
-
94
- # --- 1. Category Distribution ---
95
- st.header(T['category_dist_header'])
96
- st.markdown(T['category_dist_desc'])
97
-
98
- category_counts = df[classification_col_display].value_counts().reset_index()
99
- category_counts.columns = [classification_col_display, 'count']
100
-
101
- fig_cat = px.bar(
102
- category_counts,
103
- x='count',
104
- y=classification_col_display,
105
- orientation='h',
106
- title=T['category_dist_header'],
107
- labels={
108
- 'count': T['verb_count'],
109
- classification_col_display: T['category']
110
- }
111
- )
112
- fig_cat.update_layout(yaxis={'categoryorder':'total ascending'})
113
- st.plotly_chart(fig_cat, use_container_width=True)
114
-
115
- st.divider()
116
-
117
- # --- 2. Phonetic Breakdown ---
118
- st.header(T['phonetic_header'])
119
- st.markdown(T['phonetic_desc'])
120
-
121
- col1, col2 = st.columns(2)
122
-
123
- # Function to create a frequency chart
124
- def create_freq_chart(data_series, title):
125
- freq = data_series.value_counts().nlargest(15).reset_index()
126
- freq.columns = ['component', 'count']
127
- fig = px.bar(
128
- freq,
129
- x='count',
130
- y='component',
131
- orientation='h',
132
- title=title,
133
- labels={
134
- 'count': T['frequency'],
135
- 'component': T['component']
136
- }
137
- )
138
- fig.update_layout(yaxis={'categoryorder':'total ascending'})
139
- return fig
140
-
141
- with col1:
142
- st.plotly_chart(create_freq_chart(df['initial_1'], T['initial_1']), use_container_width=True)
143
- st.plotly_chart(create_freq_chart(df['initial_2'], T['initial_2']), use_container_width=True)
144
-
145
- with col2:
146
- st.plotly_chart(create_freq_chart(df['final_1'], T['final_1']), use_container_width=True)
147
- st.plotly_chart(create_freq_chart(df['final_2'], T['final_2']), use_container_width=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
pages/4_🎵 _Tone_Patterns(声调探索).py ADDED
@@ -0,0 +1,602 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import numpy as np
4
+ import plotly.express as px
5
+ from utils import page_header, load_data
6
+ from pyvis.network import Network
7
+ import networkx as nx
8
+ import os
9
+ import streamlit.components.v1 as components
10
+ import re
11
+ from collections import Counter, defaultdict
12
+ from i18n.tone_patterns import TRANSLATIONS as TX
13
+ # ----------------------------
14
+ # Page Configuration
15
+ # ----------------------------
16
+ st.set_page_config(layout="wide")
17
+
18
+ # ----------------------------
19
+ # Translation Strings (EN/ZH)
20
+ # ----------------------------
21
+ st.markdown("""
22
+ <style>
23
+ /* ===== Expander: Blue header + persistent left stripe on body ===== */
24
+ div[data-testid="stExpander"] > details{
25
+ --accent: #2563eb; /* blue header & stripe */
26
+ --accent-open: #1d4ed8; /* header when open */
27
+ --border: #dbeafe; /* soft outer border */
28
+ --focus: #93c5fd;
29
+ border: 1px solid var(--border);
30
+ border-radius: 12px;
31
+ margin: .25rem 0 1rem 0;
32
+ overflow: hidden;
33
+ background: #fff;
34
+ position: relative;
35
+ }
36
+
37
+ /* Header bar */
38
+ div[data-testid="stExpander"] > details > summary{
39
+ list-style: none;
40
+ background: var(--accent);
41
+ color: #fff;
42
+ padding: .75rem 1rem;
43
+ font-weight: 700;
44
+ cursor: pointer;
45
+ user-select: none;
46
+ }
47
+ div[data-testid="stExpander"] > details > summary::-webkit-details-marker{ display:none; }
48
+ div[data-testid="stExpander"] > details > summary::after{
49
+ content: "▾";
50
+ float: right;
51
+ color: #fff;
52
+ transition: transform .2s ease;
53
+ }
54
+ div[data-testid="stExpander"] > details[open] > summary{
55
+ background: var(--accent-open);
56
+ }
57
+ div[data-testid="stExpander"] > details[open] > summary::after{
58
+ transform: rotate(180deg);
59
+ }
60
+
61
+ /* Body container (cover multiple Streamlit versions) */
62
+ div[data-testid="stExpander"] > details > div[role='group'],
63
+ div[data-testid="stExpander"] > details > div[role='region'],
64
+ div[data-testid="stExpander"] > details > div[data-testid="stExpanderContent"]{
65
+ position: relative; /* needed for the pseudo stripe */
66
+ background: #fff;
67
+ padding: 1rem 1.1rem 1rem 1.1rem; /* base padding; we'll add left offset when open */
68
+ border-top: 1px solid var(--border);
69
+ }
70
+
71
+ /* Left stripe ON the body when open (pseudo-element so it never disappears) */
72
+ div[data-testid="stExpander"] > details[open] > div[role='group']::before,
73
+ div[data-testid="stExpander"] > details[open] > div[role='region']::before,
74
+ div[data-testid="stExpander"] > details[open] > div[data-testid="stExpanderContent"]::before{
75
+ content: "";
76
+ position: absolute;
77
+ left: 0; top: 0; bottom: 0;
78
+ width: 6px;
79
+ background: var(--accent);
80
+ border-radius: 0; /* keep it crisp */
81
+ pointer-events: none;
82
+ }
83
+ /* Add space so text doesn't sit under the stripe */
84
+ div[data-testid="stExpander"] > details[open] > div[role='group'],
85
+ div[data-testid="stExpander"] > details[open] > div[role='region'],
86
+ div[data-testid="stExpander"] > details[open] > div[data-testid="stExpanderContent"]{
87
+ padding-left: calc(1.1rem + 6px);
88
+ }
89
+
90
+ /* Focus ring & hover (accessibility niceties) */
91
+ div[data-testid="stExpander"] > details > summary:hover{ filter: brightness(0.97); }
92
+ div[data-testid="stExpander"] > details > summary:focus{
93
+ outline: 2px solid var(--focus);
94
+ outline-offset: 2px;
95
+ }
96
+ </style>
97
+ """, unsafe_allow_html=True)
98
+
99
+
100
+
101
+ # ----------------------------
102
+ # Sidebar: language and header
103
+ # ----------------------------
104
+ st.sidebar.header("⚙️ Settings / 设置")
105
+ lang_options = {'English': 'en', '中文 (Chinese)': 'zh'}
106
+ selected_lang_display = st.sidebar.radio("Select Language / 选择语言", options=lang_options.keys(), horizontal=True)
107
+ lang = lang_options[selected_lang_display]
108
+ T = TX[lang]
109
+
110
+ page_header(T['page_title'], "🎵")
111
+
112
+ # ----------------------------
113
+ # Data Loading & Preprocessing
114
+ # ----------------------------
115
+ @st.cache_data
116
+ def get_df():
117
+ return load_data()
118
+
119
+ df = get_df()
120
+ if df.empty:
121
+ st.error(T['load_error'])
122
+ st.stop()
123
+
124
+ # Handle bilingual classification
125
+
126
+ def parse_bilingual(text):
127
+ if isinstance(text, str) and '(' in text and ')' in text:
128
+ parts = text.split('(')
129
+ zh, en = parts[0], parts[1].replace(')', '')
130
+ return zh.strip(), en.strip()
131
+ return text, text
132
+
133
+ if 'Chinese_Verbs' in df.columns and 'Verb' not in df.columns:
134
+ df.rename(columns={'Chinese_Verbs': 'Verb'}, inplace=True)
135
+
136
+ if '分类(Classification)' in df.columns:
137
+ df[['Classification_zh', 'Classification_en']] = df['分类(Classification)'].apply(lambda x: pd.Series(parse_bilingual(x)))
138
+ classification_col_display = 'Classification_zh' if lang == 'zh' else 'Classification_en'
139
+ else:
140
+ classification_col_display = 'English_Verb' # fallback
141
+
142
+ # Clean tone pair
143
+
144
+ def split_tone_pair(tp: str):
145
+ try:
146
+ a,b = str(tp).split('-')
147
+ return int(a), int(b)
148
+ except Exception:
149
+ return None, None
150
+
151
+ # Compute helper columns
152
+ for col in ['char1','char2','tone_pattern','pinyin']:
153
+ if col not in df.columns:
154
+ df[col] = None
155
+
156
+ # Remove rows missing chars or tones
157
+ src_tone, dst_tone = zip(*df['tone_pattern'].astype(str).map(split_tone_pair))
158
+ df['src_tone'] = src_tone
159
+ df['dst_tone'] = dst_tone
160
+ mask_valid = df['char1'].notna() & df['char2'].notna() & df['src_tone'].between(1,5) & df['dst_tone'].between(1,5)
161
+ df = df.loc[mask_valid].copy()
162
+
163
+ # Pinyin base (remove 1–5 digits)
164
+ df['pinyin_base'] = df['pinyin'].astype(str).str.replace(r"[1-5]", "", regex=True)
165
+
166
+ # Build aggregated edge table to get weights
167
+ agg_cols = ['char1','char2','tone_pattern','src_tone','dst_tone','Verb','pinyin','English_Verb']
168
+ if 'Classification_zh' in df.columns and 'Classification_en' in df.columns:
169
+ agg_cols += ['Classification_zh','Classification_en']
170
+ edge_df = df[agg_cols].copy()
171
+ edge_df['weight'] = 1
172
+ edge_df = edge_df.groupby(['char1','char2','tone_pattern','src_tone','dst_tone'], as_index=False).agg({
173
+ 'weight':'sum',
174
+ 'Verb':'first','pinyin':'first','English_Verb':'first',
175
+ **({'Classification_zh':'first','Classification_en':'first'} if 'Classification_zh' in df.columns else {})
176
+ })
177
+
178
+ # Build graph
179
+ @st.cache_data
180
+ def build_graph(edge_df: pd.DataFrame):
181
+ G = nx.DiGraph()
182
+ for _, r in edge_df.iterrows():
183
+ G.add_edge(r['char1'], r['char2'],
184
+ tone_pair=r['tone_pattern'], src_tone=int(r['src_tone']), dst_tone=int(r['dst_tone']),
185
+ weight=int(r['weight']),
186
+ verb=r.get('Verb'), pinyin=r.get('pinyin'), english=r.get('English_Verb'),
187
+ cls_zh=r.get('Classification_zh'), cls_en=r.get('Classification_en'))
188
+ # dominant node tone
189
+ node_tone = {}
190
+ for n in G.nodes():
191
+ tones = []
192
+ for _, _, d in G.in_edges(n, data=True):
193
+ tones.append(d['dst_tone'])
194
+ for _, _, d in G.out_edges(n, data=True):
195
+ tones.append(d['src_tone'])
196
+ if tones:
197
+ counts = Counter(tones)
198
+ node_tone[n] = sorted(counts.items(), key=lambda kv: (-kv[1], kv[0]))[0][0]
199
+ nx.set_node_attributes(G, node_tone, 'tone')
200
+ return G
201
+
202
+ G_full = build_graph(edge_df)
203
+
204
+ # ----------------------------
205
+ # Shared Filters (apply to multiple tabs)
206
+ # ----------------------------
207
+ all_pairs = sorted(edge_df['tone_pattern'].dropna().unique())
208
+ all_src = sorted(edge_df['src_tone'].dropna().unique())
209
+ all_dst = sorted(edge_df['dst_tone'].dropna().unique())
210
+ all_classes = sorted(df[classification_col_display].dropna().unique()) if classification_col_display in df.columns else []
211
+
212
+ st.sidebar.header(T['controls_header'])
213
+ selected_pairs = st.sidebar.multiselect(T['filter_by_tonepair'], options=all_pairs, default=all_pairs)
214
+ selected_src = st.sidebar.multiselect(T['filter_src_tone'], options=all_src, default=all_src)
215
+ selected_dst = st.sidebar.multiselect(T['filter_dst_tone'], options=all_dst, default=all_dst)
216
+ selected_cls = st.sidebar.multiselect(T['filter_class'], options=all_classes, default=all_classes) if all_classes else []
217
+
218
+ # Filter edge table
219
+ mask = edge_df['tone_pattern'].isin(selected_pairs) & edge_df['src_tone'].isin(selected_src) & edge_df['dst_tone'].isin(selected_dst)
220
+ if selected_cls and 'Classification_zh' in edge_df.columns:
221
+ disp_col = 'Classification_zh' if lang == 'zh' else 'Classification_en'
222
+ mask = mask & edge_df[disp_col].isin(selected_cls)
223
+ edge_df_f = edge_df.loc[mask].copy()
224
+
225
+ # Color map for tone pairs
226
+ palette = ["#1f77b4","#ff7f0e","#2ca02c","#d62728","#9467bd","#8c564b","#e377c2","#7f7f7f","#bcbd22","#17becf",
227
+ "#393b79","#637939","#8c6d31","#843c39","#7b4173","#3182bd","#e6550d","#31a354","#756bb1","#636363"]
228
+ unique_pairs = sorted(edge_df['tone_pattern'].dropna().unique())
229
+ pair_color = {tp: palette[i % len(palette)] for i, tp in enumerate(unique_pairs)}
230
+
231
+ # ----------------------------
232
+ # Tabs
233
+ # ----------------------------
234
+ TAB2, TAB3, TAB4, TAB5, TAB6, TAB9 = st.tabs([
235
+ T['tab_network'], T['tab_pathways'], T['tab_families'], T['tab_minpairs'], T['tab_charprof'], T['tab_curriculum']
236
+ ])
237
+
238
+ # ----------------------------
239
+ # TAB 2 – Tone Network
240
+ # ----------------------------
241
+ with TAB2:
242
+ st.header(T['tab_network'])
243
+ with st.expander(T['help_network_title'], expanded=False):
244
+ st.markdown(T['help_network_body'])
245
+
246
+ st.markdown(T['network_desc'])
247
+ fade_unselected = st.checkbox(T['fade_unselected'], value=True)
248
+
249
+ if edge_df_f.empty:
250
+ st.warning(T['no_match_warning'])
251
+ else:
252
+ # Build subgraph
253
+ G = nx.DiGraph()
254
+ for _, r in edge_df.iterrows():
255
+ # include all nodes for layout stability
256
+ if r['char1'] not in G:
257
+ G.add_node(r['char1'])
258
+ if r['char2'] not in G:
259
+ G.add_node(r['char2'])
260
+ for _, r in edge_df.iterrows():
261
+ show = (r['tone_pattern'] in selected_pairs and r['src_tone'] in selected_src and r['dst_tone'] in selected_dst)
262
+ if selected_cls and 'Classification_zh' in r and 'Classification_en' in r:
263
+ disp_col = 'cls_zh' if lang=='zh' else 'cls_en'
264
+ # Add edges regardless (to allow fading), but mark visibility
265
+ G.add_edge(r['char1'], r['char2'],
266
+ tone_pair=r['tone_pattern'], src_tone=int(r['src_tone']), dst_tone=int(r['dst_tone']),
267
+ weight=int(r['weight']),
268
+ verb=r.get('Verb'), pinyin=r.get('pinyin'), english=r.get('English_Verb'),
269
+ cls_zh=r.get('Classification_zh'), cls_en=r.get('Classification_en'),
270
+ visible=show)
271
+
272
+ degrees = dict(G.degree())
273
+ min_d, max_d = (0, 1)
274
+ if degrees:
275
+ min_d = min(degrees.values()); max_d = max(degrees.values()) if max(degrees.values())>0 else 1
276
+ size_scale = {n: 12 + 24*(deg-min_d)/(max_d-min_d) if (max_d-min_d)>0 else 15 for n, deg in degrees.items()}
277
+
278
+ net = Network(height='750px', width='100%', notebook=False, directed=True, cdn_resources='in_line', select_menu=True, filter_menu=True)
279
+ # Node groups by dominant tone for simple coloring when grouping in menu
280
+ node_tone = nx.get_node_attributes(G, 'tone')
281
+ for n in G.nodes():
282
+ tone = node_tone.get(n, None)
283
+ net.add_node(n, label=n, size=size_scale.get(n, 15), font={'size': int(size_scale.get(n, 15))+8}, group=str(tone) if tone else 'N/A')
284
+
285
+ for u, v, d in G.edges(data=True):
286
+ color = pair_color.get(d['tone_pair'], '#cccccc')
287
+ width = 1 + (d.get('weight',1))
288
+ # Fade if not selected
289
+ if not d.get('visible'):
290
+ if fade_unselected:
291
+ color = '#dddddd'
292
+ width = 1
293
+ else:
294
+ continue
295
+ title = f"{d.get('verb','')} ({d.get('pinyin','')})\n{d.get('english','')}\n{u}→{v} [{d.get('tone_pair','')}]"
296
+ net.add_edge(u, v, title=title, color=color, width=width)
297
+
298
+ # Legend
299
+ legend_pairs = [tp for tp in selected_pairs][:12]
300
+ if legend_pairs:
301
+ legend_html = "<div style='padding:6px 0'>" + " ".join(
302
+ f"<span style='display:inline-flex;align-items:center;margin-right:10px'>"
303
+ f"<span style='width:12px;height:12px;background:{pair_color[tp]};display:inline-block;border-radius:2px;margin-right:6px'></span>{tp}</span>"
304
+ for tp in legend_pairs
305
+ ) + ("<span style='opacity:0.6;margin-left:8px'>…</span>" if len(selected_pairs)>12 else "") + "</div>"
306
+ st.markdown(f"**{T['legend_header']}:**", unsafe_allow_html=True)
307
+ st.markdown(legend_html, unsafe_allow_html=True)
308
+
309
+ try:
310
+ file_path = 'tone_network.html'
311
+ net.save_graph(file_path)
312
+ with open(file_path, 'r', encoding='utf-8') as f:
313
+ source_code = f.read()
314
+ components.html(source_code, height=800)
315
+ if os.path.exists(file_path):
316
+ os.remove(file_path)
317
+ except Exception as e:
318
+ st.error(f"Error displaying graph: {e}")
319
+
320
+ # ----------------------------
321
+ # TAB 3 – Tone Pathways
322
+ # ----------------------------
323
+ with TAB3:
324
+ st.header(T['tab_pathways'])
325
+ with st.expander(T['help_pathways_title'], expanded=False):
326
+ st.markdown(T['help_pathways_body'])
327
+
328
+ st.caption(T['path_desc'])
329
+ if edge_df_f.empty:
330
+ st.warning(T['no_match_warning'])
331
+ else:
332
+ # Build subgraph with only filtered edges for pathfinding preference
333
+ Gp = nx.DiGraph()
334
+ for _, r in edge_df_f.iterrows():
335
+ Gp.add_edge(r['char1'], r['char2'], tone_pair=r['tone_pattern'], src_tone=int(r['src_tone']), dst_tone=int(r['dst_tone']),
336
+ weight=int(r['weight']), verb=r['Verb'], pinyin=r['pinyin'], english=r['English_Verb'])
337
+ all_chars = sorted(list(set(Gp.nodes())))
338
+ col1, col2, col3, col4 = st.columns([1.2,1,1,1])
339
+ with col1:
340
+ tgt_pair = st.selectbox(T['path_target_pair'], options=selected_pairs or all_pairs)
341
+ with col2:
342
+ start_char = st.selectbox(T['path_start_char'], options=['']+all_chars)
343
+ with col3:
344
+ k = st.number_input(T['path_len'], min_value=3, max_value=12, value=6, step=1)
345
+ with col4:
346
+ seed = st.number_input('Seed', min_value=0, max_value=9999, value=42, step=1)
347
+
348
+ def tone_path(G, start, target_pair, k=6, seed=42):
349
+ if not start or start not in G:
350
+ return []
351
+ rng = np.random.default_rng(seed)
352
+ path = [start]
353
+ cur = start
354
+ visited = {cur}
355
+ tp_src, tp_dst = target_pair.split('-')
356
+ tp_src, tp_dst = int(tp_src), int(tp_dst)
357
+ for _ in range(k-1):
358
+ candidates = []
359
+ for _, v, d in G.out_edges(cur, data=True):
360
+ if v in visited: continue
361
+ score = 0.0
362
+ if d.get('src_tone')==tp_src and d.get('dst_tone')==tp_dst:
363
+ score += 3.0
364
+ score += 0.5*np.log1p(d.get('weight',1))
365
+ score += 0.2*G.degree(v)
366
+ candidates.append((score + 0.01*rng.random(), v))
367
+ if not candidates:
368
+ break
369
+ candidates.sort(reverse=True)
370
+ cur = candidates[0][1]
371
+ visited.add(cur)
372
+ path.append(cur)
373
+ return path
374
+
375
+ if st.button(T['path_make'], use_container_width=False) and start_char:
376
+ chain = tone_path(Gp, start_char, tgt_pair, k=int(k), seed=int(seed))
377
+ if len(chain) < 2:
378
+ st.info(T['no_match_warning'])
379
+ else:
380
+ # Collect edges along the path
381
+ rows = []
382
+ for a,b in zip(chain[:-1], chain[1:]):
383
+ d = Gp.get_edge_data(a,b)
384
+ if d:
385
+ rows.append({'char1':a,'char2':b,'tone_pair':d.get('tone_pair'), 'Verb':d.get('verb'), 'pinyin':d.get('pinyin'), 'English_Verb':d.get('english')})
386
+ path_df = pd.DataFrame(rows)
387
+ st.subheader(T['verbs_on_path'])
388
+ st.dataframe(path_df, use_container_width=True)
389
+ if not path_df.empty:
390
+ st.download_button(T['download_csv'], path_df.to_csv(index=False).encode('utf-8'), file_name='tone_path.csv', mime='text/csv')
391
+
392
+ # ----------------------------
393
+ # TAB 4 – Tone in Families
394
+ # ----------------------------
395
+ with TAB4:
396
+ st.header(T['tab_families'])
397
+ with st.expander(T['help_families_title'], expanded=False):
398
+ st.markdown(T['help_families_body'])
399
+
400
+ st.caption(T['families_desc'])
401
+
402
+ if G_full.number_of_nodes() <= 1:
403
+ st.warning(T['no_match_warning'])
404
+ else:
405
+ # communities on the full graph for stability
406
+ comms = list(nx.community.greedy_modularity_communities(G_full.to_undirected()))
407
+ comms = [c for c in comms if len(c) >= 6]
408
+ if not comms:
409
+ st.warning(T['no_match_warning'])
410
+ else:
411
+ fam_options = {f"Family {i+1} ({len(c)} chars)": i for i,c in enumerate(comms[:20])}
412
+ key = st.selectbox(T['family_select'], options=list(fam_options.keys()))
413
+ idx = fam_options[key]
414
+ C = comms[idx]
415
+ st.info(f"**{T['family_members']}:** {', '.join(list(C)[:50])}{' …' if len(C)>50 else ''}")
416
+
417
+ # Subset edges to intra-community + current tone filters
418
+ sub = edge_df.copy()
419
+ sub = sub[sub['char1'].isin(C) & sub['char2'].isin(C)]
420
+ mask2 = sub['tone_pattern'].isin(selected_pairs) & sub['src_tone'].isin(selected_src) & sub['dst_tone'].isin(selected_dst)
421
+ sub = sub.loc[mask2]
422
+
423
+ if sub.empty:
424
+ st.warning(T['no_match_warning'])
425
+ else:
426
+ # Tone distribution
427
+ dist = sub.groupby('tone_pattern', as_index=False)['weight'].sum().sort_values('weight', ascending=False)
428
+ st.subheader(T['tone_distribution'])
429
+ fig = px.bar(dist, x='weight', y='tone_pattern', orientation='h', text='weight', color='tone_pattern', color_discrete_map=pair_color)
430
+ fig.update_layout(yaxis={'categoryorder':'total ascending'})
431
+ st.plotly_chart(fig, use_container_width=True)
432
+
433
+ # Intra-community graph
434
+ net_fam = Network(height='650px', width='100%', notebook=False, directed=True, cdn_resources='in_line')
435
+ # Node sizing by degree within community
436
+ Gc = nx.DiGraph()
437
+ for _, r in sub.iterrows():
438
+ Gc.add_edge(r['char1'], r['char2'], tone_pair=r['tone_pattern'], weight=int(r['weight']), title=f"{r['Verb']} ({r['pinyin']})")
439
+ degs = dict(Gc.degree())
440
+ for n in Gc.nodes():
441
+ sz = 12 + 20*(degs.get(n,0)/max(1,max(degs.values())))
442
+ net_fam.add_node(n, label=n, size=sz, font={'size': int(sz)+6})
443
+ for u,v,d in Gc.edges(data=True):
444
+ color = pair_color.get(d.get('tone_pair'), '#cccccc')
445
+ net_fam.add_edge(u,v, title=d.get('title'), color=color, width=1+d.get('weight',1))
446
+ try:
447
+ file_path_fam = 'tone_family.html'
448
+ net_fam.save_graph(file_path_fam)
449
+ with open(file_path_fam, 'r', encoding='utf-8') as f:
450
+ components.html(f.read(), height=600)
451
+ if os.path.exists(file_path_fam):
452
+ os.remove(file_path_fam)
453
+ except Exception as e:
454
+ st.error(f"Error displaying family graph: {e}")
455
+
456
+ # ----------------------------
457
+ # TAB 5 – Minimal Tone-Contrast Sets
458
+ # ----------------------------
459
+ with TAB5:
460
+ st.header(T['tab_minpairs'])
461
+ with st.expander(T['help_minpairs_title'], expanded=False):
462
+ st.markdown(T['help_minpairs_body'])
463
+
464
+ st.caption(T['minpairs_desc'])
465
+
466
+ if edge_df_f.empty:
467
+ st.warning(T['no_match_warning'])
468
+ else:
469
+ focus = st.selectbox(T['minpairs_contrast'], options=[T['contrast_any'], T['contrast_src'], T['contrast_dst']])
470
+ # Build groups where letters are the same (pinyin digits removed)
471
+ sub = df.copy()
472
+ sub = sub[sub['tone_pattern'].isin(selected_pairs) & sub['src_tone'].isin(selected_src) & sub['dst_tone'].isin(selected_dst)]
473
+ groups = sub.groupby('pinyin_base')
474
+ records = []
475
+ for base, block in groups:
476
+ if len(block) < 2: continue
477
+ # unique by tone pair
478
+ block_u = block.drop_duplicates(subset=['tone_pattern'])
479
+ # pairwise combinations
480
+ rows = block_u[['Verb','pinyin','English_Verb','tone_pattern']]
481
+ arr = rows.to_dict('records')
482
+ for i in range(len(arr)):
483
+ for j in range(i+1, len(arr)):
484
+ a, b = arr[i], arr[j]
485
+ s1, d1 = map(int, a['tone_pattern'].split('-'))
486
+ s2, d2 = map(int, b['tone_pattern'].split('-'))
487
+ cond = False
488
+ if focus == T['contrast_any']:
489
+ cond = (a['tone_pattern'] != b['tone_pattern'])
490
+ elif focus == T['contrast_src']:
491
+ cond = (s1 != s2)
492
+ elif focus == T['contrast_dst']:
493
+ cond = (d1 != d2)
494
+ if cond:
495
+ records.append({
496
+ 'pinyin_base': base,
497
+ 'A_Verb': a['Verb'], 'A_pinyin': a['pinyin'], 'A_tone': a['tone_pattern'], 'A_Eng': a['English_Verb'],
498
+ 'B_Verb': b['Verb'], 'B_pinyin': b['pinyin'], 'B_tone': b['tone_pattern'], 'B_Eng': b['English_Verb'],
499
+ })
500
+ mpairs = pd.DataFrame(records)
501
+ if mpairs.empty:
502
+ st.warning(T['no_match_warning'])
503
+ else:
504
+ st.dataframe(mpairs.head(300), use_container_width=True)
505
+ st.download_button(T['download_csv'], mpairs.to_csv(index=False).encode('utf-8'), file_name='minimal_pairs.csv', mime='text/csv')
506
+
507
+ # ----------------------------
508
+ # TAB 6 – Character Tone Profiles
509
+ # ----------------------------
510
+ with TAB6:
511
+ st.header(T['tab_charprof'])
512
+ with st.expander(T['help_charprof_title'], expanded=False):
513
+ st.markdown(T['help_charprof_body'])
514
+
515
+ st.caption(T['charprof_desc'])
516
+ all_chars = sorted(list(set(edge_df[['char1','char2']].values.flatten())))
517
+ sel_char = st.selectbox(T['charprof_select'], options=['']+all_chars)
518
+
519
+ if sel_char:
520
+ df_char_src = df[df['char1']==sel_char]
521
+ df_char_dst = df[df['char2']==sel_char]
522
+ # Profile
523
+ tone_counts = pd.Series(dtype=int)
524
+ tone_counts = df_char_src['src_tone'].value_counts().add(df_char_dst['dst_tone'].value_counts(), fill_value=0).astype(int)
525
+ tone_counts = tone_counts.sort_index()
526
+ prof_df = pd.DataFrame({'tone': tone_counts.index.astype(int), 'count': tone_counts.values})
527
+ st.subheader(T['tone_profile'])
528
+ fig = px.bar(prof_df, x='tone', y='count', text='count')
529
+ st.plotly_chart(fig, use_container_width=True)
530
+
531
+ col1, col2 = st.columns(2)
532
+ with col1:
533
+ st.metric(T['src_count'], int(len(df_char_src)))
534
+ st.dataframe(df_char_src[['Verb','pinyin','English_Verb','tone_pattern']].drop_duplicates(), use_container_width=True)
535
+ with col2:
536
+ st.metric(T['dst_count'], int(len(df_char_dst)))
537
+ st.dataframe(df_char_dst[['Verb','pinyin','English_Verb','tone_pattern']].drop_duplicates(), use_container_width=True)
538
+
539
+ # Quick buttons
540
+ st.subheader(T['quick_show'])
541
+ tlist = [1,2,3,4,5]
542
+ c1, c2 = st.columns(2)
543
+ with c1:
544
+ toneX = st.selectbox('X (src)', options=tlist, index=2)
545
+ sub = df[(df['char1']==sel_char) & (df['src_tone']==toneX)]
546
+ st.caption(T['show_src_to_any'].replace('X', str(toneX)))
547
+ st.dataframe(sub[['Verb','pinyin','English_Verb','tone_pattern']], use_container_width=True)
548
+ with c2:
549
+ toneY = st.selectbox('X (dst)', options=tlist, index=3)
550
+ sub2 = df[(df['char2']==sel_char) & (df['dst_tone']==toneY)]
551
+ st.caption(T['show_any_to_dst'].replace('X', str(toneY)))
552
+ st.dataframe(sub2[['Verb','pinyin','English_Verb','tone_pattern']], use_container_width=True)
553
+
554
+ # ----------------------------
555
+ # TAB 9 – Curriculum Builder
556
+ # ----------------------------
557
+ with TAB9:
558
+ st.header(T['tab_curriculum'])
559
+ with st.expander(T['help_curriculum_title'], expanded=False):
560
+ st.markdown(T['help_curriculum_body'])
561
+
562
+ st.caption(T['curriculum_desc'])
563
+
564
+ if edge_df_f.empty:
565
+ st.warning(T['no_match_warning'])
566
+ else:
567
+ colA, colB, colC = st.columns([1.3,1,1])
568
+ with colA:
569
+ choose_pairs = st.multiselect(T['deck_pairs'], options=selected_pairs or all_pairs, default=selected_pairs or all_pairs)
570
+ with colB:
571
+ deck_size = st.number_input(T['deck_size'], min_value=10, max_value=200, value=40, step=5)
572
+ with colC:
573
+ weighting = st.selectbox(T['weighting'], options=[T['weight_degree'], T['weight_uniform']])
574
+
575
+ # Build candidate pool
576
+ pool = edge_df_f[edge_df_f['tone_pattern'].isin(choose_pairs)].copy()
577
+ if pool.empty:
578
+ st.warning(T['no_match_warning'])
579
+ else:
580
+ # Weighting
581
+ if weighting == T['weight_degree']:
582
+ # degree on filtered graph
583
+ Gc = nx.DiGraph()
584
+ for _, r in pool.iterrows():
585
+ Gc.add_edge(r['char1'], r['char2'])
586
+ deg = {n: Gc.degree(n) for n in Gc.nodes()}
587
+ pool['deg_score'] = pool['char1'].map(deg).fillna(0) + pool['char2'].map(deg).fillna(0)
588
+ pool['score'] = 1 + np.log1p(pool['weight']) + 0.5*pool['deg_score']
589
+ else:
590
+ pool['score'] = 1.0
591
+ # Sample without replacement, proportional to score
592
+ pool = pool.sample(frac=1, random_state=42) # shuffle
593
+ probs = pool['score'] / pool['score'].sum()
594
+ k = min(int(deck_size), len(pool))
595
+ chosen_idx = np.random.default_rng(42).choice(pool.index, size=k, replace=False, p=probs)
596
+ deck = pool.loc[chosen_idx, ['Verb','pinyin','English_Verb','tone_pattern','char1','char2']].copy()
597
+ # Nice order: group by tone pair
598
+ deck = deck.sort_values(['tone_pattern']).reset_index(drop=True)
599
+
600
+ st.subheader(T['deck_table'])
601
+ st.dataframe(deck, use_container_width=True)
602
+ st.download_button(T['download_csv'], deck.to_csv(index=False).encode('utf-8'), file_name='tone_deck.csv', mime='text/csv')
pages/5_🎮_Playground.py ADDED
@@ -0,0 +1,500 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import numpy as np
4
+ from collections import defaultdict, Counter
5
+ from utils import page_header, load_data
6
+ import random
7
+
8
+ # ============================
9
+ # Page Config
10
+ # ============================
11
+ st.set_page_config(layout="wide", page_title="🎮 Verb Playground")
12
+
13
+ # ============================
14
+ # Translations (EN/ZH)
15
+ # ============================
16
+ I18N = {
17
+ 'en': {
18
+ 'title': "Verb Playground",
19
+ 'settings': "⚙️ Settings",
20
+ 'lang_select': "Select Language",
21
+ 'study': "🧠 Study",
22
+ 'study_tip': "Pick strong pivots (high degree). Click characters to add/remove them from your Practice List.",
23
+ 'top_starters': "Top Starters (as first char)",
24
+ 'top_enders': "Top Enders (as second char)",
25
+ 'char_explorer': "Character Explorer",
26
+ 'pick_char': "Pick a character",
27
+ 'as_start': "As Starter (A→•)",
28
+ 'as_end': "As Ender (•→B)",
29
+ 'add_pivot': "Add to Practice List",
30
+ 'remove_pivot': "Remove from Practice List",
31
+ 'practice_list': "Practice List",
32
+ 'play': "🎮 Play",
33
+ 'play_desc': "Connect the pivot with one option to form a valid verb.",
34
+ 'mode': "Game Mode",
35
+ 'mode_start': "Start Mode (pick second char)",
36
+ 'mode_end': "End Mode (pick first char)",
37
+ 'mode_mix': "Mixed",
38
+ 'opts_count': "Options per round",
39
+ 'lives': "Lives",
40
+ 'start_game': "Start New Game",
41
+ 'next_round': "Next Round",
42
+ 'skip_round': "Skip",
43
+ 'score': "Score",
44
+ 'streak': "Streak",
45
+ 'accuracy': "Accuracy",
46
+ 'attempts': "Attempts",
47
+ 'pivot': "Pivot",
48
+ 'choose_char': "Choose a character:",
49
+ 'correct': "Correct! +1",
50
+ 'wrong': "Oops! −1",
51
+ 'near_miss_reverse': "Near miss: BA exists, not AB",
52
+ 'no_valid_answers': "No valid answers for this pivot. Picking a new pivot…",
53
+ 'formed_table': "Formed Verbs (learning artifact)",
54
+ 'download_csv': "Download CSV",
55
+ 'game_over': "Game Over",
56
+ 'empty_data': "No data available.",
57
+ 'classification': "Semantic Class",
58
+ },
59
+ 'zh': {
60
+ 'title': "动词游乐场",
61
+ 'settings': "⚙️ 设置",
62
+ 'lang_select': "选择语言",
63
+ 'study': "🧠 学习",
64
+ 'study_tip': "先选择高连接度的枢纽字。点击汉字加入/移出练习单。",
65
+ 'top_starters': "高起始字(作首字)",
66
+ 'top_enders': "高收尾字(作尾字)",
67
+ 'char_explorer': "汉字浏览",
68
+ 'pick_char': "选择一个汉字",
69
+ 'as_start': "作为首字 (A→•)",
70
+ 'as_end': "作为尾字 (•→B)",
71
+ 'add_pivot': "加入练习单",
72
+ 'remove_pivot': "移出练习单",
73
+ 'practice_list': "练习单",
74
+ 'play': "🎮 练习",
75
+ 'play_desc': "将枢纽字与选项连接,若构成动词则得分。",
76
+ 'mode': "模式",
77
+ 'mode_start': "首字模式(选第二个字)",
78
+ 'mode_end': "尾字模式(选第一个字)",
79
+ 'mode_mix': "混合",
80
+ 'opts_count': "每轮选项数",
81
+ 'lives': "生命",
82
+ 'start_game': "开始新游戏",
83
+ 'next_round': "下一轮",
84
+ 'skip_round': "跳过",
85
+ 'score': "分数",
86
+ 'streak': "连击",
87
+ 'accuracy': "准确率",
88
+ 'attempts': "尝试次数",
89
+ 'pivot': "枢纽字",
90
+ 'choose_char': "请选择:",
91
+ 'correct': "正确!+1",
92
+ 'wrong': "可惜!−1",
93
+ 'near_miss_reverse': "差一点:存在 BA,不是 AB",
94
+ 'no_valid_answers': "该枢纽没有可连词,自动更换…",
95
+ 'formed_table': "已生成的动词(学习成果)",
96
+ 'download_csv': "下载 CSV",
97
+ 'game_over': "游戏结束",
98
+ 'empty_data': "没有可用数据。",
99
+ 'classification': "语义类别",
100
+ }
101
+ }
102
+
103
+ # ============================
104
+ # Helpers
105
+ # ============================
106
+
107
+ def ensure_cols(df: pd.DataFrame) -> pd.DataFrame:
108
+ if 'Chinese_Verbs' in df.columns and 'Verb' not in df.columns:
109
+ df = df.rename(columns={'Chinese_Verbs':'Verb'})
110
+ for col in ['char1','char2','Verb','pinyin','English_Verb']:
111
+ if col not in df.columns:
112
+ df[col] = None
113
+ return df
114
+
115
+
116
+ def parse_bilingual(text):
117
+ if isinstance(text, str) and '(' in text and ')' in text:
118
+ parts = text.split('(')
119
+ zh, en = parts[0], parts[1].replace(')', '')
120
+ return zh.strip(), en.strip()
121
+ return text, text
122
+
123
+
124
+ def build_tables(df: pd.DataFrame):
125
+ # aggregate by edge (char1,char2) to one example verb (+ class)
126
+ cols = ['char1','char2','Verb','pinyin','English_Verb']
127
+ if 'Classification_zh' in df.columns and 'Classification_en' in df.columns:
128
+ cols += ['Classification_zh','Classification_en']
129
+ tmp = df[cols].dropna(subset=['char1','char2']).copy()
130
+ tmp['count'] = 1
131
+ agg = { 'count':'sum','Verb':'first','pinyin':'first','English_Verb':'first' }
132
+ if 'Classification_zh' in tmp.columns:
133
+ agg['Classification_zh'] = 'first'; agg['Classification_en'] = 'first'
134
+ edges = (tmp.groupby(['char1','char2'], as_index=False).agg(agg))
135
+
136
+ # adjacency
137
+ forward = defaultdict(list)
138
+ reverse = defaultdict(list)
139
+ for _, r in edges.iterrows():
140
+ rec = {
141
+ 'other': r['char2'], 'verb': r['Verb'], 'pinyin': r['pinyin'], 'english': r['English_Verb'], 'count': int(r['count']),
142
+ 'cls_zh': r.get('Classification_zh'), 'cls_en': r.get('Classification_en')
143
+ }
144
+ forward[r['char1']].append(rec)
145
+ rec2 = {
146
+ 'other': r['char1'], 'verb': r['Verb'], 'pinyin': r['pinyin'], 'english': r['English_Verb'], 'count': int(r['count']),
147
+ 'cls_zh': r.get('Classification_zh'), 'cls_en': r.get('Classification_en')
148
+ }
149
+ reverse[r['char2']].append(rec2)
150
+
151
+ # degrees
152
+ out_deg = edges.groupby('char1')['char2'].nunique().to_dict()
153
+ in_deg = edges.groupby('char2')['char1'].nunique().to_dict()
154
+ all_chars = set(list(out_deg.keys()) + list(in_deg.keys()))
155
+ degree = {c: out_deg.get(c,0) + in_deg.get(c,0) for c in all_chars}
156
+ return edges, forward, reverse, out_deg, in_deg, degree
157
+
158
+
159
+ def pick_top_series(d: dict, n=20):
160
+ if not d:
161
+ return pd.DataFrame({'char':[], 'deg':[]})
162
+ s = pd.Series(d).sort_values(ascending=False).head(n)
163
+ return s.reset_index().rename(columns={'index':'char',0:'deg'})
164
+
165
+
166
+ def build_round(state, lang):
167
+ """Create one round based on current mode, practice pivots and data."""
168
+ L = I18N[lang]
169
+ rng = random.Random(state.get('seed', 42))
170
+ mode = state.get('mode','start')
171
+
172
+ # candidate pivot pool
173
+ pivot_pool = list(state['pivots']) if state['pivots'] else list(state['degree_sorted'])[:50]
174
+ if not pivot_pool:
175
+ state['round_msg'] = L['empty_data']
176
+ state['current'] = None
177
+ return
178
+
179
+ # choose mode if mixed
180
+ mode_used = rng.choice(['start','end']) if mode == 'mix' else mode
181
+
182
+ # try a few pivots to ensure valid answers
183
+ for _ in range(50):
184
+ pivot = rng.choice(pivot_pool)
185
+ if mode_used == 'start':
186
+ valid = state['forward'].get(pivot, [])
187
+ valid_set = {v['other'] for v in valid}
188
+ else:
189
+ valid = state['reverse'].get(pivot, [])
190
+ valid_set = {v['other'] for v in valid}
191
+ if len(valid_set) > 0:
192
+ break
193
+ else:
194
+ state['round_msg'] = L['no_valid_answers']
195
+ state['current'] = None
196
+ return
197
+
198
+ # Build options list
199
+ opts_target = state.get('opts_count', 8)
200
+ n_valid = min(max(2, opts_target//3), len(valid_set))
201
+ valid_choices = rng.sample(list(valid_set), n_valid)
202
+
203
+ # decoys: reversed-only + random none-edges
204
+ decoys = set()
205
+ all_chars = state['all_chars']
206
+ if mode_used == 'start':
207
+ reversed_only = {x['other'] for x in state['reverse'].get(pivot, [])} - valid_set
208
+ else:
209
+ reversed_only = {x['other'] for x in state['forward'].get(pivot, [])} - valid_set
210
+ rev_pick = rng.sample(list(reversed_only), min(len(reversed_only), max(1, opts_target//4))) if reversed_only else []
211
+ decoys.update(rev_pick)
212
+
213
+ # random decoys without edge in current direction
214
+ while len(valid_choices) + len(decoys) < opts_target:
215
+ c = rng.choice(list(all_chars))
216
+ if c == pivot or c in valid_set or c in decoys:
217
+ continue
218
+ decoys.add(c)
219
+
220
+ options = list(valid_choices) + list(decoys)
221
+ rng.shuffle(options)
222
+
223
+ # stash round
224
+ state['current'] = {
225
+ 'pivot': pivot,
226
+ 'mode_used': mode_used,
227
+ 'options': options,
228
+ 'valid_set': valid_set
229
+ }
230
+ state['round_msg'] = None
231
+
232
+
233
+ def handle_choice(state, choice, lang):
234
+ L = I18N[lang]
235
+ cur = state.get('current')
236
+ if not cur:
237
+ return
238
+ pivot = cur['pivot']
239
+ mode_used = cur['mode_used']
240
+ valid_set = cur['valid_set']
241
+
242
+ state['attempts'] += 1
243
+
244
+ correct = choice in valid_set
245
+ if correct:
246
+ state['score'] += 1
247
+ state['streak'] += 1
248
+ # append formed verb row with semantic class
249
+ if mode_used == 'start':
250
+ recs = state['forward'].get(pivot, [])
251
+ example = next((r for r in recs if r['other']==choice), None)
252
+ verb = example['verb'] if example else f"{pivot}{choice}"
253
+ pinyin = example['pinyin'] if example else ''
254
+ eng = example['english'] if example else ''
255
+ cls = example.get('cls_zh') if lang=='zh' else example.get('cls_en') if example else ''
256
+ row = {'char1': pivot, 'char2': choice, 'Verb': verb, 'pinyin': pinyin, 'English_Verb': eng, 'Mode': 'Start', 'Classification': cls}
257
+ else:
258
+ recs = state['reverse'].get(pivot, [])
259
+ example = next((r for r in recs if r['other']==choice), None)
260
+ verb = example['verb'] if example else f"{choice}{pivot}"
261
+ pinyin = example['pinyin'] if example else ''
262
+ eng = example['english'] if example else ''
263
+ cls = example.get('cls_zh') if lang=='zh' else example.get('cls_en') if example else ''
264
+ row = {'char1': choice, 'char2': pivot, 'Verb': verb, 'pinyin': pinyin, 'English_Verb': eng, 'Mode': 'End', 'Classification': cls}
265
+ state['formed'].append(row)
266
+ state['feedback'] = (True, L['correct'], row)
267
+ else:
268
+ state['score'] -= 1
269
+ state['streak'] = 0
270
+ state['lives'] -= 1
271
+ # near miss if reversed exists
272
+ reversed_ok = False
273
+ if mode_used == 'start':
274
+ reversed_ok = any(choice == r['other'] for r in state['reverse'].get(pivot, []))
275
+ else:
276
+ reversed_ok = any(choice == r['other'] for r in state['forward'].get(pivot, []))
277
+ msg = L['wrong'] + (f" — {L['near_miss_reverse']}" if reversed_ok else "")
278
+ state['feedback'] = (False, msg, None)
279
+
280
+
281
+ # ============================
282
+ # Load & Prepare Data
283
+ # ============================
284
+ @st.cache_data
285
+ def get_df():
286
+ return load_data()
287
+
288
+ df_raw = get_df()
289
+ if df_raw is None or df_raw.empty:
290
+ st.error("No data.")
291
+ st.stop()
292
+
293
+ df = ensure_cols(df_raw.copy())
294
+
295
+ # Bilingual classification
296
+ if '分类(Classification)' in df.columns:
297
+ df[['Classification_zh', 'Classification_en']] = df['分类(Classification)'].apply(lambda x: pd.Series(parse_bilingual(x)))
298
+
299
+ # Build everything once (no teacher filters)
300
+ edges, forward, reverse, out_deg, in_deg, degree = build_tables(df)
301
+ all_chars = set(list(degree.keys()))
302
+
303
+ # ============================
304
+ # Init session state
305
+ # ============================
306
+ if 'game' not in st.session_state:
307
+ st.session_state['game'] = {}
308
+ state = st.session_state['game']
309
+
310
+ # Static maps into state
311
+ state['forward'] = forward
312
+ state['reverse'] = reverse
313
+ state['all_chars'] = all_chars
314
+ state['degree_sorted'] = [c for c,_ in sorted(degree.items(), key=lambda kv:-kv[1])]
315
+
316
+ # Practice list
317
+ if 'pivots' not in state:
318
+ state['pivots'] = set()
319
+
320
+ # Game vars
321
+ state.setdefault('mode','start')
322
+ state.setdefault('opts_count', 8)
323
+ state.setdefault('lives', 3)
324
+ state.setdefault('score', 0)
325
+ state.setdefault('streak', 0)
326
+ state.setdefault('attempts', 0)
327
+ state.setdefault('formed', []) # list of dicts
328
+ state.setdefault('seed', 42)
329
+ state.setdefault('current', None)
330
+ state.setdefault('round_msg', None)
331
+ state.setdefault('feedback', None)
332
+
333
+ # Sidebar: language only (no teacher controls)
334
+ st.sidebar.header(I18N['en']['settings'] + " / " + I18N['zh']['settings'])
335
+ lang_options = {'English': 'en', '中文 (Chinese)': 'zh'}
336
+ selected_lang_display = st.sidebar.radio("Select Language / 选择语言", options=lang_options.keys(), horizontal=True)
337
+ lang = lang_options[selected_lang_display]
338
+ L = I18N[lang]
339
+
340
+ page_header(L['title'], "🎮")
341
+
342
+ # ============================
343
+ # STUDY EXPANDER
344
+ # ============================
345
+ with st.expander(L['study'], expanded=True):
346
+ st.caption(L['study_tip'])
347
+ colA, colB = st.columns(2)
348
+ with colA:
349
+ st.subheader(L['top_starters'])
350
+ top_out = pick_top_series(out_deg, n=20)
351
+ for _, r in top_out.iterrows():
352
+ c = r['char']; deg = int(r['deg'])
353
+ cols = st.columns([2,1])
354
+ with cols[0]:
355
+ st.write(f"**{c}** · out={deg} · in={in_deg.get(c,0)}")
356
+ with cols[1]:
357
+ if c in state['pivots']:
358
+ if st.button(f"− {L['remove_pivot']}", key=f"rm_start_{c}"):
359
+ state['pivots'].discard(c)
360
+ else:
361
+ if st.button(f"+ {L['add_pivot']}", key=f"add_start_{c}"):
362
+ state['pivots'].add(c)
363
+ with colB:
364
+ st.subheader(L['top_enders'])
365
+ top_in = pick_top_series(in_deg, n=20)
366
+ for _, r in top_in.iterrows():
367
+ c = r['char']; deg = int(r['deg'])
368
+ cols = st.columns([2,1])
369
+ with cols[0]:
370
+ st.write(f"**{c}** · in={deg} · out={out_deg.get(c,0)}")
371
+ with cols[1]:
372
+ if c in state['pivots']:
373
+ if st.button(f"− {L['remove_pivot']}", key=f"rm_end_{c}"):
374
+ state['pivots'].discard(c)
375
+ else:
376
+ if st.button(f"+ {L['add_pivot']}", key=f"add_end_{c}"):
377
+ state['pivots'].add(c)
378
+
379
+ st.markdown(f"**{L['practice_list']}:** " + ("、".join(sorted(state['pivots'])) if state['pivots'] else "—"))
380
+
381
+ st.subheader(L['char_explorer'])
382
+ char_options = sorted(list(all_chars))
383
+ sel_char = st.selectbox(L['pick_char'], options=['']+char_options)
384
+ if sel_char:
385
+ c1, c2 = st.columns(2)
386
+ with c1:
387
+ st.markdown(f"**{L['as_start']}**")
388
+ starts = pd.DataFrame(state['forward'].get(sel_char, []))
389
+ if not starts.empty:
390
+ starts = starts.rename(columns={'other':'char2','verb':'Verb','pinyin':'pinyin','english':'English_Verb','count':'freq','cls_zh':'Classification_zh','cls_en':'Classification_en'})
391
+ disp_cls = 'Classification_zh' if lang=='zh' else 'Classification_en'
392
+ cols = ['char2','Verb','pinyin','English_Verb','freq', disp_cls] if disp_cls in starts.columns else ['char2','Verb','pinyin','English_Verb','freq']
393
+ st.dataframe(starts[cols].head(50), use_container_width=True)
394
+ else:
395
+ st.info('—')
396
+ with c2:
397
+ st.markdown(f"**{L['as_end']}**")
398
+ ends = pd.DataFrame(state['reverse'].get(sel_char, []))
399
+ if not ends.empty:
400
+ ends = ends.rename(columns={'other':'char1','verb':'Verb','pinyin':'pinyin','english':'English_Verb','count':'freq','cls_zh':'Classification_zh','cls_en':'Classification_en'})
401
+ disp_cls = 'Classification_zh' if lang=='zh' else 'Classification_en'
402
+ cols = ['char1','Verb','pinyin','English_Verb','freq', disp_cls] if disp_cls in ends.columns else ['char1','Verb','pinyin','English_Verb','freq']
403
+ st.dataframe(ends[cols].head(50), use_container_width=True)
404
+ else:
405
+ st.info('—')
406
+ col_add = st.columns([1,3])[0]
407
+ with col_add:
408
+ if sel_char in state['pivots']:
409
+ if st.button(f"− {L['remove_pivot']}", key=f"rm_sel_{sel_char}"):
410
+ state['pivots'].discard(sel_char)
411
+ else:
412
+ if st.button(f"+ {L['add_pivot']}", key=f"add_sel_{sel_char}"):
413
+ state['pivots'].add(sel_char)
414
+
415
+ # ============================
416
+ # PLAY EXPANDER
417
+ # ============================
418
+ with st.expander(L['play'], expanded=False):
419
+ st.caption(L['play_desc'])
420
+ c1,c2,c3,c4,c5,c6 = st.columns([1.3,1,1,1,1,1])
421
+ with c1:
422
+ state['mode'] = st.selectbox(L['mode'], options=['start','end','mix'], format_func=lambda x: { 'start':L['mode_start'], 'end':L['mode_end'], 'mix':L['mode_mix']}[x], index=0)
423
+ with c2:
424
+ state['opts_count'] = st.slider(L['opts_count'], min_value=4, max_value=12, value=8, step=2)
425
+ with c3:
426
+ state['lives'] = st.number_input(L['lives'], min_value=1, max_value=10, value=int(state.get('lives',3)))
427
+ with c4:
428
+ if st.button(L['start_game']):
429
+ # reset game
430
+ state['score'] = 0
431
+ state['streak'] = 0
432
+ state['attempts'] = 0
433
+ state['formed'] = []
434
+ state['feedback'] = None
435
+ # build first round
436
+ build_round(state, lang)
437
+ with c5:
438
+ if st.button(L['next_round']):
439
+ state['feedback'] = None
440
+ build_round(state, lang)
441
+ with c6:
442
+ if st.button(L['skip_round']):
443
+ state['feedback'] = None
444
+ build_round(state, lang)
445
+
446
+ # Scoreboard
447
+ colS, colT, colA, colL = st.columns(4)
448
+ correct_n = len(state['formed'])
449
+ acc = (state['attempts'] and f"{(correct_n/state['attempts']*100):.0f}%") or "—"
450
+ colS.metric(L['score'], state['score'])
451
+ colT.metric(L['streak'], state['streak'])
452
+ colA.metric(L['accuracy'], acc)
453
+ colL.metric(L['lives'], state['lives'])
454
+
455
+ st.divider()
456
+
457
+ # Round area
458
+ cur = state.get('current')
459
+ if state.get('lives',0) <= 0:
460
+ st.subheader(f"🛑 {L['game_over']}")
461
+ elif cur is None:
462
+ st.info(state.get('round_msg') or L['empty_data'])
463
+ else:
464
+ st.subheader(f"{L['pivot']}: {cur['pivot']}")
465
+ st.caption({ 'start': L['mode_start'], 'end': L['mode_end'] }[cur['mode_used']])
466
+
467
+ # Options as buttons (grid)
468
+ opts = cur['options']
469
+ ncols = 4
470
+ rows = (len(opts) + ncols - 1)//ncols
471
+ idx = 0
472
+ for _ in range(rows):
473
+ cols = st.columns(ncols)
474
+ for c in cols:
475
+ if idx < len(opts):
476
+ val = opts[idx]
477
+ if c.button(val, key=f"opt_{idx}"):
478
+ handle_choice(state, val, lang)
479
+ idx += 1
480
+ # Feedback
481
+ if state.get('feedback'):
482
+ ok, msg, row = state['feedback']
483
+ if ok:
484
+ st.success(msg)
485
+ if row:
486
+ dfrow = pd.DataFrame([row])
487
+ st.table(dfrow[['Verb','pinyin','English_Verb','Classification','char1','char2','Mode']])
488
+ else:
489
+ st.error(msg)
490
+
491
+ # Formed verbs table (learning artifact)
492
+ st.subheader(L['formed_table'])
493
+ formed_df = pd.DataFrame(state['formed'])
494
+ if formed_df.empty:
495
+ st.info('—')
496
+ else:
497
+ cols = ['Verb','pinyin','English_Verb','Classification','char1','char2','Mode']
498
+ keep = [c for c in cols if c in formed_df.columns]
499
+ st.dataframe(formed_df[keep], use_container_width=True)
500
+ st.download_button(L['download_csv'], formed_df[keep].to_csv(index=False).encode('utf-8'), file_name='formed_verbs.csv', mime='text/csv')