I understand now - you want the LLM to analyze past conversations and generate/update the user personality profile automatically rather than requiring manual updates to the personality file. Here's a modified version that does this:
python
#!/bin/python
import os
import json
import subprocess
import threading
from datetime import datetime
import ollama
import time
import sys
import signal
# Configuration
ALARM_SOUND_FILE = os.path.expanduser("~/Music/166467_rocket_race.mp3")
PERSISTENT_STORAGE_FILE = "alarm_chat_history.json"
SCHEDULE_FILE = "user_schedule.json"
PERSONALITY_FILE = "user_personality.json" # Will be auto-generated/updated
OLLAMA_MODEL = "gemma3:1b"
SUMMARY_INTERVAL = 600 # 10 minutes in seconds
PERSONALITY_UPDATE_THRESHOLD = 3 # Update personality after this many new conversations
# Escape sequences
ESCAPE_SEQUENCES = {
"stop_alarm": "<<STOP_ALARM>>",
"snooze": "<<SNOOZE>>",
"add_to_schedule": "<<ADD_TO_SCHEDULE>>",
"remove_from_schedule": "<<REMOVE_FROM_SCHEDULE>>",
}
class AlarmChatApp:
def __init__(self):
# Initialize all attributes first
self.alarm_active = False
self.mpv_process = None
self.tts_process = None
self.chat_history = []
self.current_conversation = None
self.last_summary_time = time.time()
self.tts_available = self.check_tts_available()
self.user_personality = {} # Container for personality info
self.last_personality_update = 0 # Track when personality was last updated
# Verify requirements before proceeding
self.verify_system_requirements()
self.load_persistent_data()
self.load_personality_data() # Load existing personality data if available
# Setup signal handlers
signal.signal(signal.SIGINT, self.signal_handler)
signal.signal(signal.SIGTERM, self.signal_handler)
signal.signal(signal.SIGHUP, self.signal_handler)
signal.signal(signal.SIGQUIT, self.signal_handler)
signal.signal(signal.SIGTRAP, self.signal_handler)
signal.signal(signal.SIGSYS, self.signal_handler)
def check_tts_available(self):
"""Check if spd-say is available"""
try:
subprocess.run(['spd-say', '--version'],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL)
return True
except (FileNotFoundError, subprocess.SubprocessError):
print("Warning: spd-say not found. Falling back to text-only mode.")
return False
def load_persistent_data(self):
"""Load chat history and user schedule from files"""
try:
with open(PERSISTENT_STORAGE_FILE, 'r') as f:
self.chat_history = json.load(f)
except (FileNotFoundError, json.JSONDecodeError) as e:
print(f"Warning: Could not load chat history - {str(e)}")
self.chat_history = []
try:
with open(SCHEDULE_FILE, 'r') as f:
self.user_schedule = json.load(f)
except (FileNotFoundError, json.JSONDecodeError) as e:
print(f"Warning: Could not load schedule - {str(e)}")
self.user_schedule = {
"wakeup_times": [],
"preferred_wakeup_questions": [],
"emergency_contacts": []
}
def load_personality_data(self):
"""Load personality information from a file"""
try:
with open(PERSONALITY_FILE, 'r') as f:
self.user_personality = json.load(f)
print("Loaded existing personality profile.")
except (FileNotFoundError, json.JSONDecodeError) as e:
print(f"Warning: Could not load personality data - {str(e)}")
# Default personality (will be updated by LLM)
self.user_personality = {
"description": "No personality data available yet.",
"likes": [],
"dislikes": [],
"pros": [],
"cons": [],
"last_updated": "never"
}
# Force an update of personality on first run
self.update_personality_profile()
def save_schedule(self):
"""Save the updated user schedule"""
try:
with open(SCHEDULE_FILE, 'w') as f:
json.dump(self.user_schedule, f)
except IOError as e:
print(f"Error saving schedule: {str(e)}")
def save_personality_data(self):
"""Save the updated personality profile"""
try:
with open(PERSONALITY_FILE, 'w') as f:
json.dump(self.user_personality, f, indent=2)
except IOError as e:
print(f"Error saving personality data: {str(e)}")
def verify_system_requirements(self):
"""Check for all required components"""
# Verify Ollama is installed
try:
subprocess.run(['ollama', '--version'],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL)
except FileNotFoundError:
print("Error: Ollama is required but not found. Please install Ollama.")
sys.exit(1)
# Verify model is available
if not self.verify_model():
print(f"Error: Model '{OLLAMA_MODEL}' is not available.")
print(f"Please install it with: ollama pull {OLLAMA_MODEL}")
sys.exit(1)
def verify_model(self):
"""Check if the required model is available"""
try:
models = ollama.list()
return any(m['model'] == OLLAMA_MODEL for m in models.get('models', []))
except Exception as e:
print(f"Error checking for model: {str(e)}")
return False
def text_to_speech(self, text):
"""Convert text to speech using spd-say"""
if not self.tts_available or not text.strip():
return
# Stop any previous TTS
if self.tts_process and self.tts_process.poll() is None:
self.tts_process.terminate()
try:
self.tts_process = subprocess.Popen(
['spd-say','-w', text],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL
)
except Exception as e:
print(f"Error in TTS: {str(e)}")
self.tts_available = False
def generate_hint_prompt(self):
"""
Instead of appending the whole past conversation,
this method examines the persistent chat history and generates
a short hint about past mistakes or successes.
"""
hints = []
for conv in self.chat_history:
timestamp = conv.get("timestamp", "unknown time")
# Consider conversations where the alarm was not stopped as "mistakes"
if not conv.get("woke_up", False):
hints.append(f"On {timestamp}, the attempt was unsuccessful.")
else:
hints.append(f"On {timestamp}, you managed to wake up successfully.")
if hints:
return "Past conversation summary: " + " ".join(hints)
else:
return "No past conversation history available."
def generate_personality_text(self):
"""
Generate a short text summary of the guessed personality,
likes, dislikes, pros, and cons.
"""
description = self.user_personality.get("description", "N/A")
likes = ", ".join(self.user_personality.get("likes", [])) or "None"
dislikes = ", ".join(self.user_personality.get("dislikes", [])) or "None"
pros = ", ".join(self.user_personality.get("pros", [])) or "None"
cons = ", ".join(self.user_personality.get("cons", [])) or "None"
last_updated = self.user_personality.get("last_updated", "never")
personality_text = (
f"Personality: {description}. "
f"Likes: {likes}. "
f"Dislikes: {dislikes}. "
f"Pros: {pros}. "
f"Cons: {cons}. "
f"(Last updated: {last_updated})"
)
return personality_text
def update_personality_profile(self):
"""
Use the LLM to analyze past conversations and generate/update
the user personality profile.
"""
if not self.chat_history:
print("No chat history available to analyze personality.")
return False
try:
print("Updating user personality profile based on conversation history...")
# Prepare conversation data for analysis
conversation_data = []
for conv in self.chat_history:
messages = []
for msg in conv.get("messages", []):
if isinstance(msg, dict):
if "user" in msg:
messages.append(f"User: {msg['user']}")
elif "assistant" in msg:
messages.append(f"Assistant: {msg['assistant']}")
if messages:
conversation_data.append("\n".join(messages))
# If we have too much data, limit to the most recent conversations
if len(conversation_data) > 5:
conversation_data = conversation_data[-5:]
# Join all conversations with separators
all_conversations = "\n\n--- Next Conversation ---\n\n".join(conversation_data)
# Create a prompt for the LLM to analyze the conversations
analysis_prompt = f"""Based on the following alarm clock conversations, analyze the user's personality, preferences, and behavior patterns.
{all_conversations}
Create a personality profile with the following information:
1. A brief description of the user's personality when waking up
2. Things the user seems to like
3. Things the user seems to dislike
4. Positive traits (pros) of the user
5. Negative traits or challenges (cons) the user faces when waking up
Format your response as a JSON object with these keys: description, likes (array), dislikes (array), pros (array), cons (array).
Only respond with the JSON object, nothing else.
"""
# Get LLM analysis
response = ollama.chat(
model=OLLAMA_MODEL,
messages=[{"role": "system", "content": "You are a helpful assistant that analyzes conversations and extracts personality insights."},
{"role": "user", "content": analysis_prompt}],
options={"temperature": 0.2} # Lower temperature for more consistent output
)
llm_response = response['message']['content']
# Try to extract JSON from the response
try:
# Find JSON in the response (it might be surrounded by markdown or other text)
json_start = llm_response.find('{')
json_end = llm_response.rfind('}') + 1
if json_start >= 0 and json_end > json_start:
json_str = llm_response[json_start:json_end]
personality_data = json.loads(json_str)
# Update the personality profile
self.user_personality.update(personality_data)
self.user_personality["last_updated"] = datetime.now().isoformat()
# Save the updated profile
self.save_personality_data()
print("User personality profile updated successfully.")
self.last_personality_update = len(self.chat_history)
return True
else:
raise ValueError("No JSON found in LLM response")
except (json.JSONDecodeError, ValueError) as e:
print(f"Error parsing personality data: {str(e)}")
print(f"Raw LLM response: {llm_response}")
return False
except Exception as e:
print(f"Error updating personality profile: {str(e)}")
return False
def generate_system_prompt(self):
"""Generate the system prompt for the LLM including hint and personality info"""
try:
current_time = datetime.now()
weekday = current_time.strftime("%A")
time_str = current_time.strftime("%H:%M")
today_schedule = next((day for day in self.user_schedule["wakeup_times"]
if day["weekday"].lower() == weekday.lower()), None)
schedule_info = f"Today is {weekday}. "
if today_schedule:
schedule_info += f"Scheduled wake-up time: {today_schedule['time']}. "
if today_schedule.get("important_events"):
schedule_info += "Important events: " + ", ".join(today_schedule["important_events"])
else:
schedule_info += "No specific wake-up time scheduled for today."
# Generate hint prompt from past persistent conversations
hint_prompt = self.generate_hint_prompt()
# Generate personality summary
personality_text = self.generate_personality_text()
return f"""You are an intelligent alarm clock helping the user wake up. Your primary goal is to determine if the user is truly awake and alert.
Talk like a police officer interrogating a suspect or a military officer with a subordinate.
Current time: {time_str}
{schedule_info}
Previous attempts hint: {hint_prompt}
User personality details: {personality_text}
Special commands available:
{ESCAPE_SEQUENCES["stop_alarm"]} - Stop the alarm (only when absolutely sure the user is awake)
{ESCAPE_SEQUENCES["snooze"]} - Snooze for 5 minutes (if the user seems groggy)
{ESCAPE_SEQUENCES["add_to_schedule"]} - Modify schedule: add a new wakeup time
{ESCAPE_SEQUENCES["remove_from_schedule"]} - Modify schedule: remove an existing wakeup time
Assessment criteria for wakefulness:
1. Responses should be coherent and specific.
2. Must demonstrate awareness of time/surroundings.
3. Should indicate a clear intention to start the day.
Begin by asking a specific question that requires a thoughtful answer.
"""
except Exception as e:
print(f"Error generating system prompt: {str(e)}")
return """You are an alarm clock assistant. Determine if the user is awake by asking thoughtful questions.
Use <<STOP_ALARM>> when convinced they're awake, or <<SNOOZE>> if more time is needed."""
def generate_periodic_summary(self):
"""Generate a periodic summary message"""
try:
current_time = datetime.now().strftime("%H:%M")
conv_duration = int(time.time() - self.current_conversation["start_time"])
summary = f"""<<PERIODIC_SUMMARY>>
Time: {current_time}
Conversation duration: {conv_duration} seconds
Messages exchanged: {len(self.current_conversation["messages"])//2}
Assessment: {'User appears awake' if self.check_wakefulness() else 'User still seems sleepy'}
Recommended action: {ESCAPE_SEQUENCES["stop_alarm"] if self.check_wakefulness() else ESCAPE_SEQUENCES["snooze"]}
"""
return summary
except Exception as e:
print(f"Error generating summary: {str(e)}")
return "<<PERIODIC_SUMMARY>>\nError generating summary\n"
def check_wakefulness(self):
"""Analyze conversation to determine if user is awake"""
try:
if not self.current_conversation or len(self.current_conversation["messages"]) < 4:
return False
last_responses = [
msg["user"] for msg in self.current_conversation["messages"]
if isinstance(msg, dict) and "user" in msg
][-2:]
return all(len(response.split()) > 5 for response in last_responses)
except Exception as e:
print(f"