npdrop 0.3.0__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.
npdrop-0.3.0/PKG-INFO ADDED
@@ -0,0 +1,89 @@
1
+ Metadata-Version: 2.4
2
+ Name: npdrop
3
+ Version: 0.3.0
4
+ Summary: Notebook-friendly machine-learning code templates and full-block source retrieval
5
+ Requires-Python: >=3.9
6
+ Description-Content-Type: text/markdown
7
+ Provides-Extra: notebook
8
+ Requires-Dist: ipython>=7; extra == "notebook"
9
+ Provides-Extra: test
10
+ Requires-Dist: pytest>=7; extra == "test"
11
+
12
+ # myml — verbatim notebook ML templates and code retrieval
13
+
14
+ myml provides seven reusable Python source templates and a full-block search engine for the personal ML/EDA code in myml/data/train.txt. Template imports read UTF-8 resources and insert their exact text into a fresh notebook cell; template code is never executed during import.
15
+
16
+ ## Install
17
+
18
+ Git install:
19
+
20
+ ~~~bash
21
+ pip install --upgrade git+https://github.com/DilipDC/npdrop.git
22
+ ~~~
23
+
24
+ Windows ZIP install (PowerShell or Command Prompt):
25
+
26
+ ~~~bash
27
+ py -m pip install --upgrade https://github.com/DilipDC/npdrop/archive/refs/heads/main.zip
28
+ ~~~
29
+
30
+ Restart the notebook kernel after upgrading.
31
+
32
+ ## Use the seven templates
33
+
34
+ Each import queues an untouched code block in the next editable cell in local Jupyter Notebook, JupyterLab, Notebook 7, and Google Colab.
35
+
36
+ ~~~python
37
+ from myml import cluster
38
+ from myml import iqr
39
+ from myml import linear_regression
40
+ from myml import logistic_regression
41
+ from myml import model
42
+ from myml import tensorflow
43
+ from myml import token
44
+ ~~~
45
+
46
+ Aliases are also supported:
47
+
48
+ ~~~python
49
+ from myml import LinearRegression
50
+ from myml import LogisticRegression
51
+ from myml import tokenizer
52
+ ~~~
53
+
54
+ Use myml.get_template("cluster").code to read source text without inserting a cell. Calling an import or accessing the template attribute again creates another cell.
55
+
56
+ Local Jupyter uses IPython's payload manager with source="set_next_input" and replace=False. Colab first tries google.colab._frontend.create_scratch_cell(code) and uses a one-click Copy card only if that API fails.
57
+
58
+ ## Search complete code blocks with myml.sug()
59
+
60
+ The suggestion index is built exclusively from myml/data/train.txt using Python's standard library. Queries support identifier splitting, ML/EDA shorthand, generated acronyms, weighted BM25-style ranking, exact-phrase boosts, and typo-tolerant fuzzy matching.
61
+
62
+ ~~~python
63
+ myml.sug() # print every parsed block with its number
64
+ myml.sug("km") # insert the best K-Means block
65
+ myml.sug("scatter plot") # insert the matching scatter-plot block
66
+ myml.sug("hist") # histogram block
67
+ myml.sug("logistic regression") # logistic-regression block
68
+ myml.sug("sactter plot") # tolerate a typo
69
+ myml.sug("scatter plot", rank=2) # insert the second-ranked match
70
+ ~~~
71
+
72
+ A query returns the selected full multi-line source block and also queues that exact text into the next notebook cell. The function prints its selected rank and up to three alternative matches. myml.reload_index() rebuilds the index after train.txt is updated.
73
+
74
+ The training source is available only through myml.sug(); from myml import train is intentionally unsupported.
75
+
76
+ ## Package contents
77
+
78
+ - myml/templates/: the seven verbatim import templates
79
+ - myml/data/train.txt: the separate EDA/ML suggestion source
80
+ - myml/__init__.pyi: static type declarations
81
+
82
+ The runtime package has no third-party dependencies. IPython is optional for notebook insertion; ML libraries referenced by inserted template code are needed only when those cells are executed.
83
+
84
+ ## Tests
85
+
86
+ ~~~bash
87
+ python -m pip install -e ".[test]"
88
+ python -m pytest -q
89
+ ~~~
npdrop-0.3.0/README.md ADDED
@@ -0,0 +1,78 @@
1
+ # myml — verbatim notebook ML templates and code retrieval
2
+
3
+ myml provides seven reusable Python source templates and a full-block search engine for the personal ML/EDA code in myml/data/train.txt. Template imports read UTF-8 resources and insert their exact text into a fresh notebook cell; template code is never executed during import.
4
+
5
+ ## Install
6
+
7
+ Git install:
8
+
9
+ ~~~bash
10
+ pip install --upgrade git+https://github.com/DilipDC/npdrop.git
11
+ ~~~
12
+
13
+ Windows ZIP install (PowerShell or Command Prompt):
14
+
15
+ ~~~bash
16
+ py -m pip install --upgrade https://github.com/DilipDC/npdrop/archive/refs/heads/main.zip
17
+ ~~~
18
+
19
+ Restart the notebook kernel after upgrading.
20
+
21
+ ## Use the seven templates
22
+
23
+ Each import queues an untouched code block in the next editable cell in local Jupyter Notebook, JupyterLab, Notebook 7, and Google Colab.
24
+
25
+ ~~~python
26
+ from myml import cluster
27
+ from myml import iqr
28
+ from myml import linear_regression
29
+ from myml import logistic_regression
30
+ from myml import model
31
+ from myml import tensorflow
32
+ from myml import token
33
+ ~~~
34
+
35
+ Aliases are also supported:
36
+
37
+ ~~~python
38
+ from myml import LinearRegression
39
+ from myml import LogisticRegression
40
+ from myml import tokenizer
41
+ ~~~
42
+
43
+ Use myml.get_template("cluster").code to read source text without inserting a cell. Calling an import or accessing the template attribute again creates another cell.
44
+
45
+ Local Jupyter uses IPython's payload manager with source="set_next_input" and replace=False. Colab first tries google.colab._frontend.create_scratch_cell(code) and uses a one-click Copy card only if that API fails.
46
+
47
+ ## Search complete code blocks with myml.sug()
48
+
49
+ The suggestion index is built exclusively from myml/data/train.txt using Python's standard library. Queries support identifier splitting, ML/EDA shorthand, generated acronyms, weighted BM25-style ranking, exact-phrase boosts, and typo-tolerant fuzzy matching.
50
+
51
+ ~~~python
52
+ myml.sug() # print every parsed block with its number
53
+ myml.sug("km") # insert the best K-Means block
54
+ myml.sug("scatter plot") # insert the matching scatter-plot block
55
+ myml.sug("hist") # histogram block
56
+ myml.sug("logistic regression") # logistic-regression block
57
+ myml.sug("sactter plot") # tolerate a typo
58
+ myml.sug("scatter plot", rank=2) # insert the second-ranked match
59
+ ~~~
60
+
61
+ A query returns the selected full multi-line source block and also queues that exact text into the next notebook cell. The function prints its selected rank and up to three alternative matches. myml.reload_index() rebuilds the index after train.txt is updated.
62
+
63
+ The training source is available only through myml.sug(); from myml import train is intentionally unsupported.
64
+
65
+ ## Package contents
66
+
67
+ - myml/templates/: the seven verbatim import templates
68
+ - myml/data/train.txt: the separate EDA/ML suggestion source
69
+ - myml/__init__.pyi: static type declarations
70
+
71
+ The runtime package has no third-party dependencies. IPython is optional for notebook insertion; ML libraries referenced by inserted template code are needed only when those cells are executed.
72
+
73
+ ## Tests
74
+
75
+ ~~~bash
76
+ python -m pip install -e ".[test]"
77
+ python -m pytest -q
78
+ ~~~
@@ -0,0 +1,49 @@
1
+ """myml: verbatim ML templates and source-indexed notebook code retrieval."""
2
+ import sys
3
+
4
+ from .core import (
5
+ ALIASES,
6
+ Snippet,
7
+ ask,
8
+ get_template,
9
+ list_templates,
10
+ template_names,
11
+ )
12
+ from .suggester import reload_index, suggest
13
+ from .suggester import sug as sug
14
+ from .magic import enable_magic
15
+
16
+ __all__ = [
17
+ "ALIASES",
18
+ "Snippet",
19
+ "ask",
20
+ "get_template",
21
+ "list_templates",
22
+ "template_names",
23
+ "sug",
24
+ "suggest",
25
+ "reload_index",
26
+ ] + template_names(include_aliases=True)
27
+
28
+
29
+ def __getattr__(name):
30
+ """Deliver a fresh template cell on every attribute retrieval."""
31
+ if name in template_names(include_aliases=True):
32
+ try:
33
+ caller = sys._getframe(1)
34
+ if caller.f_code.co_name == "_handle_fromlist":
35
+ return get_template(name)
36
+ except Exception:
37
+ pass
38
+ return get_template(name).show()
39
+ raise AttributeError(f"module 'myml' has no attribute {name!r}")
40
+
41
+
42
+ def __dir__():
43
+ return sorted(set(globals()) | set(template_names(include_aliases=True)))
44
+
45
+
46
+ try:
47
+ enable_magic()
48
+ except Exception:
49
+ pass
@@ -0,0 +1,22 @@
1
+ """Generated declarations for myml's verbatim templates and retrieval API."""
2
+ from typing import Any, List, Optional, Union
3
+ from .core import Snippet
4
+
5
+ cluster: Snippet
6
+ iqr: Snippet
7
+ linear_regression: Snippet
8
+ logistic_regression: Snippet
9
+ model: Snippet
10
+ tensorflow: Snippet
11
+ token: Snippet
12
+ LinearRegression: Snippet
13
+ LogisticRegression: Snippet
14
+ tokenizer: Snippet
15
+
16
+ def get_template(name: str) -> Snippet: ...
17
+ def template_names(include_aliases: bool = ...) -> List[str]: ...
18
+ def list_templates() -> List[tuple]: ...
19
+ def ask(query: str) -> Optional[Snippet]: ...
20
+ def sug(query: Optional[str] = ..., rank: int = ...) -> Union[str, list]: ...
21
+ def suggest(query: str = ..., limit: int = ...) -> List[str]: ...
22
+ def reload_index() -> int: ...
@@ -0,0 +1,201 @@
1
+ """Safe, UTF-8 template loading and notebook cell delivery."""
2
+ from __future__ import annotations
3
+
4
+ import html
5
+ import sys
6
+ from importlib import resources
7
+ from pathlib import Path
8
+
9
+ ALIASES = {
10
+ "LinearRegression": "linear_regression",
11
+ "LogisticRegression": "logistic_regression",
12
+ "tokenizer": "token",
13
+ }
14
+
15
+
16
+ def _template_files():
17
+ """Return packaged resources; template Python is never imported or executed."""
18
+ root = resources.files(__package__).joinpath("templates")
19
+ return {
20
+ item.name[:-3]: item
21
+ for item in root.iterdir()
22
+ if item.name.endswith(".py") and not item.name.startswith("_")
23
+ }
24
+
25
+
26
+ def template_names(include_aliases: bool = False):
27
+ names = sorted(_template_files())
28
+ if include_aliases:
29
+ names.extend(sorted(ALIASES))
30
+ return names
31
+
32
+
33
+ def resolve_template_name(name: str) -> str:
34
+ canonical = ALIASES.get(name, name)
35
+ if canonical not in _template_files():
36
+ raise KeyError(name)
37
+ return canonical
38
+
39
+
40
+ def _read(name: str) -> str:
41
+ """Read a template as UTF-8 text without importing or executing its source."""
42
+ canonical = resolve_template_name(name)
43
+ return _template_files()[canonical].read_text(
44
+ encoding="utf-8",
45
+ errors="replace",
46
+ )
47
+
48
+
49
+ def _description(code: str) -> str:
50
+ for line in code.splitlines():
51
+ candidate = line.strip()
52
+ if candidate.startswith("#"):
53
+ candidate = candidate.lstrip("#").strip(" -\t")
54
+ if candidate:
55
+ return candidate[:180]
56
+ return "Python source template"
57
+
58
+
59
+ def _colab_copy_card(name: str, code: str) -> bool:
60
+ """Show the Colab-only fallback card when scratch-cell creation fails."""
61
+ try:
62
+ from IPython.display import HTML, display
63
+
64
+ safe_name = html.escape(name)
65
+ safe_code = html.escape(code)
66
+ card = f"""<div style="border:1px solid #d0d7de;border-radius:12px;padding:14px;margin:8px 0;font-family:system-ui">
67
+ <h3 style="margin:0 0 8px">myml · {safe_name}</h3>
68
+ <button style="padding:7px 12px;border:0;border-radius:7px;background:#1463d5;color:#fff;cursor:pointer"
69
+ onclick="navigator.clipboard.writeText(this.parentElement.querySelector('pre').innerText).then(()=>this.innerText='Copied!')">Copy code</button>
70
+ <pre style="white-space:pre-wrap;overflow:auto;max-height:520px;background:#f6f8fa;padding:12px;border-radius:7px"><code>{safe_code}</code></pre>
71
+ </div>"""
72
+ display(HTML(card))
73
+ return True
74
+ except Exception:
75
+ return False
76
+
77
+
78
+ def deliver(name: str, code: str, replace: bool = False) -> bool:
79
+ """Insert code in Colab or the next local Jupyter cell.
80
+
81
+ Returns True when a notebook delivery mechanism accepted the code. Outside
82
+ notebooks, or when no local payload manager is available, prints the code.
83
+ Local Jupyter never falls back to an HTML copy card.
84
+ """
85
+ source = str(code)
86
+
87
+ # Try Colab explicitly first. If Colab is present but its scratch-cell API
88
+ # is missing or raises, use the one-click HTML card as the Colab fallback.
89
+ try:
90
+ import google.colab # type: ignore # noqa: F401
91
+ except Exception:
92
+ google_colab_available = False
93
+ else:
94
+ google_colab_available = True
95
+
96
+ if google_colab_available:
97
+ try:
98
+ from google.colab import _frontend # type: ignore
99
+
100
+ _frontend.create_scratch_cell(source)
101
+ return True
102
+ except Exception:
103
+ if _colab_copy_card(name, source):
104
+ return True
105
+ print(source, end="" if source.endswith("\n") else "\n")
106
+ return False
107
+
108
+ # Local Jupyter/JupyterLab/Notebook 7. Check both the IPython instance and
109
+ # payload manager before accessing write_payload; do not show HTML here.
110
+ try:
111
+ from IPython import get_ipython
112
+
113
+ ip = get_ipython()
114
+ if ip is not None:
115
+ payload_manager = getattr(ip, "payload_manager", None)
116
+ writer = getattr(payload_manager, "write_payload", None)
117
+ if callable(writer):
118
+ writer(
119
+ {
120
+ "source": "set_next_input",
121
+ "text": source,
122
+ "replace": replace,
123
+ },
124
+ single=False,
125
+ )
126
+ return True
127
+ except Exception:
128
+ # Missing/broken IPython state must not make sug() or template imports fail.
129
+ pass
130
+
131
+ print(source, end="" if source.endswith("\n") else "\n")
132
+ return False
133
+
134
+
135
+ # Backward-compatible private name used by earlier myml releases.
136
+ _deliver = deliver
137
+
138
+
139
+ class Snippet:
140
+ """A source snippet; .code is the untouched UTF-8 template text."""
141
+
142
+ def __init__(self, name: str, code: str):
143
+ self.name = resolve_template_name(name)
144
+ self.code = code
145
+ self.description = _description(code)
146
+
147
+ def show(self):
148
+ deliver(self.name, self.code)
149
+ return self
150
+
151
+ def insert(self, replace: bool = False):
152
+ deliver(self.name, self.code, replace=replace)
153
+ return self
154
+
155
+ def save(self, filename):
156
+ path = Path(filename)
157
+ path.write_bytes(self.code.encode("utf-8"))
158
+ return path
159
+
160
+ def __repr__(self):
161
+ return f"Snippet({self.name!r}: {self.description})"
162
+
163
+
164
+ def get_template(name: str) -> Snippet:
165
+ canonical = resolve_template_name(name)
166
+ return Snippet(canonical, _read(canonical))
167
+
168
+
169
+ def list_templates():
170
+ rows = [(name, _description(_read(name))) for name in template_names()]
171
+ for name, description in rows:
172
+ print(f"{name:24} {description}")
173
+ return rows
174
+
175
+
176
+ def ask(query):
177
+ """Compatibility helper: retrieve a template by name or simple keyword."""
178
+ import difflib
179
+ import re
180
+
181
+ query = str(query or "").strip().lower()
182
+ if not query:
183
+ return list_templates()
184
+
185
+ ranked = []
186
+ for name in template_names(include_aliases=True):
187
+ canonical = ALIASES.get(name, name)
188
+ code = _read(canonical)
189
+ words = set(re.findall(r"[a-z0-9]+", (name + " " + code).lower()))
190
+ query_words = set(re.findall(r"[a-z0-9]+", query))
191
+ overlap = len(words & query_words) / max(1, len(query_words))
192
+ fuzzy = difflib.SequenceMatcher(
193
+ None, query, name.replace("_", " ").lower()
194
+ ).ratio()
195
+ ranked.append((overlap * 0.7 + fuzzy * 0.3, name))
196
+
197
+ ranked.sort(reverse=True)
198
+ if not ranked or ranked[0][0] < 0.08:
199
+ print("No matching templates. Try myml.list_templates().")
200
+ return None
201
+ return get_template(ranked[0][1]).show()