Пример #1
0
def decompress(compressed, uncompressed):
    '''First, read a Huffman tree from the 'compressed' stream using your
    read_tree function. Then use that tree to decode the rest of the
    stream and write the resulting symbols to the 'uncompressed'
    stream.

    Args:
      compressed: A file stream from which compressed input is read.
      uncompressed: A writable file stream to which the uncompressed
          output is written.
    '''
    # read the tree from the compressed file
    tree = read_tree(compressed)

    # initialize bit reading
    readin = bitio.BitReader(compressed)
    not_end_file = True
    # initialize new file for bit writing
    writeout = bitio.BitWriter(uncompressed)
    while not_end_file:
          try:
            # recursively decode one byte
            byte = decode_byte(tree, readin)

            if byte != None:
                  writeout.writebits(byte, 8)
                  
          except EOFError:
            not_end_file = False
            # push changes to file
            writeout.flush()
    
    writeout.flush()
Пример #2
0
def decompress(compressed, uncompressed):
    '''First, read a Huffman tree from the 'compressed' stream using your
    read_tree function. Then use that tree to decode the rest of the
    stream and write the resulting symbols to the 'uncompressed'
    stream.

    Args:
      compressed: A file stream from which compressed input is read.
      uncompressed: A writable file stream to which the uncompressed
          output is written.

    '''

    bitreader = bitio.BitReader(compressed)
    bitwriter = bitio.BitWriter(uncompressed)

    # read the tree from the compressed stream
    tree = read_tree(bitreader)

    # keep decoding bytes and writing to the uncompressed stream until the
    # EOF symbol is reached
    while True:
        decoded = decode_byte(tree, bitreader)
        if decoded == None:
            break
        bitwriter.writebits(decoded, 8)
def compress(tree, uncompressed, compressed):
    '''First write the given tree to the stream 'compressed' using the
    write_tree function. Then use the same tree to encode the data
    from the input stream 'uncompressed' and write it to 'compressed'.
    If there are any partially-written bytes remaining at the end,
    write 0 bits to form a complete byte.

    Flush the bitwriter after writing the entire compressed file.

    Args:
      tree: A Huffman tree.
      uncompressed: A file stream from which you can read the input.
      compressed: A file stream that will receive the tree description
          and the coded input data.
    '''
    write_tree(tree, compressed)
    table = huffman.make_encoding_table(tree)  # make encoding table from tree
    writing = bitio.BitWriter(compressed)
    for z in uncompressed:
        for asciChar in z:  # go through each asci character in the line and find it on the table which would give the corrosponding binaries
            binary = table[asciChar]
            for singleBit in binary:  # go through each binary and write it, true = 1 false =0
                if singleBit == 1:
                    writing.writebit(True)
                elif singleBit == 0:
                    writing.writebit(False)
    for singleBit in table[
            None]:  # table[None] = EOF binary which was not included in the above for loop.
        if singleBit == 1:
            writing.writebit(True)
        elif singleBit == 0:
            writing.writebit(False)
    writing.flush()
Пример #4
0
def compress(tree, uncompressed, compressed):

	write_tree(tree, compressed)
	encoding_table = huffman.make_encoding_table(tree)
	values_table = list(encoding_table.values())
	keys_table = list(encoding_table.keys())

	mybytereader = bitio.BitReader(uncompressed)
	endoffile = False

	list1 = []

	while not endoffile:
		try:
			mybyte = mybytereader.readbits(8)
			list1.append(mybyte)
		except EOFError:
			endoffile = True

	mybitwriter = bitio.BitWriter(compressed)		


	for i in list1:
		if i in encoding_table.keys():
			code = encoding_table[i]
			for h in code:
				mybitwriter.writebit(h)


	mybitwriter.writebit(None)
	mybitwriter.flush()					
