| import gradio as gr |
| import json |
| import os |
|
|
| |
| DATA_PATH = "data/students.json" |
| PHOTO_DIR = "data/photos" |
|
|
| def load_data(): |
| if os.path.exists(DATA_PATH): |
| with open(DATA_PATH, 'r', encoding='utf-8') as f: |
| return json.load(f) |
| return [] |
|
|
| students_data = load_data() |
|
|
| def search_student(name): |
| |
| target_name = name.strip() |
| result = next((s for s in students_data if s["name"] == target_name), None) |
| |
| if not result: |
| return "❌ 未找到该同学信息", "", "无", None |
| |
| |
| stu_class = result.get("class", "初59级二班") |
| status = result.get("status", "未知") |
| phone = result.get("phone", "").strip() |
| photo_path = result.get("photo", "") |
| |
| |
| info_html = f""" |
| <div style='line-height: 1.8; font-size: 16px;'> |
| <b>基本信息:</b><br> |
| 📍 班级:{stu_class}<br> |
| 📌 状态:{status} |
| </div> |
| """ |
| |
| phone_display = phone if phone else "未登记" |
| |
| |
| if not photo_path or not os.path.exists(photo_path): |
| display_photo = None |
| else: |
| display_photo = photo_path |
|
|
| return info_html, phone_display, display_photo |
|
|
| |
| with gr.Blocks(title="初59级二班同学录") as demo: |
| gr.Markdown("# 🎓 初59级二班同学信息查询系统") |
| gr.Markdown("---") |
| |
| with gr.Row(): |
| with gr.Column(scale=1): |
| input_name = gr.Textbox(label="输入同学姓名", placeholder="请输入完整姓名...", lines=1) |
| search_btn = gr.Button("🔍 立即查询", variant="primary") |
| output_phone = gr.Label(label="联系电话") |
| |
| with gr.Column(scale=2): |
| output_info = gr.HTML(label="详细状态") |
| output_photo = gr.Image(label="同学照片", type="filepath") |
|
|
| |
| search_btn.click( |
| fn=search_student, |
| inputs=input_name, |
| outputs=[output_info, output_phone, output_photo] |
| ) |
| |
| |
| input_name.submit( |
| fn=search_student, |
| inputs=input_name, |
| outputs=[output_info, output_phone, output_photo] |
| ) |
|
|
| if __name__ == "__main__": |
| demo.launch() |