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 |