AimanGh commited on
Commit
ed40612
·
1 Parent(s): 840f7f8
pages/1_🕸️_Character_Network(汉字网络).py CHANGED
@@ -8,9 +8,6 @@ import os
8
  import streamlit.components.v1 as components
9
  import json
10
 
11
-
12
-
13
-
14
  # ----------------------------
15
  # Page Configuration
16
  # ----------------------------
@@ -26,13 +23,13 @@ translations = {
26
  'settings_header': "⚙️ Settings",
27
  'language_select': "Select Language",
28
  'controls_header': "🔍 Controls",
29
- 'filter_by_tone': "Filter by Tone Pattern",
30
  'highlight_char': "Select Character to Analyze",
31
  'no_match_warning': "No data to display for the current selection.",
32
  'network_header': "Interactive Character Network",
33
  'network_desc': """
34
- This graph visualizes how characters form verbs. Use the dropdown menu at the top of the graph to filter characters by their most common verb category.
35
- - **Nodes:** Single Chinese characters, colored by category.
36
  - **Edges:** An arrow indicates a verb is formed (e.g., A → B means the verb is 'AB').
37
  """,
38
  'generating_network': "Generating network graph...",
@@ -47,7 +44,7 @@ translations = {
47
  'tab_families': "🧩 Word Families",
48
  'tab_stats': "🔢 Character Statistics",
49
  'learning_pathways_header': "Data-Driven Learning Pathways",
50
- 'learning_pathways_desc': "Use network science to find the most important characters to learn first. This analysis is based on the currently filtered data.",
51
  'centrality_expander': "🔑 Most Connected Characters (Degree Centrality)",
52
  'centrality_desc': "**Why it matters:** These are 'super-connector' characters. Learning them first helps you recognize and form the largest number of verbs quickly.",
53
  'betweenness_expander': "🌉 Key Bridging Characters (Betweenness Centrality)",
@@ -70,14 +67,14 @@ translations = {
70
  'settings_header': "⚙️ 设置",
71
  'language_select': "选择语言",
72
  'controls_header': "🔍 控制面板",
73
- 'filter_by_tone': "按声调模式筛选",
74
  'highlight_char': "选择要分析的汉字",
75
  'no_match_warning': "没有符合当前筛选条件的数据。",
76
  'network_header': "互动汉字网络",
77
  'network_desc': """
78
- 此图可视化了汉字如何构成动词。使用图上方的下拉菜单可以按最常见的动词类别筛选汉字。
79
- - **节点:** 单个汉字,按类别着色。
80
- - **边:** 箭头表示构成一个动词 (例如 A → B 意味着动词是'AB')。
81
  """,
82
  'generating_network': "正在生成网络图...",
83
  'char_stats_header': "汉字统计浏览器",
@@ -91,17 +88,17 @@ translations = {
91
  'tab_families': "🧩 词族",
92
  'tab_stats': "🔢 汉字统计",
93
  'learning_pathways_header': "数据驱动的学习路径",
94
- 'learning_pathways_desc': "利用网络科学找出最重要的汉字,优先学习。此分析基于当前筛选的数据。",
95
- 'centrality_expander': "🔑 连接最多的核心字 (度中心性)",
96
- 'centrality_desc': "**重要性:** 这些是“超级连接词”。优先学习它们可以帮助您最快地识别和构成最多的动词。",
97
- 'betweenness_expander': "🌉 关键桥梁字 (中介中心性)",
98
- 'betweenness_desc': "**重要性:** 这些汉字如同桥梁,连接着不同的词族。掌握它们有助于将不同的词汇集联系在一起。",
99
  'character_col': "汉字",
100
  'score_col': "得分",
101
  'in_degree_col': "作尾字次数",
102
  'out_degree_col': "作首字次数",
103
  'families_header': "词族浏览器",
104
- 'families_desc': "通过社群检测算法,我们可以发现内部联系紧密的汉字集群。将这些“词族”一起学习可能是一种有效的策略。",
105
  'family_select': "选择一个词族进行探索",
106
  'family_members': "词族成员",
107
  'family_verbs_header': "该词族内的动词",
@@ -155,17 +152,18 @@ def parse_bilingual(text):
155
  return zh.strip(), en.strip()
156
  return text, text
157
 
 
158
  df[['Classification_zh', 'Classification_en']] = df['分类(Classification)'].apply(lambda x: pd.Series(parse_bilingual(x)))
159
  df.rename(columns={'Chinese_Verbs': 'Verb'}, inplace=True)
160
  classification_col_display = 'Classification_zh' if lang == 'zh' else 'Classification_en'
161
 
162
- # --- Sidebar Filters ---
163
  st.sidebar.header(T['controls_header'])
164
- unique_tone_patterns = sorted(df['tone_pattern'].unique())
165
- selected_tones = st.sidebar.multiselect(T['filter_by_tone'], options=unique_tone_patterns, default=unique_tone_patterns)
166
 
167
- # Filter by tone only, as category filter is now in the graph
168
- filtered_df = df[df['tone_pattern'].isin(selected_tones)].copy()
169
  G = build_graph(filtered_df)
170
 
171
  # ----------------------------
@@ -182,11 +180,7 @@ with tab1:
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'])
189
-
190
  degrees = dict(G.degree())
191
  min_degree, max_degree = (1, 1)
192
  if degrees:
@@ -201,12 +195,19 @@ with tab1:
201
  for node, deg in degrees.items()
202
  }
203
 
204
- net = Network(height='750px', width='100%', notebook=False, directed=True,
205
- cdn_resources='in_line', select_menu=True, filter_menu=True)
 
 
 
 
206
  for node, size in normalized_degrees.items():
207
- classification = df.loc[(df['char1'] == node) | (df['char2'] == node), classification_col_display].iloc[0]
 
 
208
  net.add_node(node, label=node, size=size, font={'size': size + 10}, group=classification)
209
 
 
210
  for _, row in filtered_df.iterrows():
211
  if row['char1'] and row['char2']:
212
  net.add_edge(row['char1'], row['char2'], title=row['Verb'])
@@ -219,7 +220,7 @@ with tab1:
219
  st.components.v1.html(source_code, height=800)
220
  os.remove(file_path)
221
  except Exception as e:
222
- st.error(T['network_error'].format(e=e))
223
  else:
224
  st.warning(T['no_match_warning'])
225
 
@@ -330,7 +331,11 @@ with tab4:
330
  col3.metric(T['total_verbs_metric'], G.degree(selected_char))
331
 
332
  with st.expander(T['verbs_list_expander']):
333
- st.dataframe(filtered_df[(filtered_df['char1'] == selected_char) | (filtered_df['char2'] == selected_char)][['Verb', 'pinyin', 'English_Verb', classification_col_display]].drop_duplicates(), use_container_width=True)
 
 
 
 
 
334
  else:
335
  st.info(T['select_char_prompt'])
336
-
 
8
  import streamlit.components.v1 as components
9
  import json
10
 
 
 
 
11
  # ----------------------------
12
  # Page Configuration
13
  # ----------------------------
 
23
  'settings_header': "⚙️ Settings",
24
  'language_select': "Select Language",
25
  'controls_header': "🔍 Controls",
26
+ 'filter_by_class': "Filter by Verb Class",
27
  'highlight_char': "Select Character to Analyze",
28
  'no_match_warning': "No data to display for the current selection.",
29
  'network_header': "Interactive Character Network",
30
  'network_desc': """
31
+ This graph visualizes how characters form verbs. Use the sidebar to **filter by verb class**.
32
+ - **Nodes:** Single Chinese characters, colored by class.
33
  - **Edges:** An arrow indicates a verb is formed (e.g., A → B means the verb is 'AB').
34
  """,
35
  'generating_network': "Generating network graph...",
 
44
  'tab_families': "🧩 Word Families",
45
  'tab_stats': "🔢 Character Statistics",
46
  'learning_pathways_header': "Data-Driven Learning Pathways",
47
+ 'learning_pathways_desc': "Use network science to find the most important characters to learn first. Analysis uses the current class filter.",
48
  'centrality_expander': "🔑 Most Connected Characters (Degree Centrality)",
49
  'centrality_desc': "**Why it matters:** These are 'super-connector' characters. Learning them first helps you recognize and form the largest number of verbs quickly.",
50
  'betweenness_expander': "🌉 Key Bridging Characters (Betweenness Centrality)",
 
67
  'settings_header': "⚙️ 设置",
68
  'language_select': "选择语言",
69
  'controls_header': "🔍 控制面板",
70
+ 'filter_by_class': "按动词类别筛选",
71
  'highlight_char': "选择要分析的汉字",
72
  'no_match_warning': "没有符合当前筛选条件的数据。",
73
  'network_header': "互动汉字网络",
74
  'network_desc': """
75
+ 此图展示汉字如何构成动词。请使用侧栏按**动词类别**进行筛选。
76
+ - **节点:** 单个汉字,按类别着色。
77
+ - **边:** 箭头表示构成一个动词(例如 A → B 表示“AB”)。
78
  """,
79
  'generating_network': "正在生成网络图...",
80
  'char_stats_header': "汉字统计浏览器",
 
88
  'tab_families': "🧩 词族",
89
  'tab_stats': "🔢 汉字统计",
90
  'learning_pathways_header': "数据驱动的学习路径",
91
+ 'learning_pathways_desc': "利用网络科学找出最重要的汉字,优先学习。分析基于当前的类别筛选。",
92
+ 'centrality_expander': "🔑 连接最多的核心字(度中心性)",
93
+ 'centrality_desc': "**重要性:** 这些是“超级连接词”。优先学习它们有助于快速识别和构成更多动词。",
94
+ 'betweenness_expander': "🌉 关键桥梁字(中介中心性)",
95
+ 'betweenness_desc': "**重要性:** 这些汉字如桥梁,连接不同词族。掌握它们有助于把不同词汇集联系在一起。",
96
  'character_col': "汉字",
97
  'score_col': "得分",
98
  'in_degree_col': "作尾字次数",
99
  'out_degree_col': "作首字次数",
100
  'families_header': "词族浏览器",
101
+ 'families_desc': "通过社群检测算法,我们可以发现内部联系紧密的汉字集群。将这些“词族”一起学习可能是一种有效策略。",
102
  'family_select': "选择一个词族进行探索",
103
  'family_members': "词族成员",
104
  'family_verbs_header': "该词族内的动词",
 
152
  return zh.strip(), en.strip()
153
  return text, text
154
 
155
+ # Bilingual classification
156
  df[['Classification_zh', 'Classification_en']] = df['分类(Classification)'].apply(lambda x: pd.Series(parse_bilingual(x)))
157
  df.rename(columns={'Chinese_Verbs': 'Verb'}, inplace=True)
158
  classification_col_display = 'Classification_zh' if lang == 'zh' else 'Classification_en'
159
 
160
+ # --- Sidebar Filters (by class) ---
161
  st.sidebar.header(T['controls_header'])
162
+ unique_classes = sorted(df[classification_col_display].dropna().unique())
163
+ selected_classes = st.sidebar.multiselect(T['filter_by_class'], options=unique_classes, default=unique_classes)
164
 
165
+ # Filter data by selected classes
166
+ filtered_df = df[df[classification_col_display].isin(selected_classes)].copy()
167
  G = build_graph(filtered_df)
168
 
169
  # ----------------------------
 
180
 
181
  if not filtered_df.empty:
182
  with st.spinner(T['generating_network']):
183
+ # Compute node sizes from degree on filtered graph
 
 
 
 
184
  degrees = dict(G.degree())
185
  min_degree, max_degree = (1, 1)
186
  if degrees:
 
195
  for node, deg in degrees.items()
196
  }
197
 
198
+ net = Network(
199
+ height='750px', width='100%', notebook=False, directed=True,
200
+ cdn_resources='in_line', select_menu=True, filter_menu=True
201
+ )
202
+
203
+ # Add nodes, colored/grouped by class (from filtered data, fallback to full df)
204
  for node, size in normalized_degrees.items():
205
+ # try filtered_df first; if node not present (edge case), fallback to df
206
+ pool = filtered_df if ((filtered_df['char1'] == node) | (filtered_df['char2'] == node)).any() else df
207
+ classification = pool.loc[(pool['char1'] == node) | (pool['char2'] == node), classification_col_display].iloc[0]
208
  net.add_node(node, label=node, size=size, font={'size': size + 10}, group=classification)
209
 
210
+ # Add edges for filtered set
211
  for _, row in filtered_df.iterrows():
212
  if row['char1'] and row['char2']:
213
  net.add_edge(row['char1'], row['char2'], title=row['Verb'])
 
220
  st.components.v1.html(source_code, height=800)
221
  os.remove(file_path)
222
  except Exception as e:
223
+ st.error(f"Error displaying network graph: {e}")
224
  else:
225
  st.warning(T['no_match_warning'])
226
 
 
331
  col3.metric(T['total_verbs_metric'], G.degree(selected_char))
332
 
333
  with st.expander(T['verbs_list_expander']):
334
+ st.dataframe(
335
+ filtered_df[
336
+ (filtered_df['char1'] == selected_char) | (filtered_df['char2'] == selected_char)
337
+ ][['Verb', 'pinyin', 'English_Verb', classification_col_display]].drop_duplicates(),
338
+ use_container_width=True
339
+ )
340
  else:
341
  st.info(T['select_char_prompt'])