Пример #5
0
def decompress(compressed, uncompressed):
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
    # First, read a Huffman tree from the 'tree_stream' using your
    # read_tree function. Then use that tree to decode the rest of the
    # stream and write the resulting symbols to the 'uncompressed'
    # stream.

    # Args:
    #  compressed: A file stream from which compressed input is read.
    #  uncompressed: A writable file stream to which the uncompressed
    #      output is written.
    # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #

    # unpickling the tree from the compressed file stream
    unpkltree = read_tree(compressed)

    # creating BitReader and BitWriter objects
    bitread = bitio.BitReader(compressed)
    bitwriter = bitio.BitWriter(uncompressed)

    while True:
        try:
            nextbyte = decode_byte(unpkltree, bitread)

            # use bitwriter to write indiviual bits to a file
            bitwriter.writebits(nextbyte, 8)
        except:
            break

    # flushing the bit writer object
    bitwriter.flush()

    pass
def decompress(compressed, uncompressed):
    '''First, read a Huffman tree from the 'compressed' stream using your
    read_tree function. Then use that tree to decode the rest of the
    stream and write the resulting symbols to the 'uncompressed'
    stream.

    Args:
      compressed: A file stream from which compressed input is read.
      uncompressed: A writable file stream to which the uncompressed
          output is written.
    '''
    decompTree = read_tree(compressed)  # read whole tree

    binary = bitio.BitReader(compressed)  # convert compressed to binary
    writing = bitio.BitWriter(uncompressed)  # writing to huff tree to var
    end = False
    place = 0
    while end == False:
        try:
            place = decode_byte(decompTree,
                                binary)  # compare whole tree with binary
            writing.writebits(place, 8)
        except:
            end = True
    writing.flush()
    pass
Пример #7
0
def decompress(compressed, uncompressed):
    '''First, read a Huffman tree from the 'compressed' stream using your
    read_tree function. Then use that tree to decode the rest of the
    stream and write the resulting symbols to the 'uncompressed'
    stream.

    Args:
      compressed: A file stream from which compressed input is read.
      uncompressed: A writable file stream to which the uncompressed
          output is written.

    '''
    #set up reader and writer
    reader = bitio.BitReader(compressed)
    writer = bitio.BitWriter(uncompressed)
    #read in and construct tree
    tree = read_tree(reader)

    while (True):
        byte = decode_byte(tree, reader)
        #if the byte is the eof char, break you are done
        if byte == None:
            break
        else:
            #write bits to uncompressed file
            writer.writebits(byte, 8)
Пример #8
0
def decompress(compressed, uncompressed):
    '''First, read a Huffman tree from the 'compressed' stream using your
	read_tree function. Then use that tree to decode the rest of the
	stream and write the resulting symbols to the 'uncompressed'
	stream.

	Args:
	  compressed: A file stream from which compressed input is read.
	  uncompressed: A writable file stream to which the uncompressed
		  output is written.

	'''

    # instances of the BitReader and BitWriter
    reader = bitio.BitReader(compressed)
    writer = bitio.BitWriter(uncompressed)

    # first read the huffman tree off the compressed file
    huffman_tree = read_tree(reader)
    # continue to read the bytes encoded using tree
    while True:
        # decode the next byte
        byte_read = decode_byte(huffman_tree, reader)
        # stop when end-of-message is read
        if byte_read == None:
            break
        # write the byte to the uncompressed file
        writer.writebits(byte_read, 8)
Пример #9
0
def decompress(compressed, uncompressed):
    '''First, read a Huffman tree from the 'compressed' stream using your
    read_tree function. Then use that tree to decode the rest of the
    stream and write the resulting symbols to the 'uncompressed'
    stream.

    Args:
      compressed: A file stream from which compressed input is read.
      uncompressed: A writable file stream to which the uncompressed
          output is written.
    '''
    tree = read_tree(compressed)
    encoded = bitio.BitReader(compressed)
    decoded = bitio.BitWriter(uncompressed)
    end_of_file = False
    try:
        while not end_of_file:

            byte = decode_byte(tree, encoded)
            if byte is None:
                end_of_file = True
            else:
                decoded.writebits(byte, 8)
    except EOFError:
        end_of_file = True
