app.py 11.8 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 26
#!/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 json
import os
import time
import sys
import multiprocessing
import threading
import re
import webbrowser
import requests
27
from visualdl.reader.reader import LogReader
28 29 30 31
from argparse import ArgumentParser

from flask import (Flask, Response, redirect, request, send_file,
                   send_from_directory)
P
Peter Pan 已提交
32
from flask_babel import Babel
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52

import visualdl.server
from visualdl.server import lib
from visualdl.server.log import logger
from visualdl.python.cache import MemCache

error_retry_times = 3
error_sleep_time = 2  # seconds

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]))
static_file_path = os.path.join(SERVER_DIR, "./dist")
mock_data_path = os.path.join(SERVER_DIR, "./mock_data/")


class ParseArgs(object):
53 54 55 56 57 58 59
    def __init__(self,
                 logdir,
                 host="0.0.0.0",
                 port=8040,
                 model_pb="",
                 cache_timeout=20,
                 language=None):
60 61 62 63 64 65 66 67 68 69 70 71
        self.logdir = logdir
        self.host = host
        self.port = port
        self.model_pb = model_pb
        self.cache_timeout = cache_timeout
        self.language = language


def try_call(function, *args, **kwargs):
    res = lib.retry(error_retry_times, function, error_sleep_time, *args,
                    **kwargs)
    if not res:
P
Peter Pan 已提交
72
        logger.error("Internal server error. Retry later.")
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
    return res


def parse_args():
    """
    :return:
    """
    parser = ArgumentParser(
        description="VisualDL, a tool to visualize deep learning.")
    parser.add_argument(
        "-p",
        "--port",
        type=int,
        default=8040,
        action="store",
        dest="port",
        help="api service port")
    parser.add_argument(
        "-t",
        "--host",
        type=str,
        default="0.0.0.0",
        action="store",
        help="api service ip")
    parser.add_argument(
        "-m",
        "--model_pb",
        type=str,
        action="store",
        help="model proto in ONNX format or in Paddle framework format")
    parser.add_argument(
        "--logdir",
        required=True,
        action="store",
        dest="logdir",
        help="log file directory")
    parser.add_argument(
        "--cache_timeout",
        action="store",
        dest="cache_timeout",
        type=float,
        default=20,
115
        help="memory cache timeout duration in seconds, default 20", )
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
    parser.add_argument(
        "-L",
        "--language",
        type=str,
        action="store",
        help="set the default language")

    args = parser.parse_args()
    if not args.logdir:
        parser.print_help()
        sys.exit(-1)
    return args


# status, msg, data
def gen_result(status, msg, data):
    """
    :param status:
    :param msg:
    :return:
    """
    result = dict()
    result['status'] = status
    result['msg'] = msg
    result['data'] = data
    return result


def create_app(args):
    app = Flask(__name__, static_url_path="")
    # set static expires in a short time to reduce browser's memory usage.
    app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 30

P
Peter Pan 已提交
149 150 151
    app.config['BABEL_DEFAULT_LOCALE'] = default_language
    babel = Babel(app)

152 153 154 155 156 157 158 159
    log_reader = LogReader(args.logdir)

    # mannully put graph's image on this path also works.
    graph_image_path = os.path.join(args.logdir, 'graph.jpg')
    # use a memory cache to reduce disk reading frequency.
    CACHE = MemCache(timeout=args.cache_timeout)
    cache_get = lib.cache_get(CACHE)

P
Peter Pan 已提交
160 161 162
    @babel.localeselector
    def get_locale():
        language = args.language
163
        if not language or language not in support_language:
P
Peter Pan 已提交
164 165 166
            language = request.accept_languages.best_match(support_language)
        return language

167 168
    @app.route("/")
    def index():
P
Peter Pan 已提交
169
        language = get_locale()
170 171 172 173 174 175 176
        if language == default_language:
            return redirect('/app/index', code=302)
        return redirect('/app/' + language + '/index', code=302)

    @app.route('/app/<path:filename>')
    def serve_static(filename):
        return send_from_directory(
177 178
            os.path.join(server_path, static_file_path), filename
            if re.search(r'\..+$', filename) else filename + '.html')
179 180 181 182 183 184 185 186 187 188

    @app.route('/graphs/image')
    def serve_graph():
        return send_file(os.path.join(os.getcwd(), graph_image_path))

    @app.route('/api/logdir')
    def logdir():
        result = gen_result(0, "", {"logdir": args.logdir})
        return Response(json.dumps(result), mimetype='application/json')

189 190 191 192 193 194 195 196 197 198 199 200
    @app.route('/api/language')
    def language():
        data = get_locale()
        result = gen_result(0, "", data)
        return Response(json.dumps(result), mimetype='application/json')

    @app.route("/api/components")
    def components():
        data = cache_get('/data/components', lib.get_components, log_reader)
        result = gen_result(0, "", data)
        return Response(json.dumps(result), mimetype='application/json')

201 202
    @app.route('/api/runs')
    def runs():
203
        data = cache_get('/data/runs', lib.get_runs, log_reader)
204 205 206
        result = gen_result(0, "", data)
        return Response(json.dumps(result), mimetype='application/json')

207 208 209 210 211 212 213 214 215
    @app.route('/api/tags')
    def tags():
        data = cache_get('/data/tags', lib.get_tags, log_reader)
        result = gen_result(0, "", data)
        return Response(json.dumps(result), mimetype='application/json')

    @app.route('/api/logs')
    def logs():
        data = cache_get('/data/logs', lib.get_logs, log_reader)
