├── research_app ├── demo │ ├── __init__.py │ ├── model.py │ └── clip.py ├── components │ ├── __init__.py │ ├── jupyter_notebook.py │ ├── jupyter_lite.py │ └── app_status.py ├── __init__.py ├── __about__.py └── utils.py ├── tests ├── requirements.txt ├── test_research_app.py ├── resources │ ├── poster.md │ └── Interacting_with_CLIP.ipynb ├── app.py └── test_app_gallery.py ├── assets └── demo.png ├── requirements.txt ├── .github ├── CODEOWNERS ├── workflows │ ├── ci-checks.yml │ └── ci-testing.yml ├── PULL_REQUEST_TEMPLATE.md ├── stale.yml └── dependabot.yml ├── MANIFEST.in ├── setup.py ├── .pre-commit-config.yaml ├── README.md ├── .gitignore └── LICENSE /research_app/demo/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /research_app/components/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tests/requirements.txt: -------------------------------------------------------------------------------- 1 | coverage==7.4.0 2 | pytest==7.4.3 3 | -------------------------------------------------------------------------------- /research_app/__init__.py: -------------------------------------------------------------------------------- 1 | from research_app.__about__ import * # noqa: F403 2 | -------------------------------------------------------------------------------- /assets/demo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Lightning-Universe/Research-poster/HEAD/assets/demo.png -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | markdown-poster @ https://github.com/Lightning-Universe/MarkDown-poster_component/archive/refs/heads/main.zip 2 | rich==13.7.0 3 | torch==2.1.2 4 | torchvision==0.16.2 5 | gradio==3.41.2 6 | transformers==4.36.2 7 | nbconvert==7.14.2 8 | jupyterlite==0.2.3 9 | lightning[app]==2.1.* 10 | jupyterlab==4.0.12 11 | -------------------------------------------------------------------------------- /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | # Each line is a file pattern followed by one or more owners. 2 | 3 | # These owners will be the default owners for everything in the repo. Unless a later match takes precedence, 4 | # @global-owner1 and @global-owner2 will be requested for review when someone opens a pull request. 5 | * @aniketmaurya @Lightning-Universe/engs 6 | 7 | # CI/CD and configs 8 | /.github/ @aniketmaurya 9 | *.yml @aniketmaurya 10 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | # Manifest syntax https://docs.python.org/2/distutils/sourcedist.html 2 | graft wheelhouse 3 | 4 | recursive-exclude __pycache__ *.py[cod] *.orig 5 | 6 | # Include the license file 7 | include LICENSE 8 | 9 | # Exclude build configs 10 | exclude *.sh 11 | exclude *.toml 12 | exclude *.svg 13 | exclude *.yml 14 | exclude *.yaml 15 | 16 | # Include the Requirements 17 | include requirements.txt 18 | 19 | # Exclude Makefile 20 | exclude Makefile 21 | 22 | prune .git 23 | prune .github 24 | prune temp* 25 | prune test* 26 | -------------------------------------------------------------------------------- /.github/workflows/ci-checks.yml: -------------------------------------------------------------------------------- 1 | name: General checks 2 | 3 | on: 4 | push: 5 | branches: [main, "release/*"] 6 | pull_request: 7 | branches: [main, "release/*"] 8 | 9 | concurrency: 10 | group: ${{ github.workflow }}-${{ github.ref }}-${{ github.head_ref }} 11 | cancel-in-progress: ${{ ! (github.ref == 'refs/heads/main' || startsWith(github.ref, 'refs/heads/release/')) }} 12 | 13 | jobs: 14 | 15 | check-schema: 16 | uses: Lightning-AI/utilities/.github/workflows/check-schema.yml@main 17 | with: 18 | azure-dir: "" 19 | 20 | check-package: 21 | uses: Lightning-AI/utilities/.github/workflows/check-package.yml@main 22 | with: 23 | actions-ref: main 24 | import-name: "research_app" 25 | artifact-name: dist-packages-${{ github.sha }} 26 | testing-matrix: | 27 | { 28 | "os": ["ubuntu-latest", "macos-latest", "windows-latest"], 29 | "python-version": ["3.9"] 30 | } 31 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | ## What does this PR do? 2 | 3 | 8 | 9 | Fixes #\ 10 | 11 | ## Before submitting 12 | 13 | - [ ] Was this **discussed/approved** via a GitHub issue or with the team? (not for typos and docs) 14 | - [ ] Did you make sure your **PR does only one thing**, instead of bundling different changes together? 15 | - [ ] Did you list all the **breaking changes** introduced by this pull request? 16 | - [ ] Did you **test your PR locally**? 17 | - [ ] Did you **test your PR on cloud**? 18 | 19 | ### Does your PR introduce any breaking changes? If yes, please list them. 20 | 21 | 22 | 23 | ## PR review 24 | 25 | Anyone in the community is welcome to review the PR. 26 | 27 | ## Did you have fun? 28 | 29 | Make sure you had fun coding 🙃 30 | -------------------------------------------------------------------------------- /research_app/__about__.py: -------------------------------------------------------------------------------- 1 | __version__ = "0.0.4" 2 | __author__ = "Lightning et al." 3 | __author_email__ = "aniket@lightning.ai" 4 | __license__ = "Apache 2.0" 5 | __copyright__ = f"Copyright (c) 2021-2022, {__author__}." 6 | __homepage__ = "https://github.com/Lightning-AI/LAI-research-template-App" 7 | __docs__ = ( 8 | "Share your paper 'bundled' with the arxiv link, poster, live jupyter notebook," 9 | "interactive demo to try the model and more!" 10 | ) 11 | __long_doc__ = """ 12 | Use this app to share your research paper results. This app lets you connect a blogpost, arxiv paper, and jupyter 13 | notebook and even have an interactive demo for people to play with the model. This app also allows industry 14 | practitioners to productionize your work by adding inference components (sub 1ms inference time), data pipelines, etc. 15 | """ 16 | 17 | __all__ = [ 18 | "__author__", 19 | "__author_email__", 20 | "__copyright__", 21 | "__docs__", 22 | "__homepage__", 23 | "__license__", 24 | "__version__", 25 | ] 26 | -------------------------------------------------------------------------------- /.github/stale.yml: -------------------------------------------------------------------------------- 1 | # https://github.com/marketplace/stale 2 | 3 | # Number of days of inactivity before an issue becomes stale 4 | daysUntilStale: 60 5 | # Number of days of inactivity before a stale issue is closed 6 | daysUntilClose: 14 7 | # Issues with these labels will never be considered stale 8 | exemptLabels: 9 | - pinned 10 | - security 11 | # Label to use when marking an issue as stale 12 | staleLabel: won't fix 13 | # Comment to post when marking an issue as stale. Set to `false` to disable 14 | markComment: > 15 | This issue has been automatically marked as stale because it has not had 16 | recent activity. It will be closed if no further activity occurs. Thank you 17 | for your contributions. 18 | # Comment to post when closing a stale issue. Set to `false` to disable 19 | closeComment: false 20 | 21 | # Set to true to ignore issues in a project (defaults to false) 22 | exemptProjects: true 23 | # Set to true to ignore issues in a milestone (defaults to false) 24 | exemptMilestones: true 25 | # Set to true to ignore issues with an assignee (defaults to false) 26 | exemptAssignees: true 27 | -------------------------------------------------------------------------------- /tests/test_research_app.py: -------------------------------------------------------------------------------- 1 | r""" 2 | To test a lightning app: 3 | 1. Use LightningTestApp which is a subclass of LightningApp. 4 | 2. Subclass run_once in LightningTestApp. 5 | 3. in run_once, come up with a way to verify the behavior you wanted. 6 | 7 | run_once runs your app through one cycle of the event loop and then terminates 8 | """ 9 | import io 10 | import os 11 | from contextlib import redirect_stdout 12 | 13 | from lightning.app.testing.testing import LightningTestApp, application_testing 14 | 15 | os.environ["TESTING_LAI"] = "true" 16 | 17 | 18 | class LightningAppTestInt(LightningTestApp): 19 | def run_once(self) -> bool: 20 | f = io.StringIO() 21 | with redirect_stdout(f): 22 | super().run_once() 23 | out = f.getvalue() 24 | assert "⚡ Lightning Research App! ⚡\n" == out 25 | return True 26 | 27 | 28 | def test_research_app(): 29 | cwd = os.path.dirname(__file__) 30 | cwd = os.path.join(cwd, "app.py") 31 | command_line = [ 32 | cwd, 33 | "--blocking", 34 | "False", 35 | "--open-ui", 36 | "False", 37 | ] 38 | result = application_testing(LightningAppTestInt, command_line) 39 | assert result.exit_code == 0 40 | -------------------------------------------------------------------------------- /research_app/components/jupyter_notebook.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import os 3 | import subprocess 4 | from pathlib import Path 5 | 6 | from lightning.app import LightningWork 7 | 8 | logger = logging.getLogger(__name__) 9 | 10 | 11 | class JupyterLab(LightningWork): 12 | def __init__(self): 13 | super().__init__(parallel=True) 14 | 15 | def run(self): 16 | jupyter_notebook_config_path = Path.home() / ".jupyter/jupyter_notebook_config.py" 17 | try: 18 | os.remove(jupyter_notebook_config_path) 19 | except FileNotFoundError: 20 | logger.debug("Jupyter config didn't exist!") 21 | 22 | cmd = "jupyter notebook --generate-config" 23 | subprocess.run(cmd, shell=True) 24 | 25 | with open(jupyter_notebook_config_path, "a") as f: 26 | f.write( 27 | "c.NotebookApp.tornado_settings = {'headers': {'Content-Security-Policy': " 28 | "\"frame-ancestors * 'self' http://0.0.0.0\"," 29 | ' "Access-Control-Allow-Origin": "http://0.0.0.0"}}' 30 | ) 31 | 32 | cmd = f"jupyter-lab --allow-root --no-browser --ip={self.host} --port={self.port} --NotebookApp.token='' --NotebookApp.password=''" # noqa: E501 33 | subprocess.run(cmd, shell=True) 34 | -------------------------------------------------------------------------------- /research_app/demo/model.py: -------------------------------------------------------------------------------- 1 | import logging 2 | 3 | import gradio as gr 4 | from lightning.app.components.serve import ServeGradio 5 | from rich.logging import RichHandler 6 | 7 | from research_app.demo.clip import CLIPDemo 8 | 9 | FORMAT = "%(message)s" 10 | logging.basicConfig(level="INFO", format=FORMAT, datefmt="[%X]", handlers=[RichHandler()]) 11 | 12 | logger = logging.getLogger(__name__) 13 | 14 | 15 | class ModelDemo(ServeGradio): 16 | """Serve model with Gradio UI. 17 | 18 | You need to define i. `build_model` and ii. `predict` method and Lightning `ServeGradio` component will 19 | automatically launch the Gradio interface. 20 | """ 21 | 22 | inputs = gr.inputs.Textbox(default="Going into the space", label="Unsplash Image Search") 23 | outputs = gr.outputs.HTML(label="Images from Unsplash") 24 | enable_queue = True 25 | examples = [["Cat reading a book"], ["Going into the space"]] 26 | 27 | def __init__(self): 28 | super().__init__(parallel=True) 29 | 30 | def build_model(self) -> CLIPDemo: 31 | logger.info("loading model...") 32 | clip = CLIPDemo() 33 | logger.info("built model!") 34 | return clip 35 | 36 | def predict(self, query: str) -> str: 37 | return self.model.predict(query) 38 | -------------------------------------------------------------------------------- /.github/workflows/ci-testing.yml: -------------------------------------------------------------------------------- 1 | name: CI testing 2 | 3 | # see: https://help.github.com/en/actions/reference/events-that-trigger-workflows 4 | on: 5 | # Trigger the workflow on push or pull request, but only for the master branch 6 | push: 7 | branches: [ main ] 8 | pull_request: 9 | branches: [ main ] 10 | 11 | jobs: 12 | pytest: 13 | 14 | runs-on: ${{ matrix.os }} 15 | strategy: 16 | fail-fast: false 17 | matrix: 18 | os: [ ubuntu-latest, macOS-latest ] 19 | python-version: [ 3.9 ] 20 | 21 | # Timeout: https://stackoverflow.com/a/59076067/4521646 22 | timeout-minutes: 15 23 | 24 | steps: 25 | - uses: actions/checkout@v4 26 | - name: Set up Python ${{ matrix.python-version }} 27 | uses: actions/setup-python@v5 28 | with: 29 | python-version: ${{ matrix.python-version }} 30 | 31 | - name: Install dependencies 32 | run: | 33 | pip --version 34 | pip install -e . -U -q -r tests/requirements.txt -f https://download.pytorch.org/whl/cpu/torch_stable.html 35 | pip list 36 | shell: bash 37 | 38 | - name: Tests 39 | run: coverage run --source research_app -m pytest research_app tests -v 40 | 41 | - name: Statistics 42 | run: coverage report 43 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # Basic dependabot.yml file with 2 | # minimum configuration for two package managers 3 | 4 | version: 2 5 | updates: 6 | # Enable version updates for python 7 | - package-ecosystem: "pip" 8 | # Look for a `requirements` in the `root` directory 9 | directory: "/" 10 | # Check for updates once a week 11 | schedule: 12 | interval: "monthly" 13 | # Labels on pull requests for version updates only 14 | labels: 15 | - "ci / tests" 16 | pull-request-branch-name: 17 | # Separate sections of the branch name with a hyphen 18 | # for example, `dependabot-npm_and_yarn-next_js-acorn-6.4.1` 19 | separator: "-" 20 | # Allow up to 5 open pull requests for pip dependencies 21 | open-pull-requests-limit: 5 22 | reviewers: 23 | - "aniketmaurya" 24 | 25 | # Enable version updates for GitHub Actions 26 | - package-ecosystem: "github-actions" 27 | directory: "/" 28 | # Check for updates once a week 29 | schedule: 30 | interval: "monthly" 31 | # Labels on pull requests for version updates only 32 | labels: 33 | - "ci / tests" 34 | pull-request-branch-name: 35 | # Separate sections of the branch name with a hyphen 36 | # for example, `dependabot-npm_and_yarn-next_js-acorn-6.4.1` 37 | separator: "-" 38 | # Allow up to 5 open pull requests for GitHub Actions 39 | open-pull-requests-limit: 5 40 | reviewers: 41 | - "aniketmaurya" 42 | -------------------------------------------------------------------------------- /research_app/utils.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import os 3 | import subprocess 4 | import tempfile 5 | from pathlib import Path 6 | 7 | from rich.logging import RichHandler 8 | 9 | FORMAT = "%(message)s" 10 | logging.basicConfig(level="INFO", format=FORMAT, datefmt="[%X]", handlers=[RichHandler()]) 11 | 12 | logger = logging.getLogger(__name__) 13 | 14 | 15 | def notebook_to_html(path: str) -> str: 16 | """Provided notebook file path will be converted into html.""" 17 | if not os.path.exists(path): 18 | raise FileNotFoundError(f"Can't convert notebook to html, path={path} not found!") 19 | 20 | tempdir = tempfile.mkdtemp() 21 | command = f"jupyter nbconvert --to html {path} --output-dir='{tempdir}' --output index.html" 22 | subprocess.run(command, shell=True) 23 | return tempdir 24 | 25 | 26 | def clone_repo(url: str) -> str: 27 | """Clones the github repo from url to current dir. 28 | 29 | Example: 30 | url = "https://github.com/PyTorchLightning/lightning-template-research-app.git" 31 | clone_repo(url) 32 | 33 | The given repo will be cloned to current dir. 34 | """ 35 | logger.info(f"cloning {url}") 36 | tempdir = Path(tempfile.mkdtemp()) 37 | target_path = str(tempdir / os.path.basename(url)).replace(".git", "") 38 | cmd = f"git clone {url} {target_path}" 39 | subprocess.run(cmd, shell=True) 40 | return target_path 41 | 42 | 43 | if __name__ == "__main__": 44 | clone_repo("https://github.com/PyTorchLightning/lightning-template-research-app.git") # E501 45 | -------------------------------------------------------------------------------- /research_app/components/jupyter_lite.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import os.path 3 | import subprocess 4 | 5 | from lightning.app import LightningApp, LightningFlow, LightningWork 6 | 7 | logger = logging.getLogger(__name__) 8 | 9 | 10 | class JupyterLite(LightningWork): 11 | """This component will launch JupyterLab instance that runs entirely in the browser. 12 | 13 | https://jupyterlite.readthedocs.io/en/latest/ 14 | 15 | contents: folder location to be copied while building jupyter lite. This will appear in the Jupyterlab. 16 | """ 17 | 18 | def __init__(self, contents="research_app", **kwargs): 19 | super().__init__(parallel=True, **kwargs) 20 | assert os.path.exists(contents), f"{contents} not exist at {os.getcwd()}" 21 | self.contents = contents 22 | 23 | def run(self): 24 | cmd = "jupyter lite init" 25 | subprocess.run(cmd, shell=True) 26 | 27 | cmd = "jupyter lite build" 28 | subprocess.run(cmd, shell=True) 29 | 30 | cmd = f"jupyter lite serve --contents {self.contents} --port {self.port}" 31 | subprocess.run(cmd, shell=True) 32 | 33 | 34 | if __name__ == "__main__": 35 | 36 | class Demo(LightningFlow): 37 | def __init__(self) -> None: 38 | super().__init__() 39 | self.lite = JupyterLite(github_url="https://github.com/openai/CLIP") 40 | 41 | def run(self): 42 | self.lite.run() 43 | 44 | def configure_layout(self): 45 | return [{"name": "lite", "content": self.lite.url}] 46 | 47 | app = LightningApp(Demo()) 48 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import os 4 | from importlib.util import module_from_spec, spec_from_file_location 5 | 6 | from pkg_resources import parse_requirements 7 | from setuptools import find_packages, setup 8 | 9 | _PATH_ROOT = os.path.dirname(__file__) 10 | 11 | 12 | def _load_requirements(path_dir: str = _PATH_ROOT, file_name: str = "requirements.txt") -> list: 13 | reqs = parse_requirements(open(os.path.join(path_dir, file_name)).readlines()) 14 | return list(map(str, reqs)) 15 | 16 | 17 | def _load_py_module(fname, pkg="research_app"): 18 | spec = spec_from_file_location(os.path.join(pkg, fname), os.path.join(_PATH_ROOT, pkg, fname)) 19 | py = module_from_spec(spec) 20 | spec.loader.exec_module(py) 21 | return py 22 | 23 | 24 | about = _load_py_module("__about__.py") 25 | with open(os.path.join(_PATH_ROOT, "README.md"), encoding="utf-8") as fo: 26 | readme = fo.read() 27 | 28 | setup( 29 | name="research-app", 30 | version=about.__version__, 31 | description=about.__docs__, 32 | author=about.__author__, 33 | author_email=about.__author_email__, 34 | url=about.__homepage__, 35 | download_url="https://github.com/PyTorchLightning/lightning", 36 | license=about.__license__, 37 | packages=find_packages(exclude=["tests", "docs"]), 38 | long_description=readme, 39 | long_description_content_type="text/markdown", 40 | include_package_data=True, 41 | zip_safe=False, 42 | keywords=["deep learning", "pytorch", "AI"], 43 | python_requires=">=3.8", 44 | setup_requires=["wheel"], 45 | install_requires=_load_requirements(), 46 | ) 47 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | default_language_version: 2 | python: python3 3 | 4 | ci: 5 | autofix_prs: true 6 | autoupdate_commit_msg: '[pre-commit.ci] pre-commit suggestions' 7 | autoupdate_schedule: 'quarterly' 8 | 9 | repos: 10 | - repo: https://github.com/pre-commit/pre-commit-hooks 11 | rev: v4.5.0 12 | hooks: 13 | - id: end-of-file-fixer 14 | - id: trailing-whitespace 15 | - id: check-case-conflict 16 | - id: check-yaml 17 | - id: check-toml 18 | - id: check-json 19 | - id: check-added-large-files 20 | - id: check-docstring-first 21 | - id: detect-private-key 22 | 23 | - repo: https://github.com/asottile/pyupgrade 24 | rev: v3.15.0 25 | hooks: 26 | - id: pyupgrade 27 | args: [--py38-plus] 28 | name: Upgrade code 29 | 30 | - repo: https://github.com/PyCQA/docformatter 31 | rev: v1.7.5 32 | hooks: 33 | - id: docformatter 34 | args: [--in-place, --wrap-summaries=120, --wrap-descriptions=120] 35 | 36 | - repo: https://github.com/psf/black 37 | rev: 23.12.1 38 | hooks: 39 | - id: black 40 | name: Black code 41 | args: ["--line-length=120"] 42 | 43 | - repo: https://github.com/executablebooks/mdformat 44 | rev: 0.7.17 45 | hooks: 46 | - id: mdformat 47 | additional_dependencies: 48 | - mdformat-gfm 49 | - mdformat-black 50 | - mdformat_frontmatter 51 | 52 | - repo: https://github.com/astral-sh/ruff-pre-commit 53 | rev: v0.1.9 54 | hooks: 55 | - id: ruff 56 | args: ["--fix", "--line-length=120", "--ignore=E402"] 57 | -------------------------------------------------------------------------------- /research_app/components/app_status.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from typing import Dict, List, Union 3 | 4 | import streamlit as st 5 | from lightning.app import LightningFlow, LightningWork 6 | from lightning.app.frontend import StreamlitFrontend 7 | from lightning.app.utilities.state import AppState 8 | from rich.logging import RichHandler 9 | from streamlit_autorefresh import st_autorefresh 10 | 11 | FORMAT = "%(message)s" 12 | logging.basicConfig(level="INFO", format=FORMAT, datefmt="[%X]", handlers=[RichHandler()]) 13 | 14 | logger = logging.getLogger(__name__) 15 | 16 | 17 | # This component is WIP @aniketmaurya 18 | class AppStatus(LightningFlow): 19 | """This component shows the list of Works which are not ready.""" 20 | 21 | def __init__(self, components: List[Union[LightningWork, LightningFlow]]) -> None: 22 | super().__init__() 23 | self.components: Dict[str, bool] = {} 24 | self.close = False 25 | for component in components: 26 | self.components[component.name] = getattr(component, "ready", None) 27 | 28 | @property 29 | def all_ready(self) -> bool: 30 | for name, ready in self.components.items(): 31 | if ready is False: 32 | return False 33 | return True 34 | 35 | def run(self) -> None: 36 | if self.all_ready: 37 | self.close = self.all_ready 38 | return 39 | 40 | for component, ready in self.components.items(): 41 | if not ready: 42 | return 43 | 44 | def configure_layout(self): 45 | return StreamlitFrontend(render_fn=render) 46 | 47 | 48 | def render(state: AppState): 49 | st_autorefresh(interval=1000) 50 | 51 | if not state.close: 52 | st.title("App status") 53 | st.write("Some components of this app is not ready yet! Please wait for sometime...") 54 | 55 | md = "" 56 | for name, ready in state.components.item(): 57 | logger.debug(f"{name} not ready!") 58 | if ready is False: 59 | md += f"* {name.capitalize()} ❌\n" 60 | 61 | st.markdown(md) 62 | 63 | else: 64 | st.title("All components ready!") 65 | st.write("This tab will close itself soon.") 66 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ⚡️ Lightning Research Poster Template 🔬 2 | 3 | [![Lightning](https://img.shields.io/badge/-Lightning-792ee5?logo=pytorchlightning&logoColor=white)](https://lightning.ai) 4 | ![license](https://img.shields.io/badge/License-Apache%202.0-blue.svg) 5 | [![CI testing](https://github.com/Lightning-Universe/Research-poster/actions/workflows/ci-testing.yml/badge.svg?event=push)](https://github.com/Lightning-Universe/Research-poster/actions/workflows/ci-testing.yml) 6 | [![pre-commit.ci status](https://results.pre-commit.ci/badge/github/Lightning-Universe/Research-poster/main.svg)](https://results.pre-commit.ci/latest/github/Lightning-Universe/Research-poster/main) 7 | 8 | Use this app to share your research paper results. This app lets you connect a blogpost, arxiv paper, and a jupyter 9 | notebook and even have an interactive demo for people to play with the model. This app also allows industry 10 | practitioners to reproduce your work. 11 | 12 | ## Getting started 13 | 14 | To create a Research Poster you can install this app via the [Lightning CLI](https://lightning.ai/lightning-docs/) or 15 | [use the template](https://docs.github.com/en/articles/creating-a-repository-from-a-template) from GitHub and 16 | manually install the app as mentioned below. 17 | 18 | > ![image](./assets/demo.png) 19 | 20 | You can modify the content of this app and customize it to your research. 21 | At the root of this template, you will find [app.py](./app.py) that contains the `ResearchApp` class. This class 22 | provides arguments like a link to a paper, a blog, and whether to launch a Gradio demo. You can read more about what 23 | each of the arguments does in the docstrings. 24 | 25 | ### 1. Poster Component 26 | 27 | This component lets you make research posters using markdown files. The component comes with a predefined poster.md file 28 | in the resources folder that contains markdown content for building the poster. You can directly update the existing 29 | file with your research content. 30 | 31 | ### 2. Link to Paper, blog and Training Logs 32 | 33 | You can add your research paper, a blog post, and training logs to your app. These are usually static web links that can 34 | be directly passed as optional arguments within app.py 35 | 36 | ### 3. A view only Jupyter Notebook 37 | 38 | You can provide the path to your notebook and it will be converted into static HTML. 39 | 40 | ### 4. Model Demo 41 | 42 | To create an interactive demo you’d need to implement the `build_model` and `predict` methods of the ModelDemo class 43 | present 44 | in the `research_app/demo/model.py` module. 45 | 46 | ### 5. JupyterLab Component 47 | 48 | This component runs and adds a JupyterLab instance to your app. You can provide a way to edit and run your code for 49 | quick audience demonstrations. However, note that sharing a JupyterLab instance can expose the cloud instance to 50 | security vulnerability. 51 | -------------------------------------------------------------------------------- /research_app/demo/clip.py: -------------------------------------------------------------------------------- 1 | """This module implements the demo for CLIP model. 2 | 3 | This demo is inspired from the work of [Vivien](https://github.com/vivien000). Checkout the original implementation 4 | [here](( 5 | https://github.com/vivien000/clip-demo) 6 | The app integration is done at `research_app/components/model.py`. 7 | """ 8 | import enum 9 | import logging 10 | import os.path 11 | import urllib.request 12 | from typing import List 13 | 14 | import numpy as np 15 | import pandas as pd 16 | from rich import print 17 | from rich.logging import RichHandler 18 | from transformers import CLIPModel, CLIPProcessor 19 | 20 | FORMAT = "%(message)s" 21 | logging.basicConfig(level="INFO", format=FORMAT, datefmt="[%X]", handlers=[RichHandler()]) 22 | 23 | logger = logging.getLogger(__name__) 24 | 25 | 26 | class DATASET(enum.Enum): 27 | UNSPLASH = "Unsplash" 28 | MOVIES = "Movies" 29 | 30 | 31 | dataset = DATASET.UNSPLASH.value 32 | _HTTP_POSTER_ASSETS = "https://github.com/aniketmaurya/temp-poster-assets/blob/main/" 33 | 34 | 35 | def download_files(): 36 | print("Downloading embeddings, this might take some time!") 37 | urllib.request.urlretrieve(_HTTP_POSTER_ASSETS + "embeddings.npy?raw=true", "resources/embeddings.npy") 38 | urllib.request.urlretrieve(_HTTP_POSTER_ASSETS + "embeddings2.npy?raw=true", "resources/embeddings2.npy") 39 | urllib.request.urlretrieve(_HTTP_POSTER_ASSETS + "data.csv?raw=true", "resources/data.csv") 40 | urllib.request.urlretrieve( 41 | "https://drive.google.com/uc?export=download&id=19aVnFBY-Rc0-3VErF_C7PojmWpBsb5wk", "resources/data2.csv" 42 | ) 43 | logger.info("✅ Downloaded embeddings") 44 | 45 | 46 | def get_html(url_list, height=200): 47 | html = "
" 48 | for url, title, link in url_list: 49 | html2 = f"" 50 | if len(link) > 0: 51 | html2 = f"" + html2 + "" 52 | html = html + html2 53 | html += "
" 54 | return html 55 | 56 | 57 | class CLIPDemo: 58 | def _pre_setup(self): 59 | if not os.path.exists("resources/data.csv"): 60 | download_files() 61 | 62 | self.df = {0: pd.read_csv("resources/data.csv"), 1: pd.read_csv("resources/data2.csv")} 63 | self.EMBEDDINGS = { 64 | 0: np.load("resources/embeddings.npy"), 65 | 1: np.load("resources/embeddings2.npy"), 66 | } 67 | for k in [0, 1]: 68 | self.EMBEDDINGS[k] = np.divide( 69 | self.EMBEDDINGS[k], np.sqrt(np.sum(self.EMBEDDINGS[k] ** 2, axis=1, keepdims=True)) 70 | ) 71 | self.source = {0: "\nSource: Unsplash", 1: "\nSource: The Movie Database (TMDB)"} 72 | 73 | def __init__(self): 74 | self.source = None 75 | self.df = None 76 | self.EMBEDDINGS = None 77 | 78 | self._pre_setup() 79 | 80 | self.model = CLIPModel.from_pretrained("openai/clip-vit-base-patch32").eval() 81 | self.processor = CLIPProcessor.from_pretrained("openai/clip-vit-base-patch32") 82 | for p in self.model.parameters(): 83 | p.requires_grad = False 84 | 85 | def _compute_text_embeddings(self, list_of_strings: List[str]): 86 | inputs = self.processor(text=list_of_strings, return_tensors="pt", padding=True) 87 | return self.model.get_text_features(**inputs) 88 | 89 | def _image_search(self, query: str, n_results=24): 90 | assert isinstance(query, str), f"query is of type {type(query)}" 91 | text_embeddings = self._compute_text_embeddings([query]).detach().numpy() 92 | k = 0 if dataset == "Unsplash" else 1 93 | results = np.argsort((self.EMBEDDINGS[k] @ text_embeddings.T)[:, 0])[-1 : -n_results - 1 : -1] # noqa E203 94 | result = [ 95 | (self.df[k].iloc[i]["path"], self.df[k].iloc[i]["tooltip"] + self.source[k], self.df[k].iloc[i]["link"]) 96 | for i in results 97 | ] 98 | return result 99 | 100 | def predict(self, query: str) -> str: 101 | results = self._image_search(query) 102 | return get_html(results) 103 | -------------------------------------------------------------------------------- /tests/resources/poster.md: -------------------------------------------------------------------------------- 1 |
2 |
3 | 4 |
5 |
6 |

