Okay, creating a single HTML file that handles text input, reordering, ONNX model inference (embeddings), correlation calculation, linear regression training, and prediction entirely within the browser is ambitious but feasible using modern web technologies like ONNX Runtime Web and Transformers.js.
Key Challenges & Considerations:
- Model Loading: The
model.onnx (67.4 MB) needs to be downloaded by the browser. This will happen once when the page loads. We'll load it directly from the Hugging Face Hub URL.
- Performance: Calculating embeddings for ~100 text blocks and performing correlation/regression might take noticeable time, especially on less powerful devices. We need to provide user feedback.
- Dependencies: We need external JavaScript libraries (ONNX Runtime Web, Transformers.js for tokenization/pipeline, a regression library). We'll use CDNs.
- Complexity: This involves asynchronous operations, data manipulation, and statistical calculations all in JavaScript.
- Reordering: We'll implement simple "Move Up" / "Move Down" buttons for reordering, as full drag-and-drop adds significant complexity. The order in the list defines the rank.
- GTE Pooling: General Text Embedding (GTE) models require specific pooling (usually mean pooling of last hidden states, respecting attention masks) to get a single sentence embedding vector. Transformers.js's
pipeline API often handles this correctly.
Here is the HTML file structure. Copy and save this code as an .html file (e.g., rank_predictor.html) and open it in a modern web browser.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Text Rank Predictor</title>
<style>
body { font-family: sans-serif; line-height: 1.6; padding: 20px; max-width: 900px; margin: auto; }
.container { margin-bottom: 20px; padding: 15px; border: 1px solid #ccc; border-radius: 5px; }
h2, h3 { margin-top: 0; }
textarea { width: 95%; min-height: 60px; margin-bottom: 10px; display: block; }
button { padding: 10px 15px; margin-right: 10px; cursor: pointer; background-color: #007bff; color: white; border: none; border-radius: 3px; }
button:hover { background-color: #0056b3; }
button:disabled { background-color: #aaa; cursor: not-allowed; }
#textBlockList > div { border: 1px dashed #eee; padding: 10px; margin-bottom: 10px; background-color: #f9f9f9; display: flex; justify-content: space-between; align-items: center; }
#textBlockList span { flex-grow: 1; margin-right: 10px; white-space: pre-wrap; word-break: break-word; }
#textBlockList .controls button { padding: 3px 8px; font-size: 0.8em; margin-left: 5px; }
#status { margin-top: 15px; font-weight: bold; color: #333; }
#results { margin-top: 15px; background-color: #e9f7ef; padding: 10px; border-radius: 3px; }
pre { background-color: #eee; padding: 10px; border-radius: 3px; overflow-x: auto; }
.error { color: red; font-weight: bold; }
.info { color: blue; }
</style>
<!-- ONNX Runtime Web -->
<script src="https://cdn.jsdelivr.net/npm/onnxruntime-web/dist/ort.min.js"></script>
<!-- Transformers.js -->
<script type="importmap">
{
"imports": {
"@xenova/transformers": "https://cdn.jsdelivr.net/npm/@xenova/transformers@2.17.1"
}
}
</script>
<!-- Regression-JS -->
<script src="https://cdn.jsdelivr.net/npm/regression@2.0.1/dist/regression.min.js"></script>
</head>
<body>
<h1>Text Rank Predictor using mini-gte-onnx</h1>
<div class="container">
<h2>1. Add Text Blocks</h2>
<textarea id="newTextInput" placeholder="Enter text here..."></textarea>
<button id="addTextBtn">Add Text Block</button>
<p><span id="blockCount">0</span> blocks added.</p>
</div>
<div class="container">
<h2>2. Arrange Text Blocks</h2>
<p>Use the Up/Down buttons to order the blocks. The topmost block is rank 1 (target value 1.0), the bottommost is rank N (target value 0.0).</p>
<div id="textBlockList"></div>
</div>
<div class="container">
<h2>3. Train Model</h2>
<button id="trainModelBtn" disabled>Calculate Embeddings & Train Rank Predictor</button>
<div id="status">Status: Waiting for model setup...</div>
<div id="trainingResults" style="display: none;">
<h3>Training Complete</h3>
<p>Model trained using the top 5 embedding dimensions most correlated with rank.</p>
<p>Selected Dimensions (Indices): <code id="selectedDims"></code></p>
<p>R-squared values: <code id="rSquaredVals"></code></p>
<p>Linear Regression Model (Coefficients + Intercept):</p>
<pre id="regressionModelOutput"></pre>
</div>
</div>
<div class="container">
<h2>4. Predict Rank for New Text</h2>
<textarea id="predictTextInput" placeholder="Enter new text here to predict its rank..."></textarea>
<button id="predictRankBtn" disabled>Predict Rank</button>
<div id="predictionResult" style="display: none;">
<h3>Predicted Normalized Rank: <span id="predictedRank"></span></h3>
<p>(Rank 1.0 = Top, Rank 0.0 = Bottom, based on the training data order)</p>
</div>
</div>
<script type="module">
// Import necessary modules
import { pipeline, env } from '@xenova/transformers';
// --- Configuration ---
// Disable local model checks for Transformers.js (we load ONNX directly or via pipeline)
env.allowLocalModels = false;
// Use WebAssembly backend for ONNX Runtime for better performance
ort.env.wasm.wasmPaths = 'https://cdn.jsdelivr.net/npm/onnxruntime-web/dist/';
const MODEL_REPO = 'RainbowPiBubbles/mini-gte-onnx';
const MIN_BLOCKS_FOR_TRAINING = 10; // Need enough data points
// --- State Variables ---
let textBlocks = []; // Array of { id: number, text: string, embedding: Float32Array | null }
let nextId = 0;
let featureExtractor = null;
let regressionModel = null;
let topDimensionIndices = []; // Stores indices of top 5 dimensions
// --- DOM Elements ---
const addTextBtn = document.getElementById('addTextBtn');
const newTextInput = document.getElementById('newTextInput');
const textBlockListDiv = document.getElementById('textBlockList');
const blockCountSpan = document.getElementById('blockCount');
const trainModelBtn = document.getElementById('trainModelBtn');
const predictRankBtn = document.getElementById('predictRankBtn');
const predictTextInput = document.getElementById('predictTextInput');
const statusDiv = document.getElementById('status');
const trainingResultsDiv = document.getElementById('trainingResults');
const selectedDimsSpan = document.getElementById('selectedDims');
const rSquaredValsSpan = document.getElementById('rSquaredVals');
const regressionModelOutput = document.getElementById('regressionModelOutput');
const predictionResultDiv = document.getElementById('predictionResult');
const predictedRankSpan = document.getElementById('predictedRank');
// --- Utility Functions ---
function updateStatus(message, type = 'info') {
statusDiv.textContent = `Status: ${message}`;
statusDiv.className = type; // 'info' or 'error'
console.log(`Status (${type}): ${message}`);
}
function renderTextBlocks() {
textBlockListDiv.innerHTML = ''; // Clear current list
textBlocks.forEach((block, index) => {
const div = document.createElement('div');
div.dataset.id = block.id;
const textSpan = document.createElement('span');
textSpan.textContent = `${index + 1}. ${block.text}`; // Display rank and text
div.appendChild(textSpan);
const controlsDiv = document.createElement('div');
controlsDiv.className = 'controls';
const upBtn = document.createElement('button');
upBtn.textContent = 'Up';
upBtn.onclick = () => moveBlock(block.id, -1);
upBtn.disabled = index === 0;
controlsDiv.appendChild(upBtn);
const downBtn = document.createElement('button');
downBtn.textContent = 'Down';
downBtn.onclick = () => moveBlock(block.id, 1);
downBtn.disabled = index === textBlocks.length - 1;
controlsDiv.appendChild(downBtn);
const deleteBtn = document.createElement('button');
deleteBtn.textContent = 'Delete';
deleteBtn.style.backgroundColor = '#dc3545';
deleteBtn.onclick = () => deleteBlock(block.id);
controlsDiv.appendChild(deleteBtn);
div.appendChild(controlsDiv);
textBlockListDiv.appendChild(div);
});
blockCountSpan.textContent = textBlocks.length;
trainModelBtn.disabled = textBlocks.length < MIN_BLOCKS_FOR_TRAINING || !featureExtractor;
predictRankBtn.disabled = !regressionModel; // Enable only after training
trainingResultsDiv.style.display = 'none'; // Hide old results on list change
predictionResultDiv.style.display = 'none'; // Hide old prediction on list change
}
function addBlock() {
const text = newTextInput.value.trim();
if (text) {
textBlocks.push({ id: nextId++, text: text, embedding: null });
newTextInput.value = '';
renderTextBlocks();
}
}
function deleteBlock(id) {
textBlocks = textBlocks.filter(block => block.id !== id);
renderTextBlocks();
}
function moveBlock(id, direction) { // direction: -1 for up, 1 for down
const index = textBlocks.findIndex(block => block.id === id);
if (index === -1) return;
const newIndex = index + direction;
if (newIndex < 0 || newIndex >= textBlocks.length) return; // Boundary check
// Swap elements
[textBlocks[index], textBlocks[newIndex]] = [textBlocks[newIndex], textBlocks[index]];
renderTextBlocks();
}
// Calculate Pearson Correlation Coefficient (r)
function calculatePearsonCorrelation(x, y) {
const n = x.length;
if (n === 0 || n !== y.length) return 0;
let sumX = 0, sumY = 0, sumXY = 0, sumX2 = 0, sumY2 = 0;
for (let i = 0; i < n; i++) {
sumX += x[i];
sumY += y[i];
sumXY += x[i] * y[i];
sumX2 += x[i] * x[i];
sumY2 += y[i] * y[i];
}
const numerator = n * sumXY - sumX * sumY;
const denominator = Math.sqrt((n * sumX2 - sumX * sumX) * (n * sumY2 - sumY * sumY));
if (denominator === 0) return 0; // Avoid division by zero (if all x or all y are constant)
return numerator / denominator;
}
// --- Core Logic ---
async function loadModel() {
try {
updateStatus('Loading feature extraction pipeline...');
// Transformers.js pipeline handles tokenization and ONNX loading
featureExtractor = await pipeline('feature-extraction', MODEL_REPO, {
quantized: false // Assuming the main model is not quantized, adjust if needed
// If using the quantized model, ensure transformers.js supports it or load manually
});
updateStatus('Model and tokenizer ready.');
trainModelBtn.disabled = textBlocks.length < MIN_BLOCKS_FOR_TRAINING;
} catch (error) {
updateStatus(`Error loading model: ${error}`, 'error');
console.error("Model loading failed:", error);
trainModelBtn.disabled = true;
}
}
async function calculateEmbeddingsAndTrain() {
if (textBlocks.length < MIN_BLOCKS_FOR_TRAINING) {
updateStatus(`Need at least ${MIN_BLOCKS_FOR_TRAINING} blocks to train.`, 'error');
return;
}
if (!featureExtractor) {
updateStatus(`Model not loaded yet. Please wait or reload.`, 'error');
return;
}
trainModelBtn.disabled = true;
predictRankBtn.disabled = true;
trainingResultsDiv.style.display = 'none';
regressionModel = null; // Clear previous model
topDimensionIndices = [];
try {
// 1. Calculate Embeddings
updateStatus(`Calculating embeddings for ${textBlocks.length} blocks...`);
const texts = textBlocks.map(block => block.text);
// Use batch processing if possible, otherwise one by one
// Transformers.js pipeline might handle batching internally
const embeddings = [];
for (let i = 0; i < texts.length; i++) {
updateStatus(`Calculating embedding for block ${i + 1}/${textBlocks.length}...`);
// The pipeline output needs extraction of the embedding tensor
// For GTE/sentence-transformers, it's often the first (and only) item in the pooler_output or just the output tensor
const output = await featureExtractor(texts[i], { pooling: 'mean', normalize: true });
// Output structure depends on transformers.js version and model. Inspect it.
// Assuming output.data contains the Float32Array embedding
if (output && output.data instanceof Float32Array) {
embeddings.push(output.data);
} else {
// Fallback/alternative structure check - adjust based on actual output
console.warn("Unexpected embedding output structure for block", i+1, ":", output);
// Attempt to find Float32Array data if nested differently
if (output && typeof output === 'object' && Object.values(output).find(v => v?.data instanceof Float32Array)) {
embeddings.push(Object.values(output).find(v => v.data instanceof Float32Array).data);
console.log("Found embedding data in nested property.");
} else {
throw new Error(`Could not extract embedding for block ${i + 1}. Output: ${JSON.stringify(output)}`);
}
}
textBlocks[i].embedding = embeddings[i]; // Store embedding
}
const embeddingDim = embeddings[0].length;
updateStatus(`Embeddings calculated (${embeddingDim} dimensions).`);
// 2. Calculate Normalized Ranks (Target Variable)
// Rank 1 (top) = 1.0, Rank N (bottom) = 0.0
const numBlocks = textBlocks.length;
const normalizedRanks = textBlocks.map((_, index) => {
// Linear scaling from 1 (index 0) to 0 (index N-1)
return numBlocks <= 1 ? 0.5 : 1.0 - (index / (numBlocks - 1));
});
// 3. Calculate Correlations (R-squared) for each dimension
updateStatus('Calculating correlations...');
const correlations = [];
for (let d = 0; d < embeddingDim; d++) {
const dimensionValues = embeddings.map(emb => emb[d]);
const r = calculatePearsonCorrelation(dimensionValues, normalizedRanks);
const rSquared = r * r; // R-squared
if (!isNaN(rSquared)) { // Handle potential NaN if variance is zero
correlations.push({ dimension: d, rSquared: rSquared });
} else {
correlations.push({ dimension: d, rSquared: 0 });
}
}
// 4. Select Top 5 Dimensions
correlations.sort((a, b) => b.rSquared - a.rSquared); // Sort descending by R-squared
topDimensionIndices = correlations.slice(0, 5).map(c => c.dimension);
const topRSquared = correlations.slice(0, 5).map(c => c.rSquared.toFixed(4));
updateStatus('Top 5 dimensions selected.');
selectedDimsSpan.textContent = topDimensionIndices.join(', ');
rSquaredValsSpan.textContent = topRSquared.join(', ');
// 5. Prepare Data for Linear Regression
// Data format for regression.js: array of arrays, where each inner array is [feature1, feature2, ..., feature5, target]
const regressionData = textBlocks.map((block, index) => {
const features = topDimensionIndices.map(dimIndex => block.embedding[dimIndex]);
return [...features, normalizedRanks[index]];
});
// 6. Train Linear Regression Model
updateStatus('Training linear regression model...');
// Using 'linear' for multiple linear regression
const result = regression.linear(regressionData, { precision: 6 }); // Increase precision if needed
regressionModel = {
coefficients: result.equation, // Array of coefficients [b1, b2, ..., b5, intercept]
predict: (features) => { // Prediction function based on the equation
let prediction = result.equation[features.length]; // Start with intercept
for (let i = 0; i < features.length; i++) {
prediction += result.equation[i] * features[i];
}
// Clamp prediction between 0 and 1 as it's a normalized rank
return Math.max(0, Math.min(1, prediction));
}
};
// Display regression model details
const coefficients = result.equation.slice(0, -1); // All but the last element (intercept)
const intercept = result.equation[result.equation.length - 1];
regressionModelOutput.textContent = `Coefficients (for dims ${topDimensionIndices.join(', ')}): ${coefficients.map(c => c.toFixed(4)).join(', ')}\nIntercept: ${intercept.toFixed(4)}`;
trainingResultsDiv.style.display = 'block';
updateStatus('Training complete. Ready to predict.');
predictRankBtn.disabled = false; // Enable prediction button
} catch (error) {
updateStatus(`Error during training: ${error}`, 'error');
console.error("Training failed:", error);
regressionModel = null;
topDimensionIndices = [];
} finally {
trainModelBtn.disabled = textBlocks.length < MIN_BLOCKS_FOR_TRAINING; // Re-enable if possible
}
}
async function predictRank() {
const text = predictTextInput.value.trim();
if (!text || !regressionModel || !featureExtractor || topDimensionIndices.length === 0) {
updateStatus('Cannot predict. Ensure text is entered and model is trained.', 'error');
predictionResultDiv.style.display = 'none';
return;
}
predictRankBtn.disabled = true;
updateStatus('Calculating embedding for prediction...');
try {
// 1. Calculate embedding for the new text
const output = await featureExtractor(text, { pooling: 'mean', normalize: true });
let embedding;
if (output && output.data instanceof Float32Array) {
embedding = output.data;
} else if (output && typeof output === 'object' && Object.values(output).find(v => v?.data instanceof Float32Array)) {
embedding = Object.values(output).find(v => v.data instanceof Float32Array).data;
} else {
throw new Error(`Could not extract embedding for prediction text. Output: ${JSON.stringify(output)}`);
}
// 2. Extract features using the top 5 dimensions identified during training
const features = topDimensionIndices.map(dimIndex => embedding[dimIndex]);
// 3. Predict using the trained regression model
const predictedNormalizedRank = regressionModel.predict(features);
// 4. Display result
predictedRankSpan.textContent = predictedNormalizedRank.toFixed(4);
predictionResultDiv.style.display = 'block';
updateStatus('Prediction complete.');
} catch (error) {
updateStatus(`Error during prediction: ${error}`, 'error');
console.error("Prediction failed:", error);
predictionResultDiv.style.display = 'none';
} finally {
predictRankBtn.disabled = !regressionModel; // Re-enable if model exists
}
}
// --- Event Listeners ---
addTextBtn.addEventListener('click', addBlock);
trainModelBtn.addEventListener('click', calculateEmbeddingsAndTrain);
predictRankBtn.addEventListener('click', predictRank);
// --- Initialization ---
renderTextBlocks(); // Initial render
loadModel(); // Start loading the model immediately
</script>
</body>
</html>