216 217 218 219 220 221 222 223 224 225 226 227
        result = gen_result(0, "", data)
        return Response(json.dumps(result), mimetype='application/json')

    @app.route("/api/scalars/tags")
    def scalar_tags():
        data = cache_get("/data/plugin/scalars/tags", try_call,
                         lib.get_scalar_tags, log_reader)
        result = gen_result(0, "", data)
        return Response(json.dumps(result), mimetype='application/json')

    @app.route("/api/images/tags")
    def image_tags():
228 229
        data = cache_get("/data/plugin/images/tags", try_call,
                         lib.get_image_tags, log_reader)
230 231 232 233 234
        result = gen_result(0, "", data)
        return Response(json.dumps(result), mimetype='application/json')

    @app.route("/api/audio/tags")
    def audio_tags():
235 236
        data = cache_get("/data/plugin/audio/tags", try_call,
                         lib.get_audio_tags, log_reader)
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
        result = gen_result(0, "", data)
        return Response(json.dumps(result), mimetype='application/json')

    @app.route('/api/scalars/list')
    def scalars():
        run = request.args.get('run')
        tag = request.args.get('tag')
        key = os.path.join('/data/plugin/scalars/scalars', run, tag)
        data = cache_get(key, try_call, lib.get_scalar, log_reader, run, tag)
        result = gen_result(0, "", data)
        return Response(json.dumps(result), mimetype='application/json')

    @app.route('/api/images/list')
    def images():
        mode = request.args.get('run')
        tag = request.args.get('tag')
        key = os.path.join('/data/plugin/images/images', mode, tag)

255 256
        data = cache_get(key, try_call, lib.get_image_tag_steps, log_reader,
                         mode, tag)
257 258 259 260 261 262 263 264 265 266 267 268
        result = gen_result(0, "", data)

        return Response(json.dumps(result), mimetype='application/json')

    @app.route('/api/images/image')
    def individual_image():
        mode = request.args.get('run')
        tag = request.args.get('tag')  # include a index
        step_index = int(request.args.get('index'))  # index of step

        key = os.path.join('/data/plugin/images/individualImage', mode, tag,
                           str(step_index))
269 270 271
        data = cache_get(key, try_call, lib.get_individual_image, log_reader,
                         mode, tag, step_index)
        return Response(data, mimetype="image/png")
272 273 274 275 276 277

    @app.route('/api/embeddings/embedding')
    def embeddings():
        run = request.args.get('run')
        dimension = request.args.get('dimension')
        reduction = request.args.get('reduction')
278 279 280 281
        key = os.path.join('/data/plugin/embeddings/embeddings', run,
                           dimension, reduction)
        data = cache_get(key, try_call, lib.get_embeddings, log_reader, run,
                         reduction, int(dimension))
282 283 284 285 286
        result = gen_result(0, "", data)
        return Response(json.dumps(result), mimetype='application/json')

    @app.route('/api/audio/list')
    def audio():
287
        run = request.args.get('run')
288
        tag = request.args.get('tag')
289
        key = os.path.join('/data/plugin/audio/audio', run, tag)
290

291 292
        data = cache_get(key, try_call, lib.get_audio_tag_steps, log_reader,
                         run, tag)
293 294 295 296 297 298
        result = gen_result(0, "", data)

        return Response(json.dumps(result), mimetype='application/json')

    @app.route('/api/audio/audio')
    def individual_audio():
299
        run = request.args.get('run')
300 301 302
        tag = request.args.get('tag')  # include a index
        step_index = int(request.args.get('index'))  # index of step

303
        key = os.path.join('/data/plugin/audio/individualAudio', run, tag,
304
                           str(step_index))
305 306
        data = cache_get(key, try_call, lib.get_individual_audio, log_reader,
                         run, tag, step_index)
307 308 309 310 311 312 313 314 315 316 317 318
        response = send_file(
            data, as_attachment=True, attachment_filename='audio.wav')
        return response

    return app


def _open_browser(app, index_url):
    while True:
        try:
            requests.get(index_url)
            break
319
        except Exception:
320 321 322 323
            time.sleep(0.5)
    webbrowser.open(index_url)


324 325 326 327 328 329 330 331 332 333 334 335 336 337
def _run(logdir,
         host="127.0.0.1",
         port=8080,
         model_pb="",
         cache_timeout=20,
         language=None,
         open_browser=False):
    args = ParseArgs(
        logdir=logdir,
        host=host,
        port=port,
        model_pb=model_pb,
        cache_timeout=cache_timeout,
        language=language)
338 339 340 341
    logger.info(" port=" + str(args.port))
    app = create_app(args)
    index_url = "http://" + host + ":" + str(port)
    if open_browser:
342 343 344
        threading.Thread(
            target=_open_browser, kwargs={"app": app,
                                          "index_url": index_url}).start()
345 346 347
    app.run(debug=False, host=args.host, port=args.port, threaded=True)


348 349 350 351 352 353 354
def run(logdir,
        host="127.0.0.1",
        port=8080,
        model_pb="",
        cache_timeout=20,
        language=None,
        open_browser=False):
355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
    kwarg = {
        "logdir": logdir,
        "host": host,
        "port": port,
        "model_pb": model_pb,
        "cache_timeout": cache_timeout,
        "language": language,
        "open_browser": open_browser
    }

    p = multiprocessing.Process(target=_run, kwargs=kwarg)
    p.start()
    return p.pid


def main():
    args = parse_args()
    logger.info(" port=" + str(args.port))
P
Peter Pan 已提交
373
    app = create_app(args=args)
374
    app.run(debug=False, host=args.host, port=args.port, threaded=True)
375 376 377 378 379 380 381 382


if __name__ == "__main__":

    args = parse_args()
    logger.info(" port=" + str(args.port))
    app = create_app(args=args)
    app.run(debug=False, host=args.host, port=args.port, threaded=False)