Пример #10
0
def decompress(compressed, uncompressed):
    '''First, read a Huffman tree from the 'compressed' stream using your
    read_tree function. Then use that tree to decode the rest of the
    stream and write the resulting symbols to the 'uncompressed'
    stream.

    Args:
      compressed: A file stream from which compressed input is read.
      uncompressed: A writable file stream to which the uncompressed
          output is written.
    '''

    # load the tree
    tree = read_tree(compressed)

    # Instantiate the Bit Reader and Bit Writer objects
    read_bit = bitio.BitReader(compressed)
    write_val = bitio.BitWriter(uncompressed)

    # Continously decode the bytes from the compressed file until EOF is
    # reached
    try:
        while True:
            val = decode_byte(tree, read_bit)
            write_val.writebits(val, 8)
    except:
        pass  # EOF

    # flush the bitwriter
    write_val.flush()
    return
Пример #11
0
def decompress(compressed, uncompressed):
    '''First, read a Huffman tree from the 'compressed' stream using your
    read_tree function. Then use that tree to decode the rest of the
    stream and write the resulting symbols to the 'uncompressed'
    stream.

    Args:
      compressed: A file stream from which compressed input is read.
      uncompressed: A writable file stream to which the uncompressed
          output is written.
    '''
    flag = 1
    # We get the bits from the compressed stream and use it to obtain our tree
    unpickled = read_tree(compressed)
    # Bit Reader object is created
    in_stream = bitio.BitReader(compressed)
    # Bit Writer object is created
    out_stream = bitio.BitWriter(uncompressed)
    while flag == 1:
        # Coded bits will be decoded until we reach the end and None will be returned
        decoded = decode_byte(unpickled, in_stream)
        if decoded == None:
            flag = 0
        # Keep writing the bits until we reach the end of the file
        elif decoded != None:
            out_stream.writebits(decoded, 8)
    out_stream.flush()
Пример #12
0
def decompress(compressed, uncompressed):
    '''First, read a Huffman tree from the 'compressed' stream using your
    read_tree function. Then use that tree to decode the rest of the
    stream and write the resulting symbols to the 'uncompressed'
    stream.

    Args:
      compressed: A file stream from which compressed input is read.
      uncompressed: A writable file stream to which the uncompressed
          output is written.

    '''

    bitreader = bitio.BitReader(compressed)
    bitwriter = bitio.BitWriter(uncompressed)

    # read Huffman tree from beginning of file
    tree = read_tree(bitreader)

    # while compressed stream has data
    while True:
        b = decode_byte(tree, bitreader)
        # if we reach the end
        if b == None:
            break
        else:
            # write decoded bytes
            bitwriter.writebits(b, 8)
Пример #13
0
def compress(tree, uncompressed, compressed):
    '''First write the given tree to the stream 'compressed' using the
    write_tree function. Then use the same tree to encode the data
    from the input stream 'uncompressed' and write it to 'compressed'.
    If there are any partially-written bytes remaining at the end,
    write 0 bits to form a complete byte.

    Flush the bitwriter after writing the entire compressed file.

    Args:
      tree: A Huffman tree.
      uncompressed: A file stream from which you can read the input.
      compressed: A file stream that will receive the tree description
          and the coded input data.
    '''
    write_tree(tree, compressed)
    decoded = bitio.BitReader(uncompressed)
    encoded = bitio.BitWriter(compressed)
    table = huffman.make_encoding_table(tree)
    end_of_file = False

    try:
        while not end_of_file:
            byte = decoded.readbits(8)
            for x in table[byte]:
                encoded.writebit(x)
    except EOFError:
        for x in table[None]:
            encoded.writebit(x)
    encoded.flush()
Пример #14
0
def compress(tree, uncompressed, compressed):
    '''First write the given tree to the stream 'compressed' using the
    write_tree function. Then use the same tree to encode the data
    from the input stream 'uncompressed' and write it to 'compressed'.
    If there are any partially-written bytes remaining at the end,
    write 0 bits to form a complete byte.

    Flush the bitwriter after writing the entire compressed file.

    Args:
      tree: A Huffman tree.
      uncompressed: A file stream from which you can read the input.
      compressed: A file stream that will receive the tree description
          and the coded input data.
    '''
    write_tree(tree, compressed)
    # instantiate classes
    bitwriter = bitio.BitWriter(compressed)
    bitreader = bitio.BitReader(uncompressed)
    # create table with paths to bytes
    table = huffman.make_encoding_table(tree)
    end_of_file = False
    while not end_of_file:
        try:
            # read in byte
            compress = bitreader.readbits(8)
            # write byte in compressed form
            for el in (table[compress]):
                bitwriter.writebit(el)
        except EOFError:
            # reached end of file
            bitwriter.flush()
            end_of_file = True
