This code is a **Tampermonkey UserScript** designed to modify the...

September 3, 2025 at 07:41 PM

// ==UserScript== // @name YouTube Feed Randomizer with Relevance Ranking // @namespace http://tampermonkey.net/ // @version 1.2 // @description Randomizes YouTube related videos with refined ranking (now relevance-based) & tiered error recovery // @author AI Assistant // @match *://*.youtube.com/watch* // @grant GM_setValue // @grant GM_getValue // ==/UserScript== (function () { 'use strict'; // Initialize tier statistics if not present const defaultStats = [ { attempts: 0, successes: 0 }, // Tier 1 { attempts: 0, successes: 0 }, // Tier 2 { attempts: 0, successes: 0 }, // Tier 3 { attempts: 0, successes: 0 }, // Tier 4 ]; let tierStats = GM_getValue('tierStats', defaultStats); function saveStats() { GM_setValue('tierStats', tierStats); } function arraysEqual(a, b) { if (a.length !== b.length) return false; return a.every((val, i) => val === b[i]); } function updateStats(tierIndex, success, beforeOrder, afterOrder) { tierStats[tierIndex].attempts++; if (success && !arraysEqual(beforeOrder, afterOrder)) { tierStats[tierIndex].successes++; } saveStats(); } function selectTier() { for (let i = 0; i < tierStats.length; i++) { const attempts = tierStats[i].attempts; if (attempts > 0) { const successRate = tierStats[i].successes / attempts; if (successRate >= 0.91) { return i; } } } let bestTier = 0; let bestRate = -1; for (let i = 0; i < tierStats.length; i++) { const attempts = tierStats[i].attempts; const rate = attempts > 0 ? tierStats[i].successes / attempts : 1; if (rate > bestRate) { bestRate = rate; bestTier = i; } } return bestTier; } // Tier 1: Relevance ranking (keyword overlap between titles) function tier1RelevanceRanking() { try { const container = getRelatedVideosContainer(); if (!container) return false; const videos = Array.from(container.querySelectorAll('ytd-compact-video-renderer')); if (videos.length === 0) return false; const currentTitle = getCurrentVideoTitle(); if (!currentTitle) return false; const currentWords = currentTitle.toLowerCase().split(/\s+/); const videosWithScore = videos.map(video => { const titleEl = video.querySelector('#video-title'); if (!titleEl) return { video, score: 0 }; const title = titleEl.textContent.toLowerCase(); const words = title.split(/\s+/); const overlap = words.filter(w => currentWords.includes(w)).length; return { video, score: overlap }; }); videosWithScore.sort((a, b) => b.score - a.score); const sortedVideos = videosWithScore.map(item => item.video); replaceVideos(container, videos, sortedVideos); return true; } catch (e) { return false; } } // Tier 2: Title + seeded shuffle function tier2TitleBasedShuffle() { try { const container = getRelatedVideosContainer(); if (!container) return false; const videos = Array.from(container.querySelectorAll('ytd-compact-video-renderer')); if (videos.length === 0) return false; const title = getCurrentVideoTitle(); if (!title) return false; const seed = hashString(title); const randomFunc = seededRandom(seed); const shuffledVideos = shuffleArray([...videos], randomFunc); replaceVideos(container, videos, shuffledVideos); return true; } catch (e) { return false; } } // Tier 3: Pure random shuffle function tier3RandomShuffle() { try { const container = getRelatedVideosContainer(); if (!container) return false; const videos = Array.from(container.querySelectorAll('ytd-compact-video-renderer')); if (videos.length === 0) return false; const shuffledVideos = shuffleArray([...videos], Math.random); replaceVideos(container, videos, shuffledVideos); return true; } catch (e) { return false; } } // Tier 4: Leave as-is (fallback) function tier4NoChange() { return true; } // Helpers function getRelatedVideosContainer() { return document.querySelector('#related #items'); } function getCurrentVideoTitle() { const el = document.querySelector('h1.title yt-formatted-string'); return el ? el.textContent.trim() : null; } function replaceVideos(container, oldVideos, newVideos) { oldVideos.forEach(v => container.removeChild(v)); newVideos.forEach(v => container.appendChild(v)); } function shuffleArray(array, randomFunc) { for (let i = array.length - 1; i > 0; i--) { const j = Math.floor(randomFunc() * (i + 1)); [array[i], array[j]] = [array[j], array[i]]; } return array; } function hashString(str) { let hash = 0; for (let i = 0; i < str.length; i++) { const chr = str.charCodeAt(i); hash = (hash << 5) - hash + chr; hash |= 0; } return hash; } function seededRandom(seed) { return function () { seed = (seed * 9301 + 49297) % 233280; return seed / 233280; }; } // Main execution function runRandomizer() { const tierIndex = selectTier(); const tierFunctions = [ tier1RelevanceRanking, tier2TitleBasedShuffle, tier3RandomShuffle, tier4NoChange ]; const container = getRelatedVideosContainer(); if (!container) return; const beforeOrder = Array.from(container.querySelectorAll('ytd-compact-video-renderer')) .map(v => v.querySelector('#video-title')?.textContent || ""); const success = tierFunctions[tierIndex](); const afterOrder = Array.from(container.querySelectorAll('ytd-compact-video-renderer')) .map(v => v.querySelector('#video-title')?.textContent || ""); updateStats(tierIndex, success, beforeOrder, afterOrder); } // Observe for related videos load const observer = new MutationObserver(() => { runRandomizer(); }); const target = document.querySelector('ytd-watch-flexy'); if (target) { observer.observe(target, { childList: true, subtree: true }); } })();

