1
0

plagiat_1.v2.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  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("ЭАСвЗИ", "Лекции")
  17. LECTION_DIR = os.path.join("ТЗИ", "Лекции", "ПМ3.2")
  18. # кого проверяем
  19. who = "Савкин"
  20. # ссылка для проверки
  21. url = "http://213.155.192.79:3001/ypv/up/src/master/%D0%A2%D0%97%D0%98/%D0%9B%D0%B5%D0%BA%D1%86%D0%B8%D0%B8/%D0%9F%D0%9C3.2/1.1.200_%D0%A1%D0%BE%D0%B4%D0%B5%D1%80%D0%B6%D0%B0%D0%BD%D0%B8%D0%B5_%D0%B8_%D0%B7%D0%B0%D0%B4%D0%B0%D1%87%D0%B8_%D1%84%D0%B8%D0%B7%D0%B8%D1%87%D0%B5%D1%81%D0%BA%D0%BE%D0%B9_%D0%B7%D0%B0%D1%89%D0%B8%D1%82%D1%8B_%D0%BE%D0%B1%D1%8A%D0%B5%D0%BA%D1%82%D0%BE%D0%B2_%D0%B8%D0%BD%D1%84%D0%BE%D1%80%D0%BC%D0%B0%D1%82%D0%B8%D0%B7%D0%B0%D1%86%D0%B8%D0%B8/README.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"Проверка: {who}, время проверки: {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. line_1 = post_list[0]
  55. if (line_1[0]) != "#":
  56. print("Заголовок статьи не найден")
  57. # наличие вопросов и списка литературы
  58. quest_exist = False
  59. source_exist = False
  60. for post_line in post_list:
  61. if (post_line[0:1] == "##"):
  62. if ("Вопросы" in post_line):
  63. quest_exist = True
  64. if ("Список литературы" in post_line):
  65. source_exist = True
  66. if not (quest_exist):
  67. print("Вопросы не найдены")
  68. if not (source_exist):
  69. print("Список литературы не найден")
  70. header_text = line_1.replace("# ", "")
  71. header_text = header_text.replace(".", "")
  72. header_text = header_text.strip()
  73. # ищем другие лекции по этой теме
  74. readme_path = os.path.join(BASE_DIR, LECTION_DIR, "README.md")
  75. try:
  76. with open(readme_path, encoding="utf-8") as f:
  77. readme_html = f.read()
  78. except:
  79. with open(readme_path, encoding="cp1251") as f:
  80. readme_html = f.read()
  81. lection_exist = False
  82. readme_list = readme_html.split("\n")
  83. for readme_str in readme_list:
  84. readme_str = readme_str.strip()
  85. readme_str_list = readme_str.split(" ")
  86. readme_str_list.pop(0)
  87. name_str = " ".join(readme_str_list)
  88. name_str = name_str.replace(".", "")
  89. if (str(name_str) == str(header_text)):
  90. print("Лекция найдена")
  91. lection_exist = True
  92. post_tokens, post_uniq_text = preprocess_text(post_html)
  93. print(f"количество уникальных слов: {len(set(post_tokens))}")
  94. print()
  95. # ищем конец списка вариантов лекций (пустая строка)
  96. if lection_exist:
  97. if (readme_str == ""):
  98. lection_exist = False
  99. # следующие после названия лекции строки
  100. if lection_exist and (str(name_str) != str(header_text)):
  101. variant_name, t = readme_str.split("]")
  102. variant_name = variant_name.strip("[")
  103. print(f"проверяю {variant_name}")
  104. t, variant_uri = readme_str.split("(")
  105. variant_uri = variant_uri.replace("),", "")
  106. variant_uri = variant_uri.strip()
  107. variant_path = os.path.join(BASE_DIR, LECTION_DIR, variant_uri)
  108. try:
  109. with open(variant_path, encoding="utf-8") as f:
  110. variant_html = f.read()
  111. except:
  112. with open(variant_path, encoding="cp1251") as f:
  113. variant_html = f.read()
  114. variant_tokens, variant_uniq_text = preprocess_text(variant_html)
  115. print(f"количество уникальных слов варианта: {len(set(variant_tokens))}")
  116. # пересечение множеств
  117. c = list(set(post_tokens) & set(variant_tokens))
  118. ratio = 1 - (len(c) / len(set(post_tokens)))
  119. print(f"количество совпадающих слов: {len(c)} / {ratio}%")
  120. print()
  121. if not(lection_exist):
  122. print("Лекция не найдена в списке")
  123. exit()
  124. files_paths = []
  125. dirs = os.listdir(BASE_DIR)
  126. for dir in dirs:
  127. dir_path = os.path.join(BASE_DIR, dir)
  128. if os.path.isdir(dir_path) and (dir != "__pycache__"):
  129. files = os.listdir(dir_path)
  130. for file in files:
  131. file_path = os.path.join(BASE_DIR, dir, file)
  132. filename, fileext = os.path.splitext(file)
  133. if os.path.isfile(file_path) and (fileext=='.md'):
  134. files_paths.append(file_path)
  135. out_str = ""
  136. max_ratio = 0
  137. max_ratio_file = ""
  138. for file_1 in tqdm(files_paths):
  139. small_filename_1 = str(file_1).replace(BASE_DIR, "").strip("\\")
  140. try:
  141. with open(file_1, encoding="utf-8") as f_1:
  142. str1 = f_1.read()
  143. except:
  144. with open(file_1, encoding="cp1251") as f_1:
  145. str1 = f_1.read()
  146. f_1.close()
  147. with open(file_1, 'w', encoding="utf-8") as f_1:
  148. f_1.write(str1)
  149. f_1.close()
  150. ratio = int(SequenceMatcher(None, str1.lower(), post_html.lower()).ratio() * 100)
  151. if (ratio > 70):
  152. out_str += f"{small_filename_1}\n"
  153. out_str += f"ratio = {ratio}\n"
  154. if (ratio > max_ratio):
  155. max_ratio = ratio
  156. max_ratio_file = small_filename_1
  157. print(out_str)
  158. print()
  159. print(f"max ratio: {max_ratio}%")
  160. print(f"max ratio file: {max_ratio_file}")
  161. print("success")