61 lines
1.7 KiB
Python
61 lines
1.7 KiB
Python
import enum
|
|
|
|
|
|
class CodingType(enum.Enum):
|
|
balls: str = "balls"
|
|
shevkan: str = "shevkan"
|
|
|
|
|
|
def guess_coding(text: str) -> CodingType:
|
|
|
|
if "человек" in text:
|
|
return CodingType.balls
|
|
else:
|
|
return CodingType.shevkan
|
|
|
|
|
|
def encode_balls(text: str) -> str:
|
|
binary = ''.join(format(byte, '08b') for byte in text.encode('utf-8'))
|
|
encoded = ' '.join("человек" if bit == '0' else "яйца" for bit in binary)
|
|
return encoded
|
|
|
|
|
|
def decode_balls(encoded: str) -> str:
|
|
words = encoded.split()
|
|
binary = ''.join('0' if word == "человек" else '1' for word in words)
|
|
try:
|
|
bytes_list = [binary[i:i + 8] for i in range(0, len(binary), 8)]
|
|
decoded_bytes = bytes(int(b, 2) for b in bytes_list if len(b) == 8)
|
|
return decoded_bytes.decode('utf-8')
|
|
except (ValueError, UnicodeDecodeError):
|
|
return "Decode error :<"
|
|
|
|
|
|
SHEVKAN_ALPHABET = ("йов", "Шевкан", "кіть", "ош", "укладати", "зватиня", "айно", "файно")
|
|
|
|
def to_base8_custom(num, digits=SHEVKAN_ALPHABET):
|
|
if num == 0:
|
|
return digits[0]
|
|
result = []
|
|
while num:
|
|
result.append(digits[num % 8])
|
|
num //= 8
|
|
return " ".join(result[::-1])
|
|
|
|
def from_base8_custom(base8_str, digits=SHEVKAN_ALPHABET):
|
|
num = 0
|
|
for char in base8_str.split(" "):
|
|
num = num * 8 + digits.index(char)
|
|
return num
|
|
|
|
def encode_shevkan(text):
|
|
encoded = text.encode("utf-8")
|
|
num = int.from_bytes(encoded, byteorder="big")
|
|
return to_base8_custom(num)
|
|
|
|
def decode_shevkan(base8_str):
|
|
num = from_base8_custom(base8_str.strip())
|
|
byte_length = (num.bit_length() + 7) // 8
|
|
bytes_data = num.to_bytes(byte_length, byteorder="big")
|
|
return bytes_data.decode("utf-8")
|
|
|