app.py 32.1 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.
# =======================================================================
16
import json
C
chenjian 已提交
17
import multiprocessing
18
import os
C
chenjian 已提交
19
import re
C
chenjian 已提交
20
import signal
21 22
import sys
import threading
C
chenjian 已提交
23
import time
24
import urllib
25
import webbrowser
26

C
chenjian 已提交
27 28 29 30 31 32 33
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 已提交
34
from flask_babel import Babel
35 36

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

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

P
Peter Pan 已提交
60 61
check_live_path = '/alive'

62

C
chenjian 已提交
63
def create_app(args):  # noqa: C901
P
Peter Pan 已提交
64 65 66 67
    # disable warning from flask
    cli = sys.modules['flask.cli']
    cli.show_server_banner = lambda *x: None

68
    app = Flask('visualdl', static_folder=None)
P
Peter Pan 已提交
69 70
    app.logger.disabled = True

71 72 73
    # set static expires in a short time to reduce browser's memory usage.
    app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 30

P
Peter Pan 已提交
74
    app.config['BABEL_DEFAULT_LOCALE'] = default_language
75 76 77 78 79 80 81

    def get_locale():
        lang = args.language
        if not lang or lang not in support_language:
            lang = request.accept_languages.best_match(support_language)
        return lang

C
chenjian 已提交
82 83 84
    signal.signal(
        signal.SIGINT, signal.SIG_DFL
    )  # we add this to prevent SIGINT not work in multiprocess queue waiting
85 86
    babel = Babel(app, locale_selector=get_locale)  # noqa:F841
    # Babel api from flask_babel v3.0.0
87
    api_call = create_api_call(args.logdir, args.model, args.cache_timeout)
C
chenjian 已提交
88
    profiler_api_call = create_profiler_api_call(args.logdir)
89
    inference_api_call = create_model_convert_api_call()
90
    fastdeploy_api_call = create_fastdeploy_api_call()
91 92
    if args.telemetry:
        update_util.PbUpdater(args.product).start()
93

94
    public_path = args.public_path
P
Peter Pan 已提交
95 96
    api_path = public_path + '/api'

P
Peter Pan 已提交
97 98 99 100 101 102
    def append_query_string(url):
        query_string = ''
        if request.query_string:
            query_string = '?' + request.query_string.decode()
        return url + query_string

103 104
    if not args.api_only:

P
Peter Pan 已提交
105 106
        template = Template(
            os.path.join(server_path, template_file_path),
107 108 109
            PUBLIC_PATH=public_path,
            BASE_URI=public_path,
            API_URL=api_path,
C
chenjian 已提交
110 111 112
            TELEMETRY_ID='63a600296f8a71f576c4806376a9245b'
            if args.telemetry else '',
            THEME='' if args.theme is None else args.theme)
P
Peter Pan 已提交
113

P
Peter Pan 已提交
114
        @app.route('/')
115
        def base():
P
Peter Pan 已提交
116
            return redirect(append_query_string(public_path), code=302)
117

P
Peter Pan 已提交
118
        @app.route('/favicon.ico')
119 120 121 122
        def favicon():
            icon = os.path.join(template_file_path, 'favicon.ico')
            if os.path.exists(icon):
                return send_file(icon)
P
Peter Pan 已提交
123
            return 'file not found', 404
124

125
        @app.route(public_path + '/')
126
        def index():
C
chenjian 已提交
127 128
            return redirect(
                append_query_string(public_path + '/index'), code=302)
129 130 131

        @app.route(public_path + '/<path:filename>')
        def serve_static(filename):
132
            is_not_page_request = re.search(r'\..+$', filename)
C
chenjian 已提交
133 134
            response = template.render(
                filename if is_not_page_request else 'index.html')
135
            if not is_not_page_request:
C
chenjian 已提交
136 137 138 139 140 141 142
                response.set_cookie(
                    'vdl_lng',
                    get_locale(),
                    path='/',
                    samesite='Strict',
                    secure=False,
                    httponly=False)
143
            return response
144

