PulseGlucose / app.py
Anupam007's picture
Update app.py
2f3dd26 verified
# app.py (for Hugging Face Spaces)
import gradio as gr
import numpy as np
import random
from datetime import datetime
import pandas as pd
# Simulated glucose log
glucose_log = []
# Mock CGM data (simulates Dexcom-like readings)
def fetch_mock_cgm_reading():
base = random.uniform(150, 250) # Type 1 diabetic range (e.g., your 201 mg/dL)
variability = random.uniform(-30, 30)
return base + variability
# Prediction and analysis function
def glucothumb_predict(calibrate_value=None):
global glucose_log
try:
# Fetch mock CGM reading
current_glucose = fetch_mock_cgm_reading()
# Apply calibration if provided
if calibrate_value is not None:
calibration_offset = calibrate_value - current_glucose
current_glucose = calibrate_value
else:
calibration_offset = 0
# Clamp to realistic range
current_glucose = max(50, min(400, current_glucose))
# Log the reading
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
glucose_log.append({"Time": timestamp, "Glucose (mg/dL)": current_glucose})
# Trend analysis (last 5 readings)
if len(glucose_log) > 1:
df = pd.DataFrame(glucose_log[-5:])
avg_glucose = df["Glucose (mg/dL)"].mean()
trend = "Rising" if df["Glucose (mg/dL)"].iloc[-1] > df["Glucose (mg/dL)"].iloc[-2] else "Falling"
high_alert = "High Alert!" if current_glucose > 250 else ""
low_alert = "Low Alert!" if current_glucose < 70 else ""
summary = f"Average (last 5): {avg_glucose:.2f} mg/dL\nTrend: {trend}\n{high_alert}{low_alert}"
else:
summary = "Initial reading logged. Add more for trends."
# Shareable log
log_text = "\n".join([f"{entry['Time']}: {entry['Glucose (mg/dL)']:.2f} mg/dL" for entry in glucose_log])
return (
f"Current Blood Sugar Level: {current_glucose:.2f} mg/dL (Simulated CGM Data)",
summary,
log_text
)
except Exception as e:
return f"Error: {str(e)}", "", ""
# Gradio interface
interface = gr.Interface(
fn=glucothumb_predict,
inputs=[
gr.Number(label="Calibrate with Known Glucose (Optional, e.g., 201 mg/dL)", value=None)
],
outputs=[
gr.Textbox(label="Current Glucose"),
gr.Textbox(label="Trend Analysis & Alerts"),
gr.Textbox(label="Glucose Log (Share with Doctor)")
],
title="GlucoThumb",
description="Simulates real-time blood sugar monitoring for Type 1 diabetes using mock CGM data. Calibrate with a known value (e.g., 201 mg/dL) if desired. Click 'Submit' to refresh. Note: Demo only—replace with Dexcom API for real data.",
live=False
)
# Launch the app
interface.launch()