Пример #15
0
def decompress(compressed, uncompressed):
	'''First, read a Huffman tree from the 'compressed' stream using your
	read_tree function. Then use that tree to decode the rest of the
	stream and write the resulting symbols to the 'uncompressed'
	stream.

	Args:
	compressed: A file stream from which compressed input is read.
	uncompressed: A writable file stream to which the uncompressed
	output is written.

	'''

	#let compressed be an instance of bitio.BitReader
	reading = bitio.BitReader(compressed)
	#use read_tree to get the huffman tree
	tree = read_tree(reading)
	#let uncompressed be an instance of bitio.BitWriter
	Target = bitio.BitWriter(uncompressed)

	while True:
		#get the value of leaf
		val = decode_byte(tree, reading)
		
		#if EOF just break
		if val is None:
			break

		#write the value of leaf to uncompressed file
		Target.writebits(val,8)

	Target.flush()
Пример #16
0
def compress(tree, uncompressed, compressed):
    '''First write the given tree to the stream 'compressed' using the
    write_tree function. Then use the same tree to encode the data
    from the input stream 'uncompressed' and write it to 'compressed'.
    If there are any partially-written bytes remaining at the end,
    write 0 bits to form a complete byte.

    Flush the bitwriter after writing the entire compressed file.

    Args:
      tree: A Huffman tree.
      uncompressed: A file stream from which you can read the input.
      compressed: A file stream that will receive the tree description
          and the coded input data.
    '''

    # no try statement given, becuase if file exists, and
    try:
        write_tree(tree, compressed)
    except:
        print("File does not contain any bits to compress")
        return

    encoding_table = huffman.make_encoding_table(tree)

    # open using bitio
    bitread = bitio.BitReader(uncompressed)
    bitwrite = bitio.BitWriter(compressed)

    # assume EOF is not reached
    eof = False

    # read till EOF is reached
    while not eof:

        try:
            # read 8 bits to byte
            byte = bitread.readbits(8)
            # encode using encoding_table
            code = encoding_table[byte]
            # write code bitwise
            for bit in code:
                bitwrite.writebit(bit)

        # this is a crucial step to ensure loop stops
        # and compressed files are marked with None to indicate EOF
        except EOFError:
            # stop loop
            eof = True

            # manually write None to indicate EOF to decompressor
            code = encoding_table[None]
            for bit in code:
                bitwrite.writebit(bit)

    bitwrite.flush()

    pass
Пример #17
0
def compress(tree, uncompressed, compressed):
    '''
    First write the given tree to the stream 'compressed' using the
    write_tree function. Then use the same tree to encode the data
    from the input stream 'uncompressed' and write it to 'compressed'.
    If there are any partially-written bytes remaining at the end,
    write 0 bits to form a complete byte.

    Flush the bitwriter after writing the entire compressed file.

    Args:
      tree: A Huffman tree.
      uncompressed: A file stream from which you can read the input.
      compressed: A file stream that will receive the tree description
          and the coded input data.
    '''

    bitreader = bitio.BitReader(uncompressed)
    bitwriter = bitio.BitWriter(compressed)

    # write tree to the beginning of the file
    write_tree(tree, bitwriter)

    # create encoding table for compressed bits of file using our tree
    table = huffman.make_encoding_table(tree)

    counter = 0

    # read from uncompressed stream until done
    while True:
        try:
            # find path description (tuple) from encoding table
            path = table[bitreader.readbits(8)]
        # if we have reached the end of the file
        except EOFError:
            bitwriter.writebits(0, 2)
            # to have a full byte at the end
            counter += 2
            break

        # write the path to the compressed file
        for p in path:
            if p:
                bitwriter.writebit(1)
                counter += 1
            else:
                bitwriter.writebit(0)
                counter += 1

    # find how many bits left to make an even byte
    counter %= 8

    # complete byte with 0s
    while counter:
        bitwriter.writebit(0)
        counter -= 1
