app.py 4.5 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

走神的阿圆's avatar
走神的阿圆 已提交
27
from visualdl.utils import update_util
28

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

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

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 已提交
44
template_file_path = os.path.join(SERVER_DIR, "./dist")
45 46 47
mock_data_path = os.path.join(SERVER_DIR, "./mock_data/")


走神的阿圆's avatar
走神的阿圆 已提交
48
def create_app(args):
49
    app = Flask('visualdl', static_folder=None)
50 51 52
    # set static expires in a short time to reduce browser's memory usage.
    app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 30

P
Peter Pan 已提交
53 54
    app.config['BABEL_DEFAULT_LOCALE'] = default_language
    babel = Babel(app)
P
Peter Pan 已提交
55
    api_call = create_api_call(args.logdir, args.cache_timeout)
56

走神的阿圆's avatar
走神的阿圆 已提交
57
    update_util.PbUpdater().start()
58

59
    public_path = args.public_path
P
Peter Pan 已提交
60 61
    api_path = public_path + '/api'

62 63 64
    if args.api_only:
        logger.info('Running in API mode, only {}/* will be served.'.format(api_path))

P
Peter Pan 已提交
65 66
    @babel.localeselector
    def get_locale():
P
Peter Pan 已提交
67 68 69 70
        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 已提交
71

72 73
    if not args.api_only:

74
        template = Template(os.path.join(server_path, template_file_path), PUBLIC_PATH=public_path.lstrip('/'))
P
Peter Pan 已提交
75

P
Peter Pan 已提交
76
        @app.route('/')
77 78
        def base():
            return redirect(public_path, code=302)
79

P
Peter Pan 已提交
80
        @app.route('/favicon.ico')
81 82 83 84
        def favicon():
            icon = os.path.join(template_file_path, 'favicon.ico')
            if os.path.exists(icon):
                return send_file(icon)
P
Peter Pan 已提交
85
            return 'file not found', 404
86

87
        @app.route(public_path + '/')
88 89 90 91 92 93 94 95 96
        def index():
            lang = get_locale()
            if lang == default_language:
                return redirect(public_path + '/index', code=302)
            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')
97

P
Peter Pan 已提交
98 99 100 101
    @app.route(api_path + '/<path:method>')
    def serve_api(method):
        data, mimetype = api_call(method, request.args)
        return make_response(Response(data, mimetype=mimetype))
102 103 104 105 106
    return app


def _open_browser(app, index_url):
    while True:
P
Peter Pan 已提交
107
        # noinspection PyBroadException
108 109 110
        try:
            requests.get(index_url)
            break
111
        except Exception:
112 113 114 115
            time.sleep(0.5)
    webbrowser.open(index_url)


116 117
def _run(**kwargs):
    args = ParseArgs(**kwargs)
P
Peter Pan 已提交
118
    logger.info(' port=' + str(args.port))
走神的阿圆's avatar
走神的阿圆 已提交
119
    app = create_app(args)
120
    if not args.api_only:
P
Peter Pan 已提交
121
        index_url = 'http://' + args.host + ':' + str(args.port) + args.public_path
122 123
        if kwargs.get('open_browser', False):
            threading.Thread(
P
Peter Pan 已提交
124
                target=_open_browser, kwargs={'app': app, 'index_url': index_url}).start()
125
    app.run(debug=False, host=args.host, port=args.port, threaded=False)
126 127


128 129 130
def run(logdir=None, **options):
    kwargs = {
        'logdir': logdir
131
    }
132 133
    kwargs.update(options)
    p = multiprocessing.Process(target=_run, kwargs=kwargs)
134 135 136 137 138 139
    p.start()
    return p.pid


def main():
    args = parse_args()
P
Peter Pan 已提交
140
    logger.info(' port=' + str(args.port))
走神的阿圆's avatar
走神的阿圆 已提交
141
    app = create_app(args)
142
    app.run(debug=False, host=args.host, port=args.port, threaded=False)
143 144


P
Peter Pan 已提交
145
if __name__ == '__main__':
P
Peter Pan 已提交
146
    main()