├── LICENSE ├── README.md └── examples ├── Readme.md ├── pyscript_pandas.html └── pyscript_random_gen.html /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Tirthajyoti Sarkar 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # PyScript-examples 2 | Examples of web pages developed with PyScript framework 3 | 4 | ## What is PyScript? 5 | From their [Github repo](https://github.com/pyscript/pyscript) 6 | > PyScript is a meta project that aims to combine multiple open technologies to create a framework for users to use Python (and other languages) to create sophisticated applications in the browser. It highly integrates with the way the DOM works in the browser and allows users to add logic, in Python, in a way that feels natural to web as well as Python developers. 7 | 8 | ## No installation needed 9 | To write Python code inside your HTML, just add these assets in your script inside the `...` 10 | ``` 11 | 12 | 13 | ``` 14 | -------------------------------------------------------------------------------- /examples/Readme.md: -------------------------------------------------------------------------------- 1 | ## Examples 2 | - Random number generation using NumPy ([HTML source](https://github.com/tirthajyoti/PyScript-examples/blob/main/examples/pyscript_random_gen.html), [Github page](https://tirthajyoti.github.io/pyscript_random_gen.html)) 3 | - Basic Pandas demo ([HTML source](https://github.com/tirthajyoti/PyScript-examples/blob/main/examples/pyscript_pandas.html), [Github page](https://tirthajyoti.github.io/pyscript_pandas.html)) 4 | -------------------------------------------------------------------------------- /examples/pyscript_pandas.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | PyScript Pandas Demo 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | - matplotlib 15 | - pandas 16 | - lxml 17 | 18 | 55 | 56 | 57 | 58 |
59 |
60 |

Pandas operations Demo using PyScript

61 |

Demo developed by Dr. Tirthajyoti sarkar

62 | Check out the announcement from Anaconda about PyScript framework 63 |
64 |
65 | 73 |

Test: Random integers

74 |
75 |
76 |

PyScript loading and initializing...

77 |
78 | 79 | import matplotlib.pyplot as plt 80 | import numpy as np 81 | integers = np.random.randint(0,100,100) 82 | fig1,ax1 = plt.subplots(1,1,dpi=150,figsize=(5,2)) 83 | ax1.hist(integers,bins=20,edgecolor='k',color='blue') 84 | ax1.set_title("Histogram of random integers",fontsize=11) 85 | pyscript.write('test-plot',fig1) 86 | 87 |
88 |
89 |

Pandas - random dataframe

90 | Let's generate a Pandas DataFrame with some random nunbers (drawn from the ubiquitous Gaussian Normal distribution). 91 | 95 |
97 |
98 |
99 |
100 |

Interested in the statistics of this dataset?

101 | 106 |
108 |
109 |
110 |
111 |

Download file and analyze

112 | Now, we will download a CSV file from an externally hosted URL (a GitHub repo) and show its contents and statistics. 113 |
114 | 116 |
119 |
120 |
121 |

First 5 records of the downloaded file

122 |
123 |
124 |

Statistics of the downloaded file

125 |
126 |
127 | 128 | import pandas as pd, numpy as np 129 | from js import document 130 | from pyodide.http import open_url 131 | 132 | def random_table(n_cols=5,n_rows=20,*ags, **kws): 133 | cols = ['Col-'+str(i) for i in range(1,n_cols+1)] 134 | idx = ['Row-'+str(i) for i in range(1,n_rows+1)] 135 | data = np.round(np.random.normal(size=(n_rows,n_cols)),2) 136 | df = pd.DataFrame(data,columns=cols,index=idx) 137 | return df 138 | 139 | def show_table(*ags, **kws): 140 | out = Element('pandas-output') 141 | random_df = random_table() 142 | out.write(random_df.to_html(classes='pd-table')) 143 | 144 | def show_stats(*ags, **kws): 145 | out = Element('pandas-ops') 146 | input_div = document.getElementById("pandas-output") 147 | html_data = input_div.children[0].outerHTML 148 | df = pd.read_html(html_data,flavor='lxml')[0] 149 | stats_df = df.describe() 150 | out.write(stats_df.to_html(classes='pd-table')) 151 | 152 | def download_analyze(*ags, **kws): 153 | url=document.getElementById('file-url').value 154 | try: 155 | df = pd.read_csv(open_url(url)) 156 | pyscript.write('url-file-head',df.head(5).to_html(classes='pd-table')) 157 | pyscript.write('url-file-ops',df.describe().to_html(classes='pd-table')) 158 | except: 159 | pyscript.write('url-file-head',"Could not access the file") 160 | 161 |
162 | 163 | 164 | -------------------------------------------------------------------------------- /examples/pyscript_random_gen.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | PyScript Random Number Generation 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | - matplotlib 15 | 16 | 17 | 18 | 19 |
20 |
21 |

