-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgallery.ts
More file actions
131 lines (108 loc) · 4.8 KB
/
Copy pathgallery.ts
File metadata and controls
131 lines (108 loc) · 4.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
import * as fs from 'fs';
import * as path from 'path';
import { PhotoData } from "./types";
const constrainRange = (val: number, min: number, max: number) => Math.max(Math.min(val, max), min);
class Gallery {
private images: Map<string, { data: PhotoData; lastShown: number; shownCount: number }> = new Map();
private gallerySize: number;
private currentTick: number = 0;
constructor(gallerySize: number, cachePath?: string) {
this.gallerySize = gallerySize;
// Load images from cachePath
if (cachePath && fs.existsSync(cachePath) && fs.statSync(cachePath).isDirectory()) {
const files = fs.readdirSync(cachePath);
for (const file of files) {
if (file.endsWith('.json')) {
try {
const fullPath = path.join(cachePath, file);
const raw = fs.readFileSync(fullPath, 'utf-8');
const parsed = JSON.parse(raw);
// Validate and coerce types
if (parsed.timestamp && parsed.finalScore !== null && parsed.filename) {
const photo: PhotoData = {
...parsed,
timestamp: new Date(parsed.timestamp)
};
this.addImage(photo);
if (this.images.size >= this.gallerySize) break;
}
} catch (err) {
console.warn(`Failed to load image from ${file}:`, err);
}
}
}
} else {
console.warn(`Invalid cachePath: ${cachePath}`);
}
}
addImage(img: PhotoData) {
const key = img.filename;
if (this.images.has(key)) {
this.images.set(key, {
...this.images.get(key)!,
data: img, // update timestamp/score if needed
});
return;
}
if (this.images.size >= this.gallerySize) {
// Remove least recently shown or lowest score image
const toRemove = [...this.images.entries()].sort((a, b) => {
const ageA = this.currentTick - a[1].lastShown;
const ageB = this.currentTick - b[1].lastShown;
const scoreA = a[1].data.finalScore || 0;
const scoreB = b[1].data.finalScore || 0;
return ageA !== ageB ? ageA - ageB : scoreA - scoreB;
})[0];
this.images.delete(toRemove[0]);
}
this.images.set(key, {
data: img,
lastShown: -Infinity,
shownCount: 0,
});
}
getNextImage(): PhotoData | null {
if (this.images.size === 0) return null;
this.currentTick++;
const now = Date.now();
const scoredImages = [...this.images.values()].map((entry) => {
// Fresh: recently taken is better (0.5 - 2)
const ageMinutes = (now - entry.data.timestamp.getTime()) / 1000 / 60;
const decayTimeMinutes = 30;
const freshnessWeight = constrainRange(2 - (ageMinutes / decayTimeMinutes), 0.5, 2);
// Score: better is better (0.5 - 1.5), assume min score is 5
const scoreWeight = (Math.max((entry.data.finalScore || 0) - 5, 0) / 10) + 0.5;
// Rarity: not seen much is better (0.5 - 1.5)
const thisImageShownFraction = (entry.shownCount / this.currentTick);
const rarityWeight = 2 - constrainRange(thisImageShownFraction * this.images.size, 0.5, 1.5);
// Recency weight: not shown recently is better (0.1 - 3)
const sinceLastShown = this.currentTick - entry.lastShown;
const recencyWeight = constrainRange(sinceLastShown / this.images.size, 0.1, 3)
// Multiply
const weight = freshnessWeight * scoreWeight * rarityWeight * recencyWeight;
return {
entry,
weights: { freshnessWeight, scoreWeight, rarityWeight, recencyWeight },
weight,
};
});
console.log(scoredImages);
const totalWeight = scoredImages.reduce((sum, item) => sum + item.weight, 0);
const rand = Math.random() * totalWeight;
let acc = 0;
for (const { entry, weight } of scoredImages) {
acc += weight;
if (rand <= acc) {
entry.lastShown = this.currentTick;
entry.shownCount++;
return entry.data;
}
}
// Fallback (shouldn't happen): return a random image
const fallback = [...this.images.values()][0];
fallback.lastShown = this.currentTick;
fallback.shownCount++;
return fallback.data;
}
}
export default Gallery;