BloodGlucoseManagement / ui /ui_history_tab.py
DeepWeek's picture
Upload ui_history_tab.py
aa412a0 verified
import gradio as gr
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import pandas as pd
from datetime import datetime, timedelta
from sqlite_handler import load_records # DBからレコード読み込み
import matplotlib.font_manager as fm
import os
# 日本語フォント設定
font_path = "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc"
if os.path.exists(font_path):
jp_font = fm.FontProperties(fname=font_path)
plt.rcParams["font.family"] = jp_font.get_name()
else:
jp_font = None
def filter_data_by_range(df, days=None):
if days is None:
return df
limit = datetime.now() - timedelta(days=days)
return df[df["timestamp"] >= limit]
def plot_history_graph(period_option):
df = load_records()
if df.empty:
fig, ax = plt.subplots()
ax.set_title("データがありません", fontproperties=jp_font)
return fig
df["timestamp"] = pd.to_datetime(df["timestamp"])
if period_option != "全期間":
days = {"1日": 1, "1週間": 7, "1か月": 30}[period_option]
df = filter_data_by_range(df, days)
fig, ax1 = plt.subplots()
ax1.plot(df["timestamp"], df["current_bg"], label="血糖値", color="blue", marker="o")
ax1.set_ylabel("血糖値 (mg/dL)", fontproperties=jp_font, color="blue")
ax1.tick_params(axis='y', labelcolor='blue')
ax2 = ax1.twinx()
ax2.plot(df["timestamp"], df["total_insulin"], label="インスリン", color="red", marker="x")
ax2.set_ylabel("インスリン量 (単位)", fontproperties=jp_font, color="red")
ax2.tick_params(axis='y', labelcolor='red')
ax1.set_title(f"血糖値とインスリン量の推移({period_option})", fontproperties=jp_font)
ax1.set_xlabel("日時", fontproperties=jp_font)
fig.autofmt_xdate()
return fig
def get_recent_table():
df = load_records()
if df.empty:
return pd.DataFrame()
df["timestamp"] = pd.to_datetime(df["timestamp"])
week_ago = datetime.now() - timedelta(days=7)
df_week = df[df["timestamp"] >= week_ago]
return df_week[["timestamp", "current_bg", "total_insulin"]].fillna("")
def get_insulin_summary():
df = load_records()
if df.empty:
return "データがありません"
df["timestamp"] = pd.to_datetime(df["timestamp"])
two_weeks_ago = datetime.now() - timedelta(days=14)
df_recent = df[df["timestamp"] >= two_weeks_ago]
total = df_recent["total_insulin"].fillna(0).sum()
return f"直近2週間のインスリン合計: {total:.1f} 単位"
def create_history_tab():
with gr.Tab("履歴管理"):
with gr.Row():
period_selector = gr.Radio(choices=["1日", "1週間", "1か月", "全期間"], value="1週間", label="表示期間")
plot = gr.Plot()
table = gr.Dataframe(headers=["日時", "血糖値", "インスリン量"], interactive=False)
insulin_summary = gr.Textbox(label="インスリン統計", interactive=False)
period_selector.change(fn=plot_history_graph, inputs=period_selector, outputs=plot)
period_selector.change(fn=get_recent_table, inputs=None, outputs=table)
period_selector.change(fn=get_insulin_summary, inputs=None, outputs=insulin_summary)