-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathadhdo_server.py
More file actions
executable file
·557 lines (488 loc) · 19.5 KB
/
adhdo_server.py
File metadata and controls
executable file
·557 lines (488 loc) · 19.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
#!/usr/bin/env python3
"""
ADHDo Server - Minimal Working Version
Uses your actual environment with graceful fallbacks.
"""
import os
import asyncio
import json
from datetime import datetime, timedelta
from typing import Dict, Optional, List, Any
from pathlib import Path
from fastapi import FastAPI, HTTPException, BackgroundTasks
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse, HTMLResponse
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel, Field
from dotenv import load_dotenv
import structlog
# Load environment
load_dotenv()
# Configure logging
logger = structlog.get_logger()
# Configuration from environment
class Config:
redis_url = os.getenv('REDIS_URL', '')
use_redis = os.getenv('ENABLE_REDIS', 'false').lower() == 'true'
database_url = os.getenv('DATABASE_URL', 'sqlite:///./adhdo.db')
ollama_model = os.getenv('OLLAMA_MODEL', '')
use_local_llm = os.getenv('USE_LOCAL_LLM', 'false').lower() == 'true'
openai_key = os.getenv('OPENAI_API_KEY', '')
port = int(os.getenv('PORT', 8000))
config = Config()
# Initialize storage
if config.use_redis:
try:
import redis.asyncio as redis
redis_client = redis.from_url(config.redis_url)
logger.info("Using Redis for storage")
except:
redis_client = None
logger.info("Redis failed, using memory storage")
else:
redis_client = None
logger.info("Using in-memory storage")
# In-memory fallback
memory_store: Dict[str, Any] = {
'sessions': {},
'tasks': {},
'patterns': {}
}
# Initialize LLM
llm_client = None
if config.use_local_llm and config.ollama_model:
try:
import ollama
llm_client = ollama.Client()
logger.info(f"Using Ollama with model: {config.ollama_model}")
except:
logger.warning("Ollama client failed to initialize")
elif config.openai_key:
try:
import openai
openai.api_key = config.openai_key
llm_client = openai
logger.info("Using OpenAI API")
except:
logger.warning("OpenAI client failed to initialize")
# Create FastAPI app
app = FastAPI(
title="ADHDo - ADHD Support Assistant",
description="Personal ADHD support with privacy-first local processing",
version="1.0.0"
)
# CORS for web interface
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Models
class ChatRequest(BaseModel):
message: str
user_id: str = "default_user"
context: Optional[Dict] = None
class ChatResponse(BaseModel):
response: str
suggestions: List[str] = []
energy_level: Optional[str] = None
task_breakdown: Optional[List[str]] = None
class Task(BaseModel):
id: Optional[str] = None
title: str
description: Optional[str] = None
due: Optional[datetime] = None
priority: str = "medium"
completed: bool = False
steps: List[str] = []
# ADHD Support Logic
class ADHDSupport:
"""Core ADHD support functionality."""
def __init__(self):
self.crisis_keywords = [
"suicide", "kill myself", "end it all",
"self harm", "hurt myself", "not worth living"
]
self.adhd_patterns = {
"can't start": self.handle_task_initiation,
"overwhelmed": self.handle_overwhelm,
"distracted": self.handle_distraction,
"can't focus": self.handle_focus,
"forgot": self.handle_memory,
"time": self.handle_time_blindness,
"procrastinat": self.handle_procrastination,
}
async def process_message(self, message: str, context: Dict) -> ChatResponse:
"""Process user message with ADHD support logic."""
message_lower = message.lower()
# Crisis detection
if any(keyword in message_lower for keyword in self.crisis_keywords):
return ChatResponse(
response=(
"I'm very concerned about what you're sharing. Please reach out for help:\n"
"• Crisis Line: 988 (US)\n"
"• Text HOME to 741741\n"
"• Emergency: 911\n"
"You matter and there is support available."
),
suggestions=["Talk to someone now", "Call a friend", "Contact therapist"]
)
# Check ADHD patterns
for pattern, handler in self.adhd_patterns.items():
if pattern in message_lower:
return await handler(message, context)
# Try LLM if available
if llm_client:
return await self.llm_response(message, context)
# Fallback response
return ChatResponse(
response="I hear you. What specific challenge can I help you tackle right now?",
suggestions=[
"Break down a task",
"Set a timer",
"Make a simple plan"
]
)
async def handle_task_initiation(self, message: str, context: Dict) -> ChatResponse:
return ChatResponse(
response=(
"Starting is often the hardest part. Let's make it tiny:\n\n"
"1. What's the absolute smallest piece you could do?\n"
"2. Can you just open the document/app?\n"
"3. Set a 2-minute timer and do anything related to it\n\n"
"Remember: Starting badly is better than not starting at all!"
),
suggestions=["Set 2-min timer", "List first step", "Just open the file"],
task_breakdown=["Open the document", "Write one sentence", "Save the file"]
)
async def handle_overwhelm(self, message: str, context: Dict) -> ChatResponse:
return ChatResponse(
response=(
"Let's slow down and simplify:\n\n"
"🫁 Take 3 deep breaths first\n\n"
"Now, let's find ONE thing:\n"
"• What's the most urgent?\n"
"• What's the easiest?\n"
"• What would feel best to complete?\n\n"
"Pick one. Ignore everything else for now."
),
suggestions=["List everything out", "Pick the easiest", "Take a break first"],
energy_level="low"
)
async def handle_distraction(self, message: str, context: Dict) -> ChatResponse:
return ChatResponse(
response=(
"ADHD brains seek stimulation - it's not a character flaw!\n\n"
"Try these:\n"
"• 🎵 Background music (lo-fi, brown noise)\n"
"• ⏰ Pomodoro: 15 min work, 5 min break\n"
"• 🎯 Make it a game: How much can you do in 10 min?\n"
"• 📝 Keep a 'distraction list' for later\n\n"
"What usually helps you focus best?"
),
suggestions=["Start timer", "Put on focus music", "Change location"]
)
async def handle_focus(self, message: str, context: Dict) -> ChatResponse:
return self.handle_distraction(message, context) # Similar approach
async def handle_memory(self, message: str, context: Dict) -> ChatResponse:
return ChatResponse(
response=(
"Working memory challenges are real! Let's externalize it:\n\n"
"Right now:\n"
"• Write it down immediately\n"
"• Set a phone reminder\n"
"• Send yourself an email\n"
"• Take a photo as a memory cue\n\n"
"For the future:\n"
"• Same place for keys/wallet/phone\n"
"• Calendar EVERYTHING\n"
"• Sticky notes in obvious places"
),
suggestions=["Set reminder now", "Write it down", "Create a routine"]
)
async def handle_time_blindness(self, message: str, context: Dict) -> ChatResponse:
current_time = datetime.now().strftime("%I:%M %p")
return ChatResponse(
response=(
f"Current time: {current_time}\n\n"
"Time check-in:\n"
"• How long did you think that took?\n"
"• Have you eaten recently?\n"
"• Water break needed?\n"
"• Should you transition to something else?\n\n"
"Consider setting hourly alarms as time anchors."
),
suggestions=["Set hourly alarm", "Schedule next break", "Review today's plan"]
)
async def handle_procrastination(self, message: str, context: Dict) -> ChatResponse:
return ChatResponse(
response=(
"Procrastination often = perfectionism or overwhelm.\n\n"
"Let's lower the bar:\n"
"• 'Good enough' > Perfect but never done\n"
"• What's the crappiest version you could do?\n"
"• Can you do just 10%?\n\n"
"Sometimes our brain needs:\n"
"• More information (research for 10 min)\n"
"• More energy (take a walk)\n"
"• More dopamine (reward yourself after)\n\n"
"What's really stopping you?"
),
suggestions=["Do worst version", "Set tiny goal", "Plan reward"],
task_breakdown=["Open document", "Write bad first line", "Keep going for 2 min"]
)
async def llm_response(self, message: str, context: Dict) -> ChatResponse:
"""Get response from LLM if available."""
prompt = f"""You are an ADHD support assistant. Be concise, supportive, and practical.
User message: {message}
Context: {json.dumps(context) if context else 'None'}
Provide a helpful response focused on ADHD challenges.
Keep it under 100 words and actionable."""
try:
if config.use_local_llm and llm_client:
# Ollama
response = llm_client.chat(
model=config.ollama_model,
messages=[{'role': 'user', 'content': prompt}]
)
text = response['message']['content']
elif llm_client:
# OpenAI
response = llm_client.ChatCompletion.create(
model='gpt-3.5-turbo',
messages=[{'role': 'user', 'content': prompt}],
max_tokens=150
)
text = response.choices[0].message.content
else:
text = "I want to help. Can you tell me more about what you're struggling with?"
return ChatResponse(response=text)
except Exception as e:
logger.error(f"LLM error: {e}")
return ChatResponse(
response="Let me help you with that. What's the specific challenge?",
suggestions=["Break it down", "Set a timer", "Take a break"]
)
# Initialize support system
adhd_support = ADHDSupport()
# API Endpoints
@app.get("/")
async def root():
"""Serve simple web interface."""
html = """
<!DOCTYPE html>
<html>
<head>
<title>ADHDo - ADHD Support</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
background: #f5f5f5;
}
h1 { color: #4a90e2; }
.chat-container {
background: white;
border-radius: 10px;
padding: 20px;
height: 400px;
overflow-y: auto;
margin-bottom: 20px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
.message {
margin: 10px 0;
padding: 10px;
border-radius: 5px;
}
.user { background: #e3f2fd; text-align: right; }
.assistant { background: #f5f5f5; }
.input-container {
display: flex;
gap: 10px;
}
input {
flex: 1;
padding: 12px;
border: 1px solid #ddd;
border-radius: 5px;
font-size: 16px;
}
button {
padding: 12px 24px;
background: #4a90e2;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 16px;
}
button:hover { background: #357abd; }
.suggestions {
display: flex;
gap: 10px;
margin-top: 10px;
flex-wrap: wrap;
}
.suggestion {
padding: 8px 12px;
background: #fff3cd;
border-radius: 20px;
cursor: pointer;
font-size: 14px;
}
.suggestion:hover { background: #ffe69c; }
</style>
</head>
<body>
<h1>🧠 ADHDo Support</h1>
<div class="chat-container" id="chat"></div>
<div class="input-container">
<input type="text" id="message" placeholder="What are you struggling with?"
onkeypress="if(event.key==='Enter') sendMessage()">
<button onclick="sendMessage()">Send</button>
</div>
<div class="suggestions" id="suggestions"></div>
<script>
async function sendMessage() {
const input = document.getElementById('message');
const message = input.value.trim();
if (!message) return;
// Add user message to chat
const chat = document.getElementById('chat');
chat.innerHTML += `<div class="message user">${message}</div>`;
input.value = '';
// Send to API
try {
const response = await fetch('/chat', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({message: message})
});
const data = await response.json();
// Add response to chat
chat.innerHTML += `<div class="message assistant">${data.response.replace(/\n/g, '<br>')}</div>`;
// Show suggestions
const sugg = document.getElementById('suggestions');
sugg.innerHTML = '';
if (data.suggestions) {
data.suggestions.forEach(s => {
sugg.innerHTML += `<span class="suggestion" onclick="quickSend('${s}')">${s}</span>`;
});
}
// Scroll to bottom
chat.scrollTop = chat.scrollHeight;
} catch (err) {
chat.innerHTML += `<div class="message assistant">Sorry, something went wrong. Try again?</div>`;
}
}
function quickSend(text) {
document.getElementById('message').value = text;
sendMessage();
}
// Focus input on load
document.getElementById('message').focus();
</script>
</body>
</html>
"""
return HTMLResponse(content=html)
@app.get("/health")
async def health():
"""Health check endpoint."""
return {
"status": "healthy",
"timestamp": datetime.now().isoformat(),
"storage": "redis" if redis_client else "memory",
"llm": config.ollama_model or "pattern-based"
}
@app.post("/chat", response_model=ChatResponse)
async def chat(request: ChatRequest):
"""Main chat endpoint."""
try:
# Store in session
session_key = f"session:{request.user_id}"
if redis_client:
await redis_client.lpush(session_key, request.message)
await redis_client.expire(session_key, 3600) # 1 hour expiry
else:
if request.user_id not in memory_store['sessions']:
memory_store['sessions'][request.user_id] = []
memory_store['sessions'][request.user_id].append({
'message': request.message,
'timestamp': datetime.now().isoformat()
})
# Process message
response = await adhd_support.process_message(request.message, request.context or {})
return response
except Exception as e:
logger.error(f"Chat error: {e}")
return ChatResponse(
response="I'm having trouble right now. Can you try rephrasing that?",
suggestions=["Try again", "Simplify the question"]
)
@app.post("/task", response_model=Task)
async def create_task(task: Task):
"""Create a task with ADHD-friendly breakdown."""
# Auto-generate ID
task.id = f"task_{int(time.time())}"
# Break down if no steps provided
if not task.steps:
task.steps = [
f"Open anything related to '{task.title}'",
"Work for just 2 minutes",
"Save your progress",
"Celebrate that you started!"
]
# Store task
if redis_client:
await redis_client.hset(f"tasks:{task.id}", mapping=task.dict())
else:
memory_store['tasks'][task.id] = task.dict()
return task
@app.get("/tasks")
async def get_tasks(user_id: str = "default_user"):
"""Get all tasks."""
tasks = []
if redis_client:
# Get from Redis
keys = await redis_client.keys("tasks:*")
for key in keys:
task_data = await redis_client.hgetall(key)
if task_data:
tasks.append(task_data)
else:
tasks = list(memory_store['tasks'].values())
return tasks
@app.post("/nudge")
async def send_nudge(user_id: str = "default_user", message: Optional[str] = None):
"""Send a gentle nudge."""
default_nudges = [
"Hey! Just checking in. How's it going?",
"Perfect time for a 2-minute task sprint!",
"Water break? Stretch? Both? 💧",
"What's one tiny thing you could do right now?",
"You're doing better than you think! 🌟"
]
import random
nudge = message or random.choice(default_nudges)
return {"nudge": nudge, "timestamp": datetime.now().isoformat()}
if __name__ == "__main__":
import uvicorn
print("\n🚀 Starting ADHDo Server...")
print(f"📍 Open http://localhost:{config.port} in your browser")
print("\n✨ Features enabled:")
print(f" • Storage: {'Redis' if config.use_redis else 'In-memory'}")
print(f" • LLM: {config.ollama_model or config.openai_key[:8]+'...' if config.openai_key else 'Pattern-based'}")
print(f" • Database: {config.database_url.split('://')[0]}")
print("\n💡 Tips:")
print(" • Be specific about what you're struggling with")
print(" • Use the quick suggestions for common issues")
print(" • Tasks are automatically broken down into small steps")
print("\nPress Ctrl+C to stop\n")
uvicorn.run(app, host="0.0.0.0", port=config.port)