☰

Sleazy Fork is available in English.

JM Shelf - Score & Rank

五维评分引擎 + Gumbel-Max 排名 — JM Shelf 推荐脚本的模块库,通过 @require 被主脚本引用。

Questo script non dovrebbe essere installato direttamente. È una libreria per altri script da includere con la chiave // @require https://update.sleazyfork.org/scripts/581109/1842608/JM%20Shelf%20-%20Score%20%20Rank.js

Dovrai installare un'estensione come Tampermonkey, Greasemonkey o Violentmonkey per installare questo script.

Dovrai installare un'estensione come Tampermonkey o Violentmonkey per installare questo script.

Dovrai installare un'estensione come Tampermonkey o Violentmonkey per installare questo script.

Dovrai installare un'estensione come Tampermonkey o Userscripts per installare questo script.

Dovrai installare un'estensione come ad esempio Tampermonkey per installare questo script.

Dovrai installare un gestore di script utente per installare questo script.

(Ho già un gestore di script utente, lasciamelo installare!)

Dovrai installare un'estensione come ad esempio Stylus per installare questo stile.

Dovrai installare un'estensione come ad esempio Stylus per installare questo stile.

Dovrai installare un'estensione come ad esempio Stylus per installare questo stile.

Dovrai installare un'estensione per la gestione degli stili utente per installare questo stile.

Dovrai installare un'estensione per la gestione degli stili utente per installare questo stile.

Dovrai installare un'estensione per la gestione degli stili utente per installare questo stile.

(Ho già un gestore di stile utente, lasciamelo installare!)

// ==UserScript==
// @name         JM Shelf - Score & Rank
// @namespace    jmshelf-lib
// @version      1.0.0
// @author       Kesdi
// @description  五维评分引擎 + Gumbel-Max 排名 — JM Shelf 推荐脚本的模块库,通过 @require 被主脚本引用。
// @license      MIT
// ==/UserScript==
// 
// 此文件是 GreasyFork 库(library),不直接安装。
// 请安装主脚本: JM Shelf 给杂鱼的个性化推荐
//

