api.py 10.8 KB
Newer Older
P
Peter Pan 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
#!/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 functools
import json
import os

走神的阿圆's avatar
走神的阿圆 已提交
22
from visualdl import LogReader
P
Peter Pan 已提交
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
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


def gen_result(data=None, status=0, msg=''):
    return {
        'status': status,
        'msg': msg,
        'data': data
    }


40
def result(mimetype='application/json', headers=None):
P
Peter Pan 已提交
41 42
    def decorator(func):
        @functools.wraps(func)
43 44
        def wrapper(self, *args, **kwargs):
            data = func(self, *args, **kwargs)
P
Peter Pan 已提交
45 46
            if mimetype == 'application/json':
                data = json.dumps(gen_result(data))
47 48 49 50 51
            if callable(headers):
                headers_output = headers(self)
            else:
                headers_output = headers
            return data, mimetype, headers_output
P
Peter Pan 已提交
52 53 54 55 56 57 58 59 60 61 62 63
        return wrapper
    return decorator


def try_call(function, *args, **kwargs):
    res = lib.retry(error_retry_times, function, error_sleep_time, *args, **kwargs)
    if not res:
        logger.error("Internal server error. Retry later.")
    return res


class Api(object):
64
    def __init__(self, logdir, model, cache_timeout):
P
Peter Pan 已提交
65
        self._reader = LogReader(logdir)
走神的阿圆's avatar
走神的阿圆 已提交
66 67
        if model:
            self._reader.model = model
68 69 70
            self.model_name = os.path.basename(model)
        else:
            self.model_name = ''
P
Peter Pan 已提交
71 72 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

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

    def _get(self, key, func, *args, **kwargs):
        return self._cache(key, func, self._reader, *args, **kwargs)

    def _get_with_retry(self, key, func, *args, **kwargs):
        return self._cache(key, try_call, func, self._reader, *args, **kwargs)

    @result()
    def components(self):
        return self._get('data/components', lib.get_components)

    @result()
    def runs(self):
        return self._get('data/runs', lib.get_runs)

    @result()
    def tags(self):
        return self._get('data/tags', lib.get_tags)

    @result()
    def logs(self):
        return self._get('data/logs', lib.get_logs)

    @result()
P
Peter Pan 已提交
99
    def scalar_tags(self):
P
Peter Pan 已提交
100 101 102
        return self._get_with_retry('data/plugin/scalars/tags', lib.get_scalar_tags)

    @result()
P
Peter Pan 已提交
103
    def image_tags(self):
P
Peter Pan 已提交
104 105
        return self._get_with_retry('data/plugin/images/tags', lib.get_image_tags)

走神的阿圆's avatar
走神的阿圆 已提交
106 107 108 109
    @result()
    def text_tags(self):
        return self._get_with_retry('data/plugin/text/tags', lib.get_text_tags)

P
Peter Pan 已提交
110 111 112 113 114
    @result()
    def audio_tags(self):
        return self._get_with_retry('data/plugin/audio/tags', lib.get_audio_tags)

    @result()
P
Peter Pan 已提交
115
    def embedding_tags(self):
P
Peter Pan 已提交
116 117
        return self._get_with_retry('data/plugin/embeddings/tags', lib.get_embeddings_tags)

走神的阿圆's avatar
走神的阿圆 已提交
118 119 120
    @result()
    def pr_curve_tags(self):
        return self._get_with_retry('data/plugin/pr_curves/tags', lib.get_pr_curve_tags)
P
Peter Pan 已提交
121

P
Peter Pan 已提交
122 123 124
    @result()
    def roc_curve_tags(self):
        return self._get_with_retry('data/plugin/roc_curves/tags', lib.get_roc_curve_tags)
走神的阿圆's avatar
走神的阿圆 已提交
125

走神的阿圆's avatar
走神的阿圆 已提交
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
    @result()
    def hparam_importance(self):
        return self._get_with_retry('data/plugin/hparams/importance', lib.get_hparam_importance)

    @result()
    def hparam_indicator(self):
        return self._get_with_retry('data/plugin/hparams/indicators', lib.get_hparam_indicator)

    @result()
    def hparam_list(self):
        return self._get_with_retry('data/plugin/hparams/list', lib.get_hparam_list)

    @result()
    def hparam_metric(self, run, metric):
        key = os.path.join('data/plugin/hparams/metric', run, metric)
        return self._get_with_retry(key, lib.get_hparam_metric, run, metric)

    @result('text/csv')
    def hparam_data(self, type='tsv'):
        key = os.path.join('data/plugin/hparams/data', type)
        return self._get_with_retry(key, lib.get_hparam_data, type)

P
Peter Pan 已提交
148
    @result()
