lib.py 11.3 KB
Newer Older
J
Jeff Wang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
# 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.
# =======================================================================

O
Oraoto 已提交
16
from __future__ import absolute_import
S
superjom 已提交
17
import re
Y
Yan Chunwei 已提交
18
import sys
19
import time
S
superjom 已提交
20 21 22
from tempfile import NamedTemporaryFile
import numpy as np
from PIL import Image
O
Oraoto 已提交
23
from .log import logger
24
import wave
25

O
Oraoto 已提交
26 27 28 29
try:
    from urllib.parse import urlencode
except Exception:
    from urllib import urlencode
S
superjom 已提交
30

S
superjom 已提交
31

S
superjom 已提交
32 33 34 35
def get_modes(storage):
    return storage.modes()


36
def get_tags(storage, component):
S
superjom 已提交
37 38
    result = {}
    for mode in storage.modes():
S
superjom 已提交
39
        with storage.mode(mode) as reader:
40
            tags = reader.tags(component)
S
superjom 已提交
41
            if tags:
P
Peter Pan 已提交
42
                result[mode] = tags
S
superjom 已提交
43 44 45
    return result


46 47 48 49
def get_scalar_tags(storage):
    return get_tags(storage, 'scalar')


50
def get_scalar(storage, mode, tag, num_records=300):
D
daminglu 已提交
51 52
    assert num_records > 1

S
superjom 已提交
53 54
    with storage.mode(mode) as reader:
        scalar = reader.scalar(tag)
S
superjom 已提交
55

S
superjom 已提交
56 57 58
        records = scalar.records()
        ids = scalar.ids()
        timestamps = scalar.timestamps()
S
superjom 已提交
59

O
Oraoto 已提交
60
        data = list(zip(timestamps, ids, records))
D
daminglu 已提交
61 62 63
        data_size = len(data)

        if data_size <= num_records:
S
superjom 已提交
64
            return data
S
superjom 已提交
65

D
daminglu 已提交
66 67 68 69 70 71 72 73 74 75 76 77
        span = float(data_size) / (num_records - 1)
        span_offset = 0

        data_idx = int(span_offset * span)
        sampled_data = []

        while data_idx < data_size:
            sampled_data.append(data[data_size - data_idx - 1])
            span_offset += 1
            data_idx = int(span_offset * span)

        sampled_data.append(data[0])
Y
Yan Chunwei 已提交
78 79 80 81 82
        res = sampled_data[::-1]
        # TODO(Superjomn) some bug here, sometimes there are zero here.
        if res[-1] == 0.:
            res = res[:-1]
        return res
S
superjom 已提交
83 84


S
superjom 已提交
85
def get_image_tags(storage):
S
superjom 已提交
86 87 88
    result = {}

    for mode in storage.modes():
S
superjom 已提交
89 90 91
        with storage.mode(mode) as reader:
            tags = reader.tags('image')
            if tags:
P
Peter Pan 已提交
92
                result[mode] = []
S
superjom 已提交
93 94
                for tag in tags:
                    image = reader.image(tag)
O
Oraoto 已提交
95
                    for i in range(max(1, image.num_samples())):
96 97
                        caption = tag if image.num_samples(
                        ) <= 1 else '%s/%d' % (tag, i)
P
Peter Pan 已提交
98
                        result[mode].append(caption)
S
superjom 已提交
99 100 101 102 103 104
    return result


def get_image_tag_steps(storage, mode, tag):
    # remove suffix '/x'
    res = re.search(r".*/([0-9]+$)", tag)
S
superjom 已提交
105
    sample_index = 0
S
superjom 已提交
106
    origin_tag = tag
S
superjom 已提交
107 108
    if res:
        tag = tag[:tag.rfind('/')]
S
superjom 已提交
109
        sample_index = int(res.groups()[0])
S
superjom 已提交
110

S
superjom 已提交
111 112 113
    with storage.mode(mode) as reader:
        image = reader.image(tag)
        res = []
S
superjom 已提交
114

S
superjom 已提交
115 116
    for step_index in range(image.num_records()):
        record = image.record(step_index, sample_index)
S
superjom 已提交
117
        shape = record.shape()
S
superjom 已提交
118
        # TODO(ChunweiYan) remove this trick, some shape will be empty
T
Thuan Nguyen 已提交
119 120
        if not shape:
            continue
121
        try:
