Real catalogue: 83 verified models, buy-advice mode, live model lookup, license-aware cards
Browse filesFiles changed (7)
- app.py+41-240
- catalogue.jsonAdded
- engine/hub_lookup.pyAdded+155
- engine/real_advisor.pyAdded+538
- static/app.js+143-7
- static/index.html+19-4
- static/style.css+29
12345678910111213141516171819201 unmodified line22232425262728291 unmodified line3132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562579 unmodified lines2672682692702712722732742752762 unmodified lines279280281282283284285"""FitCheck — what AI can your computer actually run?This file wires three bricks together behind a `gr.Server` (which IS a FastAPIapp) that serves the hand-built frontend in static/:- /api/advise : the honest verdict. For LLM goals it runs the REALdeterministic engine (engine/, via ui_adapter). Vision /image-gen / audio / data goals — which the engine doesn'tmodel yet — still use the input-aware placeholder below.- /gradio_api/call/ask : the model brick (model_brick.ask), a small local LLMthat explains the engine's numbers in plain words. Exposed as@app.api so it runs on Gradio's queue and gets a ZeroGPUallocation; called from the browser via @gradio/client."""import refrom pathlib import Pathimport gradio as gr1 unmodified linefrom fastapi.staticfiles import StaticFilesfrom pydantic import BaseModelfrom engine import CATALOGUE_VERSIONfrom engine.ui_adapter import advise_for_ui, is_llm_usecasefrom model_brick import ask as model_askSTATIC = Path(__file__).parent / "static"1 unmodified lineapp = gr.Server()# ==========================================================================# PLACEHOLDER engine — vision / image-gen / audio / data goals only.# The real engine (engine/) covers LLM goals; these families aren't modelled# there yet, so they keep these plausible, conservative placeholder numbers.# ==========================================================================_COLORS = {"model": "#818CF8", "chat": "#A5F3C4", "work": "#868E9C"}# Which broad family each goal belongs to (drives models/tools/commands)._FAMILY = {"chat": "llm", "writing": "llm", "coding": "llm", "agents": "llm","rag": "llm", "translate": "llm", "finetune": "llm","detect": "vision", "segment": "vision", "pose": "vision","classify": "vision", "depth": "vision", "ocr": "vision", "train-vision": "vision","imagegen": "gen", "inpaint": "gen", "upscale": "gen", "videogen": "gen", "bgremove": "gen","stt": "audio", "tts": "audio", "music": "audio","embed": "data", "forecast": "data", "tabular": "data","custom": "llm",}# variant = (name, description, memory-need-GB at sensible setting, setting label)_VARIANTS = {"llm": [("Huge (70B)", "Top open quality. Serious hardware only.", 42, "4-bit"),("Very large (32B)", "Near-premium. Wants a strong GPU.", 20, "4-bit"),("Large (14B)", "Noticeably smarter and more reliable.", 9, "4-bit"),("Medium (7-9B)", "Solid all-rounder: chat, coding, reasoning.", 5.5, "4-bit"),("Small (3-4B)", "Surprisingly capable everyday assistant.", 2.5, "4-bit"),("Tiny (~1B)", "Quick simple chat. Runs on almost anything.", 1.2, "4-bit"),],"vision": [("Extra-large model", "Highest accuracy, slowest.", 6.0, "full"),("Large model", "Great accuracy for real work.", 3.5, "full"),("Medium model", "Balanced accuracy and speed.", 2.0, "full"),("Small model", "Fast, good for live video.", 1.2, "full"),("Nano model", "Real-time even on weak hardware.", 0.6, "full"),],"gen": [("Flux.1 (dev)", "State-of-the-art image quality.", 18, "full"),("Flux.1 (schnell)", "Near-top quality, much faster.", 12, "8-bit"),("SDXL", "Excellent 1024px images.", 8, "full"),("SDXL Turbo", "Fast SDXL, fewer steps.", 7, "full"),("Stable Diffusion 1.5", "Light, fast, huge community.", 3.5, "full"),],"audio": [("Whisper large-v3", "Best transcription accuracy.", 5.0, "full"),("Whisper medium", "Strong accuracy, lighter.", 3.0, "full"),("Whisper small", "Good for clear audio, fast.", 1.5, "full"),("Whisper base", "Quick drafts, light hardware.", 0.8, "full"),],"data": [("Large embedder", "Best search relevance.", 2.5, "full"),("Base embedder", "Great balance for most search.", 1.2, "full"),("Small embedder", "Fast, runs on anything.", 0.5, "full"),],}_TOOLS = {"llm": [("Ollama", "Type one line; it downloads and runs the model for you.", "Get it from ollama.com", "Easiest"),("LM Studio", "A point-and-click app with a chat window, no commands.", "Download from lmstudio.ai", "Easy"),("llama.cpp", "The lightweight engine under the hood. Runs GGUF files directly.", "Releases on GitHub", "Advanced"),],"vision": [("Ultralytics", "One pip install, then detect objects from a webcam or file.", "pip install ultralytics", "Easiest"),("Roboflow", "Browser tools to label data and run models, little code.", "roboflow.com", "Easy"),("PyTorch", "Full control for custom pipelines and training.", "pytorch.org", "Advanced"),],"gen": [("Fooocus", "Image generation that 'just works': one folder, double-click.", "Download from GitHub", "Easiest"),("ComfyUI", "Powerful visual node editor for image/video pipelines.", "Download from GitHub", "Moderate"),("Automatic1111", "The classic full-featured Stable Diffusion web UI.", "Download from GitHub", "Moderate"),],"audio": [("faster-whisper", "Fast, accurate transcription with a tiny install.", "pip install faster-whisper", "Easiest"),("whisper.cpp", "Runs Whisper efficiently on CPU and small machines.", "Build from GitHub", "Advanced"),],"data": [("sentence-transformers", "Turn text into searchable vectors in a few lines.", "pip install sentence-transformers", "Easiest"),("Chroma", "A simple local database to store and search those vectors.", "pip install chromadb", "Easy"),],}_COMMANDS = {"llm": [("Easy way (Ollama)", "ollama run llama3.1:8b"),("Power way (llama.cpp)", "llama-server -hf bartowski/Meta-Llama-3.1-8B-Instruct-GGUF:Q4_K_M -c 4096"),],"vision": [("Install", "pip install ultralytics"),("Detect from your webcam", "yolo predict model=yolo11n.pt source=0 show=True"),],"gen": [("Easiest (Fooocus)", "# Download Fooocus, unzip, double-click run.bat"),("Power (ComfyUI)", "git clone https://github.com/comfyanonymous/ComfyUI && cd ComfyUI && python main.py"),],"audio": [("Install", "pip install faster-whisper"),("Transcribe a file", 'python -c "from faster_whisper import WhisperModel; m=WhisperModel(\'small\'); print(list(m.transcribe(\'audio.mp3\')[0]))"'),],"data": [("Install", "pip install sentence-transformers"),("Make searchable vectors", 'python -c "from sentence_transformers import SentenceTransformer as S; print(S(\'all-MiniLM-L6-v2\').encode(\'hello world\').shape)"'),],}def _parse_vram(label: str) -> float:m = re.search(r"(\d+(?:\.\d+)?)\s*GB", label or "")return float(m.group(1)) if m else 0.0def _budgets(p: dict):ram = float(p.get("ram_gb") or 16)provider = p.get("provider", "none")computer = p.get("computer", "Windows laptop")if provider == "apple":fast = round(ram * 0.70, 1)return fast, fast, ram, Truevram = p.get("vram_gb")if not vram:vram = _parse_vram(p.get("gpu", ""))vram = float(vram or 0)fast = round(vram * 0.85, 1)reserve = 1.0 if "Mini PC" in computer else (3.0 if "desktop" in computer.lower() or computer == "Mac" else 3.5)total = round(vram + max(0.0, ram - reserve) * 0.9, 1)return fast, vram, total, Falsedef advise_mock(p: dict) -> dict:fam = _FAMILY.get(p.get("usecase", "chat"), "llm")variants = _VARIANTS[fam]fast, _vram, total, is_apple = _budgets(p)is_finetune = p.get("usecase") in ("finetune", "train-vision")factor = 2.4 if is_finetune else 1.0# Classify each variant.def verdict_for(need):need *= factorif fast >= 1 and need <= fast * 0.9:return "great", needif need <= total * 0.9:return "tight", needreturn "no", needoptions = []for name, desc, need, setting in variants:vd, real_need = verdict_for(need)feel = {"great": "Snappy on your graphics card","tight": "Runs, but slower (uses normal memory)","no": "Not enough memory"}[vd]options.append({"verdict": vd, "model": name, "desc": desc,"setting": setting, "memory": ("—" if vd == "no" else f"{round(real_need,1):g} GB"),"feel": feel,})# Headline = best that runs great, else best that's tight, else smallest.great = [o for o in options if o["verdict"] == "great"]tight = [o for o in options if o["verdict"] == "tight"]head = great[0] if great else (tight[0] if tight else options[-1])hv = head["verdict"]need_gb = float(re.search(r"[\d.]+", head["memory"]).group()) if head["memory"] != "—" else verdict_for(variants[-1][2])[1]if is_apple and hv == "great":where = "on your Mac"elif hv == "great" and fast >= 1:where = "on your graphics card"elif hv == "tight":where = "using your computer's memory"else:where = ""verdict_word = {"great": "Runs great", "tight": "Tight, but works", "no": "Won't fit"}[hv]if hv == "great":headline = f"Yes, you can run the {head['model']} {where}, today."elif hv == "tight":headline = f"Sort of. The {head['model']} will run {where}, with trade-offs."else:headline = "This goal is a stretch on this machine. Here's the honest picture."detail = (f"For this goal, the sweet spot is a <b>{head['model']}</b> model "f"at the <b>{head['setting']}</b> setting. {head['desc']} "f"It needs about <b>{round(need_gb,1):g} GB</b>, and you have roughly "f"<b>{fast:g} GB</b> fast / <b>{total:g} GB</b> total to work with.")note = ("Fine-tuning needs roughly 2 to 3 times the memory of just using a model. That's baked in above."if is_finetune else "")# Gaugescale = max(total, need_gb, 1) * 1.05gauge = {"need_gb": f"{round(need_gb,1):g} GB needed","fast_gb": f"{fast:g} GB", "total_gb": f"{total:g} GB","fill_pct": round(need_gb / scale * 100, 1),"mark_pct": round(fast / scale * 100, 1),"breakdown": [{"label": f"Model {round(need_gb*0.8,1):g} GB", "color": _COLORS["model"]},{"label": f"Working space {round(need_gb*0.2,1):g} GB", "color": _COLORS["work"]},],}tools = [{"name": n, "what": w, "install": i, "tag": t} for n, w, i, t in _TOOLS[fam]]cmd_intro = ("These get you a running model in minutes. Pick the easy one or the power one; ""they do the same job.")commands = {"intro": cmd_intro,"items": [{"label": l, "code": c} for l, c in _COMMANDS[fam]]}return {"catalogue_version": CATALOGUE_VERSION,"verdict": hv, "verdict_word": verdict_word,"headline": headline, "detail": detail, "note": note,"gauge": gauge, "options": options, "tools": tools, "commands": commands,}# ==========================================================================# Connector endpoint + static frontend# ==========================================================================class AdviseIn(BaseModel):computer: str = "Windows laptop"ram_gb: float | None = 169 unmodified lines@app.post("/api/advise")def api_advise(payload: AdviseIn):p = payload.model_dump()# LLM goals -> the real, audited engine. Other families -> placeholder.if is_llm_usecase(p.get("usecase", "chat")):return advise_for_ui(p, CATALOGUE_VERSION)return advise_mock(p)@app.api(name="ask")2 unmodified linesExposed at /gradio_api/call/ask (NOT a plain POST) so it runs throughGradio's queue and gets a ZeroGPU allocation. `facts` is the JSON string ofthe last /api/advise result. Returns {headline, why, next_step}."""return model_ask(question, facts)1234567891011121314151617181920212223241 unmodified line26272829303132331 unmodified line3536373839409 unmodified lines505152535455565758596061626364656667686970717273747576772 unmodified lines80818283848586"""FitCheck — what AI can your computer actually run?Four bricks behind a `gr.Server` (which IS a FastAPI app) serving thehand-built frontend in static/:- /api/advise : the honest verdict. Deterministic engine (engine/) overcatalogue.json — 83 real models with exact GGUF file sizes,licenses, and links, refreshed from the Hugging Face API atbuild time. The running app makes no network calls here.- /api/minspecs : the reverse question — "what machine do I need for X?"Same engine, inverted over a hardware ladder. Offline.- /api/lookup : OPTIONAL live check of any pasted HF repo id. Walks themodel-tree (finetune -> base) to a catalogue entry, or doeslabelled raw math. The one endpoint that touches thenetwork, and the UI says so.- /gradio_api/call/ask : the model brick (model_brick.ask) — a small localLLM that explains the engine's numbers in plain words.@app.api so it runs on Gradio's queue and gets ZeroGPU."""from pathlib import Pathimport gradio as gr1 unmodified linefrom fastapi.staticfiles import StaticFilesfrom pydantic import BaseModelfrom engine.real_advisor import advise_real, min_specsfrom engine.ui_adapter import spec_from_payloadfrom model_brick import ask as model_askSTATIC = Path(__file__).parent / "static"1 unmodified lineapp = gr.Server()class AdviseIn(BaseModel):computer: str = "Windows laptop"ram_gb: float | None = 169 unmodified lines@app.post("/api/advise")def api_advise(payload: AdviseIn):p = payload.model_dump()return advise_real(p, spec_from_payload(p))class MinSpecsIn(BaseModel):usecase: str = "chat"@app.post("/api/minspecs")def api_minspecs(payload: MinSpecsIn):return min_specs(payload.usecase)class LookupIn(AdviseIn):repo: str = ""@app.post("/api/lookup")def api_lookup(payload: LookupIn):"""Live lookup of one HF repo id (labelled online in the UI)."""from engine.hub_lookup import lookupp = payload.model_dump()return lookup(p.get("repo", ""), p, spec_from_payload(p))@app.api(name="ask")2 unmodified linesExposed at /gradio_api/call/ask (NOT a plain POST) so it runs throughGradio's queue and gets a ZeroGPU allocation. `facts` is the JSON string ofthe last /api/advise result. Returns {headline, why, next_step} or {error}."""return model_ask(question, facts)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155"""Optional ONLINE lookup: "will this exact Hugging Face model run on my machine?"
Deterministic — no AI involved. Given any repo id (or model page URL), this: 1. checks the local catalogue (offline) by repo id and aliases; 2. otherwise makes ONE metadata call to the Hub, reads the model-tree tags (base_model:finetune/adapter/quantized/merge), and walks up to 3 hops to find a catalogue ancestor — "your finetune runs because its base runs"; 3. otherwise falls back to raw parameter-count math, clearly labelled.
This is the only part of FitCheck that touches the network at runtime, and theUI labels it as a live lookup. The core advisor stays fully offline."""
import refrom functools import lru_cache
from .hardware import HardwareSpecfrom .real_advisor import ( USE_CASES, _SAFETY_FILL, _evaluate, _option_json, catalogue,)
_RELATION = re.compile(r"^base_model:(finetune|adapter|quantized|merge):(.+)$")
@lru_cache(maxsize=1)def _index() -> dict: idx = {} for e in catalogue()["entries"]: idx[e["repo_id"].lower()] = e for a in e.get("aliases", []): idx[a.lower()] = e return idx
def normalize_repo_id(text: str) -> str: """Accept a bare repo id or any huggingface.co URL.""" text = (text or "").strip().rstrip("/") m = re.search(r"huggingface\.co/([\w.-]+/[\w.-]+)", text) if m: return m.group(1) return text
def _relations(info) -> list[tuple[str, str]]: out = [] for t in (getattr(info, "tags", None) or []): m = _RELATION.match(t) if m: out.append((m.group(1), m.group(2))) if not out: # cardData fallback only when tags carry no typed relation — the tag # knows whether it's a finetune or a quantized copy; cardData doesn't. card = getattr(info, "card_data", None) if card: base = card.get("base_model") if hasattr(card, "get") else getattr(card, "base_model", None) if isinstance(base, str): out.append(("finetune", base)) elif isinstance(base, list): out.extend(("finetune", b) for b in base if isinstance(b, str)) return out
def lookup(repo_input: str, payload: dict, spec: HardwareSpec) -> dict: """Returns {found, model, chain, verdict-ish fields} or {error}.""" repo_id = normalize_repo_id(repo_input) if not re.fullmatch(r"[\w.-]+/[\w.-]+", repo_id): return {"error": f"'{repo_input}' doesn't look like a Hugging Face repo id " f"(expected something like author/model-name)."}
uc = USE_CASES.get(payload.get("usecase", "chat"), USE_CASES["chat"]) chain = [repo_id]
# 1) Offline: direct catalogue hit (also via aliases). entry = _index().get(repo_id.lower()) via = None
# 2) Online: one metadata call + base-model walk. info = None if entry is None: from huggingface_hub import HfApi api = HfApi() current = repo_id try: info = api.model_info(current, expand=["tags", "safetensors", "cardData", "pipeline_tag", "gated"]) except Exception as exc: # noqa: BLE001 — surface the real failure return {"error": f"Couldn't find '{repo_id}' on Hugging Face " f"({type(exc).__name__}). Check the spelling?"} hop_info = info for _hop in range(3): rels = _relations(hop_info) if not rels: break # Prefer finetune/merge (same memory as base) over quantized. rels.sort(key=lambda r: 0 if r[0] in ("finetune", "merge", "adapter") else 1) rel, parent = rels[0] chain.append(parent) entry = _index().get(parent.lower()) if entry is not None: via = {"relation": rel, "base": parent} break try: hop_info = api.model_info(parent, expand=["tags", "cardData"]) except Exception: # noqa: BLE001 — chain ends here break
if entry is not None: r = _evaluate(entry, spec, uc) opt = _option_json(r, spec) explain = f"<b>{repo_id.split('/')[-1]}</b> " if via: word = {"finetune": "is fine-tuned from", "merge": "is merged from", "adapter": "is an adapter on", "quantized": "is a compressed copy of"}[via["relation"]] explain += (f"{word} <b>{entry['name']}</b> — if the base runs, this runs, " f"with the same memory needs.") if via["relation"] == "adapter": explain += " Add roughly 0.1–0.5 GB for the adapter file." else: explain += f"is <b>{entry['name']}</b> in our catalogue." return {"found": True, "match": "catalogue", "chain": chain, "explain": explain, "option": opt, "live": via is not None or info is not None}
# 3) Raw math from parameter count — clearly labelled estimate. st = getattr(info, "safetensors", None) total = getattr(st, "total", None) if st else None if not total: return {"error": f"'{repo_id}' exists, but doesn't share its size or a known " f"base model, so an honest estimate isn't possible."} params_b = total / 1e9 weights_4bit = round(params_b * 4.85 / 8, 2) # effective 4-bit bits/weight need = round(weights_4bit * 1.25 + 0.58, 2) fast, total_b = spec.fast_budget_gb, spec.total_budget_gb if spec.has_fast_path and need <= fast * _SAFETY_FILL: verdict = "great" elif need <= total_b * _SAFETY_FILL: verdict = "tight" else: verdict = "no" return { "found": True, "match": "estimate", "chain": chain, "live": True, "explain": (f"<b>{repo_id.split('/')[-1]}</b> isn't in our catalogue and lists no " f"known base, so this is raw math from its {params_b:.1f}B parameters " f"at a 4-bit setting — an estimate, not a measured figure."), "option": { "verdict": verdict, "model": repo_id.split("/")[-1], "desc": f"{params_b:.1f}B parameters (from its files on Hugging Face)", "setting": "Balanced (4-bit)", "memory": "Too big" if verdict == "no" else f"{need:g} GB", "feel": "", "url": f"https://huggingface.co/{repo_id}", "license": "", "license_note": "", "gated": bool(getattr(info, "gated", False)), "run": {}, "provenance": "estimated", "stale": False, "params_b": round(params_b, 2), "active_params_b": None, }, }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538"""Engine v2: honest verdicts over REAL models from catalogue.json.
This replaces both the size-class advisor and the placeholder families. Everyoption it returns is an actual model with a Hugging Face link, a license, andmemory figures with provenance:
- LLM / VLM weights = the EXACT GGUF file size in bytes from the Hub (ground truth — better than any params-times-bits estimate). - Chat memory (KV cache) = GQA-aware math from the model's real config (layers, hidden, kv-heads) when available; a conservative parameter-count heuristic when the repo is gated (labelled as estimated). - Working space includes a +0.577 GB buffer — the 95% load-success margin oobabooga fitted over 19,517 real measurements (gguf-vram-formula). - Non-GGUF families (vision / image gen / audio / embeddings / data) carry a single memory figure whose provenance is vendor-published, community- reported, or estimated — and the UI says which.
The catalogue is baked into the repo at build time (refreshed byscripts/refresh_catalogue.py), so the running app makes no network calls."""
import jsonfrom functools import lru_cachefrom pathlib import Path
from .hardware import HardwareSpecfrom .runtimes import pick_runtimes
_CATALOGUE_PATH = Path(__file__).resolve().parent.parent / "catalogue.json"
# We only fill a budget to this fraction — the rest is breathing room._SAFETY_FILL = 0.90# oobabooga's fitted 95%-load-success buffer (GB), cited in the UI footnote._CONFIDENCE_BUFFER_GB = 0.577
_VERDICT_WORD = {"great": "Runs great", "tight": "Tight, but works", "no": "Won't fit"}_C_MODEL = "#818CF8"_C_WORK = "#868E9C"
# Quant ladder quality order (matches scripts/refresh_catalogue.py)._QUANT_ORDER = ["Q8_0", "Q6_K", "Q5_K_M", "Q4_K_M", "IQ4_XS", "Q3_K_M", "Q2_K"]_FOUR_BIT_RANK = _QUANT_ORDER.index("IQ4_XS") # >= this index quality = sub-4-bit_COMPROMISE_QUANTS = ["Q4_K_M", "IQ4_XS", "Q3_K_M", "Q2_K"]
# --------------------------------------------------------------------------# Use cases# --------------------------------------------------------------------------
class UC: def __init__(self, key, plain, family, ctx=4096, min_b=0.5, good_b=3.0, factor=1.0, note=""): self.key, self.plain_name, self.family = key, plain, family self.context_tokens, self.min_b, self.good_b = ctx, min_b, good_b self.overhead_factor, self.note = factor, note
USE_CASES = {u.key: u for u in [ UC("chat", "Just chatting / asking questions", "llm", 4096, 0.5, 3.0), UC("writing", "Writing & summarising", "llm", 4096, 1.5, 7.0), UC("coding", "Coding help", "llm", 8192, 3.0, 7.0, note="Bigger models are much more reliable for code."), UC("agents", "Agents & tool use", "llm", 8192, 7.0, 7.0, 1.15, note="Needs steady instruction-following — go medium or larger."), UC("rag", "Chat with your documents", "llm", 16384, 3.0, 7.0, note="Long documents use extra memory for context — that's included here."), UC("translate", "Translation", "llm", 4096, 1.5, 7.0), UC("finetune", "Fine-tune an LLM (LoRA)", "llm", 2048, 3.0, 7.0, 2.2, note="Training needs roughly 2-3x the memory of just chatting. That's baked into these numbers."), UC("custom", "Your custom goal", "llm", 4096, 0.5, 7.0), UC("vlm", "Chat about images & video", "vlm", 4096, 2.0, 4.0), UC("detect", "Object detection", "vision"), UC("segment", "Image segmentation", "vision"), UC("pose", "Pose estimation (2D & 6-DoF)", "vision"), UC("classify", "Image classification", "vision"), UC("depth", "Depth estimation", "vision"), UC("ocr", "Read text from images (OCR)", "vision"), UC("train-vision", "Train a vision model", "vision", factor=3.0, note="Training needs roughly 3x the memory of running the same model."), UC("imagegen", "Generate images", "imagegen"), UC("inpaint", "Edit / inpaint images", "imagegen"), UC("upscale", "Upscale / restore images", "imagegen"), UC("videogen", "Generate video", "imagegen"), UC("bgremove", "Remove backgrounds", "imagegen"), UC("stt", "Speech to text", "audio"), UC("tts", "Text to speech / voice", "audio"), UC("music", "Generate music", "audio"), UC("embed", "Semantic search / embeddings", "embed"), UC("forecast", "Time-series forecasting", "data"), UC("tabular", "Predict from spreadsheets", "data"),]}
# Use cases answered by the whole LLM family (entries don't list these)._TEXT_UCS = {"chat", "writing", "coding", "agents", "rag", "translate", "finetune", "custom"}
_TOOLS = { "llm": [ {"name": "Ollama", "what": "Type one line; it downloads and runs the model for you.", "install": "Get it from ollama.com", "tag": "Easiest"}, {"name": "LM Studio", "what": "A point-and-click app with a chat window, no commands.", "install": "Download from lmstudio.ai", "tag": "Easy"}, {"name": "llama.cpp", "what": "The lightweight engine under the hood. Runs GGUF files directly.", "install": "Releases on GitHub", "tag": "Advanced"}, ], "vision": [ {"name": "Ultralytics", "what": "One pip install, then detect objects from a webcam or file.", "install": "pip install ultralytics", "tag": "Easiest"}, {"name": "PyTorch", "what": "Full control for custom pipelines and training.", "install": "pytorch.org", "tag": "Advanced"}, ], "imagegen": [ {"name": "ComfyUI", "what": "Powerful visual node editor for image/video pipelines.", "install": "Download from GitHub", "tag": "Moderate"}, {"name": "diffusers", "what": "Hugging Face's Python library for generation pipelines.", "install": "pip install diffusers", "tag": "Moderate"}, {"name": "Fooocus", "what": "Image generation that 'just works': one folder, double-click.", "install": "Download from GitHub", "tag": "Easiest"}, ], "audio": [ {"name": "faster-whisper", "what": "Fast, accurate transcription with a tiny install.", "install": "pip install faster-whisper", "tag": "Easiest"}, {"name": "whisper.cpp", "what": "Runs Whisper efficiently on CPU and small machines.", "install": "Build from GitHub", "tag": "Advanced"}, ], "embed": [ {"name": "sentence-transformers", "what": "Turn text into searchable vectors in a few lines.", "install": "pip install sentence-transformers", "tag": "Easiest"}, {"name": "Chroma", "what": "A simple local database to store and search those vectors.", "install": "pip install chromadb", "tag": "Easy"}, ], "data": [ {"name": "Python + pip", "what": "These models ship as small Python packages.", "install": "pip install (see the model card)", "tag": "Easiest"}, ],}_TOOLS["vlm"] = _TOOLS["llm"]
# --------------------------------------------------------------------------# Catalogue access# --------------------------------------------------------------------------
@lru_cache(maxsize=1)def catalogue() -> dict: return json.loads(_CATALOGUE_PATH.read_text(encoding="utf-8"))
@lru_cache(maxsize=1)def _by_use_case() -> dict: out: dict[str, list[dict]] = {} for e in catalogue()["entries"]: if e["family"] in ("llm", "vlm"): ucs = list(_TEXT_UCS) if e["family"] == "llm" else ["vlm"] else: ucs = e.get("use_cases", []) for uc in ucs: out.setdefault(uc, []).append(e) for uc in out: out[uc].sort(key=lambda e: e.get("params_b", 0), reverse=True) return out
def catalogue_date() -> str: return catalogue().get("generated_at", "")[:10]
# --------------------------------------------------------------------------# Memory math# --------------------------------------------------------------------------
# Fallback architecture shapes by parameter count (conservative typicals),# used only when a gated repo hides its config.json._ARCH_FALLBACK = [ (1.5, 24, 2048), (4.5, 28, 3072), (9.0, 32, 4096), (16.0, 40, 5120), (40.0, 48, 6656), (1e9, 80, 8192),]
def _kv_gb(entry: dict, ctx: int) -> tuple[float, bool]: """KV-cache GB for `ctx` tokens. Returns (gb, exact?).""" ctx = min(ctx, entry.get("context_len") or ctx) arch = entry.get("arch") if arch: per_layer = arch["hidden"] * arch["n_kv_heads"] / arch["n_heads"] return 2 * arch["n_layers"] * per_layer * ctx * 2 / 1e9, True params = entry.get("params_b", 4.0) for cap, layers, hidden in _ARCH_FALLBACK: if params <= cap: return 2 * layers * hidden * ctx * 2 * 0.30 / 1e9, False return 1.0, False
def _overhead_gb(weights: float, factor: float) -> float: if factor >= 2.0: # training: optimizer state + activations dominate return round(_CONFIDENCE_BUFFER_GB + weights * (factor - 1.0), 2) return round((_CONFIDENCE_BUFFER_GB + 0.08 * weights) * factor, 2)
def _estimate(entry: dict, quant: dict, ctx: int, factor: float) -> dict: weights = quant["file_gb"] kv, kv_exact = _kv_gb(entry, ctx) kv = round(kv, 2) overhead = _overhead_gb(weights, factor) return {"weights": weights, "kv": kv, "overhead": overhead, "total": round(weights + kv + overhead, 2), "kv_exact": kv_exact}
# --------------------------------------------------------------------------# Per-entry evaluation# --------------------------------------------------------------------------
def _quant_rank(key: str) -> int: return _QUANT_ORDER.index(key) if key in _QUANT_ORDER else len(_QUANT_ORDER)
def _feel(entry: dict, verdict: str, spec: HardwareSpec) -> str: if verdict == "no": return "—" active = entry.get("active_params_b") or entry.get("params_b", 4) if verdict == "tight": if entry.get("active_params_b"): return f"Usable even part-offloaded (only {entry['active_params_b']:g}B active per word)" return "Slow — usable for short tasks, not snappy chat" if active <= 4: return "Fast — replies feel instant" if active <= 14: return "Comfortable — quick enough for live chat" return "Steady — fine, just not instant on big answers"
def _eval_gguf(entry: dict, spec: HardwareSpec, uc: UC) -> dict: """Verdict for an LLM/VLM entry with a real quant ladder.""" fast, total = spec.fast_budget_gb, spec.total_budget_gb quants = sorted(entry.get("quants", []), key=lambda q: _quant_rank(q["key"])) ctx, factor = uc.context_tokens, uc.overhead_factor
# Fast path: best quality quant >= 4-bit that fits the GPU budget. if spec.has_fast_path: for q in quants: if _quant_rank(q["key"]) > _FOUR_BIT_RANK: break # don't call a sub-4-bit squeeze "runs great" est = _estimate(entry, q, ctx, factor) if est["total"] <= fast * _SAFETY_FILL: return {"verdict": "great", "quant": q, "est": est}
# Compromise: spill into ordinary RAM, shrinking quality only if needed. for qkey in _COMPROMISE_QUANTS: q = next((x for x in quants if x["key"] == qkey), None) if not q: continue est = _estimate(entry, q, ctx, factor) if est["total"] <= total * _SAFETY_FILL: return {"verdict": "tight", "quant": q, "est": est}
q = quants[-1] if quants else {"key": "Q4_K_M", "plain": "Balanced (4-bit)", "file_gb": entry.get("params_b", 4) * 0.6} return {"verdict": "no", "quant": q, "est": _estimate(entry, q, ctx, factor)}
def _eval_flat(entry: dict, spec: HardwareSpec, uc: UC) -> dict: """Verdict for a non-GGUF entry with one memory figure.""" need = round(entry.get("mem_gb", 4.0) * uc.overhead_factor, 2) fast, total = spec.fast_budget_gb, spec.total_budget_gb est = {"weights": need, "kv": 0.0, "overhead": 0.0, "total": need, "kv_exact": False} setting = {"key": "full", "plain": "Full model", "file_gb": need} if spec.has_fast_path and need <= fast * _SAFETY_FILL: return {"verdict": "great", "quant": setting, "est": est} # Image/video generation without a GPU is minutes-per-image: say so. if entry["family"] == "imagegen" and not spec.has_fast_path and need > 4: return {"verdict": "no", "quant": setting, "est": est} if need <= total * _SAFETY_FILL: return {"verdict": "tight", "quant": setting, "est": est} return {"verdict": "no", "quant": setting, "est": est}
def _evaluate(entry: dict, spec: HardwareSpec, uc: UC) -> dict: if entry.get("quants"): r = _eval_gguf(entry, spec, uc) else: r = _eval_flat(entry, spec, uc) r["entry"] = entry return r
# --------------------------------------------------------------------------# Advise: full UI-shaped result# --------------------------------------------------------------------------
def _option_json(r: dict, spec: HardwareSpec) -> dict: e, v = r["entry"], r["verdict"] feel = _feel(e, v, spec) if not e.get("quants") and v == "tight" and not spec.has_fast_path: feel = "Runs on the processor — slow but workable" lic_label = e.get("license", "") return { "verdict": v, "model": e["name"], "desc": e.get("good_for", ""), "setting": r["quant"].get("plain", "Full model"), "memory": "Too big" if v == "no" else f"{r['est']['total']:g} GB", "feel": feel, "params_b": e.get("params_b"), "active_params_b": e.get("active_params_b"), "url": (e.get("links") or {}).get("hf") or (e.get("links") or {}).get("home", ""), "license": lic_label, "license_note": e.get("license_note", ""), "gated": e.get("gated", False), "run": e.get("run", {}), "provenance": e.get("provenance", "estimated"), "stale": e.get("stale", False), }
def _pick_headline(results: list[dict], uc: UC) -> tuple[dict | None, bool]: great = [r for r in results if r["verdict"] == "great"] tight = [r for r in results if r["verdict"] == "tight"]
def params(r): return r["entry"].get("params_b", 0)
great_ok = [r for r in great if params(r) >= uc.min_b] tight_ok = [r for r in tight if params(r) >= uc.min_b] if great_ok: # Fast-and-capable is the best answer: biggest model that runs great. return max(great_ok, key=params), True if tight_ok: # Compromise: close to the ideal size, not needlessly oversized-and-slow. below = [r for r in tight_ok if params(r) <= uc.good_b * 1.5] return (max(below, key=params) if below else min(tight_ok, key=params)), True if great: return max(great, key=params), False if tight: return min(tight, key=params), False return None, False
def _provenance_line(headline: dict | None) -> str: if not headline: return "" e = headline["entry"] prov = e.get("provenance", "estimated") if prov == "filesize": line = ("Model size is the exact file size on Hugging Face. Chat memory and " "working space are conservative estimates with a 0.58 GB safety buffer " "(the 95% load-success margin fitted from ~19,500 real measurements).") if not headline["est"].get("kv_exact"): line += " This repo hides its exact shape, so chat memory is estimated from its size." return line if prov == "vendor": return "The memory figure is the maker's own published number." if prov == "community": return "The memory figure is community-reported, not vendor-published — treat it as a good estimate." return "The memory figure is estimated from the model's size — conservative, not measured."
def advise_real(payload: dict, spec: HardwareSpec) -> dict: uc = USE_CASES.get(payload.get("usecase", "chat"), USE_CASES["chat"]) candidates = _by_use_case().get(uc.key, []) results = [_evaluate(e, spec, uc) for e in candidates]
fast, total = spec.fast_budget_gb, spec.total_budget_gb headline, meets_goal = _pick_headline(results, uc)
options = [_option_json(r, spec) for r in results]
if headline: e, est, q = headline["entry"], headline["est"], headline["quant"] hv = headline["verdict"] need = est["total"] where = ("on your Mac" if spec.is_apple_silicon and hv == "great" else "on your graphics card" if hv == "great" and spec.has_fast_path else "using your computer's memory" if hv == "tight" else "") if hv == "great": head_text = f"Yes, you can run {e['name']} {where}, today." else: head_text = f"Sort of. {e['name']} will run {where}, with trade-offs." if e.get("quants"): detail = ( f"For this goal, the honest pick is <b>{e['name']}</b> at the " f"<b>{q.get('plain', q['key'])}</b> setting. {e.get('good_for','')} " f"It needs about <b>{need:g} GB</b> " f"(the model file is {est['weights']:g} GB — exact size on Hugging Face — " f"plus {est['kv']:g} GB chat memory and {est['overhead']:g} GB working space), " f"and you have roughly <b>{fast:g} GB</b> fast / <b>{total:g} GB</b> total." ) else: detail = ( f"For this goal, the honest pick is <b>{e['name']}</b>. " f"{e.get('good_for','')} It needs about <b>{need:g} GB</b>, and you have " f"roughly <b>{fast:g} GB</b> fast / <b>{total:g} GB</b> total." ) model_part, work_part = est["weights"], round(need - est["weights"], 2) else: hv = "no" smallest = min(results, key=lambda r: r["est"]["total"], default=None) need = smallest["est"]["total"] if smallest else 1.0 head_text = "This goal is a stretch on this machine. Here's the honest picture." detail = ( f"Even the lightest option here needs about <b>{need:g} GB</b>, but this " f"machine can offer only about <b>{total:g} GB</b> once the operating system " f"has its share. That's not a failure — small computers just have small " f"budgets. Adding memory, or a free cloud notebook, would open this up." ) model_part, work_part = round(need * 0.8, 2), round(need * 0.2, 2)
note_bits = [] if headline and not meets_goal: note_bits.append( f"This is the best this machine can do, but it's on the small side for " f"{uc.plain_name.lower()} — treat results as 'okay', not great.") if uc.note: note_bits.append(uc.note) if headline and headline["entry"].get("mem_note"): note_bits.append(headline["entry"]["mem_note"]) if headline and headline["entry"].get("license_note"): note_bits.append(headline["entry"]["license_note"]) if headline and headline["entry"].get("gated"): note_bits.append("This model is gated: accept its terms on Hugging Face once before downloading.")
scale = max(total, need, 1) * 1.05 gauge = { "need_gb": f"{need:g} GB needed", "fast_gb": f"{fast:g} GB", "total_gb": f"{total:g} GB", "fill_pct": round(min(need / scale, 1.0) * 100, 1), "mark_pct": round(min(fast / scale, 1.0) * 100, 1), "breakdown": [ {"label": f"Model {model_part:g} GB", "color": _C_MODEL}, {"label": f"Chat memory + working space {work_part:g} GB", "color": _C_WORK}, ], }
if uc.family == "llm": tools = [{"name": r.name, "what": r.plain_what, "install": r.install_hint, "tag": r.difficulty} for r in pick_runtimes(spec)] else: tools = _TOOLS.get(uc.family, [])
commands = {"intro": "These get you running in minutes — real commands for the exact pick above.", "items": []} if headline: run = headline["entry"].get("run", {}) if run.get("ollama"): commands["items"].append({"label": "Easy way (Ollama)", "code": run["ollama"]}) if run.get("llamacpp"): commands["items"].append({"label": "Power way (llama.cpp)", "code": run["llamacpp"]}) if run.get("pip"): commands["items"].append({"label": "Install", "code": run["pip"]})
return { "catalogue_version": catalogue_date(), "verdict": hv, "verdict_word": _VERDICT_WORD[hv], "headline": head_text, "detail": detail, "note": " ".join(note_bits), "gauge": gauge, "options": options, "tools": tools, "commands": commands, "provenance": _provenance_line(headline), "meets_goal": meets_goal, "use_case": uc.plain_name, }
# --------------------------------------------------------------------------# Reverse mode: "what machine do I need for X?"# --------------------------------------------------------------------------
# Ladders are cheap -> expensive. Budget hints are rough 2026 street prices for# a whole sensible build, shown as guidance, not gospel._PC_LADDER = [ ("Any old laptop (8 GB RAM, no GPU)", dict(ram_gb=8, vram_gb=0, vendor="none"), "what you may already own"), ("16 GB RAM laptop, no GPU", dict(ram_gb=16, vram_gb=0, vendor="none"), "~$500"), ("16 GB RAM + RTX 4060 (8 GB)", dict(ram_gb=16, vram_gb=8, vendor="nvidia"), "~$800"), ("16 GB RAM + RTX 3060 (12 GB)", dict(ram_gb=16, vram_gb=12, vendor="nvidia"), "~$900"), ("32 GB RAM + RTX 5070 (12 GB)", dict(ram_gb=32, vram_gb=12, vendor="nvidia"), "~$1,300"), ("32 GB RAM + RTX 5070 Ti (16 GB)", dict(ram_gb=32, vram_gb=16, vendor="nvidia"), "~$1,600"), ("32 GB RAM + RTX 4090 (24 GB)", dict(ram_gb=32, vram_gb=24, vendor="nvidia"), "~$2,500"), ("64 GB RAM + RTX 5090 (32 GB)", dict(ram_gb=64, vram_gb=32, vendor="nvidia"), "~$3,500+"),]_MAC_LADDER = [ ("Mac with 16 GB unified memory", dict(ram_gb=16), "~$1,000"), ("Mac with 24 GB unified memory", dict(ram_gb=24), "~$1,400"), ("Mac with 32 GB unified memory", dict(ram_gb=32), "~$1,800"), ("Mac with 64 GB unified memory", dict(ram_gb=64), "~$2,800"), ("Mac with 128 GB unified memory", dict(ram_gb=128), "~$4,500+"),]
def _spec_for_tier(kind: str, hw: dict) -> HardwareSpec: if kind == "mac": return HardwareSpec(os="macos", ram_gb=hw["ram_gb"], gpu_vendor="apple", is_apple_silicon=True, form_factor="mac") return HardwareSpec(os="windows", ram_gb=hw["ram_gb"], gpu_vendor=hw.get("vendor", "none"), vram_gb=hw.get("vram_gb", 0.0), form_factor="desktop")
def min_specs(usecase: str) -> dict: """For a goal: cheapest tier that works at all, the comfortable tier, and what each would actually run. Pure engine inversion — fully offline.""" uc = USE_CASES.get(usecase, USE_CASES["chat"])
def walk(kind, ladder): minimum = comfortable = None for label, hw, price in ladder: spec = _spec_for_tier(kind, hw) res = advise_real({"usecase": uc.key}, spec) great = [o for o in res["options"] if o["verdict"] == "great"] fits = [o for o in res["options"] if o["memory"] != "Too big"] best = (max(great, key=lambda o: o.get("params_b") or 0) if great else (max(fits, key=lambda o: o.get("params_b") or 0) if fits else None)) tier = {"label": label, "price": price, "runs": best["model"] if best else "", "verdict": res["verdict"]} if minimum is None and res["verdict"] in ("great", "tight") and res["meets_goal"]: minimum = tier if comfortable is None and res["verdict"] == "great" and res["meets_goal"]: comfortable = tier if minimum and comfortable: break return minimum, comfortable
pc_min, pc_comfy = walk("pc", _PC_LADDER) mac_min, mac_comfy = walk("mac", _MAC_LADDER) return { "use_case": uc.plain_name, "catalogue_version": catalogue_date(), "note": uc.note, "pc": {"minimum": pc_min, "comfortable": pc_comfy}, "mac": {"minimum": mac_min, "comfortable": mac_comfy}, "disclaimer": ("Price hints are rough 2026 street prices for a sensible whole " "build — they vary a lot by region and second-hand luck. The " "memory math is the same conservative engine as the main check."), }23 unmodified lines24252627282943 unmodified lines73747576777879808182 unmodified lines1641651661671681696 unmodified lines1761771781791801811821831841851861871881891901911921931947 unmodified lines20220320420520620720820921021121221313 unmodified lines22722822923023123213 unmodified lines246247248249250251252253254109 unmodified lines36436536636736836937037137237337437537637723 unmodified lines{ id: "translate", icon: "translate", label: "Translation" },]},{ icon: "cat-vision", name: "See & understand images", items: [{ id: "detect", icon: "detect", label: "Object detection (YOLO)" },{ id: "segment", icon: "segment", label: "Image segmentation" },{ id: "pose", icon: "pose", label: "Pose / 6-DoF (FoundationPose)" },43 unmodified lines};const $ = (s) => document.querySelector(s);const state = { computer: "Windows laptop", provider: "none", priority: "balanced", usecase: "chat", checked: false };let lastAdvice = null; // the most recent /api/advise result — facts the model explains// ---- Build the use-case picker -------------------------------------------function buildPicker() {const wrap = $("#usecase-picker");82 unmodified linesusecase: state.usecase,custom: $("#custom-uc").value.trim(),priority: state.priority,};}6 unmodified linesasync function check() {state.checked = true;try {const res = await fetch("/api/advise", {method: "POST", headers: { "Content-Type": "application/json" },body: JSON.stringify(gather()),});render(await res.json());} catch (e) {$("#results").innerHTML = `<div class="empty-state"><div class="big"><span class="ic" data-ic="monitor"></span></div><p>Couldn't reach the advisor. Is the server running?</p></div>`;hydrate($("#results"));}}// ---- Render results -------------------------------------------------------const VMAP = {great: { cls: "var(--ok)", soft: "var(--ok-soft)", word: "Runs great", em: "✓" },7 unmodified linesconst g = d.gauge || {};$("#cat-version").textContent = d.catalogue_version || "—";const opts = (d.options || []).map(o => {const ov = VMAP[o.verdict] || VMAP.tight;return `<div class="opt" style="--status:${ov.cls};--status-soft:${ov.soft}"><div class="vdot">${ov.em}</div><div><div class="name">${o.model}</div><div class="desc">${o.desc}</div></div><div class="meta"><b>${o.memory}</b><div class="feel">${o.setting} · ${o.feel}</div></div></div>`;}).join("");13 unmodified lines$("#results").innerHTML = `<div class="reveal"><div class="verdict" style="--status:${v.cls};--status-soft:${v.soft}"><span class="badge"><span class="dot"></span>${d.verdict_word || v.word}</span><h2>${d.headline || ""}</h2>13 unmodified lines<span class="item marker">Fast: ${g.fast_gb}</span><span class="item marker">Total: ${g.total_gb}</span></div></div>` : ""}${opts ? `<div class="section-title">What you can run <span class="sub">honestly, biggest to smallest</span></div><div class="opt-grid">${opts}</div>` : ""}${tools ? `<div class="section-title">How to actually run it</div>109 unmodified linesfunction init() {hydrate(document);buildPicker();wireSegmented("#computer-seg", "computer", () => { syncProviderForComputer(); $("#find-specs-body").innerHTML = findSpecsText(); });wireSegmented("#provider-seg", "provider", fillGpu);wireSegmented("#priority-seg", "priority");["#ram","#gpu","#vram","#custom-uc"].forEach(s => $(s).addEventListener("change", maybeLiveUpdate));$("#paste").addEventListener("input", maybeLiveUpdate);$("#check-btn").addEventListener("click", check);fillGpu();$("#find-specs-body").innerHTML = findSpecsText();// Pre-filled share/preview links: /?go renders results immediately.if (new URLSearchParams(location.search).has("go")) check();}23 unmodified lines2425262728293043 unmodified lines747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912082 unmodified lines2032042052062072082096 unmodified lines2162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143157 unmodified lines32332432532632732832933033133233333433533633733833934034134234334434513 unmodified lines35936036136236336436513 unmodified lines379380381382383384385386387388109 unmodified lines49849950050150250350450550650750850951051151251323 unmodified lines{ id: "translate", icon: "translate", label: "Translation" },]},{ icon: "cat-vision", name: "See & understand images", items: [{ id: "vlm", icon: "classify", label: "Chat about images (VLM)" },{ id: "detect", icon: "detect", label: "Object detection (YOLO)" },{ id: "segment", icon: "segment", label: "Image segmentation" },{ id: "pose", icon: "pose", label: "Pose / 6-DoF (FoundationPose)" },43 unmodified lines};const $ = (s) => document.querySelector(s);const state = { mode: "have", computer: "Windows laptop", provider: "none", priority: "balanced", usecase: "chat", checked: false };let lastAdvice = null; // the most recent /api/advise result — facts the model explains// ---- Buy-vs-check mode -----------------------------------------------------function applyMode() {const buy = state.mode === "buy";["#machine-step", "#priority-step", "#find-specs"].forEach(s => {const el = $(s); if (el) el.style.display = buy ? "none" : "";});const repo = $("#repo-field"); if (repo) repo.style.display = buy ? "none" : "";$("#check-btn").innerHTML = (buy ? "What should I get? " : "Check my setup ")+ '<span class="ic" data-ic="arrow"></span>';hydrate($("#check-btn"));}// ---- Best-effort hardware hints from the browser (honest: vendor + floor) --async function detectHardware() {const bits = [];try {if (navigator.gpu) {const ad = await navigator.gpu.requestAdapter();const v = ((ad && ad.info && (ad.info.vendor || ad.info.description)) || "").toLowerCase();for (const vendor of ["nvidia", "amd", "apple", "intel"]) {if (v.includes(vendor)) {state.provider = vendor;setActive("#provider-seg", vendor);fillGpu();bits.push(`a ${vendor.toUpperCase().replace("APPLE","Apple")} GPU`);break;}}}} catch (e) { /* detection is best-effort only */ }if (navigator.deviceMemory) bits.push(`at least ${navigator.deviceMemory} GB of RAM`);if (bits.length) {const h = $("#detect-hint");h.style.display = "";h.textContent = `Your browser reports ${bits.join(" and ")} — browsers can't see exact specs, so please confirm below.`;}}// ---- Build the use-case picker -------------------------------------------function buildPicker() {const wrap = $("#usecase-picker");82 unmodified linesusecase: state.usecase,custom: $("#custom-uc").value.trim(),priority: state.priority,repo: $("#repo-check") ? $("#repo-check").value.trim() : "",};}6 unmodified linesasync function check() {state.checked = true;const payload = gather();try {if (state.mode === "buy") {const res = await fetch("/api/minspecs", {method: "POST", headers: { "Content-Type": "application/json" },body: JSON.stringify({ usecase: state.usecase }),});renderBuy(await res.json());return;}const res = await fetch("/api/advise", {method: "POST", headers: { "Content-Type": "application/json" },body: JSON.stringify(payload),});render(await res.json());if (payload.repo) lookupRepo(payload); // optional live check, appended on top} catch (e) {$("#results").innerHTML = `<div class="empty-state"><div class="big"><span class="ic" data-ic="monitor"></span></div><p>Couldn't reach the advisor: ${e && e.message ? e.message : e}</p></div>`;hydrate($("#results"));}}// ---- Live single-model lookup (the one online feature, labelled as such) ---async function lookupRepo(payload) {const holder = $("#lookup-result");if (!holder) return;holder.innerHTML = `<div class="ans-loading"><span class="spinner"></span>Looking up ${payload.repo} on Hugging Face…</div>`;try {const res = await fetch("/api/lookup", {method: "POST", headers: { "Content-Type": "application/json" },body: JSON.stringify(payload),});const d = await res.json();if (d.error) {holder.innerHTML = `<div class="ans-card ans-error"><h3>Couldn't check that model</h3><p>${d.error}</p></div>`;return;}const o = d.option || {};const v = VMAP[o.verdict] || VMAP.tight;holder.innerHTML = `<div class="lookup-card reveal" style="--status:${v.cls};--status-soft:${v.soft}"><div class="lookup-head"><span class="badge"><span class="dot"></span>${v.word}</span><span class="live-tag">Live Hugging Face lookup</span></div><p class="lookup-explain">${d.explain || ""}</p><div class="lookup-meta">${o.memory && o.memory !== "Too big" ? `<span><b>${o.memory}</b> needed (${o.setting})</span>` : `<span><b>Too big</b> for this machine</span>`}${o.url ? `<a href="${o.url}" target="_blank" rel="noopener">View on Hugging Face</a>` : ""}</div>${o.run && o.run.ollama ? `<div class="cmd-box" style="margin-top:10px"><div class="cmd-label">Run it<button class="copy-btn" data-code="${encodeURIComponent(o.run.ollama)}">Copy</button></div><pre><code>${o.run.ollama}</code></pre></div>` : ""}</div>`;holder.querySelectorAll(".copy-btn").forEach(b => b.addEventListener("click", () => {navigator.clipboard.writeText(decodeURIComponent(b.dataset.code));b.textContent = "Copied ✓";setTimeout(() => { b.textContent = "Copy"; }, 1500);}));} catch (e) {holder.innerHTML = `<div class="ans-card ans-error"><h3>Lookup failed</h3><p>${e && e.message ? e.message : e}</p></div>`;}}// ---- Buy-advice render ------------------------------------------------------function renderBuy(d) {const lane = (title, icon, lanes) => {const tier = (t, kind) => t ? `<div class="tool" style="border-left:3px solid ${kind === "min" ? "var(--warn)" : "var(--ok)"}"><div class="tool-head"><span class="tname">${kind === "min" ? "Minimum" : "Comfortable"}</span><span class="tag ${kind === "min" ? "mid" : "best"}">${t.price}</span></div><div class="twhat"><b>${t.label}</b></div><div class="twhat">Runs: ${t.runs}${kind === "min" && t.verdict === "tight" ? " (with trade-offs)" : ""}</div></div>` : `<div class="tool"><div class="twhat">No tier on this ladder handles it comfortably — this goal wants workstation hardware.</div></div>`;return `<div class="section-title"><span class="ic" data-ic="${icon}"></span>${title}</div><div class="tool-grid">${tier(lanes.minimum, "min")}${tier(lanes.comfortable, "comfy")}</div>`;};$("#results").innerHTML = `<div class="reveal"><div class="verdict" style="--status:var(--accent);--status-soft:var(--accent-soft)"><span class="badge"><span class="dot"></span>Buying advice</span><h2>What you need for ${(d.use_case || "this").toLowerCase()}</h2><p>Two honest tiers per platform: the cheapest setup that genuinely works, and the one that feels good daily.</p>${d.note ? `<div class="note">${d.note}</div>` : ""}</div>${lane("Windows / Linux PC", "brand-windows", d.pc || {})}${lane("Mac (Apple Silicon)", "brand-apple", d.mac || {})}<p class="cmd-intro" style="margin-top:var(--s-4)">${d.disclaimer || ""}</p></div>`;hydrate($("#results"));$("#cat-version").textContent = d.catalogue_version || "—";}// ---- Render results -------------------------------------------------------const VMAP = {great: { cls: "var(--ok)", soft: "var(--ok-soft)", word: "Runs great", em: "✓" },7 unmodified linesconst g = d.gauge || {};$("#cat-version").textContent = d.catalogue_version || "—";const licChip = (o) => {if (!o.license) return "";const note = (o.license_note || "").toLowerCase();const warn = note.includes("non-commercial") || note.includes("agpl") || note.includes("research");const label = o.license.replace("apache-2.0", "Apache 2.0").replace("mit", "MIT").replace("agpl-3.0", "AGPL").replace("cc-by-nc-4.0", "CC-NC");return `<span class="lic${warn ? " warn" : ""}" title="${o.license_note || o.license}">${label}</span>`+ (o.gated ? `<span class="lic gatechip" title="Accept the terms on Hugging Face once before downloading">gated</span>` : "");};const opts = (d.options || []).map(o => {const ov = VMAP[o.verdict] || VMAP.tight;const name = o.url? `<a href="${o.url}" target="_blank" rel="noopener">${o.model}</a>` : o.model;return `<div class="opt" style="--status:${ov.cls};--status-soft:${ov.soft}"><div class="vdot">${ov.em}</div><div><div class="name">${name}${licChip(o)}</div><div class="desc">${o.desc}</div></div><div class="meta"><b>${o.memory}</b><div class="feel">${o.setting}${o.feel && o.feel !== "—" ? " · " + o.feel : ""}</div></div></div>`;}).join("");13 unmodified lines$("#results").innerHTML = `<div class="reveal"><div id="lookup-result"></div><div class="verdict" style="--status:${v.cls};--status-soft:${v.soft}"><span class="badge"><span class="dot"></span>${d.verdict_word || v.word}</span><h2>${d.headline || ""}</h2>13 unmodified lines<span class="item marker">Fast: ${g.fast_gb}</span><span class="item marker">Total: ${g.total_gb}</span></div>${d.provenance ? `<div class="prov">${d.provenance}</div>` : ""}</div>` : ""}${opts ? `<div class="section-title">What you can run <span class="sub">real models, biggest to smallest — names link to Hugging Face</span></div><div class="opt-grid">${opts}</div>` : ""}${tools ? `<div class="section-title">How to actually run it</div>109 unmodified linesfunction init() {hydrate(document);buildPicker();wireSegmented("#mode-seg", "mode", applyMode);wireSegmented("#computer-seg", "computer", () => { syncProviderForComputer(); $("#find-specs-body").innerHTML = findSpecsText(); });wireSegmented("#provider-seg", "provider", fillGpu);wireSegmented("#priority-seg", "priority");["#ram","#gpu","#vram","#custom-uc","#repo-check"].forEach(s => { const el = $(s); if (el) el.addEventListener("change", maybeLiveUpdate); });$("#paste").addEventListener("input", maybeLiveUpdate);$("#check-btn").addEventListener("click", check);fillGpu();$("#find-specs-body").innerHTML = findSpecsText();detectHardware();// Pre-filled share/preview links: /?go renders results immediately.if (new URLSearchParams(location.search).has("go")) check();}
31 unmodified lines32333435363738394053 unmodified lines94959697989910010110210340 unmodified lines14414514614714814915015131 unmodified lines<div class="layout"><!-- ============================== INPUTS ============================== --><aside class="panel form-panel"><!-- Step 1: machine --><div class="step"><div class="step-head"><span class="step-num">1</span><h2>Your computer</h2></div><div class="field"><span class="label">What kind of computer?</span>53 unmodified lines<span class="label">Describe what you want to build</span><input type="text" id="custom-uc" placeholder="e.g. real-time hand tracking from my webcam" /></div></div><!-- Step 3: preference --><div class="step"><div class="step-head"><span class="step-num">3</span><h2>What matters most? <span class="optional">(optional)</span></h2></div><div class="field" style="margin-bottom:0"><div class="segmented" id="priority-seg">40 unmodified lines<footer class="foot" id="how"><p>FitCheck gives <b>conservative</b> estimates from a transparent rules engine.It would rather under-promise than over-promise. Real speed depends on your exact chip, drivers and settings.</p><p style="margin-top:8px">Catalogue last updated <b id="cat-version">—</b>. Built for the Hugging Face Build Small hackathon.</p></footer></main>31 unmodified lines32333435363738394041424344454647484953 unmodified lines10310410510610710810911011111211311411511611740 unmodified lines15815916016116216316416516631 unmodified lines<div class="layout"><!-- ============================== INPUTS ============================== --><aside class="panel form-panel"><!-- Mode: check what I own, or advise what to buy --><div class="field" style="margin-bottom:var(--s-5)"><div class="segmented" id="mode-seg"><button class="seg-btn active" data-val="have"><span class="ic" data-ic="monitor"></span>Check my computer</button><button class="seg-btn" data-val="buy"><span class="ic" data-ic="search"></span>Help me pick one</button></div></div><!-- Step 1: machine --><div class="step" id="machine-step"><div class="step-head"><span class="step-num">1</span><h2>Your computer</h2></div><div class="hint" id="detect-hint" style="display:none; margin-bottom:var(--s-3)"></div><div class="field"><span class="label">What kind of computer?</span>53 unmodified lines<span class="label">Describe what you want to build</span><input type="text" id="custom-uc" placeholder="e.g. real-time hand tracking from my webcam" /></div><div class="field" id="repo-field" style="margin-top:var(--s-4); margin-bottom:0"><span class="label">Have a specific model in mind? <span class="optional">(optional)</span></span><input type="text" id="repo-check" placeholder="Paste a Hugging Face model id or link, e.g. lerobot/smolvla_base" /><div class="hint">Checks that exact model with a live Hugging Face lookup (the rest of FitCheck runs fully offline).</div></div></div><!-- Step 3: preference --><div class="step" id="priority-step"><div class="step-head"><span class="step-num">3</span><h2>What matters most? <span class="optional">(optional)</span></h2></div><div class="field" style="margin-bottom:0"><div class="segmented" id="priority-seg">40 unmodified lines<footer class="foot" id="how"><p>FitCheck gives <b>conservative</b> estimates from a transparent rules engine.Model sizes are the <b>exact file sizes on Hugging Face</b>; the rest is careful, deliberatelypessimistic math. It would rather under-promise than over-promise. Real speed depends on your exact chip, drivers and settings.</p><p style="margin-top:8px">Catalogue of real models last verified <b id="cat-version">—</b>. Built for the Hugging Face Build Small hackathon.</p></footer></main>
325 unmodified lines32632732832933033131 unmodified lines363364365366367368325 unmodified linesdisplay: grid; place-items: center; font-size: 15px; font-weight: 700;}.opt .name { font-weight: 700; font-family: var(--font-head); font-size: 15px; }.opt .desc { font-size: 13px; color: var(--text-muted); margin-top: 2px; }.opt .meta { text-align: right; font-size: 13px; color: var(--text-secondary); white-space: nowrap; }.opt .meta b { color: var(--text-primary); font-family: var(--font-head); }31 unmodified lines.copy-btn:hover { color: var(--text-primary); border-color: var(--border-hi); }.copy-btn.done { color: var(--ok); border-color: var(--ok); }/* Ask a follow-up (the model brick) */.ask-row { display: flex; gap: var(--s-2); }.ask-row input {325 unmodified lines32632732832933033133233333433533633733833934034134234334434531 unmodified lines377378379380381382383384385386387388389390391392393394395396397325 unmodified linesdisplay: grid; place-items: center; font-size: 15px; font-weight: 700;}.opt .name { font-weight: 700; font-family: var(--font-head); font-size: 15px; }.opt .name a { color: var(--text-primary); }.opt .name a:hover { color: var(--accent); text-decoration: none; }.lic {display: inline-block; margin-left: 8px; padding: 1px 8px; vertical-align: 1px;border-radius: var(--r-pill); border: 1px solid var(--border-hi);font: 600 10.5px/1.6 var(--font-body); letter-spacing: .02em;color: var(--text-muted); text-transform: uppercase;}.lic.warn { color: var(--warn); border-color: var(--warn); opacity: .9; }.lic.gatechip { color: var(--accent); border-color: var(--accent); }.prov {margin-top: 10px; padding-top: 10px; border-top: 1px solid var(--border);font-size: 12px; color: var(--text-muted); line-height: 1.55;}.opt .desc { font-size: 13px; color: var(--text-muted); margin-top: 2px; }.opt .meta { text-align: right; font-size: 13px; color: var(--text-secondary); white-space: nowrap; }.opt .meta b { color: var(--text-primary); font-family: var(--font-head); }31 unmodified lines.copy-btn:hover { color: var(--text-primary); border-color: var(--border-hi); }.copy-btn.done { color: var(--ok); border-color: var(--ok); }/* Live single-model lookup card */.lookup-card {border: 1px solid var(--border); border-left: 4px solid var(--status, var(--accent));border-radius: var(--r-md); background: var(--bg-raised);padding: var(--s-4) var(--s-5); margin-bottom: var(--s-5);}.lookup-head { display: flex; align-items: center; justify-content: space-between; margin-bottom: var(--s-2); }.live-tag {font: 600 11px/1 var(--font-body); text-transform: uppercase; letter-spacing: .05em;color: var(--accent); border: 1px dashed var(--accent); border-radius: var(--r-pill);padding: 4px 10px; opacity: .85;}.lookup-explain { color: var(--text-secondary); font-size: 14.5px; }.lookup-meta { display: flex; gap: var(--s-4); margin-top: var(--s-2); font-size: 13.5px; color: var(--text-secondary); }/* Ask a follow-up (the model brick) */.ask-row { display: flex; gap: var(--s-2); }.ask-row input {
app.py+41-240
catalogue.jsonAdded
engine/hub_lookup.pyAdded+155
engine/real_advisor.pyAdded+538
static/app.js+143-7
static/index.html+19-4
static/style.css+29