label marker vs sweep regions; explain sweep parse failures; sweep toggle
Browse files65 unmodified lines6667686970717273747565 unmodified linesmarker-dense go to the model first. **The ranking decides reading order, never the verdict.** Thereport always says how many marked regions were left unread, so "clean" never overstates itself.A file with no marker anywhere yields exactly one candidate β the head of the document β which isbyte-identical to what the corpus builder produced for a *clean* file. The triage only knows thetwelve families this project generated, so a payload shaped like none of them is triaged as if thefile were clean and MiMo sees the head of the file. That is a real hole, and the interface says so.**Nothing is downloaded until it is needed.** The page comes up first; the 4.7 GB GGUF, the550 MB embedding model and the 3 MB index arrive on the first scan and are cached after that.65 unmodified lines666768697071727374757677787980818283848586878889909165 unmodified linesmarker-dense go to the model first. **The ranking decides reading order, never the verdict.** Thereport always says how many marked regions were left unread, so "clean" never overstates itself.A file with no marker anywhere yields exactly one marker candidate β the head of the document βwhich is byte-identical to what the corpus builder produced for a *clean* file.### Batches, and the sweepMarker regions alone leave most of a file unread: the triage only knows the twelve families thisproject generated, so a payload shaped like none of them produces no marker and would sit in textthe model never saw while the report said "clean". So after the marker regions, the rest of theskeleton is tiled into windows of the same size, and the whole list is cut into **batches sized tofit one run of the model** β one ZeroGPU grant, or a tolerable wait on CPU. You pick which batch tospend a run on, and the report always states how much is still unread.**The sweep regions do not inherit Part B's accuracy, and the app says so.** Part B only evershowed MiMo marker-centred windows or the head of a document. Handed an arbitrary mid-file contentstream β a page of font-positioning operators β MiMo frequently does not answer at all: it carrieson copying the input after the prefill, and the answer parses as unrecoverable, which scores as*not injected*. Those regions buy coverage of text that would otherwise never be looked at; a*clean* verdict on one is close to no evidence. The regions table labels every row `marker` or`sweep`, the report counts the sweep parse failures separately and explains them, and the sweep canbe switched off to keep the app strictly inside the shape Part B measured.**Nothing is downloaded until it is needed.** The page comes up first; the 4.7 GB GGUF, the550 MB embedding model and the 3 MB index arrive on the first scan and are cached after that.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306"""PDF Injection Detector - MiMo-7B.Upload a PDF, and this reads it the way the corpus was read, cuts it into batches of regions thatfit one run of the model, and asks MiMo-7B-RL whether a payload is hidden in the batch you choose.`app.py` holds the interface, the batching and the aggregation. It contains no detection logic ofits own: the text extraction lives in `corpus_text.py`, the prompt and parser in `mimo.py`, theembedding lookup in `neighbours.py`, and each is quoted from the notebook that measured it."""import reimport tracebackimport gradio as grimport corpus_textimport mimoimport neighbours# Measured in Part B on a T4, on the project's own 1,100-document corpus.PART_B = {"f1": 0.945, "precision": 0.988, "recall": 0.906, "family_acc": 0.433,"false_alarm_rate": 0.05, "unparsable": 155, "n": 1100}GPU = mimo.BACKEND == "gpu"# How many regions fit in ONE run is not a taste decision. On ZeroGPU a single grant is capped at# 300 seconds and the whole scan plus the 4-bit load must fit inside it; on 2 vCPUs a region costs# two minutes and a browser will not wait for many. That ceiling is what a batch is.MAX_PER_BATCH = mimo.MAX_WINDOWS_GPU if GPU else 6DEFAULT_PER_BATCH = 8 if GPU else 3WINDOW_COLUMNS = ["#", "where in the skeleton", "markers", "verdict", "family", "evidence"]def fmt_eta(n: int) -> str:seconds = n * mimo.SECONDS_PER_WINDOWif seconds < 90:return f"about {max(20, int(seconds))}s"return f"{seconds * 0.6 / 60:.0f}-{seconds * 1.5 / 60:.0f} min"def extract(path):"""PDF bytes to ranked candidate regions. No model touched, so this runs on upload."""with open(path, "rb") as fh:data = fh.read()skeleton, truncated, dropped = corpus_text.build_skeleton(data)return data, skeleton, truncated, dropped, corpus_text.candidate_windows(skeleton)def batches_of(candidates, per_batch):"""The ranked regions cut into runnable chunks. Batch 1 is the most marker-dense."""per_batch = max(1, int(per_batch))return [candidates[i:i + per_batch] for i in range(0, len(candidates), per_batch)]def batch_label(batch, i, n_batches):"""What one batch is, in a line, so the choice is informed rather than a number."""first, last = batch[0], batch[-1]if first["is_head"]:where = "head of document"else:where = f"chars {min(w['start'] for w in batch):,}-{max(w['end'] for w in batch):,}"fams = sorted({f for w in batch for f in w["families"]})n_marker = sum(1 for w in batch if w["source"] == "marker")kind = ("marker regions" if n_marker == len(batch) else"sweep of the document" if n_marker == 0 elsef"{n_marker} marker + {len(batch) - n_marker} sweep")tail = f" Β· {', '.join(fams)}" if fams else ""return (f"Batch {i + 1} of {n_batches} β {len(batch)} region(s), {kind} Β· {where}{tail} Β· "f"~{fmt_eta(len(batch))}")def on_upload(path, per_batch):"""Extract, rank and batch. Fast enough to run on every upload and every slider move."""if not path:return (None, "Upload a PDF to see what will be read.",gr.update(choices=[], value=None, interactive=False))try:data, skeleton, truncated, dropped, candidates = extract(path)except Exception as e:return (None, f"Could not read that file: `{type(e).__name__}: {e}`",gr.update(choices=[], value=None, interactive=False))groups = batches_of(candidates, per_batch)choices = [(batch_label(b, i, len(groups)), i) for i, b in enumerate(groups)]lines = [f"**{len(data):,} bytes** on disk, rendered to a **{len(skeleton):,}-character skeleton**"+ (f" (truncated to the {corpus_text.SKELETON_CHAR_BUDGET:,}-character budget)"if truncated else "")+ (f", {dropped} binary stream(s) dropped." if dropped else "."),]n_marker = sum(1 for w in candidates if w["source"] == "marker")fams = corpus_text.detect_markers(data)if n_marker:lines.append(f"**{n_marker} region(s) carry a marker**, and the remaining "f"{len(candidates) - n_marker} cover the rest of the document β "f"**{len(candidates)} in total, cut into {len(groups)} batch(es)** of at most "f"{int(per_batch)}. Structural signatures in the raw file: "f"`{'`, `'.join(fams) or 'none'}`.")lines.append("_Ranking decides **reading order only** β batch 1 is the most marker-dense, not the ""guilty one. The verdict is MiMo's alone._")else:lines.append(f"**No structural marker anywhere in the file.** The triage only recognises the twelve "f"families this project generated, so this means either a clean file or a payload "f"shaped like none of them β which is why the batches below sweep the **whole** "f"skeleton rather than stopping here: **{len(candidates)} region(s) in "f"{len(groups)} batch(es)**.")lines.append(f"Pick a batch and press **Check this batch**. One batch is one run of the model, "f"sized to fit the **{mimo.BACKEND.upper()}** runtime's limit; run as many "f"batches as you like, one at a time.")return ((skeleton, candidates), "\n\n".join(lines),gr.update(choices=choices, value=0, interactive=True))def resolve_batch(value, n_batches: int) -> int:"""Whatever the dropdown handed back, as a batch index that exists.Because the dropdown allows custom values it can arrive as the integer index, as `None` beforeanything was picked, or as the label string itself. All three mean something, and none of themshould be an exception in front of a user who just pressed a button."""if isinstance(value, (int, float)):idx = int(value)else:digits = re.search(r"\d+", str(value or ""))idx = int(digits.group()) - 1 if digits else 0 # labels are 1-based, indices are notreturn idx if 0 <= idx < n_batches else 0def run(path, per_batch, batch_index, want_neighbours, progress=gr.Progress()):"""Score one batch."""if not path:return "Upload a PDF first.", [], [], ""progress(0.05, desc="reading the PDF")try:_, _, _, _, candidates = extract(path)except Exception as e:return f"Could not read that file: `{type(e).__name__}: {e}`", [], [], ""groups = batches_of(candidates, per_batch)idx = resolve_batch(batch_index, len(groups))batch = groups[idx]progress(0.15, desc=f"loading MiMo ({mimo.BACKEND})")try:answers = mimo.judge_all([w["text"] for w in batch],progress=lambda m: progress(0.4, desc=m))except Exception as e:return (f"## MiMo could not run\n\n`{type(e).__name__}: {e}`\n\nRuntime selected: "f"**{mimo.BACKEND}**."), [], [], traceback.format_exc()offset = idx * max(1, int(per_batch))rows, log, results = [], [], list(zip(batch, answers))for i, (win, r) in enumerate(results):where = "head of document" if win["is_head"] else f"chars {win['start']:,}-{win['end']:,}"verdict = ("PAYLOAD" if r["pred_injected"] else "clean") + ("" if r["parse_ok"] else " (unreadable answer)")rows.append([offset + i + 1, where, ", ".join(win["families"]) or "-", verdict,r["pred_family"], (r["evidence"] or "-")[:160]])log.append(f"--- region {offset + i + 1} ({where}, prompt via {r['prompt_route']}) ---\n"f"{r['raw']}")report = build_report(results, idx, groups, len(candidates))nb_rows = []if want_neighbours and results:progress(0.95, desc="embedding and looking up the corpus")flagged = next((w for w, r in results if r["pred_injected"]), None)query = flagged or batch[0]try:neighbours.check_provenance()nb_rows = neighbours.neighbour_rows(query["text"], k=5)basis = ("the first flagged region" if flagged else"the first region in this batch (nothing was flagged)")report += (f"\n\n### Nearest files in the corpus\n\nEmbedded from **{basis}** with "f"Part A's winning configuration. Precision@5 on this index is **35.6%** "f"against a 6.8% random baseline: fewer than 2 of the 5 listed are the same "f"kind of attack. Read it as *resemblance*, not identification.")except Exception as e:report += (f"\n\n### Nearest files in the corpus\n\nUnavailable: "f"`{type(e).__name__}: {e}`")log.append(traceback.format_exc())return report, rows, nb_rows, "\n\n".join(log)def build_report(results, idx, groups, n_candidates) -> str:"""The verdict for this batch, and an explicit account of what is still unread."""if not results:return "Nothing was read."hits = [(w, r) for w, r in results if r["pred_injected"]]unparsed = sum(1 for _, r in results if not r["parse_ok"])read = len(results)unread = n_candidates - readothers = [i for i in range(len(groups)) if i != idx]if hits:fams = sorted({r["pred_family"] for _, r in hits if r["pred_family"] != "none"})head = (f"## Payload found in batch {idx + 1}\n\nMiMo flagged **{len(hits)} of the {read} "f"region(s)** in this batch.")head += (f" It named the family as **{', '.join(fams)}** β correct 43% of the time in "f"Part B, so treat it as a suggestion." if famselse " It did not commit to a family.")else:head = (f"## Nothing found in batch {idx + 1}\n\nMiMo read **{read} region(s)** in this "f"batch and flagged none of them.")caveats = []if unread > 0:caveats.append(f"**This is 1 of {len(groups)} batches.** {unread} region(s) across "f"{len(others)} other batch(es) have not been read. Whatever this batch says, it says "f"it about {read} of the file's {n_candidates} candidate regions β nothing more.")if unparsed:caveats.append(f"{unparsed} answer(s) could not be parsed and count as *not injected*, "f"exactly as Part B scored them (155 of 1,100 there).")body = headif caveats:body += "\n\n" + "\n\n".join("- " + c for c in caveats)body += (f"\n\n---\n\n**On the corpus Part B measured**, MiMo scored F1 {PART_B['f1']}, "f"precision {PART_B['precision']}, recall {PART_B['recall']} on {PART_B['n']:,} "f"documents that were 82% injected β where a detector that flags everything without "f"reading it scores F1 0.900. Read 0.945 against 0.900, not against zero.\n\n"f"_Runtime: **{mimo.BACKEND}**. {mimo.RUNTIME_CAVEAT}_")return bodyINTRO = f"""# PDF Injection Detector β MiMo-7BUpload a PDF. It is rendered to text with the extractor that built the project corpus, the regionscarrying structural markers are ranked and cut into **batches that fit one run of the model**, and**MiMo-7B-RL** reads the batch you choose β reporting whether a payload is hidden there, and thesubstring that convinced it.Batching is what keeps a long document inside the runtime's limit: one batch is one run, and youdecide how many runs to spend. The report always states how much of the file is still unread.This is a coursework artefact built on a synthetic corpus of 1,100 PDFs carrying harmlessEICAR/AMTSO/WICAR/RANSIM test markers. **It is not a general malware scanner**, and real malwaredoes not announce itself the way these samples do.Running on the **{mimo.BACKEND.upper()}** runtime({'4-bit NF4 β Part Bβs own configuration' if GPU else 'Q4_K_M GGUF via llama.cpp'}),about {mimo.SECONDS_PER_WINDOW:g}s per region."""with gr.Blocks(title="PDF Injection Detector") as demo:gr.Markdown(INTRO)state = gr.State()with gr.Row():with gr.Column(scale=1):pdf = gr.File(label="PDF", file_types=[".pdf"], type="filepath")per_batch = gr.Slider(1, MAX_PER_BATCH, value=DEFAULT_PER_BATCH, step=1,label="Regions per batch",info=f"One batch is one run of the model. The "f"{mimo.BACKEND.upper()} runtime tops out at "f"{MAX_PER_BATCH}.")# allow_custom_value: the choices are empty until a PDF is uploaded, and without this# Gradio validates any incoming value against that empty list and rejects it - which# makes the batch un-selectable over the API even though the UI had populated it.# `resolve_batch` below is what actually decides the index, from the file itself.batch_pick = gr.Dropdown(label="Batch to check", choices=[], interactive=False,allow_custom_value=True,info="Each batch is a separate run β spend as many as you ""like.")want_nb = gr.Checkbox(value=True, label="Also show the nearest files in the corpus",info="Adds a one-off 550 MB embedding-model download.")go = gr.Button("Check this batch", variant="primary")plan = gr.Markdown("Upload a PDF to see what will be read.")with gr.Column(scale=2):with gr.Tab("Report"):report = gr.Markdown()with gr.Tab("Regions read"):window_table = gr.Dataframe(headers=WINDOW_COLUMNS, wrap=True, interactive=False)with gr.Tab("Nearest corpus files"):nb_table = gr.Dataframe(headers=neighbours.NEIGHBOUR_COLUMNS, interactive=False)with gr.Tab("What MiMo actually said"):# No `show_copy_button`: gradio 6 removed it, and this Space should survive an# sdk_version bump rather than crash at startup on a cosmetic argument.raw = gr.Textbox(lines=22, interactive=False,label="The prompt route and untouched generation per region")for ev in (pdf.change, per_batch.change):ev(on_upload, [pdf, per_batch], [state, plan, batch_pick])go.click(run, [pdf, per_batch, batch_pick, want_nb],[report, window_table, nb_table, raw])if __name__ == "__main__":demo.queue(max_size=8).launch()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329"""PDF Injection Detector - MiMo-7B.Upload a PDF, and this reads it the way the corpus was read, cuts it into batches of regions thatfit one run of the model, and asks MiMo-7B-RL whether a payload is hidden in the batch you choose.`app.py` holds the interface, the batching and the aggregation. It contains no detection logic ofits own: the text extraction lives in `corpus_text.py`, the prompt and parser in `mimo.py`, theembedding lookup in `neighbours.py`, and each is quoted from the notebook that measured it."""import reimport tracebackimport gradio as grimport corpus_textimport mimoimport neighbours# Measured in Part B on a T4, on the project's own 1,100-document corpus.PART_B = {"f1": 0.945, "precision": 0.988, "recall": 0.906, "family_acc": 0.433,"false_alarm_rate": 0.05, "unparsable": 155, "n": 1100}GPU = mimo.BACKEND == "gpu"# How many regions fit in ONE run is not a taste decision. On ZeroGPU a single grant is capped at# 300 seconds and the whole scan plus the 4-bit load must fit inside it; on 2 vCPUs a region costs# two minutes and a browser will not wait for many. That ceiling is what a batch is.MAX_PER_BATCH = mimo.MAX_WINDOWS_GPU if GPU else 6DEFAULT_PER_BATCH = 8 if GPU else 3WINDOW_COLUMNS = ["#", "where in the skeleton", "kind", "markers", "verdict", "family", "evidence"]def fmt_eta(n: int) -> str:seconds = n * mimo.SECONDS_PER_WINDOWif seconds < 90:return f"about {max(20, int(seconds))}s"return f"{seconds * 0.6 / 60:.0f}-{seconds * 1.5 / 60:.0f} min"def extract(path, cover_all=True):"""PDF bytes to ranked candidate regions. No model touched, so this runs on upload."""with open(path, "rb") as fh:data = fh.read()skeleton, truncated, dropped = corpus_text.build_skeleton(data)return (data, skeleton, truncated, dropped,corpus_text.candidate_windows(skeleton, cover_all=bool(cover_all)))def batches_of(candidates, per_batch):"""The ranked regions cut into runnable chunks. Batch 1 is the most marker-dense."""per_batch = max(1, int(per_batch))return [candidates[i:i + per_batch] for i in range(0, len(candidates), per_batch)]def batch_label(batch, i, n_batches):"""What one batch is, in a line, so the choice is informed rather than a number."""first, last = batch[0], batch[-1]if first["is_head"]:where = "head of document"else:where = f"chars {min(w['start'] for w in batch):,}-{max(w['end'] for w in batch):,}"fams = sorted({f for w in batch for f in w["families"]})n_marker = sum(1 for w in batch if w["source"] == "marker")kind = ("marker regions" if n_marker == len(batch) else"sweep of the document" if n_marker == 0 elsef"{n_marker} marker + {len(batch) - n_marker} sweep")tail = f" Β· {', '.join(fams)}" if fams else ""return (f"Batch {i + 1} of {n_batches} β {len(batch)} region(s), {kind} Β· {where}{tail} Β· "f"~{fmt_eta(len(batch))}")def on_upload(path, per_batch, cover_all):"""Extract, rank and batch. Fast enough to run on every upload and every slider move."""if not path:return (None, "Upload a PDF to see what will be read.",gr.update(choices=[], value=None, interactive=False))try:data, skeleton, truncated, dropped, candidates = extract(path, cover_all)except Exception as e:return (None, f"Could not read that file: `{type(e).__name__}: {e}`",gr.update(choices=[], value=None, interactive=False))groups = batches_of(candidates, per_batch)choices = [(batch_label(b, i, len(groups)), i) for i, b in enumerate(groups)]lines = [f"**{len(data):,} bytes** on disk, rendered to a **{len(skeleton):,}-character skeleton**"+ (f" (truncated to the {corpus_text.SKELETON_CHAR_BUDGET:,}-character budget)"if truncated else "")+ (f", {dropped} binary stream(s) dropped." if dropped else "."),]n_marker = sum(1 for w in candidates if w["source"] == "marker")fams = corpus_text.detect_markers(data)if n_marker:lines.append(f"**{n_marker} region(s) carry a marker**, and the remaining "f"{len(candidates) - n_marker} cover the rest of the document β "f"**{len(candidates)} in total, cut into {len(groups)} batch(es)** of at most "f"{int(per_batch)}. Structural signatures in the raw file: "f"`{'`, `'.join(fams) or 'none'}`.")lines.append("_Ranking decides **reading order only** β batch 1 is the most marker-dense, not the ""guilty one. The verdict is MiMo's alone._")elif cover_all:lines.append(f"**No structural marker anywhere in the file.** The triage only recognises the twelve "f"families this project generated, so this means either a clean file or a payload "f"shaped like none of them β which is why the batches below sweep the **whole** "f"skeleton rather than stopping here: **{len(candidates)} region(s) in "f"{len(groups)} batch(es)**.")else:lines.append("**No structural marker anywhere in the file**, and the sweep is switched off β so ""only the head of the document will be read, which is exactly what the corpus builder ""produced for a *clean* file. Switch the sweep on to look at the rest of it.")lines.append(f"Pick a batch and press **Check this batch**. One batch is one run of the model, "f"sized to fit the **{mimo.BACKEND.upper()}** runtime's limit; run as many "f"batches as you like, one at a time.")return ((skeleton, candidates), "\n\n".join(lines),gr.update(choices=choices, value=0, interactive=True))def resolve_batch(value, n_batches: int) -> int:"""Whatever the dropdown handed back, as a batch index that exists.Because the dropdown allows custom values it can arrive as the integer index, as `None` beforeanything was picked, or as the label string itself. All three mean something, and none of themshould be an exception in front of a user who just pressed a button."""if isinstance(value, (int, float)):idx = int(value)else:digits = re.search(r"\d+", str(value or ""))idx = int(digits.group()) - 1 if digits else 0 # labels are 1-based, indices are notreturn idx if 0 <= idx < n_batches else 0def run(path, per_batch, batch_index, want_neighbours, cover_all, progress=gr.Progress()):"""Score one batch."""if not path:return "Upload a PDF first.", [], [], ""progress(0.05, desc="reading the PDF")try:_, _, _, _, candidates = extract(path, cover_all)except Exception as e:return f"Could not read that file: `{type(e).__name__}: {e}`", [], [], ""groups = batches_of(candidates, per_batch)idx = resolve_batch(batch_index, len(groups))batch = groups[idx]progress(0.15, desc=f"loading MiMo ({mimo.BACKEND})")try:answers = mimo.judge_all([w["text"] for w in batch],progress=lambda m: progress(0.4, desc=m))except Exception as e:return (f"## MiMo could not run\n\n`{type(e).__name__}: {e}`\n\nRuntime selected: "f"**{mimo.BACKEND}**."), [], [], traceback.format_exc()offset = idx * max(1, int(per_batch))rows, log, results = [], [], list(zip(batch, answers))for i, (win, r) in enumerate(results):where = "head of document" if win["is_head"] else f"chars {win['start']:,}-{win['end']:,}"verdict = ("PAYLOAD" if r["pred_injected"] else "clean") + ("" if r["parse_ok"] else " (unreadable answer)")rows.append([offset + i + 1, where, win["source"], ", ".join(win["families"]) or "-",verdict, r["pred_family"], (r["evidence"] or "-")[:160]])log.append(f"--- region {offset + i + 1} ({where}, prompt via {r['prompt_route']}) ---\n"f"{r['raw']}")report = build_report(results, idx, groups, len(candidates))nb_rows = []if want_neighbours and results:progress(0.95, desc="embedding and looking up the corpus")flagged = next((w for w, r in results if r["pred_injected"]), None)query = flagged or batch[0]try:neighbours.check_provenance()nb_rows = neighbours.neighbour_rows(query["text"], k=5)basis = ("the first flagged region" if flagged else"the first region in this batch (nothing was flagged)")report += (f"\n\n### Nearest files in the corpus\n\nEmbedded from **{basis}** with "f"Part A's winning configuration. Precision@5 on this index is **35.6%** "f"against a 6.8% random baseline: fewer than 2 of the 5 listed are the same "f"kind of attack. Read it as *resemblance*, not identification.")except Exception as e:report += (f"\n\n### Nearest files in the corpus\n\nUnavailable: "f"`{type(e).__name__}: {e}`")log.append(traceback.format_exc())return report, rows, nb_rows, "\n\n".join(log)def build_report(results, idx, groups, n_candidates) -> str:"""The verdict for this batch, and an explicit account of what is still unread."""if not results:return "Nothing was read."hits = [(w, r) for w, r in results if r["pred_injected"]]unparsed = sum(1 for _, r in results if not r["parse_ok"])read = len(results)unread = n_candidates - readothers = [i for i in range(len(groups)) if i != idx]if hits:fams = sorted({r["pred_family"] for _, r in hits if r["pred_family"] != "none"})head = (f"## Payload found in batch {idx + 1}\n\nMiMo flagged **{len(hits)} of the {read} "f"region(s)** in this batch.")head += (f" It named the family as **{', '.join(fams)}** β correct 43% of the time in "f"Part B, so treat it as a suggestion." if famselse " It did not commit to a family.")else:head = (f"## Nothing found in batch {idx + 1}\n\nMiMo read **{read} region(s)** in this "f"batch and flagged none of them.")caveats = []if unread > 0:caveats.append(f"**This is 1 of {len(groups)} batches.** {unread} region(s) across "f"{len(others)} other batch(es) have not been read. Whatever this batch says, it says "f"it about {read} of the file's {n_candidates} candidate regions β nothing more.")if unparsed:sweep_bad = sum(1 for w, r in results if not r["parse_ok"] and w["source"] == "sweep")note = (f"{unparsed} answer(s) could not be parsed and count as *not injected*, exactly as "f"Part B scored them (155 of 1,100 there).")if sweep_bad:note += (f" **{sweep_bad} of those were sweep regions**, and that is expected rather than "f"surprising: Part B only ever showed MiMo marker-centred windows or the head of a "f"document, never arbitrary mid-file content streams. Given a page of font "f"positioning operators it tends to carry on copying the input instead of "f"answering. Sweep regions buy coverage of text that would otherwise never be "f"looked at; they do not inherit Part B's accuracy, and a *clean* verdict on one "f"is close to no evidence at all.")caveats.append(note)body = headif caveats:body += "\n\n" + "\n\n".join("- " + c for c in caveats)body += (f"\n\n---\n\n**On the corpus Part B measured**, MiMo scored F1 {PART_B['f1']}, "f"precision {PART_B['precision']}, recall {PART_B['recall']} on {PART_B['n']:,} "f"documents that were 82% injected β where a detector that flags everything without "f"reading it scores F1 0.900. Read 0.945 against 0.900, not against zero.\n\n"f"_Runtime: **{mimo.BACKEND}**. {mimo.RUNTIME_CAVEAT}_")return bodyINTRO = f"""# PDF Injection Detector β MiMo-7BUpload a PDF. It is rendered to text with the extractor that built the project corpus, the regionscarrying structural markers are ranked and cut into **batches that fit one run of the model**, and**MiMo-7B-RL** reads the batch you choose β reporting whether a payload is hidden there, and thesubstring that convinced it.Batching is what keeps a long document inside the runtime's limit: one batch is one run, and youdecide how many runs to spend. The report always states how much of the file is still unread.This is a coursework artefact built on a synthetic corpus of 1,100 PDFs carrying harmlessEICAR/AMTSO/WICAR/RANSIM test markers. **It is not a general malware scanner**, and real malwaredoes not announce itself the way these samples do.Running on the **{mimo.BACKEND.upper()}** runtime({'4-bit NF4 β Part Bβs own configuration' if GPU else 'Q4_K_M GGUF via llama.cpp'}),about {mimo.SECONDS_PER_WINDOW:g}s per region."""with gr.Blocks(title="PDF Injection Detector") as demo:gr.Markdown(INTRO)state = gr.State()with gr.Row():with gr.Column(scale=1):pdf = gr.File(label="PDF", file_types=[".pdf"], type="filepath")per_batch = gr.Slider(1, MAX_PER_BATCH, value=DEFAULT_PER_BATCH, step=1,label="Regions per batch",info=f"One batch is one run of the model. The "f"{mimo.BACKEND.upper()} runtime tops out at "f"{MAX_PER_BATCH}.")# allow_custom_value: the choices are empty until a PDF is uploaded, and without this# Gradio validates any incoming value against that empty list and rejects it - which# makes the batch un-selectable over the API even though the UI had populated it.# `resolve_batch` below is what actually decides the index, from the file itself.batch_pick = gr.Dropdown(label="Batch to check", choices=[], interactive=False,allow_custom_value=True,info="Each batch is a separate run β spend as many as you ""like.")sweep = gr.Checkbox(value=True, label="Sweep the rest of the document too",info="Off = marker regions only, which is the shape Part B measured. On = the ""batches cover the whole file, at the cost of regions MiMo often will not ""answer about.")want_nb = gr.Checkbox(value=True, label="Also show the nearest files in the corpus",info="Adds a one-off 550 MB embedding-model download.")go = gr.Button("Check this batch", variant="primary")plan = gr.Markdown("Upload a PDF to see what will be read.")with gr.Column(scale=2):with gr.Tab("Report"):report = gr.Markdown()with gr.Tab("Regions read"):window_table = gr.Dataframe(headers=WINDOW_COLUMNS, wrap=True, interactive=False)with gr.Tab("Nearest corpus files"):nb_table = gr.Dataframe(headers=neighbours.NEIGHBOUR_COLUMNS, interactive=False)with gr.Tab("What MiMo actually said"):# No `show_copy_button`: gradio 6 removed it, and this Space should survive an# sdk_version bump rather than crash at startup on a cosmetic argument.raw = gr.Textbox(lines=22, interactive=False,label="The prompt route and untouched generation per region")for ev in (pdf.change, per_batch.change):ev(on_upload, [pdf, per_batch, sweep], [state, plan, batch_pick])sweep.change(on_upload, [pdf, per_batch, sweep], [state, plan, batch_pick])go.click(run, [pdf, per_batch, batch_pick, want_nb, sweep],[report, window_table, nb_table, raw])if __name__ == "__main__":demo.queue(max_size=8).launch()
README.md+20-4
app.py+329-306