-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUserBehaviorObserver.cs
More file actions
662 lines (569 loc) · 23.8 KB
/
UserBehaviorObserver.cs
File metadata and controls
662 lines (569 loc) · 23.8 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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.Script.Serialization;
using System.Windows;
namespace TimeTask
{
public enum InteractionType
{
Voice,
Text,
MouseClick,
KeyboardInput,
TaskOperation,
GoalOperation,
SystemEvent
}
public class UserInteraction
{
public string InteractionId { get; set; }
public InteractionType Type { get; set; }
public DateTime Timestamp { get; set; }
public string Description { get; set; }
public string Context { get; set; }
public Dictionary<string, string> Metadata { get; set; } = new Dictionary<string, string>();
public string RelatedTaskId { get; set; }
public string RelatedGoalId { get; set; }
}
public class BehaviorPattern
{
public string PatternId { get; set; }
public string PatternName { get; set; }
public string Description { get; set; }
public double Confidence { get; set; }
public DateTime FirstObserved { get; set; }
public DateTime LastObserved { get; set; }
public int ObservationCount { get; set; }
public Dictionary<string, int> FrequencyByHour { get; set; } = new Dictionary<string, int>();
public Dictionary<string, int> FrequencyByDay { get; set; } = new Dictionary<string, int>();
}
public class WorkHabitInsight
{
public string InsightId { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string Recommendation { get; set; }
public DateTime GeneratedAt { get; set; }
public List<string> RelatedPatterns { get; set; } = new List<string>();
public double Priority { get; set; }
public bool IsAcknowledged { get; set; }
}
public class UserBehaviorObserver
{
private readonly string _dataPath;
private readonly string _interactionsPath;
private readonly string _patternsPath;
private readonly string _insightsPath;
private readonly object _lock = new object();
private List<UserInteraction> _interactions;
private List<BehaviorPattern> _patterns;
private List<WorkHabitInsight> _insights;
private const int MaxInteractions = 10000;
private const int InteractionRetentionDays = 90;
public event Action<WorkHabitInsight> NewInsightGenerated;
public event Action<BehaviorPattern> PatternDetected;
public UserBehaviorObserver(string appDataPath)
{
_dataPath = appDataPath;
_interactionsPath = Path.Combine(appDataPath, "behavior", "interactions.json");
_patternsPath = Path.Combine(appDataPath, "behavior", "patterns.json");
_insightsPath = Path.Combine(appDataPath, "behavior", "insights.json");
Directory.CreateDirectory(Path.GetDirectoryName(_interactionsPath));
_interactions = new List<UserInteraction>();
_patterns = new List<BehaviorPattern>();
_insights = new List<WorkHabitInsight>();
LoadData();
}
public void RecordInteraction(InteractionType type, string description, string context = null,
Dictionary<string, string> metadata = null, string relatedTaskId = null, string relatedGoalId = null)
{
lock (_lock)
{
var interaction = new UserInteraction
{
InteractionId = Guid.NewGuid().ToString("N"),
Type = type,
Timestamp = DateTime.Now,
Description = description,
Context = context,
Metadata = metadata ?? new Dictionary<string, string>(),
RelatedTaskId = relatedTaskId,
RelatedGoalId = relatedGoalId
};
_interactions.Add(interaction);
if (_interactions.Count > MaxInteractions)
{
CleanupOldInteractions();
}
SaveInteractions();
AnalyzePatterns();
}
}
public void RecordVoiceInteraction(string recognizedText, float confidence, string context = null)
{
var metadata = new Dictionary<string, string>
{
{ "confidence", confidence.ToString("F2") },
{ "text_length", recognizedText.Length.ToString() }
};
RecordInteraction(InteractionType.Voice, recognizedText, context, metadata);
}
public void RecordTaskOperation(string operation, string taskDescription, string taskId = null)
{
var metadata = new Dictionary<string, string>
{
{ "operation", operation },
{ "task_length", taskDescription?.Length.ToString() ?? "0" }
};
RecordInteraction(InteractionType.TaskOperation, operation, taskDescription, metadata, taskId);
}
public void RecordGoalOperation(string operation, string goalDescription, string goalId = null)
{
var metadata = new Dictionary<string, string>
{
{ "operation", operation }
};
RecordInteraction(InteractionType.GoalOperation, operation, goalDescription, metadata, null, goalId);
}
public void RecordSystemEvent(string eventName, string details = null)
{
RecordInteraction(InteractionType.SystemEvent, eventName, details);
}
private void AnalyzePatterns()
{
if (_interactions.Count < 10) return;
AnalyzeActiveHours();
AnalyzeTaskCreationPatterns();
AnalyzeVoiceUsagePatterns();
AnalyzeGoalProgressPatterns();
AnalyzeProcrastinationPatterns();
GenerateInsights();
}
private void AnalyzeActiveHours()
{
var recentInteractions = _interactions
.Where(i => i.Timestamp > DateTime.Now.AddDays(-7))
.ToList();
if (recentInteractions.Count < 5) return;
var hourlyActivity = recentInteractions
.GroupBy(i => i.Timestamp.Hour)
.Select(g => new { Hour = g.Key, Count = g.Count() })
.OrderByDescending(g => g.Count)
.ToList();
if (hourlyActivity.Any())
{
var peakHour = hourlyActivity.First();
UpdateOrCreatePattern(
"peak_active_hour",
"高峰活跃时段",
$"用户在{peakHour.Hour}:00-{peakHour.Hour + 1}:00时段最活跃",
peakHour.Count,
hourlyActivity.ToDictionary(h => h.Hour.ToString(), h => h.Count)
);
}
}
private void AnalyzeTaskCreationPatterns()
{
var taskInteractions = _interactions
.Where(i => i.Type == InteractionType.TaskOperation &&
i.Timestamp > DateTime.Now.AddDays(-14))
.ToList();
if (taskInteractions.Count < 5) return;
var dailyTaskCount = taskInteractions
.GroupBy(i => i.Timestamp.Date)
.Select(g => new { Date = g.Key, Count = g.Count() })
.ToList();
var avgTasksPerDay = dailyTaskCount.Average(g => g.Count);
UpdateOrCreatePattern(
"task_creation_frequency",
"任务创建频率",
$"平均每天创建{avgTasksPerDay:F1}个任务",
dailyTaskCount.Count,
dailyTaskCount.ToDictionary(d => d.Date.ToString("yyyy-MM-dd"), d => d.Count)
);
var morningTasks = taskInteractions.Count(i => i.Timestamp.Hour < 12);
var afternoonTasks = taskInteractions.Count(i => i.Timestamp.Hour >= 12 && i.Timestamp.Hour < 18);
var eveningTasks = taskInteractions.Count(i => i.Timestamp.Hour >= 18);
if (morningTasks > afternoonTasks && morningTasks > eveningTasks)
{
UpdateOrCreatePattern(
"morning_planner",
"早晨规划者",
"倾向于在上午规划和创建任务",
morningTasks
);
}
else if (eveningTasks > morningTasks && eveningTasks > afternoonTasks)
{
UpdateOrCreatePattern(
"evening_planner",
"晚间规划者",
"倾向于在晚上规划和创建任务",
eveningTasks
);
}
}
private void AnalyzeVoiceUsagePatterns()
{
var voiceInteractions = _interactions
.Where(i => i.Type == InteractionType.Voice &&
i.Timestamp > DateTime.Now.AddDays(-7))
.ToList();
if (voiceInteractions.Count < 3) return;
var voiceUsageRate = (double)voiceInteractions.Count / _interactions.Count(i => i.Timestamp > DateTime.Now.AddDays(-7));
UpdateOrCreatePattern(
"voice_usage_preference",
"语音使用偏好",
$"语音交互占比{voiceUsageRate:P1}",
voiceInteractions.Count
);
var taskKeywords = voiceInteractions
.Where(i => i.Description != null)
.SelectMany(i => Regex.Matches(i.Description, @"[\u4e00-\u9fa5A-Za-z]{2,}").Cast<Match>())
.Select(m => m.Value)
.GroupBy(w => w, StringComparer.Ordinal)
.Where(g => g.Count() >= 2)
.OrderByDescending(g => g.Count())
.Take(10)
.ToDictionary(g => g.Key, g => g.Count());
if (taskKeywords.Any())
{
UpdateOrCreatePattern(
"voice_task_topics",
"语音任务主题",
"通过语音创建的常见任务主题",
taskKeywords.Values.Sum(),
taskKeywords
);
}
}
private void AnalyzeGoalProgressPatterns()
{
var goalInteractions = _interactions
.Where(i => i.Type == InteractionType.GoalOperation &&
i.Timestamp > DateTime.Now.AddDays(-30))
.ToList();
if (goalInteractions.Count < 3) return;
var goalReviewFrequency = goalInteractions
.GroupBy(i => i.Timestamp.Date)
.Count();
var avgReviewInterval = 30.0 / Math.Max(1, goalReviewFrequency);
UpdateOrCreatePattern(
"goal_review_frequency",
"目标回顾频率",
$"平均每{avgReviewInterval:F1}天回顾一次目标",
goalInteractions.Count
);
if (avgReviewInterval > 14)
{
GenerateInsight(
"low_goal_review_frequency",
"目标回顾频率较低",
$"你平均每{avgReviewInterval:F0}天才回顾一次目标,建议每周回顾一次以保持目标进度",
"设置每周固定时间回顾长期目标,可以使用提醒功能",
0.8
);
}
}
private void AnalyzeProcrastinationPatterns()
{
var taskInteractions = _interactions
.Where(i => i.Type == InteractionType.TaskOperation &&
i.Metadata.ContainsKey("operation") &&
i.Metadata["operation"] == "update" &&
i.Timestamp > DateTime.Now.AddDays(-14))
.ToList();
if (taskInteractions.Count < 5) return;
var delayedUpdates = taskInteractions
.Where(i => i.Context != null &&
(i.Context.Contains("延期") || i.Context.Contains("推迟") || i.Context.Contains("延后")))
.ToList();
var delayRate = (double)delayedUpdates.Count / taskInteractions.Count;
if (delayRate > 0.3)
{
UpdateOrCreatePattern(
"procrastination_tendency",
"拖延倾向",
$"任务延期率{delayRate:P1}",
delayedUpdates.Count
);
GenerateInsight(
"high_procrastination_rate",
"任务延期率较高",
$"近期{delayRate:P1}的任务被延期,可能存在拖延倾向",
"尝试将大任务拆解成小步骤,使用专注冲刺功能,或重新评估任务优先级",
0.9
);
}
}
private void GenerateInsights()
{
var recentPatterns = _patterns
.Where(p => p.LastObserved > DateTime.Now.AddDays(-7))
.ToList();
if (recentPatterns.Count < 2) return;
CheckWorkloadBalance();
CheckFocusPatterns();
CheckGoalAlignment();
}
private void CheckWorkloadBalance()
{
var taskPattern = _patterns.FirstOrDefault(p => p.PatternId == "task_creation_frequency");
if (taskPattern == null) return;
if (taskPattern.FrequencyByDay == null || taskPattern.FrequencyByDay.Count == 0)
{
return;
}
var avgTasksPerDay = taskPattern.FrequencyByDay.Values.Average();
if (avgTasksPerDay > 10)
{
GenerateInsight(
"high_workload",
"任务量较大",
$"平均每天创建{avgTasksPerDay:F1}个任务,可能存在任务过载",
"考虑使用任务拆解功能,将任务分类并设置优先级,或委托部分任务",
0.85
);
}
else if (avgTasksPerDay < 2)
{
GenerateInsight(
"low_task_engagement",
"任务创建较少",
"近期任务创建量较少,可以尝试设定更具体的目标",
"从长期目标开始,将大目标分解为可执行的小任务",
0.6
);
}
}
private void CheckFocusPatterns()
{
var voicePattern = _patterns.FirstOrDefault(p => p.PatternId == "voice_usage_preference");
if (voicePattern == null) return;
int recentCount = _interactions.Count(i => i.Timestamp > DateTime.Now.AddDays(-7));
if (recentCount == 0)
{
return;
}
var voiceUsageRate = voicePattern.ObservationCount / (double)recentCount;
if (voiceUsageRate < 0.1)
{
GenerateInsight(
"low_voice_usage",
"语音功能使用较少",
"语音功能可以帮助你快速记录任务,减少手动输入",
"尝试开启语音监听,用说话的方式快速添加任务",
0.5
);
}
}
private void CheckGoalAlignment()
{
var goalPattern = _patterns.FirstOrDefault(p => p.PatternId == "goal_review_frequency");
if (goalPattern == null) return;
var hasActiveGoals = _interactions.Any(i => i.Type == InteractionType.GoalOperation &&
i.Timestamp > DateTime.Now.AddDays(-7));
if (!hasActiveGoals)
{
GenerateInsight(
"no_active_goals",
"缺少长期目标",
"设置长期目标可以帮助你更好地规划工作和生活",
"从你关心的事情开始,设定1-2个长期目标,并分解为可执行的任务",
0.9
);
}
}
private void UpdateOrCreatePattern(string patternId, string name, string description,
int observationCount, Dictionary<string, int> frequencyData = null)
{
var existingPattern = _patterns.FirstOrDefault(p => p.PatternId == patternId);
if (existingPattern != null)
{
existingPattern.LastObserved = DateTime.Now;
existingPattern.ObservationCount += observationCount;
existingPattern.Description = description;
if (frequencyData != null)
{
foreach (var kvp in frequencyData)
{
if (!existingPattern.FrequencyByHour.ContainsKey(kvp.Key))
{
existingPattern.FrequencyByHour[kvp.Key] = 0;
}
existingPattern.FrequencyByHour[kvp.Key] += kvp.Value;
}
}
PatternDetected?.Invoke(existingPattern);
}
else
{
var newPattern = new BehaviorPattern
{
PatternId = patternId,
PatternName = name,
Description = description,
Confidence = Math.Min(1.0, observationCount / 10.0),
FirstObserved = DateTime.Now,
LastObserved = DateTime.Now,
ObservationCount = observationCount,
FrequencyByHour = frequencyData ?? new Dictionary<string, int>(),
FrequencyByDay = new Dictionary<string, int>()
};
_patterns.Add(newPattern);
PatternDetected?.Invoke(newPattern);
}
SavePatterns();
}
private void GenerateInsight(string insightId, string title, string description,
string recommendation, double priority)
{
var existingInsight = _insights.FirstOrDefault(i => i.InsightId == insightId);
if (existingInsight == null)
{
var newInsight = new WorkHabitInsight
{
InsightId = insightId,
Title = title,
Description = description,
Recommendation = recommendation,
GeneratedAt = DateTime.Now,
Priority = priority,
IsAcknowledged = false
};
_insights.Add(newInsight);
NewInsightGenerated?.Invoke(newInsight);
SaveInsights();
}
}
public List<BehaviorPattern> GetPatterns()
{
lock (_lock)
{
return _patterns.OrderByDescending(p => p.LastObserved).ToList();
}
}
public List<WorkHabitInsight> GetInsights(bool includeAcknowledged = false)
{
lock (_lock)
{
var query = _insights.AsEnumerable();
if (!includeAcknowledged)
{
query = query.Where(i => !i.IsAcknowledged);
}
return query.OrderByDescending(i => i.Priority).ThenByDescending(i => i.GeneratedAt).ToList();
}
}
public void AcknowledgeInsight(string insightId)
{
lock (_lock)
{
var insight = _insights.FirstOrDefault(i => i.InsightId == insightId);
if (insight != null)
{
insight.IsAcknowledged = true;
SaveInsights();
}
}
}
public List<UserInteraction> GetInteractions(DateTime? startDate = null, DateTime? endDate = null,
InteractionType? type = null)
{
lock (_lock)
{
var query = _interactions.AsEnumerable();
if (startDate.HasValue)
{
query = query.Where(i => i.Timestamp >= startDate.Value);
}
if (endDate.HasValue)
{
query = query.Where(i => i.Timestamp <= endDate.Value);
}
if (type.HasValue)
{
query = query.Where(i => i.Type == type.Value);
}
return query.OrderByDescending(i => i.Timestamp).Take(1000).ToList();
}
}
private void CleanupOldInteractions()
{
var cutoffDate = DateTime.Now.AddDays(-InteractionRetentionDays);
_interactions = _interactions.Where(i => i.Timestamp >= cutoffDate).ToList();
}
private void LoadData()
{
try
{
if (File.Exists(_interactionsPath))
{
string json = File.ReadAllText(_interactionsPath);
var serializer = new JavaScriptSerializer();
_interactions = serializer.Deserialize<List<UserInteraction>>(json) ?? new List<UserInteraction>();
}
if (File.Exists(_patternsPath))
{
string json = File.ReadAllText(_patternsPath);
var serializer = new JavaScriptSerializer();
_patterns = serializer.Deserialize<List<BehaviorPattern>>(json) ?? new List<BehaviorPattern>();
}
if (File.Exists(_insightsPath))
{
string json = File.ReadAllText(_insightsPath);
var serializer = new JavaScriptSerializer();
_insights = serializer.Deserialize<List<WorkHabitInsight>>(json) ?? new List<WorkHabitInsight>();
}
CleanupOldInteractions();
}
catch (Exception ex)
{
Console.WriteLine($"[UserBehaviorObserver] Failed to load data: {ex.Message}");
}
}
private void SaveInteractions()
{
try
{
var serializer = new JavaScriptSerializer();
string json = serializer.Serialize(_interactions);
File.WriteAllText(_interactionsPath, json);
}
catch (Exception ex)
{
Console.WriteLine($"[UserBehaviorObserver] Failed to save interactions: {ex.Message}");
}
}
private void SavePatterns()
{
try
{
var serializer = new JavaScriptSerializer();
string json = serializer.Serialize(_patterns);
File.WriteAllText(_patternsPath, json);
}
catch (Exception ex)
{
Console.WriteLine($"[UserBehaviorObserver] Failed to save patterns: {ex.Message}");
}
}
private void SaveInsights()
{
try
{
var serializer = new JavaScriptSerializer();
string json = serializer.Serialize(_insights);
File.WriteAllText(_insightsPath, json);
}
catch (Exception ex)
{
Console.WriteLine($"[UserBehaviorObserver] Failed to save insights: {ex.Message}");
}
}
}
}