| |
| import os |
| import gradio as gr |
| import re |
|
|
| |
| def build_family_tree(): |
| if not os.path.exists("genealogy.txt"): |
| return {}, {} |
| |
| with open("genealogy.txt", "r", encoding="utf-8") as f: |
| text = f.read() |
| |
| |
| child_to_parent = {} |
| |
| parent_to_children = {} |
| |
| blocks = text.split("——") |
| current_person = "" |
| |
| for block in blocks: |
| lines = [l.strip() for l in block.split("\n") if l.strip()] |
| current_person = "" |
| |
| for line in lines: |
| |
| if re.search(r"[冯陈胡秦杨李董周][\u4e00-\u9fa5]{1,4}", line): |
| match = re.search(r"[冯陈胡秦杨李董周][\u4e00-\u9fa5]{1,4}", line) |
| if match: |
| current_person = match.group(0) |
| |
| |
| if current_person: |
| father_match = re.search(r"[孝曾外][男孙玄曾][孙女]?\s*([冯陈胡秦杨李董周][\u4e00-\u9fa5]{1,4})", line) |
| if father_match: |
| father = father_match.group(1) |
| child_to_parent[current_person] = father |
| parent_to_children.setdefault(father, []).append(current_person) |
| |
| return child_to_parent, parent_to_children |
|
|
| CHILD_TO_PARENT, PARENT_TO_CHILDREN = build_family_tree() |
|
|
| |
| def query_relation(name, up=0, down=0): |
| if name not in CHILD_TO_PARENT and name not in PARENT_TO_CHILDREN: |
| return f"家谱里没找到「{name}」这个人" |
| |
| result = [f"【{name}】的关系查询结果:\n"] |
| |
| |
| current = name |
| for i in range(1, up + 1): |
| father = CHILD_TO_PARENT.get(current) |
| if not father: |
| result.append(f"往上第 {i} 代:未知(家谱未记录)") |
| break |
| titles = ["父亲,祖父,曾祖父,高祖父,天祖父,烈祖父"] |
| title = titles[i-1] if i <= 6 else f"第{i}代祖先" |
| result.append(f"{title}:{father}") |
| current = father |
| |
| |
| children = PARENT_TO_CHILDREN.get(name, []) |
| if down >= 1 and children: |
| result.append(f"\n儿子/女儿:{'、'.join(children) if children else '无'}") |
| if down >= 2: |
| grandchildren = [] |
| for child in children: |
| grandchildren.extend(PARENT_TO_CHILDREN.get(child, [])) |
| result.append(f"孙子/孙女:{'、'.join(grandchildren) if grandchildren else '无'}") |
| |
| return "\n".join(result) |
|
|
| def chat(message, history): |
| msg = message.strip() |
| |
| |
| up_match = re.search(r"(.+)[的的上]([0-9一二三四五六七八九十]+)代", msg) |
| if up_match: |
| name = up_match.group(1).replace("的","").replace("上","") |
| n_str = up_match.group(2) |
| n_map = {"一":1,"二":2,"三":3,"四":4,"五":5,"六":6,"七":7,"八":8,"九":9,"十":10} |
| n = n_map.get(n_str, 0) or int(n_str) if n_str.isdigit() else 3 |
| return query_relation(name, up=n) |
| |
| |
| down_match = re.search(r"(.+)[的下]([0-9一二三四五]+)代", msg) |
| if down_match: |
| name = down_match.group(1).replace("的","") |
| n_str = down_match.group(2) |
| n_map = {"一":1,"二":2,"三":3,"四":4,"五":5} |
| n = n_map.get(n_str, 0) or int(n_str) if n_str.isdigit() else 2 |
| return query_relation(name, down=n) |
| |
| |
| try: |
| with open("genealogy.txt", "r", encoding="utf-8") as f: |
| text = f.read() |
| lines = text.split("\n") |
| for i, line in enumerate(lines): |
| if message |