Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
vrachieru committed Jul 26, 2019
0 parents commit 5411207
Show file tree
Hide file tree
Showing 7 changed files with 373 additions and 0 deletions.
130 changes: 130 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
### Python ###
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/
.pytest_cache/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
.python-version

# celery beat schedule file
celerybeat-schedule

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

### Python Patch ###
.venv/

### Python.VirtualEnv Stack ###
# Virtualenv
# http://iamzed.com/2009/05/07/a-primer-on-virtualenv/
[Bb]in
[Ii]nclude
[Ll]ib
[Ll]ib64
[Ll]ocal
[Ss]cripts
pyvenv.cfg
pip-selfcheck.json


# End of https://www.gitignore.io/api/python
12 changes: 12 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
FROM python:3-alpine

MAINTAINER Victor Rachieru

WORKDIR /app
COPY . .

RUN pip install -r requirements.txt

EXPOSE 8080

CMD [ "python", "app.py" ]
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2019 Victor Rachieru

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
103 changes: 103 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
<p align="center">
<img src="https://user-images.githubusercontent.com/5860071/61949755-7dbca580-afb4-11e9-87b6-1187933cccfb.png" width="200" border="0" alt="rasa-model-server">
<br/>
<a href="https://github.com/vrachieru/rasa-model-server/releases/latest">
<img src="https://img.shields.io/badge/version-1.0-brightgreen.svg?style=flat-square" alt="Version">
</a>
<a href="https://hub.docker.com/r/vrachieru/rasa-model-server/">
<img src="https://img.shields.io/docker/stars/vrachieru/rasa-model-server.svg?style=flat-square" />
</a>
<a href="https://hub.docker.com/r/vrachieru/rasa-model-server/">
<img src="https://img.shields.io/docker/pulls/vrachieru/rasa-model-server.svg?style=flat-square" />
</a>
<br/>
Simple webserver for externalizing RASA models.
</p>


### Quick start

I recommend pulling the [latest image](https://hub.docker.com/r/vrachieru/rasa-model-server/) from Docker hub as this is the easiest way:
```bash
$ docker pull vrachieru/rasa-model-server
```

If you'd like, you can build the Docker image yourself:
```bash
docker build -t <yourname>/rasa-model-server .
```

Specify your desired configuration and run the container:
```bash
$ docker run -<d|i> --rm \
-v /host/path/to/models:/models \
-p <host_port>:8080 \
vrachieru/rasa-model-server
```

You can stop the container using:
```bash
$ docker stop rasa-model-server
```


### Configuration

You can configure the service via the following environment variables.

| Environment Variable | Default Value | Description |
| --------------------- | ------------- | ------------------------------------------------------- |
| PORT | 8080 | Port on which to run the webserver. |
| MODELS_DIR | models | The absolute or relative location of the models folder. |


### Example

Fetch a model without specifying a `If-None-Match` header.
```
$ curl -s -I 'http://localhost:8080/bot/model.tar.gz'
HTTP/1.0 200 OK
Content-Disposition: attachment; filename=model.tar.gz
Content-Length: 6478848
Content-Type: application/x-tar
Last-Modified: Tue, 23 Apr 2019 12:28:43 GMT
Cache-Control: public, max-age=43200
Expires: Fri, 26 Jul 2019 23:42:05 GMT
ETag: "1556022523.364716-6478848-1948524791"
Date: Fri, 26 Jul 2019 11:42:05 GMT
Accept-Ranges: bytes
Server: Werkzeug/0.14.1 Python/3.6.3
```

Once the model is loaded by RASA, subsequent requests will use the received ETAG to check if the model has been updated.
```
$ curl -s -I 'http://localhost:8080/bot/model.tar.gz' -H 'If-None-Match: 1556022523.364716-6478848-1948524791'
HTTP/1.0 304 NOT MODIFIED
Content-Disposition: attachment; filename=model.tar.gz
Cache-Control: public, max-age=43200
Expires: Fri, 26 Jul 2019 23:42:48 GMT
ETag: "1556022523.364716-6478848-1948524791"
Date: Fri, 26 Jul 2019 11:42:48 GMT
Accept-Ranges: bytes
Server: Werkzeug/0.14.1 Python/3.6.3
```

Update the model on the server an the next request will pull the new model upon ETag mismatch.
```
$ curl -s -I 'http://localhost:8080/bot/model.tar.gz' -H 'If-None-Match: 1556022523.364716-6478848-1948524791'
HTTP/1.0 200 OK
Content-Disposition: attachment; filename=model.tar.gz
Content-Length: 900
Content-Type: application/x-tar
Last-Modified: Sat, 29 Dec 2018 23:17:54 GMT
Cache-Control: public, max-age=43200
Expires: Fri, 26 Jul 2019 23:43:32 GMT
ETag: "1546125474.453404-900-1948524791"
Date: Fri, 26 Jul 2019 11:43:32 GMT
Accept-Ranges: bytes
Server: Werkzeug/0.14.1 Python/3.6.3
```

### License

MIT
68 changes: 68 additions & 0 deletions app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
from os import scandir, listdir, environ
from os.path import isfile, isdir, dirname, basename, relpath, join, exists, getsize
from datetime import datetime
from flask import Flask, render_template, send_from_directory


class Scaner:
def __init__(self, path):
self.entries = [Entry(entry) for entry in scandir(path.encode())]

class Entry:
def __init__(self, entry):
self.name = entry.name.decode()
self.path = entry.path.decode()
self.rel_path = relpath(self.path, models_dir)
self.is_dir = entry.is_dir()
self.created_time = datetime.fromtimestamp(entry.stat().st_ctime).ctime()
self.modified_time = datetime.fromtimestamp(entry.stat().st_mtime).ctime()
self.size = self._human_readable_size(self._get_size(entry.path))

def _get_size(self, path):
total_size = getsize(path)
if isdir(path):
for item in listdir(path):
item_path = join(path, item)
if isfile(item_path):
total_size += getsize(item_path)
elif isdir(item_path):
total_size += self._get_size(item_path)
return total_size

def _human_readable_size(self, size):
units = ['B', 'KB', 'MB', 'GB', 'TB']
human_fmt = '{0:.2f} {1}'
human_radix = 1024.

for unit in units[:-1]:
if size < human_radix:
return human_fmt.format(size, unit)
size /= humanradix

return human_fmt.format(size, units[-1])


models_dir = environ.get('MODELS_DIR', 'models')

app = Flask(__name__)

@app.route('/', methods=['GET'])
def index():
return render_template('index.html', path='/', entries=Scaner(models_dir).entries)

@app.route('/<path:path>', methods=['GET'])
def serve(path):
real_path = join(models_dir, path)
parent_path = relpath(dirname(real_path), models_dir)

if not exists(real_path):
return 'Not Found', 404

if isdir(real_path):
return render_template('index.html', parent_path=parent_path, path=path, entries=Scaner(real_path).entries)
else:
return send_from_directory(dirname(real_path), basename(real_path), as_attachment=True, attachment_filename=basename(real_path))


if __name__ == '__main__':
app.run(host='0.0.0.0', port=environ.get('PORT', 8080))
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Flask==1.0.2
38 changes: 38 additions & 0 deletions templates/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{ path }}</title>
<style>
table { width: 100%; }
td { width: 25%; }
</style>
</head>

<body>
<h1>{{ path }}</h1>
<hr/>
<table>
{% if parent_path %}
<tr>
<td>
<a href="{{ url_for('serve', path=parent_path) }}">../</a>
</td>
</tr>
{% endif %}
{% for entry in entries %}
<tr>
<td>
<a href="{{ url_for('serve', path=entry.rel_path) }}">
{{ entry.name|truncate(50, True) }}{% if entry.is_dir %}/{% endif %}
</a>
</td>
<td>{{ entry.created_time }}</td>
<td>{{ entry.modified_time }}</td>
<td>{{ entry.size }}</td>
</tr>
{% endfor %}
</table>
<hr/>
</body>
</html>

0 comments on commit 5411207

Please sign in to comment.