Пример #18
0
def decompress(compressed, uncompressed):
    bitreader = bitio.BitReader(compressed)
    bitwriter = bitio.BitWriter(uncompressed)
    tree = read_tree(bitreader)
    # Repeatedly read coded bits from the file, decode them using tree
    while True:
        decoded = huffman.decode(tree, bitreader)
        # As soon as you decode the end-of-message symbol, you should stop reading.
        if decoded is None:
            break
        # write the decoded byte to the uncompressed output
        bitwriter.writebits(decoded, 8)
Пример #19
0
def compress(tree, uncompressed, compressed):
    '''First write the given tree to the stream 'compressed' using the
    write_tree function. Then use the same tree to encode the data
    from the input stream 'uncompressed' and write it to 'compressed'.
    If there are any partially-written bytes remaining at the end,
    write 0 bits to form a complete byte.

    Flush the bitwriter after writing the entire compressed file.

    Args:
      tree: A Huffman tree.
      uncompressed: A file stream from which you can read the input.
      compressed: A file stream that will receive the tree description
          and the coded input data.
    '''

    bitwriter = bitio.BitWriter(compressed)
    bitreader = bitio.BitReader(uncompressed)

    # table maps the byte of a leaf node to a tuple containiing the bit sequence
    table = huffman.make_encoding_table(tree)

    write_tree(tree, bitwriter)

    # holds the bits written to the compressed stream
    bit_count = 0

    # read bits from the uncompressed stream until there are none left
    while True:
        try:
            symbol = bitreader.readbits(8)
        except:
            break

        # write the bit sequence for the symbol read
        encoded = table[symbol]
        for bit in encoded:
            bit_count += 1
            bitwriter.writebit(bit)

    # write the end of file message
    for bit in table[None]:
        bit_count += 1
        bitwriter.writebit(bit)

    # pad with zeros if there are partial bytes
    remaining = bit_count % 8
    if remaining != 0:
        for i in range(remaining):
            bitwriter.writebit(False)

    bitwriter.flush()
Пример #20
0
def compress(tree, uncompressed, compressed):
    """First write the given tree to the stream 'compressed' using the
    write_tree function. Then use the same tree to encode the data
    from the input stream 'uncompressed' and write it to 'compressed'.
    If there are any partially-written bytes remaining at the end,
    write 0 bits to form a complete byte.

    Flush the BitWriter after writing the entire compressed file.

    Args:
      tree: A Huffman tree.
      uncompressed: A file stream from which you can read the input.
      compressed: A file stream that will receive the tree description
          and the coded input data.
    """

    def read_byte(bit_stream):
        """
        Short function to read the file, just to allow for use of iter(), decreasing clutter
        :param bit_stream: a BitReader object
        :return: None when EOF, the byte read otherwise.
        """
        try:
            return bit_stream.readbits(8)
        except EOFError:
            return None

    write_tree(tree, compressed)
    encoding_table = huffman.make_encoding_table(tree)

    # Open a BitReader for uncompressed file
    in_stream = bitio.BitReader(uncompressed)

    output = []

    # Read the uncompressed file until EOF
    for uncompressed_byte in iter(lambda: read_byte(in_stream), None):
        compressed_byte = encoding_table[uncompressed_byte]
        output += list(compressed_byte)

    # Add EOF
    output += list(encoding_table[None])

    # Open BitWriter for compressed file
    out_stream = bitio.BitWriter(compressed)

    # Write out bits
    for bit in output:
        out_stream.writebit(bit)

    # Flush stream
    out_stream.flush()
