├── .github └── workflows │ └── test.yml ├── .gitignore ├── LICENSE ├── Makefile ├── README.md ├── examples └── clicker.py ├── fh_matplotlib └── __init__.py ├── setup.py └── tests ├── __init__.py ├── test_basics.py └── test_clicker.py /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Code Checks 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | pull_request: 8 | branches: 9 | - main 10 | 11 | jobs: 12 | build: 13 | runs-on: ubuntu-latest 14 | strategy: 15 | matrix: 16 | python-version: ['3.10'] 17 | 18 | steps: 19 | - uses: actions/checkout@v2 20 | - name: Set up Python ${{ matrix.python-version }} 21 | uses: actions/setup-python@v1 22 | with: 23 | python-version: ${{ matrix.python-version }} 24 | - name: Install Testing Dependencies 25 | run: make install 26 | - name: Unittest 27 | run: make test 28 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # poetry 98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 102 | #poetry.lock 103 | 104 | # pdm 105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 106 | #pdm.lock 107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 108 | # in version control. 109 | # https://pdm.fming.dev/latest/usage/project/#working-with-version-control 110 | .pdm.toml 111 | .pdm-python 112 | .pdm-build/ 113 | 114 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 115 | __pypackages__/ 116 | 117 | # Celery stuff 118 | celerybeat-schedule 119 | celerybeat.pid 120 | 121 | # SageMath parsed files 122 | *.sage.py 123 | 124 | # Environments 125 | .env 126 | .venv 127 | env/ 128 | venv/ 129 | ENV/ 130 | env.bak/ 131 | venv.bak/ 132 | 133 | # Spyder project settings 134 | .spyderproject 135 | .spyproject 136 | 137 | # Rope project settings 138 | .ropeproject 139 | 140 | # mkdocs documentation 141 | /site 142 | 143 | # mypy 144 | .mypy_cache/ 145 | .dmypy.json 146 | dmypy.json 147 | 148 | # Pyre type checker 149 | .pyre/ 150 | 151 | # pytype static type analyzer 152 | .pytype/ 153 | 154 | # Cython debug symbols 155 | cython_debug/ 156 | 157 | # PyCharm 158 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 159 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 160 | # and can be added to the global gitignore or merged into this file. For a more nuclear 161 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 162 | #.idea/ 163 | .sesskey -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 vincent d warmerdam 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 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | install: 2 | python -m pip install --upgrade pip 3 | python -m pip install -e ".[dev]" 4 | python -m pip install wheel twine 5 | 6 | pypi: 7 | python setup.py sdist 8 | python setup.py bdist_wheel --universal 9 | twine upload dist/* 10 | 11 | test: 12 | pytest -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ### fh-matplotlib 2 | 3 | Making it easier to show matplotlib charts in FastHTML. 4 | 5 | ## Usage 6 | 7 | You can install this tool by running: 8 | 9 | ``` 10 | python -m pip install fh-matplotlib 11 | ``` 12 | 13 | After this step, it is ready for use! At the moment this package merely contains a decorator. You can use it to wrap any function that generates a matplotlib chart in order for it to return an `Img` for FastHTML to render. In, short you would typically use it like this: 14 | 15 | ```python 16 | import numpy as np 17 | import matplotlib.pylab as plt 18 | from fh_matplotlib import matplotlib2fasthtml 19 | 20 | # This function will return a proper Img that can be rendered 21 | @matplotlib2fasthtml 22 | def matplotlib_function(): 23 | plt.plot(np.arange(25), np.random.exponential(1, size=25)) 24 | ``` 25 | 26 |
27 | Want to see a full example that you could copy and paste directly? 28 | 29 | ```python 30 | from fh_matplotlib import matplotlib2fasthtml 31 | from fasthtml.common import * 32 | import numpy as np 33 | import matplotlib.pylab as plt 34 | 35 | app, rt = fast_app() 36 | 37 | 38 | count = 0 39 | plotdata = [] 40 | 41 | @matplotlib2fasthtml 42 | def generate_chart(): 43 | global plotdata 44 | plt.plot(range(len(plotdata)), plotdata) 45 | 46 | 47 | @app.get("/") 48 | def home(): 49 | return Title("Matplotlib Demo"), Main( 50 | H1("Matplotlib Demo"), 51 | P("Nothing too fancy, but still kind of fancy."), 52 | Div(f"You have pressed the button {count} times.", id="chart"), 53 | Button("Increment", hx_get="/increment", hx_target="#chart", hx_swap="innerHTML"), 54 | style="margin: 20px" 55 | ) 56 | 57 | 58 | @app.get("/increment/") 59 | def increment(): 60 | global plotdata, count 61 | count += 1 62 | plotdata.append(np.random.exponential(1)) 63 | return Div( 64 | generate_chart(), 65 | P(f"You have pressed the button {count} times."), 66 | ) 67 | 68 | serve() 69 | ``` 70 |
71 | 72 | ## Roadmap 73 | 74 | This repository is originally meant to be simple helper, but if there are more advanced use-cases to consider I will gladly consider them. Please start a conversation by opening up an issue before starting a PR though. 75 | -------------------------------------------------------------------------------- /examples/clicker.py: -------------------------------------------------------------------------------- 1 | from fh_matplotlib import matplotlib2fasthtml 2 | from fasthtml.common import * 3 | import numpy as np 4 | import matplotlib.pylab as plt 5 | 6 | app, rt = fast_app() 7 | 8 | 9 | count = 0 10 | plotdata = [] 11 | 12 | @matplotlib2fasthtml 13 | def generate_chart(): 14 | global plotdata 15 | plt.plot(range(len(plotdata)), plotdata) 16 | 17 | 18 | @app.get("/") 19 | def home(): 20 | return Title("Matplotlib Demo"), Main( 21 | H1("Matplotlib Demo"), 22 | P("Nothing too fancy, but still kind of fancy."), 23 | Div(f"You have pressed the button {count} times.", id="chart"), 24 | Button("Increment", hx_get="/increment/", hx_target="#chart", hx_swap="innerHTML"), 25 | style="margin: 20px" 26 | ) 27 | 28 | 29 | @app.get("/increment/") 30 | def increment(): 31 | global plotdata, count 32 | count += 1 33 | plotdata.append(np.random.exponential(1)) 34 | return Div( 35 | generate_chart(), 36 | P(f"You have pressed the button {count} times."), 37 | ) 38 | 39 | serve() -------------------------------------------------------------------------------- /fh_matplotlib/__init__.py: -------------------------------------------------------------------------------- 1 | import matplotlib.pyplot 2 | from fasthtml.common import Img 3 | import matplotlib.pylab as plt 4 | import matplotlib 5 | import io 6 | import base64 7 | 8 | # This is necessary to prevent matplotlib from causing memory leaks 9 | # https://stackoverflow.com/questions/31156578/matplotlib-doesnt-release-memory-after-savefig-and-close 10 | matplotlib.use('Agg') 11 | 12 | 13 | def matplotlib2fasthtml(func): 14 | ''' 15 | Ensure that matplotlib yielding function returns a renderable item for FastHTML. 16 | 17 | Usage: 18 | 19 | ```python 20 | import numpy as np 21 | import matplotlib.pylab as plt 22 | from fh_matplotlib import matplotlib2fasthtml 23 | 24 | # This function will return a proper Img that can be rendered 25 | @matplotlib2fasthtml 26 | def matplotlib_function(): 27 | plt.plot(np.arange(25), np.random.exponential(1, size=25)) 28 | ``` 29 | ''' 30 | def wrapper(*args, **kwargs): 31 | # Reset the figure to prevent accumulation. Maybe we need a setting for this? 32 | fig = plt.figure() 33 | 34 | # Run function as normal 35 | func(*args, **kwargs) 36 | 37 | # Store it as base64 and put it into an image. 38 | my_stringIObytes = io.BytesIO() 39 | plt.savefig(my_stringIObytes, format='jpg') 40 | my_stringIObytes.seek(0) 41 | my_base64_jpgData = base64.b64encode(my_stringIObytes.read()).decode() 42 | 43 | # Close the figure to prevent memory leaks 44 | plt.close(fig) 45 | plt.close('all') 46 | return Img(src=f'data:image/jpg;base64, {my_base64_jpgData}') 47 | return wrapper 48 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup, find_packages 2 | from pathlib import Path 3 | 4 | long_description = (Path(__file__).parent / "README.md").read_text() 5 | 6 | setup( 7 | name="fh-matplotlib", 8 | description="Make is easy to use matplotlib in FastHTML", 9 | long_description=long_description, 10 | long_description_content_type="text/markdown", 11 | author="Vincent D. Warmerdam", 12 | version="0.0.4", 13 | packages=find_packages(), 14 | install_requires=["matplotlib", "python-fasthtml"], 15 | extras_require={ 16 | "dev": ["pytest"], 17 | }, 18 | ) 19 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/koaning/fh-matplotlib/b74177417662d4a8d74af1476574a8f47667528c/tests/__init__.py -------------------------------------------------------------------------------- /tests/test_basics.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import matplotlib.pylab as plt 3 | from fh_matplotlib import matplotlib2fasthtml 4 | 5 | # This function will return a proper Img that can be rendered 6 | @matplotlib2fasthtml 7 | def matplotlib_function(): 8 | plt.plot(np.arange(25), np.random.exponential(1, size=25)) 9 | 10 | def test_no_err(): 11 | matplotlib_function() 12 | -------------------------------------------------------------------------------- /tests/test_clicker.py: -------------------------------------------------------------------------------- 1 | from fh_matplotlib import matplotlib2fasthtml 2 | from fasthtml.common import * 3 | import numpy as np 4 | import matplotlib.pylab as plt 5 | 6 | app = FastHTML() 7 | 8 | 9 | count = 0 10 | plotdata = [] 11 | 12 | @matplotlib2fasthtml 13 | def generate_chart(): 14 | global plotdata 15 | plt.plot(range(len(plotdata)), plotdata) 16 | 17 | 18 | @app.get("/") 19 | def home(): 20 | return Title("Matplotlib Demo"), Main( 21 | H1("Matplotlib Demo"), 22 | P("Nothing too fancy, but still kind of fancy."), 23 | Div(f"You have pressed the button {count} times.", id="chart"), 24 | Button("Increment", hx_get="/increment", hx_target="#chart", hx_swap="innerHTML"), 25 | style="margin: 20px" 26 | ) 27 | 28 | 29 | @app.get("/increment/") 30 | def increment(): 31 | global plotdata, count 32 | count += 1 33 | plotdata.append(np.random.exponential(1)) 34 | return Div( 35 | generate_chart(), 36 | P(f"You have pressed the button {count} times."), 37 | ) 38 | 39 | from starlette.testclient import TestClient 40 | 41 | client = TestClient(app) 42 | 43 | def test_clicks(): 44 | for i in range(10): 45 | client.get('/increment') 46 | resp = client.get('') 47 | assert 'You have pressed the button 10 times.' in resp.text 48 | # To properly test if the chart really shows up I will need to resort to Playwright and I prefer to do that another time 49 | --------------------------------------------------------------------------------