function
stringlengths
18
3.86k
intent_category
stringlengths
5
24
def brute_force(input_string: str, alphabet: str | None = None) -> dict[int, str]: # Set default alphabet to lower and upper case english chars alpha = alphabet or ascii_letters # To store data on all the combinations brute_force_data = {} # Cycle through each combination for key in range(1, len(alpha) + 1): # Decrypt the message and store the result in the data brute_force_data[key] = decrypt(input_string, key, alpha) return brute_force_data
ciphers
def dencrypt(s: str, n: int = 13) -> str: out = "" for c in s: if "A" <= c <= "Z": out += chr(ord("A") + (ord(c) - ord("A") + n) % 26) elif "a" <= c <= "z": out += chr(ord("a") + (ord(c) - ord("a") + n) % 26) else: out += c return out
ciphers
def main() -> None: s0 = input("Enter message: ") s1 = dencrypt(s0, 13) print("Encryption:", s1) s2 = dencrypt(s1, 13) print("Decryption: ", s2)
ciphers
def __encrypt_part(message_part: str, character_to_number: dict[str, str]) -> str: one, two, three = "", "", "" tmp = [] for character in message_part: tmp.append(character_to_number[character]) for each in tmp: one += each[0] two += each[1] three += each[2] return one + two + three
ciphers
def __decrypt_part( message_part: str, character_to_number: dict[str, str] ) -> tuple[str, str, str]: tmp, this_part = "", "" result = [] for character in message_part: this_part += character_to_number[character] for digit in this_part: tmp += digit if len(tmp) == len(message_part): result.append(tmp) tmp = "" return result[0], result[1], result[2]
ciphers
def __prepare( message: str, alphabet: str ) -> tuple[str, str, dict[str, str], dict[str, str]]: # Validate message and alphabet, set to upper and remove spaces alphabet = alphabet.replace(" ", "").upper() message = message.replace(" ", "").upper() # Check length and characters if len(alphabet) != 27: raise KeyError("Length of alphabet has to be 27.") for each in message: if each not in alphabet: raise ValueError("Each message character has to be included in alphabet!") # Generate dictionares numbers = ( "111", "112", "113", "121", "122", "123", "131", "132", "133", "211", "212", "213", "221", "222", "223", "231", "232", "233", "311", "312", "313", "321", "322", "323", "331", "332", "333", ) character_to_number = {} number_to_character = {} for letter, number in zip(alphabet, numbers): character_to_number[letter] = number number_to_character[number] = letter return message, alphabet, character_to_number, number_to_character
ciphers
def encrypt_message( message: str, alphabet: str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.", period: int = 5 ) -> str: message, alphabet, character_to_number, number_to_character = __prepare( message, alphabet ) encrypted, encrypted_numeric = "", "" for i in range(0, len(message) + 1, period): encrypted_numeric += __encrypt_part( message[i : i + period], character_to_number ) for i in range(0, len(encrypted_numeric), 3): encrypted += number_to_character[encrypted_numeric[i : i + 3]] return encrypted
ciphers
def decrypt_message( message: str, alphabet: str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ.", period: int = 5 ) -> str: message, alphabet, character_to_number, number_to_character = __prepare( message, alphabet ) decrypted_numeric = [] decrypted = "" for i in range(0, len(message) + 1, period): a, b, c = __decrypt_part(message[i : i + period], character_to_number) for j in range(0, len(a)): decrypted_numeric.append(a[j] + b[j] + c[j]) for each in decrypted_numeric: decrypted += number_to_character[each] return decrypted
ciphers
def generate_table(key: str) -> list[tuple[str, str]]: return [alphabet[char] for char in key.upper()]
ciphers
def encrypt(key: str, words: str) -> str: cipher = "" count = 0 table = generate_table(key) for char in words.upper(): cipher += get_opponent(table[count], char) count = (count + 1) % len(table) return cipher
ciphers
def decrypt(key: str, words: str) -> str: return encrypt(key, words)
ciphers
def get_position(table: tuple[str, str], char: str) -> tuple[int, int]: # `char` is either in the 0th row or the 1st row row = 0 if char in table[0] else 1 col = table[row].index(char) return row, col
ciphers
def get_opponent(table: tuple[str, str], char: str) -> str: row, col = get_position(table, char.upper()) if row == 1: return table[0][col] else: return table[1][col] if row == 0 else char
ciphers
def encode(word: str) -> str: encoded = "" for letter in word.lower(): if letter.isalpha() or letter == " ": encoded += encode_dict[letter] else: raise Exception("encode() accepts only letters of the alphabet and spaces") return encoded
ciphers
def decode(coded: str) -> str: if set(coded) - {"A", "B", " "} != set(): raise Exception("decode() accepts only 'A', 'B' and spaces") decoded = "" for word in coded.split(): while len(word) != 0: decoded += decode_dict[word[:5]] word = word[5:] decoded += " " return decoded.strip()
ciphers
def main() -> None: message = input("Enter message: ") key = input("Enter key [alphanumeric]: ") mode = input("Encrypt/Decrypt [e/d]: ") if mode.lower().startswith("e"): mode = "encrypt" translated = encrypt_message(key, message) elif mode.lower().startswith("d"): mode = "decrypt" translated = decrypt_message(key, message) print(f"\n{mode.title()}ed message:") print(translated)
ciphers
def encrypt_message(key: str, message: str) -> str: return translate_message(key, message, "encrypt")
ciphers
def decrypt_message(key: str, message: str) -> str: return translate_message(key, message, "decrypt")
ciphers
def translate_message(key: str, message: str, mode: str) -> str: translated = [] key_index = 0 key = key.upper() for symbol in message: num = LETTERS.find(symbol.upper()) if num != -1: if mode == "encrypt": num += LETTERS.find(key[key_index]) elif mode == "decrypt": num -= LETTERS.find(key[key_index]) num %= len(LETTERS) if symbol.isupper(): translated.append(LETTERS[num]) elif symbol.islower(): translated.append(LETTERS[num].lower()) key_index += 1 if key_index == len(key): key_index = 0 else: translated.append(symbol) return "".join(translated)
ciphers
def main() -> None: message = input("Enter message: ") key = "LFWOAYUISVKMNXPBDCRJTQEGHZ" resp = input("Encrypt/Decrypt [e/d]: ") check_valid_key(key) if resp.lower().startswith("e"): mode = "encrypt" translated = encrypt_message(key, message) elif resp.lower().startswith("d"): mode = "decrypt" translated = decrypt_message(key, message) print(f"\n{mode.title()}ion: \n{translated}")
ciphers
def check_valid_key(key: str) -> None: key_list = list(key) letters_list = list(LETTERS) key_list.sort() letters_list.sort() if key_list != letters_list: sys.exit("Error in the key or symbol set.")
ciphers
def encrypt_message(key: str, message: str) -> str: return translate_message(key, message, "encrypt")
ciphers
def decrypt_message(key: str, message: str) -> str: return translate_message(key, message, "decrypt")
ciphers
def translate_message(key: str, message: str, mode: str) -> str: translated = "" chars_a = LETTERS chars_b = key if mode == "decrypt": chars_a, chars_b = chars_b, chars_a for symbol in message: if symbol.upper() in chars_a: sym_index = chars_a.find(symbol.upper()) if symbol.isupper(): translated += chars_b[sym_index].upper() else: translated += chars_b[sym_index].lower() else: translated += symbol return translated
ciphers
def get_random_key() -> str: key = list(LETTERS) random.shuffle(key) return "".join(key)
ciphers
def _validator( rotpos: RotorPositionT, rotsel: RotorSelectionT, pb: str ) -> tuple[RotorPositionT, RotorSelectionT, dict[str, str]]: # Checks if there are 3 unique rotors if (unique_rotsel := len(set(rotsel))) < 3: raise Exception(f"Please use 3 unique rotors (not {unique_rotsel})") # Checks if rotor positions are valid rotorpos1, rotorpos2, rotorpos3 = rotpos if not 0 < rotorpos1 <= len(abc): raise ValueError( "First rotor position is not within range of 1..26 (" f"{rotorpos1}" ) if not 0 < rotorpos2 <= len(abc): raise ValueError( "Second rotor position is not within range of 1..26 (" f"{rotorpos2})" ) if not 0 < rotorpos3 <= len(abc): raise ValueError( "Third rotor position is not within range of 1..26 (" f"{rotorpos3})" ) # Validates string and returns dict pbdict = _plugboard(pb) return rotpos, rotsel, pbdict
ciphers
def _plugboard(pbstring: str) -> dict[str, str]: # tests the input string if it # a) is type string # b) has even length (so pairs can be made) if not isinstance(pbstring, str): raise TypeError(f"Plugboard setting isn't type string ({type(pbstring)})") elif len(pbstring) % 2 != 0: raise Exception(f"Odd number of symbols ({len(pbstring)})") elif pbstring == "": return {} pbstring.replace(" ", "") # Checks if all characters are unique tmppbl = set() for i in pbstring: if i not in abc: raise Exception(f"'{i}' not in list of symbols") elif i in tmppbl: raise Exception(f"Duplicate symbol ({i})") else: tmppbl.add(i) del tmppbl # Created the dictionary pb = {} for j in range(0, len(pbstring) - 1, 2): pb[pbstring[j]] = pbstring[j + 1] pb[pbstring[j + 1]] = pbstring[j] return pb
ciphers
def enigma( text: str, rotor_position: RotorPositionT, rotor_selection: RotorSelectionT = (rotor1, rotor2, rotor3), plugb: str = "",
ciphers
def __init__(self) -> None: self.SQUARE = np.array(SQUARE)
ciphers
def letter_to_numbers(self, letter: str) -> np.ndarray: index1, index2 = np.where(letter == self.SQUARE) indexes = np.concatenate([index1 + 1, index2 + 1]) return indexes
ciphers
def numbers_to_letter(self, index1: int, index2: int) -> str: letter = self.SQUARE[index1 - 1, index2 - 1] return letter
ciphers
def encode(self, message: str) -> str: message = message.lower() message = message.replace(" ", "") message = message.replace("j", "i") first_step = np.empty((2, len(message))) for letter_index in range(len(message)): numbers = self.letter_to_numbers(message[letter_index]) first_step[0, letter_index] = numbers[0] first_step[1, letter_index] = numbers[1] second_step = first_step.reshape(2 * len(message)) encoded_message = "" for numbers_index in range(len(message)): index1 = int(second_step[numbers_index * 2]) index2 = int(second_step[(numbers_index * 2) + 1]) letter = self.numbers_to_letter(index1, index2) encoded_message = encoded_message + letter return encoded_message
ciphers
def miller_rabin(n: int, allow_probable: bool = False) -> bool: if n == 2: return True if not n % 2 or n < 2: return False if n > 5 and n % 10 not in (1, 3, 7, 9): # can quickly check last digit return False if n > 3_317_044_064_679_887_385_961_981 and not allow_probable: raise ValueError( "Warning: upper bound of deterministic test is exceeded. " "Pass allow_probable=True to allow probabilistic test. " "A return value of True indicates a probable prime." ) # array bounds provided by analysis bounds = [ 2_047, 1_373_653, 25_326_001, 3_215_031_751, 2_152_302_898_747, 3_474_749_660_383, 341_550_071_728_321, 1, 3_825_123_056_546_413_051, 1, 1, 318_665_857_834_031_151_167_461, 3_317_044_064_679_887_385_961_981, ] primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41] for idx, _p in enumerate(bounds, 1): if n < _p: # then we have our last prime to check plist = primes[:idx] break d, s = n - 1, 0 # break up n -1 into a power of 2 (s) and # remaining odd component # essentially, solve for d * 2 ** s == n - 1 while d % 2 == 0: d //= 2 s += 1 for prime in plist: pr = False for r in range(s): m = pow(prime, d * 2**r, n) # see article for analysis explanation for m if (r == 0 and m == 1) or ((m + 1) % n == 0): pr = True # this loop will not determine compositeness break if pr: continue # if pr is False, then the above loop never evaluated to true, # and the n MUST be composite return False return True
ciphers
def test_miller_rabin() -> None: assert not miller_rabin(561) assert miller_rabin(563) # 2047 assert not miller_rabin(838_201) assert miller_rabin(838_207) # 1_373_653 assert not miller_rabin(17_316_001) assert miller_rabin(17_316_017) # 25_326_001 assert not miller_rabin(3_078_386_641) assert miller_rabin(3_078_386_653) # 3_215_031_751 assert not miller_rabin(1_713_045_574_801) assert miller_rabin(1_713_045_574_819) # 2_152_302_898_747 assert not miller_rabin(2_779_799_728_307) assert miller_rabin(2_779_799_728_327) # 3_474_749_660_383 assert not miller_rabin(113_850_023_909_441) assert miller_rabin(113_850_023_909_527) # 341_550_071_728_321 assert not miller_rabin(1_275_041_018_848_804_351) assert miller_rabin(1_275_041_018_848_804_391) # 3_825_123_056_546_413_051 assert not miller_rabin(79_666_464_458_507_787_791_867) assert miller_rabin(79_666_464_458_507_787_791_951) # 318_665_857_834_031_151_167_461 assert not miller_rabin(552_840_677_446_647_897_660_333) assert miller_rabin(552_840_677_446_647_897_660_359) # 3_317_044_064_679_887_385_961_981 # upper limit for probabilistic test
ciphers
def generate_key(message: str, key: str) -> str: x = len(message) i = 0 while True: if x == i: i = 0 if len(key) == len(message): break key += key[i] i += 1 return key
ciphers
def cipher_text(message: str, key_new: str) -> str: cipher_text = "" i = 0 for letter in message: if letter == " ": cipher_text += " " else: x = (dict1[letter] - dict1[key_new[i]]) % 26 i += 1 cipher_text += dict2[x] return cipher_text
ciphers
def original_text(cipher_text: str, key_new: str) -> str: or_txt = "" i = 0 for letter in cipher_text: if letter == " ": or_txt += " " else: x = (dict1[letter] + dict1[key_new[i]] + 26) % 26 i += 1 or_txt += dict2[x] return or_txt
ciphers
def main() -> None: message = "THE GERMAN ATTACK" key = "SECRET" key_new = generate_key(message, key) s = cipher_text(message, key_new) print(f"Encrypted Text = {s}") print(f"Original Text = {original_text(s, key_new)}")
ciphers
def mixed_keyword(key: str = "college", pt: str = "UNIVERSITY") -> str: key = key.upper() pt = pt.upper() temp = [] for i in key: if i not in temp: temp.append(i) len_temp = len(temp) # print(temp) alpha = [] modalpha = [] for j in range(65, 91): t = chr(j) alpha.append(t) if t not in temp: temp.append(t) # print(temp) r = int(26 / 4) # print(r) k = 0 for _ in range(r): s = [] for _ in range(len_temp): s.append(temp[k]) if k >= 25: break k += 1 modalpha.append(s) # print(modalpha) d = {} j = 0 k = 0 for j in range(len_temp): for m in modalpha: if not len(m) - 1 >= j: break d[alpha[k]] = m[j] if not k < 25: break k += 1 print(d) cypher = "" for i in pt: cypher += d[i] return cypher
ciphers
def main() -> None: input_file = "Prehistoric Men.txt" output_file = "Output.txt" key = int(input("Enter key: ")) mode = input("Encrypt/Decrypt [e/d]: ") if not os.path.exists(input_file): print(f"File {input_file} does not exist. Quitting...") sys.exit() if os.path.exists(output_file): print(f"Overwrite {output_file}? [y/n]") response = input("> ") if not response.lower().startswith("y"): sys.exit() start_time = time.time() if mode.lower().startswith("e"): with open(input_file) as f: content = f.read() translated = trans_cipher.encrypt_message(key, content) elif mode.lower().startswith("d"): with open(output_file) as f: content = f.read() translated = trans_cipher.decrypt_message(key, content) with open(output_file, "w") as output_obj: output_obj.write(translated) total_time = round(time.time() - start_time, 2) print(("Done (", total_time, "seconds )"))
ciphers
def __init__(self, passcode: str | None = None) -> None: self.__passcode = passcode or self.__passcode_creator() self.__key_list = self.__make_key_list() self.__shift_key = self.__make_shift_key()
ciphers
def __str__(self) -> str: return "".join(self.__passcode)
ciphers
def __neg_pos(self, iterlist: list[int]) -> list[int]: for i in range(1, len(iterlist), 2): iterlist[i] *= -1 return iterlist
ciphers
def __passcode_creator(self) -> list[str]: choices = string.ascii_letters + string.digits password = [random.choice(choices) for _ in range(random.randint(10, 20))] return password
ciphers
def __make_key_list(self) -> list[str]: # key_list_options contain nearly all printable except few elements from # string.whitespace key_list_options = ( string.ascii_letters + string.digits + string.punctuation + " \t\n" ) keys_l = [] # creates points known as breakpoints to break the key_list_options at those # points and pivot each substring breakpoints = sorted(set(self.__passcode)) temp_list: list[str] = [] # algorithm for creating a new shuffled list, keys_l, out of key_list_options for i in key_list_options: temp_list.extend(i) # checking breakpoints at which to pivot temporary sublist and add it into # keys_l if i in breakpoints or i == key_list_options[-1]: keys_l.extend(temp_list[::-1]) temp_list.clear() # returning a shuffled keys_l to prevent brute force guessing of shift key return keys_l
ciphers
def __make_shift_key(self) -> int: num = sum(self.__neg_pos([ord(x) for x in self.__passcode])) return num if num > 0 else len(self.__passcode)
ciphers
def decrypt(self, encoded_message: str) -> str: decoded_message = "" # decoding shift like Caesar cipher algorithm implementing negative shift or # reverse shift or left shift for i in encoded_message: position = self.__key_list.index(i) decoded_message += self.__key_list[ (position - self.__shift_key) % -len(self.__key_list) ] return decoded_message
ciphers
def encrypt(self, plaintext: str) -> str: encoded_message = "" # encoding shift like Caesar cipher algorithm implementing positive shift or # forward shift or right shift for i in plaintext: position = self.__key_list.index(i) encoded_message += self.__key_list[ (position + self.__shift_key) % len(self.__key_list) ] return encoded_message
ciphers
def test_end_to_end(msg: str = "Hello, this is a modified Caesar cipher") -> str: cip1 = ShuffledShiftCipher() return cip1.decrypt(cip1.encrypt(msg))
ciphers
def gcd(a: int, b: int) -> int: while a != 0: a, b = b % a, a return b
ciphers
def base32_encode(string: str) -> bytes: # encoded the input (we need a bytes like object) # then, b32encoded the bytes-like object return base64.b32encode(string.encode("utf-8"))
ciphers
def base32_decode(encoded_bytes: bytes) -> str: # decode the bytes from base32 # then, decode the bytes-like object to return as a string return base64.b32decode(encoded_bytes).decode("utf-8")
ciphers
def base16_encode(data: bytes) -> str: # Turn the data into a list of integers (where each integer is a byte), # Then turn each byte into its hexadecimal representation, make sure # it is uppercase, and then join everything together and return it. return "".join([hex(byte)[2:].zfill(2).upper() for byte in list(data)])
ciphers
def base16_decode(data: str) -> bytes: # Check data validity, following RFC3548 # https://www.ietf.org/rfc/rfc3548.txt if (len(data) % 2) != 0: raise ValueError( ) # Check the character set - the standard base16 alphabet # is uppercase according to RFC3548 section 6 if not set(data) <= set("0123456789ABCDEF"): raise ValueError( ) # For every two hexadecimal digits (= a byte), turn it into an integer. # Then, string the result together into bytes, and return it. return bytes(int(data[i] + data[i + 1], 16) for i in range(0, len(data), 2))
ciphers
def main() -> None: print("Making key files...") make_key_files("rsa", 1024) print("Key files generation successful.")
ciphers
def generate_key(key_size: int) -> tuple[tuple[int, int], tuple[int, int]]: print("Generating prime p...") p = rabinMiller.generate_large_prime(key_size) print("Generating prime q...") q = rabinMiller.generate_large_prime(key_size) n = p * q print("Generating e that is relatively prime to (p - 1) * (q - 1)...") while True: e = random.randrange(2 ** (key_size - 1), 2 ** (key_size)) if cryptoMath.gcd(e, (p - 1) * (q - 1)) == 1: break print("Calculating d that is mod inverse of e...") d = cryptoMath.find_mod_inverse(e, (p - 1) * (q - 1)) public_key = (n, e) private_key = (n, d) return (public_key, private_key)
ciphers
def make_key_files(name: str, key_size: int) -> None: if os.path.exists(f"{name}_pubkey.txt") or os.path.exists(f"{name}_privkey.txt"): print("\nWARNING:") print( f'"{name}_pubkey.txt" or "{name}_privkey.txt" already exists. \n' "Use a different name or delete these files and re-run this program." ) sys.exit() public_key, private_key = generate_key(key_size) print(f"\nWriting public key to file {name}_pubkey.txt...") with open(f"{name}_pubkey.txt", "w") as out_file: out_file.write(f"{key_size},{public_key[0]},{public_key[1]}") print(f"Writing private key to file {name}_privkey.txt...") with open(f"{name}_privkey.txt", "w") as out_file: out_file.write(f"{key_size},{private_key[0]},{private_key[1]}")
ciphers
def find_primitive(n: int) -> int | None: for r in range(1, n): li = [] for x in range(n - 1): val = pow(r, x, n) if val in li: break li.append(val) else: return r return None
ciphers
def __init__(self) -> None: self.SQUARE = np.array(SQUARE)
ciphers
def letter_to_numbers(self, letter: str) -> np.ndarray: index1, index2 = np.where(letter == self.SQUARE) indexes = np.concatenate([index1 + 1, index2 + 1]) return indexes
ciphers
def numbers_to_letter(self, index1: int, index2: int) -> str: return self.SQUARE[index1 - 1, index2 - 1]
ciphers
def encode(self, message: str) -> str: message = message.lower() message = message.replace("j", "i") encoded_message = "" for letter_index in range(len(message)): if message[letter_index] != " ": numbers = self.letter_to_numbers(message[letter_index]) encoded_message = encoded_message + str(numbers[0]) + str(numbers[1]) elif message[letter_index] == " ": encoded_message = encoded_message + " " return encoded_message
ciphers
def base85_encode(string: str) -> bytes: # encoded the input to a bytes-like object and then a85encode that return base64.a85encode(string.encode("utf-8"))
ciphers
def base85_decode(a85encoded: bytes) -> str: # a85decode the input into bytes and decode that into a human readable string return base64.a85decode(a85encoded).decode("utf-8")
ciphers
def good_file_paths(top_dir: str = ".") -> Iterator[str]: for dir_path, dir_names, filenames in os.walk(top_dir): dir_names[:] = [d for d in dir_names if d != "scripts" and d[0] not in "._"] for filename in filenames: if filename == "__init__.py": continue if os.path.splitext(filename)[1] in (".py", ".ipynb"): yield os.path.join(dir_path, filename).lstrip("./")
scripts
def md_prefix(i): return f"{i * ' '}*" if i else "\n##"
scripts
def print_path(old_path: str, new_path: str) -> str: old_parts = old_path.split(os.sep) for i, new_part in enumerate(new_path.split(os.sep)): if (i + 1 > len(old_parts) or old_parts[i] != new_part) and new_part: print(f"{md_prefix(i)} {new_part.replace('_', ' ').title()}") return new_path
scripts
def print_directory_md(top_dir: str = ".") -> None: old_path = "" for filepath in sorted(good_file_paths(top_dir)): filepath, filename = os.path.split(filepath) if filepath != old_path: old_path = print_path(old_path, filepath) indent = (filepath.count(os.sep) + 1) if filepath else 0 url = "/".join((filepath, filename)).replace(" ", "%20") filename = os.path.splitext(filename.replace("_", " ").title())[0] print(f"{md_prefix(indent)} [{filename}]({url})")
scripts
def convert_path_to_module(file_path: pathlib.Path) -> ModuleType: solution_file_paths = [] for problem_dir_path in PROJECT_EULER_DIR_PATH.iterdir(): if problem_dir_path.is_file() or problem_dir_path.name.startswith("_"): continue for file_path in problem_dir_path.iterdir(): if file_path.suffix != ".py" or file_path.name.startswith(("_", "test")): continue solution_file_paths.append(file_path) return solution_file_paths
scripts
def read_file_binary(file_path: str) -> str: result = "" try: with open(file_path, "rb") as binary_file: data = binary_file.read() for dat in data: curr_byte = f"{dat:08b}" result += curr_byte return result except OSError: print("File not accessible") sys.exit()
compression
def add_key_to_lexicon( lexicon: dict[str, str], curr_string: str, index: int, last_match_id: str ) -> None: lexicon.pop(curr_string) lexicon[curr_string + "0"] = last_match_id if math.log2(index).is_integer(): for curr_key in lexicon: lexicon[curr_key] = "0" + lexicon[curr_key] lexicon[curr_string + "1"] = bin(index)[2:]
compression
def compress_data(data_bits: str) -> str: lexicon = {"0": "0", "1": "1"} result, curr_string = "", "" index = len(lexicon) for i in range(len(data_bits)): curr_string += data_bits[i] if curr_string not in lexicon: continue last_match_id = lexicon[curr_string] result += last_match_id add_key_to_lexicon(lexicon, curr_string, index, last_match_id) index += 1 curr_string = "" while curr_string != "" and curr_string not in lexicon: curr_string += "0" if curr_string != "": last_match_id = lexicon[curr_string] result += last_match_id return result
compression
def add_file_length(source_path: str, compressed: str) -> str: file_length = os.path.getsize(source_path) file_length_binary = bin(file_length)[2:] length_length = len(file_length_binary) return "0" * (length_length - 1) + file_length_binary + compressed
compression
def write_file_binary(file_path: str, to_write: str) -> None: byte_length = 8 try: with open(file_path, "wb") as opened_file: result_byte_array = [ to_write[i : i + byte_length] for i in range(0, len(to_write), byte_length) ] if len(result_byte_array[-1]) % byte_length == 0: result_byte_array.append("10000000") else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1]) - 1 ) for elem in result_byte_array: opened_file.write(int(elem, 2).to_bytes(1, byteorder="big")) except OSError: print("File not accessible") sys.exit()
compression
def compress(source_path: str, destination_path: str) -> None: data_bits = read_file_binary(source_path) compressed = compress_data(data_bits) compressed = add_file_length(source_path, compressed) write_file_binary(destination_path, compressed)
compression
def run_length_encode(text: str) -> list: encoded = [] count = 1 for i in range(len(text)): if i + 1 < len(text) and text[i] == text[i + 1]: count += 1 else: encoded.append((text[i], count)) count = 1 return encoded
compression
def run_length_decode(encoded: list) -> str: return "".join(char * length for char, length in encoded)
compression
def peak_signal_to_noise_ratio(original: float, contrast: float) -> float: mse = np.mean((original - contrast) ** 2) if mse == 0: return 100 return 20 * math.log10(PIXEL_MAX / math.sqrt(mse))
compression
def main() -> None: dir_path = os.path.dirname(os.path.realpath(__file__)) # Loading images (original image and compressed image) original = cv2.imread(os.path.join(dir_path, "image_data/original_image.png")) contrast = cv2.imread(os.path.join(dir_path, "image_data/compressed_image.png"), 1) original2 = cv2.imread(os.path.join(dir_path, "image_data/PSNR-example-base.png")) contrast2 = cv2.imread( os.path.join(dir_path, "image_data/PSNR-example-comp-10.jpg"), 1 ) # Value expected: 29.73dB print("-- First Test --") print(f"PSNR value is {peak_signal_to_noise_ratio(original, contrast)} dB") # # Value expected: 31.53dB (Wikipedia Example) print("\n-- Second Test --") print(f"PSNR value is {peak_signal_to_noise_ratio(original2, contrast2)} dB")
compression
def read_file_binary(file_path: str) -> str: result = "" try: with open(file_path, "rb") as binary_file: data = binary_file.read() for dat in data: curr_byte = f"{dat:08b}" result += curr_byte return result except OSError: print("File not accessible") sys.exit()
compression
def decompress_data(data_bits: str) -> str: lexicon = {"0": "0", "1": "1"} result, curr_string = "", "" index = len(lexicon) for i in range(len(data_bits)): curr_string += data_bits[i] if curr_string not in lexicon: continue last_match_id = lexicon[curr_string] result += last_match_id lexicon[curr_string] = last_match_id + "0" if math.log2(index).is_integer(): new_lex = {} for curr_key in list(lexicon): new_lex["0" + curr_key] = lexicon.pop(curr_key) lexicon = new_lex lexicon[bin(index)[2:]] = last_match_id + "1" index += 1 curr_string = "" return result
compression
def write_file_binary(file_path: str, to_write: str) -> None: byte_length = 8 try: with open(file_path, "wb") as opened_file: result_byte_array = [ to_write[i : i + byte_length] for i in range(0, len(to_write), byte_length) ] if len(result_byte_array[-1]) % byte_length == 0: result_byte_array.append("10000000") else: result_byte_array[-1] += "1" + "0" * ( byte_length - len(result_byte_array[-1]) - 1 ) for elem in result_byte_array[:-1]: opened_file.write(int(elem, 2).to_bytes(1, byteorder="big")) except OSError: print("File not accessible") sys.exit()
compression
def remove_prefix(data_bits: str) -> str: counter = 0 for letter in data_bits: if letter == "1": break counter += 1 data_bits = data_bits[counter:] data_bits = data_bits[counter + 1 :] return data_bits
compression
def compress(source_path: str, destination_path: str) -> None: data_bits = read_file_binary(source_path) data_bits = remove_prefix(data_bits) decompressed = decompress_data(data_bits) write_file_binary(destination_path, decompressed)
compression
def all_rotations(s: str) -> list[str]: if not isinstance(s, str): raise TypeError("The parameter s type must be str.") return [s[i:] + s[:i] for i in range(len(s))]
compression
def bwt_transform(s: str) -> BWTTransformDict: if not isinstance(s, str): raise TypeError("The parameter s type must be str.") if not s: raise ValueError("The parameter s must not be empty.") rotations = all_rotations(s) rotations.sort() # sort the list of rotations in alphabetically order # make a string composed of the last char of each rotation response: BWTTransformDict = { "bwt_string": "".join([word[-1] for word in rotations]), "idx_original_string": rotations.index(s), } return response
compression
def reverse_bwt(bwt_string: str, idx_original_string: int) -> str: if not isinstance(bwt_string, str): raise TypeError("The parameter bwt_string type must be str.") if not bwt_string: raise ValueError("The parameter bwt_string must not be empty.") try: idx_original_string = int(idx_original_string) except ValueError: raise TypeError( "The parameter idx_original_string type must be int or passive" " of cast to int." ) if idx_original_string < 0: raise ValueError("The parameter idx_original_string must not be lower than 0.") if idx_original_string >= len(bwt_string): raise ValueError( "The parameter idx_original_string must be lower than" " len(bwt_string)." ) ordered_rotations = [""] * len(bwt_string) for _ in range(len(bwt_string)): for i in range(len(bwt_string)): ordered_rotations[i] = bwt_string[i] + ordered_rotations[i] ordered_rotations.sort() return ordered_rotations[idx_original_string]
compression
def __init__(self, letter: str, freq: int): self.letter: str = letter self.freq: int = freq self.bitstring: dict[str, str] = {}
compression
def __repr__(self) -> str: return f"{self.letter}:{self.freq}"
compression
def __init__(self, freq: int, left: Letter | TreeNode, right: Letter | TreeNode): self.freq: int = freq self.left: Letter | TreeNode = left self.right: Letter | TreeNode = right
compression
def parse_file(file_path: str) -> list[Letter]: chars: dict[str, int] = {} with open(file_path) as f: while True: c = f.read(1) if not c: break chars[c] = chars[c] + 1 if c in chars else 1 return sorted((Letter(c, f) for c, f in chars.items()), key=lambda x: x.freq)
compression
def build_tree(letters: list[Letter]) -> Letter | TreeNode: response: list[Letter | TreeNode] = letters # type: ignore while len(response) > 1: left = response.pop(0) right = response.pop(0) total_freq = left.freq + right.freq node = TreeNode(total_freq, left, right) response.append(node) response.sort(key=lambda x: x.freq) return response[0]
compression
def traverse_tree(root: Letter | TreeNode, bitstring: str) -> list[Letter]: if isinstance(root, Letter): root.bitstring[root.letter] = bitstring return [root] treenode: TreeNode = root # type: ignore letters = [] letters += traverse_tree(treenode.left, bitstring + "0") letters += traverse_tree(treenode.right, bitstring + "1") return letters
compression
def huffman(file_path: str) -> None: letters_list = parse_file(file_path) root = build_tree(letters_list) letters = { k: v for letter in traverse_tree(root, "") for k, v in letter.bitstring.items() } print(f"Huffman Coding of {file_path}: ") with open(file_path) as f: while True: c = f.read(1) if not c: break print(letters[c], end=" ") print()
compression
def __repr__(self) -> str: return f"({self.offset}, {self.length}, {self.indicator})"
compression
def __init__(self, window_size: int = 13, lookahead_buffer_size: int = 6) -> None: self.window_size = window_size self.lookahead_buffer_size = lookahead_buffer_size self.search_buffer_size = self.window_size - self.lookahead_buffer_size
compression
def compress(self, text: str) -> list[Token]: output = [] search_buffer = "" # while there are still characters in text to compress while text: # find the next encoding phrase # - triplet with offset, length, indicator (the next encoding character) token = self._find_encoding_token(text, search_buffer) # update the search buffer: # - add new characters from text into it # - check if size exceed the max search buffer size, if so, drop the # oldest elements search_buffer += text[: token.length + 1] if len(search_buffer) > self.search_buffer_size: search_buffer = search_buffer[-self.search_buffer_size :] # update the text text = text[token.length + 1 :] # append the token to output output.append(token) return output
compression
def decompress(self, tokens: list[Token]) -> str: output = "" for token in tokens: for _ in range(token.length): output += output[-token.offset] output += token.indicator return output
compression
def _find_encoding_token(self, text: str, search_buffer: str) -> Token: if not text: raise ValueError("We need some text to work with.") # Initialise result parameters to default values length, offset = 0, 0 if not search_buffer: return Token(offset, length, text[length]) for i, character in enumerate(search_buffer): found_offset = len(search_buffer) - i if character == text[0]: found_length = self._match_length_from_index(text, search_buffer, 0, i) # if the found length is bigger than the current or if it's equal, # which means it's offset is smaller: update offset and length if found_length >= length: offset, length = found_offset, found_length return Token(offset, length, text[length])
compression
def _match_length_from_index( self, text: str, window: str, text_index: int, window_index: int ) -> int: if not text or text[text_index] != window[window_index]: return 0 return 1 + self._match_length_from_index( text, window + text[text_index], text_index + 1, window_index + 1 )
compression