Пример #21
0
def compress(tree, uncompressed, compressed):
    '''First write the given tree to the stream 'compressed' using the
	write_tree function. Then use the same tree to encode the data
	from the input stream 'uncompressed' and write it to 'compressed'.
	If there are any partially-written bytes remaining at the end,
	write 0 bits to form a complete byte.

	Flush the bitwriter after writing the entire compressed file.

	Args:
	  tree: A Huffman tree.
	  uncompressed: A file stream from which you can read the input.
	  compressed: A file stream that will receive the tree description
		  and the coded input data.
	'''

    # instances of the BitReader and BitWriter
    reader = bitio.BitReader(uncompressed)
    writer = bitio.BitWriter(compressed)

    # make the encoding table for the given tree
    encode_table = huffman.make_encoding_table(tree)

    # call write_tree, to write the tree to the compressed file
    write_tree(tree, writer)

    # write all the bytes untill EOFError occurs
    while True:
        try:
            # read the byte from uncompressed file
            byte_towrite = reader.readbits(8)
            # encode the byte using the dictionary
            bit_sequence = encode_table[byte_towrite]
            # write each bit to the compressed file
            for b in bit_sequence:
                if b == True:
                    writer.writebit(1)
                elif b == False:
                    writer.writebit(0)

        except EOFError:
            bit_sequence = encode_table[None]
            # write each bit to the compressed file
            for b in bit_sequence:
                if b == True:
                    writer.writebit(1)
                elif b == False:
                    writer.writebit(0)
            # stop the loop
            break
    # Flush the bitwriter
    writer.flush()
Пример #22
0
def decompress(compressed, uncompressed):
    
    #defining reader and writer 
    bitreader1 = bitio.BitReader(compressed)
    bitwriter1 = bitio.BitWriter(uncompressed)

    tree = read_tree(compressed)
    alphabet = 0

    while alphabet!=None:
    	letter = decode_byte(tree, bitreader1)		
    	bitwriter1.writebits(letter, 8)	
    bitwriter1.flush()	
Пример #23
0
def compress(tree, uncompressed, compressed):
    '''First write the given tree to the stream 'compressed' using the
    write_tree function. Then use the same tree to encode the data
    from the input stream 'uncompressed' and write it to 'compressed'.
    If there are any partially-written bytes remaining at the end,
    write 0 bits to form a complete byte.

    Args:
      tree: A Huffman tree.
      uncompressed: A file stream from which you can read the input.
      compressed: A file stream that will receive the tree description
          and the coded input data.
    '''
    bitwriter = bitio.BitWriter(compressed)
    # encode the tree itself
    write_tree(tree, bitwriter)
    # create a dictionary for codes where each code takes the form (bool,bool,bool,...)
    codes = huffman.make_encoding_table(tree)

    buff = bytearray(512)  # the buffer in which to read the input
    while True:
        count = uncompressed.readinto(buff)
        for i in range(count):
            for node in codes[buff[i]]:
                if node == True:
                    bitwriter.writebit(1)
                elif node == False:
                    bitwriter.writebit(0)
                else:
                    # if the node is for some reason not stored correctly
                    raise Exception("Nodetype not boolean, found: {}".format(
                        type(node)))

        if count < len(buff):  # when there is no more input
            break

    # encode and send an end of message character to finish the message
    for node in codes[None]:  # None is the end of message character
        if node == True:
            bitwriter.writebit(1)
        elif node == False:
            bitwriter.writebit(0)
        else:
            # if the node is for some reason not stored correctly
            raise Exception("Nodetype not boolean, found: {}".format(
                type(node)))

    # write extra bits if needed to fill the last byte
    bitwriter.writebits(0, 8 - bitwriter.bcount)
    bitwriter.flush()
Пример #24
0
def decompress(compressed, uncompressed):
    '''First, read a Huffman tree from the 'compressed' stream using your
    read_tree function. Then use that tree to decode the rest of the
    stream and write the resulting symbols to the 'uncompressed'
    stream.
    Args:
      compressed: A file stream from which compressed input is read.
      uncompressed: A writable file stream to which the uncompressed
          output is written.
    '''
    '''br = BitReader(compressed)
    tree = read_tree(br)
    print(tree.left.left.left.left.left)
    # encoded_table = huffman.make_encoding_table(tree)
    # print(encoded_table)
    # print(bin(br.readbits(100)))
    bw = BitWriter(uncompressed)
    while True:
        try:
            bit = br.readbit()
            byte = decode_byte(tree, br)
            bw.writebits(byte, 8)
        except EOFError:
            break

    bw.writebit(0b0)
    bw.writebit(0b1)
    bw.writebit(0b0)
    bw.writebit(0b1)

    bw.writebit(0b0)
    bw.writebit(0b0)
    bw.writebit(0b1)
    bw.writebit(0b0)'''
    # initialize the reading and writing
    reader = bitio.BitReader(compressed)
    writer = bitio.BitWriter(uncompressed)
    tree = read_tree(reader)

    while 1:
        byte = decode_byte(tree, reader)
        if byte == None:  # means ending
            break
        else:
            writer.writebits(byte, 8)
