1
0

plagiat_1.v2.py 7.7 KB

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