GlycoAI
AI-Powered Glucose Insights
Demo Users + Dexcom Sandbox OAuth • Chat with AI for personalized glucose insights
#!/usr/bin/env python3
"""
GlycoAI - AI-Powered Glucose Insights
Complete application with Demo Users + Dexcom Sandbox OAuth
IMPROVED UI VERSION - Clean, readable design with blue theme
"""
import gradio as gr
import plotly.graph_objects as go
import plotly.express as px
from datetime import datetime, timedelta
import pandas as pd
from typing import Optional, Tuple, List
import logging
import os
# Load environment variables from .env file
from dotenv import load_dotenv
load_dotenv()
# Import the Mistral chat class and unified data manager
from mistral_chat import GlucoBuddyMistralChat, validate_environment
from unified_data_manager import UnifiedDataManager
# Setup logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Import our custom functions
from apifunctions import (
DexcomAPI,
GlucoseAnalyzer,
DEMO_USERS,
format_glucose_data_for_display
)
# Import Dexcom Sandbox OAuth
try:
from dexcom_sandbox_oauth import DexcomSandboxIntegration, DexcomSandboxUser
DEXCOM_SANDBOX_AVAILABLE = True
logger.info("✅ Dexcom Sandbox OAuth available")
except ImportError as e:
DEXCOM_SANDBOX_AVAILABLE = False
logger.warning(f"⚠️ Dexcom Sandbox OAuth not available: {e}")
class GlycoAIApp:
"""Main application class for GlycoAI with demo users AND Dexcom Sandbox OAuth"""
def __init__(self):
# Validate environment before initializing
if not validate_environment():
raise ValueError("Environment validation failed - check your .env file or environment variables")
# Single data manager for consistency
self.data_manager = UnifiedDataManager()
# Chat interface (will use data manager's context)
self.mistral_chat = GlucoBuddyMistralChat()
# Dexcom Sandbox OAuth API
self.dexcom_sandbox = DexcomSandboxIntegration() if DEXCOM_SANDBOX_AVAILABLE else None
# UI state
self.chat_history = []
self.current_user_type = None # "demo" or "dexcom_sandbox"
def select_demo_user(self, user_key: str) -> Tuple[str, str]:
"""Handle demo user selection and load data consistently"""
if user_key not in DEMO_USERS:
return "❌ Invalid user selection", gr.update(visible=False)
try:
# Load data through unified manager
load_result = self.data_manager.load_user_data(user_key)
if not load_result['success']:
return f"❌ {load_result['message']}", gr.update(visible=False)
user = self.data_manager.current_user
self.current_user_type = "demo"
# Update Mistral chat with the same context
self._sync_chat_with_data_manager()
# Clear chat history when switching users
self.chat_history = []
self.mistral_chat.clear_conversation()
return (
f"✅ Connected: {user.name} ({user.device_type}) - Demo Data",
gr.update(visible=True)
)
except Exception as e:
logger.error(f"Demo user selection failed: {str(e)}")
return f"❌ Connection failed: {str(e)}", gr.update(visible=False)
def initialize_chat_with_prompts(self) -> List:
"""Initialize chat with demo prompts as conversation bubbles"""
if not self.data_manager.current_user:
return [
[None, "👋 Welcome to GlycoAI! Please select a demo user or connect Dexcom Sandbox to get started."],
[None, "💡 Once you load your glucose data, I'll provide personalized insights about your patterns and trends."]
]
templates = self.get_template_prompts()
# Create initial conversation with demo prompts
initial_chat = [
[None, f"👋 Hi! I'm ready to analyze {self.data_manager.current_user.name}'s glucose data. Here are some quick ways to get started:"],
[None, f"🎯 **{templates[0] if templates else 'Analyze my recent glucose patterns and trends'}**"],
[None, f"⚡ **{templates[1] if len(templates) > 1 else 'What can I do to improve my glucose control?'}**"],
[None, f"🍽️ **What are some meal management strategies for better glucose control?**"],
[None, "💬 You can click on any of these questions above, or ask me anything about glucose management!"]
]
return initial_chat
def handle_demo_prompt_click(self, prompt_text: str, history: List) -> Tuple[str, List]:
"""Handle clicking on demo prompts in chat"""
# Remove the emoji and formatting from the prompt
clean_prompt = prompt_text.replace("🎯 **", "").replace("⚡ **", "").replace("🍽️ **", "").replace("**", "")
# Process the prompt as if user typed it
return self.chat_with_mistral(clean_prompt, history)
def start_dexcom_sandbox_oauth(self) -> str:
"""Start Dexcom Sandbox OAuth process"""
if not DEXCOM_SANDBOX_AVAILABLE:
return """
❌ **Dexcom Sandbox OAuth Not Available**
The Dexcom Sandbox authentication module is not properly configured.
Please ensure:
1. dexcom_sandbox_oauth.py exists and imports correctly
2. You have valid Dexcom developer credentials
3. All dependencies are installed
For now, please use the demo users above for instant access to realistic glucose data.
"""
try:
# Start OAuth flow for Dexcom Sandbox
auth_url = self.dexcom_sandbox.oauth.generate_auth_url()
# Try to open browser automatically
try:
import webbrowser
webbrowser.open(auth_url)
browser_status = "✅ Browser opened automatically"
except:
browser_status = "⚠️ Please open the URL manually"
return f"""
🚀 **Dexcom Sandbox OAuth Started**
{browser_status}
**🌐 OAuth URL:** {auth_url}
**Step-by-Step Instructions:**
1. Browser should open automatically (or open URL above)
2. Select a sandbox user from the dropdown (SandboxUser6 recommended)
3. Click "Authorize" to grant access
4. **You will get a 404 error - THIS IS EXPECTED!**
5. Copy the COMPLETE callback URL from address bar
**Example callback URL:**
`http://localhost:7860/callback?code=ABC123XYZ&state=sandbox_test`
**Important:** Copy the entire URL (not just the code part)!
"""
except Exception as e:
logger.error(f"Dexcom Sandbox OAuth start error: {e}")
return f"❌ OAuth error: {str(e)}"
def complete_dexcom_sandbox_oauth(self, callback_url_input: str) -> Tuple[str, str]:
"""Complete Dexcom Sandbox OAuth with full callback URL"""
if not DEXCOM_SANDBOX_AVAILABLE:
return "❌ Dexcom Sandbox OAuth not available", gr.update(visible=False)
if not callback_url_input or not callback_url_input.strip():
return "❌ Please paste the complete callback URL", gr.update(visible=False)
try:
callback_url = callback_url_input.strip()
logger.info(f"Processing Dexcom Sandbox callback: {callback_url[:50]}...")
# Use Dexcom Sandbox OAuth completion
status_message, show_interface = self.dexcom_sandbox.complete_oauth(callback_url)
if show_interface:
logger.info("✅ Dexcom Sandbox OAuth successful")
# Load Dexcom Sandbox data into data manager
sandbox_data_result = self._load_dexcom_sandbox_data()
if sandbox_data_result['success']:
self.current_user_type = "dexcom_sandbox"
# Update chat context
self._sync_chat_with_data_manager()
# Clear chat history for new user
self.chat_history = []
self.mistral_chat.clear_conversation()
return (
f"✅ Connected: Dexcom Sandbox User - OAuth Authenticated",
gr.update(visible=True)
)
else:
return f"❌ Dexcom Sandbox data loading failed: {sandbox_data_result['message']}", gr.update(visible=False)
else:
logger.error(f"Dexcom Sandbox OAuth failed: {status_message}")
return f"❌ {status_message}", gr.update(visible=False)
except Exception as e:
logger.error(f"Dexcom Sandbox OAuth completion error: {e}")
return f"❌ OAuth completion failed: {str(e)}", gr.update(visible=False)
def _load_dexcom_sandbox_data(self) -> dict:
"""Load Dexcom Sandbox data through the unified data manager"""
try:
# Get Dexcom Sandbox user profile
sandbox_profile = self.dexcom_sandbox.get_user_profile()
if not sandbox_profile:
return {
'success': False,
'message': 'No Dexcom Sandbox user profile available'
}
# Set in data manager (compatible with existing structure)
self.data_manager.current_user = sandbox_profile
self.data_manager.data_source = "dexcom_sandbox_oauth"
self.data_manager.data_loaded_at = datetime.now()
logger.info("✅ Dexcom Sandbox data integrated with data manager")
return {
'success': True,
'message': 'Dexcom Sandbox user profile loaded successfully'
}
except Exception as e:
logger.error(f"Failed to load Dexcom Sandbox data: {e}")
return {
'success': False,
'message': f'Failed to load OAuth data: {str(e)}'
}
def load_glucose_data(self) -> Tuple[str, go.Figure, str]:
"""Load and display glucose data using unified manager with notifications"""
if not self.data_manager.current_user:
return "Please select a user first (demo or Dexcom Sandbox)", None, ""
try:
# For Dexcom Sandbox users, load real data via OAuth
if self.current_user_type == "dexcom_sandbox":
overview, chart = self._load_dexcom_sandbox_glucose_data()
else:
# For demo users, force reload data to ensure freshness
load_result = self.data_manager.load_user_data(
self._get_current_user_key(),
force_reload=True
)
if not load_result['success']:
return load_result['message'], None, ""
# Get unified stats and build display
overview, chart = self._build_glucose_display()
# Create notification message based on user and data quality
notification = self._create_data_loaded_notification()
return overview, chart, notification
except Exception as e:
logger.error(f"Failed to load glucose data: {str(e)}")
return f"Failed to load glucose data: {str(e)}", None, ""
def _create_data_loaded_notification(self) -> str:
"""Create appropriate notification based on loaded data"""
if not self.data_manager.current_user or not self.data_manager.calculated_stats:
return ""
user_name = self.data_manager.current_user.name
stats = self.data_manager.calculated_stats
tir = stats.get('time_in_range_70_180', 0)
cv = stats.get('cv', 0)
avg_glucose = stats.get('average_glucose', 0)
total_readings = stats.get('total_readings', 0)
# Special handling for Sarah (unstable patterns)
if user_name == "Sarah Thompson":
if tir < 50 and cv > 40:
notification = f"""
🚨 **DATA LOADED - CONCERNING PATTERNS DETECTED**
**Patient:** {user_name} ({total_readings:,} readings analyzed)
**⚠️ Critical Findings:**
• Time in Range: {tir:.1f}% (Target: >70%)
• High Variability: CV {cv:.1f}% (Target: <36%)
• Average Glucose: {avg_glucose:.1f} mg/dL
**🔥 Immediate Action Required**
• Frequent hypoglycemia detected
• Severe glucose instability
• Healthcare provider consultation recommended
*AI analysis ready - Click Chat tab for urgent insights*
"""
else:
notification = f"""
✅ **DATA LOADED SUCCESSFULLY**
**Patient:** {user_name} ({total_readings:,} readings analyzed)
**Time in Range:** {tir:.1f}% | **Average:** {avg_glucose:.1f} mg/dL
*14-day analysis complete - Ready for AI insights*
"""
else:
# For other users with better control
if tir >= 70:
notification = f"""
✅ **DATA LOADED - EXCELLENT CONTROL**
**Patient:** {user_name} ({total_readings:,} readings analyzed)
**Time in Range:** {tir:.1f}% ✅ | **CV:** {cv:.1f}%
*Great glucose management - AI ready to help maintain control*
"""
else:
notification = f"""
📊 **DATA LOADED SUCCESSFULLY**
**Patient:** {user_name} ({total_readings:,} readings analyzed)
**Time in Range:** {tir:.1f}% | **Average:** {avg_glucose:.1f} mg/dL
*Analysis complete - AI ready to provide insights*
"""
return notification
def _load_dexcom_sandbox_glucose_data(self) -> Tuple[str, go.Figure]:
"""Load Dexcom Sandbox glucose data via OAuth"""
if not self.dexcom_sandbox.authenticated:
return "❌ Dexcom Sandbox not authenticated. Please complete OAuth first.", None
try:
# Load 14 days of data from Dexcom Sandbox
data_result = self.dexcom_sandbox.load_glucose_data(days=14)
if not data_result['success']:
return f"❌ {data_result['error']}", None
# Convert Dexcom Sandbox data to data manager format
self._convert_dexcom_sandbox_to_dataframe()
return self._build_glucose_display()
except Exception as e:
logger.error(f"Failed to load Dexcom Sandbox data: {e}")
return f"❌ Failed to load Dexcom Sandbox data: {str(e)}", None
def _convert_dexcom_sandbox_to_dataframe(self):
"""Convert Dexcom Sandbox glucose data to DataFrame format"""
try:
glucose_data = self.dexcom_sandbox.get_glucose_data_for_ui()
if not glucose_data:
raise Exception("No glucose data available from Dexcom Sandbox")
# Convert to DataFrame
df = pd.DataFrame(glucose_data)
# Ensure proper datetime conversion
df['systemTime'] = pd.to_datetime(df['systemTime'])
df['displayTime'] = pd.to_datetime(df['displayTime'])
df['value'] = pd.to_numeric(df['value'], errors='coerce')
# Sort by time
df = df.sort_values('systemTime')
# Set in data manager
self.data_manager.processed_glucose_data = df
# Calculate statistics using existing analyzer
self.data_manager.calculated_stats = self.data_manager._calculate_unified_stats()
self.data_manager.identified_patterns = GlucoseAnalyzer.identify_patterns(df)
logger.info(f"✅ Converted {len(df)} Dexcom Sandbox readings to DataFrame")
except Exception as e:
logger.error(f"Failed to convert Dexcom Sandbox data: {e}")
raise
def _build_glucose_display(self) -> Tuple[str, go.Figure]:
"""Build glucose data display (common for demo and Dexcom Sandbox)"""
# Get unified stats
stats = self.data_manager.get_stats_for_ui()
chart_data = self.data_manager.get_chart_data()
# Sync chat with fresh data
self._sync_chat_with_data_manager()
if chart_data is None or chart_data.empty:
return "No glucose data available", None
# Build data summary with CONSISTENT metrics
user = self.data_manager.current_user
data_points = stats.get('total_readings', 0)
avg_glucose = stats.get('average_glucose', 0)
std_glucose = stats.get('std_glucose', 0)
min_glucose = stats.get('min_glucose', 0)
max_glucose = stats.get('max_glucose', 0)
time_in_range = stats.get('time_in_range_70_180', 0)
time_below_range = stats.get('time_below_70', 0)
time_above_range = stats.get('time_above_180', 0)
gmi = stats.get('gmi', 0)
cv = stats.get('cv', 0)
# Calculate date range
end_date = datetime.now()
start_date = end_date - timedelta(days=14)
# Determine data source
if self.current_user_type == "dexcom_sandbox":
data_source = "Dexcom Sandbox OAuth"
oauth_status = "✅ Authenticated Dexcom Sandbox with working OAuth"
else:
data_source = "Demo Data"
oauth_status = "🎭 Using demo data for testing"
data_summary = f"""
## 📊 Data Summary for {user.name}
### Basic Information
• **Data Type:** {data_source}
• **Analysis Period:** {start_date.strftime('%B %d, %Y')} to {end_date.strftime('%B %d, %Y')} (14 days)
• **Total Readings:** {data_points:,} glucose measurements
• **Device:** {user.device_type}
### Glucose Statistics
• **Average Glucose:** {avg_glucose:.1f} mg/dL
• **Standard Deviation:** {std_glucose:.1f} mg/dL
• **Coefficient of Variation:** {cv:.1f}%
• **Glucose Range:** {min_glucose:.0f} - {max_glucose:.0f} mg/dL
• **GMI (Glucose Management Indicator):** {gmi:.1f}%
### Time in Range Analysis
• **Time in Range (70-180 mg/dL):** {time_in_range:.1f}%
• **Time Below Range (<70 mg/dL):** {time_below_range:.1f}%
• **Time Above Range (>180 mg/dL):** {time_above_range:.1f}%
### Clinical Targets
• **Target Time in Range:** >70% (Current: {time_in_range:.1f}%)
• **Target Time Below Range:** <4% (Current: {time_below_range:.1f}%)
• **Target CV:** <36% (Current: {cv:.1f}%)
### Authentication Status
• **User Type:** {self.current_user_type.upper() if self.current_user_type else 'Unknown'}
• **OAuth Status:** {oauth_status}
"""
chart = self.create_glucose_chart()
return data_summary, chart
def _sync_chat_with_data_manager(self):
"""Ensure chat uses the same data as the UI"""
try:
# Get context from unified data manager
context = self.data_manager.get_context_for_agent()
# Update chat's internal data to match
if not context.get("error"):
self.mistral_chat.current_user = self.data_manager.current_user
self.mistral_chat.current_glucose_data = self.data_manager.processed_glucose_data
self.mistral_chat.current_stats = self.data_manager.calculated_stats
self.mistral_chat.current_patterns = self.data_manager.identified_patterns
logger.info(f"Synced chat with data manager - TIR: {self.data_manager.calculated_stats.get('time_in_range_70_180', 0):.1f}%")
except Exception as e:
logger.error(f"Failed to sync chat with data manager: {e}")
def _get_current_user_key(self) -> str:
"""Get the current user key"""
if not self.data_manager.current_user:
return ""
# Find the key for current user
for key, user in DEMO_USERS.items():
if user == self.data_manager.current_user:
return key
return ""
def get_template_prompts(self) -> List[str]:
"""Get template prompts based on current user data"""
if not self.data_manager.current_user or not self.data_manager.calculated_stats:
return [
"What should I know about managing my diabetes?",
"How can I improve my glucose control?"
]
stats = self.data_manager.calculated_stats
time_in_range = stats.get('time_in_range_70_180', 0)
time_below_70 = stats.get('time_below_70', 0)
templates = []
if time_in_range < 70:
templates.append(f"My time in range is {time_in_range:.1f}% which is below the 70% target. What specific strategies can help me improve it?")
else:
templates.append(f"My time in range is {time_in_range:.1f}% which meets the target. How can I maintain this level of control?")
if time_below_70 > 4:
templates.append(f"I'm experiencing {time_below_70:.1f}% time below 70 mg/dL. What can I do to prevent these low episodes?")
else:
templates.append("What are the best practices for preventing hypoglycemia in my situation?")
# Add data source specific template
if self.current_user_type == "dexcom_sandbox":
templates.append("This is my Dexcom Sandbox OAuth-authenticated data. What insights can you provide about these glucose patterns?")
else:
templates.append("Based on this demo data, what would you recommend for someone with similar patterns?")
return templates
def chat_with_mistral(self, message: str, history: List) -> Tuple[str, List]:
"""Handle chat interaction with Mistral using unified data"""
if not message.strip():
return "", history
if not self.data_manager.current_user:
response = "Please select a user first (demo or Dexcom Sandbox) to get personalized insights about glucose data."
history.append([message, response])
return "", history
try:
# Ensure chat is synced with latest data
self._sync_chat_with_data_manager()
# Send message to Mistral chat
result = self.mistral_chat.chat_with_mistral(message)
if result['success']:
response = result['response']
# Add data consistency note
validation = self.data_manager.validate_data_consistency()
if validation.get('valid'):
data_age = validation.get('data_age_minutes', 0)
if data_age > 10: # Warn if data is old
response += f"\n\n📊 *Note: Analysis based on data from {data_age} minutes ago. Reload data for most current insights.*"
# Add data source context
if self.current_user_type == "dexcom_sandbox":
response += f"\n\n🔐 *This analysis is based on your OAuth-authenticated Dexcom Sandbox data.*"
else:
response += f"\n\n🎭 *This analysis is based on demo data for testing purposes.*"
# Add context note if no user data was included
if not result.get('context_included', True):
response += f"\n\n💡 *For more personalized advice, make sure your glucose data is loaded.*"
else:
response = f"I apologize, but I encountered an error: {result.get('error', 'Unknown error')}. Please try again or rephrase your question."
history.append([message, response])
return "", history
except Exception as e:
logger.error(f"Chat error: {str(e)}")
error_response = f"I apologize, but I encountered an error while processing your question: {str(e)}. Please try rephrasing your question."
history.append([message, error_response])
return "", history
def clear_chat_history(self) -> List:
"""Clear chat history"""
self.chat_history = []
self.mistral_chat.clear_conversation()
return []
def create_glucose_chart(self) -> Optional[go.Figure]:
"""Create an interactive glucose chart using unified data"""
chart_data = self.data_manager.get_chart_data()
if chart_data is None or chart_data.empty:
return None
fig = go.Figure()
# Color code based on glucose ranges
colors = []
for value in chart_data['value']:
if value < 70:
colors.append('#E74C3C') # Red for low
elif value > 180:
colors.append('#F39C12') # Orange for high
else:
colors.append('#3498DB') # Blue for in range
fig.add_trace(go.Scatter(
x=chart_data['systemTime'],
y=chart_data['value'],
mode='lines+markers',
name='Glucose',
line=dict(color='#2980B9', width=2),
marker=dict(size=4, color=colors),
hovertemplate='%{y} mg/dL
%{x}
AI-Powered Glucose Insights
Demo Users + Dexcom Sandbox OAuth • Chat with AI for personalized glucose insights
⚠️ Medical Disclaimer
GlycoAI is for informational and educational purposes only. Always consult your healthcare provider before making any changes to your diabetes management plan.
🔒 Data processed securely • 💡 Powered by Dexcom API & Mistral AI
🎭 Demo: Available • 🔐 Dexcom Sandbox: {"Available" if DEXCOM_SANDBOX_AVAILABLE else "Not configured"}