lib.py 11.6 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 92 93 94
        with storage.mode(mode) as reader:
            tags = reader.tags('image')
            if tags:
                result[mode] = {}
                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)
S
superjom 已提交
98 99 100 101 102
                        result[mode][caption] = {
                            'displayName': caption,
                            'description': "",
                            'samples': 1,
                        }
S
superjom 已提交
103 104 105 106 107 108
    return result


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

S
superjom 已提交
115 116 117
    with storage.mode(mode) as reader:
        image = reader.image(tag)
        res = []
S
superjom 已提交
118

S
superjom 已提交
119 120
    for step_index in range(image.num_records()):
        record = image.record(step_index, sample_index)
S
superjom 已提交
121
        shape = record.shape()
S
superjom 已提交
122
        # TODO(ChunweiYan) remove this trick, some shape will be empty
T
Thuan Nguyen 已提交
123 124
        if not shape:
            continue
125
        try:
O
Oraoto 已提交
126
            query = urlencode({
127 128 129 130 131 132 133 134 135 136 137 138
                '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 已提交
139
        except Exception:
140 141
            logger.error("image sample out of range")

S
superjom 已提交
142 143 144
    return res


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

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

S
superjom 已提交
157 158
        shape = record.shape()

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


169 170 171 172 173 174 175 176 177 178 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 227 228 229 230 231 232 233 234
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)
                        result[mode][caption] = {
                            'displayName': caption,
                            'description': "",
                            'samples': 1,
                        }

    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)

235 236 237 238
        shape = record.shape()
        sample_rate = shape[0]
        sample_width = shape[1]
        num_channels = shape[2]
239

240
        # sending a temp file to front end
241 242
        tempfile = NamedTemporaryFile(mode='w+b', suffix='.wav')

243
        # write audio file to that tempfile
244
        wavfile = wave.open(tempfile, 'wb')
245 246 247 248 249 250 251

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

254
        # make sure the marker is at the start of file
255 256 257 258 259
        tempfile.seek(0, 0)

        return tempfile


260 261 262 263
def get_histogram_tags(storage):
    return get_tags(storage, 'histogram')


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 293 294 295 296 297 298 299 300
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 已提交
301
def get_embeddings(storage, mode, reduction, dimension=2, num_records=5000):
302
    with storage.mode(mode) as reader:
J
Jeff Wang 已提交
303
        embedding = reader.embedding()
304
        labels = embedding.get_all_labels()
J
Jeff Wang 已提交
305
        high_dimensional_vectors = np.array(embedding.get_all_embeddings())
306 307

        if reduction == 'tsne':
308
            import visualdl.server.tsne as tsne
J
Jeff Wang 已提交
309 310 311 312 313
            low_dim_embs = tsne.tsne(
                high_dimensional_vectors,
                dimension,
                initial_dims=50,
                perplexity=30.0)
314 315

        elif reduction == 'pca':
J
Jeff Wang 已提交
316
            low_dim_embs = simple_pca(high_dimensional_vectors, dimension)
317 318 319 320

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


321
def get_histogram(storage, mode, tag):
322 323 324 325
    with storage.mode(mode) as reader:
        histogram = reader.histogram(tag)
        res = []

O
Oraoto 已提交
326
        for i in range(histogram.num_records()):
327 328 329
            try:
                # some bug with protobuf, some times may overflow
                record = histogram.record(i)
T
Thuan Nguyen 已提交
330
            except Exception:
331 332 333 334 335 336 337 338 339
                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 已提交
340
            for j in range(record.num_instances()):
341 342
                instance = record.instance(j)
                data.append(
T
Thuan Nguyen 已提交
343
                    [instance.left(), instance.right(), instance.frequency()])
344 345 346

        # num_samples: We will only return 100 samples.
        num_samples = 100
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
        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]
363 364


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

T
Thuan Nguyen 已提交
378

379 380 381 382 383 384 385 386 387
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 已提交
388

389
    return _handler
J
Jeff Wang 已提交
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412


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)