app.py 12.0 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
    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",
108
        nargs="+",
109 110 111 112 113 114 115
        help="log file directory")
    parser.add_argument(
        "--cache_timeout",
        action="store",
        dest="cache_timeout",
        type=float,
        default=20,
116
        help="memory cache timeout duration in seconds, default 20", )
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 149
    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 已提交
150 151
    app.config['BABEL_DEFAULT_LOCALE'] = default_language
    babel = Babel(app)
152 153 154 155 156 157
    log_reader = LogReader(args.logdir)

    # use a memory cache to reduce disk reading frequency.
    CACHE = MemCache(timeout=args.cache_timeout)
    cache_get = lib.cache_get(CACHE)

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

165 166
    @app.route("/")
    def index():
P
Peter Pan 已提交
167
        language = get_locale()
168 169 170 171 172 173 174
        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(
175 176
            os.path.join(server_path, static_file_path), filename
            if re.search(r'\..+$', filename) else filename + '.html')
177 178 179 180 181 182 183 184 185 186

    @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')

187 188 189 190 191 192 193 194 195 196 197 198
    @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')

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

205 206 207 208 209 210 211 212 213
    @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)
214 215 216 217 218 219 220 221 222 223 224 225
        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():
226 227
        data = cache_get("/data/plugin/images/tags", try_call,
                         lib.get_image_tags, log_reader)
228 229 230 231 232
        result = gen_result(0, "", data)
        return Response(json.dumps(result), mimetype='application/json')

    @app.route("/api/audio/tags")
    def audio_tags():
233 234
        data = cache_get("/data/plugin/audio/tags", try_call,
                         lib.get_audio_tags, log_reader)
235 236 237
        result = gen_result(0, "", data)
        return Response(json.dumps(result), mimetype='application/json')

238 239 240 241 242 243 244
    @app.route("/api/embeddings/tags")
    def embeddings_tags():
        data = cache_get("/data/plugin/embeddings/tags", try_call,
                         lib.get_embeddings_tags, log_reader)
        result = gen_result(0, "", data)
        return Response(json.dumps(result), mimetype='application/json')

245 246 247 248 249 250 251 252 253 254 255 256 257 258 259
    @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)

260 261
        data = cache_get(key, try_call, lib.get_image_tag_steps, log_reader,
                         mode, tag)
262 263 264 265 266 267 268 269 270 271 272 273
        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))
274 275 276
        data = cache_get(key, try_call, lib.get_individual_image, log_reader,
                         mode, tag, step_index)
        return Response(data, mimetype="image/png")
277 278 279 280

    @app.route('/api/embeddings/embedding')
    def embeddings():
        run = request.args.get('run')
走神的阿圆's avatar
走神的阿圆 已提交
281
        tag = request.args.get('tag', 'default')
282 283
        dimension = request.args.get('dimension')
        reduction = request.args.get('reduction')
284 285 286
        key = os.path.join('/data/plugin/embeddings/embeddings', run,
                           dimension, reduction)
        data = cache_get(key, try_call, lib.get_embeddings, log_reader, run,
287
                         tag, reduction, int(dimension))
288 289 290 291 292
        result = gen_result(0, "", data)
        return Response(json.dumps(result), mimetype='application/json')

    @app.route('/api/audio/list')
    def audio():
293
        run = request.args.get('run')
294
        tag = request.args.get('tag')
295
        key = os.path.join('/data/plugin/audio/audio', run, tag)
296

297 298
        data = cache_get(key, try_call, lib.get_audio_tag_steps, log_reader,
                         run, tag)
299 300 301 302 303 304
        result = gen_result(0, "", data)

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

    @app.route('/api/audio/audio')
    def individual_audio():
305
        run = request.args.get('run')
306 307 308
        tag = request.args.get('tag')  # include a index
        step_index = int(request.args.get('index'))  # index of step

309
        key = os.path.join('/data/plugin/audio/individualAudio', run, tag,
310
                           str(step_index))
311 312
        data = cache_get(key, try_call, lib.get_individual_audio, log_reader,
                         run, tag, step_index)
313 314 315 316 317 318 319 320 321 322 323 324
        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
325
        except Exception:
326 327 328 329
            time.sleep(0.5)
    webbrowser.open(index_url)


330 331 332 333 334 335 336 337 338 339 340 341 342 343
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)
344 345 346 347
    logger.info(" port=" + str(args.port))
    app = create_app(args)
    index_url = "http://" + host + ":" + str(port)
    if open_browser:
348 349 350
        threading.Thread(
            target=_open_browser, kwargs={"app": app,
                                          "index_url": index_url}).start()
351 352 353
    app.run(debug=False, host=args.host, port=args.port, threaded=True)


354 355
def run(logdir,
        host="127.0.0.1",
356
        port=8040,
357 358 359 360
        model_pb="",
        cache_timeout=20,
        language=None,
        open_browser=False):
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
    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 已提交
379
    app = create_app(args=args)
380
    app.run(debug=False, host=args.host, port=args.port, threaded=False)
381 382 383 384 385 386 387 388


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)