Random number generation using PyScript

22 |

Demo developed by Dr. Tirthajyoti sarkar

23 | Check out the announcement from Anaconda about PyScript framework 24 |
25 |
26 | 34 |

Test: Random integers

35 |

These are 100 random integers, generated by NumPy

36 |

We literally wrote this pure Python code in the HTML file to generate these numbers! If you don't believe us, just right-click and view the source code of this page :-) 37 | The only thing to note here is the <py-script></py-script> tags around the code block. 38 |

39 |
 40 | <py-script>
 41 | import numpy as np
 42 | integers = np.random.randint(0,100,100)
 43 | print(integers)
 44 | </py-script>
45 | 46 | import numpy as np 47 | integers = np.random.randint(0,100,100) 48 | print(integers) 49 | 50 |
51 |

This is the histogram of those random integers, generated by Matplotlib

52 |

You can do all the usual Matplotlib tweaks and tricks with the visualization as you would in a normal Python script or Jupyter Notebook. 53 | Here, we have just set the dpi=150 and figsize=(5,2) inside the plt.subplots() function. 54 |

This code is inline too i.e., embedded with this HTML. So, feel free to check it out. The last line of the Python code block is just the figure object fig1. 55 | This tells the PyScript framework to output the object/image (it detects the type intelligently) to the corresponding div section. 56 |

57 |
58 | 59 | import matplotlib.pyplot as plt 60 | fig1,ax1 = plt.subplots(1,1,dpi=150,figsize=(5,2)) 61 | ax1.hist(integers,bins=20,edgecolor='k',color='blue') 62 | ax1.set_title("Histogram of random integers",fontsize=11) 63 | fig1 64 | 65 |
66 |
67 |

Changing the image output method

68 |

In the next section, we generate histogram based on the type of the distribution that the user (you) choses. 69 | We slightly change the output method for this 70 | as we grab the div element where we want to display the image and write the figure object with a code like out.write(fig1)

71 | 78 |

User-defined random variate generation

79 |

How many random variates to generate? (if left blank, 10 values will be generated)

80 | 81 | 82 |
84 |
85 |
87 |
88 |

Choose the type of distribution you want to generate random variates from

89 |

As you expect, every time the button is clicked, you will see a new histogram. 90 | All that computation is happening with pure Python code and in your browser!

91 | 96 |
97 |

Adjust the number of random variates

98 | 100 | 500 101 |
102 |
104 |
105 | 106 | 107 | 108 | import numpy as np 109 | import matplotlib.pyplot as plt 110 | 111 | out = Element("outputDiv") 112 | input_num = Element("how-many") 113 | dist_type = Element("dist").value 114 | out2 = Element("outputDiv2") 115 | 116 | def random_num(n): 117 | """ 118 | """ 119 | r = np.random.normal(size=n) 120 | return np.array2string(r) 121 | 122 | def clear(*ags, **kws): 123 | out = Element("outputDiv") 124 | out.clear() 125 | 126 | def print_num(*ags, **kws): 127 | if input_num.value=='': 128 | n = 10 129 | else: 130 | n = int(input_num.value) 131 | r = random_num(n) 132 | out.write(f"Here are {n} random variates from Normal distribution: {r}") 133 | 134 | def show_dist(*ags, **kws): 135 | dist_type = Element("dist").value 136 | dist_size = int(Element("slider-num-var").value) 137 | fig1,ax1 = plt.subplots(1,1,dpi=150,figsize=(6,4)) 138 | fig1.subplots_adjust(hspace=0.25) 139 | if dist_type=='Gaussian': 140 | data = np.random.normal(size=dist_size) 141 | ax1.hist(data,bins=20,edgecolor='k',color='blue') 142 | ax1.set_title(f"Histogram of Normal (Gaussian) Distribution \nwith {dist_size} random variates",fontsize=11) 143 | out2.write(fig1) 144 | if dist_type=='Beta': 145 | data = np.random.beta(1,3,size=dist_size) 146 | ax1.hist(data,bins=20,edgecolor='k',color='blue') 147 | ax1.set_title(f"Histogram of Beta Distribution \nwith {dist_size} random variates",fontsize=11) 148 | out2.write(fig1) 149 | if dist_type=='Exponential': 150 | data = np.random.exponential(0.5,size=dist_size) 151 | ax1.hist(data,bins=20,edgecolor='k',color='blue') 152 | ax1.set_title(f"Histogram of Exponential Distribution \nwith {dist_size} random variates",fontsize=11) 153 | out2.write(fig1) 154 | 155 |
156 | 157 | 158 | 159 | --------------------------------------------------------------------------------