Пример #25
0
def compress(tree, uncompressed, compressed):
    '''First write the given tree to the stream 'compressed' using the
    write_tree function. Then use the same tree to encode the data
    from the input stream 'uncompressed' and write it to 'compressed'.
    If there are any partially-written bytes remaining at the end,
    write 0 bits to form a complete byte.

    Flush the bitwriter after writing the entire compressed file.

    Args:
      tree: A Huffman tree.
      uncompressed: A file stream from which you can read the input.
      compressed: A file stream that will receive the tree description
          and the coded input data.
    '''
    # initialise tables and input and output bitstreams
    table = huffman.make_encoding_table(tree)
    input_stream = bitio.BitReader(uncompressed)

    output_stream = bitio.BitWriter(compressed)
    write_tree(tree, output_stream)

    # set up a counter to find partially filled bytes
    counter = 0

    while (True):
        try:
            # tries to read 8 bytes, if end of file found, go to except
            byte = input_stream.readbits(8)
            path = table[byte]  # find the path
            counter += len(path)
            for i in path:
                # output the bits
                output_stream.writebit(i)
        except:
            # for partially filled bytes, pad with 0's to make a byte
            path = table[None]  # find the path
            counter += len(path)
            for i in path:
                # output the bits
                output_stream.writebit(i)
            output_stream.writebits(0, counter % 8)
            # flush
            output_stream.flush()
            return
Пример #26
0
def decompress(compressed, uncompressed):
    '''First, read a Huffman tree from the 'compressed' stream using your
    read_tree function. Then use that tree to decode the rest of the
    stream and write the resulting symbols to the 'uncompressed'
    stream.

    Args:
      compressed: A file stream from which compressed input is read.
      uncompressed: A writable file stream to which the uncompressed
          			output is written.
    '''

    # create tree using read_tree
    try:
        tree = read_tree(compressed)
    except:
        print("Huffman tree description invalid")
        return

    # open using bitio
    bitread = bitio.BitReader(compressed)
    bitwrite = bitio.BitWriter(uncompressed)

    # attempt to decode file bits after Huffman tree description
    try:
        decode = decode_byte(tree, bitread)
    except EOFError:
        decode = None
        print("No bits to read after Huffman tree description")

    # if bits are successfully decoded, begin writing them, till EOF is reached
    while decode != None:

        try:
            # write decoded symbol with 8 bits and decode the next bits
            bitwrite.writebits(decode, 8)
            decode = decode_byte(tree, bitread)

        # exception in case compressed file does not have None written before EOF
        except EOFError:
            decode = None

    pass
Пример #27
0
def compress(tree, uncompressed, compressed):
    '''First write the given tree to the stream 'compressed' using the
    write_tree function. Then use the same tree to encode the data
    from the input stream 'uncompressed' and write it to 'compressed'.
    If there are any partially-written bytes remaining at the end,
    write 0 bits to form a complete byte.
    Flush the bitwriter after writing the entire compressed file.
    Args:
      tree: A Huffman tree.
      uncompressed: A file stream from which you can read the input.
      compressed: A file stream that will receive the tree description
          and the coded input data.
    '''
    # Same initial setup as decompress
    reader = bitio.BitReader(uncompressed)
    writer = bitio.BitWriter(compressed)

    # This time we are writing the tree instead
    write_tree(tree, writer)

    # key is a dictionary that is used to find the specific bitsequence for a
    # specific byte using the huffman coding
    key = huffman.make_encoding_table(tree)

    while 1:
        try:
            # use the key to map the specific byte to the corresponding
            # huffman bitsequence. By looping through the whole file, we can
            # compress every byte to a huffman compressed bit sequence, thus
            # compressing the whole file to a .huff extension

            byte = reader.readbits(8)
            bitsequence = key[byte]
            for bit in bitsequence:
                writer.writebit(bit)

        # This flag is hear to indicate we have reached the end of the file
        # and to thus stop compressing
        except EOFError:
            break

    pass
