nbdevAuto 0.3.76__tar.gz → 0.3.78__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: nbdevAuto
3
- Version: 0.3.76
3
+ Version: 0.3.78
4
4
  Summary: automating nbdev
5
5
  Author-email: Benedict Thekkel <bthekkel1@gmail.com>
6
6
  License-Expression: Apache-2.0
@@ -0,0 +1 @@
1
+ __version__ = "0.3.78"
@@ -47,7 +47,9 @@ d = { 'settings': { 'branch': 'main',
47
47
  'nbdevAuto.fleet._hits': ('fleet.html#_hits', 'nbdevAuto/fleet.py'),
48
48
  'nbdevAuto.fleet._line_of': ('fleet.html#_line_of', 'nbdevAuto/fleet.py'),
49
49
  'nbdevAuto.fleet._porcelain': ('fleet.html#_porcelain', 'nbdevAuto/fleet.py'),
50
+ 'nbdevAuto.fleet._public_notebooks': ('fleet.html#_public_notebooks', 'nbdevAuto/fleet.py'),
50
51
  'nbdevAuto.fleet._render': ('fleet.html#_render', 'nbdevAuto/fleet.py'),
52
+ 'nbdevAuto.fleet._src': ('fleet.html#_src', 'nbdevAuto/fleet.py'),
51
53
  'nbdevAuto.fleet.ahead_of_remote': ('fleet.html#ahead_of_remote', 'nbdevAuto/fleet.py'),
52
54
  'nbdevAuto.fleet.copy_one': ('fleet.html#copy_one', 'nbdevAuto/fleet.py'),
53
55
  'nbdevAuto.fleet.dirty_submodules': ('fleet.html#dirty_submodules', 'nbdevAuto/fleet.py'),
@@ -55,6 +57,7 @@ d = { 'settings': { 'branch': 'main',
55
57
  'nbdevAuto.fleet.finish': ('fleet.html#finish', 'nbdevAuto/fleet.py'),
56
58
  'nbdevAuto.fleet.fleet': ('fleet.html#fleet', 'nbdevAuto/fleet.py'),
57
59
  'nbdevAuto.fleet.fleet_copy': ('fleet.html#fleet_copy', 'nbdevAuto/fleet.py'),
60
+ 'nbdevAuto.fleet.fleet_nblint': ('fleet.html#fleet_nblint', 'nbdevAuto/fleet.py'),
58
61
  'nbdevAuto.fleet.fleet_push': ('fleet.html#fleet_push', 'nbdevAuto/fleet.py'),
59
62
  'nbdevAuto.fleet.fleet_scan': ('fleet.html#fleet_scan', 'nbdevAuto/fleet.py'),
60
63
  'nbdevAuto.fleet.fleet_status': ('fleet.html#fleet_status', 'nbdevAuto/fleet.py'),
@@ -64,6 +67,9 @@ d = { 'settings': { 'branch': 'main',
64
67
  'nbdevAuto.fleet.format_summary': ('fleet.html#format_summary', 'nbdevAuto/fleet.py'),
65
68
  'nbdevAuto.fleet.init_new': ('fleet.html#init_new', 'nbdevAuto/fleet.py'),
66
69
  'nbdevAuto.fleet.is_published': ('fleet.html#is_published', 'nbdevAuto/fleet.py'),
70
+ 'nbdevAuto.fleet.lint_notebook': ('fleet.html#lint_notebook', 'nbdevAuto/fleet.py'),
71
+ 'nbdevAuto.fleet.lint_one': ('fleet.html#lint_one', 'nbdevAuto/fleet.py'),
72
+ 'nbdevAuto.fleet.lint_totals': ('fleet.html#lint_totals', 'nbdevAuto/fleet.py'),
67
73
  'nbdevAuto.fleet.looks_secret': ('fleet.html#looks_secret', 'nbdevAuto/fleet.py'),
68
74
  'nbdevAuto.fleet.notebook_text': ('fleet.html#notebook_text', 'nbdevAuto/fleet.py'),
69
75
  'nbdevAuto.fleet.parse_verb': ('fleet.html#parse_verb', 'nbdevAuto/fleet.py'),
@@ -74,6 +80,7 @@ d = { 'settings': { 'branch': 'main',
74
80
  'nbdevAuto.fleet.scan_one': ('fleet.html#scan_one', 'nbdevAuto/fleet.py'),
75
81
  'nbdevAuto.fleet.script_path': ('fleet.html#script_path', 'nbdevAuto/fleet.py'),
76
82
  'nbdevAuto.fleet.status_one': ('fleet.html#status_one', 'nbdevAuto/fleet.py'),
83
+ 'nbdevAuto.fleet.unlinked_from_index': ('fleet.html#unlinked_from_index', 'nbdevAuto/fleet.py'),
77
84
  'nbdevAuto.fleet.update_one': ('fleet.html#update_one', 'nbdevAuto/fleet.py'),
78
85
  'nbdevAuto.fleet.upload_one': ('fleet.html#upload_one', 'nbdevAuto/fleet.py'),
79
86
  'nbdevAuto.fleet.usage': ('fleet.html#usage', 'nbdevAuto/fleet.py'),
@@ -6,11 +6,13 @@ Docs: https://bthek1.github.io/nbdevAuto/fleet.html.md"""
6
6
 
7
7
  # %% auto #0
8
8
  __all__ = ['RAW_DOC_SUFFIXES', 'KNOWN_TOKEN', 'SECRET_PATTERNS', 'ALLOW', 'RENDERED_SUFFIXES', 'TEXT_SUFFIXES', 'EMAIL',
9
- 'RESERVED_DOMAINS', 'BULK_EMAIL_MIN', 'VERBS', 'Skip', 'Outcome', 'Report', 'format_summary', 'walk',
10
- 'finish', 'script_path', 'upload_one', 'fleet_upload', 'ahead_of_remote', 'push_one', 'copy_one',
11
- 'fleet_push', 'fleet_copy', 'status_one', 'fleet_status', 'fetch_all', 'update_one', 'dirty_submodules',
12
- 'init_new', 'pull_root', 'fleet_update', 'fleet_sync', 'looks_secret', 'notebook_text', 'is_published',
13
- 'scan_file', 'scan_one', 'fleet_scan', 'parse_verb', 'usage', 'run_verb', 'fleet']
9
+ 'RESERVED_DOMAINS', 'BULK_EMAIL_MIN', 'NB_RULES', 'DLTASK_SECTIONS', 'DLTASK_NOT_TASKS', 'LARGE_NB_BYTES',
10
+ 'SKIP_DIRECTIVES', 'NOT_PUBLISHED', 'VERBS', 'Skip', 'Outcome', 'Report', 'format_summary', 'walk', 'finish',
11
+ 'script_path', 'upload_one', 'fleet_upload', 'ahead_of_remote', 'push_one', 'copy_one', 'fleet_push',
12
+ 'fleet_copy', 'status_one', 'fleet_status', 'fetch_all', 'update_one', 'dirty_submodules', 'init_new',
13
+ 'pull_root', 'fleet_update', 'fleet_sync', 'looks_secret', 'notebook_text', 'is_published', 'scan_file',
14
+ 'scan_one', 'fleet_scan', 'lint_notebook', 'unlinked_from_index', 'lint_one', 'lint_totals', 'fleet_nblint',
15
+ 'parse_verb', 'usage', 'run_verb', 'fleet']
14
16
 
15
17
  # %% ../nbs/04_Fleet.ipynb #d361ee5f-9f09-464f-aec6-0e27cec90fe9
16
18
  import json
@@ -21,6 +23,7 @@ import sys
21
23
  from concurrent.futures import ThreadPoolExecutor
22
24
  from dataclasses import dataclass, field
23
25
  from pathlib import Path
26
+ from urllib.parse import unquote
24
27
 
25
28
  from fastcore.script import *
26
29
 
@@ -575,10 +578,208 @@ def fleet_scan(
575
578
  sys.exit(1 if published or (strict and rep.ran) else 0)
576
579
 
577
580
 
581
+ # %% ../nbs/04_Fleet.ipynb #7a605ea9
582
+ # (key, label, issue #24 phase). The phase is what a count is FOR: each phase of the
583
+ # cleanup drives its own rows to 0, so the table doubles as the plan's progress bar.
584
+ NB_RULES = [
585
+ ("mermaid_plain", "Plain ```mermaid fence (raw source on the site)", 1),
586
+ ("title_leading_rule","Title cell starts with --- (breaks nbdev-test)", 1),
587
+ ("title_no_h1", "Title cell has no # H1", 1),
588
+ ("title_bad_directive","Misspelled skip directive (nbdev ignores it)", 1),
589
+ ("index_unlinked", "Public notebook missing from index.ipynb", 1),
590
+ ("mermaid_braced", "Braced {mermaid} not yet an .svg file", 2),
591
+ ("svg_in_index", "Inline <svg> in index.ipynb (README strips it)", 2),
592
+ ("title_code", "Title cell is a code cell", 3),
593
+ ("title_no_desc", "Title cell has no > description", 3),
594
+ ("no_skip_showdoc", "Concept notebook without skip_showdoc", 3),
595
+ ("non_ascii", "Non-ASCII characters in code cells", 4),
596
+ ("naive_datetime", "Naive now() or utcnow(), no timezone", 4),
597
+ ("bad_filename", "Filename with a space or &", 4),
598
+ ("dl_matplotlib", "DL_methods chart in matplotlib (imshow is fine)", 5),
599
+ ("dltask_sections", "DL_tasks notebook missing a required section", 5),
600
+ ("dltask_no_require", "DL_tasks live demo that fails on a cold kernel", 5),
601
+ ("stale_outputs", "skip_exec notebook carrying outputs", 6),
602
+ ("large_file", "Notebook over 3 MB", 6),
603
+ ("multi_h2", "Markdown cell with several ## sections", 7),
604
+ ("no_trailing_rule", "## cell without a trailing ---", 7),
605
+ ]
606
+ # Matched case-insensitively against the `##` headings, as substrings, so "Datasets"
607
+ # also accepts "Datasets and splits". From dl-task-notebook-format.instructions.md.
608
+ DLTASK_SECTIONS = ["What is", "Real-world use cases", "Evaluation", "Datasets",
609
+ "Setup", "benchmark", "Common frameworks", "Going further"]
610
+ DLTASK_NOT_TASKS = ("Theory", "Frameworks")
611
+ LARGE_NB_BYTES = 3_000_000
612
+ SKIP_DIRECTIVES = ("skip_showdoc", "skip_exec")
613
+ # Never a site, so never held to the publishing standard (see special-submodules).
614
+ NOT_PUBLISHED = ("Personal/bthek1_career",)
615
+
616
+ def _src(c):
617
+ s = c.get("source", "")
618
+ return "".join(s) if isinstance(s, list) else s
619
+
620
+ def lint_notebook(path, sub=""):
621
+ """{rule key: count} for one notebook. A count is the number of offending items
622
+ (diagrams, characters, cells); 1 for a yes/no rule. Empty means it meets the standard."""
623
+ out = {}
624
+ name = path.name
625
+ if " " in name or "&" in name: out["bad_filename"] = 1
626
+ try: nb = json.loads(path.read_text(encoding="utf-8"))
627
+ except Exception: return out
628
+ cells = nb.get("cells", [])
629
+ if not cells: return out
630
+ code = [_src(c) for c in cells if c.get("cell_type") == "code"]
631
+ md = [_src(c) for c in cells if c.get("cell_type") == "markdown"]
632
+ allcode, allmd = "\n".join(code), "\n".join(md)
633
+ exports = re.search(r"^#\|\s*(export|exporti|exports|default_exp)\b", allcode, re.M)
634
+ first = _src(cells[0]).strip()
635
+
636
+ if cells[0].get("cell_type") != "markdown": out["title_code"] = 1
637
+ else:
638
+ if first.startswith("---"): out["title_leading_rule"] = 1
639
+ if not re.match(r"^(---[\s\S]*?---\s*)?#\s+\S", first): out["title_no_h1"] = 1
640
+ if not re.search(r"^>\s*\S", first, re.M): out["title_no_desc"] = 1
641
+ # nbdev matches directive keys exactly, so `Skip_exec` or `skip_doc` is silently
642
+ # ignored and the notebook executes or shows docs it was meant to skip.
643
+ keys = re.findall(r"^\s*-\s*([A-Za-z_]+)\s*:", first, re.M)
644
+ bad = [k for k in keys if re.search(r"skip|showdoc|exec", k, re.I) and k not in SKIP_DIRECTIVES]
645
+ if bad: out["title_bad_directive"] = len(bad)
646
+ if not exports and "skip_showdoc: true" not in first: out["no_skip_showdoc"] = 1
647
+
648
+ # The title cell is checked above; a `##` packed into it is a title problem first.
649
+ multi = sum(len(re.findall(r"^##\s", m, re.M)) > 1 for m in md[1:])
650
+ trail = sum(bool(re.search(r"^##\s", m, re.M)) and not m.rstrip().endswith("---")
651
+ for m in md[1:])
652
+ if multi: out["multi_h2"] = multi
653
+ if trail: out["no_trailing_rule"] = trail
654
+
655
+ plain = len(re.findall(r"^```mermaid\s*$", allmd, re.M))
656
+ brace = len(re.findall(r"^```\{mermaid\}", allmd, re.M))
657
+ if plain: out["mermaid_plain"] = plain
658
+ if brace: out["mermaid_braced"] = brace
659
+ if name == "index.ipynb" and re.search(r"<svg[\s>]", allmd): out["svg_in_index"] = 1
660
+
661
+ nonascii = sum(ord(ch) > 127 for ch in allcode)
662
+ if nonascii: out["non_ascii"] = nonascii
663
+ if re.search(r"datetime\.utcnow\(|\b(?:dt|datetime)\.now\(\s*\)", allcode):
664
+ out["naive_datetime"] = 1
665
+
666
+ # Charts only: imshow image display is allowed (ECharts cannot draw an image array).
667
+ if sub == "DL/DL_methods" and re.search(
668
+ r"^\s*(import|from)\s+(matplotlib|seaborn|plotly)", allcode, re.M) and re.search(
669
+ r"\b(?:plt|ax|axes\[[^]]*\])\.(?:plot|scatter|bar|barh|hist|pie|errorbar|fill_between|"
670
+ r"boxplot|violinplot|step|stem|contourf?|plot_surface|plot_wireframe)\(|\bsns\.\w+\(|\bpx\.\w+\(",
671
+ allcode):
672
+ out["dl_matplotlib"] = 1
673
+ # Only a real task notebook: not the index, a library notebook, a stub, or the
674
+ # Theory/ and Frameworks/ reference pages, which have no task to benchmark.
675
+ if (sub == "DL/DL_tasks" and name != "index.ipynb" and not exports and len(cells) > 3
676
+ and path.parent.name not in DLTASK_NOT_TASKS):
677
+ heads = "\n".join(re.findall(r"^##\s+.*$", allmd, re.M)).lower()
678
+ # "Head-to-head: <question>" is the benchmark section under a sharper title.
679
+ missing = [s for s in DLTASK_SECTIONS if s.lower() not in heads
680
+ and not (s == "benchmark" and "head-to-head" in heads)]
681
+ if missing: out["dltask_sections"] = len(missing)
682
+ # A live demo is the cell people run alone, so it must survive a cold kernel:
683
+ # a require(...) guard, a bootstrap(...) that runs Setup from the .ipynb, or a
684
+ # standalone prelude defining its own free_memory(). Comment lines do not count.
685
+ for c in cells:
686
+ if c.get("cell_type") != "code": continue
687
+ live = "\n".join(l for l in "".join(c["source"]).splitlines()
688
+ if not l.lstrip().startswith("#"))
689
+ if (re.search(r"cv2\.VideoCapture|sounddevice|pyaudio", live)
690
+ and not re.search(r"\b(?:require|bootstrap)\(|^def free_memory\(", live, re.M)):
691
+ out["dltask_no_require"] = out.get("dltask_no_require", 0) + 1
692
+
693
+ # DL notebooks keep outputs on purpose (benchmarks, demos), so only elsewhere is a
694
+ # skip_exec notebook with outputs a sign of stale results.
695
+ outs = sum(len(c.get("outputs", [])) for c in cells if c.get("cell_type") == "code")
696
+ if outs and "skip_exec: true" in first and not sub.startswith("DL/"):
697
+ out["stale_outputs"] = outs
698
+ if path.stat().st_size > LARGE_NB_BYTES: out["large_file"] = 1
699
+ return out
700
+
701
+ def _public_notebooks(nbs):
702
+ "Every published notebook under `nbs`, relative paths. `_`/`.` dirs are build output"
703
+ found = []
704
+ for p in sorted(nbs.rglob("*.ipynb")):
705
+ rel = p.relative_to(nbs)
706
+ if any(part.startswith((".", "_")) for part in rel.parts[:-1]): continue
707
+ if p.name.lower().startswith("p_"): continue
708
+ found.append(rel)
709
+ return found
710
+
711
+ def unlinked_from_index(nbs, public=None):
712
+ "Public notebooks (as posix paths) that `nbs/index.ipynb` does not link to"
713
+ idx = nbs/"index.ipynb"
714
+ if not idx.exists(): return []
715
+ public = public if public is not None else _public_notebooks(nbs)
716
+ body = "".join(_src(c) for c in json.loads(idx.read_text(encoding="utf-8")).get("cells", []))
717
+ links = {unquote(l).split("#")[0] for l in re.findall(r"\]\(([^)\s]+)\)", body)
718
+ if not l.startswith(("http", "#"))}
719
+ return [r.as_posix() for r in public
720
+ if r.name != "index.ipynb" and r.as_posix() not in links]
721
+
722
+ def lint_one(path, sub=None, nbs="nbs"):
723
+ "{notebook path relative to the superproject: {rule key: count}} for one submodule"
724
+ name = sub.path if sub else path.name
725
+ root = path/nbs
726
+ if name in NOT_PUBLISHED: raise Skip("not published")
727
+ if not root.is_dir(): raise Skip("without nbs")
728
+ public = _public_notebooks(root)
729
+ found = {}
730
+ for rel in public:
731
+ hits = lint_notebook(root/rel, name)
732
+ if hits: found[f"{name}/{nbs}/{rel.as_posix()}"] = hits
733
+ for rel in unlinked_from_index(root, public):
734
+ found.setdefault(f"{name}/{nbs}/{rel}", {})["index_unlinked"] = 1
735
+ return found
736
+
737
+ def lint_totals(found):
738
+ "{rule key: (notebooks, items)} over the output of `lint_one`, every rule present"
739
+ tot = {k: [0, 0] for k, _, _ in NB_RULES}
740
+ for hits in found.values():
741
+ for k, n in hits.items(): tot[k][0] += 1; tot[k][1] += n
742
+ return {k: tuple(v) for k, v in tot.items()}
743
+
744
+ def fleet_nblint(
745
+ detail:bool = False, # List the offending notebooks under each rule
746
+ phase:int = None, # Only the rules for this phase of issue #24
747
+ strict:bool = False, # Exit 1 when any rule is above 0
748
+ root:str = None, # Superproject root (default: nearest ancestor with .gitmodules)
749
+ ):
750
+ "Count public notebooks that break the notebook standard, one row per rule"
751
+ from rich.table import Table
752
+ found = {}
753
+ def _collect(p, s):
754
+ found.update(lint_one(p, s))
755
+ raise Skip("linted") # counted below in one table, not narrated per submodule
756
+ rep = walk(_collect, root=root, workers=8, style="line")
757
+ if rep.failed: sys.exit(finish(rep, "linted"))
758
+ rules = [r for r in NB_RULES if phase is None or r[2] == phase]
759
+ tot = lint_totals(found)
760
+ t = Table(title="Notebook standard (issue #24)", title_justify="left")
761
+ for col, kw in (("Phase", {"justify": "right"}), ("Rule", {}),
762
+ ("Notebooks", {"justify": "right"}), ("Items", {"justify": "right"})):
763
+ t.add_column(col, **kw)
764
+ for key, label, ph in rules:
765
+ nbks, items = tot[key]
766
+ style = "green" if nbks == 0 else None
767
+ t.add_row(str(ph), escape(label), str(nbks), str(items), style=style)
768
+ console.print(t)
769
+ left = sum(tot[k][0] for k, _, _ in rules)
770
+ console.print(f"[bold]{len(found)} notebooks flagged, {left} rule hits in view[/bold]")
771
+ if detail:
772
+ for key, label, _ in rules:
773
+ hits = sorted((p, h[key]) for p, h in found.items() if key in h)
774
+ if not hits: continue
775
+ console.print(f"\n[bold cyan]{escape(label)}[/bold cyan]")
776
+ for p, n in hits: console.print(f" {escape(p)} [dim]({n})[/dim]")
777
+ sys.exit(1 if strict and left else 0)
778
+
578
779
  # %% ../nbs/04_Fleet.ipynb #0281bd2b-91ba-4e49-90dc-d1a95d54d5a6
579
780
  VERBS = {"upload": fleet_upload, "push": fleet_push, "copy": fleet_copy,
580
781
  "status": fleet_status, "update": fleet_update, "sync": fleet_sync,
581
- "scan": fleet_scan}
782
+ "scan": fleet_scan, "nblint": fleet_nblint}
582
783
 
583
784
  def parse_verb(argv):
584
785
  "(verb, remaining args) for `fleet ...`, or None when `argv` does not name a verb"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: nbdevAuto
3
- Version: 0.3.76
3
+ Version: 0.3.78
4
4
  Summary: automating nbdev
5
5
  Author-email: Benedict Thekkel <bthekkel1@gmail.com>
6
6
  License-Expression: Apache-2.0
@@ -1 +0,0 @@
1
- __version__ = "0.3.76"
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes