lib.py 10.7 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 107
    if res:
        tag = tag[:tag.rfind('/')]
S
superjom 已提交
108
        sample_index = int(res.groups()[0])
S
superjom 已提交
109

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

S
superjom 已提交
114 115
    for step_index in range(image.num_records()):
        record = image.record(step_index, sample_index)
116 117 118
        try:
            res.append({
                'step': record.step_id(),
119
                'wallTime': image.timestamp(step_index),
120
            })
T
Thuan Nguyen 已提交
121
        except Exception:
122 123
            logger.error("image sample out of range")

S
superjom 已提交
124 125 126
    return res


S
superjom 已提交
127
def get_invididual_image(storage, mode, tag, step_index, max_size=80):
S
superjom 已提交
128 129 130
    with storage.mode(mode) as reader:
        res = re.search(r".*/([0-9]+$)", tag)
        # remove suffix '/x'
Y
Yan Chunwei 已提交
131
        offset = 0
S
superjom 已提交
132 133 134 135 136 137 138
        if res:
            offset = int(res.groups()[0])
            tag = tag[:tag.rfind('/')]

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

S
superjom 已提交
139 140
        shape = record.shape()

Q
Qiao Longfei 已提交
141
        if shape[2] == 1:
142
            shape = [shape[0], shape[1]]
Q
Qiao Longfei 已提交
143
        data = np.array(record.data(), dtype='uint8').reshape(shape)
S
superjom 已提交
144 145 146 147 148
        tempfile = NamedTemporaryFile(mode='w+b', suffix='.png')
        with Image.fromarray(data) as im:
            im.save(tempfile)
        tempfile.seek(0, 0)
        return tempfile
S
superjom 已提交
149 150


151 152 153 154 155 156 157 158 159 160 161 162 163
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 已提交
164
                        result[mode].append(caption)
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185

    return result


def get_audio_tag_steps(storage, mode, tag):
    # remove suffix '/x'
    res = re.search(r".*/([0-9]+$)", tag)
    sample_index = 0
    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)

        res.append({
            'step': record.step_id(),
186
            'wallTime': audio.timestamp(step_index),
187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
        })

    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)

205 206 207 208
        shape = record.shape()
        sample_rate = shape[0]
        sample_width = shape[1]
        num_channels = shape[2]
209

210
        # sending a temp file to front end
211 212
        tempfile = NamedTemporaryFile(mode='w+b', suffix='.wav')

213
        # write audio file to that tempfile
214
        wavfile = wave.open(tempfile, 'wb')
215 216 217 218 219 220 221

        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')
222 223
        wavfile.writeframes(data.tostring())

224
        # make sure the marker is at the start of file
225 226 227 228 229
        tempfile.seek(0, 0)

        return tempfile


230 231 232 233
def get_histogram_tags(storage):
    return get_tags(storage, 'histogram')


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 264 265 266 267 268 269 270
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 已提交
271
def get_embeddings(storage, mode, reduction, dimension=2, num_records=5000):
272
    with storage.mode(mode) as reader:
J
Jeff Wang 已提交
273
        embedding = reader.embedding()
274
        labels = embedding.get_all_labels()
J
Jeff Wang 已提交
275
        high_dimensional_vectors = np.array(embedding.get_all_embeddings())
276 277

        if reduction == 'tsne':
278
            import visualdl.server.tsne as tsne
J
Jeff Wang 已提交
279 280 281 282 283
            low_dim_embs = tsne.tsne(
                high_dimensional_vectors,
                dimension,
                initial_dims=50,
                perplexity=30.0)
284 285

        elif reduction == 'pca':
J
Jeff Wang 已提交
286
            low_dim_embs = simple_pca(high_dimensional_vectors, dimension)
287 288 289 290

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


291
def get_histogram(storage, mode, tag):
292 293 294 295
    with storage.mode(mode) as reader:
        histogram = reader.histogram(tag)
        res = []

O
Oraoto 已提交
296
        for i in range(histogram.num_records()):
297 298 299
            try:
                # some bug with protobuf, some times may overflow
                record = histogram.record(i)
T
Thuan Nguyen 已提交
300
            except Exception:
301 302 303 304 305 306 307 308 309
                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 已提交
310
            for j in range(record.num_instances()):
311 312
                instance = record.instance(j)
                data.append(
T
Thuan Nguyen 已提交
313
                    [instance.left(), instance.right(), instance.frequency()])
314 315 316

        # num_samples: We will only return 100 samples.
        num_samples = 100
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
        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]
333 334


335 336 337 338 339
def retry(ntimes, function, time2sleep, *args, **kwargs):
    '''
    try to execute `function` `ntimes`, if exception catched, the thread will
    sleep `time2sleep` seconds.
    '''
O
Oraoto 已提交
340
    for i in range(ntimes):
341 342
        try:
            return function(*args, **kwargs)
T
Thuan Nguyen 已提交
343
        except Exception:
Y
Yan Chunwei 已提交
344 345
            error_info = '\n'.join(map(str, sys.exc_info()))
            logger.error("Unexpected error: %s" % error_info)
346
            time.sleep(time2sleep)
347

T
Thuan Nguyen 已提交
348

349 350 351 352 353 354 355 356 357
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 已提交
358

359
    return _handler
J
Jeff Wang 已提交
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382


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)