npdrop 0.3.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.
- myml/__init__.py +49 -0
- myml/__init__.pyi +22 -0
- myml/core.py +201 -0
- myml/data/train.txt +618 -0
- myml/magic.py +37 -0
- myml/suggester.py +398 -0
- myml/templates/cluster.py +20 -0
- myml/templates/iqr.py +16 -0
- myml/templates/linear_regression.py +38 -0
- myml/templates/logistic_regression.py +37 -0
- myml/templates/model.py +22 -0
- myml/templates/tensorflow.py +47 -0
- myml/templates/token.py +24 -0
- npdrop-0.3.0.dist-info/METADATA +89 -0
- npdrop-0.3.0.dist-info/RECORD +17 -0
- npdrop-0.3.0.dist-info/WHEEL +5 -0
- npdrop-0.3.0.dist-info/top_level.txt +1 -0
myml/__init__.py
ADDED
|
@@ -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
|
myml/__init__.pyi
ADDED
|
@@ -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: ...
|
myml/core.py
ADDED
|
@@ -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()
|