Spaces:
Runtime error
Runtime error
Update app.py
Browse files152 unmodified lines1531541551561571581591601611621631641651661671681691701711721731741751761 unmodified line17817918018118218318418518618718818919019119219325 unmodified lines21922022122222322422522622722822923023123214 unmodified lines24724824925025125225393 unmodified lines3473483493503513523533543553563 unmodified lines36036136236336436536636736836923 unmodified lines393394395396397398399459 unmodified lines85986086186286386413 unmodified lines87887988088188288316 unmodified lines9009019029039049059069079089099109119129139149159169179189199202 unmodified lines9239249259269279289299302 unmodified lines93393493593693793871 unmodified lines1010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037282 unmodified lines13201321132213231324132513264 unmodified lines1331133213331334133513361337152 unmodified linestry:if file_path.exists():try:with open(file_path, 'r') as f:data = json.load(f)try:# Validate and update existing datadata = validate_data_structure(data)# Only save if the file already existed and needed updatessave_daily_data(data, date_key)return dataexcept Exception as e:print(f"Error validating data: {e}")return create_empty_daily_data()except json.JSONDecodeError as e:print(f"Error loading data: {e}")# Try to clean up the corrupted filedata = clean_daily_data_file(date_key)return dataelse:# Only create new file if it's today's dateif date_key == get_date_key():1 unmodified linesave_daily_data(data, date_key)return dataelse:# Return empty metrics for historical dates that don't existreturn {"tracking_metrics": {"productivity": 0,"energy": 0,"mood": 0,"sleep_quality": 0,"exercise_intensity": 0}}except Exception as e:print(f"Error loading data: {e}")return create_empty_daily_data()25 unmodified lines"habits": {habit: [False] * 7 for habit in current_habits},"focus": {"priorities": [[],[],[]],"later": [[],[],[]],"priority_reward": "","later_reward": ""14 unmodified lines}}# Add journal sectiondata["journal"] = {question: "" for question in JOURNAL_QUESTIONS}93 unmodified lines"""Get the default habits list if no custom list exists"""return [# Morning Routine (Essential)# After Work Activities# Flexible Throughout Day]def load_habits():3 unmodified linestry:with open(config_path, 'r') as f:data = json.load(f)return data.get("habits", get_default_habits())except Exception as e:print(f"Error loading habits: {e}")return get_default_habits()def save_habits(habits_list):"""Save the current habits list to configuration"""23 unmodified lines# Remove redundant constantsDEFAULT_SELF_CARE_ITEMS = ["Yoga (AM)", "Vitamins", "Outside","Stretch (PM)", "Reading", "Learning", "Journal","Tapping", "Meditate", "Brain Train"]459 unmodified linesreturn default_configdef create_habit_section():"""Create the habit tracking section with better layout"""# Load current habits13 unmodified linessummary_text = gr.Markdown()refresh_btn = gr.Button("🔄 Refresh")# Connect refresh button to update summaryrefresh_btn.click(fn=update_summary,16 unmodified lines# Morning Sectionwith gr.Group():gr.Markdown("#### 🌅 Morning Routine")create_habit_group(morning_habits, summary_text) # Pass summary_text as parametergr.Markdown("---")# Evening Sectionwith gr.Group():gr.Markdown("#### 🌙 Evening Activities")create_habit_group(evening_habits, summary_text) # Pass summary_text as parametergr.Markdown("---")# Flexible Sectionwith gr.Group():gr.Markdown("#### ⭐ Flexible Activities")create_habit_group(flexible_habits, summary_text) # Pass summary_text as parametergr.Markdown("---")2 unmodified linesnew_habit = gr.Textbox(label="New Habit/Task",placeholder="Enter a new habit or task to track",scale=4,min_width=250)duration = gr.Dropdown(choices=["", "15min", "20min", "30min", "45min", "60min"],2 unmodified linesmin_width=100)add_btn = gr.Button("Add Habit", scale=1, min_width=100)def create_habit_group(habits, summary_text):"""Create a group of habit tracking rows with better scaling"""71 unmodified linesdef delete_habit_fn(habit_name=habit):"""Delete a habit and update the UI"""try:# 1. Update current daily datacurrent_data = load_daily_data()if habit_name in current_data["habits"]:del current_data["habits"][habit_name]save_daily_data(current_data)# 2. Update habits configurationcurrent_habits = load_habits()if habit_name in current_habits:current_habits.remove(habit_name)save_habits(current_habits)# 3. Update all existing daily data files to remove this habitupdate_all_daily_files(habit_to_remove=habit_name)# Show notificationgr.Info(f"Deleted: {habit_name}")return gr.update(visible=False)except Exception as e:print(f"Error deleting habit: {e}")gr.Warning(f"Failed to delete {habit_name}")return gr.update()# Connect delete button with proper outputdelete_btn.click(282 unmodified linesprint(f"Error saving data: {e}")return "❌ Error saving data"with gr.Blocks(theme='Nymbo/Nymbo_Theme') as demo:# Load initial datacurrent_data = load_daily_data()current_data = check_and_refresh_day(current_data)4 unmodified lineswith gr.Column(scale=2):pass # Empty column for spacingwith gr.Column(scale=1):gr.Image("./logo.png", show_label=False, container=False, width=250, show_download_button=False)with gr.Column(scale=2):pass # Empty column for spacing152 unmodified lines1531541551561571581591601611621631641651661671681 unmodified line17017117217317417517625 unmodified lines20220320420520620720820921021121221321421521621721821914 unmodified lines23423523623723823924093 unmodified lines3343353363373383393403413423433443453463473483493503513523533 unmodified lines35735835936036136236336436536636736836937037137237337437537637737837938023 unmodified lines404405406407408409410459 unmodified lines87087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191213 unmodified lines92692792892993093193293393416 unmodified lines9519529539549559569579589599609619629639649659669679689699709712 unmodified lines9749759769779789799809819829839849859869879882 unmodified lines9919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108571 unmodified lines1157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208282 unmodified lines14911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215334 unmodified lines1538153915401541154215431544152 unmodified linestry:if file_path.exists():try:# Try to load and clean the filedata = clean_json_file(file_path)# Validate and update the data structuredata = validate_data_structure(data)save_daily_data(data, date_key)return dataexcept Exception as e:print(f"Error loading data: {e}")return create_empty_daily_data()else:# Only create new file if it's today's dateif date_key == get_date_key():1 unmodified linesave_daily_data(data, date_key)return dataelse:return create_empty_daily_data()except Exception as e:print(f"Error loading data: {e}")return create_empty_daily_data()25 unmodified lines"habits": {habit: [False] * 7 for habit in current_habits},"focus": {"priorities": [["", ""], # Empty task and status["", ""],["", ""],["", ""],["", ""]],"later": [["", ""], # Empty task and status["", ""],["", ""],["", ""],["", ""]],"priority_reward": "","later_reward": ""14 unmodified lines}}# Add journal section with empty entriesdata["journal"] = {question: "" for question in JOURNAL_QUESTIONS}93 unmodified lines"""Get the default habits list if no custom list exists"""return [# Morning Routine (Essential)"Morning Exercise/Yoga","Meditation (20min)",# After Work Activities"Evening Stretch (20min)","Active Learning (20min)","Journal",# Flexible Throughout Day"Reading (20min)","Take a photo","Future Planning"]def load_habits():3 unmodified linestry:with open(config_path, 'r') as f:data = json.load(f)if "habits" in data and isinstance(data["habits"], list):return data["habits"]else:# If the file exists but is invalid, create a new one with defaultsdefault_habits = get_default_habits()save_habits(default_habits)return default_habitsexcept Exception as e:print(f"Error loading habits: {e}")# If there's an error reading the file, create a new one with defaultsdefault_habits = get_default_habits()save_habits(default_habits)return default_habitselse:# If the file doesn't exist, create it with defaultsdefault_habits = get_default_habits()save_habits(default_habits)return default_habitsdef save_habits(habits_list):"""Save the current habits list to configuration"""23 unmodified lines# Remove redundant constantsDEFAULT_SELF_CARE_ITEMS = ["Yoga (AM)", "Vitamins", "Outside","Stretch (PM)", "Reading", "Learning", "Journal","Tapping", "Meditate", "Brain Train"]459 unmodified linesreturn default_configdef add_new_habit(habit_name, duration, category):"""Add a new habit to the tracking system"""try:if not habit_name.strip():return "⚠️ Please enter a habit name", None, None, None# Format the habit name with duration if providedformatted_habit = habit_name.strip()if duration:formatted_habit = f"{formatted_habit} ({duration})"# Add category prefix for sortingif category == "Morning":formatted_habit = f"Morning {formatted_habit}"elif category == "Evening":formatted_habit = f"Evening {formatted_habit}"# Load current habitscurrent_habits = load_habits()# Check if habit already existsif formatted_habit in current_habits:return "⚠️ This habit already exists", None, None, None# Add new habit to listcurrent_habits.append(formatted_habit)# Save updated habits listsave_habits(current_habits)# Return success message and clear inputsreturn "✅ Habit added successfully!", "", "", ""except Exception as e:print(f"Error adding habit: {e}")return f"❌ Error adding habit: {str(e)}", None, None, Nonedef create_habit_section():"""Create the habit tracking section with better layout"""# Load current habits13 unmodified linessummary_text = gr.Markdown()refresh_btn = gr.Button("🔄 Refresh")# Add status message componentstatus_message = gr.Markdown(visible=False)# Connect refresh button to update summaryrefresh_btn.click(fn=update_summary,16 unmodified lines# Morning Sectionwith gr.Group():gr.Markdown("#### 🌅 Morning Routine")create_habit_group(morning_habits, summary_text)gr.Markdown("---")# Evening Sectionwith gr.Group():gr.Markdown("#### 🌙 Evening Activities")create_habit_group(evening_habits, summary_text)gr.Markdown("---")# Flexible Sectionwith gr.Group():gr.Markdown("#### ⭐ Flexible Activities")create_habit_group(flexible_habits, summary_text)gr.Markdown("---")2 unmodified linesnew_habit = gr.Textbox(label="New Habit/Task",placeholder="Enter a new habit or task to track",scale=3,min_width=200)category = gr.Dropdown(choices=["Morning", "Evening", "Flexible"],label="Category",value="Flexible",scale=2,min_width=100)duration = gr.Dropdown(choices=["", "15min", "20min", "30min", "45min", "60min"],2 unmodified linesmin_width=100)add_btn = gr.Button("Add Habit", scale=1, min_width=100)# Add status message componentstatus_message = gr.Markdown(visible=False)def add_and_refresh(habit_name, category, duration):message, _, _, _ = add_new_habit(habit_name, duration, category)# Reload habits and recreate sectionscurrent_habits = load_habits()morning_habits = [h for h in current_habits if any(x in h.lower() for x in ["wake", "morning", "meditation", "brain", "walk"])]evening_habits = [h for h in current_habits if any(x in h.lower() for x in ["evening", "massage", "learning", "journal", "guitar"])]flexible_habits = [h for h in current_habits if h not in morning_habits + evening_habits]# Update summarysummary = update_summary()# Create updated habit groupscreate_habit_group(morning_habits, summary_text)create_habit_group(evening_habits, summary_text)create_habit_group(flexible_habits, summary_text)return [message, # Status message"", # Clear habit inputcategory, # Keep category selection"", # Clear duration inputgr.update(visible=True), # Show status messagegr.update(value=summary) # Update summary text]# Connect the add button eventadd_btn.click(fn=add_and_refresh,inputs=[new_habit, category, duration],outputs=[status_message,new_habit,category,duration,status_message,summary_text])# Create a refresh button that will be clicked programmaticallyrefresh_habits_btn = gr.Button("Refresh", visible=False)def add_and_refresh(habit_name, duration):message, _, _ = add_new_habit(habit_name, duration)return [message, # Status message"", # Clear habit input"", # Clear duration inputgr.update(visible=True), # Show status messageTrue # Trigger refresh button]# Connect the add button eventadd_btn.click(fn=add_and_refresh,inputs=[new_habit, duration],outputs=[status_message,new_habit,duration,status_message,refresh_habits_btn])# Connect refresh button to reload habitsdef reload_habits():current_habits = load_habits()morning_habits = [h for h in current_habits if any(x in h.lower() for x in ["wake", "morning", "meditation", "brain", "walk"])]evening_habits = [h for h in current_habits if any(x in h.lower() for x in ["evening", "massage", "learning", "journal", "guitar"])]flexible_habits = [h for h in current_habits if h not in morning_habits + evening_habits]return [gr.update(value=update_summary()), # Update summarygr.update(visible=False) # Hide status message]refresh_habits_btn.click(fn=reload_habits,outputs=[summary_text,status_message])def create_habit_group(habits, summary_text):"""Create a group of habit tracking rows with better scaling"""71 unmodified linesdef delete_habit_fn(habit_name=habit):"""Delete a habit and update the UI"""try:# 1. Delete from habits_config.json firstconfig_path = Path("habits_config.json")if config_path.exists():with open(config_path, 'r') as f:config_data = json.load(f)if "habits" in config_data:if habit_name in config_data["habits"]:config_data["habits"].remove(habit_name)with open(config_path, 'w') as f:json.dump(config_data, f, indent=2)print(f"Removed {habit_name} from habits_config.json")# 2. Update current daily datacurrent_data = load_daily_data()if "habits" in current_data and habit_name in current_data["habits"]:del current_data["habits"][habit_name]save_daily_data(current_data)print(f"Removed {habit_name} from current daily data")# 3. Clean up historical datajson_files = list(DATA_DIR.glob("*.json"))for file_path in json_files:try:with open(file_path, 'r') as f:day_data = json.load(f)if "habits" in day_data and habit_name in day_data["habits"]:del day_data["habits"][habit_name]with open(file_path, 'w') as f:json.dump(day_data, f, indent=2)print(f"Removed {habit_name} from {file_path}")except Exception as e:print(f"Error updating file {file_path}: {e}")# Show success notificationgr.Info(f"Deleted: {habit_name}")# Force reload habits from configload_habits() # Reload habits to ensure sync# Hide the row in UIreturn gr.update(visible=False)except Exception as e:print(f"Error deleting habit: {e}")gr.Warning(f"Failed to delete {habit_name}")return gr.update()# Connect delete button with proper outputdelete_btn.click(282 unmodified linesprint(f"Error saving data: {e}")return "❌ Error saving data"def clean_json_file(file_path):"""Clean up potentially corrupted JSON file"""try:with open(file_path, 'r') as f:content = f.read().strip()# Try to find the last valid JSON structuretry:# First try to parse as-isdata = json.loads(content)return dataexcept json.JSONDecodeError:# If that fails, try to clean up the content# Find the last closing bracelast_brace = content.rfind('}')if last_brace != -1:content = content[:last_brace + 1]try:data = json.loads(content)# Save the cleaned data back to filewith open(file_path, 'w') as f:json.dump(data, f, indent=2)return dataexcept json.JSONDecodeError:pass# If all cleanup attempts fail, create new datadata = create_empty_daily_data()with open(file_path, 'w') as f:json.dump(data, f, indent=2)return dataexcept Exception as e:print(f"Error cleaning JSON file {file_path}: {e}")return create_empty_daily_data()with gr.Blocks() as demo:# Load initial datacurrent_data = load_daily_data()current_data = check_and_refresh_day(current_data)4 unmodified lineswith gr.Column(scale=2):pass # Empty column for spacingwith gr.Column(scale=1):gr.Image("./logo.png", show_label=False, container=False, width=250, show_download_button=False, )with gr.Column(scale=2):pass # Empty column for spacing
app.py+264-57