├── tests ├── __init__.py ├── commands │ ├── __init__.py │ └── server_simple_test.py └── fixtures │ ├── bidaf │ ├── vocabulary │ │ ├── non_padded_namespaces.txt │ │ └── tokens.txt │ ├── best.th │ └── model.tar.gz │ └── data │ └── squad.json ├── allennlp_server ├── __init__.py ├── commands │ ├── __init__.py │ └── server_simple.py └── version.py ├── MANIFEST.in ├── .github ├── dependabot.yml └── workflows │ └── main.yml ├── dev-requirements.txt ├── pyproject.toml ├── .flake8 ├── Dockerfile ├── scripts └── get_version.py ├── README.md ├── .gitignore ├── setup.py └── LICENSE /tests/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /tests/commands/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /allennlp_server/__init__.py: -------------------------------------------------------------------------------- 1 | import allennlp_server.commands 2 | -------------------------------------------------------------------------------- /tests/fixtures/bidaf/vocabulary/non_padded_namespaces.txt: -------------------------------------------------------------------------------- 1 | *labels 2 | *tags 3 | -------------------------------------------------------------------------------- /allennlp_server/commands/__init__.py: -------------------------------------------------------------------------------- 1 | from allennlp_server.commands.server_simple import SimpleServer 2 | -------------------------------------------------------------------------------- /tests/fixtures/bidaf/best.th: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/allenai/allennlp-server/HEAD/tests/fixtures/bidaf/best.th -------------------------------------------------------------------------------- /tests/fixtures/bidaf/model.tar.gz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/allenai/allennlp-server/HEAD/tests/fixtures/bidaf/model.tar.gz -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include LICENSE 2 | include README.md 3 | recursive-include allennlp_server * 4 | recursive-exclude * __pycache__ 5 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: pip 4 | directory: "/" 5 | schedule: 6 | interval: daily 7 | time: "13:00" 8 | open-pull-requests-limit: 10 -------------------------------------------------------------------------------- /dev-requirements.txt: -------------------------------------------------------------------------------- 1 | #### TESTING-RELATED PACKAGES #### 2 | 3 | # Automatic code formatting 4 | black 5 | 6 | # Checks style, syntax, and other useful errors. 7 | flake8 8 | 9 | # Static type checking 10 | mypy==0.950 11 | 12 | pytest 13 | 14 | # Allows generation of coverage reports with pytest. 15 | pytest-cov 16 | 17 | 18 | # Used for generating doc comments 19 | numpydoc>=0.8.0 20 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [tool.black] 2 | line-length = 100 3 | 4 | include = '\.pyi?$' 5 | 6 | exclude = ''' 7 | ( 8 | __pycache__ 9 | | \btutorials\b 10 | | \bbuild\b 11 | | \.git 12 | | \.mypy_cache 13 | | \.pytest_cache 14 | | \.vscode 15 | | \.venv 16 | | \bdist\b 17 | | \bdoc\b 18 | ) 19 | ''' 20 | 21 | [build-system] 22 | requires = ["setuptools", "wheel"] 23 | build-backend = "setuptools.build_meta" 24 | -------------------------------------------------------------------------------- /allennlp_server/version.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | _MAJOR = "1" 4 | _MINOR = "0" 5 | # On main and in a nightly release the patch should be one ahead of the last 6 | # released build. 7 | _PATCH = "0" 8 | # This is mainly for nightly builds which have the suffix ".dev$DATE". See 9 | # https://semver.org/#is-v123-a-semantic-version for the semantics. 10 | _SUFFIX = os.environ.get("ALLENNLP_SERVER_VERSION_SUFFIX", "") 11 | 12 | VERSION_SHORT = "{0}.{1}".format(_MAJOR, _MINOR) 13 | VERSION = "{0}.{1}.{2}{3}".format(_MAJOR, _MINOR, _PATCH, _SUFFIX) 14 | -------------------------------------------------------------------------------- /.flake8: -------------------------------------------------------------------------------- 1 | [flake8] 2 | max-line-length = 115 3 | 4 | ignore = 5 | # these rules don't play well with black 6 | E203 # whitespace before : 7 | W503 # line break before binary operator 8 | 9 | exclude = 10 | build/** 11 | doc/** 12 | 13 | per-file-ignores = 14 | # __init__.py files are allowed to have unused imports and lines-too-long 15 | allennlp_plugins/**/__init__.py:F401 16 | allennlp_server/__init__.py:F401 17 | allennlp_server/**/__init__.py:F401 18 | 19 | # tests don't have to respect 20 | # E731: do not assign a lambda expression, use a def 21 | # F401: unused imports 22 | allennlp_server/tests/**:E731,F401 23 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:3.8 2 | 3 | WORKDIR /stage/allennlp-server 4 | 5 | # Copy select files needed for installing requirements. 6 | # We only copy what we need here so small changes to the repository does not trigger re-installation of the requirements. 7 | COPY allennlp_server/version.py allennlp_server/version.py 8 | COPY setup.py . 9 | COPY README.md . 10 | RUN pip install -e . 11 | # TODO(epwalsh): In PyTorch 1.7, dataclasses is an unconditional dependency, when it should 12 | # only be a conditional dependency for Python < 3.7. 13 | # This has been fixed on PyTorch master branch, so we should be able to 14 | # remove this check with the next PyTorch release. 15 | # RUN pip uninstall -y dataclasses 16 | 17 | # Now copy source files and re-install the package without dependencies. 18 | COPY allennlp_server/ allennlp_server/ 19 | RUN pip install --no-deps -e . 20 | 21 | EXPOSE 8000 22 | 23 | ENTRYPOINT ["allennlp", "serve"] 24 | -------------------------------------------------------------------------------- /tests/fixtures/bidaf/vocabulary/tokens.txt: -------------------------------------------------------------------------------- 1 | @@UNKNOWN@@ 2 | the 3 | of 4 | . 5 | , 6 | a 7 | in 8 | to 9 | is 10 | and 11 | at 12 | building 13 | main 14 | nuclear 15 | zahm 16 | mary 17 | with 18 | statue 19 | that 20 | early 21 | used 22 | 's 23 | virgin 24 | ( 25 | through 26 | ) 27 | ? 28 | on 29 | gold 30 | dome 31 | immediately 32 | it 33 | " 34 | basilica 35 | grotto 36 | notre 37 | dame 38 | albert 39 | john 40 | brother 41 | models 42 | neoprene 43 | lourdes 44 | france 45 | 1858 46 | did 47 | what 48 | 1882 49 | built 50 | an 51 | wind 52 | tunnel 53 | compare 54 | lift 55 | drag 56 | aeronautical 57 | around 58 | 1899 59 | professor 60 | jerome 61 | green 62 | became 63 | first 64 | american 65 | send 66 | wireless 67 | message 68 | 1931 69 | father 70 | julius 71 | nieuwland 72 | performed 73 | work 74 | basic 75 | reactions 76 | was 77 | create 78 | study 79 | physics 80 | university 81 | began 82 | accelerator 83 | 1936 84 | continues 85 | now 86 | partly 87 | partnership 88 | joint 89 | institute 90 | for 91 | astrophysics 92 | architecturally 93 | school 94 | has 95 | catholic 96 | character 97 | atop 98 | golden 99 | front 100 | facing 101 | copper 102 | christ 103 | arms 104 | upraised 105 | legend 106 | venite 107 | ad 108 | me 109 | omnes 110 | next 111 | sacred 112 | heart 113 | behind 114 | marian 115 | place 116 | prayer 117 | reflection 118 | replica 119 | where 120 | reputedly 121 | appeared 122 | saint 123 | bernadette 124 | soubirous 125 | end 126 | drive 127 | direct 128 | line 129 | connects 130 | 3 131 | statues 132 | simple 133 | modern 134 | stone 135 | whom 136 | allegedly 137 | appear 138 | sits 139 | top 140 | year 141 | begin 142 | comparing 143 | aeronatical 144 | which 145 | individual 146 | worked 147 | projects 148 | eventually 149 | created 150 | construct 151 | -------------------------------------------------------------------------------- /scripts/get_version.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | import argparse 4 | from typing import Dict 5 | 6 | 7 | def parse_args(): 8 | parser = argparse.ArgumentParser() 9 | parser.add_argument("version_type", choices=["stable", "latest", "current"]) 10 | parser.add_argument("--minimal", action="store_true", default=False) 11 | parser.add_argument("--as-range", action="store_true", default=False) 12 | return parser.parse_args() 13 | 14 | 15 | def post_process(version: str, minimal: bool = False, as_range: bool = False): 16 | assert not (minimal and as_range) 17 | if version.startswith("v"): 18 | version = version[1:] 19 | if as_range: 20 | major, minor, *_ = version.split(".") 21 | return f">={version},<{major}.{int(minor)+1}" 22 | return version if minimal else f"v{version}" 23 | 24 | 25 | def get_current_version() -> str: 26 | VERSION: Dict[str, str] = {} 27 | with open("allennlp_server/version.py", "r") as version_file: 28 | exec(version_file.read(), VERSION) 29 | return VERSION["VERSION"] 30 | 31 | 32 | def get_latest_version() -> str: 33 | # Import this here so this requirements isn't mandatory when we just want to 34 | # call `get_current_version`. 35 | import requests 36 | 37 | resp = requests.get("https://api.github.com/repos/allenai/allennlp-server/tags") 38 | return resp.json()[0]["name"] 39 | 40 | 41 | def get_stable_version() -> str: 42 | import requests 43 | 44 | resp = requests.get("https://api.github.com/repos/allenai/allennlp-server/releases/latest") 45 | return resp.json()["tag_name"] 46 | 47 | 48 | def main() -> None: 49 | opts = parse_args() 50 | if opts.version_type == "stable": 51 | print(post_process(get_stable_version(), opts.minimal, opts.as_range)) 52 | elif opts.version_type == "latest": 53 | print(post_process(get_latest_version(), opts.minimal, opts.as_range)) 54 | elif opts.version_type == "current": 55 | print(post_process(get_current_version(), opts.minimal, opts.as_range)) 56 | else: 57 | raise NotImplementedError 58 | 59 | 60 | if __name__ == "__main__": 61 | main() 62 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |
2 |
3 | 4 | 5 | 6 |
7 |
8 |