Пример #28
0
def compress(tree, uncompressed, compressed):
	'''First write the given tree to the stream 'compressed' using the
	write_tree function. Then use the same tree to encode the data
	from the input stream 'uncompressed' and write it to 'compressed'.
	If there are any partially-written bytes remaining at the end,
	write 0 bits to form a complete byte.

	Flush the bitwriter after writing the entire compressed file.

	Args:
	tree: A Huffman tree.
	uncompressed: A file stream from which you can read the input.
	compressed: A file stream that will receive the tree description
	and the coded input data.
	'''
	##let compressed be an instance of bitio.BitWriter
	Target = bitio.BitWriter(compressed)
	#let uncompressed be an instance of bitio.BitReader
	readingfile = bitio.BitReader(uncompressed)
	#Write the Huffman tree to compressed file.
	write_tree(tree, Target)

	#to get encoding table 
	encode = huffman.make_encoding_table(tree)
	while True:
		# try EOFError
		try:
			# can read a byte ?
			reading = readingfile.readbits(8)	
		except EOFError:
			# reach EOF encode eof,then get out of loop
			Target.writebit(0)
			Target.writebit(0)
			break
		#if no EOFError, get the sequence from tree using encoding table

		value = encode[reading]
		for v in value:
			# write v as a bit
			Target.writebit(v)

	Target.flush()
Пример #29
0
def compress(tree, uncompressed, compressed):
    '''First write the given tree to the stream 'compressed' using the
    write_tree function. Then use the same tree to encode the data
    from the input stream 'uncompressed' and write it to 'compressed'.
    If there are any partially-written bytes remaining at the end,
    write 0 bits to form a complete byte.

    Args:
      tree: A Huffman tree.
      uncompressed: A file stream from which you can read the input.
      compressed: A file stream that will receive the tree description
          and the coded input data.
    '''
    bitstream = bitio.BitWriter(compressed)
    write_tree(tree, bitstream)

    enc_table = huffman.make_encoding_table(tree)  # Create encoding table
    end_char = enc_table[None]  # Get end char

    input_stream = uncompressed.read(1)  # Read inn one byte

    while input_stream:

        input_char = ord(input_stream)  # Convert to binary
        compressed_char = enc_table[input_char]  # Get compressed byte

        for bit in compressed_char:  # Print the compressed byte
            if bit:
                bitstream.writebit(1)
            else:
                bitstream.writebit(0)

        input_stream = uncompressed.read(1)  # Read the next byte

    # Print end bit
    for bit in end_char:
        if bit:
            bitstream.writebit(1)
        else:
            bitstream.writebit(0)

    bitstream.flush()
Пример #30
0
def compress(tree, uncompressed, compressed):
    '''
    First write the given tree to the stream 'compressed' using the
    write_tree function. Then use the same tree to encode the data
    from the input stream 'uncompressed' and write it to 'compressed'.
    If there are any partially-written bytes remaining at the end,
    write 0 bits to form a complete byte.

    Flush the bitwriter after writing the entire compressed file.

    Args:
      tree: A Huffman tree.
      uncompressed: A file stream from which you can read the input.
      compressed: A file stream that will receive the tree description
          and the coded input data.
  '''
    # The given tree is written to the compressed
    write_tree(tree, compressed)
    # The bit writer object is created
    compressed_ = bitio.BitWriter(compressed)
    # The bit reader object is created
    uncompressed_ = bitio.BitReader(uncompressed)
    # Encoding table is made here
    encoding_table = huffman.make_encoding_table(tree)
    flag1 = 1
    while flag1 == 1:
        # To catch the End of File error
        try:
            # Reading 8 bits (byte)
            current_bits = uncompressed_.readbits(8)
            # These are stored in an encoding table
            compressed1 = encoding_table[current_bits]
            for bits in compressed1:
                compressed_.writebit(bits)

        except EOFError:
            for bits in encoding_table[None]:
                compressed_.writebit(bits)
                # Where the while loop will end
                flag1 = 0
    compressed_.flush()