Demo: CLIP Research Poster

7 |

A demo of CLIP research paper using Lightning App

8 |
9 |
10 |
11 | 12 |
OpenAI
13 |
14 |
15 | 16 |
@OpenAI
17 |
18 |
19 | 20 | --split-- 21 | 22 | # Natural Language based Image Search 23 | 24 | ## OpenAI introduced a neural network called CLIP which efficiently learns visual concepts from natural language supervision. 25 | 26 | This app is a demo 27 | of [Lightning Research Template app](https://github.com/Lightning-AI/lightning-template-research-app) which allows 28 | authors to build an app to share their everything 29 | related to their work at a single place. 30 | Explore the tabs at the top of this app to view blog, paper, training logs and model demo. 31 | 32 | You can fork this app and edit to customize according to your need. 33 | 34 | Kudos to Soumik Rakshit and Manan Goel for their awesome 35 | repository [clip-lightning](https://github.com/soumik12345/clip-lightning) 36 | 37 | Thanks to [Vivien](https://github.com/vivien000) for his inspiring application using 38 | CLIP [Minimal user-friendly demo of OpenAI's CLIP for semantic image search](https://github.com/vivien000/clip-demo). 39 | 40 | 41 | 42 | CLIP pre-trains an image encoder and a text encoder to predict which images were paired with which texts in our dataset. 43 | We then use this behavior to turn CLIP into a zero-shot classifier. We convert all of a dataset's classes into captions 44 | such as "a photo of a dog" and predict the class of the caption CLIP estimates best pairs with a given image. 45 | 46 | --split-- 47 | 48 | # Lightning Apps 49 | 50 | ## Lightning Apps can be built for any AI use case, including AI research, fault-tolerant production-ready pipelines, and everything in between. 51 | 52 | !!! abstract "Key Features" 53 | 54 | ``` 55 | - **Easy to use-** Lightning apps follow the Lightning philosophy- easy to read, modular, intuitive, pythonic and highly composable interface that allows you to focus on what's important for you, and automate the rest. 56 | - **Easy to scale**- Lightning provides a common experience locally and in the cloud. The Lightning.ai cloud platform abstracts the infrastructure, so you can run your apps at any scale. The modular and composable framework allows for simpler testing and debugging. 57 | - **Leverage the power of the community-** Lightning.ai offers a variety of apps for any use case you can use as is or build upon. By following the best MLOps practices provided through the apps and documentation you can deploy state-of-the-art ML applications in days, not months. 58 | ``` 59 | 60 | ```mermaid 61 | graph LR 62 | A[local ML] 63 | A --> B{Lightning Apps
Effortless GPU distributed compute} 64 | B -->|Frontend| C[Lightning Work 1] 65 | B -->|DB integration| D[Lightning Work 2] 66 | B -->|User auth| E[Lightning Work 3] 67 | ``` 68 | 69 | ### Available at : `Lightning-AI/lightning-template-research-app/app.py` 70 | 71 | ```python 72 | from lightning.app import LightningApp 73 | 74 | paper = "https://arxiv.org/pdf/2103.00020.pdf" 75 | blog = "https://openai.com/blog/clip/" 76 | github = "https://github.com/soumik12345/clip-lightning/tree/AddModelCheckpoint" 77 | wandb = "https://wandb.ai/manan-goel/clip-lightning-image_retrieval/runs/1cedtohj" 78 | 79 | app = LightningApp( 80 | ResearchApp( 81 | resource_path="resources", 82 | paper=paper, 83 | blog=blog, 84 | training_log_url=wandb, 85 | github=github, 86 | notebook_path="resources/Interacting_with_CLIP.ipynb", 87 | launch_gradio=True, 88 | ) 89 | ) 90 | ``` 91 | 92 | ### Citation 93 | 94 | ```bibtex 95 | 96 | @article{YourName, 97 | title={Your Title}, 98 | author={Your team}, 99 | journal={Location}, 100 | year={Year} 101 | } 102 | 103 | ``` 104 | -------------------------------------------------------------------------------- /tests/app.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import os 3 | from typing import Dict, List, Optional 4 | 5 | from lightning.app import LightningFlow, LightningApp 6 | from lightning.app.frontend import StaticWebFrontend 7 | from poster import Poster 8 | from rich import print 9 | from rich.logging import RichHandler 10 | 11 | from research_app.components.jupyter_notebook import JupyterLab 12 | from research_app.demo.model import ModelDemo 13 | from research_app.utils import clone_repo, notebook_to_html 14 | 15 | FORMAT = "%(message)s" 16 | logging.basicConfig(level="NOTSET", format=FORMAT, datefmt="[%X]", handlers=[RichHandler()]) 17 | 18 | logger = logging.getLogger(__name__) 19 | 20 | 21 | class StaticNotebookViewer(LightningFlow): 22 | def __init__(self, notebook_path: str): 23 | super().__init__() 24 | self.serve_dir = notebook_to_html(notebook_path) 25 | 26 | def configure_layout(self): 27 | return StaticWebFrontend(serve_dir=self.serve_dir) 28 | 29 | 30 | class ResearchApp(LightningFlow): 31 | """Share your paper "bundled" with the arxiv link, poster, live jupyter notebook, interactive demo to try the model 32 | and more! 33 | 34 | poster_dir: folder path of markdown file. The markdown will be converted into a poster and launched as static 35 | html. 36 | paper: [Optional] Arxiv link to your paper 37 | blog: [Optional] Link to a blog post for your research 38 | github: [Optional] Clone GitHub repo to a temporary directory. 39 | training_log_url: [Optional] Link for experiment manager like wandb or tensorboard 40 | notebook_path: [Optional] View a Jupyter Notebook as static html tab 41 | launch_jupyter_lab: Launch a full-fledged Jupyter Lab instance. Note that sharing Jupyter publicly is not 42 | recommended and exposes security vulnerability to the cloud. Defaults to False. 43 | launch_gradio: Launch Gradio demo. Defaults to False. You should update the 44 | `research_app/components/model.py` file to your use case. 45 | tab_order: You can optionally reorder the tab layout by providing a list of tab name. 46 | """ 47 | 48 | def __init__( 49 | self, 50 | poster_dir: str, 51 | paper: Optional[str] = None, 52 | blog: Optional[str] = None, 53 | github: Optional[str] = None, 54 | notebook_path: Optional[str] = None, 55 | training_log_url: Optional[str] = None, 56 | launch_jupyter_lab: bool = False, 57 | launch_gradio: bool = False, 58 | tab_order: Optional[List[str]] = None, 59 | ) -> None: 60 | super().__init__() 61 | self.poster_dir = os.path.abspath(poster_dir) 62 | self.paper = paper 63 | self.blog = blog 64 | self.training_logs = training_log_url 65 | self.notebook_path = notebook_path 66 | self.jupyter_lab = None 67 | self.model_demo = None 68 | self.poster = Poster(resource_dir=self.poster_dir) 69 | self.notebook_viewer = None 70 | self.tab_order = tab_order 71 | 72 | if github: 73 | clone_repo(github) 74 | 75 | if launch_jupyter_lab: 76 | self.jupyter_lab = JupyterLab() 77 | logger.warning( 78 | "Sharing Jupyter publicly is not recommended and exposes security vulnerability " 79 | "to the cloud instance." 80 | ) 81 | 82 | if launch_gradio: 83 | self.model_demo = ModelDemo() 84 | 85 | if notebook_path: 86 | self.notebook_viewer = StaticNotebookViewer(notebook_path) 87 | 88 | def run(self) -> None: 89 | if os.environ.get("TESTING_LAI"): 90 | print("⚡ Lightning Research App! ⚡") 91 | self.poster.run() 92 | if self.jupyter_lab: 93 | self.jupyter_lab.run() 94 | if self.model_demo: 95 | self.model_demo.run() 96 | 97 | def configure_layout(self) -> List[Dict[str, str]]: 98 | tabs = [] 99 | 100 | tabs.append({"name": "Poster", "content": self.poster.url + "/poster.html"}) 101 | 102 | if self.blog: 103 | tabs.append({"name": "Blog", "content": self.blog}) 104 | 105 | if self.paper: 106 | tabs.append({"name": "Paper", "content": self.paper}) 107 | 108 | if self.notebook_viewer: 109 | tabs.append({"name": "Notebook Viewer", "content": self.notebook_viewer}) 110 | 111 | if self.training_logs: 112 | tabs.append({"name": "Training Logs", "content": self.training_logs}) 113 | 114 | if self.model_demo: 115 | tabs.append({"name": "Model Demo: Unsplash Image Search", "content": self.model_demo.url}) 116 | 117 | if self.jupyter_lab: 118 | tabs.append({"name": "Jupyter Lab", "content": self.jupyter_lab.url}) 119 | 120 | return self._order_tabs(tabs) 121 | 122 | def _order_tabs(self, tabs: List[dict]): 123 | """Reorder the tab layout.""" 124 | if self.tab_order is None: 125 | return tabs 126 | order_int: Dict[str, int] = {e.lower(): i for i, e in enumerate(self.tab_order)} 127 | try: 128 | return sorted(tabs, key=lambda x: order_int[x["name"].lower()]) 129 | except KeyError as e: 130 | logger.error( 131 | f"One of the key '{e.args[0]}' that you passed as `tab_order` argument is missing or incorrect. " 132 | f"Please check {tabs}" 133 | ) 134 | 135 | 136 | if __name__ == "__main__": 137 | path_here = os.path.dirname(__file__) 138 | poster_dir = os.path.join(path_here, "resources") 139 | 140 | app = LightningApp( 141 | ResearchApp( 142 | poster_dir=poster_dir, 143 | paper="https://arxiv.org/pdf/2103.00020", 144 | blog="https://openai.com/blog/clip/", 145 | training_log_url="https://wandb.ai/manan-goel/clip-lightning-image_retrieval/runs/1cedtohj", 146 | notebook_path=os.path.join(poster_dir, "Interacting_with_CLIP.ipynb"), 147 | launch_gradio=True, 148 | tab_order=[ 149 | "Blog", 150 | "Paper", 151 | "Poster", 152 | "Notebook Viewer", 153 | "Training Logs", 154 | "Model Demo: Unsplash Image Search", 155 | ], 156 | launch_jupyter_lab=False, # don't launch for public app, can expose to security vulnerability 157 | ) 158 | ) 159 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by https://www.toptal.com/developers/gitignore/api/python,pycharm,macos,images 2 | # Edit at https://www.toptal.com/developers/gitignore?templates=python,pycharm,macos,images 3 | 4 | ### Images ### 5 | # JPEG 6 | *.jpg 7 | *.jpeg 8 | *.jpe 9 | *.jif 10 | *.jfif 11 | *.jfi 12 | 13 | # JPEG 2000 14 | *.jp2 15 | *.j2k 16 | *.jpf 17 | *.jpx 18 | *.jpm 19 | *.mj2 20 | 21 | # JPEG XR 22 | *.jxr 23 | *.hdp 24 | *.wdp 25 | 26 | # Graphics Interchange Format 27 | *.gif 28 | 29 | # RAW 30 | *.raw 31 | 32 | # Web P 33 | *.webp 34 | 35 | # Portable Network Graphics 36 | *.png 37 | 38 | # Animated Portable Network Graphics 39 | *.apng 40 | 41 | # Multiple-image Network Graphics 42 | *.mng 43 | 44 | # Tagged Image File Format 45 | *.tiff 46 | *.tif 47 | 48 | # Scalable Vector Graphics 49 | *.svg 50 | *.svgz 51 | 52 | # Portable Document Format 53 | *.pdf 54 | 55 | # X BitMap 56 | *.xbm 57 | 58 | # BMP 59 | *.bmp 60 | *.dib 61 | 62 | # ICO 63 | *.ico 64 | 65 | # 3D Images 66 | *.3dm 67 | *.max 68 | 69 | ### macOS ### 70 | # General 71 | .DS_Store 72 | .AppleDouble 73 | .LSOverride 74 | 75 | # Icon must end with two \r 76 | Icon 77 | 78 | 79 | # Thumbnails 80 | ._* 81 | 82 | # Files that might appear in the root of a volume 83 | .DocumentRevisions-V100 84 | .fseventsd 85 | .Spotlight-V100 86 | .TemporaryItems 87 | .Trashes 88 | .VolumeIcon.icns 89 | .com.apple.timemachine.donotpresent 90 | 91 | # Directories potentially created on remote AFP share 92 | .AppleDB 93 | .AppleDesktop 94 | Network Trash Folder 95 | Temporary Items 96 | .apdisk 97 | 98 | ### macOS Patch ### 99 | # iCloud generated files 100 | *.icloud 101 | 102 | ### PyCharm ### 103 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider 104 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 105 | 106 | # User-specific stuff 107 | .idea/**/workspace.xml 108 | .idea/**/tasks.xml 109 | .idea/**/usage.statistics.xml 110 | .idea/**/dictionaries 111 | .idea/**/shelf 112 | 113 | # AWS User-specific 114 | .idea/**/aws.xml 115 | 116 | # Generated files 117 | .idea/**/contentModel.xml 118 | 119 | # Sensitive or high-churn files 120 | .idea/**/dataSources/ 121 | .idea/**/dataSources.ids 122 | .idea/**/dataSources.local.xml 123 | .idea/**/sqlDataSources.xml 124 | .idea/**/dynamic.xml 125 | .idea/**/uiDesigner.xml 126 | .idea/**/dbnavigator.xml 127 | 128 | # Gradle 129 | .idea/**/gradle.xml 130 | .idea/**/libraries 131 | 132 | # Gradle and Maven with auto-import 133 | # When using Gradle or Maven with auto-import, you should exclude module files, 134 | # since they will be recreated, and may cause churn. Uncomment if using 135 | # auto-import. 136 | # .idea/artifacts 137 | # .idea/compiler.xml 138 | # .idea/jarRepositories.xml 139 | # .idea/modules.xml 140 | # .idea/*.iml 141 | # .idea/modules 142 | # *.iml 143 | # *.ipr 144 | 145 | # CMake 146 | cmake-build-*/ 147 | 148 | # Mongo Explorer plugin 149 | .idea/**/mongoSettings.xml 150 | 151 | # File-based project format 152 | *.iws 153 | 154 | # IntelliJ 155 | out/ 156 | 157 | # mpeltonen/sbt-idea plugin 158 | .idea_modules/ 159 | 160 | # JIRA plugin 161 | atlassian-ide-plugin.xml 162 | 163 | # Cursive Clojure plugin 164 | .idea/replstate.xml 165 | 166 | # SonarLint plugin 167 | .idea/sonarlint/ 168 | 169 | # Crashlytics plugin (for Android Studio and IntelliJ) 170 | com_crashlytics_export_strings.xml 171 | crashlytics.properties 172 | crashlytics-build.properties 173 | fabric.properties 174 | 175 | # Editor-based Rest Client 176 | .idea/httpRequests 177 | 178 | # Android studio 3.1+ serialized cache file 179 | .idea/caches/build_file_checksums.ser 180 | 181 | ### PyCharm Patch ### 182 | # Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721 183 | 184 | # *.iml 185 | # modules.xml 186 | # .idea/misc.xml 187 | # *.ipr 188 | 189 | # Sonarlint plugin 190 | # https://plugins.jetbrains.com/plugin/7973-sonarlint 191 | .idea/**/sonarlint/ 192 | 193 | # SonarQube Plugin 194 | # https://plugins.jetbrains.com/plugin/7238-sonarqube-community-plugin 195 | .idea/**/sonarIssues.xml 196 | 197 | # Markdown Navigator plugin 198 | # https://plugins.jetbrains.com/plugin/7896-markdown-navigator-enhanced 199 | .idea/**/markdown-navigator.xml 200 | .idea/**/markdown-navigator-enh.xml 201 | .idea/**/markdown-navigator/ 202 | 203 | # Cache file creation bug 204 | # See https://youtrack.jetbrains.com/issue/JBR-2257 205 | .idea/$CACHE_FILE$ 206 | 207 | # CodeStream plugin 208 | # https://plugins.jetbrains.com/plugin/12206-codestream 209 | .idea/codestream.xml 210 | 211 | ### Python ### 212 | # Byte-compiled / optimized / DLL files 213 | __pycache__/ 214 | *.py[cod] 215 | *$py.class 216 | 217 | # C extensions 218 | *.so 219 | 220 | # Distribution / packaging 221 | .Python 222 | build/ 223 | develop-eggs/ 224 | dist/ 225 | downloads/ 226 | eggs/ 227 | .eggs/ 228 | lib/ 229 | lib64/ 230 | parts/ 231 | sdist/ 232 | var/ 233 | wheels/ 234 | share/python-wheels/ 235 | *.egg-info/ 236 | .installed.cfg 237 | *.egg 238 | MANIFEST 239 | 240 | # PyInstaller 241 | # Usually these files are written by a python script from a template 242 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 243 | *.manifest 244 | *.spec 245 | 246 | # Installer logs 247 | pip-log.txt 248 | pip-delete-this-directory.txt 249 | 250 | # Unit test / coverage reports 251 | htmlcov/ 252 | .tox/ 253 | .nox/ 254 | .coverage 255 | .coverage.* 256 | .cache 257 | nosetests.xml 258 | coverage.xml 259 | *.cover 260 | *.py,cover 261 | .hypothesis/ 262 | .pytest_cache/ 263 | cover/ 264 | 265 | # Translations 266 | *.mo 267 | *.pot 268 | 269 | # Django stuff: 270 | *.log 271 | local_settings.py 272 | db.sqlite3 273 | db.sqlite3-journal 274 | 275 | # Flask stuff: 276 | instance/ 277 | .webassets-cache 278 | 279 | # Scrapy stuff: 280 | .scrapy 281 | 282 | # Sphinx documentation 283 | docs/_build/ 284 | 285 | # PyBuilder 286 | .pybuilder/ 287 | target/ 288 | 289 | # Jupyter Notebook 290 | .ipynb_checkpoints 291 | 292 | # IPython 293 | profile_default/ 294 | ipython_config.py 295 | 296 | # pyenv 297 | # For a library or package, you might want to ignore these files since the code is 298 | # intended to run in multiple environments; otherwise, check them in: 299 | # .python-version 300 | 301 | # pipenv 302 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 303 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 304 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 305 | # install all needed dependencies. 306 | #Pipfile.lock 307 | 308 | # poetry 309 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 310 | # This is especially recommended for binary packages to ensure reproducibility, and is more 311 | # commonly ignored for libraries. 312 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 313 | #poetry.lock 314 | 315 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 316 | __pypackages__/ 317 | 318 | # Celery stuff 319 | celerybeat-schedule 320 | celerybeat.pid 321 | 322 | # SageMath parsed files 323 | *.sage.py 324 | 325 | # Environments 326 | .env 327 | .venv 328 | env/ 329 | venv/ 330 | ENV/ 331 | env.bak/ 332 | venv.bak/ 333 | 334 | # Spyder project settings 335 | .spyderproject 336 | .spyproject 337 | 338 | # Rope project settings 339 | .ropeproject 340 | 341 | # mkdocs documentation 342 | /site 343 | 344 | # mypy 345 | .mypy_cache/ 346 | .dmypy.json 347 | dmypy.json 348 | 349 | # Pyre type checker 350 | .pyre/ 351 | 352 | # pytype static type analyzer 353 | .pytype/ 354 | 355 | # Cython debug symbols 356 | cython_debug/ 357 | 358 | # PyCharm 359 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 360 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 361 | # and can be added to the global gitignore or merged into this file. For a more nuclear 362 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 363 | #.idea/ 364 | 365 | # End of https://www.toptal.com/developers/gitignore/api/python,pycharm,macos,images 366 | 367 | *.pt 368 | *.pth 369 | *.ckpt 370 | data/ 371 | lightning_logs/ 372 | wandb/ 373 | .idea/ 374 | flagged/ 375 | .python-version 376 | github/ 377 | -------------------------------------------------------------------------------- /tests/test_app_gallery.py: -------------------------------------------------------------------------------- 1 | import json 2 | import os 3 | from contextlib import contextmanager 4 | from time import sleep 5 | from typing import Generator 6 | 7 | import pytest 8 | import requests 9 | from lightning.app.testing.config import _Config 10 | from lightning.app.utilities.cloud import _get_project 11 | from lightning.app.utilities.imports import _is_playwright_available, requires 12 | from lightning.app.utilities.network import LightningClient 13 | from lightning_cloud.openapi.rest import ApiException 14 | 15 | if _is_playwright_available(): 16 | import playwright 17 | from playwright.sync_api import HttpCredentials, sync_playwright 18 | 19 | 20 | @requires("playwright") 21 | @contextmanager 22 | def get_gallery_app_page(app_name) -> Generator: 23 | with sync_playwright() as p: 24 | browser = p.chromium.launch(timeout=5000, headless=bool(int(os.getenv("HEADLESS", "0")))) 25 | payload = { 26 | "apiKey": _Config.api_key, 27 | "username": _Config.username, 28 | "duration": "120000", 29 | } 30 | context = browser.new_context( 31 | http_credentials=HttpCredentials( 32 | { 33 | "username": os.getenv("LAI_USER", ""), 34 | "password": os.getenv("LAI_PASS", ""), 35 | } 36 | ), 37 | record_video_dir=os.path.join(_Config.video_location, app_name), 38 | record_har_path=_Config.har_location, 39 | ) 40 | gallery_page = context.new_page() 41 | res = requests.post(_Config.url + "/v1/auth/login", data=json.dumps(payload)) 42 | token = res.json()["token"] 43 | gallery_page.goto(_Config.url) 44 | gallery_page.evaluate( 45 | """data => { 46 | window.localStorage.setItem('gridUserId', data[0]); 47 | window.localStorage.setItem('gridUserKey', data[1]); 48 | window.localStorage.setItem('gridUserToken', data[2]); 49 | } 50 | """, 51 | [_Config.id, _Config.key, token], 52 | ) 53 | 54 | for retry_count in range(5): 55 | try: 56 | gallery_page.goto(f"{_Config.url}/apps") 57 | except playwright._impl._api_types.TimeoutError as ex: 58 | try_ex = ex 59 | else: 60 | try_ex = None 61 | break 62 | if try_ex: 63 | raise try_ex 64 | 65 | # Find the app in the gallery 66 | gallery_page.locator(f"text='{app_name}'").first.click() 67 | yield gallery_page 68 | 69 | 70 | @requires("playwright") 71 | @contextmanager 72 | def launch_from_gallery_app_page(gallery_page) -> Generator: 73 | with gallery_page.context.expect_page() as page_catcher: 74 | sleep(1) 75 | gallery_page.locator("text='Try it free'").click() 76 | 77 | app_page = page_catcher.value 78 | app_page.wait_for_load_state(timeout=0) 79 | 80 | try: 81 | yield app_page 82 | except KeyboardInterrupt: 83 | pass 84 | 85 | 86 | @requires("playwright") 87 | @contextmanager 88 | def clone_and_run_from_gallery_app_page(app_gallery_page) -> Generator: 89 | with app_gallery_page.expect_navigation(): 90 | app_gallery_page.locator("text=Clone & Run").click() 91 | 92 | admin_page = app_gallery_page 93 | 94 | sleep(5) 95 | # Scroll to the bottom of the page. Used to capture all logs. 96 | admin_page.evaluate( 97 | """ 98 | var intervalID = setInterval(function () { 99 | var scrollingElement = (document.scrollingElement || document.body); 100 | scrollingElement.scrollTop = scrollingElement.scrollHeight; 101 | }, 200); 102 | 103 | if (!window._logs) { 104 | window._logs = []; 105 | } 106 | 107 | if (window.logTerminals) { 108 | Object.entries(window.logTerminals).forEach( 109 | ([key, value]) => { 110 | window.logTerminals[key]._onLightningWritelnHandler = function (data) { 111 | window._logs = window._logs.concat([data]); 112 | } 113 | } 114 | ); 115 | } 116 | """ 117 | ) 118 | 119 | # TODO: Add a timeout here. 120 | while True: 121 | try: 122 | open_app_button = admin_page.locator("text=Open App") 123 | open_app_button.wait_for(timeout=1000) 124 | 125 | if open_app_button.is_disabled(): 126 | sleep(5) 127 | continue 128 | 129 | with admin_page.context.expect_page() as page_catcher: 130 | open_app_button.click() 131 | app_page = page_catcher.value 132 | app_page.wait_for_load_state(timeout=0) 133 | break 134 | except ( 135 | playwright._impl._api_types.Error, 136 | playwright._impl._api_types.TimeoutError, 137 | ): 138 | pass 139 | 140 | def fetch_logs() -> str: 141 | return admin_page.evaluate("window._logs;") 142 | 143 | lightning_app_id = str(app_page.url).split(".")[0].split("//")[-1] 144 | print(f"The Lightning Id Name : [bold magenta]{lightning_app_id}[/bold magenta]") 145 | 146 | try: 147 | yield admin_page, app_page, fetch_logs 148 | except KeyboardInterrupt: 149 | pass 150 | finally: 151 | print(f"##################### DELETING APP {lightning_app_id}") 152 | printed_logs = [] 153 | for log in fetch_logs(): 154 | if log not in printed_logs: 155 | printed_logs.append(log) 156 | print(log.split("[0m")[-1]) 157 | stop_button = admin_page.locator("text=Stop") 158 | try: 159 | stop_button.wait_for(timeout=3 * 1000) 160 | stop_button.click() 161 | except ( 162 | playwright._impl._api_types.Error, 163 | playwright._impl._api_types.TimeoutError, 164 | ): 165 | pass 166 | 167 | client = LightningClient() 168 | project = _get_project(client) 169 | try: 170 | res = client.lightningapp_instance_service_delete_lightningapp_instance( 171 | project_id=project.project_id, 172 | id=lightning_app_id, 173 | ) 174 | assert res == {} 175 | except ApiException as e: 176 | print(f"Failed to delete app {lightning_app_id}. Exception {e}") 177 | 178 | 179 | def validate_app_functionalities(app_page) -> None: 180 | """ 181 | app_page: The UI page of the app to be validated. 182 | """ 183 | while True: 184 | try: 185 | app_page.reload() 186 | sleep(5) 187 | app_label = app_page.frame_locator("iframe").locator("text=CLIP: Connecting") 188 | app_label.wait_for(timeout=30 * 1000) 189 | break 190 | except ( 191 | playwright._impl._api_types.Error, 192 | playwright._impl._api_types.TimeoutError, 193 | ): 194 | pass 195 | 196 | app_tabs = ["Blog", "Paper", "Poster", "Notebook", "Training Logs", "Model Demo"] 197 | for tab in app_tabs: 198 | tab_ui = app_page.locator(f"button:has-text('{tab}')") 199 | tab_ui.wait_for(timeout=1000) 200 | 201 | 202 | @pytest.mark.skipif(not os.getenv("TEST_APP_NAME", None), reason="requires TEST_APP_NAME env var") 203 | def test_launch_app_from_gallery(): 204 | app_name = os.getenv("TEST_APP_NAME", None) 205 | if app_name is None: 206 | raise ValueError("TEST_APP_NAME environment variable is not set") 207 | 208 | with get_gallery_app_page(app_name) as gallery_page: 209 | with launch_from_gallery_app_page(gallery_page) as app_page: 210 | validate_app_functionalities(app_page) 211 | 212 | 213 | @pytest.mark.skipif(not os.getenv("TEST_APP_NAME", None), reason="requires TEST_APP_NAME env var") 214 | def test_clone_and_run_app_from_gallery(): 215 | app_name = os.getenv("TEST_APP_NAME", None) 216 | if app_name is None: 217 | raise ValueError("TEST_APP_NAME environment variable is not set") 218 | 219 | with get_gallery_app_page(app_name) as gallery_page: 220 | with clone_and_run_from_gallery_app_page(gallery_page) as (_, app_page, _): 221 | validate_app_functionalities(app_page) 222 | -------------------------------------------------------------------------------- /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 2021-2023 Lightning-AI team 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 | -------------------------------------------------------------------------------- /tests/resources/Interacting_with_CLIP.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Interacting with CLIP\n", 8 | "\n", 9 | "This is a self-contained notebook that shows how to download and run CLIP models, calculate the similarity between arbitrary image and text inputs, and perform zero-shot image classifications." 10 | ] 11 | }, 12 | { 13 | "cell_type": "markdown", 14 | "metadata": {}, 15 | "source": [ 16 | "# Preparation for Colab\n", 17 | "\n", 18 | "Make sure you're running a GPU runtime; if not, select \"GPU\" as the hardware accelerator in Runtime > Change Runtime Type in the menu. The next cells will install the `clip` package and its dependencies, and check if PyTorch 1.7.1 or later is installed." 19 | ] 20 | }, 21 | { 22 | "cell_type": "code", 23 | "execution_count": null, 24 | "metadata": {}, 25 | "outputs": [], 26 | "source": [ 27 | "! pip install ftfy regex tqdm\n", 28 | "! pip install git+https://github.com/openai/CLIP.git" 29 | ] 30 | }, 31 | { 32 | "cell_type": "code", 33 | "execution_count": null, 34 | "metadata": {}, 35 | "outputs": [], 36 | "source": [ 37 | "import numpy as np\n", 38 | "import torch\n", 39 | "from pkg_resources import packaging\n", 40 | "\n", 41 | "print(\"Torch version:\", torch.__version__)" 42 | ] 43 | }, 44 | { 45 | "cell_type": "markdown", 46 | "metadata": {}, 47 | "source": [ 48 | "# Loading the model\n", 49 | "\n", 50 | "`clip.available_models()` will list the names of available CLIP models." 51 | ] 52 | }, 53 | { 54 | "cell_type": "code", 55 | "execution_count": null, 56 | "metadata": {}, 57 | "outputs": [], 58 | "source": [ 59 | "import clip\n", 60 | "\n", 61 | "clip.available_models()" 62 | ] 63 | }, 64 | { 65 | "cell_type": "code", 66 | "execution_count": null, 67 | "metadata": {}, 68 | "outputs": [], 69 | "source": [ 70 | "model, preprocess = clip.load(\"ViT-B/32\")\n", 71 | "model.cuda().eval()\n", 72 | "input_resolution = model.visual.input_resolution\n", 73 | "context_length = model.context_length\n", 74 | "vocab_size = model.vocab_size\n", 75 | "\n", 76 | "print(\"Model parameters:\", f\"{np.sum([int(np.prod(p.shape)) for p in model.parameters()]):,}\")\n", 77 | "print(\"Input resolution:\", input_resolution)\n", 78 | "print(\"Context length:\", context_length)\n", 79 | "print(\"Vocab size:\", vocab_size)" 80 | ] 81 | }, 82 | { 83 | "cell_type": "markdown", 84 | "metadata": {}, 85 | "source": [ 86 | "# Image Preprocessing\n", 87 | "\n", 88 | "We resize the input images and center-crop them to conform with the image resolution that the model expects. Before doing so, we will normalize the pixel intensity using the dataset mean and standard deviation.\n", 89 | "\n", 90 | "The second return value from `clip.load()` contains a torchvision `Transform` that performs this preprocessing.\n", 91 | "\n" 92 | ] 93 | }, 94 | { 95 | "cell_type": "code", 96 | "execution_count": null, 97 | "metadata": {}, 98 | "outputs": [], 99 | "source": [ 100 | "preprocess" 101 | ] 102 | }, 103 | { 104 | "cell_type": "markdown", 105 | "metadata": {}, 106 | "source": [ 107 | "# Text Preprocessing\n", 108 | "\n", 109 | "We use a case-insensitive tokenizer, which can be invoked using `clip.tokenize()`. By default, the outputs are padded to become 77 tokens long, which is what the CLIP models expects." 110 | ] 111 | }, 112 | { 113 | "cell_type": "code", 114 | "execution_count": null, 115 | "metadata": {}, 116 | "outputs": [], 117 | "source": [ 118 | "clip.tokenize(\"Hello World!\")" 119 | ] 120 | }, 121 | { 122 | "cell_type": "markdown", 123 | "metadata": {}, 124 | "source": [ 125 | "# Setting up input images and texts\n", 126 | "\n", 127 | "We are going to feed 8 example images and their textual descriptions to the model, and compare the similarity between the corresponding features.\n", 128 | "\n", 129 | "The tokenizer is case-insensitive, and we can freely give any suitable textual descriptions." 130 | ] 131 | }, 132 | { 133 | "cell_type": "code", 134 | "execution_count": null, 135 | "metadata": {}, 136 | "outputs": [], 137 | "source": [ 138 | "import os\n", 139 | "import skimage\n", 140 | "import IPython.display\n", 141 | "import matplotlib.pyplot as plt\n", 142 | "from PIL import Image\n", 143 | "import numpy as np\n", 144 | "\n", 145 | "from collections import OrderedDict\n", 146 | "import torch\n", 147 | "\n", 148 | "%matplotlib inline\n", 149 | "%config InlineBackend.figure_format = 'retina'\n", 150 | "\n", 151 | "# images in skimage to use and their textual descriptions\n", 152 | "descriptions = {\n", 153 | " \"page\": \"a page of text about segmentation\",\n", 154 | " \"chelsea\": \"a facial photo of a tabby cat\",\n", 155 | " \"astronaut\": \"a portrait of an astronaut with the American flag\",\n", 156 | " \"rocket\": \"a rocket standing on a launchpad\",\n", 157 | " \"motorcycle_right\": \"a red motorcycle standing in a garage\",\n", 158 | " \"camera\": \"a person looking at a camera on a tripod\",\n", 159 | " \"horse\": \"a black-and-white silhouette of a horse\",\n", 160 | " \"coffee\": \"a cup of coffee on a saucer\",\n", 161 | "}" 162 | ] 163 | }, 164 | { 165 | "cell_type": "code", 166 | "execution_count": null, 167 | "metadata": {}, 168 | "outputs": [], 169 | "source": [ 170 | "original_images = []\n", 171 | "images = []\n", 172 | "texts = []\n", 173 | "plt.figure(figsize=(16, 5))\n", 174 | "\n", 175 | "for filename in [\n", 176 | " filename for filename in os.listdir(skimage.data_dir) if filename.endswith(\".png\") or filename.endswith(\".jpg\")\n", 177 | "]:\n", 178 | " name = os.path.splitext(filename)[0]\n", 179 | " if name not in descriptions:\n", 180 | " continue\n", 181 | "\n", 182 | " image = Image.open(os.path.join(skimage.data_dir, filename)).convert(\"RGB\")\n", 183 | "\n", 184 | " plt.subplot(2, 4, len(images) + 1)\n", 185 | " plt.imshow(image)\n", 186 | " plt.title(f\"{filename}\\n{descriptions[name]}\")\n", 187 | " plt.xticks([])\n", 188 | " plt.yticks([])\n", 189 | "\n", 190 | " original_images.append(image)\n", 191 | " images.append(preprocess(image))\n", 192 | " texts.append(descriptions[name])\n", 193 | "\n", 194 | "plt.tight_layout()" 195 | ] 196 | }, 197 | { 198 | "cell_type": "markdown", 199 | "metadata": {}, 200 | "source": [ 201 | "## Building features\n", 202 | "\n", 203 | "We normalize the images, tokenize each text input, and run the forward pass of the model to get the image and text features." 204 | ] 205 | }, 206 | { 207 | "cell_type": "code", 208 | "execution_count": null, 209 | "metadata": {}, 210 | "outputs": [], 211 | "source": [ 212 | "image_input = torch.tensor(np.stack(images)).cuda()\n", 213 | "text_tokens = clip.tokenize([\"This is \" + desc for desc in texts]).cuda()" 214 | ] 215 | }, 216 | { 217 | "cell_type": "code", 218 | "execution_count": null, 219 | "metadata": {}, 220 | "outputs": [], 221 | "source": [ 222 | "with torch.no_grad():\n", 223 | " image_features = model.encode_image(image_input).float()\n", 224 | " text_features = model.encode_text(text_tokens).float()" 225 | ] 226 | }, 227 | { 228 | "cell_type": "markdown", 229 | "metadata": {}, 230 | "source": [ 231 | "## Calculating cosine similarity\n", 232 | "\n", 233 | "We normalize the features and calculate the dot product of each pair." 234 | ] 235 | }, 236 | { 237 | "cell_type": "code", 238 | "execution_count": null, 239 | "metadata": {}, 240 | "outputs": [], 241 | "source": [ 242 | "image_features /= image_features.norm(dim=-1, keepdim=True)\n", 243 | "text_features /= text_features.norm(dim=-1, keepdim=True)\n", 244 | "similarity = text_features.cpu().numpy() @ image_features.cpu().numpy().T" 245 | ] 246 | }, 247 | { 248 | "cell_type": "code", 249 | "execution_count": null, 250 | "metadata": {}, 251 | "outputs": [], 252 | "source": [ 253 | "count = len(descriptions)\n", 254 | "\n", 255 | "plt.figure(figsize=(20, 14))\n", 256 | "plt.imshow(similarity, vmin=0.1, vmax=0.3)\n", 257 | "# plt.colorbar()\n", 258 | "plt.yticks(range(count), texts, fontsize=18)\n", 259 | "plt.xticks([])\n", 260 | "for i, image in enumerate(original_images):\n", 261 | " plt.imshow(image, extent=(i - 0.5, i + 0.5, -1.6, -0.6), origin=\"lower\")\n", 262 | "for x in range(similarity.shape[1]):\n", 263 | " for y in range(similarity.shape[0]):\n", 264 | " plt.text(x, y, f\"{similarity[y, x]:.2f}\", ha=\"center\", va=\"center\", size=12)\n", 265 | "\n", 266 | "for side in [\"left\", \"top\", \"right\", \"bottom\"]:\n", 267 | " plt.gca().spines[side].set_visible(False)\n", 268 | "\n", 269 | "plt.xlim([-0.5, count - 0.5])\n", 270 | "plt.ylim([count + 0.5, -2])\n", 271 | "\n", 272 | "plt.title(\"Cosine similarity between text and image features\", size=20)" 273 | ] 274 | }, 275 | { 276 | "cell_type": "markdown", 277 | "metadata": {}, 278 | "source": [ 279 | "# Zero-Shot Image Classification\n", 280 | "\n", 281 | "You can classify images using the cosine similarity (times 100) as the logits to the softmax operation." 282 | ] 283 | }, 284 | { 285 | "cell_type": "code", 286 | "execution_count": null, 287 | "metadata": {}, 288 | "outputs": [], 289 | "source": [ 290 | "from torchvision.datasets import CIFAR100\n", 291 | "\n", 292 | "cifar100 = CIFAR100(os.path.expanduser(\"~/.cache\"), transform=preprocess, download=True)" 293 | ] 294 | }, 295 | { 296 | "cell_type": "code", 297 | "execution_count": null, 298 | "metadata": {}, 299 | "outputs": [], 300 | "source": [ 301 | "text_descriptions = [f\"This is a photo of a {label}\" for label in cifar100.classes]\n", 302 | "text_tokens = clip.tokenize(text_descriptions).cuda()" 303 | ] 304 | }, 305 | { 306 | "cell_type": "code", 307 | "execution_count": null, 308 | "metadata": {}, 309 | "outputs": [], 310 | "source": [ 311 | "with torch.no_grad():\n", 312 | " text_features = model.encode_text(text_tokens).float()\n", 313 | " text_features /= text_features.norm(dim=-1, keepdim=True)\n", 314 | "\n", 315 | "text_probs = (100.0 * image_features @ text_features.T).softmax(dim=-1)\n", 316 | "top_probs, top_labels = text_probs.cpu().topk(5, dim=-1)" 317 | ] 318 | }, 319 | { 320 | "cell_type": "code", 321 | "execution_count": null, 322 | "metadata": {}, 323 | "outputs": [], 324 | "source": [ 325 | "plt.figure(figsize=(16, 16))\n", 326 | "\n", 327 | "for i, image in enumerate(original_images):\n", 328 | " plt.subplot(4, 4, 2 * i + 1)\n", 329 | " plt.imshow(image)\n", 330 | " plt.axis(\"off\")\n", 331 | "\n", 332 | " plt.subplot(4, 4, 2 * i + 2)\n", 333 | " y = np.arange(top_probs.shape[-1])\n", 334 | " plt.grid()\n", 335 | " plt.barh(y, top_probs[i])\n", 336 | " plt.gca().invert_yaxis()\n", 337 | " plt.gca().set_axisbelow(True)\n", 338 | " plt.yticks(y, [cifar100.classes[index] for index in top_labels[i].numpy()])\n", 339 | " plt.xlabel(\"probability\")\n", 340 | "\n", 341 | "plt.subplots_adjust(wspace=0.5)\n", 342 | "plt.show()" 343 | ] 344 | } 345 | ], 346 | "metadata": { 347 | "accelerator": "GPU", 348 | "colab": { 349 | "collapsed_sections": [], 350 | "name": "Interacting with CLIP.ipynb", 351 | "provenance": [] 352 | }, 353 | "kernelspec": { 354 | "display_name": "Python 3", 355 | "name": "python3" 356 | }, 357 | "widgets": { 358 | "application/vnd.jupyter.widget-state+json": { 359 | "12e23e2819094ee0a079d4eb77cfc4f9": { 360 | "model_module": "@jupyter-widgets/base", 361 | "model_name": "LayoutModel", 362 | "state": { 363 | "_model_module": "@jupyter-widgets/base", 364 | "_model_module_version": "1.2.0", 365 | "_model_name": "LayoutModel", 366 | "_view_count": null, 367 | "_view_module": "@jupyter-widgets/base", 368 | "_view_module_version": "1.2.0", 369 | "_view_name": "LayoutView", 370 | "align_content": null, 371 | "align_items": null, 372 | "align_self": null, 373 | "border": null, 374 | "bottom": null, 375 | "display": null, 376 | "flex": null, 377 | "flex_flow": null, 378 | "grid_area": null, 379 | "grid_auto_columns": null, 380 | "grid_auto_flow": null, 381 | "grid_auto_rows": null, 382 | "grid_column": null, 383 | "grid_gap": null, 384 | "grid_row": null, 385 | "grid_template_areas": null, 386 | "grid_template_columns": null, 387 | "grid_template_rows": null, 388 | "height": null, 389 | "justify_content": null, 390 | "justify_items": null, 391 | "left": null, 392 | "margin": null, 393 | "max_height": null, 394 | "max_width": null, 395 | "min_height": null, 396 | "min_width": null, 397 | "object_fit": null, 398 | "object_position": null, 399 | "order": null, 400 | "overflow": null, 401 | "overflow_x": null, 402 | "overflow_y": null, 403 | "padding": null, 404 | "right": null, 405 | "top": null, 406 | "visibility": null, 407 | "width": null 408 | } 409 | }, 410 | "1369964d45004b5e95a058910b2a33e6": { 411 | "model_module": "@jupyter-widgets/controls", 412 | "model_name": "HBoxModel", 413 | "state": { 414 | "_dom_classes": [], 415 | "_model_module": "@jupyter-widgets/controls", 416 | "_model_module_version": "1.5.0", 417 | "_model_name": "HBoxModel", 418 | "_view_count": null, 419 | "_view_module": "@jupyter-widgets/controls", 420 | "_view_module_version": "1.5.0", 421 | "_view_name": "HBoxView", 422 | "box_style": "", 423 | "children": [ 424 | "IPY_MODEL_7a5f52e56ede4ac3abe37a3ece007dc9", 425 | "IPY_MODEL_ce8b0faa1a1340b5a504d7b3546b3ccb" 426 | ], 427 | "layout": "IPY_MODEL_12e23e2819094ee0a079d4eb77cfc4f9" 428 | } 429 | }, 430 | "161969cae25a49f38aacd1568d3cac6c": { 431 | "model_module": "@jupyter-widgets/base", 432 | "model_name": "LayoutModel", 433 | "state": { 434 | "_model_module": "@jupyter-widgets/base", 435 | "_model_module_version": "1.2.0", 436 | "_model_name": "LayoutModel", 437 | "_view_count": null, 438 | "_view_module": "@jupyter-widgets/base", 439 | "_view_module_version": "1.2.0", 440 | "_view_name": "LayoutView", 441 | "align_content": null, 442 | "align_items": null, 443 | "align_self": null, 444 | "border": null, 445 | "bottom": null, 446 | "display": null, 447 | "flex": null, 448 | "flex_flow": null, 449 | "grid_area": null, 450 | "grid_auto_columns": null, 451 | "grid_auto_flow": null, 452 | "grid_auto_rows": null, 453 | "grid_column": null, 454 | "grid_gap": null, 455 | "grid_row": null, 456 | "grid_template_areas": null, 457 | "grid_template_columns": null, 458 | "grid_template_rows": null, 459 | "height": null, 460 | "justify_content": null, 461 | "justify_items": null, 462 | "left": null, 463 | "margin": null, 464 | "max_height": null, 465 | "max_width": null, 466 | "min_height": null, 467 | "min_width": null, 468 | "object_fit": null, 469 | "object_position": null, 470 | "order": null, 471 | "overflow": null, 472 | "overflow_x": null, 473 | "overflow_y": null, 474 | "padding": null, 475 | "right": null, 476 | "top": null, 477 | "visibility": null, 478 | "width": null 479 | } 480 | }, 481 | "4a61c10fc00c4f04bb00b82e942da210": { 482 | "model_module": "@jupyter-widgets/base", 483 | "model_name": "LayoutModel", 484 | "state": { 485 | "_model_module": "@jupyter-widgets/base", 486 | "_model_module_version": "1.2.0", 487 | "_model_name": "LayoutModel", 488 | "_view_count": null, 489 | "_view_module": "@jupyter-widgets/base", 490 | "_view_module_version": "1.2.0", 491 | "_view_name": "LayoutView", 492 | "align_content": null, 493 | "align_items": null, 494 | "align_self": null, 495 | "border": null, 496 | "bottom": null, 497 | "display": null, 498 | "flex": null, 499 | "flex_flow": null, 500 | "grid_area": null, 501 | "grid_auto_columns": null, 502 | "grid_auto_flow": null, 503 | "grid_auto_rows": null, 504 | "grid_column": null, 505 | "grid_gap": null, 506 | "grid_row": null, 507 | "grid_template_areas": null, 508 | "grid_template_columns": null, 509 | "grid_template_rows": null, 510 | "height": null, 511 | "justify_content": null, 512 | "justify_items": null, 513 | "left": null, 514 | "margin": null, 515 | "max_height": null, 516 | "max_width": null, 517 | "min_height": null, 518 | "min_width": null, 519 | "object_fit": null, 520 | "object_position": null, 521 | "order": null, 522 | "overflow": null, 523 | "overflow_x": null, 524 | "overflow_y": null, 525 | "padding": null, 526 | "right": null, 527 | "top": null, 528 | "visibility": null, 529 | "width": null 530 | } 531 | }, 532 | "5e6adc4592124a4581b85f4c1f3bab4d": { 533 | "model_module": "@jupyter-widgets/controls", 534 | "model_name": "ProgressStyleModel", 535 | "state": { 536 | "_model_module": "@jupyter-widgets/controls", 537 | "_model_module_version": "1.5.0", 538 | "_model_name": "ProgressStyleModel", 539 | "_view_count": null, 540 | "_view_module": "@jupyter-widgets/base", 541 | "_view_module_version": "1.2.0", 542 | "_view_name": "StyleView", 543 | "bar_color": null, 544 | "description_width": "initial" 545 | } 546 | }, 547 | "7a5f52e56ede4ac3abe37a3ece007dc9": { 548 | "model_module": "@jupyter-widgets/controls", 549 | "model_name": "FloatProgressModel", 550 | "state": { 551 | "_dom_classes": [], 552 | "_model_module": "@jupyter-widgets/controls", 553 | "_model_module_version": "1.5.0", 554 | "_model_name": "FloatProgressModel", 555 | "_view_count": null, 556 | "_view_module": "@jupyter-widgets/controls", 557 | "_view_module_version": "1.5.0", 558 | "_view_name": "ProgressView", 559 | "bar_style": "success", 560 | "description": "", 561 | "description_tooltip": null, 562 | "layout": "IPY_MODEL_4a61c10fc00c4f04bb00b82e942da210", 563 | "max": 169001437, 564 | "min": 0, 565 | "orientation": "horizontal", 566 | "style": "IPY_MODEL_5e6adc4592124a4581b85f4c1f3bab4d", 567 | "value": 169001437 568 | } 569 | }, 570 | "b597cd6f6cd443aba4bf4491ac7f957e": { 571 | "model_module": "@jupyter-widgets/controls", 572 | "model_name": "DescriptionStyleModel", 573 | "state": { 574 | "_model_module": "@jupyter-widgets/controls", 575 | "_model_module_version": "1.5.0", 576 | "_model_name": "DescriptionStyleModel", 577 | "_view_count": null, 578 | "_view_module": "@jupyter-widgets/base", 579 | "_view_module_version": "1.2.0", 580 | "_view_name": "StyleView", 581 | "description_width": "" 582 | } 583 | }, 584 | "ce8b0faa1a1340b5a504d7b3546b3ccb": { 585 | "model_module": "@jupyter-widgets/controls", 586 | "model_name": "HTMLModel", 587 | "state": { 588 | "_dom_classes": [], 589 | "_model_module": "@jupyter-widgets/controls", 590 | "_model_module_version": "1.5.0", 591 | "_model_name": "HTMLModel", 592 | "_view_count": null, 593 | "_view_module": "@jupyter-widgets/controls", 594 | "_view_module_version": "1.5.0", 595 | "_view_name": "HTMLView", 596 | "description": "", 597 | "description_tooltip": null, 598 | "layout": "IPY_MODEL_161969cae25a49f38aacd1568d3cac6c", 599 | "placeholder": "​", 600 | "style": "IPY_MODEL_b597cd6f6cd443aba4bf4491ac7f957e", 601 | "value": " 169001984/? [00:06<00:00, 25734958.25it/s]" 602 | } 603 | } 604 | } 605 | } 606 | }, 607 | "nbformat": 4, 608 | "nbformat_minor": 0 609 | } 610 | --------------------------------------------------------------------------------