lolimoska

Untitled

Jun 15th, 2021
36
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 11.36 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. import tabula
  4. from datetime import datetime
  5. import csv
  6. import requests
  7. from pyunpack import Archive
  8. from pdf2jpg import pdf2jpg
  9. import os
  10. import shutil
  11. import io
  12. from pdfminer.converter import TextConverter
  13. from pdfminer.pdfinterp import PDFPageInterpreter
  14. from pdfminer.pdfinterp import PDFResourceManager
  15. from pdfminer.pdfpage import PDFPage
  16. import telebot
  17. import cv2
  18. import numpy as np
  19.  
  20. bot = telebot.TeleBot('')
  21. keyboard = telebot.types.ReplyKeyboardMarkup(True)
  22. keyboard.row('Расписание','Кабинеты')
  23.  
  24.  
  25. spisok = [
  26. {'1': '', '2': 'Горбачева А. В. (Введение в специальность)','3': 'Горбачева Н. Ф. (Химия)', '4': 'Сорокина Д. А. (Биология)','5':'','6': ''},
  27. {'1': 'Солодкая Т. И. (Математика)', '2': 'Сычева В. Ю. (Астрономия)','3': 'Харитонова М. В. (Физическая культура)','4':'','5': '','6': ''},
  28. {'1': 'Попова С. А. (Литература)', '2': 'Сафарова Л. В. (Информатика)','3': 'Солодкая Т. И. (Математика)','4': '','5': '','6': ''},
  29. {'1': '', '2': 'Солодкая Т. И. (Математика)','3': 'Макаров А. А. (Обществознание)','4': 'Вьюгов/Алиева (Иностранный язык)','5': 'Попова С. А. (Литература)','6': ''},
  30. {'1': '', '2': '','3': 'Константинова Н. В. (Физика)','4': 'Макаров А. А. (Обществознание)','5': '','6': ''},
  31. {'1': '', '2': '','3': 'Спирина Н. В. (История)','4': 'Вьюгов/Алиева (Иностранный язык)','5': '','6': ''},
  32. {'1': '', '2': 'Горбачева А. В. (Введение в специальность)', '3': 'Горбачева Н. Ф. (Химия)','4': 'Сорокина Д. А. (Биология)', '5': 'Горбачева А. В. (Введение в специальность)', '6': ''},
  33. {'1': 'Солодкая Т. И. (Математика)', '2': 'Сычева В. Ю. (Астрономия)','3': 'Харитонова М. В. (Физическая культура)', '4': 'Попова С. А. (Литература)', '5': '', '6': ''},
  34. {'1': 'Попова С. А. (Литература)', '2': 'Сафарова Л. В. (Информатика)', '3': 'Солодкая Т. И. (Математика)', '4': '','5': '', '6': ''},
  35. {'1': '', '2': 'Солодкая Т. И. (Математика)', '3': 'Макаров А. А. (Обществознание)','4': 'Вьюгов/Алиева (Иностранный язык)', '5': 'Попова С. А. (Литература)', '6': ''},
  36. {'1': '', '2': '', '3': 'Константинова Н. В. (Физика)', '4': 'Харитонова М. В. (Физическая культура)', '5': '', '6': ''},
  37. {'1': '', '2': '', '3': 'Спирина Н. В. (История)', '4': 'Спирина Н. В. (История)', '5': '', '6': ''},
  38. ]
  39.  
  40. def send(id,text):
  41. bot.send_message(id,str(text),reply_markup=keyboard)
  42.  
  43. def raspisanieOK():
  44. global raspis
  45. Archive('zameni.rar').extractall('')
  46. def extract_text_from_pdf(pdf_path):
  47. resource_manager = PDFResourceManager()
  48. fake_file_handle = io.StringIO()
  49. converter = TextConverter(resource_manager, fake_file_handle)
  50. page_interpreter = PDFPageInterpreter(resource_manager, converter)
  51. with open(pdf_path, 'rb') as fh:
  52. for page in PDFPage.get_pages(fh,
  53. caching=True,
  54. check_extractable=True):
  55. page_interpreter.process_page(page)
  56. text = fake_file_handle.getvalue()
  57. # close open handles
  58. converter.close()
  59. fake_file_handle.close()
  60. if text:
  61. return text
  62.  
  63. if __name__=='__main__':
  64. text = (extract_text_from_pdf('Замены/' + os.listdir("Замены")[int(len(os.listdir("Замены"))) - 1]))
  65. if 'ЗНАМЕНАТЕЛЬ' in text:
  66. znam = 1
  67. else:
  68. znam = 0
  69. # сортировка пар
  70. date = datetime.today().weekday() + 1 # получение завтрашнего дня
  71. if znam==1: # если знаменатель то
  72. date + 6
  73. para1 = '1) ' + spisok[date]['1']
  74. para2 = '2) ' + spisok[date]['2']
  75. para3 = '3) ' + spisok[date]['3']
  76. para4 = '4) ' + spisok[date]['4']
  77. para5 = '5) ' + spisok[date]['5']
  78. para6 = '6) ' + spisok[date]['6']
  79. df = tabula.read_pdf('Замены/16.06.2021.pdf', pages='all')[0]
  80. tabula.convert_into("Замены/16.06.2021.pdf", "zamen.csv", output_format="csv", pages='all')
  81. with open('zamen.csv') as csv_file:
  82. csv_reader = csv.reader(csv_file, delimiter=',')
  83. line_count = 0
  84. for row in csv_reader:
  85. if 'д' not in row[1]:
  86. if '12 г' in row[1] or '12г' in row[1]:
  87. print('Пара', row[0], 'Заменить ', row[2], 'на', row[3])
  88. if row[0]=='I':
  89. para1 = '1) ' + row[3].replace("\n", " ")
  90. if row[0]=='II':
  91. para2 = '2) ' + row[3].replace("\n", " ")
  92. if row[0]=='III':
  93. para3 = '3) ' + row[3].replace("\n", " ")
  94. if row[0]=='IV':
  95. para4 = '4) ' + row[3].replace("\n", " ")
  96. if row[0]=='V':
  97. para5 = '5) ' + row[3].replace("\n", " ")
  98. if row[0]=='VI':
  99. para6 = '6) ' + row[3].replace("\n", " ")
  100. raspis = ('' + para1 + '\n' + para2 + '\n' + para3 + '\n' + para4 + '\n' + para5 + '\n' + para6)
  101. print(raspis)
  102.  
  103. def raspisanieCabin():
  104. global raspis
  105. # скачка
  106. API_ENDPOINT = 'https://cloud-api.yandex.net/v1/disk/public/resources/download?public_key={}'
  107. def _get_real_direct_link(sharing_link):
  108. pk_request = requests.get(API_ENDPOINT.format(sharing_link))
  109. return pk_request.json().get('href')
  110. def download_yadisk_link(sharing_link, filename):
  111. direct_link = _get_real_direct_link(sharing_link)
  112. if direct_link:
  113. # Try to recover the filename from the link
  114. download = requests.get(direct_link)
  115. with open(filename, 'wb') as out_file:
  116. out_file.write(download.content)
  117. print('ok')
  118. else:
  119. print('neok')
  120.  
  121. download_yadisk_link('https://disk.yandex.ru/d/YP2Zp9ysrLye7Q','cabinets.rar')
  122.  
  123. def raspisanie():
  124. global raspis
  125. # скачка
  126. API_ENDPOINT = 'https://cloud-api.yandex.net/v1/disk/public/resources/download?public_key={}'
  127. def _get_real_direct_link(sharing_link):
  128. pk_request = requests.get(API_ENDPOINT.format(sharing_link))
  129. return pk_request.json().get('href')
  130. def download_yadisk_link(sharing_link, filename):
  131. direct_link = _get_real_direct_link(sharing_link)
  132. if direct_link:
  133. # Try to recover the filename from the link
  134. download = requests.get(direct_link)
  135. with open(filename, 'wb') as out_file:
  136. out_file.write(download.content)
  137. raspisanieOK()
  138. else:
  139. raspis = '⛔Замен ещё нет⛔'
  140.  
  141. download_yadisk_link('https://disk.yandex.ru/d/FBIhy2KSHPDSng','zameni.rar')
  142. raspisanieOK()
  143.  
  144. def cabinet():
  145. raspisanieCabin()
  146. Archive('cabinets.rar').extractall('')
  147.  
  148. result = pdf2jpg.convert_pdf2jpg(('Расписание/' + os.listdir("Расписание")[int(len(os.listdir("Расписание"))) - 1]),
  149. os.path.abspath(os.curdir), dpi=120, pages="ALL")
  150. day = int(datetime.strftime(datetime.now(), "%d"));
  151. otherDate = str(datetime.strftime(datetime.now(), "%m.%Y"));
  152. nameFile = str(int(day) + 1) + '.' + otherDate
  153. print('Расписание по кабинетам среда ' + str(day + 1) + '.' + str(
  154. otherDate) + '.pdf/0_Расписание по кабинетам среда ' + str(day + 1) + '.' + str(otherDate) + '.pdf.jpg')
  155. shutil.move(r'Расписание по кабинетам среда ' + str(day + 1) + '.' + str(
  156. otherDate) + '.pdf_dir/0_Расписание по кабинетам среда ' + str(day + 1) + '.' + str(otherDate) + '.pdf.jpg',
  157. os.path.abspath(os.curdir))
  158. os.rename('0_Расписание по кабинетам среда ' + str(day + 1) + '.' + str(otherDate) + '.pdf.jpg', "Raspis.png")
  159.  
  160. img_rgb = cv2.imread('Raspis.png')
  161. template = cv2.imread('1.png')
  162. w, h = template.shape[:-1]
  163. res = cv2.matchTemplate(img_rgb, template, cv2.TM_CCOEFF_NORMED)
  164. threshold = .9
  165. loc = np.where(res >= threshold)
  166. for pt in zip(*loc[::-1]): # Switch collumns and rows
  167. cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0, 0, 255), 2)
  168. cv2.imwrite('raspisWithView ' + str(day + 1) + '.' + str(otherDate) + '.png', img_rgb)
  169.  
  170. shutil.rmtree(r'Расписание')
  171. shutil.rmtree(r'Расписание по кабинетам среда ' + str(day + 1) + '.' + str(otherDate) + '.pdf_dir')
  172. os.remove(r'Raspis.png')
  173. os.remove(r'cabinets.rar')
  174.  
  175.  
  176. @bot.message_handler(commands = ['start'])
  177. def answer(message):
  178. send(message.chat.id, 'Гениальный бот по расписанию')
  179. @bot.message_handler(content_types=['text','photo'])
  180. def main(message):
  181. global raspis
  182. id = message.chat.id
  183. msg = message.text
  184. if msg == 'Расписание':
  185. send(id, 'Ща напишу')
  186. day = str(datetime.strftime(datetime.now(), "%d"))
  187. otherDate = str(datetime.strftime(datetime.now(), "%m.%Y"))
  188. nameFile = str(int(day) + 1) + '.' + otherDate
  189. if os.path.isfile(str(nameFile)+'.txt')==True:
  190. with open(str(nameFile) + '.txt') as f:
  191. raspis = f.read()
  192. send(id,day+'.'+otherDate+'\n'+raspis)
  193. else:
  194.  
  195. if os.path.isfile('Замены')==True:
  196. shutil.rmtree(r'Замены')
  197. if os.path.isfile('zameni.rar')==True:
  198. os.remove(r'zameni.rar')
  199. if os.path.isfile('zamen.csv')==True:
  200. os.remove(r'zamen.csv')
  201.  
  202. raspisanie()
  203.  
  204. day = str(datetime.strftime(datetime.now(), "%d"))
  205. otherDate = str(datetime.strftime(datetime.now(), "%m.%Y"))
  206. send(id,day+'.'+otherDate+'\n'+raspis) # сообщение
  207. nameFile = str(int(day) + 1) + '.' + otherDate
  208. f = open(str(nameFile) + '.txt', 'w')
  209. f.write(raspis)
  210. f.close()
  211.  
  212.  
  213. elif msg == 'Кабинеты':
  214. send(id, 'Ща найду')
  215. day = str(datetime.strftime(datetime.now(), "%d"))
  216. otherDate = str(datetime.strftime(datetime.now(), "%m.%Y"))
  217. nameFile = str(int(day) + 1) + '.' + otherDate
  218. if os.path.isfile('raspisWithView '+str(nameFile)+'.png')==True:
  219. photo = open('raspisWithView '+str(nameFile)+'.png', 'rb')
  220. bot.send_photo(id, photo)
  221. else:
  222. cabinet()
  223. photo = open('raspisWithView ' + str(nameFile) + '.png', 'rb')
  224. bot.send_photo(id, photo)
  225.  
  226. bot.polling(none_stop=True)
  227.  
  228.  
  229.  
  230.  
  231.  
  232.  
  233.  
Add Comment
Please, Sign In to add comment