Here's a thinking process that leads to the suggested search platform implementation:
-
Analyze the Request:
- Goal: Create a search platform with hybrid ANN/BM25 retrieval and re-ranking.
- Role: Advanced front-end engineer and visual designer (neo-brutalism / Y2K).
- Style: Raw typography, hard borders, clashing colors, unpolished look, glitch effects, marquee, retro UI, overlapping.
- Tech Stack: HTML, Tailwind CSS, GSAP, Canvas/WebGL. (Since the file must be standalone, I need to use CDN links for Tailwind and GSAP, and JS logic to simulate the "backend" search behavior directly in the browser).
- Constraint: Single file, no external dependencies that require build steps, no alerts, functional interactive elements.
-
Conceptualize the Application:
- Theme: A search engine that looks like a chaotic time capsule, "Kind of like a junkyard but functional."
- Layout:
- Header: Huge, aggressive marquee text: "SEARCH THE VOID / HYBRID RETRIEVAL / BM25 + ANN / RERANKING ACTIVE".
- Input area: Brutalist search bar with a pixelated "GO" button.
- Results area: Split view? Or masonry? Let's go with a grid that feels aggressive but readable.
- Visuals: High saturation neon colors (pink, lime, cyan) against stark white/black.
- Typography: Mix of Courier New (code-like) and Impact/Arial Black (huge headers).
-
Simulate the Backend Logic (Frontend-side simulation):
- Since I cannot connect to a real Python backend with Annoy or Faiss in a single HTML file, I must mock the hybrid retrieval process.
- Data: A JSON array of "documents" (fake search data). Needs text content, a score vector (simulating embeddings), and metadata.
- Algorithm (The "Academic" part):
- BM25: Simulate a TF-IDF/BM25 score calculation based on query terms in the document text.
- ANN: Simulate a vector similarity search using random math (dot product on fake vectors).
- Hybrid: Weighted sum (
alpha * ANN + (1-alpha) * BM25).
- Re-ranking: Apply a "re-ranking" step using Cross-Encoder simulation (or just adjusting weights based on "relevance"). To keep it fast and realistic, I'll implement a real(ish) BM25 function (very simplified) and a fake vector distance function.
- Presentation: Show debugging info to make it look like a "platform." Show "Calculating..." indicators, score breakdowns (BM25: 0.XX, ANN: 0.XX, Final: 0.XX).
-
Designing the UI Components (Neo-Brutalism/Y2K):
- Borders:
border-2 or border-4 with black (border-black).
- Shadows: Hard offset shadows:
box-shadow: 4px 4px 0px 0px #000.
- Colors:
bg-pink-500, bg-lime-400, bg-cyan-400, bg-yellow-300.
- Attributes:
mix-blend-mode on overlapping elements.
- Animation: Use GSAP for: entering results, glitch effects on hover, marquee scrolling.
-
Step-by-Step Implementation Plan:
-
Step 1: HTML Structure & Dependencies:
- Tailwind CDN.
- GSAP CDN.
- Google Fonts (optional, but stick to system fonts as per raw tendency, maybe import a display font like 'Press Start 2P' for the pixelated feel, or just use CSS
font-family: 'Courier New', monospace;). Let's stick to system fonts but weight them heavily.
- Canvas element for background noise/static.
-
Step 2: CSS (Tailwind + Custom):
- Custom utilities for mixing blend modes, hard shadows.
- Glitch animation keyframes.
-
Step 3: JavaScript Logic - Data Generation:
- Create ~50 mock documents about tech, AI, art, glitches, etc.
-
Step 4: JavaScript Logic - Search Engine:
mockDoc2Vec(doc): Generate a random fixed-length array representing the embedding.
computeBM25(query, doc): Simple token matching with length normalization.
computeANN(query, doc): Since we don't have a query embedding, we'll fake the ANN match based on the BM25 score manipulated with some noise to simulate "semantic" variance, or actually generate pseudo-random vectors based on word indices to ensure consistency. Better: A seeded PRNG based on document ID and query terms to produce a deterministic "score" that simulates vector similarity.
hybridSearch(alpha): Combine scores.
rerank(results): Maybe boost documents with specific "tags" to simulate Re-Ranker (e.g., cross-encoder like boost if query word matches title).
-
Step 5: UI Rendering:
- Render input box.
- Render results cards.
- Each card shows: Title, snippet, tags, and a "Score Breakdown" toggle that shows BM25/ANN/Fusion values (looks "techy").
-
Step 6: Visual Polish & Animation:
- Marquee: Pure CSS
animation: scroll 20s linear infinite or GSAP.
- Glitch effect on the logo or search button.
- Canvas background: Static noise (TV snow).
-
Refining the "Neo-Brutalism" Aesthetic:
- Use
tracking-widest (letter spacing).
- Use uppercase text frequently.
- Overlap a
pointer-events-none div with a scrambled "NOISE" texture over the top.
-
Drafting the Code (Mental & Scratchpad):
-
BM25 Sim: Need a stopword list. Stopwords: "the", "and", "is", "in", "at", "of". Count terms. Score = sum(log((N - df + 0.5)/(df + 0.5)) * ((f * (k1 + 1)) / (f + k1 * (1 - b + b * (dl/avgdl))))). This is too complex to implement fully without a corpus index. Simplify: frequency-based + inverse document frequency approx. For the demo, a simpler "term frequency * inverse doc count" approach will suffice visually.
-
Vector Sim: To make it feel "real", I'll create a dictionary mapping tokens to random vectors (like word2vec). If I encounter a token in query+doc, sum the vectors, then cosine similarity. This is a real embedding simulation!
- Pre-generate: 1000 random axes for each unique term.
- Document vector = sum of term vectors * tf.
- Query vector = sum of query term vectors.
- Cosine sim = dot(A, B) / (norm(A)*norm(B)). This adds "semantic" search since shared words increase vectors, even rare ones are random.
-
Re-ranking: I will add a "Booster" that checks for lexical overlap in the title or explicit tags as a simple Cross-Encoder surrogate.
-
Writing the actual code (incorporating into the final response):
- Setup: HTML5 boilerplate.
- Styles:
<style> for custom CSS (glitch, marquee). Tailwind in head.
- Body:
- Fixed background with noise canvas.
- Overlay div with heavy border.
- Header: "VOID_SEARCH_PROTOCOL".
- Search Form.
- Results Container (Grid).
- Footer: Stats (Time, Retrieval method).
-
Addressing Interaction Details:
- Input event -> Debounce -> Show "PROCESSING..." message (Glitchy).
- Function
performSearch(query):
- Clear previous.
- Calculate scores.
- Sort hybrid.
- GSAP stagger insertion of result cards (from bottom).
- Update stats.
-
Final Review against Constraints:
- Single file? Yes.
- No alerts? Yes.
- Neo-brutalism/Y2K? Yes (bold borders, clashing colors, raw fonts).
- Hybrid logic? Yes (simulated BM25 + Vector + Re-rank).
- Interactive? Yes (search works).
- Language: The user asked in English ("Create a search platform..."), but the system prompt says "Follow the language used by the user". Wait, the user prompt is in English, so the output must be in English. The developer prompt was in Chinese, but the system instruction says "strictly follow the language used by the user". The user used English. So UI and comments in English.
-
Polishing the "Visuals":
- Use
font-mono (Courier).
- Use
uppercase.
- Buttons: Black background, white text, yellow border, hover: invert.
- Result cards: Lime background, black border, heavy shadow. Title in red.
- Add a "cursor follower" or some trailing effect? Maybe too much code. Stick to GSAP hover effects (skew/distort).
-
Self-Correction during drafting:
- Issue: The simulated embedding might be too slow if the dictionary is huge.
- Fix: Limit docs to 50. Pre-vectors for only the terms that appear.
- Design: "Unpolished look" means maybe rough edges, but keep it functional. Use
clip-path: polygon(...) to make jagged cuts instead of rounded corners. clip-path: polygon(0 0, 100% 0, 100% 90%, 95% 100%, 0 100%). This fits Y2K.
-
Final Code Structure:
<html>
<head>: Tailwind script, Google Fonts (VT323 or similar), Custom Styles.
<body>:
- Canvas (background noise).
- Container.
- Header (Marquee).
- Search bar (Big, glitchy).
- Results Grid.
- Script tag containing:
- Data.
- Vector generation.
- Search logic (BM25 + ANN + Re-rank).
- GSAP animations.
-
Output Generation: (Proceeding to generate the HTML string).
(Self-Correction during output generation): Ensure the "BM25" and "ANN" calculation functions are clearly defined even if simplified, to satisfy the "Platform" aspect. The UI should probably display these metrics (e.g., "BM25: 0.42 | V-SIM: 0.89") to prove it's hybrid. I'll add a "Debug Info" toggle (hidden by default or small text) to show the technical nature.
Let's refine the aesthetics:
- Colors:
#FF0055 (Acid Pink), #CCFF00 (Acid Lime), #00FFFF (Cyan), #FFFF00 (Yellow), Black, White.
- Fonts:
Courier New, Impact.
Let's write the code.
(Logic Check): How to simulate ANN?
I will generate a simple "embedding" for each document. For the query, generate a query vector. Since I can't know all tokens beforehand, I'll create a hashing function that deterministically maps any string token to a random vector of length 10 (perceptron neighbor). This ensures consistency without needing a massive vocabulary mapping.
Actually, simplest: each document gets a random embedding array of size 20. The query gets a random embedding array generated by hashing the query string. This is random but deterministic for the same query. To make the scores meaningful ("hybrid"), I'll calculate Hybrid = (BM25 + random_similar) / 2. But the random similarity won't reflect semantic meaning.
Better approach for demo: Create a "Fake Embedding" model.
-
Build a vocabulary of tokens from the dataset.
-
Assign a random 2D vector to each token.
-
Document vector = sum of token vectors.
-
Query vector = sum of query token vectors.
-
Cosine similarity = dot(doc_vec, query_vec) / (|doc| * |query|).
This ensures that documents containing query tokens get high ANN score. It mimics the effect of word embedding (super effectively given small corpus). This is real vector logic, not fake. It's FAISS-lite.
-
Final Code Assembly.
Here is a complete, self-contained HTML file. It implements a visual search platform called "VOID_SEARCH".
It features:
- Hybrid Retrieval Engine: A JavaScript-based simulation that calculates real BM25 (text frequency) scores and Vector (ANN cosine similarity) scores based on a simulated embedding space, then fuses them.
- Re-ranking: A final stage that boosts documents based on specific relevance signals (e.g., title exact matches).
- Y2K / Neo-Brutalism Design: Acid colors, hard borders, marquees, glitch effects, clipped shapes, and raw typography.
- Tech: Tailwind CSS, GSAP, HTML5 Canvas (for background static).
Save this as index.html and open in any browser.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>VOID_SEARCH // HYBRID RETRIEVAL</title>
<!-- Tailwind CSS (Via CDN) -->
<script src="https://cdn.tailwindcss.com"></script>
<!-- GSAP (Via CDN) -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js"></script>
<!-- Google Fonts: VT323 (Pixel) and Roboto Mono -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Roboto+Mono:wght@400;700;900&family=VT323&display=swap" rel="stylesheet">
<!-- Configuration for Tailwind theme colors -->
<script>
tailwind.config = {
theme: {
extend: {
colors: {
acid: {
pink: '#FF0055',
lime: '#CCFF00',
cyan: '#00FFFF',
yellow: '#FFFF00',
purple: '#CD00FF',
white: '#F0F0F0',
},
void: '#000000'
},
fontFamily: {
mono: ['"Roboto Mono"', 'monospace'],
pixel: ['"VT323"', 'monospace'],
},
boxShadow: {
'hard-sm': '2px 2px 0px 0px #000',
'hard-md': '4px 4px 0px 0px #000',
'hard-lg': '8px 8px 0px 0px #000',
'hard-inset': 'inset 3px 3px 0px 0px #000',
},
clipPath: {
'jagged': 'polygon(0 0, 100% 0, 100% 85%, 95% 100%, 0 100%)',
'slash': 'polygon(0 0, 100% 0, 80% 100%, 0 100%)',
}
}
}
}
</script>
<style>
/* Global Styles & Custom Animations */
body {
background-color: #111;
color: #eee;
overflow-x: hidden;
cursor: crosshair;
}
/* Noise Overlay */
#noise-canvas {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
pointer-events: none;
z-index: 0;
opacity: 0.08;
}
/* Glitch Keyframes */
@keyframes glitch-anim-1 {
0% { clip-path: inset(20% 0 80% 0); transform: translate(-2px, 1px); }
20% { clip-path: inset(60% 0 10% 0); transform: translate(2px, -1px); }
40% { clip-path: inset(40% 0 50% 0); transform: translate(-2px, 2px); }
60% { clip-path: inset(80% 0 5% 0); transform: translate(2px, -2px); }
80% { clip-path: inset(10% 0 60% 0); transform: translate(-1px, 1px); }
100% { clip-path: inset(30% 0 30% 0); transform: translate(1px, -1px); }
}
.glitch-active:hover {
animation: glitch-anim-1 0.3s infinite linear alternate-reverse;
color: #FF0055;
background: #00FFFF;
text-shadow: 2px 0 #000, -2px 0 #FF00FF;
}
/* Custom Scrollbar */
::-webkit-scrollbar {
width: 12px;
height: 12px;
}
::-webkit-scrollbar-track {
background: #000;
border: 2px solid #000;
}
::-webkit-scrollbar-thumb {
background: #CCFF00;
border: 2px solid #000;
}
::-webkit-scrollbar-thumb:hover {
background: #FF0055;
}
/* Marquee */
.marquee-container {
overflow: hidden;
white-space: nowrap;
border-top: 4px solid #000;
border-bottom: 4px solid #000;
background: #CCFF00;
color: #000;
}
.marquee-content {
display: inline-block;
font-family: 'VT323', monospace;
font-size: 1.5rem;
padding-left: 100%;
animation: marquee 20s linear infinite;
}
@keyframes marquee {
0% { transform: translateX(0); }
100% { transform: translateX(-100%); }
}
</style>
</head>
<body class="min-h-screen p-4 md:p-8 relative">
<!-- Background Static Noise -->
<canvas id="noise-canvas"></canvas>
<!-- Main Container -->
<div class="relative z-10 max-w-7xl mx-auto">
<!-- Marquee Header -->
<div class="marquee-container mb-6 font-bold uppercase clip-path-jagged">
<div class="marquee-content">
*** SYSTEM READY /// HYBRID RETRIEVAL ENGINE ACTIVE /// BM25 + FAISS (SIM) /// RERANKING MODULE: ONLINE /// SEARCH THE VOID ///
</div>
</div>
<!-- LOGO / HEADER -->
<header class="mb-8 flex items-center justify-between border-4 border-black bg-acid-white p-4 shadow-hard-lg relative overflow-hidden">
<!-- Decorative accent -->
<div class="absolute -right-4 -top-4 w-32 h-32 bg-acid-pink border-4 border-black rotate-12 opacity-80 -z-10"></div>
<div class="flex items-center gap-4">
<!-- Glitch Text -->
<h1 class="text-5xl md:text-7xl font-black font-mono leading-none tracking-tighter glitch-active cursor-pointer select-none">
VOID<br>SEARCH
</h1>
</div>
<div class="hidden md:block text-xs font-mono text-right border-l-4 border-black pl-4">
<p>QUANT architecture:</p>
<p>latent_dim: <span class="text-acid-lime font-bold">128</span></p>
<p>top_k: <span class="text-acid-lime font-bold">10</span></p>
<p>status: <span class="blink">RUNNING</span>
</div>
</header>
<!-- SEARCH PANEL -->
<div class="mb-8 border-4 border-black bg-white p-2 shadow-hard-lg relative">
<div class="absolute -bottom-2 -right-2 w-16 h-16 bg-acid-cyan border-4 border-black -z-10"></div>
<form id="search-form" class="flex flex-col md:flex-row gap-4">
<div class="flex-grow relative group">
<input
type="text"
id="search-input"
autocomplete="off"
placeholder="ENTER QUERY // _"
class="w-full h-16 px-6 text-xl font-mono border-2 border-black bg-gray-100 outline-none focus:bg-white focus:ring-4 ring-acid-purple transition-all placeholder-gray-400"
>
<!-- Scanning line effect on focus -->
<div class="absolute bottom-0 left-0 h-1 bg-acid-pink w-0 transition-all duration-300 group-focus-within:w-full"></div>
</div>
<button
type="submit"
class="px-8 h-16 bg-acid-yellow border-2 border-black font-bold text-xl uppercase font-pixel shadow-hard-sm hover:bg-acid-pink hover:text-white active:translate-x-1 active:translate-y-1 transition-all"
>
EXECUTE
</button>
</form>
<!-- Filters / Tech toggles (Decorative) -->
<div class="mt-3 flex gap-2 flex-wrap px-2">
<span class="text-xs font-bold bg-black text-white px-2 py-1 uppercase">Mode: HYBRID</span>
<span class="text-xs font-bold border-2 border-black px-2 py-1 uppercase cursor-pointer hover:bg-acid-lime">Vector Top: 20%</span>
<span class="text-xs font-bold border-2 border-black px-2 py-1 uppercase cursor-pointer hover:bg-acid-lime">BM25 Weight: 0.3</span>
</div>
</div>
<!-- RESULTS AREA -->
<div id="results-status" class="mb-4 text-xs font-mono text-right opacity-70 hidden">
FOUND <span id="result-count">0</span> DOCUMENTS IN <span id="search-time">0</span> MS // RERANKING: CSV OUTPUT
</div>
<div id="results-container" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
<!-- Results will be injected here via JS -->
<div class="col-span-full text-center py-20 border-4 border-dashed border-gray-600 text-gray-400 font-mono">
[ SYSTEM STANDBY // WAITING FOR INPUT ]
</div>
</div>
<!-- DEBUG CONSOLE (Decorative) -->
<div class="fixed bottom-4 right-4 w-64 h-40 bg-black text-green-400 font-mono text-xs p-4 border-4 border-acid-lime shadow-hard-lg z-50 overflow-hidden opacity-90">
<div class="mb-1">> VOID_SEARCH_CLIENT initialized.</div>
<div class="mb-1">> Waiting for query vectors...</div>
<div id="debug-log" class="text-[10px] text-gray-500">
...
</div>
</div>
</div>
<!-- Footnotes -->
<footer class="mt-12 border-t-4 border-black p-4 text-center font-mono text-xs text-gray-500">
DESIGN BY NEO-BRUTALISM PROTOCOLS © 2023 // RENDERED IN BROWSER // NO EXTERNAL API
</footer>
<!-- JAVASCRIPT LOGIC -->
<script>
/**
* ------------------------------------------------------------------
* 1. MOCK DATA GENERATION & LINGUISTIC SIMULATION
* ------------------------------------------------------------------
*/
const corpus = [
{ id: 1, title: "Quantum Glitch in the Matrix", category: "AI", content: "Discover how quantum computing errors manifest as visual glitches and what it means for simulation theory." },
{ id: 2, title: "BM25 vs. Vector Search: A Rant", category: "Tech", content: "Why traditional keyword matching still matters in the age of deep learning. A deep dive into sparse vectors." },
{ id: 3, title: "Re-ranking with Cross-Encoders", category: "NLP", content: "Improving precision by re-evaluating top candidates with heavy transformer models." },
{ id: 4, title: "Y2K Aesthetics Return", category: "Design", content: "How the metallic futurism of the year 2000 is influencing 2023's web design trends and UI clutter." },
{ id: 5, title: "FAISS Implementation Basics", category: "Dev", content: "Building a fast similarity search index with Facebook's FAISS library. Clustering and quantization." },
{ id: 6, title: "The Death of Minimalism", category: "Culture", content: "Why the web is getting louder, uglier, and arguably more fun again. Neo-Brutalism explained." },
{ id: 7, title: "Neural Network Pruning Guide", category: "AI", content: "Techniques to reduce model size by removing redundant neurons without losing accuracy." },
{ id: 8, title: "Asynchronous JavaScript Patterns", category: "Code", content: "Mastering Promises, Async/Await, and dealing with callback hell in modern apps." },
{ id: 9, title: "CSS Houdini: The Future", category: "Frontend", content: "Unlocking low-level CSS access with the Houdini APIs for custom layouts and paint." },
{ id: 10, title: "Metadata Optimization for Search", category: "SEO", content: "Using meta tags, structured data, and JSON-LD to give crawlers what they crave." },
{ id: 11, title: "WebGL Shader Experiments", category: "Graphics", content: "Creating psychedelic visuals and glitch effects using fragment shaders on the GPU." },
{ id: 12, title: "React Server Components Deep Dive", category: "Frontend", content: "Understanding the boundary between client and server to improve bundle size and hydration time." },
{ id: 13, title: "Glitch Art Manifesto", category: "Art", content: "Corrupting digital data as a form of artistic expression and resistance to perfection." },
{ id: 14, title: "YouTube Algorithm Secrets", category: "Media", content: "What the black box really optimizes for: watch time, session time, and saturation loops." },
{ id: 15, title: "HTTPS Certificate Pinning", category: "Sec", content: "Mitigating man-in-the-middle attacks by binding a host to a specific certificate or public key." },
{ id: 16, title: "Dockerizing Legacy Apps", category: "DevOps", content: "Containerizing old PHP and Python applications without changing the codebase." },
{ id: 17, title: "NoSQL vs SQL in 2023", category: "Data", content: "The trade-offs between document stores and relational databases for modern transactional workloads." },
{ id: 18, title: "Quantum Supremacy Debate", category: "Science", content: "Has Google really achieved quantum supremacy, or are we still years from a useful quantum computer?" },
{ id: 19, title: "TypeScript Advanced Types", category: "Code", content: "Conditional types, template literals, and mapped types for robust API design." },
{ id: 20, title: "Accessibility is Not Optional", category: "UX", content: "Building inclusive web experiences isn't just morally right, it's good business and often the law." },
{ id: 21, title: "Edge Computing Architecture", category: "Infra", content: "Moving computation closer to the user to reduce latency and bandwidth costs." },
{ id: 22, title: "CRDTs for Local-First Apps", category: "Sync", content: "Conflict-free Replicated Data Types solving sync problems in offline-first applications." },
{ id: 23, title: "Python for Data Science", category: "Data", content: "Pandas, NumPy, and Jupyter Notebooks: The essential toolkit for modern data analysis." },
{ id: 24, title: "Blockchain Scalability", category: "Web3", content: "Layer 2 solutions, rollups, and sharding: How Ethereum plans to handle millions of TPS." },
{ id: 25, title: "Nginx Configuration Mastery", category: "DevOps", content: "Load balancing, reverse proxying, and caching strategies with the Nginx web server." },
];
/**
* ------------------------------------------------------------------
* 2. SEARCH ENGINE CORE (Simulation of Backend Retrieval)
* ------------------------------------------------------------------
*/
// --- Vocabulary & Tokenizer ---
const stopWords = new Set(["a", "an", "the", "is", "in", "at", "of", "on", "and", "or", "but", "for", "to", "with", "by", "from", "up", "about", "into", "like", "through", "after", "over", "between", "out", "vs", "vs.", "we", "you", "it", "they", "i", "me", "my"]);
function tokenize(text) {
return text.toLowerCase()
.replace(/[^\w\s]/g, ' ') // remove punctuation
.split(/\s+/)
.filter(t => t.length > 1 && !stopWords.has(t));
}
// Build Index
const docLengths = {};
const avgDocLength = corpus.reduce((acc, doc) => {
const tokens = tokenize(doc.title + " " + doc.content);
doc.tokenSet = new Set(tokens);
doc.tokens = tokens;
docLengths[doc.id] = tokens.length;
return acc + tokens.length;
}, 0) / corpus.length;
// Document Frequency (DF) for BM25
const df = {};
corpus.forEach(doc => {
doc.tokenSet.forEach(term => {
df[term] = (df[term] || 0) + 1;
});
});
const N = corpus.length;
// --- BM25 Calculation ---
// Simplified k1=1.5, b=0.75
function bm25Score(queryTerms, doc) {
let score = 0;
const docLen = docLengths[doc.id];
const k1 = 1.5;
const b = 0.75;
const numeratorDenom = 1 - b + b * (docLen / avgDocLength);
queryTerms.forEach(term => {
const tf = (doc.tokens.filter(t => t === term).length);
if (tf > 0) {
const df_val = df[term] || 1;
const idf = Math.log(1 + (N - df_val + 0.5) / (df_val + 0.5));
score += idf * ((tf * (k1 + 1)) / (tf + k1 * numeratorDenom));
}
});
return score;
}
// --- Vector (ANN) Simulation ---
// Since we don't have actual embeddings, we generate deterministic pseudo-random vectors
// based on terms. This creates a "semantic" space where similar word overlap yields higher similarity.
// Get a random unit vector hashed by string
const hashCache = {};
function getVector(term) {
if (hashCache[term]) return hashCache[term];
// Simple pseudo-random generator based on string
let seed = 0;
for(let i=0; i<term.length; i++) seed += term.charCodeAt(i);
const vec = [];
for(let i=0; i<10; i++) { // dimension 10
const x = Math.sin(seed + i) * 10000;
vec.push(x - Math.floor(x));
}
// Normalize
const mag = Math.sqrt(vec.reduce((a,b)=>a+b*b, 0));
const normalized = vec.map(v => v/mag);
hashCache[term] = normalized;
return normalized;
}
// Calculate document vector (average of word vectors weighted by TF)
function getDocVector(doc) {
if (doc.vectorCache) return doc.vectorCache;
const map = {};
doc.tokens.forEach(t => map[t] = (map[t]||0)+1);
let vec = new Array(10).fill(0);
const count = doc.tokens.length;
Object.keys(map).forEach(t => {
const v = getVector(t);
const weight = map[t]/count;
for(let i=0; i<10; i++) vec[i] += v[i] * weight;
});
// Normalize doc vector
const mag = Math.sqrt(vec.reduce((a,b)=>a+b*b, 0)) || 1;
doc.vectorCache = vec.map(v => v/mag);
return doc.vectorCache;
}
function cosineSim(vecA, vecB) {
let dot = 0;
for(let i=0; i<10; i++) dot += vecA[i] * vecB[i];
return dot; // Vectors are normalized, so dot is cosine
}
// --- Hybrid Retrieval Logic ---
function hybridSearch(query) {
const qTerms = tokenize(query);
if(qTerms.length === 0) return [];
// 1. Calculate BM25 for all docs
const results = corpus.map(doc => {
const bm25 = bm25Score(qTerms, doc);
// 2. Vector Score: Simulate ANN
// Query vector is sum of query term vectors
let qVec = new Array(10).fill(0);
qTerms.forEach(t => {
const v = getVector(t);
for(let i=0; i<10; i++) qVec[i] += v[i];
});
// Normalize query vector
const qMag = Math.sqrt(qVec.reduce((a,b)=>a+b*b,0)) || 1;
qVec = qVec.map(v => v/qMag);
const annScore = cosineSim(getDocVector(doc), qVec);
return { doc, bm25, annScore };
});
// Normalize scores to 0-1 range for weighting?
// Or simply use weights. We'll scale bm25 approx to match magnitude of cosine (0 to 1 ish).
// BM25 usually floats between 0 and ~ few points. We softmax them later.
// Store raw for later fusion
const rawBM25 = results.map(r => r.bm25);
// Find max BM25 for scaling
const maxBM25 = Math.max(...rawBM25) || 1;
results.forEach(r => {
r.bm25_norm = r.bm25 / maxBM25;
// ANN score is already 0-1ish.
r.ann_norm = Math.max(0, r.annScore); // ensure non-negative
});
// Hybrid Weighted Sum
const alpha = 0.6; // 60% Vector (ANN), 40% Keyword (BM25)
results.forEach(r => {
r.final = (alpha * r.ann_norm) + ((1-alpha) * r.bm25_norm);
});
// Sort
results.sort((a,b) => b.final - a.final);
return results;
}
// --- Re-Ranking (Cross-Encoder Fake) ---
function rerank(results, queryTokens) {
// Re-rank logic: We want to boost documents that have exact title matches or have high title overlap.
// This simulates a "re-ranker" (e.g., BERT cross-encoder) that looks deeper than sum-of-vectors.
results.forEach(res => {
const titleTokens = tokenize(res.doc.title);
const intersection = new Set(titleTokens).intersection(new Set(queryTokens)); // native intersection works on sets only
// Manual intersection for older browsers or Set compat:
let count = 0;
queryTokens.forEach(qt => {
if(titleTokens.includes(qt)) count++;
});
// Boost factor based on title match density
const titleBoost = count > 0 ? (count / queryTokens.length) * 0.2 : 0;
res.final = res.final + titleBoost;
});
// Re-sort
results.sort((a,b) => b.final - a.final);
return results;
}
/**
* ------------------------------------------------------------------
* 3. UI RENDERING & INTERACTION
* ------------------------------------------------------------------
*/
const searchForm = document.getElementById('search-form');
const searchInput = document.getElementById('search-input');
const resultsContainer = document.getElementById('results-container');
const resultCountEl = document.getElementById('result-count');
const searchTimeEl = document.getElementById('search-time');
const statusEl = document.getElementById('results-status');
const debugLog = document.getElementById('debug-log');
function log(msg) {
const time = new Date().toLocaleTimeString('en-US', {hour12:false});
debugLog.innerHTML = `<div>[${time}] ${msg}</div>` + debugLog.innerHTML;
}
// GSAP Intro
window.addEventListener('load', () => {
gsap.from("header", { duration: 1, y: -50, opacity: 0, ease: "power2.out" });
gsap.from(".marquee-container", { duration: 1, x: -100, opacity: 0, delay: 0.2 });
});
searchForm.addEventListener('submit', (e) => {
e.preventDefault();
const query = searchInput.value.trim();
if (!query) return;
executeSearch(query);
});
searchInput.addEventListener('input', (e) => {
// Optional: Debounced live search could be added here
});
function executeSearch(query) {
// UI Reset
resultsContainer.innerHTML = '';
statusEl.classList.add('hidden');
log(`STARTING SEARCH: "${query}" ...`);
// Simulate Process Delay (Networking + Computation)
const btn = searchForm.querySelector('button');
const originalText = btn.innerText;
btn.innerText = "PROCESSING...";
btn.classList.add('opacity-75', 'cursor-not-allowed');
btn.disabled = true;
setTimeout(() => {
const startTime = performance.now();
// Run Engine
let results = hybridSearch(query);
results = rerank(results, tokenize(query));
const endTime = performance.now();
const duration = Math.round(endTime - startTime);
// UI Update
btn.innerText = originalText;
btn.classList.remove('opacity-75', 'cursor-not-allowed');
btn.disabled = false;
renderResults(results, duration, query);
log(`FINISHED. ${results.length} HITS. ${duration}ms.`);
}, 600 + Math.random() * 400); // Random delay between 600-1000ms
}
function renderResults(results, timeMs, query) {
resultsContainer.innerHTML = '';
// Show status top
resultCountEl.innerText = results.length;
searchTimeEl.innerText = timeMs;
statusEl.classList.remove('hidden');
if (results.length === 0) {
resultsContainer.innerHTML = `
<div class="col-span-full text-center border-4 border-black bg-pink-500 p-8 shadow-hard-lg">
<h2 class="text-4xl font-black font-mono uppercase mb-4">NO RESULTS FOUND</h2>
<p class="font-mono">The query vector returned an empty set. Check your terms.</p>
</div>`;
return;
}
// Staggered Render of Cards
const fragment = document.createDocumentFragment();
results.forEach((res, index) => {
const doc = res.doc;
const relevance = Math.round(res.final * 100);
const colorClass = relevance > 80 ? 'bg-acid-pink' : (relevance > 50 ? 'bg-acid-yellow' : 'bg-acid-white');
const border = index === 0 ? 'border-4 border-black' : 'border-2 border-black';
const card = document.createElement('div');
card.className = `relative flex flex-col p-4 shadow-hard-sm hover:shadow-hard-lg transition-shadow duration-100 group cursor-pointer mix-blend-difference opacity-90 hover:opacity-100`;
card.style.backgroundColor = index % 2 === 0 ? '#FFF' : '#F0F0F0'; // Distinct white/off-white alternating
// Glitchy hover effect via inline style interaction (lightly)
card.innerHTML = `
<div class="absolute top-2 right-2 font-pixel text-lg text-gray-300 opacity-50 group-hover:text-acid-pink">#${index+1}</div>
<!-- Category Tag (Pill) -->
<span class="self-start text-xs font-black bg-black text-white px-2 py-1 uppercase mb-2 clip-path-jagged transform -rotate-1">
${doc.category}
</span>
<!-- Title -->
<h3 class="text-xl font-black font-mono uppercase leading-tight mb-2 group-hover:text-acid-pink transition-colors">
${highlightMatch(doc.title, query)}
</h3>
<!-- Snippet -->
<p class="text-sm font-mono text-gray-800 mb-4 flex-grow">
${highlightMatch(doc.content, query)}
</p>
<!-- Footer: Score & Debug -->
<div class="mt-auto border-t-2 border-gray-300 pt-2 flex justify-between items-center text-[10px] font-mono opacity-0 group-hover:opacity-100 transition-opacity duration-200">
<div>
<span class="text-gray-500">SCORE:</span>
<span class="font-bold ${relevance > 80 ? 'text-red-600' : 'text-black'}">${relevance}%</span>
</div>
<div class="flex gap-2">
<span title="BM25" class="border border-gray-400 px-1">BM25:${(res.bm25_norm*100).toFixed(0)}</span>
<span title="Vector" class="border border-gray-400 px-1">VEC:${res.ann_norm.toFixed(2)}</span>
</div>
</div>
<!-- Decorative corner cut -->
<div class="absolute bottom-0 left-0 w-4 h-4 bg-acid-cyan border-r-4 border-t-4 border-black -z-10"></div>
`;
// Interaction: Glitch on click
card.addEventListener('click', () => {
gsap.to(card, {
x: 5,
y: 2,
duration: 0.05,
yoyo: true,
repeat: 5,
backgroundColor: "#000",
color: "#FFF",
onComplete: () => {
card.style.backgroundColor = "";
card.style.color = "";
}
});
});
fragment.appendChild(card);
});
// GSAP Stagger Occurance
gsap.fromTo(resultsContainer.children,
{ opacity: 0, y: 20, scale: 0.95 },
{ opacity: 0.9, y: 0, scale: 1, duration: 0.4, stagger: 0.05, ease: "back.out(1.7)" }
);
resultsContainer.appendChild(fragment);
}
// Helper: Bold matching terms
function highlightMatch(text, query) {
const terms = tokenize(query);
if (!terms.length) return text;
// Simple regex escape
let regex = new RegExp(`(${terms.join('|')})`, 'gi');
return text.replace(regex, '<span class="bg-acid-yellow text-black font-bold">$1</span>');
}
/**
* ------------------------------------------------------------------
* 4. CANVAS BACKGROUND STATIC (TV NOISE)
* ------------------------------------------------------------------
*/
const canvas = document.getElementById('noise-canvas');
const ctx = canvas.getContext('2d');
let w, h;
function resize() {
w = canvas.width = window.innerWidth;
h = canvas.height = window.innerHeight;
}
window.addEventListener('resize', resize);
resize();
function noise() {
const iData = ctx.createImageData(w, h);
const buffer32 = new Uint32Array(iData.data.buffer);
const len = buffer32.length;
for (let i = 0; i < len; i++) {
if (Math.random() < 0.1) { // 10% opacity on average per pixel density
// Set random grey pixel (Little Endian: ABGR)
buffer32[i] = 0x10ffffff; // R G B low, A full (but visual opacity is low)
} else {
// Transparent
buffer32[i] = 0x00000000;
}
}
ctx.putImageData(iData, 0, 0);
// Request next frame slower for performance
setTimeout(() => requestAnimationFrame(noise), 100);
}
noise();
</script>
</body>
</html>