C
chenjian 已提交
145
    @app.route(api_path + '/<path:method>', methods=["GET", "POST"])
P
Peter Pan 已提交
146
    def serve_api(method):
147
        data, mimetype, headers = api_call(method, request.args)
C
chenjian 已提交
148 149
        return make_response(
            Response(data, mimetype=mimetype, headers=headers))
P
Peter Pan 已提交
150

C
chenjian 已提交
151 152 153 154 155 156
    @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))

157 158 159 160 161 162 163 164 165
    @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))

166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
    @app.route(api_path + '/fastdeploy/<path:method>', methods=["GET", "POST"])
    def serve_fastdeploy_api(method):
        if request.method == 'POST':
            data, mimetype, headers = fastdeploy_api_call(method, request.form)
        else:
            data, mimetype, headers = fastdeploy_api_call(method, request.args)
        return make_response(
            Response(data, mimetype=mimetype, headers=headers))

    @app.route(
        api_path + '/fastdeploy/fastdeploy_client', methods=["GET", "POST"])
    def serve_fastdeploy_create_fastdeploy_client():
        try:
            if request.method == 'POST':
                fastdeploy_api_call('create_fastdeploy_client', request.form)
                request_args = request.form
            else:
                fastdeploy_api_call('create_fastdeploy_client', request.args)
                request_args = request.args
        except Exception as e:
            error_msg = '{}'.format(e)
            return make_response(error_msg)
        args = urllib.parse.urlencode(request_args)
189

190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
        if args:
            return redirect(
                api_path + "/fastdeploy/fastdeploy_client/app?{}".format(args),
                code=302)
        return redirect(
            api_path + "/fastdeploy/fastdeploy_client/app", code=302)

    @app.route(
        api_path + "/fastdeploy/fastdeploy_client/<path:path>",
        methods=["GET", "POST"])
    def request_fastdeploy_create_fastdeploy_client_app(path: str):
        '''
        Gradio app server url interface. We route urls for gradio app to gradio server.

        Args:
            path(str): All resource path from gradio server.

        Returns:
            Any thing from gradio server.
        '''
210
        lang = 'zh'
211
        if request.method == 'POST':
212 213 214 215 216 217 218 219 220 221
            if request.mimetype == 'application/json':
                request_args = request.json
            else:
                request_args = request.form.to_dict()
            if 'data' in request_args:
                lang = request_args['data'][-1]
                request_args['lang'] = lang
            elif 'lang' in request_args:
                lang = request_args['lang']

222
            port = fastdeploy_api_call('create_fastdeploy_client',
223
                                       request_args)
224
        else:
225 226 227 228 229 230
            request_args = request.args.to_dict()
            if 'data' in request_args:
                lang = request_args['data'][-1]
                request_args['lang'] = lang
            elif 'lang' in request_args:
                lang = request_args['lang']
231
            port = fastdeploy_api_call('create_fastdeploy_client',
232 233
                                       request_args)

234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
        if path == 'app':
            proxy_url = request.url.replace(
                request.host_url.rstrip('/') + api_path +
                '/fastdeploy/fastdeploy_client/app',
                'http://localhost:{}/'.format(port))
        else:
            proxy_url = request.url.replace(
                request.host_url.rstrip('/') + api_path +
                '/fastdeploy/fastdeploy_client/',
                'http://localhost:{}/'.format(port))
        resp = requests.request(
            method=request.method,
            url=proxy_url,
            headers={
                key: value
                for (key, value) in request.headers if key != 'Host'
            },
            data=request.get_data(),
            cookies=request.cookies,
            allow_redirects=False)
        if path == 'app':
            content = resp.content
            if request_args and 'server_id' in request_args:
                server_id = request_args.get('server_id')
                start_args = get_start_arguments(server_id)
                http_port = start_args.get('http-port', '')
                metrics_port = start_args.get('metrics-port', '')
                model_name = start_args.get('default_model_name', '')
                content = content.decode()
                try:
264
                    if request_args.get('lang', 'zh') == 'en':
