def unzip_to_directory_tree(drop_dir, filepath):
  hint_rx = re.compile(r'_((?:un)?hinted)/(.+)')
  plain_rx = re.compile(r'[^/]+')
  zf = zipfile.ZipFile(filepath, 'r')
  print 'extracting files from %s to %s' % (filepath, drop_dir)
  count = 0
  mapped_names = []
  unmapped = []
  for name in zf.namelist():
    # skip names representing portions of the path
    if name.endswith('/'):
      continue
    # get the blob
    try:
      data = zf.read(name)
    except __HOLE__:
      print 'did not find %s in zipfile' % name
      continue

    result = hint_rx.search(name)
    if result:
      # we know where it goes
      subdir = result.group(1)
      filename = result.group(2)
      write_data_to_file(data, drop_dir, subdir, filename)
      count += 1
      continue

    result = plain_rx.match(name)
    if not result:
      print "subdir structure without hint/unhint: '%s'" % name
      continue

    # we have to figure out where it goes.
    # if it's a .ttf file, we look for 'fpgm'
    # and 'prep' and if they are present, we put
    # it into hinted, else unhinted.
    # if it's not a .ttf file, but it starts with
    # the name of a .ttf file (sans suffix), we put
    # it in the same subdir the .ttf file went into.
    # else we put it at drop_dir (no subdir).
    if name.endswith('.ttf'):
      blobfile = cStringIO.StringIO(data)
      font = ttLib.TTFont(blobfile)
      subdir = 'hinted' if font.get('fpgm') or font.get('prep') else 'unhinted'
      write_data_to_file(data, drop_dir, subdir, name)
      count += 1

      basename = os.path.splitext(name)[0]
      mapped_names.append((basename, subdir))
      continue

    # get to these later
    unmapped.append((name, data))

  # write the remainder
  if unmapped:
    for name, data in unmapped:
      subdir = ''
      for mapped_name, mapped_subdir in mapped_names:
        if name.startswith(mapped_name):
          subdir = mapped_subdir
          break
      write_data_to_file(data, drop_dir, subdir, name)
      count += 1

  print 'extracted %d files' % count
dataset/ETHPy150Open googlei18n/nototools/nototools/grab_mt_download.py/unzip_to_directory_tree