aidiagram 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.
aidiagram/__init__.py ADDED
@@ -0,0 +1,21 @@
1
+ """PraisonAI Diagram (`aidiagram`) — interactive animated diagrams from Mermaid or YAML/JSON."""
2
+ from .html_export import render_interactive_html, runtime_info, write_interactive_html
3
+ from .importers.mermaid import (
4
+ has_opt_out_comment,
5
+ is_mermaid_source,
6
+ mermaid_to_diagram,
7
+ mermaid_to_visual,
8
+ )
9
+
10
+ __version__ = "0.1.0"
11
+
12
+ __all__ = [
13
+ "__version__",
14
+ "render_interactive_html",
15
+ "write_interactive_html",
16
+ "runtime_info",
17
+ "has_opt_out_comment",
18
+ "is_mermaid_source",
19
+ "mermaid_to_diagram",
20
+ "mermaid_to_visual",
21
+ ]
aidiagram/cli.py ADDED
@@ -0,0 +1,79 @@
1
+ """aidiagram CLI: interactive animated diagrams from Mermaid or YAML/JSON.
2
+
3
+ aidiagram html workflow.mmd [--out FILE] [--theme dark|light|auto] [--accent amber|indigo|teal|rose]
4
+ aidiagram convert workflow.mmd [--out FILE] [--format auto|yaml|json]
5
+ aidiagram info
6
+ """
7
+ import argparse
8
+ import json
9
+ import os
10
+ import pathlib
11
+ import sys
12
+
13
+ from . import __version__
14
+ from .html_export import runtime_info, write_interactive_html
15
+ from .importers.mermaid import mermaid_to_diagram
16
+
17
+
18
+ def main(argv=None):
19
+ ap = argparse.ArgumentParser(
20
+ prog="aidiagram",
21
+ description=__doc__,
22
+ formatter_class=argparse.RawDescriptionHelpFormatter,
23
+ )
24
+ ap.add_argument("--version", action="version", version=f"aidiagram {__version__}")
25
+ sub = ap.add_subparsers(dest="cmd", required=True)
26
+
27
+ h = sub.add_parser("html", help="spec (Mermaid .mmd / YAML / JSON) -> self-contained offline HTML page")
28
+ h.add_argument("spec", help="Path to a Mermaid (.mmd/.mermaid), YAML, or JSON diagram file")
29
+ h.add_argument("--out", help="Output HTML path (default: <spec>.html)")
30
+ h.add_argument("--theme", default="dark", choices=["light", "dark", "auto"])
31
+ h.add_argument("--accent", default="amber", choices=["amber", "indigo", "teal", "rose"])
32
+
33
+ cv = sub.add_parser("convert", help="Convert a supported Mermaid file into a structured diagram spec")
34
+ cv.add_argument("source", help="Path to a Mermaid (.mmd/.mermaid) file")
35
+ cv.add_argument("--out", help="Optional output path (prints to stdout if omitted)")
36
+ cv.add_argument("--format", default="auto", choices=["auto", "yaml", "json"])
37
+
38
+ sub.add_parser("info", help="Print aidiagram version and bundled browser runtime digest")
39
+
40
+ args = ap.parse_args(argv)
41
+ try:
42
+ if args.cmd == "html":
43
+ out = write_interactive_html(args.spec, args.out, theme=args.theme, accent=args.accent)
44
+ print(out)
45
+ elif args.cmd == "convert":
46
+ raw = pathlib.Path(args.source).expanduser().read_text(encoding="utf-8")
47
+ converted = mermaid_to_diagram(raw)
48
+ if converted is None:
49
+ sys.exit(f"aidiagram convert: {args.source}: unsupported or opted-out Mermaid diagram")
50
+ fmt = args.format
51
+ if fmt == "auto":
52
+ try:
53
+ import yaml # noqa: F401
54
+ fmt = "yaml"
55
+ except ImportError:
56
+ fmt = "json"
57
+ if fmt == "yaml":
58
+ import yaml
59
+ text = yaml.safe_dump(converted, sort_keys=False, allow_unicode=True)
60
+ else:
61
+ text = json.dumps(converted, indent=2, ensure_ascii=False) + "\n"
62
+ if args.out:
63
+ out_p = pathlib.Path(args.out).expanduser()
64
+ out_p.parent.mkdir(parents=True, exist_ok=True)
65
+ out_p.write_text(text, encoding="utf-8")
66
+ print(out_p)
67
+ else:
68
+ print(text, end="")
69
+ elif args.cmd == "info":
70
+ info = runtime_info()
71
+ print(json.dumps({"package": "aidiagram", "version": __version__, "runtime": info}, indent=2))
72
+ except Exception as exc:
73
+ if os.environ.get("AIDIAGRAM_DEBUG"):
74
+ raise
75
+ sys.exit(f"aidiagram {args.cmd}: {exc}")
76
+
77
+
78
+ if __name__ == "__main__":
79
+ main()
@@ -0,0 +1,159 @@
1
+ """Build a standalone, offline-ready interactive HTML page from any Mermaid/YAML/JSON spec.
2
+
3
+ Loads the versioned browser runtime and Apache-2.0 licence/notice from packaged
4
+ resources via ``importlib.resources`` so the installed wheel and sdist work
5
+ completely offline from any working directory, with zero checkout dependency and
6
+ zero external CDN requests. Exported HTML files carry an accessible copy of the
7
+ Apache-2.0 license and attribution notices alongside the embedded JS engine.
8
+ """
9
+ from importlib import resources
10
+ import hashlib
11
+ import html as _html
12
+ import json
13
+ import pathlib
14
+ import re
15
+
16
+ # Order matters: core modules first, then layouts, then Web Component.
17
+ MODULE_ORDER = (
18
+ "themes.js",
19
+ "importers/mermaid.js",
20
+ "parser.js",
21
+ "geometry.js",
22
+ "registry.js",
23
+ "svgExport.js",
24
+ "layouts/flow.js",
25
+ "layouts/fan.js",
26
+ "layouts/loop.js",
27
+ "layouts/stack.js",
28
+ "layouts/timeline.js",
29
+ "layouts/map.js",
30
+ "layouts/graph.js",
31
+ "layouts/sequence.js",
32
+ "layouts/index.js",
33
+ "styles.js",
34
+ "element.js",
35
+ )
36
+
37
+ _IMPORT_RE = re.compile(r"^\s*import\s+.*?(?:from\s+['\"][^'\"]+['\"]|['\"][^'\"]+['\"])\s*;?\s*$", re.MULTILINE)
38
+ _EXPORT_RE = re.compile(r"^\s*export\s+(?=(?:function|class|const|let|var)\b)", re.MULTILINE)
39
+ _REEXPORT_RE = re.compile(r"^\s*export\s*\{[\s\S]*?\}\s*;?\s*$", re.MULTILINE)
40
+
41
+
42
+ def _runtime_web_root():
43
+ """Return a Traversable/Path pointing to the bundled ``runtime/web`` directory."""
44
+ packaged = resources.files("aidiagram").joinpath("runtime", "web")
45
+ if packaged.joinpath("src", "themes.js").is_file():
46
+ return packaged
47
+ # Editable source checkout fallback (packages/pypi/aidiagram/src/aidiagram -> repo/web)
48
+ here = pathlib.Path(__file__).resolve()
49
+ for parent in here.parents:
50
+ candidate = parent / "web"
51
+ if (candidate / "src" / "themes.js").is_file():
52
+ return candidate
53
+ raise FileNotFoundError(
54
+ "Bundled PraisonAI Diagram browser runtime is missing (expected aidiagram/runtime/web/src/themes.js)."
55
+ )
56
+
57
+
58
+ def _read_runtime_text(web_root, *parts):
59
+ node = web_root
60
+ for part in parts:
61
+ node = node.joinpath(part)
62
+ return node.read_text(encoding="utf-8")
63
+
64
+
65
+ def _inline_runtime():
66
+ web_root = _runtime_web_root()
67
+ pkg_version = "0.1.0"
68
+ try:
69
+ pkg_meta = json.loads(_read_runtime_text(web_root, "package.json"))
70
+ if isinstance(pkg_meta.get("version"), str):
71
+ pkg_version = pkg_meta["version"]
72
+ except Exception:
73
+ pass
74
+ license_text = _read_runtime_text(web_root, "LICENSE")
75
+ notice_text = _read_runtime_text(web_root, "NOTICE")
76
+
77
+ parts = [
78
+ f"/*! PraisonAI Diagram (aidiagram {pkg_version}) | SPDX-License-Identifier: Apache-2.0 | Copyright 2026 PraisonAI */",
79
+ "(function(){'use strict';",
80
+ ]
81
+ hasher = hashlib.sha256()
82
+ for rel in MODULE_ORDER:
83
+ raw = _read_runtime_text(web_root, "src", *rel.split("/"))
84
+ hasher.update(rel.encode("utf-8"))
85
+ hasher.update(b"\0")
86
+ hasher.update(raw.encode("utf-8"))
87
+ src = _IMPORT_RE.sub("", raw)
88
+ src = _REEXPORT_RE.sub("", src)
89
+ src = _EXPORT_RE.sub("", src)
90
+ parts.append(f"// ── {rel}\n{src}")
91
+ parts.append("})();")
92
+ bundle = "\n".join(parts).replace("</script>", "<\\/script>")
93
+ return bundle, pkg_version, hasher.hexdigest(), license_text, notice_text
94
+
95
+
96
+ def runtime_info():
97
+ """Return ``{'version': ..., 'sha256': ..., 'license': 'Apache-2.0'}`` for the bundled browser runtime."""
98
+ _, version, digest, _, _ = _inline_runtime()
99
+ return {"version": version, "sha256": digest, "license": "Apache-2.0"}
100
+
101
+
102
+ def render_interactive_html(spec_text, title="PraisonAI Diagram", theme="dark", accent="amber"):
103
+ """Return a self-contained offline HTML string rendering ``spec_text`` inside <praisonai-diagram>.
104
+
105
+ Includes an accessible collapsible copy of the Apache-2.0 LICENSE and NOTICE
106
+ so standalone exported files remain compliant when shared on their own.
107
+ """
108
+ runtime, rt_version, rt_sha256, license_text, notice_text = _inline_runtime()
109
+ safe_spec = json.dumps(spec_text).replace("<", "\\u003c")
110
+ safe_title = _html.escape(title, quote=True)
111
+ safe_notice = _html.escape(notice_text.strip(), quote=False)
112
+ safe_license = _html.escape(license_text.strip(), quote=False)
113
+ bg = "#0b0f14" if theme == "dark" else "#f8fafc"
114
+ fg = "#e6edf3" if theme == "dark" else "#18181b"
115
+ muted = "#9198a1" if theme == "dark" else "#52525b"
116
+ border = "#262c36" if theme == "dark" else "#e4e4e7"
117
+ card = "#11161d" if theme == "dark" else "#ffffff"
118
+ return f"""<!doctype html>
119
+ <html lang="en">
120
+ <head>
121
+ <meta charset="utf-8" />
122
+ <meta name="viewport" content="width=device-width,initial-scale=1" />
123
+ <meta name="generator" content="aidiagram {rt_version} (runtime sha256:{rt_sha256[:12]}, Apache-2.0)" />
124
+ <title>{safe_title}</title>
125
+ <style>
126
+ body {{ margin: 0; padding: 24px; background: {bg}; color: {fg}; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif; }}
127
+ main, footer.aidiagram-legal {{ max-width: 960px; margin: 0 auto; }}
128
+ footer.aidiagram-legal {{ margin-top: 16px; font-size: 12px; color: {muted}; }}
129
+ footer.aidiagram-legal details {{ border: 1px solid {border}; border-radius: 8px; padding: 8px 12px; background: {card}; }}
130
+ footer.aidiagram-legal summary {{ cursor: pointer; font-weight: 500; }}
131
+ footer.aidiagram-legal pre {{ margin: 10px 0 0; padding: 10px; border-top: 1px solid {border}; overflow-x: auto; white-space: pre-wrap; font: 11px/1.45 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; color: {fg}; }}
132
+ </style>
133
+ </head>
134
+ <body>
135
+ <!-- aidiagram runtime version={rt_version} sha256={rt_sha256} license=Apache-2.0 -->
136
+ <main>
137
+ <praisonai-diagram id="d" theme="{theme}" accent="{accent}"></praisonai-diagram>
138
+ </main>
139
+ <footer class="aidiagram-legal" aria-label="Embedded engine license and notices">
140
+ <details>
141
+ <summary>Embedded PraisonAI Diagram engine (aidiagram {rt_version}) — Apache License 2.0 &amp; Notices</summary>
142
+ <pre aria-label="Attribution notices">{safe_notice}</pre>
143
+ <pre aria-label="Apache License 2.0 full text">{safe_license}</pre>
144
+ </details>
145
+ </footer>
146
+ <script>{runtime}</script>
147
+ <script>document.getElementById('d').spec = {safe_spec};</script>
148
+ </body>
149
+ </html>
150
+ """
151
+
152
+
153
+ def write_interactive_html(spec_path, out_path=None, theme="dark", accent="amber"):
154
+ p = pathlib.Path(spec_path).expanduser()
155
+ text = p.read_text(encoding="utf-8")
156
+ target = pathlib.Path(out_path).expanduser() if out_path else p.with_suffix(".html")
157
+ target.parent.mkdir(parents=True, exist_ok=True)
158
+ target.write_text(render_interactive_html(text, title=p.stem, theme=theme, accent=accent), encoding="utf-8")
159
+ return target
@@ -0,0 +1,4 @@
1
+ """Diagram importers for PraisonAI Diagram."""
2
+ from .mermaid import has_opt_out_comment, is_mermaid_source, mermaid_to_diagram, mermaid_to_visual
3
+
4
+ __all__ = ["has_opt_out_comment", "is_mermaid_source", "mermaid_to_diagram", "mermaid_to_visual"]