265 266 267 268 269 270 271 272 273 274 275 276 277
                        server_addr_match = re.search(
                            '"label":\\s*{}.*?"value":\\s*"".*?}}'.format(
                                json.dumps("server ip",
                                           ensure_ascii=True).replace(
                                               '\\', '\\\\')), content)
                        if not server_addr_match or server_addr_match.group(
                                0).count('"label"') >= 2:
                            server_addr_match = re.search(
                                '"value":\\s*"".*?"label":\\s*{}.*?}}'.format(
                                    json.dumps("server ip",
                                               ensure_ascii=True).replace(
                                                   '\\', '\\\\')), content)
                        default_server_addr = server_addr_match.group(0)
C
chenjian 已提交
278 279 280 281 282 283
                        if '"value": ""' in default_server_addr:
                            cur_server_addr = default_server_addr.replace(
                                '"value": ""', '"value": "localhost"')
                        else:
                            cur_server_addr = default_server_addr.replace(
                                '"value":""', '"value": "localhost"')
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
                        content = content.replace(default_server_addr,
                                                  cur_server_addr)
                        http_port_match = re.search(
                            '"label":\\s*{}.*?"value":\\s*"".*?}}'.format(
                                json.dumps("server port",
                                           ensure_ascii=True).replace(
                                               '\\', '\\\\')), content)
                        if not http_port_match or http_port_match.group(
                                0).count('"label"') >= 2:
                            http_port_match = re.search(
                                '"value":\\s*"".*?"label":\\s*{}.*?}}'.format(
                                    json.dumps(
                                        "server port",
                                        ensure_ascii=True).replace(
                                            '\\', '\\\\')), content)
                        default_http_port = http_port_match.group(0)

C
chenjian 已提交
301 302 303 304 305 306 307 308
                        if '"value": ""' in default_http_port:
                            cur_http_port = default_http_port.replace(
                                '"value": ""',
                                '"value": "{}"'.format(http_port))
                        else:
                            cur_http_port = default_http_port.replace(
                                '"value":""',
                                '"value": "{}"'.format(http_port))
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
                        if http_port:
                            content = content.replace(default_http_port,
                                                      cur_http_port)
                        metrics_port_match = re.search(
                            '"label":\\s*{}.*?"value":\\s*"".*?}}'.format(
                                json.dumps("metrics port",
                                           ensure_ascii=True).replace(
                                               '\\', '\\\\')), content)
                        if not metrics_port_match or metrics_port_match.group(
                                0).count('"label"') >= 2:
                            metrics_port_match = re.search(
                                '"value":\\s*"".*?"label":\\s*{}.*?}}'.format(
                                    json.dumps(
                                        "metrics port",
                                        ensure_ascii=True).replace(
                                            '\\', '\\\\')), content)
                        default_metrics_port = metrics_port_match.group(0)
C
chenjian 已提交
326 327 328 329 330 331 332 333
                        if '"value": ""' in default_metrics_port:
                            cur_metrics_port = default_metrics_port.replace(
                                '"value": ""',
                                '"value": "{}"'.format(metrics_port))
                        else:
                            cur_metrics_port = default_metrics_port.replace(
                                '"value":""',
                                '"value": "{}"'.format(metrics_port))
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
                        if metrics_port:
                            content = content.replace(default_metrics_port,
                                                      cur_metrics_port)
                        model_name_match = re.search(
                            '"label":\\s*{}.*?"value":\\s*"".*?}}'.format(
                                json.dumps("model name",
                                           ensure_ascii=True).replace(
                                               '\\', '\\\\')), content)
                        if not model_name_match or model_name_match.group(
                                0).count('"label"') >= 2:
                            model_name_match = re.search(
                                '"value":\\s*"".*?"label":\\s*{}.*?}}'.format(
                                    json.dumps(
                                        "model name",
                                        ensure_ascii=True).replace(
                                            '\\', '\\\\')), content)
                        default_model_name = model_name_match.group(0)
