modelbom 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
modelbom/code_rules.py ADDED
@@ -0,0 +1,642 @@
1
+ """Source-code rules (MB1xx) for Python files and Jupyter notebooks, implemented with :mod:`ast`.
2
+
3
+ The analysis is intra-file and literal-based: calls are matched by their resolved dotted name
4
+ (``import torch as t`` makes ``t.load`` resolve to ``torch.load``), and hub repository IDs or URLs
5
+ are only recognized when written as string literals.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import ast
11
+ import json
12
+ import re
13
+ import warnings
14
+ from dataclasses import dataclass, field
15
+ from pathlib import Path
16
+ from typing import Any
17
+
18
+ from .artifacts import ARTIFACT_EXTS
19
+ from .models import CodeFile, Finding, LoadSite, ModelRef, Severity
20
+
21
+ MAX_SOURCE_BYTES = 4 * 1024 * 1024
22
+
23
+ _SUPPRESS = re.compile(r"#\s*modelbom:\s*ignore(?:\[([A-Za-z0-9_,\s]+)\])?", re.IGNORECASE)
24
+ _HUB_ID = re.compile(r"^(?:[A-Za-z0-9][\w.\-]*/)?[A-Za-z0-9][\w.\-]*$")
25
+ _COMMIT = re.compile(r"^[0-9a-f]{40}$")
26
+ _URL = re.compile(r"^https?://", re.IGNORECASE)
27
+ _LOCAL_HINTS = ("checkpoint", "output", "model", "saved", "tmp", "cache", "local", "data")
28
+
29
+ _DATASET_BUILDERS = frozenset(
30
+ {
31
+ "csv",
32
+ "json",
33
+ "parquet",
34
+ "text",
35
+ "arrow",
36
+ "pandas",
37
+ "imagefolder",
38
+ "audiofolder",
39
+ "videofolder",
40
+ "webdataset",
41
+ "xml",
42
+ "sql",
43
+ "generator",
44
+ "spark",
45
+ }
46
+ )
47
+ _UNSAFE_DESER = frozenset(
48
+ {
49
+ "pickle.load",
50
+ "pickle.loads",
51
+ "pickle.Unpickler",
52
+ "_pickle.load",
53
+ "_pickle.loads",
54
+ "cPickle.load",
55
+ "cPickle.loads",
56
+ "dill.load",
57
+ "dill.loads",
58
+ "cloudpickle.load",
59
+ "cloudpickle.loads",
60
+ "joblib.load",
61
+ "sklearn.externals.joblib.load",
62
+ "pandas.read_pickle",
63
+ "shelve.open",
64
+ "jsonpickle.decode",
65
+ }
66
+ )
67
+ _TORCH_LOAD = frozenset({"torch.load", "torch.serialization.load"})
68
+ _DOWNLOADS = frozenset(
69
+ {
70
+ "urllib.request.urlretrieve",
71
+ "urllib.request.urlopen",
72
+ "urllib.urlretrieve",
73
+ "requests.get",
74
+ "httpx.get",
75
+ "wget.download",
76
+ }
77
+ )
78
+ _LC_HF_EMBEDDINGS = frozenset(
79
+ {"HuggingFaceEmbeddings", "HuggingFaceBgeEmbeddings", "HuggingFaceInstructEmbeddings"}
80
+ )
81
+ _LOAD_TAILS = frozenset(
82
+ {"load", "loads", "load_model", "read_pickle", "load_file", "load_local", "from_pretrained", "Unpickler"}
83
+ )
84
+
85
+
86
+ @dataclass
87
+ class CodeScan:
88
+ """Output of scanning one file."""
89
+
90
+ code_file: CodeFile
91
+ findings: list[Finding] = field(default_factory=list)
92
+ model_refs: list[ModelRef] = field(default_factory=list)
93
+
94
+
95
+ @dataclass
96
+ class _Ctx:
97
+ rel: str
98
+ root: Path
99
+ file_dir: Path
100
+ lines: list[str]
101
+ aliases: dict[str, str]
102
+ scan: CodeScan
103
+ cell: int | None = None
104
+
105
+ def location(self, node: ast.AST) -> dict[str, Any]:
106
+ line = getattr(node, "lineno", None)
107
+ if self.cell is None:
108
+ return {"line": line}
109
+ return {"line": None, "cell": self.cell, "cell_line": line}
110
+
111
+ def snippet(self, node: ast.AST) -> str:
112
+ start = getattr(node, "lineno", 1) - 1
113
+ end = getattr(node, "end_lineno", start + 1)
114
+ text = " ".join(x.strip() for x in self.lines[start:end])
115
+ return text[:200]
116
+
117
+ def suppressed(self, node: ast.AST, rule_id: str) -> bool:
118
+ start = getattr(node, "lineno", 1) - 1
119
+ end = getattr(node, "end_lineno", start + 1)
120
+ for text in self.lines[start:end]:
121
+ m = _SUPPRESS.search(text)
122
+ if not m:
123
+ continue
124
+ if m.group(1) is None:
125
+ return True
126
+ ids = {x.strip().upper() for x in m.group(1).split(",")}
127
+ if rule_id.upper() in ids:
128
+ return True
129
+ return False
130
+
131
+ def add(self, rule_id: str, sev: Severity, node: ast.AST, message: str, **details: Any) -> Finding:
132
+ loc = self.location(node)
133
+ extra = {k: v for k, v in loc.items() if k != "line"}
134
+ extra.update({k: v for k, v in details.items() if v is not None})
135
+ finding = Finding(
136
+ rule_id=rule_id,
137
+ severity=sev,
138
+ path=self.rel,
139
+ message=message,
140
+ line=loc["line"],
141
+ snippet=self.snippet(node),
142
+ details=extra,
143
+ suppressed=self.suppressed(node, rule_id),
144
+ )
145
+ self.scan.findings.append(finding)
146
+ return finding
147
+
148
+
149
+ # --- helpers ---------------------------------------------------------------------------------
150
+
151
+
152
+ def collect_aliases(trees: list[ast.AST]) -> tuple[dict[str, str], set[str]]:
153
+ aliases: dict[str, str] = {}
154
+ imports: set[str] = set()
155
+ for tree in trees:
156
+ for node in ast.walk(tree):
157
+ if isinstance(node, ast.Import):
158
+ for a in node.names:
159
+ imports.add(a.name.split(".", 1)[0])
160
+ if a.asname:
161
+ aliases[a.asname] = a.name
162
+ else:
163
+ top = a.name.split(".", 1)[0]
164
+ aliases.setdefault(top, top)
165
+ elif isinstance(node, ast.ImportFrom) and node.module and node.level == 0:
166
+ imports.add(node.module.split(".", 1)[0])
167
+ for a in node.names:
168
+ if a.name != "*":
169
+ aliases[a.asname or a.name] = f"{node.module}.{a.name}"
170
+ return aliases, imports
171
+
172
+
173
+ def dotted_name(node: ast.AST, aliases: dict[str, str]) -> str | None:
174
+ parts: list[str] = []
175
+ while isinstance(node, ast.Attribute):
176
+ parts.append(node.attr)
177
+ node = node.value
178
+ if isinstance(node, ast.Name):
179
+ parts.append(aliases.get(node.id, node.id))
180
+ elif isinstance(node, ast.Call):
181
+ inner = dotted_name(node.func, aliases)
182
+ if inner is None:
183
+ return None
184
+ parts.append(inner + "()")
185
+ else:
186
+ return None
187
+ parts.reverse()
188
+ return ".".join(parts)
189
+
190
+
191
+ def _kw(call: ast.Call, name: str) -> ast.expr | None:
192
+ for k in call.keywords:
193
+ if k.arg == name:
194
+ return k.value
195
+ return None
196
+
197
+
198
+ def _const(node: ast.expr | None) -> Any:
199
+ if isinstance(node, ast.Constant):
200
+ return node.value
201
+ return _MISSING if node is None else _DYNAMIC
202
+
203
+
204
+ class _Sentinel:
205
+ def __init__(self, name: str) -> None:
206
+ self.name = name
207
+
208
+ def __repr__(self) -> str:
209
+ return self.name
210
+
211
+
212
+ _MISSING = _Sentinel("<missing>")
213
+ _DYNAMIC = _Sentinel("<dynamic>")
214
+
215
+
216
+ def _arg(call: ast.Call, index: int, *names: str) -> ast.expr | None:
217
+ for n in names:
218
+ v = _kw(call, n)
219
+ if v is not None:
220
+ return v
221
+ if len(call.args) > index and not isinstance(call.args[index], ast.Starred):
222
+ return call.args[index]
223
+ return None
224
+
225
+
226
+ def _is_true(node: ast.expr | None) -> bool:
227
+ return isinstance(node, ast.Constant) and node.value is True
228
+
229
+
230
+ def _is_false(node: ast.expr | None) -> bool:
231
+ return isinstance(node, ast.Constant) and node.value is False
232
+
233
+
234
+ def _tail(name: str) -> str:
235
+ return name.rsplit(".", 1)[-1]
236
+
237
+
238
+ def _url_has_artifact_ext(url: str) -> bool:
239
+ path = re.split(r"[?#]", url, maxsplit=1)[0].lower()
240
+ return any(path.endswith(ext) for ext in ARTIFACT_EXTS)
241
+
242
+
243
+ def _looks_like_hub_id(ctx: _Ctx, value: str, allow_bare: bool) -> bool:
244
+ if not _HUB_ID.match(value) or value.startswith(".") or value.count("/") > 1:
245
+ return False
246
+ lower = value.lower()
247
+ if any(lower.endswith(ext) for ext in ARTIFACT_EXTS | {".json", ".txt", ".yaml", ".yml"}):
248
+ return False
249
+ if (ctx.file_dir / value).exists() or (ctx.root / value).exists():
250
+ return False
251
+ if "/" not in value:
252
+ if not allow_bare:
253
+ return False
254
+ if not (re.search(r"\d", value) or "-" in value):
255
+ return False
256
+ if lower.startswith(_LOCAL_HINTS):
257
+ return False
258
+ return True
259
+
260
+
261
+ # --- rule implementations ----------------------------------------------------------------------
262
+
263
+
264
+ def _hub_target(name: str, call: ast.Call) -> tuple[ast.expr | None, str, bool] | None:
265
+ """Return (id_node, kind, allow_bare) when ``name`` is a hub-loading call."""
266
+ tail = _tail(name)
267
+ if tail == "from_pretrained":
268
+ return _arg(call, 0, "pretrained_model_name_or_path"), "model", True
269
+ if tail in ("hf_hub_download", "snapshot_download") and (
270
+ name == tail or name.startswith("huggingface_hub")
271
+ ):
272
+ kind = "dataset" if _const(_kw(call, "repo_type")) == "dataset" else "model"
273
+ return _arg(call, 0, "repo_id"), kind, False
274
+ if tail == "load_dataset" and (name == tail or name.startswith("datasets")):
275
+ return _arg(call, 0, "path"), "dataset", True
276
+ if name.startswith("transformers.") and tail == "pipeline":
277
+ return _arg(call, 1, "model"), "model", True
278
+ if tail in ("SentenceTransformer", "CrossEncoder") and (
279
+ name == tail or name.startswith("sentence_transformers")
280
+ ):
281
+ return _arg(call, 0, "model_name_or_path", "model_name"), "model", True
282
+ if tail in _LC_HF_EMBEDDINGS:
283
+ return _kw(call, "model_name"), "model", True
284
+ return None
285
+
286
+
287
+ def _revision_node(call: ast.Call, name: str) -> ast.expr | None:
288
+ """``revision=`` or, for LangChain embeddings, ``model_kwargs={"revision": ...}``."""
289
+ rev = _kw(call, "revision")
290
+ if rev is not None or _tail(name) not in _LC_HF_EMBEDDINGS:
291
+ return rev
292
+ mk = _kw(call, "model_kwargs")
293
+ if isinstance(mk, ast.Dict):
294
+ for k, v in zip(mk.keys, mk.values, strict=False):
295
+ if isinstance(k, ast.Constant) and k.value == "revision":
296
+ return v
297
+ elif mk is not None:
298
+ return mk # dynamic kwargs: cannot decide statically
299
+ return None
300
+
301
+
302
+ def _short(name: str) -> str:
303
+ return ".".join(name.split(".")[-2:])
304
+
305
+
306
+ def _check_hub(ctx: _Ctx, call: ast.Call, name: str) -> None:
307
+ target = _hub_target(name, call)
308
+ if target is None:
309
+ return
310
+ id_node, kind, allow_bare = target
311
+ value = _const(id_node)
312
+ if not isinstance(value, str):
313
+ return
314
+ if kind == "dataset" and value.lower() in _DATASET_BUILDERS:
315
+ return
316
+ if not _looks_like_hub_id(ctx, value, allow_bare):
317
+ return
318
+ rev_node = _revision_node(call, name)
319
+ rev = _const(rev_node)
320
+ revision: str | None
321
+ if rev is _MISSING:
322
+ revision = None
323
+ elif rev is _DYNAMIC:
324
+ revision = "<dynamic>"
325
+ else:
326
+ revision = str(rev)
327
+ ref = ModelRef(
328
+ source="huggingface",
329
+ name=value,
330
+ kind=kind,
331
+ revision=revision,
332
+ path=ctx.rel,
333
+ line=getattr(call, "lineno", None),
334
+ call=name,
335
+ trust_remote_code=_is_true(_kw(call, "trust_remote_code")),
336
+ )
337
+ ctx.scan.model_refs.append(ref)
338
+ what = "dataset" if kind == "dataset" else "model"
339
+ if revision is None:
340
+ ctx.add(
341
+ "MB102",
342
+ Severity.MEDIUM,
343
+ call,
344
+ f"{what} '{value}' loaded via {_tail(name)}() without revision=",
345
+ ref=ref.ref,
346
+ kind=kind,
347
+ hub_id=value,
348
+ )
349
+ elif revision in ("main", "master"):
350
+ ctx.add(
351
+ "MB102",
352
+ Severity.MEDIUM,
353
+ call,
354
+ f"{what} '{value}' pinned to branch '{revision}', which moves",
355
+ ref=ref.ref,
356
+ kind=kind,
357
+ hub_id=value,
358
+ )
359
+ elif revision != "<dynamic>" and not _COMMIT.match(revision):
360
+ ctx.add(
361
+ "MB102",
362
+ Severity.LOW,
363
+ call,
364
+ f"{what} '{value}' pinned to '{revision}', a mutable ref; prefer a commit SHA",
365
+ ref=ref.ref,
366
+ kind=kind,
367
+ hub_id=value,
368
+ )
369
+
370
+
371
+ def _check_torch(ctx: _Ctx, call: ast.Call, name: str) -> None:
372
+ if name in _TORCH_LOAD:
373
+ wo = _kw(call, "weights_only")
374
+ if _is_true(wo):
375
+ return
376
+ if wo is not None and not _is_false(wo):
377
+ return # dynamic value: cannot decide statically
378
+ msg = (
379
+ "torch.load(..., weights_only=False) unpickles arbitrary objects"
380
+ if _is_false(wo)
381
+ else "torch.load() without weights_only=True (the safe default only applies to torch>=2.6)"
382
+ )
383
+ ctx.add("MB103", Severity.HIGH, call, msg)
384
+ return
385
+ if name == "torch.hub.load":
386
+ if _const(_kw(call, "source")) == "local":
387
+ return
388
+ repo = _const(_arg(call, 0, "repo_or_dir"))
389
+ if not isinstance(repo, str):
390
+ return
391
+ repo_name, _, ref = repo.partition(":")
392
+ ctx.scan.model_refs.append(
393
+ ModelRef(
394
+ source="torch-hub",
395
+ name=repo_name,
396
+ kind="model",
397
+ revision=ref or None,
398
+ path=ctx.rel,
399
+ line=getattr(call, "lineno", None),
400
+ call=name,
401
+ )
402
+ )
403
+ hub_ref = f"hub:{repo_name}@{ref or 'unpinned'}"
404
+ if not ref:
405
+ ctx.add(
406
+ "MB108",
407
+ Severity.HIGH,
408
+ call,
409
+ f"torch.hub.load('{repo}') runs hubconf.py from the repository's default branch",
410
+ ref=hub_ref,
411
+ hub_id=repo_name,
412
+ )
413
+ elif not _COMMIT.match(ref):
414
+ ctx.add(
415
+ "MB108",
416
+ Severity.MEDIUM,
417
+ call,
418
+ f"torch.hub.load('{repo}') runs repository code pinned to mutable ref '{ref}'",
419
+ ref=hub_ref,
420
+ hub_id=repo_name,
421
+ )
422
+ return
423
+ if name == "torch.hub.download_url_to_file":
424
+ hp = _arg(call, 2, "hash_prefix")
425
+ if hp is None or (isinstance(hp, ast.Constant) and hp.value is None):
426
+ url = _const(_arg(call, 0, "url"))
427
+ shown = url if isinstance(url, str) else "a URL"
428
+ ctx.add("MB107", Severity.MEDIUM, call, f"downloads {shown} without hash_prefix=")
429
+ return
430
+ if name == "torch.hub.load_state_dict_from_url" and not _is_true(_kw(call, "check_hash")):
431
+ url = _const(_arg(call, 0, "url"))
432
+ shown = url if isinstance(url, str) else "a URL"
433
+ ctx.add("MB107", Severity.MEDIUM, call, f"downloads {shown} without check_hash=True")
434
+
435
+
436
+ def _check_deser(ctx: _Ctx, call: ast.Call, name: str) -> None:
437
+ if name in _UNSAFE_DESER:
438
+ ctx.add("MB104", Severity.HIGH, call, f"{name}() deserializes code-carrying data")
439
+ elif name == "numpy.load" and _is_true(_kw(call, "allow_pickle")):
440
+ ctx.add("MB104", Severity.HIGH, call, "numpy.load(..., allow_pickle=True) can unpickle objects")
441
+ elif "keras" in name and _tail(name) == "load_model" and _is_false(_kw(call, "safe_mode")):
442
+ ctx.add("MB105", Severity.HIGH, call, f"{_short(name)}(..., safe_mode=False) allows serialized code")
443
+ elif "keras" in name and _tail(name) == "enable_unsafe_deserialization":
444
+ ctx.add("MB105", Severity.HIGH, call, f"{name}() disables Keras safe mode globally")
445
+
446
+
447
+ def _check_yaml(ctx: _Ctx, call: ast.Call, name: str) -> None:
448
+ if not name.startswith("yaml."):
449
+ return
450
+ tail = _tail(name)
451
+ if tail in ("unsafe_load", "unsafe_load_all"):
452
+ ctx.add("MB106", Severity.MEDIUM, call, f"{name}() constructs arbitrary Python objects")
453
+ elif tail in ("full_load", "full_load_all"):
454
+ ctx.add("MB106", Severity.LOW, call, f"{name}() is broader than needed; use yaml.safe_load")
455
+ elif tail in ("load", "load_all"):
456
+ loader = _arg(call, 1, "Loader")
457
+ loader_name = dotted_name(loader, ctx.aliases) if loader is not None else None
458
+ if loader_name and ("SafeLoader" in loader_name or "BaseLoader" in loader_name):
459
+ return
460
+ if loader_name and "FullLoader" in loader_name:
461
+ ctx.add("MB106", Severity.LOW, call, f"{name}(..., Loader=FullLoader); use yaml.safe_load")
462
+ return
463
+ shown = loader_name or "no Loader"
464
+ ctx.add("MB106", Severity.MEDIUM, call, f"{name}() with {shown}; use yaml.safe_load")
465
+
466
+
467
+ def _check_download(ctx: _Ctx, call: ast.Call, name: str) -> None:
468
+ if name not in _DOWNLOADS:
469
+ return
470
+ url = _const(_arg(call, 0, "url"))
471
+ if isinstance(url, str) and _URL.match(url) and _url_has_artifact_ext(url):
472
+ ctx.add(
473
+ "MB107",
474
+ Severity.MEDIUM,
475
+ call,
476
+ f"{name}('{url}') fetches a model/data file without verifying a checksum",
477
+ url=url,
478
+ )
479
+
480
+
481
+ def _check_keywords(ctx: _Ctx, call: ast.Call, name: str) -> None:
482
+ if _is_true(_kw(call, "trust_remote_code")):
483
+ target = _hub_target(name, call)
484
+ hub_id = _const(target[0]) if target else None
485
+ ref = None
486
+ if isinstance(hub_id, str):
487
+ rev = _const(_kw(call, "revision"))
488
+ rev_s = None if rev is _MISSING else ("<dynamic>" if rev is _DYNAMIC else str(rev))
489
+ kind = target[1] if target else "model"
490
+ prefix = "dataset:" if kind == "dataset" else ""
491
+ ref = f"hf:{prefix}{hub_id}@{rev_s or 'unpinned'}"
492
+ ctx.add(
493
+ "MB101",
494
+ Severity.HIGH,
495
+ call,
496
+ f"trust_remote_code=True in {_short(name)}() executes code shipped with the model",
497
+ ref=ref,
498
+ hub_id=hub_id if isinstance(hub_id, str) else None,
499
+ )
500
+ if _is_true(_kw(call, "allow_dangerous_deserialization")):
501
+ ctx.add(
502
+ "MB109",
503
+ Severity.HIGH,
504
+ call,
505
+ f"allow_dangerous_deserialization=True in {_short(name)}() unpickles the stored index",
506
+ )
507
+ if _is_false(_kw(call, "use_safetensors")):
508
+ ctx.add("MB110", Severity.MEDIUM, call, f"use_safetensors=False in {_short(name)}()")
509
+
510
+
511
+ def _record_load_site(ctx: _Ctx, call: ast.Call, name: str, before: int) -> None:
512
+ tail = _tail(name)
513
+ new_rules = [f.rule_id for f in ctx.scan.findings[before:]]
514
+ is_load = tail in _LOAD_TAILS or name in _DOWNLOADS or bool(new_rules)
515
+ if not is_load:
516
+ return
517
+ literals = [
518
+ a.value
519
+ for a in list(call.args) + [k.value for k in call.keywords]
520
+ if isinstance(a, ast.Constant) and isinstance(a.value, str)
521
+ ]
522
+ rule_id = next((r for r in new_rules if r in ("MB103", "MB104", "MB105", "MB107", "MB109")), None)
523
+ ctx.scan.code_file.load_sites.append(
524
+ LoadSite(
525
+ path=ctx.rel,
526
+ line=getattr(call, "lineno", None),
527
+ call=name,
528
+ rule_id=rule_id,
529
+ literals=literals,
530
+ )
531
+ )
532
+
533
+
534
+ def _scan_tree(ctx: _Ctx, tree: ast.AST) -> None:
535
+ for node in ast.walk(tree):
536
+ if isinstance(node, ast.Constant) and isinstance(node.value, str) and len(node.value) < 512:
537
+ line = getattr(node, "lineno", None)
538
+ ctx.scan.code_file.literals.append((node.value, line if ctx.cell is None else None))
539
+ if not isinstance(node, ast.Call):
540
+ continue
541
+ name = dotted_name(node.func, ctx.aliases) or ""
542
+ before = len(ctx.scan.findings)
543
+ _check_keywords(ctx, node, name)
544
+ _check_hub(ctx, node, name)
545
+ _check_torch(ctx, node, name)
546
+ _check_deser(ctx, node, name)
547
+ _check_yaml(ctx, node, name)
548
+ _check_download(ctx, node, name)
549
+ _record_load_site(ctx, node, name, before)
550
+
551
+
552
+ # --- entry points ----------------------------------------------------------------------------
553
+
554
+
555
+ def _parse_failure(rel: str, message: str) -> CodeScan:
556
+ scan = CodeScan(CodeFile(rel))
557
+ scan.findings.append(Finding("MB100", Severity.INFO, rel, message))
558
+ return scan
559
+
560
+
561
+ def _parse(source: str, filename: str = "<unknown>") -> ast.AST:
562
+ """Parse scanned code without letting its own SyntaxWarnings reach our stderr."""
563
+ with warnings.catch_warnings():
564
+ warnings.simplefilter("ignore")
565
+ return ast.parse(source, filename=filename)
566
+
567
+
568
+ def scan_python_source(source: str, rel: str, root: Path, file_dir: Path) -> CodeScan:
569
+ try:
570
+ tree = _parse(source, rel)
571
+ except (SyntaxError, ValueError) as exc:
572
+ return _parse_failure(rel, f"could not parse: {exc}")
573
+ aliases, imports = collect_aliases([tree])
574
+ scan = CodeScan(CodeFile(rel, imports=imports))
575
+ ctx = _Ctx(rel, root, file_dir, source.splitlines(), aliases, scan)
576
+ _scan_tree(ctx, tree)
577
+ return scan
578
+
579
+
580
+ def scan_python_file(path: Path, rel: str, root: Path) -> CodeScan:
581
+ if path.stat().st_size > MAX_SOURCE_BYTES:
582
+ return _parse_failure(rel, f"skipped: larger than {MAX_SOURCE_BYTES} bytes")
583
+ source = path.read_text(encoding="utf-8", errors="replace")
584
+ return scan_python_source(source, rel, root, path.parent)
585
+
586
+
587
+ def _clean_cell(source: str) -> str:
588
+ """Neutralise IPython magics and shell escapes so the cell parses as Python.
589
+
590
+ Each such line becomes ``pass`` at the same indentation, which keeps line numbers and
591
+ keeps indented blocks non-empty.
592
+ """
593
+ lines = source.splitlines()
594
+ if lines and lines[0].lstrip().startswith("%%"):
595
+ return ""
596
+ out = []
597
+ continuing = False # inside a magic/shell line continued with a trailing backslash
598
+ indent = ""
599
+ for ln in lines:
600
+ stripped = ln.lstrip()
601
+ if continuing:
602
+ out.append("")
603
+ elif stripped.startswith(("%", "!")) or (stripped.endswith("?") and " " not in stripped):
604
+ indent = ln[: len(ln) - len(stripped)]
605
+ out.append(indent + "pass")
606
+ else:
607
+ out.append(ln)
608
+ continue
609
+ continuing = ln.rstrip().endswith("\\")
610
+ return "\n".join(out)
611
+
612
+
613
+ def scan_notebook_file(path: Path, rel: str, root: Path) -> CodeScan:
614
+ if path.stat().st_size > MAX_SOURCE_BYTES * 4:
615
+ return _parse_failure(rel, "skipped: notebook too large")
616
+ try:
617
+ nb = json.loads(path.read_text(encoding="utf-8", errors="replace"))
618
+ except json.JSONDecodeError as exc:
619
+ return _parse_failure(rel, f"invalid notebook JSON: {exc}")
620
+ cells = nb.get("cells", []) if isinstance(nb, dict) else []
621
+ parsed: list[tuple[int, str, ast.AST]] = []
622
+ errors: list[str] = []
623
+ for index, cell in enumerate(cells, start=1):
624
+ if not isinstance(cell, dict) or cell.get("cell_type") != "code":
625
+ continue
626
+ src = cell.get("source", "")
627
+ src = "".join(src) if isinstance(src, list) else str(src)
628
+ src = _clean_cell(src)
629
+ try:
630
+ parsed.append((index, src, _parse(src, rel)))
631
+ except (SyntaxError, ValueError) as exc:
632
+ errors.append(f"cell {index}: {exc.__class__.__name__}")
633
+ aliases, imports = collect_aliases([t for _, _, t in parsed])
634
+ scan = CodeScan(CodeFile(rel, imports=imports))
635
+ for index, src, tree in parsed:
636
+ ctx = _Ctx(rel, root, path.parent, src.splitlines(), aliases, scan, cell=index)
637
+ _scan_tree(ctx, tree)
638
+ if errors:
639
+ scan.findings.append(
640
+ Finding("MB100", Severity.INFO, rel, "could not parse " + ", ".join(errors[:5]))
641
+ )
642
+ return scan