Spaces:
Running
Running
File size: 1,957 Bytes
d296a79 |
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 |
import sqlite3
from datetime import datetime, timedelta, timezone
from config import LOCAL_DB_PATH
import hf_db_sync
import pandas as pd
DEFAULT_USER_ID = "0001"
def save_result_to_db(carb_grams, current_bg, icr, isf, result, actual_insulin, timing_id, timestamp_text=None):
hf_db_sync.download_and_prepare_db()
if timestamp_text:
try:
timestamp = datetime.strptime(timestamp_text, "%Y-%m-%d %H:%M")
except ValueError:
return "❌ 日時の形式が正しくありません(例: 2025-04-22 14:30)"
else:
JST = timezone(timedelta(hours=9))
timestamp = datetime.now(JST)
timestamp_str = timestamp.strftime('%Y-%m-%d %H:%M:%S')
conn = sqlite3.connect(LOCAL_DB_PATH)
cursor = conn.cursor()
cursor.execute("""
INSERT INTO records (
user_id, timestamp, carbs, current_bg, icr, isf,
carb_insulin, correction_insulin, total_insulin, target_bg, timing_id
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""", (
DEFAULT_USER_ID,
timestamp_str,
carb_grams,
current_bg,
icr,
isf,
result["carb_insulin"],
result["correction_insulin"],
actual_insulin,
result["expected_bg"],
timing_id
))
conn.commit()
conn.close()
hf_db_sync.upload_db_to_dataset()
return f"✅ 記録しました(インスリン {actual_insulin} 単位, タイミング ID: {timing_id})"
def load_records():
try:
hf_db_sync.download_and_prepare_db()
conn = sqlite3.connect(LOCAL_DB_PATH)
query = """
SELECT * FROM records ORDER BY timestamp
"""
df = pd.read_sql_query(query, conn)
conn.close()
if not df.empty:
df["timestamp"] = pd.to_datetime(df["timestamp"])
return df
except Exception as e:
print(f"❌ DB読み込みエラー: {e}")
return pd.DataFrame()
|