C
chenjian 已提交
351 352 353 354 355 356 357 358
                        if '"value": ""' in default_model_name:
                            cur_model_name = default_model_name.replace(
                                '"value": ""',
                                '"value": "{}"'.format(model_name))
                        else:
                            cur_model_name = default_model_name.replace(
                                '"value":""',
                                '"value": "{}"'.format(model_name))
359 360 361 362 363
                        if model_name:
                            content = content.replace(default_model_name,
                                                      cur_model_name)
                        model_version_match = re.search(
                            '"label":\\s*{}.*?"value":\\s*"".*?}}'.format(
364 365
                                json.dumps("model version",
                                           ensure_ascii=True).replace(
366 367 368 369 370 371 372 373 374 375
                                               '\\', '\\\\')), content)
                        if not model_version_match or model_version_match.group(
                                0).count('"label"') >= 2:
                            model_version_match = re.search(
                                '"value":\\s*"".*?"label":\\s*{}.*?}}'.format(
                                    json.dumps(
                                        "model version",
                                        ensure_ascii=True).replace(
                                            '\\', '\\\\')), content)
                        default_model_version = model_version_match.group(0)
C
chenjian 已提交
376 377 378 379 380 381
                        if '"value": ""' in default_model_version:
                            cur_model_version = default_model_version.replace(
                                '"value": ""', '"value": "{}"'.format('1'))
                        else:
                            cur_model_version = default_model_version.replace(
                                '"value":""', '"value": "{}"'.format('1'))
382 383 384
                        content = content.replace(default_model_version,
                                                  cur_model_version)

385
                    else:
386 387
                        server_addr_match = re.search(
                            '"label":\\s*{}.*?"value":\\s*"".*?}}'.format(
388
                                json.dumps("服务ip", ensure_ascii=True).replace(
389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
                                    '\\', '\\\\')), content)
                        if not server_addr_match or server_addr_match.group(
                                0).count('"label"') >= 2:
                            server_addr_match = re.search(
                                '"value":\\s*"".*?"label":\\s*{}.*?}}'.format(
                                    json.dumps("服务ip",
                                               ensure_ascii=True).replace(
                                                   '\\', '\\\\')), content)
                            if not server_addr_match:
                                server_addr_match = re.search(
                                    '"label":\\s*{}.*?"value":\\s*"".*?}}'.
                                    format(
                                        json.dumps("服务ip",
                                                   ensure_ascii=False).replace(
                                                       '\\', '\\\\')), content)
                                if not server_addr_match or server_addr_match.group(
                                        0).count('"label"') >= 2:
                                    server_addr_match = re.search(
                                        '"value":\\s*"".*?"label":\\s*{}.*?}}'.
                                        format(
                                            json.dumps(
                                                "服务ip",
                                                ensure_ascii=False).replace(
                                                    '\\', '\\\\')), content)

                        default_server_addr = server_addr_match.group(0)
C
chenjian 已提交
415 416 417 418 419 420
                        if '"value": ""' in default_server_addr:
                            cur_server_addr = default_server_addr.replace(
                                '"value": ""', '"value": "localhost"')
                        else:
                            cur_server_addr = default_server_addr.replace(
                                '"value":""', '"value": "localhost"')
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453
                        content = content.replace(default_server_addr,
                                                  cur_server_addr)
                        http_port_match = re.search(
                            '"label":\\s*{}.*?"value":\\s*"".*?}}'.format(
                                json.dumps("推理服务端口",
                                           ensure_ascii=True).replace(
                                               '\\', '\\\\')), content)
                        if not http_port_match or http_port_match.group(
                                0).count('"label"') >= 2:
                            http_port_match = re.search(
                                '"value":\\s*"".*?"label":\\s*{}.*?}}'.format(
                                    json.dumps("推理服务端口",
                                               ensure_ascii=True).replace(
                                                   '\\', '\\\\')), content)
                            if not http_port_match:
                                http_port_match = re.search(
                                    '"label":\\s*{}.*?"value":\\s*"".*?}}'.
                                    format(
                                        json.dumps(
                                            "推理服务端口",
                                            ensure_ascii=False).replace(
                                                '\\', '\\\\')), content)
                                if not http_port_match or http_port_match.group(
                                        0).count('"label"') >= 2:
                                    http_port_match = re.search(
                                        '"value":\\s*"".*?"label":\\s*{}.*?}}'.
                                        format(
                                            json.dumps(
                                                "推理服务端口",
                                                ensure_ascii=False).replace(
                                                    '\\', '\\\\')), content)
                        default_http_port = http_port_match.group(0)

