medicineYH / app.py
ake178178's picture
Update app.py
a923270 verified
import gradio as gr
import json
import os
from datetime import datetime
# 定义JSON文件路径
JSON_FILE = "1.json"
# 初始化JSON文件
def initialize_json():
if not os.path.exists(JSON_FILE):
with open(JSON_FILE, 'w') as f:
json.dump([], f)
# 读取JSON文件
def read_json():
with open(JSON_FILE, 'r') as f:
data = json.load(f)
return data
# 写入JSON文件
def write_json(data):
with open(JSON_FILE, 'w') as f:
json.dump(data, f, indent=4)
# 记录事件
def record_event(event_type):
data = read_json()
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
data.append({"timestamp": timestamp, "event": event_type})
write_json(data)
return data
# 删除记录
def delete_record(index):
data = read_json()
if 0 <= index < len(data):
data.pop(index)
write_json(data)
return data
# 显示记录
def display_records():
data = read_json()
return "\n".join([f"{i}: {item['timestamp']} - {item['event']}" for i, item in enumerate(data)])
# Gradio界面
def main():
initialize_json()
with gr.Blocks() as demo:
gr.Markdown("## 狗狗日常记录")
with gr.Row():
poop_btn = gr.Button("拉屎", variant="primary")
pee_btn = gr.Button("尿尿", variant="secondary")
eat_all_btn = gr.Button("全吃了", variant="success")
eat_half_btn = gr.Button("吃了一半", variant="warning")
eat_none_btn = gr.Button("没吃", variant="danger")
output = gr.Textbox(label="记录", interactive=False)
delete_index = gr.Number(label="删除记录的索引", precision=0)
delete_btn = gr.Button("删除记录")
poop_btn.click(lambda: record_event("拉屎"), None, output, queue=False)
pee_btn.click(lambda: record_event("尿尿"), None, output, queue=False)
eat_all_btn.click(lambda: record_event("全吃了"), None, output, queue=False)
eat_half_btn.click(lambda: record_event("吃了一半"), None, output, queue=False)
eat_none_btn.click(lambda: record_event("没吃"), None, output, queue=False)
delete_btn.click(lambda idx: delete_record(int(idx)), delete_index, output, queue=False)
output.update(display_records())
demo.launch()
if __name__ == "__main__":
main()