O
Oraoto 已提交
122
            query = urlencode({
123 124 125 126 127 128 129 130 131 132 133 134
                'sample': 0,
                'index': step_index,
                'tag': origin_tag,
                'run': mode,
            })
            res.append({
                'height': shape[0],
                'width': shape[1],
                'step': record.step_id(),
                'wall_time': image.timestamp(step_index),
                'query': query,
            })
T
Thuan Nguyen 已提交
135
        except Exception:
136 137
            logger.error("image sample out of range")

S
superjom 已提交
138 139 140
    return res


S
superjom 已提交
141
def get_invididual_image(storage, mode, tag, step_index, max_size=80):
S
superjom 已提交
142 143 144
    with storage.mode(mode) as reader:
        res = re.search(r".*/([0-9]+$)", tag)
        # remove suffix '/x'
Y
Yan Chunwei 已提交
145
        offset = 0
S
superjom 已提交
146 147 148 149 150 151 152
        if res:
            offset = int(res.groups()[0])
            tag = tag[:tag.rfind('/')]

        image = reader.image(tag)
        record = image.record(step_index, offset)

S
superjom 已提交
153 154
        shape = record.shape()

Q
Qiao Longfei 已提交
155
        if shape[2] == 1:
156
            shape = [shape[0], shape[1]]
Q
Qiao Longfei 已提交
157
        data = np.array(record.data(), dtype='uint8').reshape(shape)
S
superjom 已提交
158 159 160 161 162
        tempfile = NamedTemporaryFile(mode='w+b', suffix='.png')
        with Image.fromarray(data) as im:
            im.save(tempfile)
        tempfile.seek(0, 0)
        return tempfile
S
superjom 已提交
163 164


165 166 167 168 169 170 171 172 173 174 175 176 177
def get_audio_tags(storage):
    result = {}

    for mode in storage.modes():
        with storage.mode(mode) as reader:
            tags = reader.tags('audio')
            if tags:
                result[mode] = {}
                for tag in tags:
                    audio = reader.audio(tag)
                    for i in range(max(1, audio.num_samples())):
                        caption = tag if audio.num_samples(
                        ) <= 1 else '%s/%d' % (tag, i)
P
Peter Pan 已提交
178
                        result[mode].append(caption)
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226

    return result


def get_audio_tag_steps(storage, mode, tag):
    # remove suffix '/x'
    res = re.search(r".*/([0-9]+$)", tag)
    sample_index = 0
    origin_tag = tag
    if res:
        tag = tag[:tag.rfind('/')]
        sample_index = int(res.groups()[0])

    with storage.mode(mode) as reader:
        audio = reader.audio(tag)
        res = []

    for step_index in range(audio.num_records()):
        record = audio.record(step_index, sample_index)

        query = urlencode({
            'sample': 0,
            'index': step_index,
            'tag': origin_tag,
            'run': mode,
        })
        res.append({
            'step': record.step_id(),
            'wall_time': audio.timestamp(step_index),
            'query': query,
        })

    return res


def get_individual_audio(storage, mode, tag, step_index, max_size=80):

    with storage.mode(mode) as reader:
        res = re.search(r".*/([0-9]+$)", tag)
        # remove suffix '/x'
        offset = 0
        if res:
            offset = int(res.groups()[0])
            tag = tag[:tag.rfind('/')]

        audio = reader.audio(tag)
        record = audio.record(step_index, offset)

227 228 229 230
        shape = record.shape()
        sample_rate = shape[0]
        sample_width = shape[1]
        num_channels = shape[2]
231

232
        # sending a temp file to front end
233 234
        tempfile = NamedTemporaryFile(mode='w+b', suffix='.wav')

235
        # write audio file to that tempfile
236
        wavfile = wave.open(tempfile, 'wb')
237 238 239 240 241 242 243

        wavfile.setframerate(sample_rate)
        wavfile.setnchannels(num_channels)
        wavfile.setsampwidth(sample_width)

        # convert to binary string to write to wav file
        data = np.array(record.data(), dtype='uint8')
244 245
        wavfile.writeframes(data.tostring())

246
        # make sure the marker is at the start of file
247 248 249 250 251
        tempfile.seek(0, 0)

        return tempfile


252 253 254 255
def get_histogram_tags(storage):
    return get_tags(storage, 'histogram')


256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
def get_texts_tags(storage):
    return get_tags(storage, 'text')


