1
0

plagiat_1.v2.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. import os
  2. from difflib import SequenceMatcher
  3. from tqdm import tqdm
  4. import datetime
  5. import requests
  6. # download stopwords corpus, you need to run it once
  7. import nltk
  8. #nltk.download("stopwords")
  9. from nltk.corpus import stopwords
  10. import pymorphy2
  11. from string import punctuation
  12. # ------------------------------- НАСТРОЙКИ ------------
  13. # директория файла (на уровень выше, для структуры репозиториев 2 сем. 2022-23)
  14. BASE_DIR = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
  15. # проверяемая директория
  16. # LECTION_DIR = os.path.join("ISRPO", "Лекции")
  17. # LECTION_DIR = os.path.join("EASvZI", "Лекции")
  18. LECTION_DIR = os.path.join("TZI", "Лекции", "ПМ3.1")
  19. # ссылка для проверки
  20. url = "http://213.155.192.79:3001/u20-24tishkevich/TZI/raw/291428f56523c9b0d3c0955dc2b58be747f4a615/%d0%9b%d0%b5%d0%ba%d1%86%d0%b8%d0%b8/%d0%9f%d0%9c3.1/1.2.100_%d0%97%d0%b0%d0%b4%d0%b0%d1%87%d0%b8_%d0%b8_%d1%82%d1%80%d0%b5%d0%b1%d0%be%d0%b2%d0%b0%d0%bd%d0%b8%d1%8f_%d0%ba_%d1%81%d0%bf%d0%be%d1%81%d0%be%d0%b1%d0%b0%d0%bc_%d0%b8_%d1%81%d1%80%d0%b5%d0%b4%d1%81%d1%82%d0%b2%d0%b0%d0%bc_%d0%b7%d0%b0%d1%89%d0%b8%d1%82%d1%8b_%d0%b8%d0%bd%d1%84%d0%be%d1%80%d0%bc%d0%b0%d1%86%d0%b8%d0%b8_%d1%82%d0%b5%d1%85%d0%bd%d0%b8%d1%87%d0%b5%d1%81%d0%ba%d0%b8%d0%bc%d0%b8_%d1%81%d1%80%d0%b5%d0%b4%d1%81%d1%82%d0%b2%d0%b0%d0%bc%d0%b8/Tyshkevich.md"
  21. # ------------------------------- / НАСТРОЙКИ ------------
  22. #Create lemmatizer and stopwords list
  23. morph = pymorphy2.MorphAnalyzer()
  24. russian_stopwords = stopwords.words("russian")
  25. #Preprocess function
  26. def preprocess_text(text):
  27. translator = str.maketrans(punctuation, ' '*len(punctuation))
  28. words = text.translate(translator)
  29. words = words.lower().split()
  30. # очистка от прилегающего к слову мусора (слово, "или так")
  31. clear_words = []
  32. for word in words:
  33. clear_word = ""
  34. for s in word:
  35. if not s in punctuation:
  36. clear_word = clear_word + s
  37. clear_words.append(clear_word)
  38. tokens = []
  39. tokens = [morph.parse(token)[0].normal_form for token in clear_words if token not in russian_stopwords\
  40. and token != " " \
  41. and token.strip() not in punctuation \
  42. ]
  43. text = " ".join(tokens)
  44. return tokens, text
  45. print()
  46. now = datetime.datetime.now().strftime('%d-%m-%Y %H:%M')
  47. out_str = f"Время проверки: {now} \n"
  48. # print(out_str)
  49. response = requests.get(url)
  50. post_html = response.text
  51. post_list = post_html.split("\n")
  52. # проверяем правильность оформления 1й строки
  53. header_exist = True
  54. line_1 = post_list[0].strip()
  55. line_1 = line_1.replace(chr(65279), "")
  56. if (line_1[0:2]) != "# ":
  57. print(f"Заголовок статьи не найден: '{line_1[0:1]} {line_1[1:2]}' вместо '# '")
  58. print(f"{ord(line_1[0:1])} {ord(line_1[1:2])} вместо {ord('#')} {ord(' ')}")
  59. header_exist = False
  60. # наличие вопросов и списка литературы
  61. quest_exist = False
  62. source_exist = False
  63. for post_line in post_list:
  64. if (post_line[0:2] == "##"):
  65. if ("Вопросы" in post_line):
  66. quest_exist = True
  67. if ("Список" in post_line) and ("литературы" in post_line):
  68. source_exist = True
  69. if not (quest_exist):
  70. print("Вопросы не найдены")
  71. if not (source_exist):
  72. print("Список литературы не найден")
  73. header_text = line_1.replace("# ", "")
  74. header_text = header_text.replace(".", "")
  75. header_text = header_text.strip()
  76. # ищем другие лекции по этой теме
  77. readme_path = os.path.join(BASE_DIR, LECTION_DIR, "README.md")
  78. try:
  79. with open(readme_path, encoding="utf-8") as f:
  80. readme_html = f.read()
  81. except:
  82. with open(readme_path, encoding="cp1251") as f:
  83. readme_html = f.read()
  84. """
  85. █ █ █████ ███████
  86. █ █ ██ ██ ██ ██
  87. █ █ ███████ ███████
  88. █ █ ██ ██ ██ ██
  89. ██ ██ ██ ██ ██
  90. """
  91. lection_exist = False
  92. variants_exist = False
  93. in_lections = False # начало поиска вариантов
  94. readme_list = readme_html.split("\n")
  95. for readme_str in readme_list:
  96. readme_str = readme_str.strip()
  97. readme_str_list = readme_str.split(" ")
  98. lection_number = readme_str_list[0]
  99. readme_str_list.pop(0)
  100. name_str = " ".join(readme_str_list)
  101. name_str = name_str.replace(".", "")
  102. name_str = name_str.strip()
  103. if len(name_str)>0:
  104. """
  105. print(lection_number)
  106. print(name_str)
  107. print(header_text)
  108. print(f"{ord(name_str[0:1])} {ord(name_str[1:2])} {ord(name_str[2:3])} вместо {ord(header_text[0:1])} {ord(header_text[1:2])} {ord(header_text[2:3])}")
  109. print(fuzz.partial_ratio(name_str, header_text))
  110. print()
  111. """
  112. if (str(name_str).lower() == str(header_text).lower()):
  113. print("Лекция найдена в readme")
  114. lection_exist = True
  115. in_lections = True
  116. post_tokens, post_uniq_text = preprocess_text(post_html)
  117. print(f"количество уникальных слов: {len(set(post_tokens))}")
  118. print()
  119. # ищем конец списка вариантов лекций (пустая строка)
  120. if lection_exist:
  121. if (readme_str == ""):
  122. in_lections = False
  123. # следующие после названия лекции строки
  124. if in_lections and (str(name_str).lower() != str(header_text).lower()):
  125. variants_exist = True
  126. variant_name, t = readme_str.split("]")
  127. variant_name = variant_name.strip("[")
  128. print(f"проверяю {variant_name}")
  129. t, variant_uri = readme_str.split("(")
  130. variant_uri = variant_uri.replace("),", "")
  131. variant_uri = variant_uri.replace(")", "")
  132. variant_uri = variant_uri.strip()
  133. variant_path = os.path.join(BASE_DIR, LECTION_DIR, variant_uri)
  134. try:
  135. with open(variant_path, encoding="utf-8") as f:
  136. variant_html = f.read()
  137. except:
  138. with open(variant_path, encoding="cp1251") as f:
  139. variant_html = f.read()
  140. variant_tokens, variant_uniq_text = preprocess_text(variant_html)
  141. print(f"количество уникальных слов варианта: {len(set(variant_tokens))}")
  142. # пересечение множеств
  143. min_tokens_len = min([len(set(post_tokens)), len(set(variant_tokens))])
  144. c = list(set(post_tokens) & set(variant_tokens))
  145. ratio = (1 - (len(c) / min_tokens_len)) * 100
  146. print(f"количество совпадающих слов: {len(c)} / {ratio:.2f}%")
  147. print()
  148. if not(lection_exist):
  149. print("Лекция не найдена в readme")
  150. if not(variants_exist):
  151. print("Вариантов не найдено")
  152. exit()
  153. files_paths = []
  154. dirs = os.listdir(BASE_DIR)
  155. for dir in dirs:
  156. dir_path = os.path.join(BASE_DIR, dir)
  157. if os.path.isdir(dir_path) and (dir != "__pycache__"):
  158. files = os.listdir(dir_path)
  159. for file in files:
  160. file_path = os.path.join(BASE_DIR, dir, file)
  161. filename, fileext = os.path.splitext(file)
  162. if os.path.isfile(file_path) and (fileext=='.md'):
  163. files_paths.append(file_path)
  164. out_str = ""
  165. max_ratio = 0
  166. max_ratio_file = ""
  167. for file_1 in tqdm(files_paths):
  168. small_filename_1 = str(file_1).replace(BASE_DIR, "").strip("\\")
  169. try:
  170. with open(file_1, encoding="utf-8") as f_1:
  171. str1 = f_1.read()
  172. except:
  173. with open(file_1, encoding="cp1251") as f_1:
  174. str1 = f_1.read()
  175. f_1.close()
  176. with open(file_1, 'w', encoding="utf-8") as f_1:
  177. f_1.write(str1)
  178. f_1.close()
  179. ratio = int(SequenceMatcher(None, str1.lower(), post_html.lower()).ratio() * 100)
  180. if (ratio > 70):
  181. out_str += f"{small_filename_1}\n"
  182. out_str += f"ratio = {ratio}\n"
  183. if (ratio > max_ratio):
  184. max_ratio = ratio
  185. max_ratio_file = small_filename_1
  186. print(out_str)
  187. print()
  188. print(f"max ratio: {max_ratio}%")
  189. print(f"max ratio file: {max_ratio_file}")
  190. print("success")