-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
157 lines (127 loc) · 5.49 KB
/
script.js
File metadata and controls
157 lines (127 loc) · 5.49 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
let pyodide;
async function initializePyodide() {
try {
document.getElementById('loading').textContent = 'Loading Pyodide...';
document.getElementById('loading').classList.remove('hidden');
pyodide = await loadPyodide();
document.getElementById('loading').textContent = 'Loading packages...';
await pyodide.loadPackage(["numpy", "scikit-learn", "pandas"]);
// Add a small delay before finalizing
await new Promise(resolve => setTimeout(resolve, 1000));
document.querySelector('button').disabled = false;
document.getElementById('loading').textContent = 'Ready!';
setTimeout(() => {
document.getElementById('loading').classList.add('hidden');
}, 2000);
} catch (error) {
console.error('Failed to initialize Pyodide:', error);
document.getElementById('loading').textContent = 'Failed to load. Please refresh the page and try again.';
}
}
document.addEventListener('DOMContentLoaded', () => {
document.querySelector('button').disabled = true;
initializePyodide();
});
function showError(message) {
const errorElement = document.getElementById('error');
errorElement.textContent = message;
errorElement.classList.remove('hidden');
}
function hideError() {
document.getElementById('error').classList.add('hidden');
}
function isValidHexCode(hexCode) {
return /^#[0-9A-Fa-f]{6}$/.test(hexCode);
}
async function processColors() {
hideError();
const hexInput = document.getElementById('hexInput').value;
const hexcodes = hexInput.split('\n').map(code => code.trim()).filter(code => code !== '');
if (hexcodes.length === 0) {
showError('Please enter at least one hexcode.');
return;
}
const invalidHexcodes = hexcodes.filter(code => !isValidHexCode(code));
if (invalidHexcodes.length > 0) {
showError(`Invalid hexcodes: ${invalidHexcodes.join(', ')}`);
return;
}
const numClusters = parseInt(document.getElementById('numClusters').value);
if (isNaN(numClusters) || numClusters < 1 || numClusters > 20) {
showError('Number of clusters must be between 1 and 20.');
return;
}
document.getElementById('loading').textContent = 'Processing colors...';
document.getElementById('loading').classList.remove('hidden');
try {
const result = await pyodide.runPythonAsync(`
import numpy as np
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
import json
def process_colors(hexcodes, n_clusters):
def hex_to_rgb(hex_color):
hex_color = hex_color.lstrip('#')
return tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4))
def rgb_to_hsl(r, g, b):
r, g, b = r/255.0, g/255.0, b/255.0
cmax = max(r, g, b)
cmin = min(r, g, b)
delta = cmax - cmin
l = (cmax + cmin) / 2
if delta == 0:
h = 0
s = 0
elif cmax == r:
h = ((g - b) / delta) % 6
elif cmax == g:
h = (b - r) / delta + 2
else:
h = (r - g) / delta + 4
h *= 60
if delta == 0:
s = 0
else:
s = delta / (1 - abs(2 * l - 1))
return (h, s, l)
rgb_values = np.array([hex_to_rgb(hex_code) for hex_code in hexcodes])
hsl_values = np.array([rgb_to_hsl(*rgb) for rgb in rgb_values])
scaler = StandardScaler()
hsl_normalized = scaler.fit_transform(hsl_values)
kmeans = KMeans(n_clusters=n_clusters, random_state=42)
clusters = kmeans.fit_predict(hsl_normalized)
sorted_colors = []
for cluster in range(n_clusters):
cluster_colors = [hexcodes[i] for i in range(len(hexcodes)) if clusters[i] == cluster]
cluster_hsl = [hsl_values[i] for i in range(len(hexcodes)) if clusters[i] == cluster]
sorted_cluster = [x for _, x in sorted(zip(cluster_hsl, cluster_colors), key=lambda pair: (pair[0][0], pair[0][1], pair[0][2]))]
sorted_colors.extend(sorted_cluster)
return {
'colors': sorted_colors,
'values': [1] * len(sorted_colors)
}
result = process_colors(${JSON.stringify(hexcodes)}, ${numClusters})
json.dumps(result)
`);
const plotData = JSON.parse(result);
const layout = {
title: 'Color Palette (Sorted by HSL Color Space)',
xaxis: { title: 'Color Index' },
yaxis: { title: '' },
showlegend: false,
height: 400
};
Plotly.newPlot('result', [{
x: Array.from({ length: plotData.colors.length }, (_, i) => i),
y: plotData.values,
type: 'bar',
marker: { color: plotData.colors },
hovertext: plotData.colors,
hoverinfo: 'text'
}], layout);
} catch (error) {
showError(`An error occurred: ${error.message}`);
} finally {
document.getElementById('loading').classList.add('hidden');
}
}