import json
import gzip
import base64
from urllib.parse import quote
def generate_pycafe_url(snippet_json: dict) -> str:
"""
Generate a py.cafe URL from a JSON snippet.
Args:
snippet_json (dict): JSON snippet, e.g., {"code": "...", "requirements": "...", ...}
Returns:
str: A py.cafe URL containing the snippet
"""
# Convert JSON dict to bytes
json_bytes = json.dumps(snippet_json).encode('utf-8')
# Compress with gzip
compressed = gzip.compress(json_bytes)
# Encode in base64url
b64url = base64.urlsafe_b64encode(compressed).decode('utf-8').rstrip("=")
# Construct URL
url = f"https://py.cafe/snippet/{snippet_json['type']}/v1?#c={quote(b64url)}"
return url
# Example usage:
snippet = {
"code": "from dash import Dash, html\napp = Dash()\napp.layout = html.H1('Hello, Dash')",
"requirements": "dash",
"type": "dash",
"python": "pyodide-v0.27.2",
"layout": {
"version": 2,
"rootRow": {
"type": "row",
"children": [
{
"type": "tabset",
"width": 150,
"minWidth": 30,
"minHeight": 30,
"id": "fileBrowserContainer",
"children": [
{
"type": "file-browser",
"path": ""
}
]
},
{
"type": "tabset",
"children": [
{"type": "tab", "path": "app.py"},
{"type": "tab", "path": "requirements.txt"}
]
},
{
"type": "row",
"children": [
{
"type": "tabset",
"minWidth": 30,
"minHeight": 30,
"id": "browserContainer",
"children": [{"type": "browser"}]
},
{
"type": "tabset",
"height": 175,
"minWidth": 30,
"minHeight": 30,
"id": "terminalContainer",
"children": [{"type": "terminal"}]
}
]
}
]
}
},
"files": [],
}
url = generate_pycafe_url(snippet)
import streamlit as st
st.link_button("PyCafe...", url)