marimo-pys 0.0.1__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.
@@ -0,0 +1,31 @@
1
+ Metadata-Version: 2.4
2
+ Name: marimo_pys
3
+ Version: 0.0.1
4
+ Summary: PyScript Execution Function in Marimo
5
+ Author: Uniras
6
+ Author-email: tkappeng@gmail.com
7
+ License: MIT License
8
+ Project-URL: Homepage, https://github.com/uniras/pysionui
9
+ Project-URL: Repository, https://github.com/uniras/pysionui
10
+ Keywords: PyScript,Marimo
11
+ Classifier: Development Status :: 5 - Production/Stable
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Programming Language :: Python :: 3.14
20
+ Classifier: Programming Language :: Python :: 3 :: Only
21
+ Classifier: Topic :: Software Development :: Libraries
22
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
23
+ Classifier: Topic :: Utilities
24
+ Description-Content-Type: text/markdown
25
+
26
+ # marimo_pys
27
+
28
+ ## Description
29
+
30
+ marimo_pys is PyScript execute function in marimo
31
+
@@ -0,0 +1,6 @@
1
+ # marimo_pys
2
+
3
+ ## Description
4
+
5
+ marimo_pys is PyScript execute function in marimo
6
+
@@ -0,0 +1,158 @@
1
+ import inspect
2
+ import textwrap
3
+ import html
4
+ import json
5
+ import base64
6
+ import marimo as mo
7
+ from typing import Callable, Optional, Union, Any
8
+
9
+
10
+ def run_pyscript(
11
+ code: Union[Callable, str],
12
+ width: str = '100%',
13
+ height: str = '200px',
14
+ body_style: str = '',
15
+ iframe_style: str = '',
16
+ iframe_sandbox: str = 'allow-scripts',
17
+ config: Optional[dict[str, Any]] = None,
18
+ data: Optional[dict[str, Any]] = None,
19
+ add_script: Optional[list[str]] = None,
20
+ add_module: Optional[list[str]] = None,
21
+ add_css: Optional[list[str]] = None,
22
+ add_dangerous_html: str = '',
23
+ terminal: bool = False,
24
+ pys_version: str = '2026.7.3',
25
+ pys_type: str = 'mpy',
26
+ ) -> mo.Html:
27
+ """
28
+ Generates HTML to execute the specified Python function as a PyScript and returns it as an Marimo iframe.
29
+
30
+ Args:
31
+ code (Union[Callable, str]): The async function or raw source code to be executed.
32
+ A callable must be a coroutine function; it is awaited in the browser as
33
+ ``await code(js, data)``, where ``js`` is the PyScript ``js`` module and
34
+ ``data`` is the ``data`` argument decoded back into a plain Python object.
35
+ Only the function's own source is transferred: it runs in a fresh
36
+ interpreter with no access to the surrounding module's imports, globals or
37
+ closure variables, so every import must happen inside the function body.
38
+ Decorators are not supported.
39
+ width (str): Width of the iframe. Default is '100%'.
40
+ height (str): Height of the iframe. Default is '200px'.
41
+ body_style (str): Additional CSS styles for the body. Default is ''.
42
+ iframe_style (str): Additional CSS styles for the iframe. Default is ''.
43
+ iframe_sandbox (str): Sandbox attributes for the iframe. Default is 'allow-scripts'.
44
+ config (Optional[dict[str, Any]]): Configuration dictionary for PyScript. Default is None.
45
+ data (Optional[dict[str, Any]]): Data dictionary to be passed to the function. Default is None.
46
+ add_script (Optional[list[str]]): List of additional JavaScript files to include. Default is None.
47
+ add_module (Optional[list[str]]): List of additional JavaScript modules to include. Default is None.
48
+ add_css (Optional[list[str]]): List of additional CSS files to include. Default is None.
49
+ add_dangerous_html (str): Additional HTML content to include in the body. note: This can be dangerous if it includes untrusted content. Default is ''.
50
+ terminal (bool): Whether to enable terminal output in PyScript. Default is False.
51
+ pys_version (str): Version of PyScript to use. Default is '2026.7.3'.
52
+ pys_type (str): Type of PyScript to use. Default is 'mpy'.
53
+
54
+ Returns:
55
+ mo.Html: An HTML object containing the iframe with the PyScript execution.
56
+ """
57
+
58
+ # Set default values for optional parameters
59
+ config = config or {}
60
+ data = data or {}
61
+ add_script = add_script or []
62
+ add_module = add_module or []
63
+ add_css = add_css or []
64
+
65
+ # Validate the input function and extract its source code
66
+ if callable(code):
67
+ # Validate that the function has a valid name
68
+ func_name: Optional[str] = getattr(code, '__name__', None)
69
+ if not func_name or not func_name.isidentifier():
70
+ raise ValueError('Provided function must have a valid name.')
71
+
72
+ # Validate that the function is a coroutine function
73
+ if not inspect.iscoroutinefunction(code):
74
+ raise TypeError(
75
+ f"{func_name!r} must be an async function; "
76
+ f"declare it as 'async def {func_name}(js, data)'."
77
+ )
78
+
79
+ # Extract function source code as a string and normalize it by left-justifying it
80
+ clean_source = textwrap.dedent(inspect.getsource(code))
81
+
82
+ execute_script = f'{clean_source}\n\n# --- Auto-generated trigger ---\nimport js\nimport json\nawait {func_name}(js, json.loads(js.JSON.stringify(js.globalThis.pys_data)))'
83
+ elif isinstance(code, str):
84
+ # If func is a string, treat it as raw source code
85
+ execute_script = code
86
+ else:
87
+ raise TypeError('code must be either a callable or a string representing the source code.')
88
+
89
+ # Encode the script in base64 for embedding in the HTML
90
+ b64_script = base64.b64encode(execute_script.encode()).decode()
91
+
92
+ # Convert config dictionaries to JSON
93
+ if isinstance(config, dict):
94
+ config_json = html.escape(json.dumps(config, allow_nan=False, ensure_ascii=False, separators=(',', ':')))
95
+ else:
96
+ raise TypeError('data must be a dictionary.')
97
+
98
+ # Convert data dictionaries to JSON
99
+ if isinstance(data, dict):
100
+ data_json = json.dumps(data, allow_nan=False, ensure_ascii=False, separators=(',', ':')).replace('<', '\\u003c')
101
+ else:
102
+ raise TypeError('data must be a dictionary.')
103
+
104
+ # Include additional scripts, modules, and CSS
105
+ script_includes = '\n' + '\n'.join([f'<script type="text/javascript" src="{html.escape(script)}"></script>' for script in add_script]) if len(add_script) > 0 else ''
106
+ module_includes = '\n' + '\n'.join([f'<script type="module" src="{html.escape(module)}"></script>' for module in add_module]) if len(add_module) > 0 else ''
107
+ css_includes = '\n' + '\n'.join([f'<link rel="stylesheet" href="{html.escape(css)}" />' for css in add_css]) if len(add_css) > 0 else ''
108
+
109
+ # Add attribute if terminal output is enabled in PyScript
110
+ terminal_attr = ' terminal' if terminal else ''
111
+
112
+ # Checking the PyScript type
113
+ if pys_type not in ('py', 'mpy', 'py-game'):
114
+ raise ValueError("Invalid pys_type. Must be one of 'mpy', 'py', or 'py-game'.")
115
+
116
+ # Assemble the HTML template (CSS {} etc. are doubled for escaping in f-string)
117
+ html_template = f"""
118
+ <!DOCTYPE html>
119
+ <html>
120
+ <head>
121
+ <meta charset="utf-8">
122
+ <script>
123
+ // Set the data JSON as a global variable
124
+ globalThis.pys_data = {data_json};
125
+
126
+ // polyscript's relative_url defaults its base to location.href:
127
+ // P = (e, t = location.href) => new URL(e, t.replace(/^blob:/, "")).href
128
+ // Inside an <iframe srcdoc>, location.href is "about:srcdoc", so config
129
+ // resolution (a non-URL config falls back to "./config.txt") throws a
130
+ // TypeError, define() fails, and PyScript never boots.
131
+ // The replace() above already strips "blob:", but "about:" is not handled.
132
+ // Patching URL before core.js loads is the only hook available:
133
+ // <base href> has no effect (the base comes from location.href, not baseURI),
134
+ // On PyScript upgrades, drop this patch and re-test. Verified against 2026.7.3.
135
+ const NativeURL = window.URL;
136
+ class PatchedURL extends NativeURL {{
137
+ constructor(url, base) {{
138
+ const b = base == null ? '' : String(base);
139
+ if (b === '' || b.startsWith('about:')) {{
140
+ base = 'https://pyscript.net/releases/{pys_version}/';
141
+ }}
142
+ super(url, base);
143
+ }}
144
+ }}
145
+ window.URL = PatchedURL;
146
+ </script>
147
+ <link rel="stylesheet" href="https://pyscript.net/releases/{pys_version}/core.css" />{css_includes}{script_includes}
148
+ <script type="module" src="https://pyscript.net/releases/{pys_version}/core.js"></script>{module_includes}
149
+ </head>
150
+ <body style="margin: 0; {html.escape(body_style)}">
151
+ {add_dangerous_html}
152
+ <script type="{pys_type}" config="{config_json}" src="data:text/python;charset=utf-8;base64,{b64_script}"{terminal_attr}></script>
153
+ </body>
154
+ </html>
155
+ """
156
+
157
+ # Wrap in an iframe and return
158
+ return mo.Html(f'<iframe srcdoc="{html.escape(html_template)}" width="{html.escape(width)}" height="{html.escape(height)}" style="{html.escape(iframe_style)}" sandbox="{html.escape(iframe_sandbox)}"></iframe>')
@@ -0,0 +1,31 @@
1
+ Metadata-Version: 2.4
2
+ Name: marimo_pys
3
+ Version: 0.0.1
4
+ Summary: PyScript Execution Function in Marimo
5
+ Author: Uniras
6
+ Author-email: tkappeng@gmail.com
7
+ License: MIT License
8
+ Project-URL: Homepage, https://github.com/uniras/pysionui
9
+ Project-URL: Repository, https://github.com/uniras/pysionui
10
+ Keywords: PyScript,Marimo
11
+ Classifier: Development Status :: 5 - Production/Stable
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Programming Language :: Python :: 3.14
20
+ Classifier: Programming Language :: Python :: 3 :: Only
21
+ Classifier: Topic :: Software Development :: Libraries
22
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
23
+ Classifier: Topic :: Utilities
24
+ Description-Content-Type: text/markdown
25
+
26
+ # marimo_pys
27
+
28
+ ## Description
29
+
30
+ marimo_pys is PyScript execute function in marimo
31
+
@@ -0,0 +1,7 @@
1
+ README.md
2
+ pyproject.toml
3
+ marimo_pys/__init__.py
4
+ marimo_pys.egg-info/PKG-INFO
5
+ marimo_pys.egg-info/SOURCES.txt
6
+ marimo_pys.egg-info/dependency_links.txt
7
+ marimo_pys.egg-info/top_level.txt
@@ -0,0 +1 @@
1
+ marimo_pys
@@ -0,0 +1,34 @@
1
+ [build-system]
2
+ requires = ["setuptools >= 61.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "marimo_pys"
7
+ version = "0.0.1"
8
+ description = "PyScript Execution Function in Marimo"
9
+ readme = "README.md"
10
+ authors = [
11
+ {name = "Uniras"},
12
+ {email = "tkappeng@gmail.com"}
13
+ ]
14
+ license = {text = "MIT License"}
15
+ keywords = ["PyScript", "Marimo"]
16
+ classifiers = [
17
+ "Development Status :: 5 - Production/Stable",
18
+ "Intended Audience :: Developers",
19
+ "License :: OSI Approved :: MIT License",
20
+ "Programming Language :: Python :: 3",
21
+ "Programming Language :: Python :: 3.10",
22
+ "Programming Language :: Python :: 3.11",
23
+ "Programming Language :: Python :: 3.12",
24
+ "Programming Language :: Python :: 3.13",
25
+ "Programming Language :: Python :: 3.14",
26
+ "Programming Language :: Python :: 3 :: Only",
27
+ "Topic :: Software Development :: Libraries",
28
+ "Topic :: Software Development :: Libraries :: Python Modules",
29
+ "Topic :: Utilities",
30
+ ]
31
+
32
+ [project.urls]
33
+ Homepage = "https://github.com/uniras/pysionui"
34
+ Repository = "https://github.com/uniras/pysionui"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+