C
chenjian 已提交
454 455 456 457 458 459 460 461
                        if '"value": ""' in default_http_port:
                            cur_http_port = default_http_port.replace(
                                '"value": ""',
                                '"value": "{}"'.format(http_port))
                        else:
                            cur_http_port = default_http_port.replace(
                                '"value":""',
                                '"value": "{}"'.format(http_port))
462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494
                        if http_port:
                            content = content.replace(default_http_port,
                                                      cur_http_port)
                        metrics_port_match = re.search(
                            '"label":\\s*{}.*?"value":\\s*"".*?}}'.format(
                                json.dumps("性能服务端口",
                                           ensure_ascii=True).replace(
                                               '\\', '\\\\')), content)
                        if not metrics_port_match or metrics_port_match.group(
                                0).count('"label"') >= 2:
                            metrics_port_match = re.search(
                                '"value":\\s*"".*?"label":\\s*{}.*?}}'.format(
                                    json.dumps("性能服务端口",
                                               ensure_ascii=True).replace(
                                                   '\\', '\\\\')), content)
                            if not metrics_port_match:
                                metrics_port_match = re.search(
                                    '"label":\\s*{}.*?"value":\\s*"".*?}}'.
                                    format(
                                        json.dumps(
                                            "性能服务端口",
                                            ensure_ascii=False).replace(
                                                '\\', '\\\\')), content)
                                if not metrics_port_match or metrics_port_match.group(
                                        0).count('"label"') >= 2:
                                    metrics_port_match = re.search(
                                        '"value":\\s*"".*?"label":\\s*{}.*?}}'.
                                        format(
                                            json.dumps(
                                                "性能服务端口",
                                                ensure_ascii=False).replace(
                                                    '\\', '\\\\')), content)
                        default_metrics_port = metrics_port_match.group(0)
C
chenjian 已提交
495 496 497 498 499 500 501 502
                        if '"value": ""' in default_metrics_port:
                            cur_metrics_port = default_metrics_port.replace(
                                '"value": ""',
                                '"value": "{}"'.format(metrics_port))
                        else:
                            cur_metrics_port = default_metrics_port.replace(
                                '"value":""',
                                '"value": "{}"'.format(metrics_port))
503 504 505 506 507
                        if metrics_port:
                            content = content.replace(default_metrics_port,
                                                      cur_metrics_port)
                        model_name_match = re.search(
                            '"label":\\s*{}.*?"value":\\s*"".*?}}'.format(
508
                                json.dumps("模型名称", ensure_ascii=True).replace(
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
                                    '\\', '\\\\')), content)
                        if not model_name_match or model_name_match.group(
                                0).count('"label"') >= 2:
                            model_name_match = re.search(
                                '"value":\\s*"".*?"label":\\s*{}.*?}}'.format(
                                    json.dumps("模型名称",
                                               ensure_ascii=True).replace(
                                                   '\\', '\\\\')), content)
                            if not model_name_match:
                                model_name_match = re.search(
                                    '"label":\\s*{}.*?"value":\\s*"".*?}}'.
                                    format(
                                        json.dumps("模型名称",
                                                   ensure_ascii=False).replace(
                                                       '\\', '\\\\')), content)
                                if not model_name_match or model_name_match.group(
                                        0).count('"label"') >= 2:
                                    model_name_match = re.search(
                                        '"value":\\s*"".*?"label":\\s*{}.*?}}'.
                                        format(
                                            json.dumps(
                                                "模型名称",
                                                ensure_ascii=False).replace(
                                                    '\\', '\\\\')), content)
                        default_model_name = model_name_match.group(0)
