app.py 7.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#!/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.
# =======================================================================
C
chenjian 已提交
16
import multiprocessing
17
import os
C
chenjian 已提交
18
import re
19 20
import sys
import threading
C
chenjian 已提交
21
import time
22
import webbrowser
23

C
chenjian 已提交
24 25 26 27 28 29 30
import requests
from flask import Flask
from flask import make_response
from flask import redirect
from flask import request
from flask import Response
from flask import send_file
P
Peter Pan 已提交
31
from flask_babel import Babel
32 33

import visualdl.server
C
chenjian 已提交
34
from visualdl import __version__
35
from visualdl.component.inference.model_convert_server import create_model_convert_api_call
C
chenjian 已提交
36
from visualdl.component.profiler.profiler_server import create_profiler_api_call
P
Peter Pan 已提交
37
from visualdl.server.api import create_api_call
38
from visualdl.server.api import get_component_tabs
C
chenjian 已提交
39 40
from visualdl.server.args import parse_args
from visualdl.server.args import ParseArgs
P
Peter Pan 已提交
41
from visualdl.server.log import info
C
chenjian 已提交
42
from visualdl.server.serve import upload_to_dev
43
from visualdl.server.template import Template
C
chenjian 已提交
44
from visualdl.utils import update_util
45 46 47 48 49 50 51

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 已提交
52
template_file_path = os.path.join(SERVER_DIR, "./dist")
53 54
mock_data_path = os.path.join(SERVER_DIR, "./mock_data/")

P
Peter Pan 已提交
55 56
check_live_path = '/alive'

57

C
chenjian 已提交
58
def create_app(args):  # noqa: C901
P
Peter Pan 已提交
59 60 61 62
    # disable warning from flask
    cli = sys.modules['flask.cli']
    cli.show_server_banner = lambda *x: None

63
    app = Flask('visualdl', static_folder=None)
P
Peter Pan 已提交
64 65
    app.logger.disabled = True

66 67 68
    # set static expires in a short time to reduce browser's memory usage.
    app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 30

P
Peter Pan 已提交
69 70
    app.config['BABEL_DEFAULT_LOCALE'] = default_language
    babel = Babel(app)
71
    api_call = create_api_call(args.logdir, args.model, args.cache_timeout)
C
chenjian 已提交
72
    profiler_api_call = create_profiler_api_call(args.logdir)
73
    inference_api_call = create_model_convert_api_call()
74 75
    if args.telemetry:
        update_util.PbUpdater(args.product).start()
76

77
    public_path = args.public_path
P
Peter Pan 已提交
78 79
    api_path = public_path + '/api'

P
Peter Pan 已提交
80 81 82 83 84 85
    def append_query_string(url):
        query_string = ''
        if request.query_string:
            query_string = '?' + request.query_string.decode()
        return url + query_string

P
Peter Pan 已提交
86 87
    @babel.localeselector
    def get_locale():
P
Peter Pan 已提交
88 89 90 91
        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 已提交
92

93 94
    if not args.api_only:

P
Peter Pan 已提交
95 96
        template = Template(
            os.path.join(server_path, template_file_path),
97 98 99
            PUBLIC_PATH=public_path,
            BASE_URI=public_path,
            API_URL=api_path,
C
chenjian 已提交
100 101 102
            TELEMETRY_ID='63a600296f8a71f576c4806376a9245b'
            if args.telemetry else '',
            THEME='' if args.theme is None else args.theme)
P
Peter Pan 已提交
103

P
Peter Pan 已提交
104
        @app.route('/')
105
        def base():
P
Peter Pan 已提交
106
            return redirect(append_query_string(public_path), code=302)
107

P
Peter Pan 已提交
108
        @app.route('/favicon.ico')
109 110 111 112
        def favicon():
            icon = os.path.join(template_file_path, 'favicon.ico')
            if os.path.exists(icon):
                return send_file(icon)
P
Peter Pan 已提交
113
            return 'file not found', 404
114

115
        @app.route(public_path + '/')
116
        def index():
C
chenjian 已提交
117 118
            return redirect(
                append_query_string(public_path + '/index'), code=302)
