scikit-doc 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.
scikit_doc/__init__.py ADDED
@@ -0,0 +1,328 @@
1
+ """scikit-doc: a practical scikit-learn reference with 127 worked examples.
2
+
3
+ Python quick start
4
+ ------------------
5
+ import scikit_doc as skdoc
6
+ help(skdoc) # full handbook + every worked example
7
+ skdoc.show() # render the practical handbook in Colab
8
+ skdoc.show_examples() # render the complete worked-example catalog
9
+ skdoc.topics() # list handbook chapters
10
+ skdoc.examples() # browse every solved example
11
+ skdoc.example("gridsearchcv") # retrieve one example by title or slug
12
+ skdoc.search("PCA n_components") # search locally
13
+ skdoc.api("sklearn.linear_model.Ridge")
14
+ skdoc.api_reference(module="preprocessing")
15
+
16
+ The PyPI distribution is ``scikit-doc``. The Python import name is ``scikit_doc``.
17
+ The official scikit-learn User Guide and API website remain the canonical full reference;
18
+ this package adds live installed-version docstrings and source-grounded worked examples.
19
+ """
20
+ from __future__ import annotations
21
+
22
+ import importlib
23
+ import inspect
24
+ import json
25
+ import pkgutil
26
+ import re
27
+ from pathlib import Path
28
+ from typing import Any
29
+
30
+ __version__ = "0.1.0"
31
+ _DISTRIBUTION_NAME = "scikit-doc"
32
+ _PACKAGE_DIR = Path(__file__).resolve().parent
33
+ _DATA_DIR = _PACKAGE_DIR / "data"
34
+ _EXAMPLES_DIR = _PACKAGE_DIR / "examples"
35
+ _GUIDE_PATH = _DATA_DIR / "USER_GUIDE.md"
36
+ _WORKED_PATH = _DATA_DIR / "WORKED_EXAMPLES.md"
37
+ _NOTEBOOK_PATH = _DATA_DIR / "NOTEBOOK_EXAMPLES.md"
38
+ _ROOT_HELP_PATH = _DATA_DIR / "SKLEARN_ROOT_HELP_1_6_1.txt"
39
+ _JSON_PATH = _DATA_DIR / "examples.json"
40
+
41
+
42
+ def _read(path: Path) -> str:
43
+ try:
44
+ return path.read_text(encoding="utf-8")
45
+ except FileNotFoundError as exc:
46
+ raise RuntimeError(f"Bundled resource is missing: {path.name}. Reinstall scikit-doc.") from exc
47
+
48
+
49
+ def _records() -> list[dict[str, Any]]:
50
+ try:
51
+ return json.loads(_read(_JSON_PATH))
52
+ except (json.JSONDecodeError, TypeError) as exc:
53
+ raise RuntimeError("The worked-example index is damaged. Reinstall scikit-doc.") from exc
54
+
55
+
56
+ def topics() -> list[str]:
57
+ """Return the handbook chapter headings."""
58
+ return [line[3:].strip() for line in _read(_GUIDE_PATH).splitlines() if line.startswith("## ")]
59
+
60
+
61
+ def guide(topic: str | None = None) -> str:
62
+ """Return the complete handbook or chapter(s) matching a title fragment."""
63
+ text = _read(_GUIDE_PATH)
64
+ if not topic:
65
+ return text
66
+ lines = text.splitlines()
67
+ starts = [i for i, line in enumerate(lines) if line.startswith("## ")]
68
+ matches=[]
69
+ needle = str(topic).casefold().strip()
70
+ for k, start in enumerate(starts):
71
+ end = starts[k+1] if k+1 < len(starts) else len(lines)
72
+ block = "\n".join(lines[start:end]).strip()
73
+ if needle in block.casefold(): matches.append(block)
74
+ if not matches:
75
+ raise KeyError(f"No handbook section matched {topic!r}. Available: {', '.join(topics())}")
76
+ return "\n\n".join(matches)
77
+
78
+
79
+ def show(topic: str | None = None) -> str:
80
+ """Display the handbook (or one topic) as Markdown in Jupyter/Colab and return it."""
81
+ text = guide(topic)
82
+ try:
83
+ from IPython.display import Markdown, display
84
+ display(Markdown(text))
85
+ except Exception:
86
+ print(text)
87
+ return text
88
+
89
+
90
+ def show_examples(query: str | None = None, *, source: str | None = None) -> str:
91
+ """Display all worked examples or a filtered set as Markdown."""
92
+ records = _records()
93
+ if query:
94
+ needle = query.casefold()
95
+ records = [r for r in records if needle in (r['title']+' '+r['prompt']+' '+r['code']).casefold()]
96
+ if source:
97
+ needle = source.casefold()
98
+ records = [r for r in records if needle in r['source'].casefold() or needle in r['origin'].casefold()]
99
+ if not records:
100
+ text = "No worked examples matched the selected filters."
101
+ else:
102
+ parts=[f"# Worked examples ({len(records)})", ""]
103
+ for r in records:
104
+ parts += [f"## {r['title']}", "", "**Task**", "", r['prompt'], "", "**Step-by-step approach**", ""]
105
+ parts += [f"{i}. {step}" for i, step in enumerate(r['steps'], 1)]
106
+ parts += ["", "**Solution**", "", "```python", r['code'], "```", ""]
107
+ if r.get('output'):
108
+ parts += ["**Recorded result**", "", "```text", str(r['output']), "```", ""]
109
+
110
+ text='\n'.join(parts)
111
+ try:
112
+ from IPython.display import Markdown, display
113
+ display(Markdown(text))
114
+ except Exception:
115
+ print(text)
116
+ return text
117
+
118
+
119
+ def examples(*, query: str | None = None, source: str | None = None) -> list[dict[str, str]]:
120
+ """List solved examples with slug, title and source; optional filters are local."""
121
+ items=[]
122
+ for r in _records():
123
+ if query and query.casefold() not in (r['title']+' '+r['prompt']+' '+r['code']).casefold(): continue
124
+ if source and source.casefold() not in (r['source']+' '+r['origin']).casefold(): continue
125
+ items.append({'slug':r['slug'], 'title':r['title'], 'source':r['source']})
126
+ return items
127
+
128
+
129
+ def example(name: str | int, *, display: bool = False) -> str:
130
+ """Retrieve one full worked example by zero-based position, slug or title fragment."""
131
+ items = _records()
132
+ match = None
133
+ if isinstance(name, int):
134
+ if name < 0 or name >= len(items): raise IndexError(f"Example index must be in 0..{len(items)-1}.")
135
+ match = items[name]
136
+ else:
137
+ needle = str(name).casefold().strip()
138
+ exact = [r for r in items if needle in {r['slug'].casefold(), r['title'].casefold()}]
139
+ matches = exact or [r for r in items if needle and (needle in r['slug'].casefold() or needle in r['title'].casefold())]
140
+ if not matches:
141
+ raise KeyError(f"No example matched {name!r}. Search with scikit_doc.examples(query=...).")
142
+ if len(matches) > 1:
143
+ labels=', '.join(r['slug'] for r in matches[:12])
144
+ raise KeyError(f"More than one example matched {name!r}. Use a unique slug: {labels}")
145
+ match=matches[0]
146
+ text = _format_example(match)
147
+ if display:
148
+ try:
149
+ from IPython.display import Markdown, display as display_markdown
150
+ display_markdown(Markdown(text))
151
+ except Exception: print(text)
152
+ return text
153
+
154
+
155
+ def _format_example(r: dict[str, Any]) -> str:
156
+ parts=[f"# {r['title']}", "", f"**Source collection:** {r['source']}", "", "**Task**", "", r['prompt'], "", "**Step-by-step approach**", ""]
157
+ parts += [f"{i}. {step}" for i, step in enumerate(r['steps'], 1)]
158
+ parts += ["", "**Solution**", "", "```python", r['code'], "```", ""]
159
+ if r.get('output'): parts += ["**Recorded result**", "", "```text", str(r['output']), "```", ""]
160
+ return '\n'.join(parts)
161
+
162
+
163
+ def worked_examples(*, source: str | None = None) -> str:
164
+ """Return the complete collection; filter by a source-name fragment if requested."""
165
+ if source is None: return _read(_WORKED_PATH)
166
+ return show_examples(source=source)
167
+
168
+
169
+ def notebook_examples() -> str:
170
+ """Return the 104 example collection extracted from the five supplied notebooks."""
171
+ return _read(_NOTEBOOK_PATH)
172
+
173
+
174
+ def root_help() -> str:
175
+ """Return the user-supplied scikit-learn root help snapshot (version 1.6.1)."""
176
+ return _read(_ROOT_HELP_PATH)
177
+
178
+
179
+ def search(query: str, *, limit: int = 15) -> list[dict[str, str]]:
180
+ """Search handbook text, every worked problem and bundled references offline."""
181
+ if not str(query).strip(): raise ValueError("query must not be empty")
182
+ if limit < 1: raise ValueError("limit must be at least one")
183
+ needle=str(query).casefold()
184
+ documents=[('handbook', _read(_GUIDE_PATH)), ('worked_examples', _read(_WORKED_PATH)), ('root_help', _read(_ROOT_HELP_PATH))]
185
+ results=[]
186
+ for source, content in documents:
187
+ current=''
188
+ for line in content.splitlines():
189
+ if line.startswith('#'): current=line.lstrip('# ').strip()
190
+ if needle in line.casefold():
191
+ snippet=line.strip()
192
+ if len(snippet)>360: snippet=snippet[:357]+'…'
193
+ results.append({'source':source,'heading':current,'excerpt':snippet})
194
+ if len(results)>=limit: return results
195
+ for r in _records():
196
+ body=' '.join([r['title'],r['prompt'],r['code'],*r['steps']])
197
+ if needle in body.casefold():
198
+ results.append({'source':r['source'],'heading':r['title'],'excerpt':r['prompt'][:360]})
199
+ if len(results)>=limit: return results
200
+ return results
201
+
202
+
203
+ def _resolve_api(path: str):
204
+ name=path.strip()
205
+ if not name: raise ValueError("Provide an API name such as 'Ridge' or 'sklearn.preprocessing.StandardScaler'.")
206
+ if name.startswith('sklearn.'):
207
+ parts=name.split('.')
208
+ for split in range(len(parts)-1,0,-1):
209
+ try: obj=importlib.import_module('.'.join(parts[:split]))
210
+ except Exception: continue
211
+ try:
212
+ for attr in parts[split:]: obj=getattr(obj,attr)
213
+ return obj,name
214
+ except AttributeError: continue
215
+ raise KeyError(f"Could not resolve {name!r} in the installed scikit-learn version.")
216
+ import sklearn
217
+ found=[]
218
+ mods=['sklearn']+[f'sklearn.{x.name}' for x in pkgutil.iter_modules(sklearn.__path__) if not x.name.startswith('_') and x.name!='tests']
219
+ for module_name in mods:
220
+ try:
221
+ mod=importlib.import_module(module_name)
222
+ if hasattr(mod,name):
223
+ obj=getattr(mod,name)
224
+ if not any(o is obj for o,_ in found): found.append((obj,module_name+'.'+name))
225
+ except Exception: pass
226
+ if len(found)==1: return found[0]
227
+ if len(found)>1: raise KeyError(f"{name!r} is ambiguous: {', '.join(x[1] for x in found)}. Use a dotted path.")
228
+ raise KeyError(f"Could not find {name!r}. Use a dotted sklearn path.")
229
+
230
+
231
+ def api(name: str) -> str:
232
+ """Return the live installed signature and full docstring for a scikit-learn API object."""
233
+ try: import sklearn
234
+ except ImportError as exc: raise ImportError("Install scikit-learn to use API lookup.") from exc
235
+ obj,path=_resolve_api(name)
236
+ try: sig=str(inspect.signature(obj))
237
+ except (TypeError,ValueError): sig='(signature unavailable)'
238
+ doc=inspect.getdoc(obj) or 'No docstring is available.'
239
+ return f"{path}\nscikit-learn version: {sklearn.__version__}\nSignature: {getattr(obj,'__name__',type(obj).__name__)}{sig}\n\n{doc}"
240
+
241
+
242
+ def api_catalog(*, module: str | None = None, query: str | None = None, limit: int | None = None) -> list[dict[str,str]]:
243
+ """Index public objects exported by scikit-learn modules available in this runtime."""
244
+ if limit is not None and limit<1: raise ValueError('limit must be positive or None')
245
+ try: import sklearn
246
+ except ImportError as exc: raise ImportError('Install scikit-learn to build the API catalogue.') from exc
247
+ modules=[module if module.startswith('sklearn.') else 'sklearn.'+module] if module else ['sklearn']+[f'sklearn.{x.name}' for x in pkgutil.iter_modules(sklearn.__path__) if not x.name.startswith('_') and x.name!='tests']
248
+ needle=query.casefold().strip() if query else None
249
+ results=[]; seen=set()
250
+ for module_name in modules:
251
+ try: mod=importlib.import_module(module_name)
252
+ except Exception: continue
253
+ for name,obj in inspect.getmembers(mod):
254
+ if name.startswith('_'): continue
255
+ objmod=getattr(obj,'__module__','') or ''
256
+ if not (objmod.startswith('sklearn') or module_name=='sklearn'): continue
257
+ kind='class' if inspect.isclass(obj) else 'function' if inspect.isroutine(obj) else 'object'
258
+ summary=(inspect.getdoc(obj) or '').splitlines()
259
+ summary=summary[0].strip() if summary else ''
260
+ key=(module_name+'.'+name,kind)
261
+ if key in seen: continue
262
+ seen.add(key)
263
+ if needle and needle not in f'{name} {summary} {module_name}'.casefold(): continue
264
+ results.append({'path':module_name+'.'+name,'kind':kind,'summary':summary})
265
+ if limit is not None and len(results)>=limit: return results
266
+ return sorted(results,key=lambda x:x['path'])
267
+
268
+
269
+ def api_reference(*, module: str | None = None, query: str | None = None, limit: int | None = None) -> str:
270
+ """Compile live signature and docstring reference for public scikit-learn objects.
271
+
272
+ With no filters, all discovered public objects are documented. Use module='preprocessing'
273
+ or query='PCA' to create a smaller reference. This is generated from the installed
274
+ version and is not a copied snapshot of the official documentation website.
275
+ """
276
+ entries=api_catalog(module=module,query=query,limit=limit)
277
+ if not entries: return 'No public API objects matched the requested filters.'
278
+ try: import sklearn; version=sklearn.__version__
279
+ except Exception: version='unknown'
280
+ parts=[f'SCIKIT-LEARN PUBLIC API REFERENCE\nInstalled version: {version}\nObjects documented: {len(entries)}\n']
281
+ for entry in entries:
282
+ try: doc=api(entry['path'])
283
+ except Exception as exc: doc=f"Documentation lookup failed: {type(exc).__name__}: {exc}"
284
+ parts += ['\n'+'='*88+'\n'+doc+'\n']
285
+ return '\n'.join(parts)
286
+
287
+
288
+ def modules() -> list[str]:
289
+ """Return public scikit-learn subpackages available in the active environment."""
290
+ try: import sklearn
291
+ except ImportError as exc: raise ImportError('Install scikit-learn to list modules.') from exc
292
+ return sorted(x.name for x in pkgutil.iter_modules(sklearn.__path__) if not x.name.startswith('_') and x.name!='tests')
293
+
294
+
295
+ def version_info() -> dict[str,str]:
296
+ """Return this distribution and active scikit-learn versions."""
297
+ info={'version':__version__,'distribution':_DISTRIBUTION_NAME}
298
+ try: import sklearn; info['scikit_learn_version']=sklearn.__version__
299
+ except ImportError: info['scikit_learn_version']='not installed'
300
+ return info
301
+
302
+
303
+ def format_number(value: float, decimals: int = 3, *, truncate: bool = False) -> str:
304
+ """Format a numeric scalar with explicit rounding or truncation."""
305
+ from decimal import Decimal, ROUND_DOWN, ROUND_HALF_UP
306
+ if decimals<0: raise ValueError('decimals must be non-negative')
307
+ number=Decimal(str(float(value)))
308
+ quantum=Decimal('1').scaleb(-decimals)
309
+ mode=ROUND_DOWN if truncate else ROUND_HALF_UP
310
+ return format(number.quantize(quantum,rounding=mode),f'.{decimals}f')
311
+
312
+
313
+ # The full module docstring is what the built-in help() function prints.
314
+ # Include every worked example, the supplied root help snapshot and runtime API guidance.
315
+ try:
316
+ import sklearn as _sklearn
317
+ _runtime=(f"\n\n## Installed scikit-learn runtime\n\nVersion: {_sklearn.__version__}\n\n"
318
+ f"Public modules: {', '.join(modules())}\n\n"
319
+ "Use scikit_doc.api_catalog() to browse objects, scikit_doc.api(path) for a full live docstring, "
320
+ "and scikit_doc.api_reference() to compile all discovered public API documentation.")
321
+ except Exception:
322
+ _runtime="\n\nInstall scikit-learn to activate live API documentation lookups."
323
+
324
+ __doc__ = (_read(_GUIDE_PATH) + _runtime + "\n\n# Supplied root namespace reference\n\n" +
325
+ _read(_ROOT_HELP_PATH) + "\n\n" + _read(_WORKED_PATH))
326
+
327
+ __all__=['__version__','api','api_catalog','api_reference','example','examples','format_number','guide',
328
+ 'modules','notebook_examples','root_help','search','show','show_examples','topics','version_info','worked_examples']