Sidhi2512's picture
Update app.py
400b5a2 verified
import gradio as gr
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import torch
from transformers import AutoImageProcessor, AutoModelForImageClassification
from PIL import Image
from difflib import get_close_matches
from typing import Optional, Dict, Any
import json
import io
from datasets import load_dataset # Import the datasets library
# -------------------------------------------------
# Configuration
# -------------------------------------------------
# Define insulin types and their durations and peak times
INSULIN_TYPES = {
"Rapid-Acting": {"onset": 0.25, "duration": 4, "peak_time": 1.0}, # Onset in hours, duration in hours, peak time in hours
"Long-Acting": {"onset": 2, "duration": 24, "peak_time": 8},
}
#Define basal rates
DEFAULT_BASAL_RATES = {
"00:00-06:00": 0.8,
"06:00-12:00": 1.0,
"12:00-18:00": 0.9,
"18:00-24:00": 0.7
}
# -------------------------------------------------
# Load Food Data from Hugging Face Dataset
# -------------------------------------------------
def load_food_data(dataset_name="Anupam007/Diabetic"):
try:
dataset = load_dataset(dataset_name)
food_data = dataset['train'].to_pandas()
# Normalize column names to lowercase
food_data.columns = [col.lower() for col in food_data.columns]
# Remove unnamed columns
food_data = food_data.loc[:, ~food_data.columns.str.contains('^unnamed')]
# Check if "fiber_grams" and "sugar_grams" are not in the dataset
if "fiber_grams" not in food_data.columns:
food_data['fiber_grams'] = None
if "sugar_grams" not in food_data.columns:
food_data['sugar_grams'] = None
# Normalize food_name column to lowercase: Crucial for matching
if 'food_name' in food_data.columns:
food_data['food_name'] = food_data['food_name'].str.lower()
print("Unique Food Names in Dataset:")
print(food_data['food_name'].unique())
else:
print("Warning: 'food_name' column not found in dataset.")
food_data = pd.DataFrame({
'food_category': ['starch'],
'food_subcategory': ['bread'],
'food_name': ['white bread'],
'serving_description': ['servingsize'],
'serving_amount': [29],
'serving_unit': ['g'],
'carbohydrate_grams': [15],
'fiber_grams': [0], #added column
'sugar_grams': [0], #added column
'notes': ['default']
})
#Print first 5 rows to check columns and values
print("First 5 rows of loaded data from Hugging Face Dataset:")
print(food_data.head())
return food_data
except Exception as e:
print(f"Error loading Hugging Face Dataset: {e}")
# Provide minimal default data in case of error
food_data = pd.DataFrame({
'food_category': ['starch'],
'food_subcategory': ['bread'],
'food_name': ['white bread'],
'serving_description': ['servingsize'],
'serving_amount': [29],
'serving_unit': ['g'],
'carbohydrate_grams': [15],
'fiber_grams': [0], #added column
'sugar_grams': [0], #added column
'notes': ['default']
})
return food_data
# -------------------------------------------------
# Load Food Classification Model
# -------------------------------------------------
try:
processor = AutoImageProcessor.from_pretrained("google/vit-base-patch16-224")
model = AutoModelForImageClassification.from_pretrained(
"google/vit-base-patch16-224",
torch_dtype=torch.float16, # Use float16 for efficiency
device_map="cpu", # Run on CPU
low_cpu_mem_usage=True # Optimize memory usage
)
model_loaded = True #Flag for error handling in other defs
except Exception as e:
print(f"Model Load Error: {e}") # include e in print statement
model_loaded = False
processor = None
model = None
def classify_food(image):
"""Classify food image using the pre-trained model"""
print("classify_food function called") # Check if this function is even called
try:
if not model_loaded:
print("Model not loaded, returning 'Unknown'")
return "Unknown"
print(f"Image type: {type(image)}") # Check the type of the image
if isinstance(image, np.ndarray):
print("Image is a numpy array, converting to PIL Image")
image = Image.fromarray(image)
print(f"Image mode: {image.mode}") # Check image mode (e.g., RGB, L)
inputs = processor(images=image, return_tensors="pt")
print(f"Processed image: {inputs}") # Print the output of the processor
with torch.no_grad():
outputs = model(**inputs)
predicted_idx = torch.argmax(outputs.logits, dim=-1).item()
food_name = model.config.id2label.get(predicted_idx, "Unknown Food")
print(f"Predicted food name before lower: {food_name}")
food_name = food_name.lower() # Convert classification to lowercase
print(f"Predicted food name after lower: {food_name}") # Print the predicted food name
return food_name
except Exception as e:
print(f"Classify food error: {e}") # Print the full error message
return "Unknown" # If an exception arises make sure to create a default case
# -------------------------------------------------
# USDA API Integration - REMOVED for local HF Spaces deployment
# -------------------------------------------------
def get_food_nutrition(food_name: str, food_data, portion_size: float = 1.0) -> Optional[Dict[str, Any]]:
"""Get carbohydrate content for the given food, and also sugar and fiber"""
print("get_food_nutrition function called") # Ensure the function is called
try:
# First try the local CSV database
food_name_lower = food_name.lower() # Ensure input is also lowercase
food_names = food_data['food_name'].str.lower().tolist()
print(f"Searching for: {food_name_lower}")
matches = get_close_matches(food_name_lower, food_names, n=1, cutoff=0.5)
print(f"Matches found: {matches}")
if matches:
matched_row = food_data[food_data['food_name'].str.lower() == matches[0]]
if not matched_row.empty:
row = matched_row.iloc[0]
print(f"Matched row from CSV: {row}")
carb_col = 'carbohydrate_grams'
amount_col = 'serving_amount'
unit_col = 'serving_unit'
fiber_col = 'fiber_grams' # Added Fiber column
sugar_col = 'sugar_grams' # Added Sugar column
base_carbs = row.get(carb_col, 0.0) if pd.notna(row.get(carb_col, None)) else 0.0
base_fiber = row.get(fiber_col, 0.0) if pd.notna(row.get(fiber_col, None)) else 0.0
base_sugar = row.get(sugar_col, 0.0) if pd.notna(row.get(sugar_col, None)) else 0.0
if amount_col not in row or unit_col not in row or pd.isna(row[amount_col]) or pd.isna(row[unit_col]):
serving_size = "Unknown"
print(f"Warning: '{amount_col}' or '{unit_col}' is missing in CSV")
else:
serving_size = f"{row[amount_col]} {row[unit_col]}"
adjusted_carbs = base_carbs * portion_size
adjusted_fiber = base_fiber * portion_size
adjusted_sugar = base_sugar * portion_size
return {
'matched_food': row['food_name'],
'category': row['food_category'] if 'food_category' in row and not pd.isna(row['food_category']) else 'Unknown',
'subcategory': row['food_subcategory'] if 'food_subcategory' in row and not pd.isna(row['food_subcategory']) else 'Unknown',
'base_carbs': base_carbs,
'adjusted_carbs': adjusted_carbs,
'base_fiber': base_fiber,
'adjusted_fiber': adjusted_fiber,
'base_sugar': base_sugar,
'adjusted_sugar': adjusted_sugar,
'serving_size': serving_size,
'portion_multiplier': portion_size,
'notes': row['notes'] if 'notes' in row and not pd.isna(row['notes']) else ''
}
print(f"No match found in CSV for {food_name}")
print(f"No nutrition information found for {food_name} in the local database.")
return None
except Exception as e:
print(f"Error in get_food_nutrition: {e}")
return None
def create_detailed_report(nutrition_info, insulin_info, current_basal_rate):
"""Create a detailed report of carbs and insulin calculations"""
carb_details = f"""
FOOD DETAILS:
-------------
Detected Food: {nutrition_info['matched_food']}
Category: {nutrition_info['category']}
Subcategory: {nutrition_info['subcategory']}
CARBOHYDRATE INFORMATION:
------------------------
Standard Serving Size: {nutrition_info['serving_size']}
Carbs per Serving: {nutrition_info['base_carbs']}g
Adjusted Carbs: {nutrition_info['adjusted_carbs']}g
Fiber per Serving: {nutrition_info['base_fiber']}g
Adjusted Fiber: {nutrition_info['adjusted_fiber']}g
Sugar per Serving: {nutrition_info['base_sugar']}g
Adjusted Sugar: {nutrition_info['adjusted_sugar']}g
Portion Multiplier: {nutrition_info['portion_multiplier']}x
Notes: {nutrition_info['notes']}
"""
insulin_details = f"""
INSULIN CALCULATIONS:
--------------------
ICR (Insulin to Carb Ratio): 1:{insulin_info['icr']}
ISF (Insulin Sensitivity Factor): 1:{insulin_info['isf']}
Insulin Type: {insulin_info['insulin_type']}
Onset: {insulin_info['insulin_onset']} hours
Duration: {insulin_info['insulin_duration']} hours
Peak Time: {insulin_info['peak_time']} hours
RECOMMENDED DOSES:
-----------------
Correction Dose: {insulin_info['correction_dose']} units
Carb Dose: {insulin_info['carb_dose']} units
Total Bolus: {insulin_info['total_bolus']} units
Daily Basal: {insulin_info['basal_dose']} units
Current Basal Rate: {current_basal_rate} units/hour
"""
return carb_details, insulin_details
# -------------------------------------------------
# Main Dashboard Function
# -------------------------------------------------
def diabetes_dashboard(initial_glucose, food_image, stress_level, sleep_hours, time_hours,
weight, tdd, target_glucose, exercise_duration, exercise_intensity, portion_size, insulin_type,
override_correction_dose, extended_bolus_duration, basal_rates_input):
"""Main dashboard function"""
try:
# 0. Load Files
food_data = load_food_data() #loads HF Datasets from the function
# 1. Food Classification and Carb Calculation
food_name = classify_food(food_image) # This line is now inside the function
print(f"Classified food name: {food_name}") # Debugging: What is classified as? # Corrected indentation
nutrition_info = get_food_nutrition(food_name, food_data, portion_size) # Changed to pass in data
if not nutrition_info:
# Try with generic categories if specific food not found
generic_terms = food_name.split()
for term in generic_terms:
nutrition_info = get_food_nutrition(term, food_data, portion_size) # Changed to pass in data
if nutrition_info:
break
if not nutrition_info:
return (
f"Could not find nutrition information for: {food_name} in the local database", # Removed USDA ref
"No insulin calculations available",
None,
None,
None
)
# 2. Insulin Calculations
try:
basal_rates_dict = json.loads(basal_rates_input)
except Exception as e: # added exception handling
print(f"Basal rates JSON invalid, using default. Error: {e}")
basal_rates_dict = DEFAULT_BASAL_RATES
insulin_info = calculate_insulin_needs(
nutrition_info['adjusted_carbs'],
initial_glucose,
target_glucose,
tdd,
weight,
insulin_type,
override_correction_dose # Pass override
)
if 'error' in insulin_info:
return insulin_info['error'], None, None, None, None
# 3. Create detailed reports
current_time_for_basal = 12 #Arbitrary number to pull from Basal Rates Dict
current_basal_rate = get_basal_rate(current_time_for_basal, basal_rates_dict) # Added basal rate to the function and report.
carb_details, insulin_details = create_detailed_report(nutrition_info, insulin_info, current_basal_rate)
# 4. Glucose Prediction
hours = list(range(time_hours))
glucose_levels = []
current_glucose = initial_glucose
insulin_history = [] # This will store all past doses for active insulin calculations
# simulate that a dose has just been given to the patient at t=0
insulin_history.append((0, insulin_info['total_bolus'], insulin_info['insulin_type'], extended_bolus_duration)) # Pass bolus duration
for t in hours:
# Factor in carbs effect (peaks at 1-2 hours)
carb_effect = nutrition_info['adjusted_carbs'] * 0.1 * np.exp(-(t - 1.5) ** 2 / 2)
# Factor in insulin effect (peaks at 2-3 hours)
# Original model: insulin_effect = insulin_info['total_bolus'] * 2 * np.exp(-(t-2.5)**2/2)
# get effect based on amount of insulin still active from previous boluses
active_insulin = calculate_active_insulin(insulin_history, t)
insulin_effect = insulin_activity(t, insulin_type, active_insulin, extended_bolus_duration) # Pass bolus duration
# Get the basal effect
basal_rate = get_basal_rate(t, basal_rates_dict)
basal_insulin_effect = basal_rate # Units per hour
# Add stress effect
stress_effect = stress_level * 2
# Add sleep effect
sleep_effect = abs(8 - sleep_hours) * 5
# Add exercise effect
exercise_effect = (exercise_duration / 60) * exercise_intensity * 2
# Calculate glucose with all factors
glucose = (current_glucose + carb_effect - insulin_effect +
stress_effect + sleep_effect + exercise_effect - basal_insulin_effect)
glucose_levels.append(max(70, min(400, glucose)))
current_glucose = glucose_levels[-1]
# 5. Create visualization
fig, ax = plt.subplots(figsize=(12, 6))
ax.plot(hours, glucose_levels, 'b-', label='Predicted Glucose')
ax.axhline(y=target_glucose, color='g', linestyle='--', label='Target')
ax.fill_between(hours, [70] * len(hours), [180] * len(hours),
alpha=0.1, color='g', label='Target Range')
ax.set_ylabel('Glucose (mg/dL)')
ax.set_xlabel('Hours')
ax.set_title('Predicted Blood Glucose Over Time')
ax.legend()
ax.grid(True)
return (
carb_details,
insulin_details,
insulin_info['basal_dose'],
insulin_info['total_bolus'],
fig
)
except Exception as e:
return f"Error: {str(e)}", None, None, None, None
# -------------------------------------------------
# Gradio Interface Setup
# -------------------------------------------------
with gr.Blocks() as app: # using Blocks API to manually design the layout
gr.Markdown("# Type 1 Diabetes Management Dashboard")
with gr.Tab("Glucose & Meal"):
with gr.Row():
initial_glucose = gr.Number(label="Current Blood Glucose (mg/dL)", value=120)
food_image = gr.Image(label="Food Image", type="pil") # Now a file upload
with gr.Row():
portion_size = gr.Slider(0.1, 3, step=0.1, label="Portion Size Multiplier", value=1.0)
with gr.Tab("Insulin"):
with gr.Column(): # Place inputs in a column layout
insulin_type = gr.Dropdown(choices=list(INSULIN_TYPES.keys()), label="Insulin Type", value="Rapid-Acting")
override_correction_dose = gr.Number(label="Override Correction Dose (Units)", value=None)
extended_bolus_duration = gr.Number(label="Extended Bolus Duration (Hours)", value=0)
with gr.Tab("Basal Settings"):
with gr.Column():
basal_rates_input = gr.Textbox(label="Basal Rates (JSON)", lines=3,
value="""{"00:00-06:00": 0.8, "06:00-12:00": 1.0, "12:00-18:00": 0.9, "18:00-24:00": 0.7}""")
with gr.Tab("Other Factors"):
with gr.Accordion("Factors affecting Glucose levels", open=False): # keep advanced options collapsed by default
weight = gr.Number(label="Weight (kg)", value=70)
tdd = gr.Number(label="Total Daily Dose (TDD) of insulin (units)", value=40)
target_glucose = gr.Number(label="Target Blood Glucose (mg/dL)", value=100)
stress_level = gr.Slider(1, 10, step=1, label="Stress Level (1-10)", value=1)
sleep_hours = gr.Number(label="Sleep Hours", value=7)
exercise_duration = gr.Number(label="Exercise Duration (minutes)", value=0)
exercise_intensity = gr.Slider(1, 10, step=1, label="Exercise Intensity (1-10)", value=1)
with gr.Row():
time_hours = gr.Slider(1, 24, step=1, label="Prediction Time (hours)", value=6)
with gr.Row():
calculate_button = gr.Button("Calculate")
with gr.Column():
carb_details_output = gr.Textbox(label="Carbohydrate Details", lines=5)
insulin_details_output = gr.Textbox(label="Insulin Calculation Details", lines=5)
basal_dose_output = gr.Number(label="Basal Insulin Dose (units/day)")
bolus_dose_output = gr.Number(label="Bolus Insulin Dose (units)")
glucose_plot_output = gr.Plot(label="Glucose Prediction")
calculate_button.click(
fn=diabetes_dashboard,
inputs=[
initial_glucose,
food_image,
stress_level,
sleep_hours,
time_hours,
weight,
tdd,
target_glucose,
exercise_duration,
exercise_intensity,
portion_size,
insulin_type,
override_correction_dose,
extended_bolus_duration,
basal_rates_input,
],
outputs=[
carb_details_output,
insulin_details_output,
basal_dose_output,
bolus_dose_output,
glucose_plot_output
]
)
if __name__ == "__main__":
app.launch(share=True)