P
Peter Pan 已提交
149
    def scalar_list(self, run, tag):
P
Peter Pan 已提交
150 151 152
        key = os.path.join('data/plugin/scalars/scalars', run, tag)
        return self._get_with_retry(key, lib.get_scalar, run, tag)

走神的阿圆's avatar
走神的阿圆 已提交
153 154 155 156
    @result('text/csv')
    def scalar_data(self, run, tag, type='tsv'):
        key = os.path.join('data/plugin/scalars/data', run, tag, type)
        return self._get_with_retry(key, lib.get_scalar_data, run, tag, type)
走神的阿圆's avatar
走神的阿圆 已提交
157

P
Peter Pan 已提交
158
    @result()
P
Peter Pan 已提交
159
    def image_list(self, mode, tag):
P
Peter Pan 已提交
160 161 162 163
        key = os.path.join('data/plugin/images/images', mode, tag)
        return self._get_with_retry(key, lib.get_image_tag_steps, mode, tag)

    @result('image/png')
P
Peter Pan 已提交
164
    def image_image(self, mode, tag, index=0):
P
Peter Pan 已提交
165 166 167 168
        index = int(index)
        key = os.path.join('data/plugin/images/individualImage', mode, tag, str(index))
        return self._get_with_retry(key, lib.get_individual_image, mode, tag, index)

走神的阿圆's avatar
走神的阿圆 已提交
169 170 171 172 173 174 175 176 177 178 179
    @result()
    def text_list(self, mode, tag):
        key = os.path.join('data/plugin/text/text', mode, tag)
        return self._get_with_retry(key, lib.get_text_tag_steps, mode, tag)

    @result('text/plain')
    def text_text(self, mode, tag, index=0):
        index = int(index)
        key = os.path.join('data/plugin/text/individualText', mode, tag, str(index))
        return self._get_with_retry(key, lib.get_individual_text, mode, tag, index)

P
Peter Pan 已提交
180 181 182 183 184
    @result()
    def audio_list(self, run, tag):
        key = os.path.join('data/plugin/audio/audio', run, tag)
        return self._get_with_retry(key, lib.get_audio_tag_steps, run, tag)

P
Peter Pan 已提交
185
    @result('audio/wav')
P
Peter Pan 已提交
186 187 188 189 190 191
    def audio_audio(self, run, tag, index=0):
        index = int(index)
        key = os.path.join('data/plugin/audio/individualAudio', run, tag, str(index))
        return self._get_with_retry(key, lib.get_individual_audio, run, tag, index)

    @result()
P
Peter Pan 已提交
192
    def embedding_embedding(self, run, tag='default', reduction='pca', dimension=2):
P
Peter Pan 已提交
193 194 195 196
        dimension = int(dimension)
        key = os.path.join('data/plugin/embeddings/embeddings', run, str(dimension), reduction)
        return self._get_with_retry(key, lib.get_embeddings, run, tag, reduction, dimension)

走神的阿圆's avatar
走神的阿圆 已提交
197 198 199 200 201 202 203 204 205 206 207 208 209 210
    @result()
    def embedding_list(self):
        return self._get_with_retry('data/plugin/embeddings/list', lib.get_embeddings_list)

    @result('text/tab-separated-values')
    def embedding_metadata(self, name):
        key = os.path.join('data/plugin/embeddings/metadata', name)
        return self._get_with_retry(key, lib.get_embedding_labels, name)

    @result('application/octet-stream')
    def embedding_tensor(self, name):
        key = os.path.join('data/plugin/embeddings/tensor', name)
        return self._get_with_retry(key, lib.get_embedding_tensors, name)

211 212 213 214 215
    @result()
    def histogram_tags(self):
        return self._get_with_retry('data/plugin/histogram/tags', lib.get_histogram_tags)

    @result()
P
Peter Pan 已提交
216 217 218
    def histogram_list(self, run, tag):
        key = os.path.join('data/plugin/histogram/histogram', run, tag)
        return self._get_with_retry(key, lib.get_histogram, run, tag)
219

走神的阿圆's avatar
走神的阿圆 已提交
220 221 222 223
    @result()
    def pr_curves_pr_curve(self, run, tag):
        key = os.path.join('data/plugin/pr_curves/pr_curve', run, tag)
        return self._get_with_retry(key, lib.get_pr_curve, run, tag)
P
Peter Pan 已提交
224

P
Peter Pan 已提交
225 226 227 228
    @result()
    def roc_curves_roc_curve(self, run, tag):
        key = os.path.join('data/plugin/roc_curves/roc_curve', run, tag)
        return self._get_with_retry(key, lib.get_roc_curve, run, tag)
P
Peter Pan 已提交
229

走神的阿圆's avatar
走神的阿圆 已提交
230 231 232 233
    @result()
    def pr_curves_steps(self, run):
        key = os.path.join('data/plugin/pr_curves/steps', run)
        return self._get_with_retry(key, lib.get_pr_curve_step, run)
P
Peter Pan 已提交
234

P
Peter Pan 已提交
235 236 237 238
    @result()
    def roc_curves_steps(self, run):
        key = os.path.join('data/plugin/roc_curves/steps', run)
        return self._get_with_retry(key, lib.get_roc_curve_step, run)
走神的阿圆's avatar
走神的阿圆 已提交
239

P
Peter Pan 已提交
240 241 242 243
    @result(
        'application/octet-stream',
        lambda s: {"Content-Disposition": 'attachment; filename="%s"' % s.model_name} if len(s.model_name) else None
    )
P
Peter Pan 已提交
244
    def graph_graph(self):
245 246
        key = os.path.join('data/plugin/graphs/graph')
        return self._get_with_retry(key, lib.get_graph)
P
Peter Pan 已提交
247

248 249 250

def create_api_call(logdir, model, cache_timeout):
    api = Api(logdir, model, cache_timeout)
P
Peter Pan 已提交
251 252 253 254 255
    routes = {
        'components': (api.components, []),
        'runs': (api.runs, []),
        'tags': (api.tags, []),
        'logs': (api.logs, []),
P
Peter Pan 已提交
256 257
        'scalar/tags': (api.scalar_tags, []),
        'image/tags': (api.image_tags, []),
走神的阿圆's avatar
走神的阿圆 已提交
258
        'text/tags': (api.text_tags, []),
P
Peter Pan 已提交
259
        'audio/tags': (api.audio_tags, []),
P
Peter Pan 已提交
260
        'embedding/tags': (api.embedding_tags, []),
261
        'histogram/tags': (api.histogram_tags, []),
走神的阿圆's avatar
走神的阿圆 已提交
262
        'pr-curve/tags': (api.pr_curve_tags, []),
P
Peter Pan 已提交
263
        'roc-curve/tags': (api.roc_curve_tags, []),
P
Peter Pan 已提交
264
        'scalar/list': (api.scalar_list, ['run', 'tag']),
走神的阿圆's avatar
走神的阿圆 已提交
265
        'scalar/data': (api.scalar_data, ['run', 'tag', 'type']),
P
Peter Pan 已提交
266 267
        'image/list': (api.image_list, ['run', 'tag']),
        'image/image': (api.image_image, ['run', 'tag', 'index']),
走神的阿圆's avatar
走神的阿圆 已提交
268 269
        'text/list': (api.text_list, ['run', 'tag']),
        'text/text': (api.text_text, ['run', 'tag', 'index']),
P
Peter Pan 已提交
270 271
        'audio/list': (api.audio_list, ['run', 'tag']),
        'audio/audio': (api.audio_audio, ['run', 'tag', 'index']),
P
Peter Pan 已提交
272
        'embedding/embedding': (api.embedding_embedding, ['run', 'tag', 'reduction', 'dimension']),
走神的阿圆's avatar
走神的阿圆 已提交
273 274 275
        'embedding/list': (api.embedding_list, []),
        'embedding/tensor': (api.embedding_tensor, ['name']),
        'embedding/metadata': (api.embedding_metadata, ['name']),
P
Peter Pan 已提交
276
        'histogram/list': (api.histogram_list, ['run', 'tag']),
P
Peter Pan 已提交
277
        'graph/graph': (api.graph_graph, []),
走神的阿圆's avatar
走神的阿圆 已提交
278
        'pr-curve/list': (api.pr_curves_pr_curve, ['run', 'tag']),
P
Peter Pan 已提交
279 280
        'roc-curve/list': (api.roc_curves_roc_curve, ['run', 'tag']),
        'pr-curve/steps': (api.pr_curves_steps, ['run']),
走神的阿圆's avatar
走神的阿圆 已提交
281 282 283 284 285 286
        'roc-curve/steps': (api.roc_curves_steps, ['run']),
        'hparams/importance': (api.hparam_importance, []),
        'hparams/data': (api.hparam_data, ['type']),
        'hparams/indicators': (api.hparam_indicator, []),
        'hparams/list': (api.hparam_list, []),
        'hparams/metric': (api.hparam_metric, ['run', 'metric'])
P
Peter Pan 已提交
287 288 289 290 291
    }

    def call(path: str, args):
        route = routes.get(path)
        if not route:
P
Peter Pan 已提交
292
            return json.dumps(gen_result(status=1, msg='api not found')), 'application/json', None
P
Peter Pan 已提交
293 294 295 296 297
        method, call_arg_names = route
        call_args = [args.get(name) for name in call_arg_names]
        return method(*call_args)

    return call