plotlyshare 1.0.9__tar.gz → 2.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.
- plotlyshare-2.0.1/LICENSE +22 -0
- plotlyshare-2.0.1/PKG-INFO +161 -0
- plotlyshare-2.0.1/README.md +119 -0
- plotlyshare-2.0.1/plotlyshare/__init__.py +23 -0
- plotlyshare-2.0.1/plotlyshare/__main__.py +95 -0
- plotlyshare-2.0.1/plotlyshare/custom_plotly_renderer.py +160 -0
- {plotlyshare-1.0.9 → plotlyshare-2.0.1}/pyproject.toml +38 -30
- plotlyshare-1.0.9/PKG-INFO +0 -44
- plotlyshare-1.0.9/README.md +0 -25
- plotlyshare-1.0.9/plotlyshare/__init__.py +0 -22
- plotlyshare-1.0.9/plotlyshare/__main__.py +0 -79
- plotlyshare-1.0.9/plotlyshare/custom_plotly_renderer.py +0 -135
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
The MIT License (MIT)
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Samarth Bhatia
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a
|
|
6
|
+
copy of this software and associated documentation files (the "Software"),
|
|
7
|
+
to deal in the Software without restriction, including without limitation
|
|
8
|
+
the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
|
9
|
+
and/or sell copies of the Software, and to permit persons to whom the
|
|
10
|
+
Software is furnished to do so, subject to the following conditions:
|
|
11
|
+
The above copyright notice and this permission notice shall be included in
|
|
12
|
+
all copies or substantial portions of the Software.
|
|
13
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
|
|
14
|
+
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
15
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
16
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
17
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
|
18
|
+
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
|
19
|
+
DEALINGS IN THE SOFTWARE.
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
This license applies to the python client.
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
Metadata-Version: 2.3
|
|
2
|
+
Name: plotlyshare
|
|
3
|
+
Version: 2.0.1
|
|
4
|
+
Summary: Link-based sharing of `plotly` plots
|
|
5
|
+
Keywords: plotly,interactive,plot
|
|
6
|
+
Author: plutonium239
|
|
7
|
+
Author-email: plutonium239 <plutonium.239.811@gmail.com>
|
|
8
|
+
License: The MIT License (MIT)
|
|
9
|
+
|
|
10
|
+
Copyright (c) 2026 Samarth Bhatia
|
|
11
|
+
|
|
12
|
+
Permission is hereby granted, free of charge, to any person obtaining a
|
|
13
|
+
copy of this software and associated documentation files (the "Software"),
|
|
14
|
+
to deal in the Software without restriction, including without limitation
|
|
15
|
+
the rights to use, copy, modify, merge, publish, distribute, sublicense,
|
|
16
|
+
and/or sell copies of the Software, and to permit persons to whom the
|
|
17
|
+
Software is furnished to do so, subject to the following conditions:
|
|
18
|
+
The above copyright notice and this permission notice shall be included in
|
|
19
|
+
all copies or substantial portions of the Software.
|
|
20
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
|
|
21
|
+
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
22
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
23
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
24
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
|
25
|
+
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
|
26
|
+
DEALINGS IN THE SOFTWARE.
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
This license applies to the python client.
|
|
30
|
+
Classifier: Programming Language :: Python :: 3
|
|
31
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
32
|
+
Classifier: Operating System :: OS Independent
|
|
33
|
+
Requires-Dist: rich
|
|
34
|
+
Requires-Dist: plotly
|
|
35
|
+
Requires-Dist: wonderwords
|
|
36
|
+
Requires-Dist: requests
|
|
37
|
+
Requires-Dist: orjson
|
|
38
|
+
Requires-Python: >=3.11
|
|
39
|
+
Project-URL: Homepage, https://github.com/plutonium-239/plotlyshare
|
|
40
|
+
Project-URL: Issues, https://github.com/plutonium-239/plotlyshare/issues
|
|
41
|
+
Description-Content-Type: text/markdown
|
|
42
|
+
|
|
43
|
+
# PlotlyShare v2 (🚀 -> 🌥)
|
|
44
|
+
[](https://pepy.tech/project/plotlyshare)
|
|
45
|
+
|
|
46
|
+
The purpose of this package is to provide a seamless way to share interactive `plotly` plots, providing a similar experience to ~~google~~ docs/etc.
|
|
47
|
+
|
|
48
|
+
The idea is to preserve the interactivity and responsiveness of `plotly` plots with the ease of **link-based sharing** and without all the hassle of sending an html file, or worse, a static image/document. Two examples:
|
|
49
|
+
- [sine noise - proportional](https://plotlyshare.pages.dev/#/plot/demo_plots/demo.da2938bdb028899928cde3467fb7bf7f)
|
|
50
|
+
- [alcoholic lord 22nd Aug](https://plotlyshare.pages.dev/#/plot/demo_plots/demo.81b9314703a002f021880c256d1660f8)
|
|
51
|
+
|
|
52
|
+
<!-- TODO: add screenshots -->
|
|
53
|
+
|
|
54
|
+
> [!TIP]
|
|
55
|
+
> If you used plotlyshare v1, go [here](https://plotlyshare.pages.dev) for migration instructions
|
|
56
|
+
|
|
57
|
+
## Installation
|
|
58
|
+
```bash
|
|
59
|
+
uv add "plotlyshare>=2"
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
```bash
|
|
63
|
+
pip install "plotlyshare>=2"
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
## First Time Setup
|
|
67
|
+
|
|
68
|
+
To use this, run `uv run -m plotlyshare setup`/`python -m plotlyshare setup` and set your ==CLI Token== as follows:
|
|
69
|
+
|
|
70
|
+
Log in to https://plotlyshare.pages.dev
|
|
71
|
+
> [!NOTE]
|
|
72
|
+
> This requires you to have a google account, as the storage (drive) is private to you. I'm working on adding a similar workflow for github as well.
|
|
73
|
+
|
|
74
|
+
Click on your profile icon, here you will see a ==CLI Token== section. Click on that to reveal it and copy the token with the copy button.
|
|
75
|
+
|
|
76
|
+
Enter that value for the `CLI_TOKEN` in the setup prompt, then it will test the connection and report back.
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
## Usage
|
|
80
|
+
And then whenever making a plot, simply import `plotlyshare` (import order doesn't matter) and set `renderer='plotlyshare'` when calling `fig.show()` like below:
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
<table style="table-layout:auto;">
|
|
84
|
+
<tr>
|
|
85
|
+
<td>
|
|
86
|
+
|
|
87
|
+
With `plotly.express`
|
|
88
|
+
|
|
89
|
+
</td>
|
|
90
|
+
<td>
|
|
91
|
+
|
|
92
|
+
With `plotly.graph_objects`
|
|
93
|
+
|
|
94
|
+
</td>
|
|
95
|
+
</tr>
|
|
96
|
+
<tr>
|
|
97
|
+
<td>
|
|
98
|
+
|
|
99
|
+
```python
|
|
100
|
+
import plotly.express as px
|
|
101
|
+
import plotlyshare
|
|
102
|
+
...
|
|
103
|
+
fig = px.line(...)
|
|
104
|
+
...
|
|
105
|
+
fig.show(renderer='plotlyshare')
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
</td>
|
|
109
|
+
<td>
|
|
110
|
+
|
|
111
|
+
```python
|
|
112
|
+
import plotly.graph_objects as go
|
|
113
|
+
import plotlyshare
|
|
114
|
+
...
|
|
115
|
+
fig = go.Figure(...)
|
|
116
|
+
...
|
|
117
|
+
fig.show(renderer='plotlyshare')
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
</td>
|
|
121
|
+
</tr>
|
|
122
|
+
</table>
|
|
123
|
+
|
|
124
|
+
<!--
|
|
125
|
+
```py
|
|
126
|
+
...
|
|
127
|
+
import plotly.express as px
|
|
128
|
+
import plotly.graph_objects as go
|
|
129
|
+
|
|
130
|
+
import plotlyshare
|
|
131
|
+
|
|
132
|
+
...
|
|
133
|
+
fig = px.line(...)
|
|
134
|
+
fig = go.Figure(...)
|
|
135
|
+
|
|
136
|
+
fig.show(renderer='plotlyshare')
|
|
137
|
+
```
|
|
138
|
+
-->
|
|
139
|
+
|
|
140
|
+
And that's it, the package will upload your plot to plotlyshare and assign it a randomly generated name with a date like *`mushy pancake 24th Jul`*.
|
|
141
|
+
It will display the name and the **direct link** to the plot, **ready to share** with anyone. Additionally, it also tells you how big the plot was so you can keep track of storage (unlikely to be a problem).
|
|
142
|
+
|
|
143
|
+
Plots are **private by default** and you can change the privacy for each plot from the dashboard.
|
|
144
|
+
|
|
145
|
+
## Misc
|
|
146
|
+
|
|
147
|
+
**Change your plot's name:**
|
|
148
|
+
|
|
149
|
+
To add a title to your plot (instead of the default randomly generated one), you can edit it from
|
|
150
|
+
1. your [online dashboard](https://plotlyshare.pages.dev/#/dash)
|
|
151
|
+
2. the plot's page
|
|
152
|
+
3. or even set it directly when uploading:
|
|
153
|
+
```python
|
|
154
|
+
fig.show(renderer='plotlyshare', plot_name='this plot has a fancy name')
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
## Screenshots:
|
|
158
|
+
|
|
159
|
+
<!--  -->
|
|
160
|
+
|
|
161
|
+

|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
# PlotlyShare v2 (🚀 -> 🌥)
|
|
2
|
+
[](https://pepy.tech/project/plotlyshare)
|
|
3
|
+
|
|
4
|
+
The purpose of this package is to provide a seamless way to share interactive `plotly` plots, providing a similar experience to ~~google~~ docs/etc.
|
|
5
|
+
|
|
6
|
+
The idea is to preserve the interactivity and responsiveness of `plotly` plots with the ease of **link-based sharing** and without all the hassle of sending an html file, or worse, a static image/document. Two examples:
|
|
7
|
+
- [sine noise - proportional](https://plotlyshare.pages.dev/#/plot/demo_plots/demo.da2938bdb028899928cde3467fb7bf7f)
|
|
8
|
+
- [alcoholic lord 22nd Aug](https://plotlyshare.pages.dev/#/plot/demo_plots/demo.81b9314703a002f021880c256d1660f8)
|
|
9
|
+
|
|
10
|
+
<!-- TODO: add screenshots -->
|
|
11
|
+
|
|
12
|
+
> [!TIP]
|
|
13
|
+
> If you used plotlyshare v1, go [here](https://plotlyshare.pages.dev) for migration instructions
|
|
14
|
+
|
|
15
|
+
## Installation
|
|
16
|
+
```bash
|
|
17
|
+
uv add "plotlyshare>=2"
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
```bash
|
|
21
|
+
pip install "plotlyshare>=2"
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
## First Time Setup
|
|
25
|
+
|
|
26
|
+
To use this, run `uv run -m plotlyshare setup`/`python -m plotlyshare setup` and set your ==CLI Token== as follows:
|
|
27
|
+
|
|
28
|
+
Log in to https://plotlyshare.pages.dev
|
|
29
|
+
> [!NOTE]
|
|
30
|
+
> This requires you to have a google account, as the storage (drive) is private to you. I'm working on adding a similar workflow for github as well.
|
|
31
|
+
|
|
32
|
+
Click on your profile icon, here you will see a ==CLI Token== section. Click on that to reveal it and copy the token with the copy button.
|
|
33
|
+
|
|
34
|
+
Enter that value for the `CLI_TOKEN` in the setup prompt, then it will test the connection and report back.
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
## Usage
|
|
38
|
+
And then whenever making a plot, simply import `plotlyshare` (import order doesn't matter) and set `renderer='plotlyshare'` when calling `fig.show()` like below:
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
<table style="table-layout:auto;">
|
|
42
|
+
<tr>
|
|
43
|
+
<td>
|
|
44
|
+
|
|
45
|
+
With `plotly.express`
|
|
46
|
+
|
|
47
|
+
</td>
|
|
48
|
+
<td>
|
|
49
|
+
|
|
50
|
+
With `plotly.graph_objects`
|
|
51
|
+
|
|
52
|
+
</td>
|
|
53
|
+
</tr>
|
|
54
|
+
<tr>
|
|
55
|
+
<td>
|
|
56
|
+
|
|
57
|
+
```python
|
|
58
|
+
import plotly.express as px
|
|
59
|
+
import plotlyshare
|
|
60
|
+
...
|
|
61
|
+
fig = px.line(...)
|
|
62
|
+
...
|
|
63
|
+
fig.show(renderer='plotlyshare')
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
</td>
|
|
67
|
+
<td>
|
|
68
|
+
|
|
69
|
+
```python
|
|
70
|
+
import plotly.graph_objects as go
|
|
71
|
+
import plotlyshare
|
|
72
|
+
...
|
|
73
|
+
fig = go.Figure(...)
|
|
74
|
+
...
|
|
75
|
+
fig.show(renderer='plotlyshare')
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
</td>
|
|
79
|
+
</tr>
|
|
80
|
+
</table>
|
|
81
|
+
|
|
82
|
+
<!--
|
|
83
|
+
```py
|
|
84
|
+
...
|
|
85
|
+
import plotly.express as px
|
|
86
|
+
import plotly.graph_objects as go
|
|
87
|
+
|
|
88
|
+
import plotlyshare
|
|
89
|
+
|
|
90
|
+
...
|
|
91
|
+
fig = px.line(...)
|
|
92
|
+
fig = go.Figure(...)
|
|
93
|
+
|
|
94
|
+
fig.show(renderer='plotlyshare')
|
|
95
|
+
```
|
|
96
|
+
-->
|
|
97
|
+
|
|
98
|
+
And that's it, the package will upload your plot to plotlyshare and assign it a randomly generated name with a date like *`mushy pancake 24th Jul`*.
|
|
99
|
+
It will display the name and the **direct link** to the plot, **ready to share** with anyone. Additionally, it also tells you how big the plot was so you can keep track of storage (unlikely to be a problem).
|
|
100
|
+
|
|
101
|
+
Plots are **private by default** and you can change the privacy for each plot from the dashboard.
|
|
102
|
+
|
|
103
|
+
## Misc
|
|
104
|
+
|
|
105
|
+
**Change your plot's name:**
|
|
106
|
+
|
|
107
|
+
To add a title to your plot (instead of the default randomly generated one), you can edit it from
|
|
108
|
+
1. your [online dashboard](https://plotlyshare.pages.dev/#/dash)
|
|
109
|
+
2. the plot's page
|
|
110
|
+
3. or even set it directly when uploading:
|
|
111
|
+
```python
|
|
112
|
+
fig.show(renderer='plotlyshare', plot_name='this plot has a fancy name')
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
## Screenshots:
|
|
116
|
+
|
|
117
|
+
<!--  -->
|
|
118
|
+
|
|
119
|
+

|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
from plotlyshare.custom_plotly_renderer import PlotlyShareRenderer
|
|
2
|
+
import json
|
|
3
|
+
import os, sys
|
|
4
|
+
|
|
5
|
+
dir_path = os.path.expanduser('~/.config/plotlyshare')
|
|
6
|
+
config_file_path = f'{dir_path}/config.json'
|
|
7
|
+
|
|
8
|
+
found_config = os.path.exists(config_file_path)
|
|
9
|
+
if found_config:
|
|
10
|
+
try:
|
|
11
|
+
with open(config_file_path) as f:
|
|
12
|
+
config = json.load(f)
|
|
13
|
+
except:
|
|
14
|
+
config = {'setup_done': False}
|
|
15
|
+
else:
|
|
16
|
+
config = {'setup_done': False}
|
|
17
|
+
|
|
18
|
+
if not found_config or not config['setup_done']:
|
|
19
|
+
from rich import print as richprint
|
|
20
|
+
richprint("[bold red]Config file not found, run [reverse]python -m plotlyshare setup[/reverse].[/bold red]")
|
|
21
|
+
else:
|
|
22
|
+
import plotly.io as pio
|
|
23
|
+
pio.renderers['plotlyshare'] = PlotlyShareRenderer(config, {})
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import os, sys, json
|
|
2
|
+
import time
|
|
3
|
+
from rich import console, pretty
|
|
4
|
+
from plotlyshare.custom_plotly_renderer import test_connection
|
|
5
|
+
|
|
6
|
+
# piped stdout on windows defaults to legacy codepage cp1252, which crashes on emojis
|
|
7
|
+
for stream in (sys.stdout, sys.stderr):
|
|
8
|
+
if stream is not None and hasattr(stream, 'reconfigure'):
|
|
9
|
+
stream.reconfigure(encoding='utf-8', errors='replace')
|
|
10
|
+
|
|
11
|
+
allowed_commands = ['setup', 'test', 'config', 'show_config']
|
|
12
|
+
assert len(sys.argv) == 2, f'Please give only one argument out of {allowed_commands}'
|
|
13
|
+
command = sys.argv[1]
|
|
14
|
+
assert command in allowed_commands, f'Given command not in {allowed_commands}'
|
|
15
|
+
|
|
16
|
+
dir_path = os.path.expanduser('~/.config/plotlyshare')
|
|
17
|
+
os.makedirs(dir_path, exist_ok=True)
|
|
18
|
+
config_file_path = f'{dir_path}/config.json'
|
|
19
|
+
|
|
20
|
+
if os.path.exists(config_file_path):
|
|
21
|
+
with open(config_file_path) as f:
|
|
22
|
+
old_config = json.load(f)
|
|
23
|
+
else:
|
|
24
|
+
old_config = {'setup_done': False}
|
|
25
|
+
|
|
26
|
+
if command == 'setup':
|
|
27
|
+
if old_config.get('setup_done'):
|
|
28
|
+
print('Previous setup detected, printing and resetting.')
|
|
29
|
+
pretty.pprint(old_config)
|
|
30
|
+
|
|
31
|
+
config = {}
|
|
32
|
+
config['optimize_template'] = True
|
|
33
|
+
|
|
34
|
+
c = console.Console()
|
|
35
|
+
|
|
36
|
+
c.print('''
|
|
37
|
+
[italic magenta]PlotlyShare v2 (🚀->⛅ ) setup in progress[/italic magenta]
|
|
38
|
+
|
|
39
|
+
Log in to https://plotlyshare.pages.dev
|
|
40
|
+
|
|
41
|
+
Click on your profile icon, here you will see a "CLI Token" section, copy the shown token
|
|
42
|
+
|
|
43
|
+
Enter that value for the "CLI_TOKEN" here:
|
|
44
|
+
''')
|
|
45
|
+
time.sleep(0.5)
|
|
46
|
+
uid_and_token = c.input('[bold #FF84AC] CLI_TOKEN: [/bold #FF84AC]')
|
|
47
|
+
if len(uid_and_token.split('//')) != 2:
|
|
48
|
+
c.print('[bold red]Setup failed:[/bold red]\nBad token, make sure you copied it correctly.')
|
|
49
|
+
exit(1)
|
|
50
|
+
config['UID'], config['CLI_TOKEN'] = uid_and_token.split('//')
|
|
51
|
+
pref_open_browser = c.input(r'[italic #FF84AC] Would you like to open the plot in a browser after plotting? (default: yes) (\[y]/n) [/italic #FF84AC]')
|
|
52
|
+
if pref_open_browser.lower() in ['n', 'no']:
|
|
53
|
+
config['open_browser_after_upload'] = False
|
|
54
|
+
else:
|
|
55
|
+
config['open_browser_after_upload'] = True
|
|
56
|
+
|
|
57
|
+
with c.status('Testing credentials...', spinner='shark'):
|
|
58
|
+
passed, display = test_connection(config['UID'], config['CLI_TOKEN'])
|
|
59
|
+
|
|
60
|
+
if passed:
|
|
61
|
+
config['setup_done'] = True
|
|
62
|
+
|
|
63
|
+
with open(config_file_path, 'w') as f:
|
|
64
|
+
json.dump(config, f, indent=4)
|
|
65
|
+
|
|
66
|
+
c.print('[bold green]Setup completed!🚀[/bold green]')
|
|
67
|
+
c.print(f'Your config has been saved to {config_file_path}')
|
|
68
|
+
else:
|
|
69
|
+
c.print('[bold red]Setup failed:[/bold red]\n'+display)
|
|
70
|
+
elif command == 'test':
|
|
71
|
+
c = console.Console()
|
|
72
|
+
assert all(key in old_config for key in ['setup_done', 'UID', 'CLI_TOKEN']), "Your config is [bold red]missing some keys[/], please run [bold white on deep_pink3]python -m plotlyshare setup[/] again."
|
|
73
|
+
if old_config.get('setup_done'):
|
|
74
|
+
with c.status('Testing credentials...', spinner='shark'):
|
|
75
|
+
passed, display = test_connection(old_config['UID'], old_config['CLI_TOKEN'])
|
|
76
|
+
|
|
77
|
+
if passed:
|
|
78
|
+
old_config['setup_done'] = True
|
|
79
|
+
c.print('[bold green]It works!🚀[/bold green]')
|
|
80
|
+
else:
|
|
81
|
+
c.print('[bold red]There was an error:[/bold red]\n'+display)
|
|
82
|
+
else:
|
|
83
|
+
c.print('Please run [bold white on deep_pink3]python -m plotlyshare setup[/] first')
|
|
84
|
+
elif command == 'show_config':
|
|
85
|
+
print(f'plotlyshare config saved at {config_file_path}:')
|
|
86
|
+
pretty.pprint(old_config)
|
|
87
|
+
elif command == 'config':
|
|
88
|
+
print(f'plotlyshare config saved at {config_file_path}:')
|
|
89
|
+
pretty.pprint(old_config)
|
|
90
|
+
if editor := os.environ.get('EDITOR'):
|
|
91
|
+
print(f'Trying to open editor {editor}')
|
|
92
|
+
import subprocess
|
|
93
|
+
subprocess.run(args=[editor, config_file_path])
|
|
94
|
+
else:
|
|
95
|
+
print('No editor configured, set the EDITOR environment variable to edit the config.')
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
import plotly.io as pio
|
|
2
|
+
import webbrowser
|
|
3
|
+
import requests
|
|
4
|
+
from datetime import datetime
|
|
5
|
+
from wonderwords import RandomWord
|
|
6
|
+
from typing import List
|
|
7
|
+
from rich import print as richprint
|
|
8
|
+
import os
|
|
9
|
+
|
|
10
|
+
# # no / at end
|
|
11
|
+
base_url = 'https://plotlyshare.pages.dev'
|
|
12
|
+
if (custom_url := os.getenv('PLOTLYSHARE_BASE_URL')) is not None:
|
|
13
|
+
base_url = custom_url
|
|
14
|
+
|
|
15
|
+
def test_connection(uid: str, cli_token: str):
|
|
16
|
+
r = requests.get(f'{base_url}/api/auth/ping_cli?user={uid}', headers={'Authorization': f'Bearer {cli_token}'})
|
|
17
|
+
# import ipdb; ipdb.set_trace()
|
|
18
|
+
if r.status_code == 200:
|
|
19
|
+
if r.text == "Hello from PlotlyShare on cloudflare! 🌥":
|
|
20
|
+
return True, 'Connected, Message Received: ' + r.text
|
|
21
|
+
elif r.status_code == 401:
|
|
22
|
+
return False, "Bad CLI Token provided, please run the setup script again with a correct one."
|
|
23
|
+
else:
|
|
24
|
+
r.raise_for_status()
|
|
25
|
+
print(f"text `{r.text}`", r.status_code)
|
|
26
|
+
return False, "Unknown error occured, please run this setup script again. "
|
|
27
|
+
|
|
28
|
+
def open_url_in_browser(url, using=None, new=0, autoraise=True):
|
|
29
|
+
"""
|
|
30
|
+
Displays the uploaded plot in a web browser.
|
|
31
|
+
|
|
32
|
+
Parameters
|
|
33
|
+
----------
|
|
34
|
+
url: str
|
|
35
|
+
URL of uploaded plot
|
|
36
|
+
using, new, autoraise:
|
|
37
|
+
See docstrings in webbrowser.get and webbrowser.open
|
|
38
|
+
"""
|
|
39
|
+
browser = None
|
|
40
|
+
|
|
41
|
+
if using is None:
|
|
42
|
+
browser = webbrowser.get(None)
|
|
43
|
+
else:
|
|
44
|
+
if not isinstance(using, tuple):
|
|
45
|
+
using = (using,)
|
|
46
|
+
for browser_key in using:
|
|
47
|
+
try:
|
|
48
|
+
browser = webbrowser.get(browser_key)
|
|
49
|
+
if browser is not None:
|
|
50
|
+
break
|
|
51
|
+
except webbrowser.Error:
|
|
52
|
+
pass
|
|
53
|
+
|
|
54
|
+
if browser is None:
|
|
55
|
+
raise ValueError("Can't locate a browser with key in " + str(using))
|
|
56
|
+
|
|
57
|
+
browser.open(url, new=new, autoraise=autoraise)
|
|
58
|
+
|
|
59
|
+
def ordinal(n): # converting dates to 1st etc
|
|
60
|
+
return str(n)+("th" if 4<=n%100<=20 else {1:"st",2:"nd",3:"rd"}.get(n%10, "th"))
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class Collection:
|
|
64
|
+
def __init__(self, name: str, collid: str, members: List[str]):
|
|
65
|
+
self.name = name
|
|
66
|
+
self.collid = collid
|
|
67
|
+
self.members = members
|
|
68
|
+
# !!! No subcollections from cli
|
|
69
|
+
# self.subcollections = subcollections
|
|
70
|
+
|
|
71
|
+
def add_plot(self, plotid):
|
|
72
|
+
self.members.append(plotid)
|
|
73
|
+
|
|
74
|
+
class PlotlyShareRenderer(pio.base_renderers.ExternalRenderer):
|
|
75
|
+
"""
|
|
76
|
+
Renderer to upload interactive figures to plotlyshare.
|
|
77
|
+
|
|
78
|
+
This can also open a new browser window or tab when the
|
|
79
|
+
show function is called on a figure (controllable by option `open_browser_after_upload`).
|
|
80
|
+
"""
|
|
81
|
+
|
|
82
|
+
def __init__(
|
|
83
|
+
self,
|
|
84
|
+
plotlyshare_config,
|
|
85
|
+
config=None,
|
|
86
|
+
auto_play=False,
|
|
87
|
+
using=None,
|
|
88
|
+
new=0,
|
|
89
|
+
autoraise=True,
|
|
90
|
+
post_script=None,
|
|
91
|
+
animation_opts=None,
|
|
92
|
+
):
|
|
93
|
+
self.config = config
|
|
94
|
+
self.plotlyshare_config = plotlyshare_config
|
|
95
|
+
self.auto_play = auto_play
|
|
96
|
+
self.using = using
|
|
97
|
+
self.new = new
|
|
98
|
+
self.autoraise = autoraise
|
|
99
|
+
self.post_script = post_script
|
|
100
|
+
self.animation_opts = animation_opts
|
|
101
|
+
|
|
102
|
+
self.base_url = base_url
|
|
103
|
+
self.auth_header = {'Authorization': f"Bearer {plotlyshare_config['CLI_TOKEN']}"}
|
|
104
|
+
self.uid = plotlyshare_config['UID']
|
|
105
|
+
self.open_browser = plotlyshare_config['open_browser_after_upload']
|
|
106
|
+
self.plot_name = None
|
|
107
|
+
self.w = RandomWord()
|
|
108
|
+
|
|
109
|
+
# TODO: add function set_default() which sets plotlyshare as default renderer (maybe unset_defafult() also)
|
|
110
|
+
|
|
111
|
+
def render(self, fig):
|
|
112
|
+
# fig is a dict
|
|
113
|
+
|
|
114
|
+
plot_data = pio.to_json(fig, engine='auto') # prefer orjson
|
|
115
|
+
assert plot_data is not None, "Plotly did not send a renderable plot."
|
|
116
|
+
|
|
117
|
+
# TODO: add readme about config option
|
|
118
|
+
# import ipdb; ipdb.set_trace()
|
|
119
|
+
if self.plotlyshare_config.get('optimize_template', False):
|
|
120
|
+
# ! pio only lazily loads templates so can't iterate over .items - weird
|
|
121
|
+
matches_base_template = [name for name in pio.templates.keys() if fig['layout']['template'] == pio.templates[name].to_plotly_json()]
|
|
122
|
+
if len(matches_base_template) == 1:
|
|
123
|
+
import json
|
|
124
|
+
plot_dict = json.loads(plot_data)
|
|
125
|
+
plot_dict['layout']['template'] = matches_base_template[0]
|
|
126
|
+
plot_data = json.dumps(plot_dict)
|
|
127
|
+
|
|
128
|
+
data = {'plot_data': plot_data}
|
|
129
|
+
now = datetime.now()
|
|
130
|
+
|
|
131
|
+
if self.plot_name:
|
|
132
|
+
data['name'] = self.plot_name
|
|
133
|
+
else:
|
|
134
|
+
data['name'] = f"{self.w.word(include_categories=['adjective'], word_max_length=10)} {self.w.word(include_categories=['noun'], word_max_length=10)}"
|
|
135
|
+
data['name'] += f" {ordinal(now.day)} {now.strftime('%b')}"
|
|
136
|
+
|
|
137
|
+
data['timestamp'] = str(now.timestamp()).split('.')[0]
|
|
138
|
+
data['time'] = now.astimezone().strftime('%Y-%m-%dT%H:%M:%S%z') # seconds since epoch and timezone
|
|
139
|
+
|
|
140
|
+
r = requests.post(self.base_url+'/api/upload?user='+self.uid, data=data, headers=self.auth_header)
|
|
141
|
+
if not r.ok:
|
|
142
|
+
richprint(f"[bold on magenta] PlotlyShare: [/] [red]The server sent an error response[/]")
|
|
143
|
+
r.raise_for_status()
|
|
144
|
+
|
|
145
|
+
# print(r.content)
|
|
146
|
+
res = r.json()
|
|
147
|
+
plot_url = self.base_url+'#/plot/'+res['key']
|
|
148
|
+
richprint(f"[bold on magenta] PlotlyShare: [/] New plot [cyan italic]{data['name']}[/]", end='')
|
|
149
|
+
# hacky but it works, idk why the whole thing in richprint has issues
|
|
150
|
+
print(f" created at {plot_url} of size {res['sent_bytes']/1024 :.2f}kB")
|
|
151
|
+
|
|
152
|
+
if self.open_browser:
|
|
153
|
+
open_url_in_browser(plot_url, self.using, self.new, self.autoraise)
|
|
154
|
+
|
|
155
|
+
# Reset plot name to check if passed next time
|
|
156
|
+
self.plot_name = None
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
# def start_collection(self, name) -> Collection:
|
|
160
|
+
# collid = random
|
|
@@ -1,30 +1,38 @@
|
|
|
1
|
-
[build-system]
|
|
2
|
-
build-backend = "
|
|
3
|
-
requires = ["
|
|
4
|
-
|
|
5
|
-
[project]
|
|
6
|
-
name = "plotlyshare"
|
|
7
|
-
version = "
|
|
8
|
-
authors = [{name="plutonium239", email="plutonium.239.811@gmail.com"}]
|
|
9
|
-
description = "Link-based sharing of `plotly` plots
|
|
10
|
-
readme = "README.md"
|
|
11
|
-
requires-python = ">=3.
|
|
12
|
-
classifiers = [
|
|
13
|
-
"Programming Language :: Python :: 3",
|
|
14
|
-
"License :: OSI Approved :: MIT License",
|
|
15
|
-
"Operating System :: OS Independent"
|
|
16
|
-
]
|
|
17
|
-
dependencies = [
|
|
18
|
-
"rich",
|
|
19
|
-
"plotly",
|
|
20
|
-
"wonderwords",
|
|
21
|
-
"requests"
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
1
|
+
[build-system]
|
|
2
|
+
build-backend = "uv_build"
|
|
3
|
+
requires = ["uv_build >=0.8.2,<0.9.0"]
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "plotlyshare"
|
|
7
|
+
version = "2.0.1"
|
|
8
|
+
authors = [{name="plutonium239", email="plutonium.239.811@gmail.com"}]
|
|
9
|
+
description = "Link-based sharing of `plotly` plots"
|
|
10
|
+
readme = "README.md"
|
|
11
|
+
requires-python = ">=3.11"
|
|
12
|
+
classifiers = [
|
|
13
|
+
"Programming Language :: Python :: 3",
|
|
14
|
+
"License :: OSI Approved :: MIT License",
|
|
15
|
+
"Operating System :: OS Independent"
|
|
16
|
+
]
|
|
17
|
+
dependencies = [
|
|
18
|
+
"rich",
|
|
19
|
+
"plotly",
|
|
20
|
+
"wonderwords",
|
|
21
|
+
"requests",
|
|
22
|
+
"orjson"
|
|
23
|
+
]
|
|
24
|
+
keywords = ["plotly", "interactive", "plot"]
|
|
25
|
+
license = { file = "LICENSE" }
|
|
26
|
+
|
|
27
|
+
[project.urls]
|
|
28
|
+
Homepage = "https://github.com/plutonium-239/plotlyshare"
|
|
29
|
+
Issues = "https://github.com/plutonium-239/plotlyshare/issues"
|
|
30
|
+
|
|
31
|
+
[tool.uv.build-backend]
|
|
32
|
+
module-root = ""
|
|
33
|
+
|
|
34
|
+
[[tool.uv.index]]
|
|
35
|
+
name = "testpypi"
|
|
36
|
+
url = "https://test.pypi.org/simple/"
|
|
37
|
+
publish-url = "https://test.pypi.org/legacy/"
|
|
38
|
+
explicit = true
|
plotlyshare-1.0.9/PKG-INFO
DELETED
|
@@ -1,44 +0,0 @@
|
|
|
1
|
-
Metadata-Version: 2.1
|
|
2
|
-
Name: plotlyshare
|
|
3
|
-
Version: 1.0.9
|
|
4
|
-
Summary: Link-based sharing of `plotly` plots with a private web app
|
|
5
|
-
Keywords: plotly,interactive,plot
|
|
6
|
-
Author-email: plutonium239 <plutonium.239.811@gmail.com>
|
|
7
|
-
Requires-Python: >=3.7
|
|
8
|
-
Description-Content-Type: text/markdown
|
|
9
|
-
Classifier: Programming Language :: Python :: 3
|
|
10
|
-
Classifier: License :: OSI Approved :: MIT License
|
|
11
|
-
Classifier: Operating System :: OS Independent
|
|
12
|
-
Requires-Dist: rich
|
|
13
|
-
Requires-Dist: plotly
|
|
14
|
-
Requires-Dist: wonderwords
|
|
15
|
-
Requires-Dist: requests
|
|
16
|
-
Project-URL: Homepage, https://github.com/plutonium-239/plotlyshare
|
|
17
|
-
Project-URL: Issues, https://github.com/plutonium-239/plotlyshare/issues
|
|
18
|
-
|
|
19
|
-
# `plotlyshare`
|
|
20
|
-
[](https://pepy.tech/project/plotlyshare)
|
|
21
|
-
|
|
22
|
-
The purpose of this package is to provide a seamless way to share interactive `plotly` plots, providing a similar experience to google docs/etc.
|
|
23
|
-
|
|
24
|
-
This requires a free account on deta space: https://deta.space, which is essentially a *personal* cloud computer *at no cost*.
|
|
25
|
-
|
|
26
|
-
The idea is to preserve the interactivity and responsiveness of `plotly` plots with the ease of **link-based sharing** and without all the hassle of sending an html file, or worse, a static image/document.
|
|
27
|
-
|
|
28
|
-
To use this, first run `python -m plotlyshare setup` and install [plotlyshare on deta space](https://deta.space/discovery/@pu239/plotlyshare) .
|
|
29
|
-
And then whenever making a plot,
|
|
30
|
-
|
|
31
|
-
```py
|
|
32
|
-
...
|
|
33
|
-
import plotly.express as px
|
|
34
|
-
import plotly.graph_objects as go
|
|
35
|
-
import plotlyshare
|
|
36
|
-
...
|
|
37
|
-
fig = px.line(...)
|
|
38
|
-
fig = go.Figure(...)
|
|
39
|
-
fig.show(renderer='plotlyshare')
|
|
40
|
-
```
|
|
41
|
-
|
|
42
|
-
and that's it, the package will upload your plot to your instance of plotlyshare running in deta space and assign it a randomly generated name (which can be edited from the app's page)
|
|
43
|
-
It will print the name that was generated and the direct link to the plot, ready to share with anyone.
|
|
44
|
-
|
plotlyshare-1.0.9/README.md
DELETED
|
@@ -1,25 +0,0 @@
|
|
|
1
|
-
# `plotlyshare`
|
|
2
|
-
[](https://pepy.tech/project/plotlyshare)
|
|
3
|
-
|
|
4
|
-
The purpose of this package is to provide a seamless way to share interactive `plotly` plots, providing a similar experience to google docs/etc.
|
|
5
|
-
|
|
6
|
-
This requires a free account on deta space: https://deta.space, which is essentially a *personal* cloud computer *at no cost*.
|
|
7
|
-
|
|
8
|
-
The idea is to preserve the interactivity and responsiveness of `plotly` plots with the ease of **link-based sharing** and without all the hassle of sending an html file, or worse, a static image/document.
|
|
9
|
-
|
|
10
|
-
To use this, first run `python -m plotlyshare setup` and install [plotlyshare on deta space](https://deta.space/discovery/@pu239/plotlyshare) .
|
|
11
|
-
And then whenever making a plot,
|
|
12
|
-
|
|
13
|
-
```py
|
|
14
|
-
...
|
|
15
|
-
import plotly.express as px
|
|
16
|
-
import plotly.graph_objects as go
|
|
17
|
-
import plotlyshare
|
|
18
|
-
...
|
|
19
|
-
fig = px.line(...)
|
|
20
|
-
fig = go.Figure(...)
|
|
21
|
-
fig.show(renderer='plotlyshare')
|
|
22
|
-
```
|
|
23
|
-
|
|
24
|
-
and that's it, the package will upload your plot to your instance of plotlyshare running in deta space and assign it a randomly generated name (which can be edited from the app's page)
|
|
25
|
-
It will print the name that was generated and the direct link to the plot, ready to share with anyone.
|
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
from plotlyshare.custom_plotly_renderer import PlotlyShareRenderer
|
|
2
|
-
import json
|
|
3
|
-
import os, sys
|
|
4
|
-
|
|
5
|
-
dir_path = os.path.dirname(os.path.realpath(__file__))
|
|
6
|
-
config_file_path = f'{dir_path}/config.json'
|
|
7
|
-
|
|
8
|
-
found_config = os.path.exists(config_file_path)
|
|
9
|
-
if found_config:
|
|
10
|
-
with open(config_file_path) as f:
|
|
11
|
-
config = json.load(f)
|
|
12
|
-
else:
|
|
13
|
-
config = {'setup_done': False}
|
|
14
|
-
|
|
15
|
-
if not found_config or not config['setup_done']:
|
|
16
|
-
from rich import console
|
|
17
|
-
from rich.markdown import Markdown
|
|
18
|
-
c = console.Console()
|
|
19
|
-
c.print("[bold red]Config file not found, run [reverse]python -m plotlyshare setup[/reverse].[/bold red]")
|
|
20
|
-
else:
|
|
21
|
-
import plotly.io as pio
|
|
22
|
-
pio.renderers['plotlyshare'] = PlotlyShareRenderer(config, {})
|
|
@@ -1,79 +0,0 @@
|
|
|
1
|
-
import os, sys, json
|
|
2
|
-
import time
|
|
3
|
-
from rich import console, pretty
|
|
4
|
-
from plotlyshare.custom_plotly_renderer import test_connection
|
|
5
|
-
|
|
6
|
-
allowed_commands = ['setup', 'test']
|
|
7
|
-
assert len(sys.argv) == 2, f'Please give only one argument out of {allowed_commands}'
|
|
8
|
-
command = sys.argv[1]
|
|
9
|
-
assert command in allowed_commands, f'Given command not in {allowed_commands}'
|
|
10
|
-
|
|
11
|
-
dir_path = os.path.dirname(os.path.realpath(__file__))
|
|
12
|
-
config_file_path = f'{dir_path}/config.json'
|
|
13
|
-
|
|
14
|
-
if os.path.exists(config_file_path):
|
|
15
|
-
with open(config_file_path) as f:
|
|
16
|
-
old_config = json.load(f)
|
|
17
|
-
else:
|
|
18
|
-
old_config = {'setup_done': False}
|
|
19
|
-
|
|
20
|
-
if command == 'setup':
|
|
21
|
-
if old_config['setup_done']:
|
|
22
|
-
print('Previous setup detected, printing and resetting.')
|
|
23
|
-
pretty.pprint(old_config)
|
|
24
|
-
|
|
25
|
-
old_config['setup_done'] = False
|
|
26
|
-
with open(config_file_path, 'w') as f:
|
|
27
|
-
json.dump(old_config, f, indent=4)
|
|
28
|
-
|
|
29
|
-
config = {}
|
|
30
|
-
|
|
31
|
-
c = console.Console()
|
|
32
|
-
|
|
33
|
-
c.print('''
|
|
34
|
-
[italic magenta]PlotlyShare on Deta Space 🚀 setup in progress[/italic magenta]
|
|
35
|
-
|
|
36
|
-
Please make an account on deta space: https://deta.space
|
|
37
|
-
|
|
38
|
-
Then, install the app 'PlotlyShare' on your personal space from this link:
|
|
39
|
-
https://deta.space/discovery/@pu239/plotlyshare
|
|
40
|
-
|
|
41
|
-
Once you have done that, open the newly installed app from your horizon (home screen in deta space) by
|
|
42
|
-
just typing 'PlotlyShare' or double clicking the icon. This will open the app in a new tab.
|
|
43
|
-
|
|
44
|
-
Then, click on the 'How do I set this up?' button on the bottom.
|
|
45
|
-
Read the instructions there and enter the values for 'DETA_APP_URL' and 'DETA_PROJECT_KEY' one by one:
|
|
46
|
-
''')
|
|
47
|
-
time.sleep(0.5)
|
|
48
|
-
config['DETA_APP_URL'] = c.input('[bold #FF84AC] DETA_APP_URL: [/bold #FF84AC]')
|
|
49
|
-
config['DETA_PROJECT_KEY'] = c.input('[bold #FF84AC] DETA_PROJECT_KEY: [/bold #FF84AC]')
|
|
50
|
-
pref_open_browser = c.input(r'[italic #FF84AC] Would you like to open the plot in a browser after plotting? (default: yes) (\[y]/n) [/italic #FF84AC]')
|
|
51
|
-
print(pref_open_browser)
|
|
52
|
-
if pref_open_browser.lower() in ['n', 'no']:
|
|
53
|
-
config['open_browser_after_upload'] = False
|
|
54
|
-
else:
|
|
55
|
-
config['open_browser_after_upload'] = True
|
|
56
|
-
|
|
57
|
-
with c.status('Testing credentials...', spinner='shark'):
|
|
58
|
-
passed, display = test_connection(config['DETA_APP_URL'], config['DETA_PROJECT_KEY'])
|
|
59
|
-
|
|
60
|
-
if passed:
|
|
61
|
-
config['setup_done'] = True
|
|
62
|
-
|
|
63
|
-
with open(config_file_path, 'w') as f:
|
|
64
|
-
json.dump(config, f, indent=4)
|
|
65
|
-
|
|
66
|
-
c.print('[bold green]Setup completed!🚀[/bold green]')
|
|
67
|
-
else:
|
|
68
|
-
c.print('[bold red]Setup failed:[/bold red]\n'+display)
|
|
69
|
-
elif command == 'test':
|
|
70
|
-
if old_config['setup_done']:
|
|
71
|
-
c = console.Console()
|
|
72
|
-
with c.status('Testing credentials...', spinner='shark'):
|
|
73
|
-
passed, display = test_connection(old_config['DETA_APP_URL'], old_config['DETA_PROJECT_KEY'])
|
|
74
|
-
|
|
75
|
-
if passed:
|
|
76
|
-
old_config['setup_done'] = True
|
|
77
|
-
c.print('[bold green]It works!🚀[/bold green]')
|
|
78
|
-
else:
|
|
79
|
-
c.print('[bold red]There was an error:[/bold red]\n'+display)
|
|
@@ -1,135 +0,0 @@
|
|
|
1
|
-
import plotly.io as pio
|
|
2
|
-
import webbrowser
|
|
3
|
-
import requests
|
|
4
|
-
from datetime import datetime
|
|
5
|
-
from wonderwords import RandomWord
|
|
6
|
-
|
|
7
|
-
def test_connection(url, prj_key):
|
|
8
|
-
r = requests.get(url+'/ping', headers={'X-API-Key': prj_key})
|
|
9
|
-
if r.status_code == 200:
|
|
10
|
-
if r.text == "Hello from PlotlyShare on Space! 🚀":
|
|
11
|
-
return True, 'Connected, Message Received: ' + r.text
|
|
12
|
-
elif 'Authorization | Deta Space' in r.text:
|
|
13
|
-
return False, "No project key provided, please run this setup script again."
|
|
14
|
-
elif r.text == 'not found\n':
|
|
15
|
-
return False, "Bad app url provided, please run this setup script again."
|
|
16
|
-
elif r.status_code == 401:
|
|
17
|
-
return False, "Bad project key provided, please run this setup script again."
|
|
18
|
-
else:
|
|
19
|
-
r.raise_for_status()
|
|
20
|
-
return False, "Unknown error occured, please run this setup script again. "
|
|
21
|
-
|
|
22
|
-
def open_url_in_browser(url, using=None, new=0, autoraise=True):
|
|
23
|
-
"""
|
|
24
|
-
Displays the uploaded plot in a web browser.
|
|
25
|
-
|
|
26
|
-
Parameters
|
|
27
|
-
----------
|
|
28
|
-
url: str
|
|
29
|
-
URL of uploaded plot
|
|
30
|
-
using, new, autoraise:
|
|
31
|
-
See docstrings in webbrowser.get and webbrowser.open
|
|
32
|
-
"""
|
|
33
|
-
browser = None
|
|
34
|
-
|
|
35
|
-
if using is None:
|
|
36
|
-
browser = webbrowser.get(None)
|
|
37
|
-
else:
|
|
38
|
-
if not isinstance(using, tuple):
|
|
39
|
-
using = (using,)
|
|
40
|
-
for browser_key in using:
|
|
41
|
-
try:
|
|
42
|
-
browser = webbrowser.get(browser_key)
|
|
43
|
-
if browser is not None:
|
|
44
|
-
break
|
|
45
|
-
except webbrowser.Error:
|
|
46
|
-
pass
|
|
47
|
-
|
|
48
|
-
if browser is None:
|
|
49
|
-
raise ValueError("Can't locate a browser with key in " + str(using))
|
|
50
|
-
|
|
51
|
-
browser.open(url, new=new, autoraise=autoraise)
|
|
52
|
-
|
|
53
|
-
def ordinal(n): # converting dates to 1st etc
|
|
54
|
-
return str(n)+("th" if 4<=n%100<=20 else {1:"st",2:"nd",3:"rd"}.get(n%10, "th"))
|
|
55
|
-
|
|
56
|
-
class PlotlyShareRenderer(pio.base_renderers.ExternalRenderer):
|
|
57
|
-
"""
|
|
58
|
-
Renderer to upload interactive figures to your personal Deta Space.
|
|
59
|
-
This can also open a new browser window or tab when the
|
|
60
|
-
show function is called on a figure (controllable by option `open_browser_after_upload`).
|
|
61
|
-
|
|
62
|
-
mime type: 'text/html'
|
|
63
|
-
"""
|
|
64
|
-
|
|
65
|
-
def __init__(
|
|
66
|
-
self,
|
|
67
|
-
plotlyshare_config,
|
|
68
|
-
config=None,
|
|
69
|
-
auto_play=False,
|
|
70
|
-
using=None,
|
|
71
|
-
new=0,
|
|
72
|
-
autoraise=True,
|
|
73
|
-
post_script=None,
|
|
74
|
-
animation_opts=None,
|
|
75
|
-
):
|
|
76
|
-
self.config = config
|
|
77
|
-
self.auto_play = auto_play
|
|
78
|
-
self.using = using
|
|
79
|
-
self.new = new
|
|
80
|
-
self.autoraise = autoraise
|
|
81
|
-
self.post_script = post_script
|
|
82
|
-
self.animation_opts = animation_opts
|
|
83
|
-
|
|
84
|
-
self.base_url = plotlyshare_config['DETA_APP_URL']
|
|
85
|
-
self.auth_header = {'X-API-Key': plotlyshare_config['DETA_PROJECT_KEY']}
|
|
86
|
-
self.open_browser = plotlyshare_config['open_browser_after_upload']
|
|
87
|
-
self.plot_name = None
|
|
88
|
-
self.w = RandomWord()
|
|
89
|
-
|
|
90
|
-
def render(self, fig):
|
|
91
|
-
# fig is a dict
|
|
92
|
-
from plotly.io import to_html
|
|
93
|
-
|
|
94
|
-
html = to_html(
|
|
95
|
-
fig,
|
|
96
|
-
config=self.config,
|
|
97
|
-
auto_play=self.auto_play,
|
|
98
|
-
include_plotlyjs="cdn",
|
|
99
|
-
include_mathjax="cdn",
|
|
100
|
-
post_script=self.post_script,
|
|
101
|
-
full_html=True,
|
|
102
|
-
animation_opts=self.animation_opts,
|
|
103
|
-
default_width="100%",
|
|
104
|
-
default_height="100%",
|
|
105
|
-
validate=False,
|
|
106
|
-
)
|
|
107
|
-
|
|
108
|
-
data = {'html_text': html}
|
|
109
|
-
now = datetime.now()
|
|
110
|
-
|
|
111
|
-
if self.plot_name:
|
|
112
|
-
data['name'] = self.plot_name
|
|
113
|
-
else:
|
|
114
|
-
data['name'] = f"{self.w.word(include_categories=['adjective'], word_max_length=10)} {self.w.word(include_categories=['noun'], word_max_length=10)}"
|
|
115
|
-
data['name'] += f" {ordinal(now.day)} {now.strftime('%b')}"
|
|
116
|
-
|
|
117
|
-
data['timestamp'] = str(now.timestamp()).split('.')[0]
|
|
118
|
-
data['time'] = now.astimezone().strftime('%Y-%m-%dT%H:%M:%S%z') # seconds since epoch and timezone
|
|
119
|
-
|
|
120
|
-
r = requests.post(self.base_url+'/upload', data=data, headers=self.auth_header)
|
|
121
|
-
if not r.ok:
|
|
122
|
-
print(f"PlotlyShare: The server at {self.base_url+'/upload'} sent an error response")
|
|
123
|
-
r.raise_for_status()
|
|
124
|
-
|
|
125
|
-
# print(r.content)
|
|
126
|
-
res = r.json()
|
|
127
|
-
plot_url = self.base_url+'/plot/'+res['key']
|
|
128
|
-
print(f"PlotlyShare: New plot {data['name']} created at {plot_url} of size {res['sent_bytes']/1024 :.2f}kB")
|
|
129
|
-
|
|
130
|
-
if self.open_browser:
|
|
131
|
-
open_url_in_browser(plot_url, self.using, self.new, self.autoraise)
|
|
132
|
-
|
|
133
|
-
# Reset plot name to check if passed next time
|
|
134
|
-
self.plot_name = None
|
|
135
|
-
|