C
chenjian 已提交
534 535 536 537 538 539 540 541
                        if '"value": ""' in default_model_name:
                            cur_model_name = default_model_name.replace(
                                '"value": ""',
                                '"value": "{}"'.format(model_name))
                        else:
                            cur_model_name = default_model_name.replace(
                                '"value":""',
                                '"value": "{}"'.format(model_name))
542 543 544 545 546
                        if model_name:
                            content = content.replace(default_model_name,
                                                      cur_model_name)
                        model_version_match = re.search(
                            '"label":\\s*{}.*?"value":\\s*"".*?}}'.format(
547
                                json.dumps("模型版本", ensure_ascii=True).replace(
548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573
                                    '\\', '\\\\')), content)
                        if not model_version_match or model_version_match.group(
                                0).count('"label"') >= 2:
                            model_version_match = re.search(
                                '"value":\\s*"".*?"label":\\s*{}.*?}}'.format(
                                    json.dumps("模型版本",
                                               ensure_ascii=True).replace(
                                                   '\\', '\\\\')), content)
                            if not model_version_match:
                                model_version_match = re.search(
                                    '"label":\\s*{}.*?"value":\\s*"".*?}}'.
                                    format(
                                        json.dumps("模型版本",
                                                   ensure_ascii=False).replace(
                                                       '\\', '\\\\')), content)
                                if not model_version_match or model_version_match.group(
                                        0).count('"label"') >= 2:
                                    model_version_match = re.search(
                                        '"value":\\s*"".*?"label":\\s*{}.*?}}'.
                                        format(
                                            json.dumps(
                                                "模型版本",
                                                ensure_ascii=False).replace(
                                                    '\\', '\\\\')), content)

                        default_model_version = model_version_match.group(0)
C
chenjian 已提交
574 575 576 577 578 579
                        if '"value": ""' in default_model_version:
                            cur_model_version = default_model_version.replace(
                                '"value": ""', '"value": "{}"'.format('1'))
                        else:
                            cur_model_version = default_model_version.replace(
                                '"value":""', '"value": "{}"'.format('1'))
580 581
                        content = content.replace(default_model_version,
                                                  cur_model_version)
582 583 584 585 586 587 588 589 590 591
                except Exception:
                    pass
                finally:
                    content = content.encode()
        else:
            content = resp.content
        headers = [(name, value) for (name, value) in resp.raw.headers.items()]
        response = Response(content, resp.status_code, headers)
        return response

592 593 594 595 596 597 598 599 600 601
    @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 已提交
602 603 604 605
    @app.route(check_live_path)
    def check_live():
        return '', 204

606 607 608
    return app


P
Peter Pan 已提交
609 610 611 612 613
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 已提交
614 615
            info('Running VisualDL at http://%s:%s/ (Press CTRL+C to quit)',
                 args.host, args.port)
P
Peter Pan 已提交
616 617

            if args.host == 'localhost':
C
chenjian 已提交
618 619 620
                info(
                    'Serving VisualDL on localhost; to expose to the network, use a proxy or pass --host 0.0.0.0'
                )
P
Peter Pan 已提交
621 622

            if args.api_only:
C
chenjian 已提交
623 624
                info('Running in API mode, only %s/* will be served.',
                     args.public_path + '/api')
P
Peter Pan 已提交
625 626 627 628 629 630 631 632 633 634

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


642
def run(logdir=None, **options):
C
chenjian 已提交
643
    args = {'logdir': logdir}
P
Peter Pan 已提交
644
    args.update(options)
C
chenjian 已提交
645
    p = multiprocessing.Process(target=_run, args=(args, ))
646 647 648 649 650 651
    p.start()
    return p.pid


def main():
    args = parse_args()
走神的阿圆's avatar
走神的阿圆 已提交
652 653 654 655 656
    if args.get('dest') == 'service':
        if args.get('behavior') == 'upload':
            upload_to_dev(args.get('logdir'), args.get('model'))
    else:
        _run(args)
657 658


P
Peter Pan 已提交
659
if __name__ == '__main__':
P
Peter Pan 已提交
660
    main()