├── MANIFEST.in ├── img └── demo.gif ├── streamlit_lottie ├── frontend │ ├── src │ │ ├── react-app-env.d.ts │ │ ├── index.css │ │ ├── index.tsx │ │ └── StreamlitLottie.tsx │ ├── .prettierrc │ ├── .env │ ├── public │ │ └── index.html │ ├── tsconfig.json │ └── package.json ├── utils.py ├── __init__.py └── url.py ├── setup.py ├── .github └── workflows │ └── publish_new_release.yml ├── .gitignore ├── README.md └── LICENSE /MANIFEST.in: -------------------------------------------------------------------------------- 1 | recursive-include streamlit_lottie/frontend/build * 2 | -------------------------------------------------------------------------------- /img/demo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/andfanilo/streamlit-lottie/HEAD/img/demo.gif -------------------------------------------------------------------------------- /streamlit_lottie/frontend/src/react-app-env.d.ts: -------------------------------------------------------------------------------- 1 | /// 2 | -------------------------------------------------------------------------------- /streamlit_lottie/frontend/.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "endOfLine": "lf", 3 | "semi": false, 4 | "trailingComma": "es5" 5 | } 6 | -------------------------------------------------------------------------------- /streamlit_lottie/frontend/.env: -------------------------------------------------------------------------------- 1 | # Run the component's dev server on :3001 2 | # (The Streamlit dev server already runs on :3000) 3 | PORT=3001 4 | 5 | # Don't automatically open the web browser on `npm run start`. 6 | BROWSER=none 7 | -------------------------------------------------------------------------------- /streamlit_lottie/frontend/src/index.css: -------------------------------------------------------------------------------- 1 | :root { 2 | box-sizing: border-box; 3 | } 4 | 5 | *, 6 | ::before, 7 | ::after { 8 | box-sizing: inherit; 9 | } 10 | 11 | body { 12 | margin: 0; 13 | background: transparent; 14 | } 15 | -------------------------------------------------------------------------------- /streamlit_lottie/frontend/src/index.tsx: -------------------------------------------------------------------------------- 1 | import React from "react" 2 | import ReactDOM from "react-dom" 3 | import StreamlitLottie from "./StreamlitLottie" 4 | 5 | import "./index.css" 6 | 7 | ReactDOM.render( 8 | , 9 | document.getElementById("root") 10 | ) 11 | -------------------------------------------------------------------------------- /streamlit_lottie/frontend/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Streamlit Lottie 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | -------------------------------------------------------------------------------- /streamlit_lottie/frontend/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es5", 4 | "lib": ["dom", "dom.iterable", "esnext"], 5 | "allowJs": true, 6 | "skipLibCheck": true, 7 | "esModuleInterop": true, 8 | "allowSyntheticDefaultImports": true, 9 | "strict": true, 10 | "forceConsistentCasingInFileNames": true, 11 | "module": "esnext", 12 | "moduleResolution": "node", 13 | "resolveJsonModule": true, 14 | "isolatedModules": true, 15 | "noEmit": true, 16 | "jsx": "react" 17 | }, 18 | "include": ["src"] 19 | } 20 | -------------------------------------------------------------------------------- /streamlit_lottie/frontend/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "streamlit_lottie", 3 | "version": "0.0.5", 4 | "private": true, 5 | "dependencies": { 6 | "lottie-web": "^5.7.4", 7 | "react": "^16.13.1", 8 | "react-dom": "^16.13.1", 9 | "streamlit-component-lib": "^1.3.0" 10 | }, 11 | "devDependencies": { 12 | "@types/node": "^12.0.0", 13 | "@types/react": "^16.9.0", 14 | "@types/react-dom": "^16.9.0", 15 | "react-scripts": "4.0.3", 16 | "typescript": "^4.6.3" 17 | }, 18 | "scripts": { 19 | "start": "react-scripts start", 20 | "build": "react-scripts build", 21 | "test": "react-scripts test", 22 | "eject": "react-scripts eject" 23 | }, 24 | "eslintConfig": { 25 | "extends": "react-app" 26 | }, 27 | "browserslist": { 28 | "production": [ 29 | ">0.2%", 30 | "not dead", 31 | "not op_mini all" 32 | ], 33 | "development": [ 34 | "last 1 chrome version", 35 | "last 1 firefox version", 36 | "last 1 safari version" 37 | ] 38 | }, 39 | "homepage": "." 40 | } 41 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from os.path import dirname 2 | from os.path import join 3 | import setuptools 4 | 5 | 6 | def readme() -> str: 7 | """Utility function to read the README file. 8 | Used for the long_description. It's nice, because now 1) we have a top 9 | level README file and 2) it's easier to type in the README file than to put 10 | a raw string in below. 11 | :return: content of README.md 12 | """ 13 | return open(join(dirname(__file__), "README.md")).read() 14 | 15 | 16 | setuptools.setup( 17 | name="streamlit-lottie", 18 | version="0.0.5", 19 | author="Fanilo ANDRIANASOLO", 20 | author_email="contact@andfanilo.com", 21 | description="A Streamlit custom component to load Lottie animations", 22 | long_description=readme(), 23 | long_description_content_type="text/markdown", 24 | url="https://github.com/andfanilo/streamlit-lottie", 25 | packages=setuptools.find_packages(), 26 | include_package_data=True, 27 | classifiers=[], 28 | python_requires=">=3.6", 29 | install_requires=[ 30 | "streamlit >= 0.63", 31 | ], 32 | ) 33 | -------------------------------------------------------------------------------- /.github/workflows/publish_new_release.yml: -------------------------------------------------------------------------------- 1 | # This workflows will upload a Python Package using Twine when a release is created 2 | # For more information see: https://help.github.com/en/actions/language-and-framework-guides/using-python-with-github-actions#publishing-to-package-registries 3 | # Copied from https://github.com/randyzwitch/streamlit-folium/blob/master/.github/workflows/publish_PYPI_each_tag.yml and https://github.com/whitphx/streamlit-webrtc/blob/main/.github/workflows/publish.yml 4 | name: Upload Python Package 5 | 6 | on: 7 | release: 8 | types: [created] 9 | 10 | jobs: 11 | deploy: 12 | runs-on: ubuntu-latest 13 | 14 | steps: 15 | - uses: actions/checkout@v3 16 | - name: Set up Python 17 | uses: actions/setup-python@v4 18 | with: 19 | python-version: "3.8" 20 | - name: Set up Node.js 21 | uses: actions/setup-node@v3 22 | with: 23 | node-version: 16 24 | - name: Install Python dependencies 25 | run: | 26 | python -m pip install --upgrade pip 27 | pip install setuptools wheel twine 28 | - name: Build streamlit-lottie JS 29 | run: | 30 | npm ci 31 | npm run build 32 | working-directory: streamlit_lottie/frontend 33 | - name: Build and publish 34 | env: 35 | TWINE_USERNAME: ${{ secrets.PYPI_USERNAME }} 36 | TWINE_PASSWORD: ${{ secrets.PYPI_PASSWORD }} 37 | run: | 38 | pwd 39 | python setup.py sdist bdist_wheel 40 | twine upload dist/* 41 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ######################################################################## 2 | # Python - https://github.com/github/gitignore/blob/master/Python.gitignore 3 | ######################################################################## 4 | # Byte-compiled / optimized / DLL files 5 | __pycache__/ 6 | *.py[cod] 7 | *$py.class 8 | 9 | # Distribution / packaging 10 | build/ 11 | dist/ 12 | eggs/ 13 | .eggs/ 14 | *.egg-info/ 15 | *.egg 16 | 17 | # Unit test / coverage reports 18 | .coverage 19 | .coverage\.* 20 | .pytest_cache/ 21 | .mypy_cache/ 22 | test-reports 23 | 24 | # Test fixtures 25 | cffi_bin 26 | 27 | # Pyenv Stuff 28 | .python-version 29 | 30 | ######################################################################## 31 | # OSX - https://github.com/github/gitignore/blob/master/Global/macOS.gitignore 32 | ######################################################################## 33 | .DS_Store 34 | .DocumentRevisions-V100 35 | .fseventsd 36 | .Spotlight-V100 37 | .TemporaryItems 38 | .Trashes 39 | .VolumeIcon.icns 40 | .com.apple.timemachine.donotpresent 41 | 42 | ######################################################################## 43 | # node - https://github.com/github/gitignore/blob/master/Node.gitignore 44 | ######################################################################## 45 | # Logs 46 | npm-debug.log* 47 | yarn-debug.log* 48 | yarn-error.log* 49 | 50 | # Dependency directories 51 | node_modules/ 52 | 53 | # Coverage directory used by tools like istanbul 54 | coverage/ 55 | 56 | ######################################################################## 57 | # JetBrains 58 | ######################################################################## 59 | .idea 60 | 61 | ######################################################################## 62 | # VSCode 63 | ######################################################################## 64 | .vscode/ 65 | -------------------------------------------------------------------------------- /streamlit_lottie/frontend/src/StreamlitLottie.tsx: -------------------------------------------------------------------------------- 1 | import { 2 | Streamlit, 3 | ComponentProps, 4 | withStreamlitConnection, 5 | } from "streamlit-component-lib" 6 | import React, { useEffect, useRef } from "react" 7 | import lottie, { AnimationItem } from "lottie-web" 8 | 9 | interface PythonArgs { 10 | animationData: any 11 | loop: boolean | number 12 | speed: number 13 | direction: 1 | -1 14 | quality: "high" | "medium" | "low" 15 | height?: number 16 | width?: number 17 | } 18 | 19 | const StreamlitLottie = (props: ComponentProps) => { 20 | const lottieElementRef = useRef(null) 21 | const lottieInstanceRef = useRef() 22 | 23 | const { 24 | animationData, 25 | speed, 26 | direction, 27 | loop, 28 | quality, 29 | height, 30 | width, 31 | }: PythonArgs = props.args 32 | 33 | useEffect(() => { 34 | if (null === lottieElementRef.current) { 35 | return 36 | } 37 | 38 | lottieInstanceRef.current = lottie.loadAnimation({ 39 | container: lottieElementRef.current, 40 | renderer: "svg", 41 | loop: loop, 42 | autoplay: true, 43 | animationData: animationData, 44 | }) 45 | lottieInstanceRef.current.setSubframe(false) 46 | 47 | lottieInstanceRef.current.addEventListener("DOMLoaded", () => { 48 | Streamlit.setFrameHeight() 49 | }) 50 | 51 | return () => { 52 | if (!lottieInstanceRef.current) { 53 | return 54 | } 55 | lottieInstanceRef.current.removeEventListener("DOMLoaded") 56 | lottieInstanceRef.current.destroy() 57 | lottieInstanceRef.current = undefined 58 | } 59 | }, [animationData, loop]) 60 | 61 | useEffect(() => { 62 | if (!lottieInstanceRef.current) return 63 | lottie.setQuality(quality) 64 | }, [quality]) 65 | 66 | useEffect(() => { 67 | if (!lottieInstanceRef.current) return 68 | if (Number.isNaN(speed)) return 69 | lottieInstanceRef.current.setSpeed(speed) 70 | }, [speed]) 71 | 72 | useEffect(() => { 73 | if (!lottieInstanceRef.current) return 74 | lottieInstanceRef.current.setDirection(direction) 75 | }, [direction]) 76 | 77 | return ( 78 | <> 79 |
83 | 84 | ) 85 | } 86 | export default withStreamlitConnection(StreamlitLottie) 87 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Streamlit Lottie 2 | 3 | --- 4 | 5 | This project is [unmaintained](https://www.youtube.com/watch?v=1RFJF_ETpLk). 6 | 7 | Though you could get a similar feature by embedding the Lottie HTML code into `st.html`. 8 | 9 | --- 10 | 11 | [![Streamlit App](https://static.streamlit.io/badges/streamlit_badge_black_white.svg)](https://share.streamlit.io/andfanilo/streamlit-lottie-demo/master/app.py) 12 | 13 | Integrate [Lottie](https://lottiefiles.com/) animations inside your Streamlit app! 14 | 15 | ![](./img/demo.gif) 16 | 17 | ## Install 18 | 19 | ``` 20 | pip install streamlit-lottie 21 | ``` 22 | 23 | ## Usage 24 | * Basic usage 25 | ```python 26 | import streamlit as st 27 | from streamlit_lottie import st_lottie 28 | 29 | with st.echo(): 30 | st_lottie("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") 31 | 32 | ``` 33 | 34 | * Basic usage (with monkey patched `st.lottie` function) 35 | ```python 36 | import streamlit as st 37 | import streamlit_lottie 38 | 39 | with st.echo(): 40 | st.lottie("https://assets5.lottiefiles.com/packages/lf20_V9t630.json") 41 | 42 | ``` 43 | 44 | * Context manager usage, using `with` notation 45 | ```python 46 | import time 47 | 48 | import streamlit as st 49 | from streamlit_lottie import st_lottie 50 | 51 | with st_lottie("https://assets5.lottiefiles.com/packages/lf20_V9t630.json"): 52 | time.sleep(5) 53 | 54 | ``` 55 | 56 | * Download lottie manually example 57 | ```python 58 | import time 59 | import requests 60 | 61 | import streamlit as st 62 | from streamlit_lottie import st_lottie 63 | from streamlit_lottie import st_lottie_spinner 64 | 65 | 66 | def load_lottieurl(url: str): 67 | r = requests.get(url) 68 | if r.status_code != 200: 69 | return None 70 | return r.json() 71 | 72 | 73 | lottie_url_hello = "https://assets5.lottiefiles.com/packages/lf20_V9t630.json" 74 | lottie_url_download = "https://assets4.lottiefiles.com/private_files/lf30_t26law.json" 75 | lottie_hello = load_lottieurl(lottie_url_hello) 76 | lottie_download = load_lottieurl(lottie_url_download) 77 | 78 | 79 | st_lottie(lottie_hello, key="hello") 80 | 81 | if st.button("Download"): 82 | with st_lottie_spinner(lottie_download, key="download"): 83 | time.sleep(5) 84 | st.balloons() 85 | 86 | ``` 87 | 88 | ## Development 89 | 90 | ### Install 91 | 92 | - JS side 93 | 94 | ```shell script 95 | cd frontend 96 | npm install 97 | ``` 98 | 99 | - Python side 100 | 101 | ```shell script 102 | conda create -n streamlit-lottie python=3.7 103 | conda activate streamlit-lottie 104 | pip install -e . 105 | ``` 106 | 107 | ### Run 108 | 109 | Both webpack dev server and Streamlit need to run for development mode. 110 | 111 | - JS side 112 | 113 | ```shell script 114 | cd frontend 115 | npm run start 116 | ``` 117 | 118 | - Python side 119 | 120 | ```shell script 121 | streamlit run app.py 122 | ``` 123 | 124 | ## References 125 | 126 | - [Lottie-web (Official)](https://github.com/airbnb/lottie-web) 127 | - [react-lottie (chenqingspring)](https://github.com/chenqingspring/react-lottie) 128 | - [lottie-react-web (felippenardi)](https://github.com/felippenardi/lottie-react-web) 129 | - [lottie-react (gamote)](https://github.com/gamote/lottie-react) 130 | - [lottie-react (LottieFiles)](https://github.com/LottieFiles/lottie-react) 131 | - [react-lottie-player (mifi)](https://github.com/mifi/react-lottie-player) 132 | - [lottie-interactivity](https://github.com/LottieFiles/lottie-interactivity) 133 | 134 | # Support me 135 | 136 | Buy Me A Coffee 137 | -------------------------------------------------------------------------------- /streamlit_lottie/utils.py: -------------------------------------------------------------------------------- 1 | """Code take from https://github.com/python-validators/validators/blob/master/validators/utils.py""" 2 | """The MIT License (MIT) 3 | 4 | Copyright (c) 2013-2014 Konsta Vesterinen 5 | 6 | Permission is hereby granted, free of charge, to any person obtaining a copy of 7 | this software and associated documentation files (the "Software"), to deal in 8 | the Software without restriction, including without limitation the rights to 9 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 10 | the Software, and to permit persons to whom the Software is furnished to do so, 11 | subject to the following conditions: 12 | 13 | The above copyright notice and this permission notice shall be included in all 14 | copies or substantial portions of the Software. 15 | 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 18 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 19 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 20 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 21 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.""" 22 | """Utils.""" 23 | # -*- coding: utf-8 -*- 24 | 25 | # standard 26 | from typing import Any, Callable, Dict 27 | from inspect import getfullargspec 28 | from functools import wraps 29 | from itertools import chain 30 | 31 | 32 | class ValidationFailure(Exception): 33 | """Exception class when validation failure occurs.""" 34 | 35 | def __init__(self, function: Callable[..., Any], arg_dict: Dict[str, Any]): 36 | """Initialize Validation Failure.""" 37 | self.func = function 38 | self.__dict__.update(arg_dict) 39 | 40 | def __repr__(self): 41 | """Repr Validation Failure.""" 42 | return ( 43 | f"ValidationFailure(func={self.func.__name__}, " 44 | + f"args={({k: v for (k, v) in self.__dict__.items() if k != 'func'})})" 45 | ) 46 | 47 | def __str__(self): 48 | """Str Validation Failure.""" 49 | return repr(self) 50 | 51 | def __bool__(self): 52 | """Bool Validation Failure.""" 53 | return False 54 | 55 | 56 | def _func_args_as_dict(func: Callable[..., Any], *args: Any, **kwargs: Any): 57 | """Return function's positional and key value arguments as an ordered dictionary.""" 58 | return dict( 59 | list(zip(dict.fromkeys(chain(getfullargspec(func)[0], kwargs.keys())), args)) 60 | + list(kwargs.items()) 61 | ) 62 | 63 | 64 | def validator(func: Callable[..., Any]): 65 | """A decorator that makes given function validator. 66 | 67 | Whenever the given `func` returns `False` this 68 | decorator returns `ValidationFailure` object. 69 | 70 | Examples: 71 | >>> @validator 72 | ... def even(value): 73 | ... return not (value % 2) 74 | >>> even(4) 75 | # Output: True 76 | >>> even(5) 77 | # Output: ValidationFailure(func=even, args={'value': 5}) 78 | 79 | Args: 80 | func: 81 | Function which is to be decorated. 82 | 83 | Returns: 84 | (Callable[..., ValidationFailure | Literal[True])): 85 | A decorator which returns either `ValidationFailure` 86 | or `Literal[True]`. 87 | 88 | > *New in version 2013.10.21*. 89 | """ 90 | 91 | @wraps(func) 92 | def wrapper(*args: Any, **kwargs: Any): 93 | return ( 94 | True 95 | if func(*args, **kwargs) 96 | else ValidationFailure(func, _func_args_as_dict(func, *args, **kwargs)) 97 | ) 98 | 99 | return wrapper 100 | -------------------------------------------------------------------------------- /streamlit_lottie/__init__.py: -------------------------------------------------------------------------------- 1 | import os 2 | from contextlib import contextmanager 3 | 4 | import uuid 5 | import time 6 | import json 7 | import requests 8 | import streamlit as st 9 | import streamlit.components.v1 as components 10 | from typing import Union, Optional, Literal 11 | from streamlit.errors import StreamlitAPIException 12 | 13 | from streamlit_lottie.url import url as validate_url 14 | from streamlit_lottie.utils import ValidationFailure 15 | 16 | # Create a _RELEASE constant. We'll set this to False while we're developing 17 | # the component, and True when we're ready to package and distribute it. 18 | _RELEASE = True 19 | 20 | if not _RELEASE: 21 | _st_lottie = components.declare_component( 22 | "streamlit_lottie", 23 | url="http://localhost:3001", 24 | ) 25 | else: 26 | parent_dir = os.path.dirname(os.path.abspath(__file__)) 27 | build_dir = os.path.join(parent_dir, "frontend/build") 28 | _st_lottie = components.declare_component("streamlit_lottie", path=build_dir) 29 | 30 | 31 | class LottieDownloadFailure(StreamlitAPIException): 32 | pass 33 | 34 | 35 | def _download_animation_data(url): 36 | request = requests.get(url) 37 | try: 38 | return request.json() 39 | except (json.JSONDecodeError, TypeError) as exc: 40 | raise LottieDownloadFailure( 41 | f"""Unable to download animation data from {url} \n 42 | * status code {request.status_code} 43 | * JSONDecodeError {exc} 44 | """ 45 | ) 46 | 47 | 48 | def download_animation_data(url): 49 | try: 50 | return _download_animation_data(url) 51 | except LottieDownloadFailure: 52 | time.sleep(1) 53 | return _download_animation_data(url) 54 | 55 | 56 | def get_animation_data(animation_source: Union[bytes, str, dict]): 57 | if not ( 58 | isinstance(animation_source, bytes) 59 | | isinstance(animation_source, str) 60 | | isinstance(animation_source, dict) 61 | ): 62 | raise StreamlitAPIException( 63 | f"""Animation data must be one of Lottie URL or loaded JSON represented by dict or string/bytes UTF-8 JSON representative. \n 64 | Given type is: {type(animation_source)}""" 65 | ) 66 | 67 | if isinstance(animation_source, bytes): 68 | animation_source = animation_source.decode("UTF-8") 69 | 70 | animation_data = None 71 | if isinstance(animation_source, dict): 72 | animation_data = animation_source 73 | elif isinstance(animation_source, str): 74 | try: 75 | if validate_url(animation_source): 76 | animation_data = download_animation_data(animation_source) 77 | except ValidationFailure: 78 | # Is not url try to convert it to json 79 | try: 80 | animation_data = json.loads(animation_source) 81 | except (json.JSONDecodeError, TypeError) as exc: 82 | raise StreamlitAPIException( 83 | f"""Unable to load animation data as JSON {exc}""" 84 | ) 85 | return animation_data 86 | 87 | 88 | class st_lottie: 89 | """Creates a new instance of lottie component. 90 | 91 | Parameters 92 | ---------- 93 | animation_source: bytes | str | dict 94 | Animation data as Lottie URL or loaded JSON represented by dict or string/bytes UTF-8 JSON representative 95 | speed: int 96 | Speed of animation 97 | reverse: bool 98 | Reverse animation 99 | quality: Literal["low", "medium", "high"] 100 | low, medium or high. Defaults to low. 101 | loop: bool | number 102 | Loop animation, forever if True, once if False, or 'loop' times if number 103 | height: Optional[int] 104 | Height of the animation in px 105 | width: Optional[int] 106 | Width of the animation in px 107 | 108 | Returns context manager, so it can be used as a spinner. 109 | """ 110 | 111 | # noinspection PyTypeChecker 112 | def __init__( 113 | self, 114 | animation_source: Union[bytes, str, dict], 115 | speed: int = 1, 116 | reverse: bool = False, 117 | loop: Union[bool, int] = True, 118 | quality: Literal["low", "medium", "high"] = "medium", 119 | height: Optional[int] = None, 120 | width: Optional[int] = None, 121 | key: Optional[str] = None, 122 | ): 123 | self.animation_data = get_animation_data(animation_source) 124 | self.speed = speed 125 | self.reverse = reverse 126 | self.loop = loop 127 | self.quality = quality 128 | self.height = height 129 | self.width = width 130 | self.container = st.empty() 131 | if not key: 132 | key = str(uuid.uuid4().hex) 133 | self.key = key 134 | self.start(key=self.key) 135 | 136 | def start(self, key: str): 137 | with self.container: 138 | _st_lottie( 139 | animationData=self.animation_data, 140 | speed=self.speed, 141 | direction=-1 if self.reverse else 1, 142 | loop=self.loop, 143 | quality=self.quality, 144 | height=self.height, 145 | width=self.width, 146 | key=key, 147 | default=None, 148 | ) 149 | 150 | def __enter__(self): 151 | self.container.empty() 152 | self.start(key=self.key or str(uuid.uuid4().hex)) 153 | 154 | def __exit__(self, exc_type, exc_val, exc_tb): 155 | self.container.empty() 156 | 157 | 158 | @contextmanager 159 | def st_lottie_spinner( 160 | animation_source: Union[bytes, str, dict], 161 | speed: int = 1, 162 | reverse: bool = False, 163 | loop: Union[bool, int] = True, 164 | quality: Literal["low", "medium", "high"] = "medium", 165 | height: Optional[int] = None, 166 | width: Optional[int] = None, 167 | key: Optional[str] = None, 168 | ): 169 | if not key: 170 | key = str(uuid.uuid4().hex) 171 | animation_data = get_animation_data(animation_source) 172 | lottie_container = st.empty() 173 | try: 174 | with lottie_container: 175 | st_lottie(animation_data, speed, reverse, loop, quality, height, width, key) 176 | yield 177 | finally: 178 | lottie_container.empty() 179 | 180 | 181 | st.lottie = st_lottie 182 | st.lottie_spinner = st_lottie_spinner 183 | -------------------------------------------------------------------------------- /streamlit_lottie/url.py: -------------------------------------------------------------------------------- 1 | """Code take from https://github.com/python-validators/validators/blob/master/validators/url.py""" 2 | """The MIT License (MIT) 3 | 4 | Copyright (c) 2013-2014 Konsta Vesterinen 5 | 6 | Permission is hereby granted, free of charge, to any person obtaining a copy of 7 | this software and associated documentation files (the "Software"), to deal in 8 | the Software without restriction, including without limitation the rights to 9 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of 10 | the Software, and to permit persons to whom the Software is furnished to do so, 11 | subject to the following conditions: 12 | 13 | The above copyright notice and this permission notice shall be included in all 14 | copies or substantial portions of the Software. 15 | 16 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 17 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS 18 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 19 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 20 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 21 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.""" 22 | import re 23 | 24 | from .utils import validator 25 | 26 | ip_middle_octet = r"(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5]))" 27 | ip_last_octet = r"(?:\.(?:0|[1-9]\d?|1\d\d|2[0-4]\d|25[0-5]))" 28 | 29 | regex = re.compile( # noqa: W605 30 | r"^" 31 | # protocol identifier 32 | r"(?:(?:https?|ftp)://)" 33 | # user:pass authentication 34 | r"(?:[-a-z\u00a1-\uffff0-9._~%!$&'()*+,;=:]+" 35 | r"(?::[-a-z0-9._~%!$&'()*+,;=:]*)?@)?" 36 | r"(?:" 37 | r"(?P" 38 | # IP address exclusion 39 | # private & local networks 40 | r"(?:(?:10|127)" + ip_middle_octet + r"{2}" + ip_last_octet + r")|" 41 | r"(?:(?:169\.254|192\.168)" + ip_middle_octet + ip_last_octet + r")|" 42 | r"(?:172\.(?:1[6-9]|2\d|3[0-1])" + ip_middle_octet + ip_last_octet + r"))" 43 | r"|" 44 | # private & local hosts 45 | r"(?P" r"(?:localhost))" r"|" 46 | # IP address dotted notation octets 47 | # excludes loopback network 0.0.0.0 48 | # excludes reserved space >= 224.0.0.0 49 | # excludes network & broadcast addresses 50 | # (first & last IP address of each class) 51 | r"(?P" 52 | r"(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])" 53 | r"" + ip_middle_octet + r"{2}" 54 | r"" + ip_last_octet + r")" 55 | r"|" 56 | # IPv6 RegEx from https://stackoverflow.com/a/17871737 57 | r"\[(" 58 | # 1:2:3:4:5:6:7:8 59 | r"([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|" 60 | # 1:: 1:2:3:4:5:6:7:: 61 | r"([0-9a-fA-F]{1,4}:){1,7}:|" 62 | # 1::8 1:2:3:4:5:6::8 1:2:3:4:5:6::8 63 | r"([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|" 64 | # 1::7:8 1:2:3:4:5::7:8 1:2:3:4:5::8 65 | r"([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|" 66 | # 1::6:7:8 1:2:3:4::6:7:8 1:2:3:4::8 67 | r"([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|" 68 | # 1::5:6:7:8 1:2:3::5:6:7:8 1:2:3::8 69 | r"([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|" 70 | # 1::4:5:6:7:8 1:2::4:5:6:7:8 1:2::8 71 | r"([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|" 72 | # 1::3:4:5:6:7:8 1::3:4:5:6:7:8 1::8 73 | r"[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|" 74 | # ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 :: 75 | r":((:[0-9a-fA-F]{1,4}){1,7}|:)|" 76 | # fe80::7:8%eth0 fe80::7:8%1 77 | # (link-local IPv6 addresses with zone index) 78 | r"fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|" 79 | r"::(ffff(:0{1,4}){0,1}:){0,1}" 80 | r"((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}" 81 | # ::255.255.255.255 ::ffff:255.255.255.255 ::ffff:0:255.255.255.255 82 | # (IPv4-mapped IPv6 addresses and IPv4-translated addresses) 83 | r"(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|" 84 | r"([0-9a-fA-F]{1,4}:){1,4}:" 85 | r"((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}" 86 | # 2001:db8:3:4::192.0.2.33 64:ff9b::192.0.2.33 87 | # (IPv4-Embedded IPv6 Address) 88 | r"(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])" r")\]|" 89 | # host name 90 | r"(?:(?:(?:xn--[-]{0,2})|[a-z\u00a1-\uffff\U00010000-\U0010ffff0-9]-?)*" 91 | r"[a-z\u00a1-\uffff\U00010000-\U0010ffff0-9]+)" 92 | # domain name 93 | r"(?:\.(?:(?:xn--[-]{0,2})|[a-z\u00a1-\uffff\U00010000-\U0010ffff0-9]-?)*" 94 | r"[a-z\u00a1-\uffff\U00010000-\U0010ffff0-9]+)*" 95 | # TLD identifier 96 | r"(?:\.(?:(?:xn--[-]{0,2}[a-z\u00a1-\uffff\U00010000-\U0010ffff0-9]{2,})|" 97 | r"[a-z\u00a1-\uffff\U00010000-\U0010ffff]{2,}))" 98 | r")" 99 | # port number 100 | r"(?::\d{2,5})?" 101 | # resource path 102 | r"(?:/[-a-z\u00a1-\uffff\U00010000-\U0010ffff0-9._~%!$&'()*+,;=:@/]*)?" 103 | # query string 104 | r"(?:\?\S*)?" 105 | # fragment 106 | r"(?:#\S*)?" r"$", 107 | re.UNICODE | re.IGNORECASE, 108 | ) 109 | 110 | pattern = re.compile(regex) 111 | 112 | 113 | @validator 114 | def url(value, public=False): 115 | """ 116 | Return whether or not given value is a valid URL. 117 | 118 | If the value is valid URL this function returns ``True``, otherwise 119 | :class:`~validators.utils.ValidationFailure`. 120 | 121 | This validator is based on the wonderful `URL validator of dperini`_. 122 | 123 | .. _URL validator of dperini: 124 | https://gist.github.com/dperini/729294 125 | 126 | Examples:: 127 | 128 | >>> url('http://foobar.dk') 129 | True 130 | 131 | >>> url('ftp://foobar.dk') 132 | True 133 | 134 | >>> url('http://10.0.0.1') 135 | True 136 | 137 | >>> url('http://foobar.d') 138 | ValidationFailure(func=url, ...) 139 | 140 | >>> url('http://10.0.0.1', public=True) 141 | ValidationFailure(func=url, ...) 142 | 143 | .. versionadded:: 0.2 144 | 145 | .. versionchanged:: 0.10.2 146 | 147 | Added support for various exotic URLs and fixed various false 148 | positives. 149 | 150 | .. versionchanged:: 0.10.3 151 | 152 | Added ``public`` parameter. 153 | 154 | .. versionchanged:: 0.11.0 155 | 156 | Made the regular expression this function uses case insensitive. 157 | 158 | .. versionchanged:: 0.11.3 159 | 160 | Added support for URLs containing localhost 161 | 162 | :param value: URL address string to validate 163 | :param public: (default=False) Set True to only allow a public IP address 164 | """ 165 | result = pattern.match(value) 166 | if not public: 167 | return result 168 | 169 | return result and not any( 170 | (result.groupdict().get(key) for key in ("private_ip", "private_host")) 171 | ) 172 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | --------------------------------------------------------------------------------