plagiat_1.v3.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. # версия полной проверки с проверкой русской орфографии
  2. import os
  3. from difflib import SequenceMatcher
  4. from tqdm import tqdm
  5. import datetime
  6. import requests
  7. # download stopwords corpus, you need to run it once
  8. import nltk
  9. #nltk.download("stopwords")
  10. from nltk.corpus import stopwords
  11. import pymorphy2
  12. from string import punctuation
  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("EASvZI", "Лекции")
  18. # ссылка для проверки
  19. url = "http://213.155.192.79:3001/u22-26shishkova/EASvZI36/src/713aa32976783477f61de2e20e35068495d9f4fa/%d0%9b%d0%b5%d0%ba%d1%86%d0%b8%d0%b8/2.2.600_%d0%9c%d0%b5%d1%82%d0%be%d0%b4%d1%8b_%d1%81%d0%bf%d0%be%d1%81%d0%be%d0%b1%d1%8b_%d1%81%d1%80%d0%b5%d0%b4%d1%81%d1%82%d0%b2%d0%b0_%d0%be%d0%b1%d0%b5%d1%81%d0%bf%d0%b5%d1%87%d0%b5%d0%bd%d0%b8%d1%8f_%d0%be%d1%82%d0%ba%d0%b0%d0%b7%d0%be%d1%83%d1%81%d1%82%d0%be%d0%b9%d1%87%d0%b8%d0%b2%d0%be%d1%81%d1%82%d0%b8/%d0%94%d0%be%d0%ba%d0%bb%d0%b0%d0%b4%d0%a8%d0%b8%d1%88%d0%ba%d0%be%d0%b2%d0%b0"
  20. # ------------------------------- / НАСТРОЙКИ ------------
  21. url = url.replace("src", "raw")
  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. #Preprocess function
  46. import language_tool_python
  47. tool = language_tool_python.LanguageTool('ru-RU')
  48. def orfo_text(tokens):
  49. bad_tokens_n = 0
  50. for token in tokens:
  51. matches = tool.check(token)
  52. if len(matches)>0:
  53. bad_tokens_n += 1
  54. #print(matches[0].ruleId)
  55. return bad_tokens_n
  56. print()
  57. now = datetime.datetime.now().strftime('%d-%m-%Y %H:%M')
  58. out_str = f"Время проверки: {now} \n"
  59. # print(out_str)
  60. response = requests.get(url)
  61. post_html = response.text
  62. post_list = post_html.split("\n")
  63. # проверяем правильность оформления 1й строки
  64. header_exist = True
  65. line_1 = post_list[0].strip()
  66. line_1 = line_1.replace(chr(65279), "")
  67. if (line_1[0:2]) != "# ":
  68. print(f"Заголовок статьи не найден: '{line_1[0:1]} {line_1[1:2]}' вместо '# '")
  69. print(f"{ord(line_1[0:1])} {ord(line_1[1:2])} вместо {ord('#')} {ord(' ')}")
  70. header_exist = False
  71. # наличие вопросов и списка литературы
  72. quest_exist = False
  73. source_exist = False
  74. for post_line in post_list:
  75. if (post_line[0:2] == "##"):
  76. if ("Вопросы" in post_line):
  77. quest_exist = True
  78. if ("Список" in post_line) and ("литературы" in post_line):
  79. source_exist = True
  80. if not (quest_exist):
  81. print("Вопросы не найдены")
  82. if not (source_exist):
  83. print("Список литературы не найден")
  84. header_text = line_1.replace("# ", "")
  85. header_text = header_text.replace(".", "")
  86. header_text = header_text.strip()
  87. header_text = header_text.strip()
  88. print(f"Заголовок: {header_text}")
  89. # ищем другие лекции по этой теме
  90. readme_path = os.path.join(BASE_DIR, LECTION_DIR, "README.md")
  91. try:
  92. with open(readme_path, encoding="utf-8") as f:
  93. readme_html = f.read()
  94. except:
  95. with open(readme_path, encoding="cp1251") as f:
  96. readme_html = f.read()
  97. """
  98. █ █ █████ ███████
  99. █ █ ██ ██ ██ ██
  100. █ █ ███████ ███████
  101. █ █ ██ ██ ██ ██
  102. ██ ██ ██ ██ ██
  103. """
  104. lection_exist = False
  105. variants_exist = False
  106. in_lections = False # начало поиска вариантов
  107. readme_list = readme_html.split("\n")
  108. for readme_str in readme_list:
  109. readme_str = readme_str.strip()
  110. readme_str_list = readme_str.split(" ")
  111. lection_number = readme_str_list[0]
  112. readme_str_list.pop(0)
  113. name_str = " ".join(readme_str_list)
  114. name_str = name_str.replace(".", "")
  115. name_str = name_str.strip()
  116. if len(name_str)>0:
  117. """
  118. print(lection_number)
  119. print(name_str)
  120. print(header_text)
  121. #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])}")
  122. #print(fuzz.partial_ratio(name_str, header_text))
  123. print()
  124. """
  125. if (str(name_str).lower() == str(header_text).lower()):
  126. print("Лекция найдена в readme")
  127. lection_exist = True
  128. in_lections = True
  129. post_tokens, post_uniq_text = preprocess_text(post_html)
  130. print(f"количество уникальных слов: {len(set(post_tokens))}")
  131. bad_tokens_n = orfo_text(post_tokens)
  132. bad_tokens_stat = int(bad_tokens_n / len(post_tokens) * 10000) / 100
  133. print(f"процент ошибок: {bad_tokens_stat}%")
  134. print()
  135. # ищем конец списка вариантов лекций (пустая строка)
  136. if lection_exist:
  137. if (readme_str == ""):
  138. in_lections = False
  139. # следующие после названия лекции строки
  140. if in_lections and (str(name_str).lower() != str(header_text).lower()):
  141. variants_exist = True
  142. variant_name, t = readme_str.split("]")
  143. variant_name = variant_name.strip("[")
  144. print(f"проверяю {variant_name}")
  145. t, variant_uri = readme_str.split("(")
  146. variant_uri = variant_uri.replace("),", "")
  147. variant_uri = variant_uri.replace(");", "")
  148. variant_uri = variant_uri.replace(")", "")
  149. variant_uri = variant_uri.strip()
  150. if ("youtube" in variant_uri) or ("habr" in variant_uri):
  151. print("external link - не проверяем")
  152. print()
  153. else:
  154. variant_path = os.path.join(BASE_DIR, LECTION_DIR, variant_uri)
  155. try:
  156. with open(variant_path, encoding="utf-8") as f:
  157. variant_html = f.read()
  158. except:
  159. with open(variant_path, encoding="cp1251") as f:
  160. variant_html = f.read()
  161. variant_tokens, variant_uniq_text = preprocess_text(variant_html)
  162. print(f"количество уникальных слов варианта: {len(set(variant_tokens))}")
  163. # пересечение множеств
  164. min_tokens_len = min([len(set(post_tokens)), len(set(variant_tokens))])
  165. c = list(set(post_tokens) & set(variant_tokens))
  166. ratio = (1 - (len(c) / min_tokens_len)) * 100
  167. print(f"количество совпадающих слов: {len(c)}")
  168. print(f"уникальность: {ratio:.2f}%")
  169. print()
  170. print()
  171. if not(lection_exist):
  172. print("Лекция не найдена в readme")
  173. if not(variants_exist):
  174. print("Вариантов не найдено")
  175. exit()
  176. files_paths = []
  177. dirs = os.listdir(BASE_DIR)
  178. for dir in dirs:
  179. dir_path = os.path.join(BASE_DIR, dir)
  180. if os.path.isdir(dir_path) and (dir != "__pycache__"):
  181. files = os.listdir(dir_path)
  182. for file in files:
  183. file_path = os.path.join(BASE_DIR, dir, file)
  184. filename, fileext = os.path.splitext(file)
  185. if os.path.isfile(file_path) and (fileext=='.md'):
  186. files_paths.append(file_path)
  187. out_str = ""
  188. max_ratio = 0
  189. max_ratio_file = ""
  190. for file_1 in tqdm(files_paths):
  191. small_filename_1 = str(file_1).replace(BASE_DIR, "").strip("\\")
  192. try:
  193. with open(file_1, encoding="utf-8") as f_1:
  194. str1 = f_1.read()
  195. except:
  196. with open(file_1, encoding="cp1251") as f_1:
  197. str1 = f_1.read()
  198. f_1.close()
  199. with open(file_1, 'w', encoding="utf-8") as f_1:
  200. f_1.write(str1)
  201. f_1.close()
  202. ratio = int(SequenceMatcher(None, str1.lower(), post_html.lower()).ratio() * 100)
  203. if (ratio > 70):
  204. out_str += f"{small_filename_1}\n"
  205. out_str += f"ratio = {ratio}\n"
  206. if (ratio > max_ratio):
  207. max_ratio = ratio
  208. max_ratio_file = small_filename_1
  209. print(out_str)
  210. print()
  211. print(f"max ratio: {max_ratio}%")
  212. print(f"max ratio file: {max_ratio_file}")
  213. print("success")