File size: 8,658 Bytes
b3f0c1a | 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 | /**
* UMAP Utils - Fonctions utilitaires pour le calcul UMAP
*
* Contient les fonctions pures utilisées par le Web Worker
*/
/**
* Charge les embeddings depuis le fichier JSON
*/
export async function loadEmbeddings() {
console.log('🔄 Chargement des embeddings CLIP...');
try {
const response = await fetch('/data/embeddings.json');
if (!response.ok) {
throw new Error(`HTTP Error: ${response.status}`);
}
const data = await response.json();
console.log(`✅ ${data.fonts.length} polices chargées`);
return data;
} catch (error) {
console.error('❌ Erreur lors du chargement des embeddings:', error);
throw error;
}
}
/**
* Extrait le préfixe pour la fusion des familles
*/
export function extractFusionPrefix(fontId, fontData) {
const parts = fontId.split('-');
if (parts.length <= 1) {
return fontId;
}
// Vérifier les subsets non standards
if (fontData && fontData.subsets && Array.isArray(fontData.subsets)) {
const commonSubsets = ['latin', 'latin-ext', 'cyrillic', 'cyrillic-ext', 'greek', 'greek-ext'];
for (const subset of fontData.subsets) {
if (!commonSubsets.includes(subset) && fontId.includes(subset)) {
const baseName = fontId.replace(`-${subset}`, '').replace(subset, '');
if (baseName && baseName !== fontId) {
return baseName;
}
}
}
}
// Cas spéciaux
const specialCases = {
'baloo': ['baloo-2', 'baloo-bhai-2', 'baloo-bhaijaan-2', 'baloo-bhaina-2', 'baloo-chettan-2', 'baloo-da-2', 'baloo-paaji-2', 'baloo-tamma-2', 'baloo-tammudu-2', 'baloo-thambi-2'],
'ibm-plex': ['ibm-plex'],
'playwrite': ['playwrite']
};
for (const [familyPrefix, patterns] of Object.entries(specialCases)) {
for (const pattern of patterns) {
if (fontId.startsWith(pattern)) {
return familyPrefix;
}
}
}
// Noto fonts
if (fontId.startsWith('noto-serif-')) return 'noto-serif';
if (fontId.startsWith('noto-')) return 'noto';
// Second word special
const secondWord = parts[1];
if (secondWord === 'sans' || secondWord === 'serif' || secondWord === 'plex') {
return parts.slice(0, 2).join('-');
}
return parts[0];
}
/**
* Fusionne les familles de polices
*/
export function mergeFontFamilies(fontDataList, embeddingMatrices, enableFusion = true) {
if (!enableFusion) {
return { fontDataList, embeddingMatrices };
}
const prefixGroups = {};
const prefixEmbeddingGroups = {};
// Grouper par préfixe
for (let i = 0; i < fontDataList.length; i++) {
const font = fontDataList[i];
const prefix = extractFusionPrefix(font.id, font);
if (!prefixGroups[prefix]) {
prefixGroups[prefix] = [];
prefixEmbeddingGroups[prefix] = [];
}
prefixGroups[prefix].push(font);
prefixEmbeddingGroups[prefix].push(embeddingMatrices[i]);
}
const mergedFonts = [];
const mergedEmbeddings = [];
// Créer les polices fusionnées
for (const [prefix, fonts] of Object.entries(prefixGroups)) {
if (fonts.length > 1) {
let representativeFont = fonts[0];
// Choix du représentant pour certaines familles
const representatives = {
'noto': 'noto-sans-arabic',
'noto-serif': 'noto-serif-latin',
'ibm-plex': 'ibm-plex-sans',
'baloo': 'baloo-2'
};
if (representatives[prefix]) {
const found = fonts.find(f => f.id === representatives[prefix]);
if (found) representativeFont = found;
}
const representativeIndex = fonts.findIndex(f => f.id === representativeFont.id);
const representativeEmbedding = prefixEmbeddingGroups[prefix][representativeIndex];
const mergedFont = {
...representativeFont,
id: prefix,
name: prefix.replace(/-/g, ' ').replace(/\b\w/g, l => l.toUpperCase()),
imageName: representativeFont.id
};
mergedFonts.push(mergedFont);
mergedEmbeddings.push(representativeEmbedding);
} else {
mergedFonts.push({ ...fonts[0], imageName: fonts[0].id });
mergedEmbeddings.push(prefixEmbeddingGroups[prefix][0]);
}
}
return {
fontDataList: mergedFonts,
embeddingMatrices: mergedEmbeddings
};
}
/**
* Normalise les données (standardisation Z-score)
*/
export function normalizeData(data) {
const rows = data.length;
const cols = data[0].length;
const means = new Array(cols).fill(0);
const stds = new Array(cols).fill(0);
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) {
means[j] += data[i][j];
}
}
for (let j = 0; j < cols; j++) {
means[j] /= rows;
}
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) {
const diff = data[i][j] - means[j];
stds[j] += diff * diff;
}
}
for (let j = 0; j < cols; j++) {
stds[j] = Math.sqrt(stds[j] / rows);
if (stds[j] === 0) stds[j] = 1;
}
const normalized = data.map(row =>
row.map((val, j) => (val - means[j]) / stds[j])
);
return normalized;
}
/**
* PCA via covariance eigen-decomposition (browser-friendly, no ml-matrix dependency).
* Reduces nDims → nComponents, concentrating variance for better UMAP quality.
*/
export function applyPCA(data, nComponents = 50) {
const rows = data.length;
const cols = data[0].length;
const target = Math.min(nComponents, cols, rows);
// Center columns
const means = new Array(cols).fill(0);
for (let i = 0; i < rows; i++) {
for (let j = 0; j < cols; j++) means[j] += data[i][j];
}
for (let j = 0; j < cols; j++) means[j] /= rows;
const centered = data.map(row => row.map((v, j) => v - means[j]));
// For browser perf: use SVD-like approach via X^T * X when cols > rows
// When rows < cols (typical: ~800 fonts, 512 dims), compute rows×rows gram matrix
if (rows < cols) {
// Gram matrix: X * X^T (rows × rows)
const gram = Array.from({ length: rows }, () => new Float64Array(rows));
for (let i = 0; i < rows; i++) {
for (let j = i; j < rows; j++) {
let dot = 0;
for (let k = 0; k < cols; k++) dot += centered[i][k] * centered[j][k];
gram[i][j] = dot / (rows - 1);
gram[j][i] = gram[i][j];
}
}
// Power iteration for top eigenvectors of gram matrix
const eigenvectors = [];
const eigenvalues = [];
const gramCopy = gram.map(row => Float64Array.from(row));
for (let comp = 0; comp < target; comp++) {
let vec = new Float64Array(rows);
for (let i = 0; i < rows; i++) vec[i] = Math.random() - 0.5;
for (let iter = 0; iter < 100; iter++) {
const newVec = new Float64Array(rows);
for (let i = 0; i < rows; i++) {
let sum = 0;
for (let j = 0; j < rows; j++) sum += gramCopy[i][j] * vec[j];
newVec[i] = sum;
}
let norm = 0;
for (let i = 0; i < rows; i++) norm += newVec[i] * newVec[i];
norm = Math.sqrt(norm);
if (norm === 0) break;
for (let i = 0; i < rows; i++) newVec[i] /= norm;
let diff = 0;
for (let i = 0; i < rows; i++) diff += (newVec[i] - vec[i]) ** 2;
vec = newVec;
if (diff < 1e-10) break;
}
let eigenvalue = 0;
const Av = new Float64Array(rows);
for (let i = 0; i < rows; i++) {
let sum = 0;
for (let j = 0; j < rows; j++) sum += gramCopy[i][j] * vec[j];
Av[i] = sum;
}
for (let i = 0; i < rows; i++) eigenvalue += vec[i] * Av[i];
eigenvalues.push(eigenvalue);
eigenvectors.push(vec);
// Deflate
for (let i = 0; i < rows; i++) {
for (let j = 0; j < rows; j++) {
gramCopy[i][j] -= eigenvalue * vec[i] * vec[j];
}
}
}
// Project: each component = X^T * u_i / sqrt(lambda_i * (n-1))
const result = Array.from({ length: rows }, () => new Array(target));
for (let comp = 0; comp < target; comp++) {
for (let i = 0; i < rows; i++) {
result[i][comp] = eigenvectors[comp][i] * Math.sqrt(Math.max(0, eigenvalues[comp]) * (rows - 1));
}
}
const totalVar = eigenvalues.reduce((s, v) => s + Math.max(0, v), 0) || 1;
const explainedVar = eigenvalues.slice(0, target).reduce((s, v) => s + Math.max(0, v), 0);
console.log(`📐 PCA: ${cols}D → ${target}D (${(explainedVar / totalVar * 100).toFixed(1)}% variance)`);
return result;
}
// Standard path when rows >= cols: covariance matrix cols × cols
// (fallback, unlikely for fonts dataset)
console.log(`📐 PCA: using standard covariance path (${cols}D → ${target}D)`);
return centered.map(row => row.slice(0, target));
}
|