cache.py 6.52 KB
Newer Older
André Anjos's avatar
André Anjos committed
1
2
#!/usr/bin/env python
# vim: set fileencoding=utf-8 :
André Anjos's avatar
André Anjos committed
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
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

###############################################################################
#                                                                             #
# Copyright (c) 2016 Idiap Research Institute, http://www.idiap.ch/           #
# Contact: beat.support@idiap.ch                                              #
#                                                                             #
# This file is part of the beat.cmdline module of the BEAT platform.          #
#                                                                             #
# Commercial License Usage                                                    #
# Licensees holding valid commercial BEAT licenses may use this file in       #
# accordance with the terms contained in a written agreement between you      #
# and Idiap. For further information contact tto@idiap.ch                     #
#                                                                             #
# Alternatively, this file may be used under the terms of the GNU Affero      #
# Public License version 3 as published by the Free Software and appearing    #
# in the file LICENSE.AGPL included in the packaging of this file.            #
# The BEAT platform is distributed in the hope that it will be useful, but    #
# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY  #
# or FITNESS FOR A PARTICULAR PURPOSE.                                        #
#                                                                             #
# You should have received a copy of the GNU Affero Public License along      #
# with the BEAT platform. If not, see http://www.gnu.org/licenses/.           #
#                                                                             #
###############################################################################


"""Configuration manipulation and display

Usage:
  %(prog)s cache clear
  %(prog)s cache info [--start=<index>] [--end=<index>] [--sizes] [<path>]...
  %(prog)s cache view [--start=<index>] [--end=<index>] [<path>]...
  %(prog)s cache --help


Commands:
  clear  Deletes all available cache
  info   Displays information about a particular cache file
  view   Displays the contents of a particular cache file


Options:
  -s, --sizes  If set, also print the size in bytes for objects in a file. This
               triggers the full file readout
  --start=<i>  If set, allows the user to print only a few bits of the file
  --end=<i>    If set, allows the user to print only a few bits of the file
  -h, --help   Display this screen


Examples:

  To clear all available cache:

    $ %(prog)s cache clear

  To collect information about a particular cache file:

    $ %(prog)s cache info 7f/d8/8d/a11178ac27075feaba8131fe878d6e3...

  To view a particular cache file:

    $ %(prog)s cache view 7f/d8/8d/a11178ac27075feaba8131fe878d6e3...
"""

import os
import fnmatch
import logging
logger = logging.getLogger()

import simplejson

from . import common
from beat.core.data import CachedDataSource, load_data_index
from beat.core.utils import NumpyJSONEncoder

def get_paths(config):

  func = lambda z: z.split('.', 1)[0]

  retval = []

  for dirname, dirs, files in os.walk(config.cache):
    files = fnmatch.filter(files, '*.data') #avoid index-only files
    if not files: continue
    d = dirname.replace(config.cache, '').strip(os.sep)
    retval += list(set([os.path.join(d, func(k)) for k in files]))

  return retval


def info(config, paths, sizes, index_start, index_end):

  if not paths:
    paths = get_paths(config)

  for path in paths:

    logger.info('path: %s', path)
    fullpath = os.path.join(config.cache, path + '.data')

    f = CachedDataSource()
    status = f.setup(fullpath, config.path, index_start, index_end)
    if not status:
      logger.error("cannot setup data source with `%s' and prefix `%s'",
              fullpath, config.path)
      return 1

    logger.info('  dataformat: %s', f.dataformat.name)

    if sizes:
      counter = 0
      logger.info('  index:')

      while f.hasMoreData():
        try:
          data, start, end = f.next()
        except Exception as e:
          logger.error("Failed to retrieve the next data: %s", e)
          return 1

        size = len(data.pack())
        counter += size
        if start == end:
          logger.info('  [%d] - %d bytes', start, size)
        else:
          logger.info('  [%d:%d] - %d bytes', start, end, size)
      logger.info('  total (stripped-down) size: %d bytes', counter)

    else:
      index = load_data_index(config.cache, path + '.data')
      logger.info('  objects   : %d', len(index)-1)

  return 0


def view(config, paths, index_start, index_end):

  if not paths:
    paths = get_paths(config)

  for path in paths:

    logger.info('path: %s', path)
    fullpath = os.path.join(config.cache, path + '.data')

    f = CachedDataSource()
    status = f.setup(fullpath, config.path, index_start, index_end)
    if not status:
      logger.error("cannot setup data source with `%s' and prefix `%s'",
              fullpath, config.path)
      return 1

    logger.info('  dataformat: %s', f.dataformat.name)

    while f.hasMoreData():

      try:
        data, start, end = f.next()
      except Exception as e:
        logger.error("Failed to retrieve the next data: %s", e)
        return 1

      logger.extra(80 * '-')

      if start == end:
        header = '[%d]: ' % start
      else:
        header = '[%d:%d]: ' % (start, end)

      json_data = data.as_dict()
      for name, value in json_data.items():
        json_data[name] = common.stringify(value)
      json_data = simplejson.dumps(json_data, indent=2,
              cls=NumpyJSONEncoder).\
              replace('"BEAT_LIST_DELIMITER[', '[')\
              .replace(']BEAT_LIST_DELIMITER"', ']')\
              .replace('"...",', '...')\
              .replace('"BEAT_LIST_SIZE(', '(')\
              .replace(')BEAT_LIST_SIZE"', ')')
      logger.info(header + json_data)

  return 0


def process(args):

  start = int(args['--start']) if args['--start'] is not None else None
  end = int(args['--end']) if args['--end'] is not None else None

  if args['clear']:
    import shutil
    for k in os.listdir(args['config'].cache):
      p = os.path.join(args['config'].cache, k)
      shutil.rmtree(p)
    return 0

  elif args['info']:
    return info(args['config'], args['<path>'], args['--sizes'], start, end)

  elif args['view']:
    return view(args['config'], args['<path>'], start, end)

  # Should not happen
  logger.error("unrecognized `cache' subcommand")
  return 1