batch the whole document into runnable chunks; user picks which batch to scan
Browse filesFiles changed (3)
- app.py+136-73
- corpus_text.py+44-3
- test_fidelity.py+1-1
1234567891011128 unmodified lines212223242526272829303132333435363738394041424344454647484950515253541 unmodified line56575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261276 unmodified lines13413513613713813914014114214314414514614714814915015115215315415515615715815916016116216313 unmodified lines1771781791801811821831841851861871881891901915 unmodified lines1971981992002012022032042052062074 unmodified lines212213214215216217218219220221222223"""PDF Injection Detector - MiMo-7B.Upload a PDF, and this reads it the way the corpus was read, picks the parts most worth looking at,and asks MiMo-7B-RL whether a payload is hidden in them.`app.py` holds the interface and the aggregation. It contains no detection logic of its own: thetext extraction lives in `corpus_text.py`, the prompt and parser in `mimo.py`, the embedding lookupin `neighbours.py`, and each of those is quoted from the notebook that measured it."""import traceback8 unmodified linesPART_B = {"f1": 0.945, "precision": 0.988, "recall": 0.906, "family_acc": 0.433,"false_alarm_rate": 0.05, "unparsable": 155, "n": 1100}# How many regions are worth offering depends entirely on what is underneath. On a GPU a window# costs about four seconds and most documents can be read whole; on 2 vCPUs it costs two minutes# and the honest offer is "a few".GPU = mimo.BACKEND == "gpu"# The GPU ceiling is not a taste decision: ZeroGPU caps one grant at 300s, so the whole scan plus# the 4-bit load has to fit inside `mimo.GPU_DURATION`.MAX_WINDOWS, DEFAULT_WINDOWS = (mimo.MAX_WINDOWS_GPU, 8) if GPU else (6, 3)WINDOW_COLUMNS = ["#", "where in the skeleton", "markers", "verdict", "family", "evidence"]def fmt_eta(n_windows: int) -> str:seconds = n_windows * mimo.SECONDS_PER_WINDOWif seconds < 90:return f"about {max(20, int(seconds))} seconds, plus loading"return f"{seconds * 0.6 / 60:.0f}-{seconds * 1.5 / 60:.0f} minutes"def triage(path):"""Extract and rank, without loading any model. Runs in under a second, so it runs on upload."""if not path:return None, "Upload a PDF to see what will be read."with open(path, "rb") as fh:data = fh.read()skeleton, truncated, dropped = corpus_text.build_skeleton(data)candidates = corpus_text.candidate_windows(skeleton)families = corpus_text.detect_markers(data)lines = [f"**{len(data):,} bytes** on disk, rendered to a **{len(skeleton):,}-character skeleton**"1 unmodified lineif truncated else "")+ (f", {dropped} binary stream(s) dropped." if dropped else "."),]if candidates[0]["is_head"]:lines.append("**No structural marker found anywhere in the file.** The head of the document will be ""read instead — which is exactly what a *clean* file in the corpus looks like. Note ""that the triage only recognises the twelve families this project generated, so a ""payload shaped like none of them lands here too.")else:lines.append(f"**{len(candidates)} candidate region(s)** carry a marker. "f"Structural signatures present in the raw file: `{'`, `'.join(families) or 'none'}`.")lines.append("_Those signatures decide **reading order only**. The verdict is MiMo's alone — the ""regex has been wrong about a file before and will be again._")return (skeleton, candidates), "\n\n".join(lines)def on_upload(path, n_windows):state, summary = triage(path)if state is None:return state, summaryn = min(int(n_windows), len(state[1]))return state, summary + (f"\n\nMiMo will read **{n} of {len(state[1])}** region(s): {fmt_eta(n)} on the "f"**{mimo.BACKEND.upper()}** runtime, plus a one-off model download the first time.")def run(path, n_windows, want_neighbours, progress=gr.Progress()):"""Score the top windows and build the report."""if not path:return "Upload a PDF first.", [], [], ""progress(0.05, desc="reading the PDF")state, _ = triage(path)_, candidates = statechosen = candidates[:int(n_windows)]progress(0.15, desc=f"loading MiMo ({mimo.BACKEND})")log = []try:answers = mimo.judge_all([w["text"] for w in chosen],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()rows, results = [], list(zip(chosen, 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([i + 1, where, ", ".join(win["families"]) or "-", verdict,r["pred_family"], (r["evidence"] or "-")[:160]])log.append(f"--- region {i + 1} ({where}, prompt via {r['prompt_route']}) ---\n{r['raw']}")report = build_report(chosen, candidates, results)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 chosen[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 read (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 "6 unmodified linesreturn report, rows, nb_rows, "\n\n".join(log)def build_report(chosen, candidates, results) -> str:"""The document-level report. One verdict from several window verdicts, and the arithmetic."""if not results:return "Nothing was read."hits = [(w, r) for w, r in results if r["pred_injected"]]unread = len(candidates) - len(chosen)unparsed = sum(1 for _, r in results if not r["parse_ok"])if hits:fams = sorted({r["pred_family"] for _, r in hits if r["pred_family"] != "none"})head = (f"## Payload found\n\nMiMo flagged **{len(hits)} of the {len(results)} region(s) "f"it read**.")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\n\nMiMo read **{len(results)} region(s)** and flagged none of "f"them.")caveats = []if unread > 0:caveats.append(f"**{unread} marked region(s) were not read.** Raise the slider to read "f"more — until then, 'clean' means 'clean in what was read'.")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).")13 unmodified lines# 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 **MiMo-7B-RL** reads the most promising ones and sayswhether a payload is hidden there — with the substring that convinced it.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."""5 unmodified lineswith gr.Row():with gr.Column(scale=1):pdf = gr.File(label="PDF", file_types=[".pdf"], type="filepath")n_windows = gr.Slider(1, MAX_WINDOWS, value=DEFAULT_WINDOWS, step=1,label="Regions for MiMo to read")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 PDF", variant="primary")plan = gr.Markdown("Upload a PDF to see what will be read.")with gr.Column(scale=2):4 unmodified lineswith gr.Tab("Nearest corpus files"):nb_table = gr.Dataframe(headers=neighbours.NEIGHBOUR_COLUMNS, interactive=False)with gr.Tab("What MiMo actually said"):raw = gr.Textbox(lines=22, show_copy_button=True, interactive=False,label="The prompt route and untouched generation per region")for ev in (pdf.change, n_windows.change):ev(on_upload, [pdf, n_windows], [state, plan])go.click(run, [pdf, n_windows, want_nb], [report, window_table, nb_table, raw])if __name__ == "__main__":demo.queue(max_size=8).launch()1234567891011128 unmodified lines2122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788891 unmodified line9192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721736 unmodified lines18018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221313 unmodified lines2272282292302312322332342352362372382392402412422432442455 unmodified lines2512522532542552562572582592602612622632642652662674 unmodified lines272273274275276277278279280281282283284285286"""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 traceback8 unmodified linesPART_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**"1 unmodified lineif 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 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 = int(batch_index or 0)if idx >= len(groups):idx = 0batch = 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 "6 unmodified linesreturn 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).")13 unmodified lines# 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."""5 unmodified lineswith 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}.")batch_pick = gr.Dropdown(label="Batch to check", choices=[], interactive=False,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):4 unmodified lineswith 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()
179 unmodified lines18018118218318418518611 unmodified lines19819920020120220320414 unmodified lines219220221222223224225226179 unmodified linesMAX_MATCH_SCAN = 4_000 # matches considered; a pathological file will not run foreverdef candidate_windows(skeleton: str, half: int = WINDOW) -> list:"""Every +/-`half` neighbourhood around a marker in `skeleton`, merged and ranked.11 unmodified linesif not spans:head = skeleton[:2 * half]return [{"start": 0, "end": len(head), "text": head, "n_markers": 0,"families": [], "is_head": True}]# Merge overlaps so two markers 200 characters apart are read once, not twice.merged = []14 unmodified linestext = skeleton[start:start + 2 * half]out.append({"start": start, "end": start + len(text), "text": text,"n_markers": len(span["hits"]),"families": detect_markers(text), "is_head": False})# Density first, then position: an early hit is where the head-insertion strategy puts things.out.sort(key=lambda w: (-len(w["families"]), -w["n_markers"], w["start"]))return out179 unmodified lines18018118218318418518611 unmodified lines19819920020120220320414 unmodified lines219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267179 unmodified linesMAX_MATCH_SCAN = 4_000 # matches considered; a pathological file will not run foreverdef marker_windows(skeleton: str, half: int = WINDOW) -> list:"""Every +/-`half` neighbourhood around a marker in `skeleton`, merged and ranked.11 unmodified linesif not spans:head = skeleton[:2 * half]return [{"start": 0, "end": len(head), "text": head, "n_markers": 0,"families": [], "is_head": True, "source": "head"}]# Merge overlaps so two markers 200 characters apart are read once, not twice.merged = []14 unmodified linestext = skeleton[start:start + 2 * half]out.append({"start": start, "end": start + len(text), "text": text,"n_markers": len(span["hits"]),"families": detect_markers(text), "is_head": False, "source": "marker"})# Density first, then position: an early hit is where the head-insertion strategy puts things.out.sort(key=lambda w: (-len(w["families"]), -w["n_markers"], w["start"]))return outdef candidate_windows(skeleton: str, half: int = WINDOW, cover_all: bool = True) -> list:"""Every region of the document worth sending to the model, in reading order.Marker neighbourhoods come first, ranked by density - they are the likeliest place to findsomething and the first batch should be the one worth spending. **Then the rest of thedocument follows**, tiled into windows of the same size, in document order.That tail is not padding. The marker alternation only knows the twelve families this projectgenerated, so a payload shaped like none of them produces no marker at all and, without thesweep, would sit in a part of the file the model never saw while the report said "clean". Withit, the batches cover the whole skeleton and "unread" means genuinely unread rather thanunreachable.`cover_all=False` gives the marker regions alone, which is what the corpus itself was builtfrom and what `test_fidelity.py` checks against."""windows = marker_windows(skeleton, half)if not cover_all:return windowssize = 2 * halfcovered = [(w["start"], w["end"]) for w in windows]sweep = []for start in range(0, max(len(skeleton), 1), size):text = skeleton[start:start + size]if not text.strip():continue# Skip a tile that a marker window already mostly covers, so the same text is not paid for# twice. Half the tile is the threshold: less than that and there is unseen text in it.overlap = sum(max(0, min(start + size, e) - max(start, s)) for s, e in covered)if overlap >= len(text) / 2:continuesweep.append({"start": start, "end": start + len(text), "text": text, "n_markers": 0,"families": detect_markers(text), "is_head": start == 0,"source": "sweep"})return windows + sweep
51 unmodified lines5253545556575851 unmodified lines# The single-window path must also be what the triage returns first for a marked file,# or the model reads a different string here than the corpus was scored on.top = corpus_text.candidate_windows(skeleton)[0]bad = [k for k, (got, want) in checks.items() if got != want]if bad:51 unmodified lines5253545556575851 unmodified lines# The single-window path must also be what the triage returns first for a marked file,# or the model reads a different string here than the corpus was scored on.top = corpus_text.candidate_windows(skeleton, cover_all=False)[0]bad = [k for k, (got, want) in checks.items() if got != want]if bad:
app.py+136-73
corpus_text.py+44-3
test_fidelity.py+1-1