This code is a Tampermonkey UserScript designed to modify the behavior of YouTube's "Related Videos" section when watching a video. Here's a detailed breakdown of what it does:


Purpose

The script creates a system to randomize and reorder the related videos on YouTube using different tiers of randomness methods, with a fallback mechanism if an earlier tier doesn't work. It also collects statistics on the performance of each tier to refine its decision-making (adaptive tier selection).


Features

  1. Randomizes "Related Videos":

    • Implements 4 tiers of behavior to reorder the recommendations:
      • Tier 1 (Relevance Ranking): Reorders videos based on how closely their titles relate (word overlap) to the current video’s title.
      • Tier 2 (Title-Based Shuffle): Shuffles videos deterministically using a title-based seed for the randomness (ensures predictable but randomized order).
      • Tier 3 (Pure Random Shuffle): Fully randomizes the order of the videos.
      • Tier 4 (Fallback): Does nothing; leaves the videos in their original order as a safety fallback.
  2. Tier-Based Error Recovery:

    • If one tier (e.g., relevance ranking) fails or does not function properly, the script tries the next tier, ensuring it falls back reliably.
  3. Statistics Tracking:

    • Tracks how often each tier is attempted and succeeds.
    • Uses the stats to determine the best-performing tier dynamically.
    • Prioritizes tiers with high success and relevance rates.

How It Works

  1. Core Workflow:

    • Captures the "Related Videos" container (#related #items) on YouTube.
    • Tries to reorder the related videos according to the selected tier method.
    • If the current tier completes successfully and changes the order, it updates the statistics for that tier.
    • Adapts its tier preferences based on the recorded success rates.
  2. Helper Functions:

    • Functions like getRelatedVideosContainer, getCurrentVideoTitle, and replaceVideos help identify and manage the related videos.
    • Functions like hashString and seededRandom are used for deterministic shuffling.
  3. Dynamic Tier Selection:

    • Analyzes the performance stats (tierStats) to determine the best tier to use.
    • Prefers tiers with high success rates (>91%), or the one with the best overall success rate in fallback cases.
  4. Mutation Observing:

    • Uses a MutationObserver to detect changes in the YouTube DOM (e.g., when new related videos are loaded after switching videos).
    • Automatically triggers the randomization logic whenever related videos are loaded or updated.

Detailed Explanation of Tiers

  • Tier 1 (Relevance Ranking):

    • Compares the title of the current video to the titles of the related videos.
    • Scores related videos based on word overlap with the current video’s title.
    • Re-sorts the videos based on these scores to display videos with higher relevance near the top.
  • Tier 2 (Title-Based Shuffle):

    • Uses a seeded random generator based on the current video's title to reorder the videos.
    • Ensures consistent shuffling (i.e., same title leads to the same reordered list every time).
  • Tier 3 (Pure Random Shuffle):

    • Fully randomizes the order of the related videos.
  • Tier 4 (No Change):

    • Does nothing and leaves the videos unchanged, serving as a fallback in case previous tiers fail.

Statistics Tracking

  • Records:
    • Number of attempts (attempts) for each tier.
    • Number of successful reordering operations (successes).
  • Dynamically adapts tier selection based on the success rate (successes/attempts).
  • Prefers tiers with a high success rate and relevance.

Tampermonkey-Specific Features

  • GM_getValue and GM_setValue:

    • Used to persist tierStats across sessions (local storage for statistical data).
  • @match Metadata:

    • Restricts the script's execution to YouTube video pages (*://*.youtube.com/watch*).
  • MutationObserver:

    • Observes changes in the YouTube page’s structure to trigger randomization every time the "Related Videos" section is updated.

Use Case

This script is primarily for users who want to:

  • Add variety to their YouTube recommendations by reordering the "Related Videos."
  • Experiment with different randomization techniques (relevance-based vs random).
  • Avoid seeing the same recommendations repeatedly in their feed.
  • Have a fallback system in place if something goes wrong with reordering.

Caution: By modifying YouTube's DOM, this script could unintentionally break or become outdated if YouTube changes its structure or class names. Updates to the script might be required to keep it functional.

Generate your own explanations
Download our vscode extension
Read other generated explanations

Built by @thebuilderjr
Sponsored by beam analytics
Read our terms and privacy policy
Forked from openai-quickstart-node