Advertisement
Mancolo

Untitled

May 10th, 2023
691
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 10.89 KB | None | 0 0
  1. import tkinter as tk
  2. from tkinter import filedialog
  3. import re
  4. from typing import Dict
  5. import sys
  6.  
  7. # Создаем корневое окно
  8. root = tk.Tk()
  9. root.title("Decoder")
  10. # root.geometry('600x500')
  11. # root.resizable(width=False, height=False)
  12.  
  13. text1 = tk.Text(root)
  14. text1.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
  15.  
  16. # Создаем полосу прокрутки
  17. scrollbar = tk.Scrollbar(root)
  18. scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
  19.  
  20. # Привязываем полосу прокрутки к текстовому виджету
  21. text1.config(yscrollcommand=scrollbar.set)
  22. scrollbar.config(command=text1.yview)
  23.  
  24.  
  25. def create_symbols(s: str) -> list:
  26.     s = s.lower()
  27.     d = {}
  28.     tot = 0
  29.     for c in s:
  30.         if c.isalpha() and c not in "quote":
  31.             d[c] = d.get(c, 0) + 1
  32.             tot += 1
  33.  
  34.     for k in d:
  35.         d[k] /= tot * 0.01
  36.  
  37.     si = list(d.items())
  38.     si.sort(key=lambda x: -x[1])
  39.  
  40.     return si
  41.  
  42.  
  43. def check_word(word):
  44.     return ''.join(i for i in word if i.isalpha())
  45.  
  46.  
  47. def match_word(match: str, word: str) -> bool:
  48.     return all(
  49.         (match[i] == match[j]) == (word[i] == word[j]) for i in range(len(word) - 1) for j in range(i, len(word)))
  50.  
  51.  
  52. def count_words(text: str) -> tuple:
  53.     words = [check_word(w) for w in text.lower().split()]
  54.     word_dict = {}
  55.     tot = 0
  56.     for word in words:
  57.         words_same_size = word_dict.setdefault(len(word), {})
  58.         words_same_size[word] = words_same_size.get(word, 0) + 1
  59.         tot += 1
  60.  
  61.         word_dict[len(word)] = words_same_size
  62.  
  63.     for k in word_dict:
  64.         for j in word_dict[k]:
  65.             word_dict[k][j] /= tot * 0.01
  66.  
  67.     for k in word_dict:
  68.         si = list(word_dict[k].items())
  69.         si.sort(key=lambda x: -x[1])
  70.         word_dict[k] = si
  71.  
  72.     return word_dict, set(words)
  73.  
  74.  
  75. def find_words(words: list, reg: str) -> list:
  76.     return [w for w in words if re.match(reg, w)]
  77.  
  78.  
  79. def check(word: str, key: Dict) -> bool:
  80.     return any(key[k] is not None and k in word for k in key)
  81.  
  82.  
  83. def get_keys(key: Dict) -> str:
  84.     return ''.join(c for c in key if key[c] is None)
  85.  
  86.  
  87. def get_chars(key: Dict):
  88.     alph = 'абвгдеёжзийклмнопрстуфчцчшщъыьэюяңөү'
  89.     return ''.join((c for c in alph if c not in key.values()))
  90.  
  91.  
  92. def create_pattern_signs(word, key, counted_encoding_chars):
  93.     reg = ''
  94.     for s in word:
  95.         if s in key.values():
  96.             reg += list(key.keys())[list(key.values()).index(s)]
  97.         elif s in 'нкы':
  98.             reg += f'[{"".join(c[0] for c in counted_encoding_chars[1:4])}]'
  99.         else:
  100.             reg += f'[{get_keys(key)}]'
  101.     return reg + '$'
  102.  
  103.  
  104. def my_func():
  105.     file_path = filedialog.askopenfilename(
  106.         filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")]
  107.     )
  108.     if file_path:
  109.         with open(file_path, "r", encoding='utf-8') as file:
  110.             content = file.read()
  111.             # Добавляем содержимое файла в текстовый виджет
  112.             text1.delete("1.0", tk.END)
  113.             text1.insert(tk.END, content)
  114.     encoded_text = open(file_path, 'r', encoding='UTF-8').read()
  115.     sample_text = open('D:/Codes/hwPy/teory/Manas-eposu-2010-S-Karalaev.txt', 'r', encoding='UTF-8').read().replace(
  116.         'www.el-sozduk.kg', '')
  117.  
  118.     counted_chars = create_symbols(sample_text)
  119.     counted_encoding_chars = create_symbols(encoded_text)
  120.  
  121.     _, encoded_words = count_words(encoded_text)
  122.     _, sample_words = count_words(sample_text)
  123.  
  124.     # инициализация словаря ключей
  125.     key = {char[0]: None for char in counted_encoding_chars}
  126.     key[counted_encoding_chars[0][0]] = 'а'
  127.  
  128.     counted_encoding_chars_dict = dict(counted_encoding_chars)
  129.     counted_chars_dict = dict(counted_chars)
  130.  
  131.     # обновление словаря ключей на основе обязательных слов
  132.     must_words = ["каныкей", 'деп', 'бейбак']
  133.     for word in must_words:
  134.         pattern = create_pattern_signs(word, key, counted_encoding_chars)
  135.         matches = find_words(encoded_words, pattern)
  136.         if len(matches) == 1:
  137.             for i, char in enumerate(matches[0]):
  138.                 if key[char] is None:
  139.                     key[char] = word[i]
  140.  
  141.     # обновление словаря ключей на основе анализа закодированного текста
  142.     while None in key.values():
  143.         examples = []
  144.         for word in encoded_words:
  145.             if not check(word, key):
  146.                 continue
  147.             pattern = ''.join([f'[{get_chars(key)}]' if key.get(s) is None else key[s] for s in word]) + '$'
  148.             matches = [match for match in (find_words(sample_words, pattern)) if match_word(match, word)]
  149.             matches = [match for match in matches if any([s not in key.values() for s in match])]
  150.             if len(matches) == 1:
  151.                 err = sum(
  152.                     [abs(counted_encoding_chars_dict[word[i]] * 1.0 / counted_chars_dict[matches[0][i]] - 1) for i in
  153.                      range(len(matches[0])) if key[word[i]] is None]) / len(word)
  154.                 examples.append((word, matches[0], err))
  155.  
  156.         if not examples:
  157.             break
  158.         examples.sort(key=lambda x: x[2])
  159.         for i, char in enumerate(examples[0][0]):
  160.             if key[char] is None and examples[0][1][i] not in key.values():
  161.                 key[char] = examples[0][1][i]
  162.  
  163.     text = ''
  164.     for w in encoded_text:
  165.         w = w.lower()
  166.         if w.isalpha():
  167.             text += key[w] if key.get(w, None) is not None else 'X'
  168.         else:
  169.             text += w
  170.     output_text.insert('end', f'{text}')
  171.  
  172. # def create_text_widget(parent):
  173. #     # create a text widget with vertical scrollbar
  174. #     text_widget = tk.Text(parent)
  175. #     scrollbar = tk.Scrollbar(parent)
  176. #     scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
  177. #     text_widget.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True)
  178. #     text_widget.config(yscrollcommand=scrollbar.set)
  179. #     scrollbar.config(command=text_widget.yview)
  180. #     return text_widget
  181. #
  182. #
  183. # def create_output_widget(parent):
  184. #     # create a text widget with vertical scrollbar
  185. #     output_widget = tk.Text(parent)
  186. #     scrollbar = tk.Scrollbar(parent)
  187. #     scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
  188. #     output_widget.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
  189. #     output_widget.config(yscrollcommand=scrollbar.set)
  190. #     scrollbar.config(command=output_widget.yview)
  191. #
  192. #     def decode_text():
  193. #         sample_text = open('D:/Codes/hwPy/teory/Manas-eposu-2010-S-Karalaev.txt', 'r', encoding='UTF-8').read().replace(
  194. #             'www.el-sozduk.kg', '')
  195. #
  196. #         counted_chars = create_symbols(sample_text)
  197. #         counted_encoding_chars = create_symbols(encoded_text)
  198. #
  199. #         _, encoded_words = count_words(encoded_text)
  200. #         _, sample_words = count_words(sample_text)
  201. #
  202. #         # инициализация словаря ключей
  203. #         key = {char[0]: None for char in counted_encoding_chars}
  204. #         key[counted_encoding_chars[0][0]] = 'а'
  205. #
  206. #         counted_encoding_chars_dict = dict(counted_encoding_chars)
  207. #         counted_chars_dict = dict(counted_chars)
  208. #
  209. #         # обновление словаря ключей на основе обязательных слов
  210. #         must_words = ["каныкей", 'деп', 'бейбак']
  211. #         for word in must_words:
  212. #             pattern = create_pattern_signs(word, key, counted_encoding_chars)
  213. #             matches = find_words(encoded_words, pattern)
  214. #             if len(matches) == 1:
  215. #                 for i, char in enumerate(matches[0]):
  216. #                     if key[char] is None:
  217. #                         key[char] = word[i]
  218. #
  219. #         # обновление словаря ключей на основе анализа закодированного текста
  220. #         while None in key.values():
  221. #             examples = []
  222. #             for word in encoded_words:
  223. #                 if not check(word, key):
  224. #                     continue
  225. #                 pattern = ''.join([f'[{get_chars(key)}]' if key.get(s) is None else key[s] for s in word]) + '$'
  226. #                 matches = [match for match in (find_words(sample_words, pattern)) if match_word(match, word)]
  227. #                 matches = [match for match in matches if any([s not in key.values() for s in match])]
  228. #                 if len(matches) == 1:
  229. #                     err = sum(
  230. #                         [abs(counted_encoding_chars_dict[word[i]] * 1.0 / counted_chars_dict[matches[0][i]] - 1) for i
  231. #                          in
  232. #                          range(len(matches[0])) if key[word[i]] is None]) / len(word)
  233. #                     examples.append((word, matches[0], err))
  234. #
  235. #             if not examples:
  236. #                 break
  237. #             examples.sort(key=lambda x: x[2])
  238. #             for i, char in enumerate(examples[0][0]):
  239. #                 if key[char] is None and examples[0][1][i] not in key.values():
  240. #                     key[char] = examples[0][1][i]
  241. #
  242. #         text = ''
  243. #         for w in encoded_text:
  244. #             w = w.lower()
  245. #             if w.isalpha():
  246. #                 text += key[w] if key.get(w, None) is not None else 'X'
  247. #             else:
  248. #                 text += w
  249. #         return text
  250. #
  251. #     def print_text():
  252. #         text = text_widget.get("1.0", tk.END)
  253. #         update_text(text)
  254. #     def decode():
  255. #         output_text.delete("1.0", tk.END)
  256. #         text = text_widget.get("1.0", tk.END)
  257. #         decoded_text = decode_text(text)
  258. #         output_text.insert(tk.END, decoded_text)
  259. #
  260. #     decode_button = tk.Button(parent, text="Decode", command=decode)
  261. #     decode_button.pack()
  262. #     output_text = create_text_widget(parent)
  263. #     return output_text
  264. #
  265. # output_widget, update_output_text = create_output_widget(root)
  266. #
  267. # def update_text(text):
  268. #     output_widget.delete("1.0", tk.END)
  269. #     output_widget.insert(tk.END, text)
  270. #
  271. #
  272. #
  273. # decode_button = tk.Button(root, text="Decode", command=create_output_widget)
  274. # decode_button.pack()
  275. # text_widget = create_text_widget(root)
  276.  
  277. def display_func():
  278.     output = tk.Text(root, height=40, width=80)
  279.     output.pack()
  280.     my_func(output)
  281.  
  282.     # перенаправляем стандартный вывод в текстовый виджет
  283.     sys.stdout = output
  284.  
  285.     # вызываем функцию my_func
  286.     my_func()
  287.  
  288.     # возвращаем стандартный вывод на место
  289.     sys.stdout = sys.__stdout__
  290.  
  291. # текстовое поле для вывода
  292. output_text = tk.Text(root, height=20, width=80)
  293. output_text.pack()
  294.  
  295. # добавляем кнопку для дешифровки
  296. decrypt_button = tk.Button(root, text="Choose your file", command=my_func)
  297. decrypt_button.pack(pady=10)
  298.  
  299. # Запускаем главный цикл окна
  300. root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement