app.py 5.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
#!/user/bin/env python

# Copyright (c) 2017 VisualDL Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# =======================================================================

import os
import time
import sys
import multiprocessing
import threading
import re
import webbrowser
import requests
26

P
Peter Pan 已提交
27
from visualdl import __version__
走神的阿圆's avatar
走神的阿圆 已提交
28
from visualdl.utils import update_util
29

P
Peter Pan 已提交
30
from flask import (Flask, Response, redirect, request, send_file, make_response)
P
Peter Pan 已提交
31
from flask_babel import Babel
32 33

import visualdl.server
P
Peter Pan 已提交
34
from visualdl.server.api import create_api_call
35
from visualdl.server.args import (ParseArgs, parse_args)
P
Peter Pan 已提交
36
from visualdl.server.log import info
37
from visualdl.server.template import Template
38 39 40 41 42 43 44

SERVER_DIR = os.path.join(visualdl.ROOT, 'server')

support_language = ["en", "zh"]
default_language = support_language[0]

server_path = os.path.abspath(os.path.dirname(sys.argv[0]))
P
Peter Pan 已提交
45
template_file_path = os.path.join(SERVER_DIR, "./dist")
46 47
mock_data_path = os.path.join(SERVER_DIR, "./mock_data/")

P
Peter Pan 已提交
48 49
check_live_path = '/alive'

50

走神的阿圆's avatar
走神的阿圆 已提交
51
def create_app(args):
P
Peter Pan 已提交
52 53 54 55
    # disable warning from flask
    cli = sys.modules['flask.cli']
    cli.show_server_banner = lambda *x: None

56
    app = Flask('visualdl', static_folder=None)
P
Peter Pan 已提交
57 58
    app.logger.disabled = True

59 60 61
    # set static expires in a short time to reduce browser's memory usage.
    app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 30

P
Peter Pan 已提交
62 63
    app.config['BABEL_DEFAULT_LOCALE'] = default_language
    babel = Babel(app)
64
    api_call = create_api_call(args.logdir, args.model, args.cache_timeout)
65

走神的阿圆's avatar
走神的阿圆 已提交
66
    update_util.PbUpdater(args.product).start()
67

68
    public_path = args.public_path
P
Peter Pan 已提交
69 70
    api_path = public_path + '/api'

P
Peter Pan 已提交
71 72
    @babel.localeselector
    def get_locale():
P
Peter Pan 已提交
73 74 75 76
        lang = args.language
        if not lang or lang not in support_language:
            lang = request.accept_languages.best_match(support_language)
        return lang
P
Peter Pan 已提交
77

78 79
    if not args.api_only:

P
Peter Pan 已提交
80 81 82 83 84
        template = Template(
            os.path.join(server_path, template_file_path),
            PUBLIC_PATH=public_path.lstrip('/'),
            API_TOKEN_KEY=''
        )
P
Peter Pan 已提交
85

P
Peter Pan 已提交
86
        @app.route('/')
87 88
        def base():
            return redirect(public_path, code=302)
89

P
Peter Pan 已提交
90
        @app.route('/favicon.ico')
91 92 93 94
        def favicon():
            icon = os.path.join(template_file_path, 'favicon.ico')
            if os.path.exists(icon):
                return send_file(icon)
P
Peter Pan 已提交
95
            return 'file not found', 404
96

97
        @app.route(public_path + '/')
98 99 100 101
        def index():
            lang = get_locale()
            if lang == default_language:
                return redirect(public_path + '/index', code=302)
102
            lang = default_language if lang is None else lang
103 104 105 106 107
            return redirect(public_path + '/' + lang + '/index', code=302)

        @app.route(public_path + '/<path:filename>')
        def serve_static(filename):
            return template.render(filename if re.search(r'\..+$', filename) else filename + '.html')
108

P
Peter Pan 已提交
109 110
    @app.route(api_path + '/<path:method>')
    def serve_api(method):
111 112
        data, mimetype, headers = api_call(method, request.args)
        return make_response(Response(data, mimetype=mimetype, headers=headers))
P
Peter Pan 已提交
113 114 115 116 117

    @app.route(check_live_path)
    def check_live():
        return '', 204

118 119 120 121 122
    return app


def _open_browser(app, index_url):
    while True:
P
Peter Pan 已提交
123
        # noinspection PyBroadException
124 125 126
        try:
            requests.get(index_url)
            break
127
        except Exception:
128 129 130 131
            time.sleep(0.5)
    webbrowser.open(index_url)


P
Peter Pan 已提交
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154
def wait_until_live(args: ParseArgs):
    url = 'http://{host}:{port}'.format(host=args.host, port=args.port)
    while True:
        try:
            requests.get(url + check_live_path)
            info('Running VisualDL at http://%s:%s/ (Press CTRL+C to quit)', args.host, args.port)

            if args.host == 'localhost':
                info('Serving VisualDL on localhost; to expose to the network, use a proxy or pass --host 0.0.0.0')

            if args.api_only:
                info('Running in API mode, only %s/* will be served.', args.public_path + '/api')

            break
        except Exception:
            time.sleep(0.5)
    if not args.api_only and args.open_browser:
        webbrowser.open(url + args.public_path)


def _run(args):
    args = ParseArgs(**args)
    info('\033[1;33mVisualDL %s\033[0m', __version__)
走神的阿圆's avatar
走神的阿圆 已提交
155
    app = create_app(args)
P
Peter Pan 已提交
156
    threading.Thread(target=wait_until_live, args=(args,)).start()
157
    app.run(debug=False, host=args.host, port=args.port, threaded=False)
158 159


160
def run(logdir=None, **options):
P
Peter Pan 已提交
161
    args = {
162
        'logdir': logdir
163
    }
P
Peter Pan 已提交
164 165
    args.update(options)
    p = multiprocessing.Process(target=_run, args=(args,))
166 167 168 169 170 171
    p.start()
    return p.pid


def main():
    args = parse_args()
P
Peter Pan 已提交
172
    _run(args)
173 174


P
Peter Pan 已提交
175
if __name__ == '__main__':
P
Peter Pan 已提交
176
    main()