119 120 121

        @app.route(public_path + '/<path:filename>')
        def serve_static(filename):
122
            is_not_page_request = re.search(r'\..+$', filename)
C
chenjian 已提交
123 124
            response = template.render(
                filename if is_not_page_request else 'index.html')
125
            if not is_not_page_request:
C
chenjian 已提交
126 127 128 129 130 131 132
                response.set_cookie(
                    'vdl_lng',
                    get_locale(),
                    path='/',
                    samesite='Strict',
                    secure=False,
                    httponly=False)
133
            return response
134

C
chenjian 已提交
135
    @app.route(api_path + '/<path:method>', methods=["GET", "POST"])
P
Peter Pan 已提交
136
    def serve_api(method):
137
        data, mimetype, headers = api_call(method, request.args)
C
chenjian 已提交
138 139
        return make_response(
            Response(data, mimetype=mimetype, headers=headers))
P
Peter Pan 已提交
140

C
chenjian 已提交
141 142 143 144 145 146
    @app.route(api_path + '/profiler/<path:method>', methods=["GET", "POST"])
    def serve_profiler_api(method):
        data, mimetype, headers = profiler_api_call(method, request.args)
        return make_response(
            Response(data, mimetype=mimetype, headers=headers))

147 148 149 150 151 152 153 154 155
    @app.route(api_path + '/inference/<path:method>', methods=["GET", "POST"])
    def serve_inference_api(method):
        if request.method == 'POST':
            data, mimetype, headers = inference_api_call(method, request.form)
        else:
            data, mimetype, headers = inference_api_call(method, request.args)
        return make_response(
            Response(data, mimetype=mimetype, headers=headers))

156 157 158 159 160 161 162 163 164 165
    @app.route(api_path + '/component_tabs')
    def component_tabs():
        data, mimetype, headers = get_component_tabs(
            api_call,
            profiler_api_call,
            vdl_args=args,
            request_args=request.args)
        return make_response(
            Response(data, mimetype=mimetype, headers=headers))

P
Peter Pan 已提交
166 167 168 169
    @app.route(check_live_path)
    def check_live():
        return '', 204

170 171 172
    return app


P
Peter Pan 已提交
173 174 175 176 177
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)
C
chenjian 已提交
178 179
            info('Running VisualDL at http://%s:%s/ (Press CTRL+C to quit)',
                 args.host, args.port)
P
Peter Pan 已提交
180 181

            if args.host == 'localhost':
C
chenjian 已提交
182 183 184
                info(
                    'Serving VisualDL on localhost; to expose to the network, use a proxy or pass --host 0.0.0.0'
                )
P
Peter Pan 已提交
185 186

            if args.api_only:
C
chenjian 已提交
187 188
                info('Running in API mode, only %s/* will be served.',
                     args.public_path + '/api')
P
Peter Pan 已提交
189 190 191 192 193 194 195 196 197 198

            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)
199
    os.system('')
P
Peter Pan 已提交
200
    info('\033[1;33mVisualDL %s\033[0m', __version__)
走神的阿圆's avatar
走神的阿圆 已提交
201
    app = create_app(args)
C
chenjian 已提交
202
    threading.Thread(target=wait_until_live, args=(args, )).start()
203
    app.run(debug=False, host=args.host, port=args.port, threaded=False)
204 205


206
def run(logdir=None, **options):
C
chenjian 已提交
207
    args = {'logdir': logdir}
P
Peter Pan 已提交
208
    args.update(options)
C
chenjian 已提交
209
    p = multiprocessing.Process(target=_run, args=(args, ))
210 211 212 213 214 215
    p.start()
    return p.pid


def main():
    args = parse_args()
走神的阿圆's avatar
走神的阿圆 已提交
216 217 218 219 220
    if args.get('dest') == 'service':
        if args.get('behavior') == 'upload':
            upload_to_dev(args.get('logdir'), args.get('model'))
    else:
        _run(args)
221 222


P
Peter Pan 已提交
223
if __name__ == '__main__':
P
Peter Pan 已提交
224
    main()