9 | A demo server for AllenNLP models. 10 |

11 |
12 |
13 |

14 | 15 | Build 16 | 17 | 18 | PyPI 19 | 20 | 21 | License 22 | 23 |
24 |

25 |
26 | 27 |
28 | ❗️ To file an issue, please open a ticket on allenai/allennlp and tag it with "Server". ❗️ 29 |
30 | 31 | ## Installation 32 | 33 | ### From PyPI 34 | 35 | `allennlp-server` is available on PyPI. To install with `pip`, just run 36 | 37 | ```bash 38 | pip install allennlp-server 39 | ``` 40 | 41 | Note that the `allennlp-server` package is tied to the [`allennlp` core package](https://pypi.org/projects/allennlp) and [`allennlp-models` package](https://pypi.org/projects/allennlp-models). Therefore when you install the server package you will get the latest compatible version of `allennlp` and `allennlp-models` (if you haven't already installed `allennlp` or `allennlp-models`). For example, 42 | 43 | ```bash 44 | pip install allennlp-server 45 | pip freeze | grep allennlp 46 | # > allennlp==2.2.0 47 | # > allennlp-models==2.2.0 48 | # > allennlp-server==1.0.0 49 | ``` 50 | 51 | ### From source 52 | 53 | You can install AllenNLP Server by cloning our git repository: 54 | 55 | ```bash 56 | git clone https://github.com/allenai/allennlp-server 57 | ``` 58 | 59 | Create a Python 3.8 virtual environment, and install AllenNLP Server in `editable` mode by running: 60 | 61 | ```bash 62 | pip install --editable . 63 | ``` 64 | 65 | ## Running AllenNLP Server 66 | 67 | AllenNLP Server is a plugin for AllenNLP which adds a "serve" subcommand: 68 | 69 | ```bash 70 | allennlp serve --help 71 | ``` 72 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | 131 | # IntelliJ 132 | /*.iml 133 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import find_packages, setup 2 | 3 | # PEP0440 compatible formatted version, see: 4 | # https://www.python.org/dev/peps/pep-0440/ 5 | # 6 | # release markers: 7 | # X.Y 8 | # X.Y.Z # For bugfix releases 9 | # 10 | # pre-release markers: 11 | # X.YaN # Alpha release 12 | # X.YbN # Beta release 13 | # X.YrcN # Release Candidate 14 | # X.Y # Final release 15 | 16 | # version.py defines the VERSION and VERSION_SHORT variables. 17 | # We use exec here so we don't import allennlp whilst setting up. 18 | 19 | VERSION = {} # type: ignore 20 | with open("allennlp_server/version.py", "r") as version_file: 21 | exec(version_file.read(), VERSION) 22 | 23 | setup( 24 | name="allennlp-server", 25 | version=VERSION["VERSION"], 26 | description="Simple demo server for AllenNLP models and training config builder.", 27 | long_description=open("README.md").read(), 28 | long_description_content_type="text/markdown", 29 | classifiers=[ 30 | "Development Status :: 5 - Production/Stable", 31 | "Framework :: Flake8", 32 | "Framework :: Flask", 33 | "Intended Audience :: Developers", 34 | "Intended Audience :: Science/Research", 35 | "License :: OSI Approved :: Apache Software License", 36 | "Programming Language :: Python", 37 | "Programming Language :: Python :: 3", 38 | "Programming Language :: Python :: 3 :: Only", 39 | "Programming Language :: Python :: 3.6", 40 | "Programming Language :: Python :: 3.7", 41 | "Programming Language :: Python :: 3.8", 42 | "Topic :: Scientific/Engineering", 43 | "Topic :: Scientific/Engineering :: Artificial Intelligence", 44 | ], 45 | keywords="allennlp simple demo server serve models configuration file NLP deep learning machine reading", 46 | url="https://github.com/allenai/allennlp-server", 47 | author="Allen Institute for Artificial Intelligence", 48 | author_email="allennlp@allenai.org", 49 | license="Apache", 50 | packages=find_packages( 51 | exclude=[ 52 | "*.tests", 53 | "*.tests.*", 54 | "tests.*", 55 | "tests", 56 | "test_fixtures", 57 | "test_fixtures.*", 58 | "benchmarks", 59 | "benchmarks.*", 60 | ] 61 | ), 62 | install_requires=[ 63 | "allennlp>=2.0,<3.0", 64 | "allennlp_models>=2.0,<3.0", 65 | "flask>=1.0.2", 66 | "flask-cors>=3.0.7", 67 | "gevent>=1.3.6", 68 | ], 69 | include_package_data=True, 70 | python_requires=">=3.6.1", 71 | zip_safe=False, 72 | ) 73 | -------------------------------------------------------------------------------- /tests/commands/server_simple_test.py: -------------------------------------------------------------------------------- 1 | import importlib 2 | import io 3 | import json 4 | import os 5 | import sys 6 | from contextlib import redirect_stdout 7 | 8 | import flask.testing 9 | from allennlp.commands import main 10 | from allennlp.common.testing import AllenNlpTestCase 11 | from allennlp.common.util import JsonDict 12 | from allennlp.models.archival import load_archive 13 | from allennlp.predictors import Predictor 14 | 15 | from allennlp_server.commands.server_simple import make_app 16 | 17 | 18 | def post_json(client: flask.testing.FlaskClient, endpoint: str, data: JsonDict) -> flask.Response: 19 | return client.post(endpoint, content_type="application/json", data=json.dumps(data)) 20 | 21 | 22 | PAYLOAD = { 23 | "passage": """ 24 | The Matrix is a 1999 science fiction action film written and directed by The Wachowskis, 25 | starring Keanu Reeves, Laurence Fishburne, Carrie-Anne Moss, Hugo Weaving, and Joe Pantoliano.""", 26 | "question": """Who stars in the matrix?""", 27 | } 28 | 29 | 30 | class TestSimpleServer(AllenNlpTestCase): 31 | def setup_method(self): 32 | super().setup_method() 33 | importlib.import_module("allennlp_models.rc") 34 | archive = load_archive("tests/fixtures/bidaf/model.tar.gz") 35 | self.bidaf_predictor = Predictor.from_archive( 36 | archive, "allennlp_models.rc.ReadingComprehensionPredictor" 37 | ) 38 | 39 | def teardown_method(self): 40 | super().teardown_method() 41 | try: 42 | os.remove("access.log") 43 | os.remove("error.log") 44 | except FileNotFoundError: 45 | pass 46 | 47 | def test_standard_model(self): 48 | app = make_app(predictor=self.bidaf_predictor, field_names=["passage", "question"]) 49 | app.testing = True 50 | client = app.test_client() 51 | 52 | # First test the HTML 53 | response = client.get("/") 54 | data = response.get_data() 55 | 56 | assert b"passage" in data 57 | assert b"question" in data 58 | 59 | # Now test the backend 60 | response = post_json(client, "/predict", PAYLOAD) 61 | data = json.loads(response.get_data()) 62 | assert "best_span_str" in data 63 | assert "span_start_logits" in data 64 | 65 | # Test the batch predictor 66 | batch_size = 8 67 | response = post_json(client, "/predict_batch", [PAYLOAD] * batch_size) 68 | data_list = json.loads(response.get_data()) 69 | assert len(data_list) == batch_size 70 | for data in data_list: 71 | assert "best_span_str" in data 72 | assert "span_start_logits" in data 73 | 74 | def test_subcommand_plugin_is_available(self): 75 | # Test originally copied from 76 | # `allennlp.tests.commands.main_test.TestMain.test_subcommand_plugin_is_available`. 77 | 78 | sys.argv = ["allennlp"] 79 | 80 | with io.StringIO() as buf, redirect_stdout(buf): 81 | main() 82 | output = buf.getvalue() 83 | 84 | assert " serve" in output 85 | 86 | def test_sanitizer(self): 87 | def sanitize(result: JsonDict) -> JsonDict: 88 | return {key: value for key, value in result.items() if key.startswith("best_span")} 89 | 90 | app = make_app( 91 | predictor=self.bidaf_predictor, 92 | field_names=["passage", "question"], 93 | sanitizer=sanitize, 94 | ) 95 | app.testing = True 96 | client = app.test_client() 97 | 98 | response = post_json(client, "/predict", PAYLOAD) 99 | data = json.loads(response.get_data()) 100 | assert "best_span_str" in data 101 | assert "span_start_logits" not in data 102 | 103 | batch_size = 8 104 | response = post_json(client, "/predict_batch", [PAYLOAD] * batch_size) 105 | data_list = json.loads(response.get_data()) 106 | assert len(data_list) == batch_size 107 | for data in data_list: 108 | assert "best_span_str" in data 109 | assert "span_start_logits" not in data 110 | 111 | def test_static_dir(self): 112 | html = """THIS IS A STATIC SITE""" 113 | jpg = """something about a jpg""" 114 | 115 | with open(os.path.join(self.TEST_DIR, "index.html"), "w") as f: 116 | f.write(html) 117 | 118 | with open(os.path.join(self.TEST_DIR, "jpg.txt"), "w") as f: 119 | f.write(jpg) 120 | 121 | app = make_app(predictor=self.bidaf_predictor, static_dir=self.TEST_DIR) 122 | app.testing = True 123 | client = app.test_client() 124 | 125 | response = client.get("/") 126 | data = response.get_data().decode("utf-8") 127 | assert data == html 128 | 129 | response = client.get("jpg.txt") 130 | data = response.get_data().decode("utf-8") 131 | assert data == jpg 132 | -------------------------------------------------------------------------------- /tests/fixtures/data/squad.json: -------------------------------------------------------------------------------- 1 | { 2 | "data": [ 3 | { 4 | "title": "University_of_Notre_Dame", 5 | "paragraphs": [ 6 | { 7 | "context": "Architecturally, the school has a Catholic character. Atop the Main Building's gold dome is a golden statue of the Virgin Mary. Immediately in front of the Main Building and facing it, is a copper statue of Christ with arms upraised with the legend \"Venite Ad Me Omnes\". Next to the Main Building is the Basilica of the Sacred Heart. Immediately behind the basilica is the Grotto, a Marian place of prayer and reflection. It is a replica of the grotto at Lourdes, France where the Virgin Mary reputedly appeared to Saint Bernadette Soubirous in 1858. At the end of the main drive (and in a direct line that connects through 3 statues and the Gold Dome), is a simple, modern stone statue of Mary.", 8 | "qas": [ 9 | { 10 | "answers": [ 11 | { 12 | "answer_start": 515, 13 | "text": "Saint Bernadette Soubirous" 14 | } 15 | ], 16 | "question": "To whom did the Virgin Mary allegedly appear in 1858 in Lourdes France?", 17 | "id": "5733be284776f41900661182" 18 | }, 19 | { 20 | "answers": [ 21 | { 22 | "answer_start": 92, 23 | "text": "a golden statue of the Virgin Mary" 24 | }, 25 | { 26 | "answer_start": 92, 27 | "text": "a golden statue of the Virgin Mary" 28 | }, 29 | { 30 | "answer_start": 0, 31 | "text": "Architecturally, the school has a Catholic character. Atop the Main Building's gold dome is a golden statue of the Virgin Mary. Immediately in front of the Main Building and facing it, is a copper statue of Christ with arms upraised with the legend \"Venite Ad Me Omnes\". Next to the Main Building is the Basilica of the Sacred Heart. Immediately behind the basilica is the Grotto, a Marian place of prayer and reflection. It is a replica of the grotto at Lourdes, France where the Virgin Mary reputedly appeared to Saint Bernadette Soubirous in 1858. At the end of the main drive (and in a direct line that connects through 3 statues and the Gold Dome), is a simple, modern stone statue of Mary." 32 | } 33 | ], 34 | "question": "What sits on top of the Main Building at Notre Dame?", 35 | "id": "5733be284776f4190066117e" 36 | } 37 | ] 38 | }, 39 | { 40 | "context": "In 1882, Albert Zahm (John Zahm's brother) built an early wind tunnel used to compare lift to drag of aeronautical models. Around 1899, Professor Jerome Green became the first American to send a wireless message. In 1931, Father Julius Nieuwland performed early work on basic reactions that was used to create neoprene. Study of nuclear physics at the university began with the building of a nuclear accelerator in 1936, and continues now partly through a partnership in the Joint Institute for Nuclear Astrophysics.", 41 | "qas": [ 42 | { 43 | "answers": [ 44 | { 45 | "answer_start": 3, 46 | "text": "1882" 47 | } 48 | ], 49 | "question": "In what year did Albert Zahm begin comparing aeronatical models at Notre Dame?", 50 | "id": "5733b1da4776f41900661068" 51 | }, 52 | { 53 | "answers": [ 54 | { 55 | "answer_start": 222, 56 | "text": "Father Julius Nieuwl" 57 | } 58 | ], 59 | "question": "Which individual worked on projects at Notre Dame that eventually created neoprene?", 60 | "id": "5733b1da4776f4190066106b" 61 | }, 62 | { 63 | "answers": [ 64 | { 65 | "answer_start": 49, 66 | "text": "an early wind tunnel" 67 | } 68 | ], 69 | "question": "What did the brother of John Zahm construct at Notre Dame?", 70 | "id": "5733b1da4776f41900661067" 71 | } 72 | ] 73 | } 74 | ] 75 | } 76 | ] 77 | } 78 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | on: 3 | pull_request: 4 | branches: 5 | - master 6 | push: 7 | branches: 8 | - master 9 | release: 10 | types: [published] 11 | schedule: 12 | - cron: '17 11 * * 1,2,3,4,5' # early morning Monday - Friday 13 | 14 | jobs: 15 | checks: 16 | name: Checks 17 | runs-on: ubuntu-latest 18 | steps: 19 | - uses: actions/checkout@v2 20 | 21 | - name: Setup Python 22 | uses: actions/setup-python@v1 23 | with: 24 | python-version: 3.8 25 | 26 | - uses: actions/cache@v2 27 | with: 28 | path: ${{ env.pythonLocation }} 29 | key: ${{ runner.os }}-pydeps-${{ env.pythonLocation }}-${{ hashFiles('setup.py') }}-${{ hashFiles('dev-requirements.txt') }} 30 | 31 | - name: Install dependencies 32 | run: | 33 | pip install --upgrade --upgrade-strategy eager -r dev-requirements.txt -e . 34 | 35 | - name: Debug info 36 | run: | 37 | pip freeze 38 | 39 | - name: Format 40 | if: always() 41 | run: | 42 | black --check . 43 | 44 | - name: Lint 45 | if: always() 46 | run: | 47 | flake8 48 | 49 | - name: Type check 50 | if: always() 51 | run: | 52 | mypy . --ignore-missing-imports --no-site-packages 53 | 54 | - name: Check package setup 55 | if: always() 56 | run: | 57 | python setup.py check 58 | 59 | - name: Run tests 60 | if: always() 61 | run: | 62 | pytest -v 63 | 64 | - name: Upload coverage to Codecov 65 | if: github.repository == 'allenai/allennlp-server' && (github.event_name == 'push' || github.event_name == 'pull_request') 66 | uses: codecov/codecov-action@v1 67 | with: 68 | file: ./coverage.xml 69 | # Ignore codecov failures as the codecov server is not 70 | # very reliable but we don't want to report a failure 71 | # in the github UI just because the coverage report failed to 72 | # be published. 73 | fail_ci_if_error: false 74 | 75 | - name: Clean up 76 | if: always() 77 | run: | 78 | pip uninstall -y allennlp-server 79 | 80 | build_package: 81 | name: Build package 82 | if: github.repository == 'allenai/allennlp-server' 83 | runs-on: ubuntu-latest 84 | 85 | steps: 86 | - uses: actions/checkout@v2 87 | 88 | - name: Setup Python 89 | uses: actions/setup-python@v1 90 | with: 91 | python-version: 3.8 92 | 93 | - name: Check and set nightly version 94 | if: github.event_name == 'schedule' 95 | run: | 96 | # The get_version.py script requires the 'requests' package. 97 | pip install requests 98 | LATEST=$(python scripts/get_version.py latest) 99 | CURRENT=$(python scripts/get_version.py current) 100 | # Verify that current version is ahead of the last release. 101 | if [ "$CURRENT" == "$LATEST" ]; then 102 | echo "Current version needs to be ahead of latest release in order to build nightly release"; 103 | exit 1; 104 | fi 105 | echo "ALLENNLP_SERVER_VERSION_SUFFIX=.dev$(date -u +%Y%m%d)" >> $GITHUB_ENV 106 | 107 | - name: Check version and release tag match 108 | if: github.event_name == 'release' 109 | run: | 110 | # Remove 'refs/tags/' to get the actual tag from the release. 111 | TAG=${GITHUB_REF#refs/tags/}; 112 | VERSION=$(python scripts/get_version.py current) 113 | if [ "$TAG" != "$VERSION" ]; then 114 | echo "Bad tag or version. Tag $TAG does not match $VERSION"; 115 | exit 1; 116 | fi 117 | 118 | - uses: actions/cache@v2 119 | with: 120 | path: ${{ env.pythonLocation }} 121 | key: ${{ runner.os }}-pydeps-${{ env.pythonLocation }}-${{ hashFiles('requirements.txt') }}-${{ hashFiles('dev-requirements.txt') }} 122 | 123 | - name: Install requirements 124 | run: | 125 | pip install --upgrade pip setuptools wheel 126 | pip uninstall -y allennlp 127 | pip install -e . 128 | pip install -r dev-requirements.txt 129 | 130 | - name: Show pip freeze 131 | run: | 132 | pip freeze 133 | 134 | - name: Build Package 135 | run: | 136 | python setup.py bdist_wheel sdist 137 | 138 | - name: Save package 139 | uses: actions/upload-artifact@v1 140 | with: 141 | name: server-package 142 | path: dist 143 | 144 | test_package: 145 | name: Test Package 146 | if: github.repository == 'allenai/allennlp-server' 147 | needs: [build_package] # needs the package artifact created from 'build_package' job. 148 | runs-on: ubuntu-latest 149 | strategy: 150 | matrix: 151 | python: ['3.7', '3.8'] 152 | 153 | steps: 154 | - name: Setup Python 155 | uses: actions/setup-python@v1 156 | with: 157 | python-version: ${{ matrix.python }} 158 | 159 | - name: Install requirements 160 | run: | 161 | pip install --upgrade pip setuptools wheel 162 | 163 | - name: Download server package 164 | uses: actions/download-artifact@v1 165 | with: 166 | name: server-package 167 | path: dist 168 | 169 | - name: Install server package 170 | run: | 171 | pip install $(ls dist/*.whl) 172 | 173 | - name: Debug info 174 | run: | 175 | pip freeze 176 | 177 | 178 | docker: 179 | name: Docker Build 180 | runs-on: ubuntu-latest 181 | steps: 182 | - uses: actions/checkout@v2 183 | 184 | - name: Build Docker image 185 | run: | 186 | docker build -t allennlp-server . 187 | 188 | - name: Test Docker image 189 | run: | 190 | docker run --rm -p 8000:8000 allennlp-server --help 191 | 192 | # Publish the distribution files to PyPI 193 | publish: 194 | name: PyPI 195 | if: github.repository == 'allenai/allennlp-server' && (github.event_name == 'release' || github.event_name == 'schedule') 196 | needs: [checks, build_package, test_package, docker] 197 | runs-on: ubuntu-latest 198 | 199 | steps: 200 | - name: Setup Python 201 | uses: actions/setup-python@v1 202 | with: 203 | python-version: 3.8 204 | 205 | - name: Install requirements 206 | run: | 207 | pip install --upgrade pip setuptools wheel twine 208 | 209 | - name: Download server package 210 | uses: actions/download-artifact@v1 211 | with: 212 | name: server-package 213 | path: dist 214 | 215 | - name: Upload to PyPI 216 | env: 217 | PYPI_PASSWORD: ${{ secrets.PYPI_PASSWORD }} 218 | run: twine upload -u allennlp -p $PYPI_PASSWORD dist/* 219 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /allennlp_server/commands/server_simple.py: -------------------------------------------------------------------------------- 1 | """ 2 | A `Flask `_ server for serving predictions 3 | from a single AllenNLP model. It also includes a very, very bare-bones 4 | web front-end for exploring predictions (or you can provide your own). 5 | 6 | $ allennlp serve --help 7 | usage: allennlp serve [-h] --archive-path ARCHIVE_PATH --predictor PREDICTOR 8 | [--weights-file WEIGHTS_FILE] 9 | [--cuda-device CUDA_DEVICE] [-o OVERRIDES] 10 | [--static-dir STATIC_DIR] [--title TITLE] 11 | [--field-name FIELD_NAME] [--host HOST] [-p PORT] 12 | [--include-package INCLUDE_PACKAGE] 13 | 14 | Serve up a simple model. 15 | 16 | optional arguments: 17 | -h, --help show this help message and exit 18 | --archive-path ARCHIVE_PATH 19 | path to trained archive file 20 | --predictor PREDICTOR 21 | name of predictor 22 | --cuda-device CUDA_DEVICE 23 | id of GPU to use (if any) (default = -1) 24 | -o OVERRIDES, --overrides OVERRIDES 25 | a JSON structure used to override the experiment 26 | configuration 27 | --static-dir STATIC_DIR 28 | serve index.html from this directory 29 | --title TITLE change the default page title (default = AllenNLP 30 | Demo) 31 | --field-name FIELD_NAME 32 | field names to include in the demo 33 | --host HOST interface to serve the demo on (default = 127.0.0.1) 34 | -p PORT, --port PORT port to serve the demo on (default = 8000) 35 | --include-package INCLUDE_PACKAGE 36 | additional packages to include 37 | """ 38 | import argparse 39 | import json 40 | import logging 41 | import os 42 | import sys 43 | from string import Template 44 | from typing import List, Callable, Optional, Any, Iterable, Dict 45 | 46 | from allennlp.commands import Subcommand 47 | from allennlp.common import JsonDict 48 | from allennlp.common.checks import check_for_gpu 49 | from allennlp.predictors import Predictor 50 | from flask import Flask, request, Response, jsonify, send_file, send_from_directory 51 | from flask_cors import CORS 52 | from gevent.pywsgi import WSGIServer 53 | 54 | 55 | logger = logging.getLogger(__name__) 56 | 57 | 58 | class ServerError(Exception): 59 | def __init__( 60 | self, message: str, status_code: int = 400, payload: Optional[Iterable[Any]] = None 61 | ) -> None: 62 | super().__init__(self) 63 | self.message = message 64 | self.status_code = status_code 65 | self.payload = payload 66 | 67 | def to_dict(self) -> Dict[Any, Any]: 68 | error_dict = dict(self.payload or ()) 69 | error_dict["message"] = self.message 70 | return error_dict 71 | 72 | 73 | def make_app( 74 | predictor: Predictor, 75 | field_names: List[str] = None, 76 | static_dir: str = None, 77 | sanitizer: Callable[[JsonDict], JsonDict] = None, 78 | title: str = "AllenNLP Demo", 79 | ) -> Flask: 80 | """ 81 | Creates a Flask app that serves up the provided ``Predictor`` 82 | along with a front-end for interacting with it. 83 | 84 | If you want to use the built-in bare-bones HTML, you must provide the 85 | field names for the inputs (which will be used both as labels 86 | and as the keys in the JSON that gets sent to the predictor). 87 | 88 | If you would rather create your own HTML, call it index.html 89 | and provide its directory as ``static_dir``. In that case you 90 | don't need to supply the field names -- that information should 91 | be implicit in your demo site. (Probably the easiest thing to do 92 | is just start with the bare-bones HTML and modify it.) 93 | 94 | In addition, if you want somehow transform the JSON prediction 95 | (e.g. by removing probabilities or logits) 96 | you can do that by passing in a ``sanitizer`` function. 97 | """ 98 | if static_dir is not None: 99 | static_dir = os.path.abspath(static_dir) 100 | if not os.path.exists(static_dir): 101 | logger.error("app directory %s does not exist, aborting", static_dir) 102 | sys.exit(-1) 103 | elif static_dir is None and field_names is None: 104 | print( 105 | "Neither build_dir nor field_names passed. Demo won't render on this port.\n" 106 | "You must use nodejs + react app to interact with the server." 107 | ) 108 | 109 | app = Flask(__name__) 110 | 111 | @app.errorhandler(ServerError) 112 | def handle_invalid_usage(error: ServerError) -> Response: 113 | response = jsonify(error.to_dict()) 114 | response.status_code = error.status_code 115 | return response 116 | 117 | @app.route("/") 118 | def index() -> Response: 119 | if static_dir is not None: 120 | return send_file(os.path.join(static_dir, "index.html")) 121 | else: 122 | html = _html(title, field_names or []) 123 | return Response(response=html, status=200) 124 | 125 | @app.route("/predict", methods=["POST", "OPTIONS"]) 126 | def predict() -> Response: 127 | """make a prediction using the specified model and return the results""" 128 | if request.method == "OPTIONS": 129 | return Response(response="", status=200) 130 | 131 | data = request.get_json() 132 | 133 | prediction = predictor.predict_json(data) 134 | if sanitizer is not None: 135 | prediction = sanitizer(prediction) 136 | 137 | log_blob = {"inputs": data, "outputs": prediction} 138 | logger.info("prediction: %s", json.dumps(log_blob)) 139 | 140 | return jsonify(prediction) 141 | 142 | @app.route("/predict_batch", methods=["POST", "OPTIONS"]) 143 | def predict_batch() -> Response: 144 | """make a prediction using the specified model and return the results""" 145 | if request.method == "OPTIONS": 146 | return Response(response="", status=200) 147 | 148 | data = request.get_json() 149 | 150 | prediction = predictor.predict_batch_json(data) 151 | if sanitizer is not None: 152 | prediction = [sanitizer(p) for p in prediction] 153 | 154 | return jsonify(prediction) 155 | 156 | @app.route("/") 157 | def static_proxy(path: str) -> Response: 158 | if static_dir is not None: 159 | return send_from_directory(static_dir, path) 160 | else: 161 | raise ServerError("static_dir not specified", 404) 162 | 163 | return app 164 | 165 | 166 | def _get_predictor(args: argparse.Namespace) -> Predictor: 167 | check_for_gpu(args.cuda_device) 168 | return Predictor.from_path( 169 | args.archive_path, 170 | predictor_name=args.predictor, 171 | cuda_device=args.cuda_device, 172 | overrides=args.overrides, 173 | ) 174 | 175 | 176 | @Subcommand.register("serve") 177 | class SimpleServer(Subcommand): 178 | def add_subparser(self, parser: argparse._SubParsersAction) -> argparse.ArgumentParser: 179 | description = """Serve up a simple model.""" 180 | subparser = parser.add_parser( 181 | self.name, 182 | description=description, 183 | help="Serve up a simple model.", 184 | ) 185 | 186 | subparser.add_argument( 187 | "--archive-path", 188 | type=str, 189 | required=True, 190 | help="path to trained archive file", 191 | ) 192 | 193 | subparser.add_argument("--predictor", type=str, help="registered name of predictor") 194 | 195 | subparser.add_argument( 196 | "--cuda-device", type=int, default=-1, help="id of GPU to use (if any)" 197 | ) 198 | 199 | subparser.add_argument( 200 | "-o", 201 | "--overrides", 202 | type=str, 203 | default="", 204 | help="a JSON structure used to override the experiment configuration", 205 | ) 206 | 207 | subparser.add_argument( 208 | "--static-dir", type=str, help="serve index.html from this directory" 209 | ) 210 | 211 | subparser.add_argument( 212 | "--title", 213 | type=str, 214 | help="change the default page title", 215 | default="AllenNLP Demo", 216 | ) 217 | 218 | subparser.add_argument( 219 | "--field-name", 220 | type=str, 221 | action="append", 222 | dest="field_names", 223 | metavar="FIELD_NAME", 224 | help="field names to include in the demo", 225 | ) 226 | 227 | subparser.add_argument( 228 | "--host", 229 | type=str, 230 | default="127.0.0.1", 231 | help="interface to serve the demo on", 232 | ) 233 | 234 | subparser.add_argument( 235 | "-p", "--port", type=int, default=8000, help="port to serve the demo on" 236 | ) 237 | 238 | subparser.set_defaults(func=serve) 239 | 240 | return subparser 241 | 242 | 243 | def serve(args: argparse.Namespace) -> None: 244 | predictor = _get_predictor(args) 245 | 246 | app = make_app( 247 | predictor=predictor, 248 | field_names=args.field_names, 249 | static_dir=args.static_dir, 250 | title=args.title, 251 | ) 252 | CORS(app) 253 | 254 | http_server = WSGIServer((args.host, args.port), app) 255 | print(f"Model loaded, serving demo on http://{args.host}:{args.port}") 256 | http_server.serve_forever() 257 | 258 | 259 | # 260 | # HTML and Templates for the default bare-bones app are below 261 | # 262 | 263 | 264 | _PAGE_TEMPLATE = Template( 265 | """ 266 | 267 | 268 | 269 | $title 270 | 271 | 274 | 275 | 276 |
277 |
278 |
279 |
280 |

