Py.Cafe

ramnathv/

streamlit-pycafe-url-generator

Streamlit PyCafe URL Generator

DocsPricing
  • app.py
  • requirements.txt
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
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)