Spaces:
Running
Running
DNA-018: verdict-first result hierarchy + audit trail; reference_count()
Browse files14 unmodified lines15161718192021123 unmodified lines14514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519614 unmodified lines# scan.py is in the same directory as app.py in both local hf_space/ and on HFsys.path.insert(0, str(Path(__file__).parent))from scan import scan, inspect_gguf, KNOWN_BASES# ββ DNA-017: scan telemetry β HF dataset (fuels derivative discovery + demand-driven ingestion)# Guarded on LOG_TOKEN (a fine-grained WRITE token for RadicalNotionAI/modeldna-scan-log).123 unmodified linespass # graceful β don't break the scan if storage failsdef format_verdict(result: dict) -> tuple[str, str, str]:"""Format scan result into three UI sections."""if "error" in result:return ("β Scan Failed",f"**Error**: {result['error']}","")v = result.get("verdict", {})e = result.get("evidence", {})m = result.get("metadata", {})flags = v.get("flags", [])# Headerconfidence_emoji = {"HIGH": "β ", "MODERATE": "β οΈ", "ORIGINAL": "π§¬", "NEW": "π", "NONE": "β"}.get(v.get("confidence",""), "β")header = f"{confidence_emoji} **{v.get('architecture', 'Unknown')}**"# DNA-001: provenance risk score gaugeif "risk_score" in v:band = v.get("risk_band", "")be = {"CLEAN": "π’", "LOW": "π‘", "MODERATE": "π ", "HIGH": "π΄"}.get(band, "βͺ")header += f"\n\n### {be} Provenance Risk: {v['risk_score']}/100 Β· {band}"header += f"\n\n*Scanned in {result.get('elapsed_s', '?')}s Β· Stage 1 (config-only)*"header += f"\n\nπ₯ {m.get('downloads',0):,} downloads Β· π {m.get('likes',0)} likes"# Verdict detailsdetails = f"### Architecture Confirmation\n"details += f"**Base model**: {v.get('base_model_confirmed', 'Unrecognized')}\n"details += f"**Confidence**: {v.get('confidence', 'None')}\n\n"if e.get("base_matches"):details += "**Evidence**:\n"for bm in e["base_matches"][:2]:for ev in bm.get("evidence", []):details += f"- {ev}\n"details += "\n"if e.get("modelatlas_similar"):details += "**Similar verified models** (ModelAtlas reference):\n"for s in e["modelatlas_similar"][:3]:details += f"- `{s['model_id']}`\n"# DNA-004: shareable badge + model-card snippetdetails += "\n\n---\n\n" + build_badge(result.get("model_id", ""), v)# Flags β lead with the DNA-003 engine panel, then the detailflag_text = _fmt_engine_panel(v.get("engines", [])) + _fmt_flags(flags)return header, details, flag_text14 unmodified lines15161718192021123 unmodified lines14514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730814 unmodified lines# scan.py is in the same directory as app.py in both local hf_space/ and on HFsys.path.insert(0, str(Path(__file__).parent))from scan import scan, inspect_gguf, KNOWN_BASES, reference_count# ββ DNA-017: scan telemetry β HF dataset (fuels derivative discovery + demand-driven ingestion)# Guarded on LOG_TOKEN (a fine-grained WRITE token for RadicalNotionAI/modeldna-scan-log).123 unmodified linespass # graceful β don't break the scan if storage fails_RISK_EMOJI = {"CLEAN": "π’", "LOW": "π‘", "MODERATE": "π ", "HIGH": "π΄"}_ATTRIB_FLAGS = {"IMPOSSIBLE_WEIGHT_PROVENANCE", "NAMING_MISATTRIBUTION", "NAME_MISMATCH", "UNVERIFIABLE_CLAIM"}_DECEPTION_FLAGS = {"PROVENANCE_SCRUBBING", "IDENTITY_OVERRIDE"}def _claimed_brand(flags: list):"""The closed/foreign brand a deceptive name is riding on (for the headline subtitle)."""for f in flags:if f.get("type") in ("IMPOSSIBLE_WEIGHT_PROVENANCE", "NAMING_MISATTRIBUTION") and f.get("term"):return f["term"]return Nonedef _headline(v: dict, base_matches: list) -> tuple[str, str, str]:"""DNA-018: verdict-first headline. Verb tracks the FINDING, emoji tracks the RISK.Returns (emoji, verb, subtitle). Never labels a misattributed model with a green check."""flags = v.get("flags", [])ftypes = {f.get("type") for f in flags}band = v.get("risk_band", "")conf = v.get("confidence", "")base_label = base_matches[0]["name"] if base_matches else Nonebrand = _claimed_brand(flags)re = _RISK_EMOJI.get(band, "βͺ")if ftypes & _DECEPTION_FLAGS or band == "HIGH":if brand and base_label:sub = f"conceals its origin β presented as {brand}, actually {base_label}"elif base_label:sub = f"provenance actively obscured β true base is {base_label}"else:sub = "provenance actively obscured"return re, "DECEPTIVE", subif ftypes & _ATTRIB_FLAGS:if brand and base_label:sub = f'marketed as "{brand}", but the weights are {base_label}'elif base_label:sub = f"name overclaims β the actual base is {base_label}"else:sub = "the name does not match the architecture"return re, "MISATTRIBUTED", subif conf == "ORIGINAL":return "π§¬", "ORIGINAL", "first-party architecture β not a derivative of any known base"if conf == "NEW":return "π", "NEW", f"{v.get('base_model_confirmed','')} β not yet catalogued"if base_label:if band == "CLEAN":return "π’", "VERIFIED", f"{base_label} β naming is consistent with the architecture"return "π΅", "IDENTIFIED", base_labelreturn "β", "UNRECOGNIZED", "does not match any known base in the reference"def _moat_block(v: dict, e: dict, base_matches: list) -> str:"""DNA-018: 'How we know' β the ModelAtlas moat, stated. Independent, architecture-derived."""n = reference_count()n_str = f"{(n // 100) * 100:,}+" if n >= 200 else (f"{n:,}" if n else "our catalogue of")out = ["### 𧬠How we know",f"Independently fingerprinted against **ModelAtlas β {n_str} catalogued models**."]if base_matches:top = base_matches[0]ev = "; ".join(list(dict.fromkeys(top.get("evidence", [])))[:2]) # dedup, top 2out.append(f"**True base:** {top['name']} β {top.get('confidence','')} match ({ev}).")out.append("Verified from the model's own architecture β **not** the uploader's declaration.")elif v.get("confidence") in ("ORIGINAL", "NEW"):out.append(f"**{v.get('base_model_confirmed','')}** β no derivative signature; treated as an original architecture.")else:out.append("No matching base architecture was found in the reference.")return "\n\n".join(out)def _action_block(v: dict) -> str:"""DNA-018: 'Why it matters / what to do' β turns the verdict into an actionable reason."""flags = v.get("flags", [])band = v.get("risk_band", "")if not flags and band in ("CLEAN", ""):return ("### β What this means\n\n""No provenance concerns detected β architecture and naming are consistent. ""Standard due-diligence (license, intended use) still applies.")out = ["### β οΈ Why it matters / what to do"]for f in flags:t = f.get("type")if t == "IMPOSSIBLE_WEIGHT_PROVENANCE":brand = f.get("term", "the referenced closed model")out.append(f"- **Impossible weight claim.** {brand} weights were never publicly released, so this model cannot contain them. At best it is trained on generated outputs (distillation) β which leaves no weight-level trace, cannot be verified, and may violate the provider's terms.")elif t == "NAMING_MISATTRIBUTION":out.append("- **Misattribution.** The name foregrounds a brand the model has no architectural claim to, while omitting the base it is actually built from.")elif t == "NAME_MISMATCH":out.append("- **Name/architecture mismatch.** The name implies a different base than the weights indicate.")elif t == "PROVENANCE_SCRUBBING":out.append("- **Provenance scrubbing.** The chat template denies its true lineage β a deliberate step to obscure origin.")elif t == "IDENTITY_OVERRIDE":out.append("- **Identity override.** The model is configured to self-report a false identity.")else:out.append(f"- {f.get('explanation','')}")if band == "HIGH":out.append("**Recommendation:** avoid for anything provenance-sensitive; treat all lineage and capability claims as unproven until independently verified.")elif band == "MODERATE":out.append("**Recommendation:** verify the license before use and treat capability claims as unproven β the true base above is what you are actually running.")else:out.append("**Recommendation:** minor β note the discrepancy and verify license terms.")return "\n\n".join(out)def _audit_trail(result: dict) -> str:"""DNA-018 (DeepSeek): shareable chain-of-custody β the fingerprint the verdict is derived from."""e = result.get("evidence", {})cs = e.get("config_signals", {}) or {}v = result.get("verdict", {})top = (e.get("base_matches") or [{}])[0]lines = ["```"]lines.append(f"model_id : {result.get('model_id','')}")lines.append(f"scanned_at : {result.get('scanned_at','')}")for k, label in (("model_type", "model_type"), ("vocab_size", "vocab_size"),("hidden_size", "hidden_size"), ("num_layers", "num_layers"),("has_mla", "has_mla")):if cs.get(k) is not None:lines.append(f"{label:<13}: {cs.get(k)}")if top:lines.append(f"matched_base : {top.get('name')} (score {top.get('score')}, {top.get('confidence')})")lines.append(f"risk : {v.get('risk_score')}/100 {v.get('risk_band','')}")lines.append(f"reference : ModelAtlas ({reference_count()} models)")lines.append("engine : ModelDNA Stage-1 (config-only, no weight download)")lines.append("```")return "### π Fingerprint Β· audit trail\n\n_Copy as evidence β this is exactly what the verdict is derived from._\n\n" + "\n".join(lines)def format_verdict(result: dict) -> tuple[str, str, str]:"""DNA-018 verdict-first layout: pane 1 = VERDICT β MOAT β ACTION; pane 2 = audit trail +similar models + badge; pane 3 = engine panel + flag detail."""if "error" in result:return ("β Scan Failed", f"**Error**: {result['error']}", "")v = result.get("verdict", {})e = result.get("evidence", {})m = result.get("metadata", {})flags = v.get("flags", [])base_matches = e.get("base_matches", [])# ββ Pane 1: the lead. Verdict headline, risk gauge, then WHY-WE-KNOW and WHAT-TO-DO.emoji, verb, subtitle = _headline(v, base_matches)header = f"# {emoji} {verb}\n**{subtitle}**"if "risk_score" in v:band = v.get("risk_band", "")be = _RISK_EMOJI.get(band, "βͺ")header += f"\n\n### {be} Provenance Risk: {v['risk_score']}/100 Β· {band}"header += f"\n\n*Scanned in {result.get('elapsed_s', '?')}s Β· Stage 1 (config-only) Β· "header += f"π₯ {m.get('downloads',0):,} Β· π {m.get('likes',0)}*"header += "\n\n---\n\n" + _moat_block(v, e, base_matches)header += "\n\n---\n\n" + _action_block(v)# ββ Pane 2: the evidence & the shareable proof.details = _audit_trail(result)if e.get("modelatlas_similar"):details += "\n\n### Similar verified models (ModelAtlas reference)\n"for s in e["modelatlas_similar"][:3]:details += f"- `{s['model_id']}`\n"details += "\n\n---\n\n" + build_badge(result.get("model_id", ""), v)# ββ Pane 3: the detector engines + flag detail (backup depth).flag_text = _fmt_engine_panel(v.get("engines", [])) + _fmt_flags(flags)return header, details, flag_text
app.py+142-30