$title

281 |
282 | $inputs 283 |
284 | 287 |
288 |
289 |
290 |
291 |
292 |
293 |
294 |
295 |
296 |
297 |

Run model to view results

298 |
299 |
300 |
301 |
302 |
303 |
304 |
305 | 306 | 329 | 330 | """ 331 | ) 332 | 333 | _SINGLE_INPUT_TEMPLATE = Template( 334 | """ 335 |
336 | 337 | 338 |
339 | """ 340 | ) 341 | 342 | _CSS = """ 343 | body, 344 | html { 345 | min-width: 48em; 346 | background: #f9fafc; 347 | font-size: 16px 348 | } 349 | 350 | * { 351 | font-family: sans-serif; 352 | color: #232323 353 | } 354 | 355 | section { 356 | background: #fff 357 | } 358 | 359 | code, 360 | code span, 361 | pre, 362 | .output { 363 | font-family: 'Roboto Mono', monospace!important 364 | } 365 | 366 | code { 367 | background: #f6f8fa 368 | } 369 | 370 | li, 371 | p, 372 | td, 373 | th { 374 | -webkit-font-smoothing: antialiased; 375 | -moz-osx-font-smoothing: grayscale; 376 | font-size: 1.125em; 377 | line-height: 1.5em; 378 | margin: 1.2em 0 379 | } 380 | 381 | pre { 382 | margin: 2em 0 383 | } 384 | 385 | h1, 386 | h2 { 387 | -webkit-font-smoothing: antialiased; 388 | -moz-osx-font-smoothing: grayscale; 389 | font-weight: 300 390 | } 391 | 392 | h2 { 393 | font-size: 2em; 394 | color: rgba(35, 35, 35, .75) 395 | } 396 | 397 | img { 398 | max-width: 100% 399 | } 400 | 401 | hr { 402 | display: block; 403 | border: none; 404 | height: .375em; 405 | background: #f6f8fa 406 | } 407 | 408 | blockquote, 409 | hr { 410 | margin: 2.4em 0 411 | } 412 | 413 | .btn { 414 | text-decoration: none; 415 | cursor: pointer; 416 | text-transform: uppercase; 417 | font-size: 1em; 418 | margin: 0; 419 | -moz-appearance: none; 420 | -webkit-appearance: none; 421 | border: none; 422 | color: #fff!important; 423 | display: block; 424 | background: #2085bc; 425 | padding: .9375em 3.625em; 426 | -webkit-transition: background-color .2s ease, opacity .2s ease; 427 | transition: background-color .2s ease, opacity .2s ease 428 | } 429 | 430 | .btn.btn--blue { 431 | background: #2085bc 432 | } 433 | 434 | .btn:focus, 435 | .btn:hover { 436 | background: #40affd; 437 | outline: 0 438 | } 439 | 440 | .btn:focus { 441 | box-shadow: 0 0 1.25em rgba(50, 50, 150, .05) 442 | } 443 | 444 | .btn:active { 445 | opacity: .66; 446 | background: #2085bc; 447 | -webkit-transition-duration: 0s; 448 | transition-duration: 0s 449 | } 450 | 451 | .btn:disabled, 452 | .btn:disabled:active, 453 | .btn:disabled:hover { 454 | cursor: default; 455 | background: #d0dae3 456 | } 457 | 458 | form { 459 | display: block 460 | } 461 | 462 | .form__field { 463 | -webkit-transition: margin .2s ease; 464 | transition: margin .2s ease 465 | } 466 | 467 | .form__field+.form__field { 468 | margin-top: 2.5em 469 | } 470 | 471 | .form__field label { 472 | display: block; 473 | font-weight: 600; 474 | font-size: 1.125em 475 | } 476 | 477 | .form__field label+* { 478 | margin-top: 1.25em 479 | } 480 | 481 | .form__field input[type=text], 482 | .form__field textarea { 483 | -moz-appearance: none; 484 | -webkit-appearance: none; 485 | width: 100%; 486 | font-size: 1em; 487 | -webkit-font-smoothing: antialiased; 488 | -moz-osx-font-smoothing: grayscale; 489 | padding: .8125em 1.125em; 490 | color: #232323; 491 | border: .125em solid #d4dce2; 492 | display: block; 493 | box-sizing: border-box; 494 | -webkit-transition: background-color .2s ease, color .2s ease, border-color .2s ease, opacity .2s ease; 495 | transition: background-color .2s ease, color .2s ease, border-color .2s ease, opacity .2s ease 496 | } 497 | 498 | .form__field input[type=text]::-webkit-input-placeholder, 499 | .form__field textarea::-webkit-input-placeholder { 500 | color: #b4b4b4 501 | } 502 | 503 | .form__field input[type=text]:-moz-placeholder, 504 | .form__field textarea:-moz-placeholder { 505 | color: #b4b4b4 506 | } 507 | 508 | .form__field input[type=text]::-moz-placeholder, 509 | .form__field textarea::-moz-placeholder { 510 | color: #b4b4b4 511 | } 512 | 513 | .form__field input[type=text]:-ms-input-placeholder, 514 | .form__field textarea:-ms-input-placeholder { 515 | color: #b4b4b4 516 | } 517 | 518 | .form__field input[type=text]:focus, 519 | .form__field textarea:focus { 520 | outline: 0; 521 | border-color: #63a7d4; 522 | box-shadow: 0 0 1.25em rgba(50, 50, 150, .05) 523 | } 524 | 525 | .form__field textarea { 526 | resize: vertical; 527 | min-height: 8.25em 528 | } 529 | 530 | .form__field .btn { 531 | -webkit-user-select: none; 532 | -moz-user-select: none; 533 | -ms-user-select: none; 534 | user-select: none; 535 | -webkit-touch-callout: none 536 | } 537 | 538 | .form__field--btn { 539 | display: -webkit-box; 540 | display: -ms-flexbox; 541 | display: -webkit-flex; 542 | display: flex; 543 | -webkit-flex-direction: row; 544 | -ms-flex-direction: row; 545 | -webkit-box-orient: horizontal; 546 | -webkit-box-direction: normal; 547 | flex-direction: row; 548 | -webkit-justify-content: flex-end; 549 | -ms-justify-content: flex-end; 550 | -webkit-box-pack: end; 551 | -ms-flex-pack: end; 552 | justify-content: flex-end 553 | } 554 | 555 | @media screen and (max-height:760px) { 556 | .form__instructions { 557 | margin: 1.875em 0 1.125em 558 | } 559 | .form__field:not(.form__field--btn)+.form__field:not(.form__field--btn) { 560 | margin-top: 1.25em 561 | } 562 | } 563 | 564 | body, 565 | html { 566 | width: 100%; 567 | height: 100%; 568 | margin: 0; 569 | padding: 0; 570 | font-family: 'Source Sans Pro', sans-serif 571 | } 572 | 573 | h1 { 574 | font-weight: 300 575 | } 576 | 577 | .model__output { 578 | background: #fff 579 | } 580 | 581 | .model__output.model__output--empty { 582 | background: 0 0 583 | } 584 | 585 | .placeholder { 586 | width: 100%; 587 | height: 100%; 588 | display: -webkit-box; 589 | display: -ms-flexbox; 590 | display: -webkit-flex; 591 | display: flex; 592 | -webkit-align-items: center; 593 | -ms-flex-align: center; 594 | -webkit-box-align: center; 595 | align-items: center; 596 | -webkit-justify-content: center; 597 | -ms-justify-content: center; 598 | -webkit-box-pack: center; 599 | -ms-flex-pack: center; 600 | justify-content: center; 601 | -webkit-user-select: none; 602 | -moz-user-select: none; 603 | -ms-user-select: none; 604 | user-select: none; 605 | -webkit-touch-callout: none; 606 | cursor: default 607 | } 608 | 609 | .placeholder .placeholder__content { 610 | display: -webkit-box; 611 | display: -ms-flexbox; 612 | display: -webkit-flex; 613 | display: flex; 614 | -webkit-flex-direction: column; 615 | -ms-flex-direction: column; 616 | -webkit-box-orient: vertical; 617 | -webkit-box-direction: normal; 618 | flex-direction: column; 619 | -webkit-align-items: center; 620 | -ms-flex-align: center; 621 | -webkit-box-align: center; 622 | align-items: center; 623 | text-align: center 624 | } 625 | 626 | .placeholder svg { 627 | display: block 628 | } 629 | 630 | .placeholder svg.placeholder__empty, 631 | .placeholder svg.placeholder__error { 632 | width: 6em; 633 | height: 3.625em; 634 | fill: #e1e5ea; 635 | margin-bottom: 2em 636 | } 637 | 638 | .placeholder svg.placeholder__error { 639 | width: 4.4375em; 640 | height: 4em 641 | } 642 | 643 | .placeholder p { 644 | font-size: 1em; 645 | margin: 0; 646 | padding: 0; 647 | color: #9aa8b2 648 | } 649 | 650 | .placeholder svg.placeholder__working { 651 | width: 3.4375em; 652 | height: 3.4375em; 653 | -webkit-animation: working 1s infinite linear; 654 | animation: working 1s infinite linear 655 | } 656 | 657 | @-webkit-keyframes working { 658 | 0% { 659 | -webkit-transform: rotate(0deg) 660 | } 661 | 100% { 662 | -webkit-transform: rotate(360deg) 663 | } 664 | } 665 | 666 | @keyframes working { 667 | 0% { 668 | -webkit-transform: rotate(0deg); 669 | -ms-transform: rotate(0deg); 670 | transform: rotate(0deg) 671 | } 672 | 100% { 673 | -webkit-transform: rotate(360deg); 674 | -ms-transform: rotate(360deg); 675 | transform: rotate(360deg) 676 | } 677 | } 678 | 679 | .model__content { 680 | padding: 1.875em 2.5em; 681 | margin: auto; 682 | -webkit-transition: padding .2s ease; 683 | transition: padding .2s ease 684 | } 685 | 686 | .model__content:not(.model__content--srl-output) { 687 | max-width: 61.25em 688 | } 689 | 690 | .model__content h2 { 691 | margin: 0; 692 | padding: 0; 693 | font-size: 1em 694 | } 695 | 696 | .model__content h2 span { 697 | font-size: 2em; 698 | color: rgba(35, 35, 35, .75) 699 | } 700 | 701 | .model__content h2 .tooltip, 702 | .model__content h2 span { 703 | vertical-align: top 704 | } 705 | 706 | .model__content h2 span+.tooltip { 707 | margin-left: .4375em 708 | } 709 | 710 | .model__content>h2:first-child { 711 | margin: -.25em 0 0 -.03125em 712 | } 713 | 714 | .model__content__summary { 715 | font-size: 1em; 716 | -webkit-font-smoothing: antialiased; 717 | -moz-osx-font-smoothing: grayscale; 718 | padding: 1.25em; 719 | background: #f6f8fa 720 | } 721 | 722 | @media screen and (min-height:800px) { 723 | .model__content { 724 | padding-top: 4.6vh; 725 | padding-bottom: 4.6vh 726 | } 727 | } 728 | 729 | .pane-container { 730 | display: -webkit-box; 731 | display: -ms-flexbox; 732 | display: -webkit-flex; 733 | display: flex; 734 | -webkit-flex-direction: column; 735 | -ms-flex-direction: column; 736 | -webkit-box-orient: vertical; 737 | -webkit-box-direction: normal; 738 | flex-direction: column; 739 | height: 100% 740 | } 741 | 742 | .pane { 743 | display: -webkit-box; 744 | display: -ms-flexbox; 745 | display: -webkit-flex; 746 | display: flex; 747 | -webkit-flex-direction: row; 748 | -ms-flex-direction: row; 749 | -webkit-box-orient: horizontal; 750 | -webkit-box-direction: normal; 751 | flex-direction: row; 752 | position: relative; 753 | -webkit-box-flex: 2; 754 | -webkit-flex: 2; 755 | -ms-flex: 2; 756 | flex: 2; 757 | height: auto; 758 | min-height: 100%; 759 | min-height: 34.375em 760 | } 761 | 762 | .pane__left, 763 | .pane__right { 764 | width: 100%; 765 | height: 100%; 766 | -webkit-align-self: stretch; 767 | -ms-flex-item-align: stretch; 768 | align-self: stretch; 769 | min-width: 24em; 770 | min-height: 34.375em 771 | } 772 | 773 | .pane__left { 774 | height: auto; 775 | min-height: 100% 776 | } 777 | 778 | .pane__right { 779 | width: 100%; 780 | overflow: auto; 781 | height: auto; 782 | min-height: 100% 783 | } 784 | 785 | .pane__right .model__content.model__content--srl-output { 786 | display: inline-block; 787 | margin: auto 788 | } 789 | 790 | .pane__thumb { 791 | height: auto; 792 | min-height: 100%; 793 | margin-left: -.625em; 794 | position: absolute; 795 | width: 1.25em 796 | } 797 | 798 | .pane__thumb:after { 799 | display: block; 800 | position: absolute; 801 | height: 100%; 802 | top: 0; 803 | content: ""; 804 | width: .25em; 805 | background: #e1e5ea; 806 | left: .5em 807 | } 808 | """ 809 | 810 | 811 | def _html(title: str, field_names: List[str]) -> str: 812 | """ 813 | Returns bare bones HTML for serving up an input form with the 814 | specified fields that can render predictions from the configured model. 815 | """ 816 | inputs = "".join( 817 | _SINGLE_INPUT_TEMPLATE.substitute(field_name=field_name) for field_name in field_names 818 | ) 819 | 820 | quoted_field_names = (f"'{field_name}'" for field_name in field_names) 821 | quoted_field_list = f"[{','.join(quoted_field_names)}]" 822 | 823 | return _PAGE_TEMPLATE.substitute(title=title, css=_CSS, inputs=inputs, qfl=quoted_field_list) 824 | --------------------------------------------------------------------------------