// ═══ [11] RECOMMENDER (score+rank) ═══
  // ============================================================
  const Recommender = {
    /**
     * Five-dimension dynamic scoring:
     * Score = wTag*TagScore + wAuthor*AuthorScore + wPop*PopScore + wQuality*QualScore + wFresh*FreshScore
     */
    score(album, profile, favorites, history, weights) {
      const favIds = new Set(favorites.map(f => f.id));
      const blacklist = getBlacklist();
      const w = weights || ProfileManager.deriveWeights(profile.popularityFingerprint || 0.7);

      if (blacklist.albums.includes(album.id)) return { id: album.id, score: -1 };
      if (favIds.has(album.id)) return { id: album.id, score: -1 };
      if ((album.tags||[]).some(t => CONFIG.TAG_HARD_BLACKLIST.includes(normalizeTag(t)))) return { id: album.id, score: -1 };

      const viewedSet = new Set(State.getViewedAlbums().map(v => String(v.id || v)));
      const viewedPenalty = viewedSet.has(String(album.id)) ? 0.5 : 1.0;

      const tts = album.typeTags || [];
      const tgs = album.tags || [];
      if (tts.some(t => CONFIG.TYPE_HARD_BLACKLIST.includes(t)) ||
          tgs.some(t => CONFIG.TYPE_HARD_BLACKLIST.includes(t)) ||
          (album.chapters || 0) > 20) {
        return { id: album.id, score: -1 };
      }

      // TAG affinity with IDF boost
      const tagContribs = [];
      const maxTagWeight = Math.max(...Object.values(profile.tags), 1);
      for (const tag of (album.tags || [])) {
        const nt = normalizeTag(tag);
        if (blacklist.tags.includes(nt) || getAllBlacklistedTags().includes(nt)) continue;
        const weight = profile.tags[nt] || 0;
        if (weight <= 0) continue;
        let idf = 1.0;
        if (CONFIG.ENABLE_IDF_BOOST) {
          const tagFreq = State.getTagFreq();
          const globalCount = tagFreq[nt] || tagFreq[tag] || 0;
          if (globalCount > 0) {
            const freqValues = Object.values(tagFreq).filter(v => v > 0);
            const maxFreq = freqValues.length > 0 ? Math.max(...freqValues) : globalCount;
            idf = 1.0 + Math.log10(Math.max(maxFreq / globalCount, 1)) * 0.6;
            idf = clamp(idf, 0.6, 2.0);
          }
        }
        tagContribs.push((weight / maxTagWeight) * idf);
      }
      tagContribs.sort((a,b) => b - a);
      const best = tagContribs[0] || 0;
      const second = tagContribs[1] || 0;
      const third = tagContribs[2] || 0;
      let tagScore = best + 0.2 * (second + third);
      tagScore = clamp(tagScore, 0, 5);

      // AUTHOR affinity
      let authorScore = 0;
      const maxAuthorWeight = Math.max(...Object.values(profile.authors), 1);
      for (const author of album.authors || []) {
        authorScore += (profile.authors[author] || 0) / maxAuthorWeight;
      }
      authorScore = clamp(authorScore, 0, 1);

      // POPULARITY
      const pop = album.views || album.likes || 0;
      const popScore = sigmoid(Math.log10(Math.max(pop, 1) + 1), CONFIG.POP_SIGMOID_CENTER, CONFIG.POP_SIGMOID_STEEP);

      // QUALITY
      const views = album.views || 1;
      const likes = album.likes !== album.views ? (album.likes || 0) : 0;
      const qualScore = likes > 0 ? clamp((likes / Math.max(views, 100)) * CONFIG.QUALITY_LIKE_SCALE, 0, 1) : 0.5;

      // FRESHNESS
      const freshScore = CONFIG.FRESH_MIN + CONFIG.FRESH_RANGE / (1 + 0 / CONFIG.FRESH_HALFLIFE);

      // MULTI-CHANNEL BONUS
      const channelBonus = (album.channelCount || 0) >= 3 ? CONFIG.MULTI_CHANNEL_BONUS_3
        : (album.channelCount || 0) >= 2 ? CONFIG.MULTI_CHANNEL_BONUS_2 : 1.0;

      // MULTI-TAG SYNERGY
      const matchedTagCount = (album.tags || []).filter(t => {
        const nt = normalizeTag(t);
        return !getAllBlacklistedTags().includes(nt) && (profile.tags[nt] || 0) > 0;
      }).length;
      const tagSynergy = 1 + Math.min(matchedTagCount / 5, 0.4) * CONFIG.MULTI_TAG_BONUS;

      // LOVE PENALTY
      const loves = album.views || 0;
      const lovePenalty = loves < CONFIG.LOVE_PENALTY_THRESHOLD
        ? Math.pow(loves / CONFIG.LOVE_PENALTY_THRESHOLD, 1.5)
        : 1.0;

      const finalScore = (
        w.wTag * tagScore +
        w.wAuthor * authorScore +
        w.wPop * popScore +
        w.wQuality * qualScore +
        w.wFresh * freshScore
      ) * viewedPenalty * channelBonus * lovePenalty * tagSynergy;

      return {
        id: album.id, title: album.title, score: finalScore,
        breakdown: {
          tag: (w.wTag * tagScore).toFixed(2),
          author: (w.wAuthor * authorScore).toFixed(2),
          pop: (w.wPop * popScore).toFixed(2),
          qual: (w.wQuality * qualScore).toFixed(2),
          fresh: (w.wFresh * freshScore).toFixed(2),
          histPen: viewedPenalty.toFixed(2),
          chBonus: channelBonus.toFixed(2),
        },
        channels: album.channels || [], channelCount: album.channelCount || 0,
      };
    },

    async rank(candidates, profile, favorites, history, topN) {
      const bw = ProfileManager.deriveWeights(profile.popularityFingerprint || 0.7);
      const topTags = ProfileManager.getTopTags(profile, 8);
      const favIds = new Set((favorites || []).map(f => String(f.id || f)));
      const favNormTitles = new Set();
      for (const f of (favorites || [])) {
        const title = (State.getAlbumCache()[String(f.id)]?.title) || f.title || '';
        if (title) {
          let nt = title.replace(/\[.*?\]/g,'').replace(/\s+/g,' ').trim().substring(0,30);
          let nr = ''; for (const ch of nt) nr += TAG_NORMALIZE[ch] || ch;
          nt = nr;
          if (nt) favNormTitles.add(nt);
        }
      }

      let _debugScored = 0;
      const allItems = [];
      let _batchCount = 0;
      for (const album of candidates) {
        if (++_batchCount % 10 === 0) updateProgress({ phase:'candidates', progress:65+Math.min(25,Math.round(_batchCount/candidates.length*25)), message:`评分排序 ${_batchCount}/${candidates.length}` });
        if (_batchCount % 100 === 0) await new Promise(r => setTimeout(r, 0));
        if (favIds.has(String(album.id))) continue;
        const atags = State.getAlbumCache()[String(album.id)]?.tags || album.tags || [];
        if (atags.some(t => CONFIG.TAG_HARD_BLACKLIST.includes(normalizeTag(t)))) continue;
        const al = State.getAlbumCache()[String(album.id)];
        if (al && al.title) {
          let nt = (al.title||'').replace(/\[.*?\]/g,'').replace(/\s+/g,' ').trim().substring(0,30);
          let nr = ''; for (const ch of nt) nr += TAG_NORMALIZE[ch] || ch;
          nt = nr;
          if (nt && favNormTitles.has(nt)) continue;
        }
        const s = this.score(album, profile, favorites, history, { ...bw, label: 'default' });
        if (s.score <= 0) continue;
        if (parseFloat(s.breakdown?.author || 0) > 0.2) {
          s._wm = 'author+';
        } else if (parseFloat(s.breakdown?.tag || 0) > 0.15) {
          s._wm = 'tag+';
        } else {
          s._wm = 'default';
        }
        allItems.push(s);
      }

      // 按模式分组
      const au = allItems.filter(s => s._wm === 'author+').sort((a,b) => b.score - a.score);
      const tg = allItems.filter(s => s._wm === 'tag+').sort((a,b) => b.score - a.score);
      const cw = { wTag:0.20, wAuthor:0.20, wPop:0.25, wQuality:0.25, wFresh:0.10 };
      let df = allItems.filter(s => s._wm === 'default' && !(s.channels||[]).some(ch => ch==='discover'||ch==='explore'));
      for (let i = 0; i < df.length; i++) {
        const album = State.getAlbumCache()[String(df[i].id)];
        if (album) {
          const ns = Recommender.score({ ...album, channels: df[i].channels, channelCount: df[i].channelCount }, profile, favorites, history, cw);
          if (ns.score > 0) { df[i] = ns; df[i]._wm = 'default'; }
        }
      }
      df.sort((a,b) => b.score - a.score);

      // 探索池
      const profileAu = new Set(Object.keys(profile.authors || {}));
      const profileTopTags = new Set(ProfileManager.getTopTags(profile, 20));
      const rawExplorePool = allItems.filter(s => (s.channels||[]).some(ch => ch==='rank_explore'||ch==='discover'||ch==='explore'));
      const rankedExplore = rawExplorePool
        .filter(s => {
          const al = State.getAlbumCache()[s.id];
          if (!al) return false;
          if ((al.authors||[]).some(a => profileAu.has(a))) return false;
          if ((al.tags||[]).some(t => CONFIG.TAG_HARD_BLACKLIST.includes(normalizeTag(t)))) return false;
          const overlap = (al.tags||[]).filter(t => profileTopTags.has(normalizeTag(t))).length / Math.max((al.tags||[]).length, 1);
          if (overlap > 0.3) return false;
          return true;
        })
        .map(s => {
          const al = State.getAlbumCache()[s.id];
          const views = al.views || 0;
          const likes = al.likes || 0;
          const community = clamp(Math.log10(Math.max(views + likes + 1, 1)) / 6, 0, 1);
          const exploreScore = s.score * 0.4 + community * 0.6;
          return { ...s, _exploreScore: exploreScore };
        })
        .filter(s => s._exploreScore > 0.15)
        .sort((a,b) => b._exploreScore - a._exploreScore);

      const ex = rankedExplore.slice(0, 50);
      ex.sort((a,b) => (_random() - 0.5));
      if (df.length === 0 && allItems.length > 0) {
        for (const s of allItems) {
          if (au.includes(s) || tg.includes(s) || ex.includes(s)) continue;
          if (s.score > 0.3 && s._wm === 'default') df.push(s);
          if (df.length >= 50) break;
        }
      }
      const pools = { 'author+': au, 'tag+': tg, 'default': df, 'explore': ex };
      const ptr = { 'author+': 0, 'tag+': 0, 'default': 0, 'explore': 0 };

      updateProgress({ phase:'candidates', progress:92, message:`池构建完成: au${au.length} tg${tg.length} df${df.length} ex${ex.length}` });
      State.savePoolSizes({ 'author+': au.length, 'tag+': tg.length, default: df.length, surprise: ex.length });

      // 加权随机取池
      function pickMode() {
        const T = CONFIG.TEMPERATURE;
        const t = Math.min(T*T, 1);
        const wTag = 50 - 25 * t, wAu = 30 - 5 * t, wDf = 10 + 15 * t, wEx = 10 + 15 * t;
        const r = _random() * 100;
        if (r < wTag) return 'tag+';
        if (r < wTag + wAu) return 'author+';
        if (r < wTag + wAu + wDf) return 'default';
        return 'explore';
      }
      const result = [];
      const resultIds = new Set();
      const authorCounts = {}, tagCounts = {};
      const usedChannels = new Set();

      function tryPush(pool, key) {
        for (let i = ptr[key]; i < pool.length; i++) {
          const item = pool[i];
          if (resultIds.has(item.id)) continue;
          const album = State.getAlbumCache()[item.id];
          if (!album) { ptr[key] = i + 1; result.push(item); return true; }
          let ab = false, tb = false;
          for (const a of album.authors || []) { if ((authorCounts[a] || 0) >= CONFIG.PER_AUTHOR_LIMIT) { ab = true; break; } }
          const tL = (album.tags || []).map(t => (tagCounts[t] || 0) >= CONFIG.PER_TAG_LIMIT);
          if (tL.length > 0 && tL.every(Boolean)) tb = true;
          if (result.length > 10 && ab && tb) continue;
          for (const a of album.authors || []) authorCounts[a] = (authorCounts[a] || 0) + 1;
          for (const t of album.tags || []) tagCounts[t] = (tagCounts[t] || 0) + 1;
          for (const ch of item.channels) usedChannels.add(ch);
          ptr[key] = i + 1;
          if (key === 'explore') item._wm = 'surprise';
          result.push(item);
          resultIds.add(item.id);
          return true;
        }
        return false;
      }

      while (result.length < topN) {
        if (result.length % 20 === 0) await new Promise(r => setTimeout(r, 0));
        const mode = pickMode();
        if (!tryPush(pools[mode], mode)) {
          const order = ['tag+', 'default', 'author+', 'explore'].sort(() => Math.random() - 0.5);
          for (const fb of order) {
            if (tryPush(pools[fb], fb)) break;
          }
        }
        if (Object.keys(pools).every(k => ptr[k] >= pools[k].length)) break;
      }

      const auTop = au.find(s => !resultIds.has(s.id));
      if (auTop) { result.splice(1, 0, auTop); resultIds.add(auTop.id); }

      if (result.length > 0 && (result[0]._wm === 'default' || result[0]._wm === 'surprise')) {
        const swapIdx = result.findIndex(r => r._wm === 'tag+' || r._wm === 'author+');
        if (swapIdx > 0) {
          const bad = result.shift();
          const good = result.splice(swapIdx - 1, 1)[0];
          result.unshift(good);
          let ins = Math.min(5, result.length);
          result.splice(ins, 0, bad);
        }
      }

      return result.slice(0, topN);
    },
  };