pybi-ray 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.
pybi/__init__.py ADDED
@@ -0,0 +1,36 @@
1
+ """PyBI — an open-source, Python-powered business intelligence studio.
2
+
3
+ pip install pybi-ray
4
+ pybi run
5
+
6
+ Author: Muhammad Rafay Shaikh, from Pakistan.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ __version__ = "0.1.0"
11
+ __author__ = "Muhammad Rafay Shaikh"
12
+
13
+ from typing import Any
14
+
15
+
16
+ def run(project: str | None = None, port: int = 8050, open_browser: bool = True,
17
+ private: bool = False, demo: bool = False, **dataframes: Any) -> None:
18
+ """Start the PyBI studio.
19
+
20
+ Pass pandas DataFrames as keyword arguments to load them as tables::
21
+
22
+ import pybi
23
+ pybi.run(Sales=df_sales, Products=df_products)
24
+ """
25
+ from .server import serve
26
+
27
+ serve(project=project, host="127.0.0.1" if private else "0.0.0.0", port=port, open_browser=open_browser,
28
+ dataframes=dataframes or None, sample=demo)
29
+
30
+
31
+ def show(**dataframes: Any) -> None:
32
+ """Alias of :func:`run` for notebooks and scripts: ``pybi.show(Sales=df)``."""
33
+ run(**dataframes)
34
+
35
+
36
+ __all__ = ["run", "show", "__version__"]
pybi/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
pybi/cli.py ADDED
@@ -0,0 +1,66 @@
1
+ """Command line interface: pybi run | pybi demo | pybi export | pybi version"""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import sys
6
+ from pathlib import Path
7
+
8
+ from . import __version__
9
+
10
+
11
+ def main(argv=None) -> int:
12
+ parser = argparse.ArgumentParser(prog="pybi", description="PyBI - open-source business intelligence studio in Python")
13
+ sub = parser.add_subparsers(dest="cmd")
14
+
15
+ run = sub.add_parser("run", help="start the PyBI studio in your browser")
16
+ run.add_argument("project", nargs="?", help="a .pybi project file (or data file: csv/xlsx/json/parquet) to open")
17
+ run.add_argument("--port", "-p", type=int, default=8050)
18
+ run.add_argument("--private", action="store_true", help="only this computer can connect (no network view link)")
19
+ run.add_argument("--no-browser", action="store_true", help="do not open a browser window")
20
+ run.add_argument("--demo", action="store_true", help="start with the demo sales dataset and dashboard")
21
+
22
+ demo = sub.add_parser("demo", help="start the studio with the demo dashboard")
23
+ demo.add_argument("--port", "-p", type=int, default=8050)
24
+ demo.add_argument("--private", action="store_true")
25
+ demo.add_argument("--no-browser", action="store_true")
26
+
27
+ exp = sub.add_parser("export", help="export a .pybi project to a standalone interactive HTML file")
28
+ exp.add_argument("project")
29
+ exp.add_argument("--out", "-o", help="output .html path")
30
+
31
+ sub.add_parser("version", help="print the version")
32
+
33
+ args = parser.parse_args(argv)
34
+ if args.cmd in (None, "run", "demo"):
35
+ from .server import serve
36
+
37
+ project = getattr(args, "project", None)
38
+ dataframes = None
39
+ if project and Path(project).suffix.lower() not in (".pybi", ""):
40
+ from .project import read_upload
41
+
42
+ p = Path(project)
43
+ dataframes = read_upload(p.name, p.read_bytes())
44
+ project = None
45
+ serve(project=project, host="127.0.0.1" if getattr(args, "private", False) else "0.0.0.0",
46
+ port=getattr(args, "port", 8050), open_browser=not getattr(args, "no_browser", False),
47
+ dataframes=dataframes, sample=args.cmd == "demo" or getattr(args, "demo", False))
48
+ return 0
49
+ if args.cmd == "export":
50
+ from .exporters import export_html
51
+ from .project import Project
52
+
53
+ proj = Project.load(args.project)
54
+ out = Path(args.out or Path(args.project).with_suffix(".html"))
55
+ out.write_text(export_html(proj.state()), encoding="utf-8")
56
+ print(f"Exported {out}")
57
+ return 0
58
+ if args.cmd == "version":
59
+ print(f"PyBI {__version__}")
60
+ return 0
61
+ parser.print_help()
62
+ return 1
63
+
64
+
65
+ if __name__ == "__main__":
66
+ sys.exit(main())
@@ -0,0 +1,10 @@
1
+ """PyBI data connectors: a catalog of 120+ sources powered by a handful of generic engines."""
2
+ from .base import Connector, ConnectorError, Param
3
+ from .catalog import BY_ID, CATALOG, CATEGORIES
4
+ from .engines import discover, run
5
+
6
+ __all__ = ["CATALOG", "BY_ID", "CATEGORIES", "Connector", "ConnectorError", "Param", "run", "discover", "catalog_json"]
7
+
8
+
9
+ def catalog_json():
10
+ return {"categories": CATEGORIES, "connectors": [c.to_dict() for c in CATALOG], "count": len(CATALOG)}
@@ -0,0 +1,112 @@
1
+ """Connector primitives: parameter specs, the Connector record, templating and optional-dependency checks."""
2
+ from __future__ import annotations
3
+
4
+ import importlib
5
+ import string
6
+ from dataclasses import dataclass, field
7
+ from typing import Any, Dict, List, Optional
8
+
9
+
10
+ class ConnectorError(Exception):
11
+ """A user-facing connector problem (bad credentials, missing driver, unreachable host...)."""
12
+
13
+ def __init__(self, message: str, install: Optional[str] = None):
14
+ super().__init__(message)
15
+ self.install = install
16
+
17
+
18
+ def need(module: str, pip_name: Optional[str] = None):
19
+ """Import an optional driver or raise a friendly 'pip install ...' error."""
20
+ try:
21
+ return importlib.import_module(module)
22
+ except ImportError as exc:
23
+ pkg = pip_name or module
24
+ raise ConnectorError(f"This connector needs the '{pkg}' package. Install it with: pip install {pkg}", install=pkg) from exc
25
+
26
+
27
+ @dataclass
28
+ class Param:
29
+ key: str
30
+ label: str
31
+ type: str = "text" # text | password | number | select | textarea | checkbox | file | json
32
+ required: bool = False
33
+ default: Any = None
34
+ help: str = ""
35
+ options: Optional[list] = None
36
+ secret: bool = False
37
+ advanced: bool = False
38
+ placeholder: str = ""
39
+
40
+ def to_dict(self):
41
+ return {k: v for k, v in self.__dict__.items() if v not in (None, "", False) or k in ("key", "label", "type")}
42
+
43
+
44
+ @dataclass
45
+ class Connector:
46
+ id: str
47
+ name: str
48
+ category: str
49
+ engine: str
50
+ params: List[Param] = field(default_factory=list)
51
+ config: Dict[str, Any] = field(default_factory=dict)
52
+ description: str = ""
53
+ install: Optional[str] = None # pip package(s) needed beyond PyBI's own dependencies
54
+ multi: bool = False # can return several tables (shows a navigator)
55
+ docs: str = ""
56
+ tags: str = ""
57
+
58
+ def to_dict(self):
59
+ return {"id": self.id, "name": self.name, "category": self.category, "engine": self.engine,
60
+ "description": self.description, "install": self.install, "multi": self.multi, "docs": self.docs,
61
+ "params": [p.to_dict() for p in self.params], "tags": self.tags}
62
+
63
+
64
+ class _SafeFormatter(string.Formatter):
65
+ def get_value(self, key, args, kwargs):
66
+ v = kwargs.get(key, "")
67
+ return "" if v is None else v
68
+
69
+
70
+ _fmt = _SafeFormatter()
71
+
72
+
73
+ def render(obj, params: Dict[str, Any]):
74
+ """Fill {placeholders} in strings / dicts / lists with parameter values (missing -> empty)."""
75
+ if isinstance(obj, str):
76
+ if "{" not in obj:
77
+ return obj
78
+ try:
79
+ return _fmt.format(obj, **params)
80
+ except (ValueError, IndexError):
81
+ return obj
82
+ if isinstance(obj, dict):
83
+ return {render(k, params): render(v, params) for k, v in obj.items()}
84
+ if isinstance(obj, list):
85
+ return [render(v, params) for v in obj]
86
+ return obj
87
+
88
+
89
+ def dig(obj, path: Optional[str]):
90
+ """Follow a dot path like 'data.items' or 'results.0.rows' through dicts and lists.
91
+ Keys that themselves contain dots (e.g. '@odata.nextLink') are matched first."""
92
+ if path in (None, "", "."):
93
+ return obj
94
+ path = str(path)
95
+ if isinstance(obj, dict) and path in obj:
96
+ return obj[path]
97
+ head, _, rest = path.partition(".")
98
+ if isinstance(obj, dict):
99
+ # try the longest dotted key prefix that exists
100
+ parts = path.split(".")
101
+ for i in range(len(parts), 0, -1):
102
+ key = ".".join(parts[:i])
103
+ if key in obj:
104
+ return obj[key] if i == len(parts) else dig(obj[key], ".".join(parts[i:]))
105
+ return None
106
+ if isinstance(obj, list):
107
+ try:
108
+ nxt = obj[int(head)]
109
+ except (ValueError, IndexError):
110
+ return None
111
+ return dig(nxt, rest) if rest else nxt
112
+ return None