100+ copy-paste UI components in plain HTML and CSS: no dependencies, no build step.

0 downloads

dbbasic-web-native/attention-ml.js
Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-web-native.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-web-native.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-web-native.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

danq9 Add canonical.html v1.0 - The single source of truth for usability standards fb6e650 1 year ago History
attention-ml.js · 19.5 KB · 598 lines
1/**
2 * ML-Enhanced Attention Budget System
3 * Uses machine learning to optimize attention scoring based on user behavior
4 * Learns from user interactions to predict what actually matters
5 */
6
7class MLAttentionScorer {
8 constructor(contextManager) {
9 this.context = contextManager;
10 this.interactionHistory = [];
11 this.maxHistorySize = 1000;
12
13 // Feature weights (learned over time)
14 this.weights = {
15 urgency: 2.0,
16 timeOfDay: 0.5,
17 userState: 1.5,
18 environmentNoise: 0.8,
19 viewerCount: 1.0,
20 historicalEngagement: 1.8,
21 contextSimilarity: 1.2,
22 recency: 0.6,
23 frequency: 0.7
24 };
25
26 // Training data
27 this.trainingData = [];
28 this.model = null;
29
30 this.init();
31 }
32
33 init() {
34 this.loadHistoryFromStorage();
35 this.startLearning();
36 console.log('ML Attention Scorer initialized');
37 }
38
39 /**
40 * Calculate attention score using ML-enhanced algorithm
41 */
42 calculateScore(component, context) {
43 const features = this.extractFeatures(component, context);
44 const baseScore = this.computeBaseScore(features);
45 const mlAdjustment = this.computeMLAdjustment(features);
46 const finalScore = baseScore * (1 + mlAdjustment);
47
48 return Math.max(0, Math.min(100, finalScore));
49 }
50
51 /**
52 * Extract features for ML model
53 */
54 extractFeatures(component, context) {
55 const urgency = this.getUrgencyValue(component.getAttribute('urgency'));
56 const priority = component.getAttribute('priority') || 'passive-info';
57 const canDefer = component.getAttribute('can-defer') !== 'false';
58
59 return {
60 // Component features
61 urgency,
62 priority: this.getPriorityValue(priority),
63 canDefer: canDefer ? 0 : 1,
64 attentionWeight: parseFloat(component.getAttribute('attention-weight') || '50'),
65
66 // Context features
67 timeOfDay: this.getTimeOfDayFeature(),
68 dayOfWeek: new Date().getDay() / 7,
69 noiseLevel: context.environment.noiseLevel / 100,
70 viewerCount: Math.log(context.environment.viewerCount + 1),
71 userBusy: context.user.isBusy ? 1 : 0,
72 userFocus: context.user.inFocusMode ? 1 : 0,
73
74 // Historical features
75 historicalEngagement: this.getHistoricalEngagement(component),
76 contextSimilarity: this.getContextSimilarity(context),
77 recency: this.getRecencyFactor(component),
78 frequency: this.getFrequencyFactor(component),
79
80 // Derived features
81 urgencyTimeCombination: urgency * this.getTimeOfDayFeature(),
82 noiseBusyCombination: (context.environment.noiseLevel / 100) * (context.user.isBusy ? 1 : 0)
83 };
84 }
85
86 /**
87 * Compute base attention score from features
88 */
89 computeBaseScore(features) {
90 let score = 0;
91
92 // Weighted sum of features
93 score += features.urgency * this.weights.urgency * 25;
94 score += features.priority * 15;
95 score += features.attentionWeight * 0.5;
96 score += features.historicalEngagement * this.weights.historicalEngagement * 10;
97 score += features.contextSimilarity * this.weights.contextSimilarity * 8;
98
99 // Penalties
100 if (features.userBusy && features.canDefer) {
101 score *= 0.3;
102 }
103
104 if (features.userFocus && features.urgency < 2) {
105 score *= 0.5;
106 }
107
108 if (features.noiseLevel > 0.7 && features.urgency < 2) {
109 score *= 0.7;
110 }
111
112 return score;
113 }
114
115 /**
116 * ML-based adjustment to base score
117 * Uses learned patterns from user behavior
118 */
119 computeMLAdjustment(features) {
120 if (this.trainingData.length < 50) {
121 return 0; // Not enough data yet
122 }
123
124 // Simple neural network-like calculation
125 // In production, use TensorFlow.js for real ML
126
127 let adjustment = 0;
128
129 // Pattern 1: User tends to engage more at certain times
130 const timePattern = this.findTimePattern(features.timeOfDay);
131 adjustment += timePattern * 0.3;
132
133 // Pattern 2: User interaction with similar components
134 const similarityPattern = this.findSimilarityPattern(features);
135 adjustment += similarityPattern * 0.4;
136
137 // Pattern 3: Context-dependent engagement
138 const contextPattern = this.findContextPattern(features);
139 adjustment += contextPattern * 0.3;
140
141 return adjustment;
142 }
143
144 /**
145 * Record user interaction for learning
146 */
147 recordInteraction(component, action, context) {
148 const interaction = {
149 timestamp: Date.now(),
150 componentType: component.tagName.toLowerCase(),
151 componentId: component.id || 'unnamed',
152 action, // 'activate', 'inspect', 'dismiss', 'ignore'
153 features: this.extractFeatures(component, context),
154 context: {
155 timeOfDay: this.getTimeOfDayFeature(),
156 dayOfWeek: new Date().getDay(),
157 noiseLevel: context.environment.noiseLevel,
158 viewerCount: context.environment.viewerCount,
159 userBusy: context.user.isBusy,
160 userFocus: context.user.inFocusMode
161 }
162 };
163
164 this.interactionHistory.push(interaction);
165
166 // Limit history size
167 if (this.interactionHistory.length > this.maxHistorySize) {
168 this.interactionHistory.shift();
169 }
170
171 // Add to training data if it's a positive engagement
172 if (action === 'activate' || action === 'inspect') {
173 this.trainingData.push({
174 features: interaction.features,
175 label: 1 // User engaged
176 });
177 } else if (action === 'dismiss' || action === 'ignore') {
178 this.trainingData.push({
179 features: interaction.features,
180 label: 0 // User didn't engage
181 });
182 }
183
184 // Retrain periodically
185 if (this.trainingData.length % 20 === 0) {
186 this.train();
187 }
188
189 this.saveHistoryToStorage();
190 }
191
192 /**
193 * Train the model on collected data
194 */
195 train() {
196 if (this.trainingData.length < 50) return;
197
198 console.log(`Training on ${this.trainingData.length} interactions...`);
199
200 // Simple gradient descent on weights
201 const learningRate = 0.01;
202 const epochs = 10;
203
204 for (let epoch = 0; epoch < epochs; epoch++) {
205 let totalError = 0;
206
207 for (const example of this.trainingData) {
208 const predicted = this.predict(example.features);
209 const error = example.label - predicted;
210 totalError += Math.abs(error);
211
212 // Update weights
213 for (const key in this.weights) {
214 if (example.features[key] !== undefined) {
215 this.weights[key] += learningRate * error * example.features[key];
216 }
217 }
218 }
219
220 if (epoch % 5 === 0) {
221 console.log(`Epoch ${epoch}, Avg Error: ${(totalError / this.trainingData.length).toFixed(4)}`);
222 }
223 }
224
225 console.log('Training complete. New weights:', this.weights);
226 }
227
228 /**
229 * Predict engagement probability
230 */
231 predict(features) {
232 let score = 0;
233 for (const key in this.weights) {
234 if (features[key] !== undefined) {
235 score += this.weights[key] * features[key];
236 }
237 }
238 return 1 / (1 + Math.exp(-score)); // Sigmoid activation
239 }
240
241 /**
242 * Find time-based patterns in user engagement
243 */
244 findTimePattern(currentTime) {
245 const relevantInteractions = this.interactionHistory.filter(i => {
246 const timeDiff = Math.abs(i.features.timeOfDay - currentTime);
247 return timeDiff < 0.1; // Within ~2.4 hours
248 });
249
250 if (relevantInteractions.length < 5) return 0;
251
252 const engagementRate = relevantInteractions.filter(i =>
253 i.action === 'activate' || i.action === 'inspect'
254 ).length / relevantInteractions.length;
255
256 return (engagementRate - 0.5) * 2; // Normalize to [-1, 1]
257 }
258
259 /**
260 * Find similarity patterns
261 */
262 findSimilarityPattern(features) {
263 const similarInteractions = this.interactionHistory.filter(i => {
264 const similarity = this.cosineSimilarity(features, i.features);
265 return similarity > 0.7;
266 });
267
268 if (similarInteractions.length < 3) return 0;
269
270 const engagementRate = similarInteractions.filter(i =>
271 i.action === 'activate' || i.action === 'inspect'
272 ).length / similarInteractions.length;
273
274 return (engagementRate - 0.5) * 2;
275 }
276
277 /**
278 * Find context-dependent patterns
279 */
280 findContextPattern(features) {
281 const contextKey = `${features.userBusy}_${features.userFocus}_${Math.floor(features.noiseLevel * 4)}`;
282
283 const contextInteractions = this.interactionHistory.filter(i => {
284 const key = `${i.context.userBusy}_${i.context.userFocus}_${Math.floor(i.context.noiseLevel / 25)}`;
285 return key === contextKey;
286 });
287
288 if (contextInteractions.length < 5) return 0;
289
290 const engagementRate = contextInteractions.filter(i =>
291 i.action === 'activate' || i.action === 'inspect'
292 ).length / contextInteractions.length;
293
294 return (engagementRate - 0.5) * 2;
295 }
296
297 /**
298 * Calculate cosine similarity between feature vectors
299 */
300 cosineSimilarity(f1, f2) {
301 const keys = new Set([...Object.keys(f1), ...Object.keys(f2)]);
302 let dotProduct = 0;
303 let mag1 = 0;
304 let mag2 = 0;
305
306 keys.forEach(key => {
307 const v1 = f1[key] || 0;
308 const v2 = f2[key] || 0;
309 dotProduct += v1 * v2;
310 mag1 += v1 * v1;
311 mag2 += v2 * v2;
312 });
313
314 if (mag1 === 0 || mag2 === 0) return 0;
315 return dotProduct / (Math.sqrt(mag1) * Math.sqrt(mag2));
316 }
317
318 /**
319 * Helper: Get urgency numeric value
320 */
321 getUrgencyValue(urgency) {
322 const map = { 'critical': 3, 'high': 2, 'medium': 1, 'low': 0 };
323 return map[urgency] || 1;
324 }
325
326 /**
327 * Helper: Get priority numeric value
328 */
329 getPriorityValue(priority) {
330 const map = {
331 'user-initiated': 5,
332 'system-critical': 4,
333 'time-sensitive': 3,
334 'user-requested': 2,
335 'passive-info': 1,
336 'promotional': 0
337 };
338 return map[priority] || 1;
339 }
340
341 /**
342 * Helper: Time of day as 0-1 value
343 */
344 getTimeOfDayFeature() {
345 const hour = new Date().getHours();
346 return hour / 24;
347 }
348
349 /**
350 * Helper: Historical engagement for component
351 */
352 getHistoricalEngagement(component) {
353 const componentId = component.id || component.tagName.toLowerCase();
354 const interactions = this.interactionHistory.filter(i =>
355 i.componentId === componentId || i.componentType === componentId
356 );
357
358 if (interactions.length === 0) return 0.5; // Neutral
359
360 const engaged = interactions.filter(i =>
361 i.action === 'activate' || i.action === 'inspect'
362 ).length;
363
364 return engaged / interactions.length;
365 }
366
367 /**
368 * Helper: Context similarity to past successful interactions
369 */
370 getContextSimilarity(context) {
371 const successfulInteractions = this.interactionHistory.filter(i =>
372 i.action === 'activate' || i.action === 'inspect'
373 );
374
375 if (successfulInteractions.length === 0) return 0.5;
376
377 const currentContext = {
378 timeOfDay: this.getTimeOfDayFeature(),
379 noiseLevel: context.environment.noiseLevel / 100,
380 viewerCount: Math.log(context.environment.viewerCount + 1),
381 userBusy: context.user.isBusy ? 1 : 0,
382 userFocus: context.user.inFocusMode ? 1 : 0
383 };
384
385 const similarities = successfulInteractions.map(i =>
386 this.cosineSimilarity(currentContext, {
387 timeOfDay: i.context.timeOfDay / 24,
388 noiseLevel: i.context.noiseLevel / 100,
389 viewerCount: Math.log(i.context.viewerCount + 1),
390 userBusy: i.context.userBusy ? 1 : 0,
391 userFocus: i.context.userFocus ? 1 : 0
392 })
393 );
394
395 return similarities.reduce((a, b) => a + b, 0) / similarities.length;
396 }
397
398 /**
399 * Helper: Recency factor
400 */
401 getRecencyFactor(component) {
402 const componentId = component.id || component.tagName.toLowerCase();
403 const lastInteraction = this.interactionHistory
404 .reverse()
405 .find(i => i.componentId === componentId || i.componentType === componentId);
406
407 if (!lastInteraction) return 1; // New component
408
409 const hoursSince = (Date.now() - lastInteraction.timestamp) / (1000 * 60 * 60);
410 return Math.exp(-hoursSince / 24); // Decay over 24 hours
411 }
412
413 /**
414 * Helper: Frequency factor
415 */
416 getFrequencyFactor(component) {
417 const componentId = component.id || component.tagName.toLowerCase();
418 const last24h = Date.now() - (24 * 60 * 60 * 1000);
419
420 const recentInteractions = this.interactionHistory.filter(i =>
421 (i.componentId === componentId || i.componentType === componentId) &&
422 i.timestamp > last24h
423 );
424
425 return Math.min(1, recentInteractions.length / 10);
426 }
427
428 /**
429 * Save interaction history to localStorage
430 */
431 saveHistoryToStorage() {
432 try {
433 localStorage.setItem('semantic-ml-history', JSON.stringify({
434 history: this.interactionHistory.slice(-500), // Save last 500
435 weights: this.weights,
436 timestamp: Date.now()
437 }));
438 } catch (e) {
439 console.warn('Could not save ML history:', e);
440 }
441 }
442
443 /**
444 * Load interaction history from localStorage
445 */
446 loadHistoryFromStorage() {
447 try {
448 const stored = localStorage.getItem('semantic-ml-history');
449 if (stored) {
450 const data = JSON.parse(stored);
451 this.interactionHistory = data.history || [];
452 this.weights = { ...this.weights, ...data.weights };
453 console.log(`Loaded ${this.interactionHistory.length} historical interactions`);
454 }
455 } catch (e) {
456 console.warn('Could not load ML history:', e);
457 }
458 }
459
460 /**
461 * Start learning from user interactions
462 */
463 startLearning() {
464 // Listen to all intents
465 document.addEventListener('intent', (e) => {
466 const component = e.target;
467 const action = e.detail.type;
468
469 if (window.semanticContext) {
470 this.recordInteraction(component, action, window.semanticContext.context);
471 }
472 });
473
474 console.log('ML learning started');
475 }
476
477 /**
478 * Get insights about learned patterns
479 */
480 getInsights() {
481 return {
482 totalInteractions: this.interactionHistory.length,
483 trainingExamples: this.trainingData.length,
484 weights: this.weights,
485 engagementRate: this.calculateOverallEngagementRate(),
486 topEngagedComponents: this.getTopEngagedComponents(),
487 bestTimes: this.getBestEngagementTimes()
488 };
489 }
490
491 calculateOverallEngagementRate() {
492 if (this.interactionHistory.length === 0) return 0;
493
494 const engaged = this.interactionHistory.filter(i =>
495 i.action === 'activate' || i.action === 'inspect'
496 ).length;
497
498 return (engaged / this.interactionHistory.length * 100).toFixed(1) + '%';
499 }
500
501 getTopEngagedComponents() {
502 const componentCounts = {};
503
504 this.interactionHistory
505 .filter(i => i.action === 'activate' || i.action === 'inspect')
506 .forEach(i => {
507 const key = i.componentId || i.componentType;
508 componentCounts[key] = (componentCounts[key] || 0) + 1;
509 });
510
511 return Object.entries(componentCounts)
512 .sort(([, a], [, b]) => b - a)
513 .slice(0, 5)
514 .map(([name, count]) => ({ name, count }));
515 }
516
517 getBestEngagementTimes() {
518 const hourCounts = Array(24).fill(0);
519 const hourEngaged = Array(24).fill(0);
520
521 this.interactionHistory.forEach(i => {
522 const hour = new Date(i.timestamp).getHours();
523 hourCounts[hour]++;
524 if (i.action === 'activate' || i.action === 'inspect') {
525 hourEngaged[hour]++;
526 }
527 });
528
529 const rates = hourCounts.map((count, hour) => ({
530 hour,
531 rate: count > 0 ? hourEngaged[hour] / count : 0
532 }));
533
534 return rates
535 .sort((a, b) => b.rate - a.rate)
536 .slice(0, 3)
537 .filter(r => r.rate > 0)
538 .map(r => ({ hour: `${r.hour}:00`, rate: (r.rate * 100).toFixed(0) + '%' }));
539 }
540}
541
542// Initialize ML scorer
543if (typeof window !== 'undefined') {
544 window.addEventListener('DOMContentLoaded', () => {
545 if (window.semanticContext) {
546 window.mlAttentionScorer = new MLAttentionScorer(window.semanticContext);
547
548 // Integrate with context manager
549 const originalAllocate = window.semanticContext.allocateAttention;
550 window.semanticContext.allocateAttention = function() {
551 // Use ML scoring instead of basic scoring
552 const needsAttention = Array.from(this.components)
553 .filter(c => c.computeAttentionScore)
554 .map(c => ({
555 component: c,
556 score: window.mlAttentionScorer.calculateScore(c, this.context)
557 }))
558 .sort((a, b) => b.score - a.score);
559
560 // Rest of allocation logic...
561 let screenUsed = 0;
562 let audioUsed = 0;
563 let cognitiveUsed = 0;
564
565 needsAttention.forEach(({ component, score }) => {
566 const needs = component.getAttentionNeeds();
567
568 const canAllocate =
569 screenUsed + needs.screen <= this.context.attention.maxScreenSpace &&
570 audioUsed + needs.audio <= this.context.attention.maxAudioTime &&
571 cognitiveUsed + needs.cognitive <= this.context.attention.maxCognitiveLoad;
572
573 if (canAllocate && score > 10) {
574 component.setAttribute('attention-state', 'allocated');
575 component.setAttribute('data-ml-score', Math.round(score));
576 screenUsed += needs.screen;
577 audioUsed += needs.audio;
578 cognitiveUsed += needs.cognitive;
579 } else {
580 component.setAttribute('attention-state', 'deferred');
581 }
582 });
583
584 this.context.attention.usedScreenSpace = screenUsed;
585 this.context.attention.usedAudioTime = audioUsed;
586 this.context.attention.usedCognitiveLoad = cognitiveUsed;
587 };
588
589 console.log('ML Attention Scoring enabled');
590 console.log('Get insights: window.mlAttentionScorer.getInsights()');
591 }
592 });
593}
594
595// Export
596if (typeof module !== 'undefined' && module.exports) {
597 module.exports = MLAttentionScorer;
598}