File size: 2,907 Bytes
7d8b657
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import json
import os
import gradio as gr

# ==============================
# 1. 加载数据函数
# ==============================
def load_student_data():
    """尝试从不同路径加载数据,兼容HF Space的环境"""
    possible_paths = [
        'data/students.json',
        './data/students.json',
        '../data/students.json'
    ]
    
    for path in possible_paths:
        try:
            with open(path, 'r', encoding='utf-8') as f:
                data = json.load(f)
            print(f"✅ 成功加载数据,共 {len(data)} 位同学")
            return data, None
        except Exception as e:
            print(f"❌ 尝试加载 {path} 失败: {e}")
            continue
    return [], "❌ 未找到同学数据文件 students.json"

# ==============================
# 2. 查询处理函数
# ==============================
def query_student(name_input):
    students_db, error_msg = load_student_data()
    if error_msg:
        return error_msg
    
    # 如果用户没输入名字
    if not name_input.strip():
        return "请输入同学的姓名进行查询。"
    
    # 简单的模糊匹配 (支持输入“李”查询所有姓李的)
    results = [student for student in students_db if name_input.strip() in student['name']]
    
    if not results:
        return f"🔍 抱歉,没有找到包含 '{name_input}' 的同学,请检查姓名是否输入正确。"
    
    # 构建漂亮的回复消息
    response = f"🔍 **查询结果 (共找到 {len(results)} 位):**\n\n"
    for student in results:
        status_map = {
            "有联系": "✅",
            "无法联系": "❓",
            "已去世": "🕯️"
        }
        status_icon = status_map.get(student['status'], "")
        
        response += f"---\n"
        response += f"**{student['name']}** {status_icon}\n"
        response += f"- 状态: {student['status']}\n"
        
        if student['phone']:
            response += f"- 电话: {student['phone']}\n"
        elif student['status'] == "已去世":
            response += f"- 备注: 愿逝者安息 🕯️\n"
        else:
            response += f"- 提示: 暂无联系方式\n"
    
    return response

# ==============================
# 3. 构建 Gradio 界面
# ==============================
with gr.Blocks(title="成都二中初59级二班同学查询系统") as demo:
    gr.Markdown("# 🏫 成都二中初59级二班同学查询机器人")
    gr.Markdown("输入同学姓名,点击查询,寻找失联多年的老友。")
    
    with gr.Row():
        inp = gr.Textbox(placeholder="在此输入同学姓名,如:阎国蜀", label="查询输入")
        out = gr.Markdown(label="查询结果")
    
    btn = gr.Button("🔍 查询同学")
    btn.click(fn=query_student, inputs=inp, outputs=out)

# 这是 HF Space 的启动入口
if __name__ == "__main__":
    demo.launch()