# Copyright (c) 2006 Carnegie Mellon University # # You may copy and modify this freely under the same terms as # Sphinx-III """Read/write Sphinx-III binary parameter files. All the various binary parameter files created by SphinxTrain and used by Sphinx-III and PocketSphinx share a common file format. This module contains some base classes for reading and writing these files. """ __author__ = "David Huggins-Daines " __version__ = "$Revision$" from struct import unpack, pack from numpy import reshape, shape, frombuffer class S3File: "Read Sphinx-III binary files" def __init__(self, filename=None, mode="rb"): self.fh = None if filename is not None: self.open(filename, mode) def __del__(self): self.close() def __enter__(self): return self def __exit__(self, exc_type, exc_value, exc_traceback): self.close() return False def getall(self): return self._params def __getitem__(self, key): return self._params[key] def __setitem__(self, key, value): self._params[key] = value def __delitem__(self, key): del self._params[key] def __iter__(self): return iter(self._params) def __len__(self): return len(self._params) def open(self, filename, mode="rb"): self.filename = filename self.fh = open(filename, mode) self.readheader() def close(self): if self.fh is not None: self.fh.close() self.fh = None def readheader(self): """ Read binary header. Sets the following attributes: - fileattr (a dictionary of attribute-value pairs) - swap (a byteswap string as used by the struct module) - otherend (a flag indicating if the file is wrong-endian for the current platform) - data_start (offset of the start of data in the file) """ spam = self.fh.readline() self.fileattr = {} if spam != b"s3\n": raise Exception("File ID not found or invalid: " + spam) while True: spam = self.fh.readline() if spam == b"": raise Exception("EOF while reading headers") if spam.endswith(b"endhdr\n"): break sp = spam.find(b' ') k = spam[0:sp].strip().decode('utf-8') v = spam[sp:].strip().decode('utf-8') self.fileattr[k] = v # This is 0x11223344 in the file's byte order spam = unpack("