plagiat_1.v2.py 7.9 KB

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