def get_texts(storage, mode, tag, num_records=100):
    with storage.mode(mode) as reader:
        texts = reader.text(tag)

        records = texts.records()
        ids = texts.ids()
        timestamps = texts.timestamps()

        data = list(zip(timestamps, ids, records))
        data_size = len(data)

        if data_size <= num_records:
            return data

        span = float(data_size) / (num_records - 1)
        span_offset = 0

        data_idx = int(span_offset * span)
        sampled_data = []

        while data_idx < data_size:
            sampled_data.append(data[data_size - data_idx - 1])
            span_offset += 1
            data_idx = int(span_offset * span)

        sampled_data.append(data[0])
        res = sampled_data[::-1]
        # TODO(Superjomn) some bug here, sometimes there are zero here.
        if res[-1] == 0.:
            res = res[:-1]
        return res


J
Jeff Wang 已提交
293
def get_embeddings(storage, mode, reduction, dimension=2, num_records=5000):
294
    with storage.mode(mode) as reader:
J
Jeff Wang 已提交
295
        embedding = reader.embedding()
296
        labels = embedding.get_all_labels()
J
Jeff Wang 已提交
297
        high_dimensional_vectors = np.array(embedding.get_all_embeddings())
298 299

        if reduction == 'tsne':
300
            import visualdl.server.tsne as tsne
J
Jeff Wang 已提交
301 302 303 304 305
            low_dim_embs = tsne.tsne(
                high_dimensional_vectors,
                dimension,
                initial_dims=50,
                perplexity=30.0)
306 307

        elif reduction == 'pca':
J
Jeff Wang 已提交
308
            low_dim_embs = simple_pca(high_dimensional_vectors, dimension)
309 310 311 312

        return {"embedding": low_dim_embs.tolist(), "labels": labels}


313
def get_histogram(storage, mode, tag):
314 315 316 317
    with storage.mode(mode) as reader:
        histogram = reader.histogram(tag)
        res = []

O
Oraoto 已提交
318
        for i in range(histogram.num_records()):
319 320 321
            try:
                # some bug with protobuf, some times may overflow
                record = histogram.record(i)
T
Thuan Nguyen 已提交
322
            except Exception:
323 324 325 326 327 328 329 330 331
                continue

            res.append([])
            py_record = res[-1]
            py_record.append(record.timestamp())
            py_record.append(record.step())
            py_record.append([])

            data = py_record[-1]
O
Oraoto 已提交
332
            for j in range(record.num_instances()):
333 334
                instance = record.instance(j)
                data.append(
T
Thuan Nguyen 已提交
335
                    [instance.left(), instance.right(), instance.frequency()])
336 337 338

        # num_samples: We will only return 100 samples.
        num_samples = 100
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354
        if len(res) < num_samples:
            return res

        # sample some steps
        span = float(len(res)) / (num_samples - 1)
        span_offset = 0
        data_idx = 0

        sampled_data = []
        data_size = len(res)
        while data_idx < data_size:
            sampled_data.append(res[data_size - data_idx - 1])
            span_offset += 1
            data_idx = int(span_offset * span)
        sampled_data.append(res[0])
        return sampled_data[::-1]
355 356


357 358 359 360 361
def retry(ntimes, function, time2sleep, *args, **kwargs):
    '''
    try to execute `function` `ntimes`, if exception catched, the thread will
    sleep `time2sleep` seconds.
    '''
O
Oraoto 已提交
362
    for i in range(ntimes):
363 364
        try:
            return function(*args, **kwargs)
T
Thuan Nguyen 已提交
365
        except Exception:
Y
Yan Chunwei 已提交
366 367
            error_info = '\n'.join(map(str, sys.exc_info()))
            logger.error("Unexpected error: %s" % error_info)
368
            time.sleep(time2sleep)
369

T
Thuan Nguyen 已提交
370

371 372 373 374 375 376 377 378 379
def cache_get(cache):
    def _handler(key, func, *args, **kwargs):
        data = cache.get(key)
        if data is None:
            logger.warning('update cache %s' % key)
            data = func(*args, **kwargs)
            cache.set(key, data)
            return data
        return data
T
Thuan Nguyen 已提交
380

381
    return _handler
J
Jeff Wang 已提交
382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404


def simple_pca(x, dimension):
    """
    A simple PCA implementation to do the dimension reduction.
    """

    # Center the data.
    x -= np.mean(x, axis=0)

    # Computing the Covariance Matrix
    cov = np.cov(x, rowvar=False)

    # Get eigenvectors and eigenvalues from the covariance matrix
    eigvals, eigvecs = np.linalg.eig(cov)

    # Sort the eigvals from high to low
    order = np.argsort(eigvals)[::-1]

    # Drop the eigenvectors with low eigenvalues
    eigvecs = eigvecs[:, order[:dimension]]

    return np.dot(x, eigvecs)