fdbw commited on
Commit
aa36715
·
verified ·
1 Parent(s): fd0c55e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +67 -73
app.py CHANGED
@@ -2,114 +2,108 @@ import gradio as gr
2
  import json
3
  from collections import defaultdict
4
 
5
- def build_family_groups():
6
- """
7
- 构建家庭:每个家庭由 (丈夫, 妻子, [子女]) 组成
8
- 策略:
9
- 1. 所有记录:{name -> {father: ..., info: ...}}
10
- 2. 找出所有“子女”:他们的 father 是 A
11
- 3. 找出所有“妻子”:她们的 father 是 A,但她们自己也是母亲(有子女)
12
- 4. 丈夫 A 必须是男性(通过是否有同名作为 father 判断)
13
- """
14
  people = {} # name -> record
15
- children_of = defaultdict(list) # father_name -> [(child_name, info)]
16
 
17
- # 第一步:加载所有人
18
  try:
19
  with open('family_data.jsonl', 'r', encoding='utf-8') as f:
20
  for line in f:
21
  line = line.strip()
22
- if not line: continue
 
23
  try:
24
  rec = json.loads(line)
25
  name = rec.get('n')
26
- if not name: continue
27
- people[name] = {
28
- 'f': rec.get('f'),
29
- 'info': rec.get('info', '')
30
- }
31
- father = rec.get('f')
32
- if father and father != "无":
33
- children_of[father].append((name, rec.get('info', '')))
34
  except:
35
  continue
36
  except Exception as e:
37
- return [{"error": str(e)}]
38
 
39
- # 第二步:找出所有“为人父母”的人(即他们的名字在 children_of 中作为 key 出现)
40
- is_parent = set(children_of.keys())
 
 
 
 
 
41
 
42
- # 第三步:构建家庭
43
  families = []
 
44
 
45
- # 遍历所有可能的丈夫(即所有有子女的人)
46
- for husband in sorted(is_parent):
47
- if husband == "无" or husband not in people:
48
  continue
 
49
 
50
- # 获取所有挂在他名下的人(包括子女和可能的妻子)
51
- related = children_of[husband]
52
- spouse = None
53
- children = []
54
-
55
- for name, info in related:
56
- # 如果这个人自己也是父母(有子女),则很可能是妻子(儿媳/配偶)
57
- if name in is_parent:
58
- # 优先作为配偶
59
- if spouse is None:
60
- spouse = name
61
- # 如果已有配偶,后续的可能是儿媳等,暂不处理
62
- else:
63
- children.append((name, info))
64
 
65
- # 去重子女
66
- children = list(set(children))
67
- children.sort(key=lambda x: x[0]) # 按名字排序
 
 
 
 
 
68
 
69
- # 只有当有子女或有配偶时才展示
70
- if children or spouse:
71
- families.append({
72
- "husband": husband,
73
- "wife": spouse or "(请补充配偶)",
74
- "children": children
75
- })
76
 
 
 
77
  return families
78
 
79
- def format_output():
80
- families = build_family_groups()
 
 
 
81
 
82
- if not families or (len(families) == 1 and "error" in families[0]):
83
- error_msg = families[0].get("error", "未知错误")
84
- return f"❌ 加��失败:{error_msg}"
85
 
86
- lines = ["# 冯氏家族关系网家网成员表\n"]
87
 
88
  for fam in families:
89
- h = fam["husband"]
90
- w = fam["wife"]
91
- kids = fam["children"]
 
 
92
 
93
- lines.append(f"### {h} 家庭")
94
- lines.append(f"- **父亲**:{h}")
95
- lines.append(f"- **母亲**:{w}")
 
96
  lines.append("- **子女**:")
97
- if kids:
98
- for name, info in kids:
99
- lines.append(f" - {name} — {info}")
100
  else:
101
- lines.append(" - (暂无子女记录)")
102
- lines.append("")
103
-
104
  return "\n".join(lines)
105
 
106
  # Gradio 应用
107
  demo = gr.Interface(
108
- fn=format_output,
109
  inputs=None,
110
- outputs=gr.Markdown(label="冯氏家族关系网"),
111
- title="冯氏家族关系网家网成员表",
112
- description="点击 **Generate** 查看所有以男性户主为核心的家庭"
113
  )
114
 
115
  if __name__ == "__main__":
 
2
  import json
3
  from collections import defaultdict
4
 
5
+ def load_families_from_jsonl():
 
 
 
 
 
 
 
 
6
  people = {} # name -> record
7
+ children_by_parents = defaultdict(list) # (father, mother) -> [child]
8
 
 
9
  try:
10
  with open('family_data.jsonl', 'r', encoding='utf-8') as f:
11
  for line in f:
12
  line = line.strip()
13
+ if not line:
14
+ continue
15
  try:
16
  rec = json.loads(line)
17
  name = rec.get('n')
18
+ if not name:
19
+ continue
20
+ people[name] = rec
 
 
 
 
 
21
  except:
22
  continue
23
  except Exception as e:
24
+ return {"__ERROR__": f"无法读取 family_data.jsonl: {e}"}
25
 
26
+ # 第二步:按父母分组子女
27
+ for name, rec in people.items():
28
+ father = rec.get('f')
29
+ mother = rec.get('m')
30
+ # 只有同时有父亲和母亲的才归入家庭(可根据需要放宽)
31
+ if father and mother and father != "无" and mother != "无":
32
+ children_by_parents[(father, mother)].append((name, rec.get('info', '')))
33
 
34
+ # 第三步:构建家庭列表
35
  families = []
36
+ seen_parents = set()
37
 
38
+ for (father, mother), children in children_by_parents.items():
39
+ if (father, mother) in seen_parents:
 
40
  continue
41
+ seen_parents.add((father, mother))
42
 
43
+ # 获取父母的完整信息
44
+ father_info = people.get(father, {}).get('info', '')
45
+ mother_info = people.get(mother, {}).get('info', '')
 
 
 
 
 
 
 
 
 
 
 
46
 
47
+ # 去重并排序子女(按 info 中的年份或名字)
48
+ unique_children = list(set(children))
49
+ # 尝试按出生年份排序
50
+ def extract_year(info):
51
+ import re
52
+ match = re.search(r'(19\d{2}|20\d{2}|18\d{2})', str(info))
53
+ return int(match.group(1)) if match else 9999
54
+ unique_children.sort(key=lambda x: extract_year(x[1]))
55
 
56
+ families.append({
57
+ "father": father,
58
+ "father_info": father_info,
59
+ "mother": mother,
60
+ "mother_info": mother_info,
61
+ "children": unique_children
62
+ })
63
 
64
+ # 按父亲名字排序
65
+ families.sort(key=lambda x: x["father"])
66
  return families
67
 
68
+ def format_family_output():
69
+ families = load_families_from_jsonl()
70
+
71
+ if isinstance(families, dict) and "__ERROR__" in families:
72
+ return families["__ERROR__"]
73
 
74
+ if not families:
75
+ return "未找到任何家庭数据。请检查 family_data.jsonl 格式是否正确。"
 
76
 
77
+ lines = ["# 冯氏家族关系网 · 家庭成员表\n"]
78
 
79
  for fam in families:
80
+ f_name = fam["father"]
81
+ m_name = fam["mother"]
82
+ f_info = fam["father_info"]
83
+ m_info = fam["mother_info"]
84
+ children = fam["children"]
85
 
86
+ # 家庭标题
87
+ lines.append(f"## {f_name} & {m_name} 家庭")
88
+ lines.append(f"- **父亲**:{f_name}({f_info})")
89
+ lines.append(f"- **母亲**:{m_name}({m_info})")
90
  lines.append("- **子女**:")
91
+ if children:
92
+ for child_name, child_info in children:
93
+ lines.append(f" - {child_name} — {child_info}")
94
  else:
95
+ lines.append(" - (无子女记录)")
96
+ lines.append("") # 空行分隔
97
+
98
  return "\n".join(lines)
99
 
100
  # Gradio 应用
101
  demo = gr.Interface(
102
+ fn=format_family_output,
103
  inputs=None,
104
+ outputs=gr.Markdown(label="家庭成员表"),
105
+ title="冯氏家族关系网 · 家庭成员表",
106
+ description="点击 **Generate** 查看所有以父母为单位的家庭(数据来自 family_data.jsonl)"
107
  )
108
 
109
  if __name__ == "__main__":