Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- import tabula
- from datetime import datetime
- import csv
- import requests
- from pyunpack import Archive
- from pdf2jpg import pdf2jpg
- import os
- import shutil
- import io
- from pdfminer.converter import TextConverter
- from pdfminer.pdfinterp import PDFPageInterpreter
- from pdfminer.pdfinterp import PDFResourceManager
- from pdfminer.pdfpage import PDFPage
- import telebot
- import cv2
- import numpy as np
- bot = telebot.TeleBot('')
- keyboard = telebot.types.ReplyKeyboardMarkup(True)
- keyboard.row('Расписание','Кабинеты')
- spisok = [
- {'1': '', '2': 'Горбачева А. В. (Введение в специальность)','3': 'Горбачева Н. Ф. (Химия)', '4': 'Сорокина Д. А. (Биология)','5':'','6': ''},
- {'1': 'Солодкая Т. И. (Математика)', '2': 'Сычева В. Ю. (Астрономия)','3': 'Харитонова М. В. (Физическая культура)','4':'','5': '','6': ''},
- {'1': 'Попова С. А. (Литература)', '2': 'Сафарова Л. В. (Информатика)','3': 'Солодкая Т. И. (Математика)','4': '','5': '','6': ''},
- {'1': '', '2': 'Солодкая Т. И. (Математика)','3': 'Макаров А. А. (Обществознание)','4': 'Вьюгов/Алиева (Иностранный язык)','5': 'Попова С. А. (Литература)','6': ''},
- {'1': '', '2': '','3': 'Константинова Н. В. (Физика)','4': 'Макаров А. А. (Обществознание)','5': '','6': ''},
- {'1': '', '2': '','3': 'Спирина Н. В. (История)','4': 'Вьюгов/Алиева (Иностранный язык)','5': '','6': ''},
- {'1': '', '2': 'Горбачева А. В. (Введение в специальность)', '3': 'Горбачева Н. Ф. (Химия)','4': 'Сорокина Д. А. (Биология)', '5': 'Горбачева А. В. (Введение в специальность)', '6': ''},
- {'1': 'Солодкая Т. И. (Математика)', '2': 'Сычева В. Ю. (Астрономия)','3': 'Харитонова М. В. (Физическая культура)', '4': 'Попова С. А. (Литература)', '5': '', '6': ''},
- {'1': 'Попова С. А. (Литература)', '2': 'Сафарова Л. В. (Информатика)', '3': 'Солодкая Т. И. (Математика)', '4': '','5': '', '6': ''},
- {'1': '', '2': 'Солодкая Т. И. (Математика)', '3': 'Макаров А. А. (Обществознание)','4': 'Вьюгов/Алиева (Иностранный язык)', '5': 'Попова С. А. (Литература)', '6': ''},
- {'1': '', '2': '', '3': 'Константинова Н. В. (Физика)', '4': 'Харитонова М. В. (Физическая культура)', '5': '', '6': ''},
- {'1': '', '2': '', '3': 'Спирина Н. В. (История)', '4': 'Спирина Н. В. (История)', '5': '', '6': ''},
- ]
- def send(id,text):
- bot.send_message(id,str(text),reply_markup=keyboard)
- def raspisanieOK():
- global raspis
- Archive('zameni.rar').extractall('')
- def extract_text_from_pdf(pdf_path):
- resource_manager = PDFResourceManager()
- fake_file_handle = io.StringIO()
- converter = TextConverter(resource_manager, fake_file_handle)
- page_interpreter = PDFPageInterpreter(resource_manager, converter)
- with open(pdf_path, 'rb') as fh:
- for page in PDFPage.get_pages(fh,
- caching=True,
- check_extractable=True):
- page_interpreter.process_page(page)
- text = fake_file_handle.getvalue()
- # close open handles
- converter.close()
- fake_file_handle.close()
- if text:
- return text
- if __name__=='__main__':
- text = (extract_text_from_pdf('Замены/' + os.listdir("Замены")[int(len(os.listdir("Замены"))) - 1]))
- if 'ЗНАМЕНАТЕЛЬ' in text:
- znam = 1
- else:
- znam = 0
- # сортировка пар
- date = datetime.today().weekday() + 1 # получение завтрашнего дня
- if znam==1: # если знаменатель то
- date + 6
- para1 = '1) ' + spisok[date]['1']
- para2 = '2) ' + spisok[date]['2']
- para3 = '3) ' + spisok[date]['3']
- para4 = '4) ' + spisok[date]['4']
- para5 = '5) ' + spisok[date]['5']
- para6 = '6) ' + spisok[date]['6']
- df = tabula.read_pdf('Замены/16.06.2021.pdf', pages='all')[0]
- tabula.convert_into("Замены/16.06.2021.pdf", "zamen.csv", output_format="csv", pages='all')
- with open('zamen.csv') as csv_file:
- csv_reader = csv.reader(csv_file, delimiter=',')
- line_count = 0
- for row in csv_reader:
- if 'д' not in row[1]:
- if '12 г' in row[1] or '12г' in row[1]:
- print('Пара', row[0], 'Заменить ', row[2], 'на', row[3])
- if row[0]=='I':
- para1 = '1) ' + row[3].replace("\n", " ")
- if row[0]=='II':
- para2 = '2) ' + row[3].replace("\n", " ")
- if row[0]=='III':
- para3 = '3) ' + row[3].replace("\n", " ")
- if row[0]=='IV':
- para4 = '4) ' + row[3].replace("\n", " ")
- if row[0]=='V':
- para5 = '5) ' + row[3].replace("\n", " ")
- if row[0]=='VI':
- para6 = '6) ' + row[3].replace("\n", " ")
- raspis = ('' + para1 + '\n' + para2 + '\n' + para3 + '\n' + para4 + '\n' + para5 + '\n' + para6)
- print(raspis)
- def raspisanieCabin():
- global raspis
- # скачка
- API_ENDPOINT = 'https://cloud-api.yandex.net/v1/disk/public/resources/download?public_key={}'
- def _get_real_direct_link(sharing_link):
- pk_request = requests.get(API_ENDPOINT.format(sharing_link))
- return pk_request.json().get('href')
- def download_yadisk_link(sharing_link, filename):
- direct_link = _get_real_direct_link(sharing_link)
- if direct_link:
- # Try to recover the filename from the link
- download = requests.get(direct_link)
- with open(filename, 'wb') as out_file:
- out_file.write(download.content)
- print('ok')
- else:
- print('neok')
- download_yadisk_link('https://disk.yandex.ru/d/YP2Zp9ysrLye7Q','cabinets.rar')
- def raspisanie():
- global raspis
- # скачка
- API_ENDPOINT = 'https://cloud-api.yandex.net/v1/disk/public/resources/download?public_key={}'
- def _get_real_direct_link(sharing_link):
- pk_request = requests.get(API_ENDPOINT.format(sharing_link))
- return pk_request.json().get('href')
- def download_yadisk_link(sharing_link, filename):
- direct_link = _get_real_direct_link(sharing_link)
- if direct_link:
- # Try to recover the filename from the link
- download = requests.get(direct_link)
- with open(filename, 'wb') as out_file:
- out_file.write(download.content)
- raspisanieOK()
- else:
- raspis = '⛔Замен ещё нет⛔'
- download_yadisk_link('https://disk.yandex.ru/d/FBIhy2KSHPDSng','zameni.rar')
- raspisanieOK()
- def cabinet():
- raspisanieCabin()
- Archive('cabinets.rar').extractall('')
- result = pdf2jpg.convert_pdf2jpg(('Расписание/' + os.listdir("Расписание")[int(len(os.listdir("Расписание"))) - 1]),
- os.path.abspath(os.curdir), dpi=120, pages="ALL")
- day = int(datetime.strftime(datetime.now(), "%d"));
- otherDate = str(datetime.strftime(datetime.now(), "%m.%Y"));
- nameFile = str(int(day) + 1) + '.' + otherDate
- print('Расписание по кабинетам среда ' + str(day + 1) + '.' + str(
- otherDate) + '.pdf/0_Расписание по кабинетам среда ' + str(day + 1) + '.' + str(otherDate) + '.pdf.jpg')
- shutil.move(r'Расписание по кабинетам среда ' + str(day + 1) + '.' + str(
- otherDate) + '.pdf_dir/0_Расписание по кабинетам среда ' + str(day + 1) + '.' + str(otherDate) + '.pdf.jpg',
- os.path.abspath(os.curdir))
- os.rename('0_Расписание по кабинетам среда ' + str(day + 1) + '.' + str(otherDate) + '.pdf.jpg', "Raspis.png")
- img_rgb = cv2.imread('Raspis.png')
- template = cv2.imread('1.png')
- w, h = template.shape[:-1]
- res = cv2.matchTemplate(img_rgb, template, cv2.TM_CCOEFF_NORMED)
- threshold = .9
- loc = np.where(res >= threshold)
- for pt in zip(*loc[::-1]): # Switch collumns and rows
- cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0, 0, 255), 2)
- cv2.imwrite('raspisWithView ' + str(day + 1) + '.' + str(otherDate) + '.png', img_rgb)
- shutil.rmtree(r'Расписание')
- shutil.rmtree(r'Расписание по кабинетам среда ' + str(day + 1) + '.' + str(otherDate) + '.pdf_dir')
- os.remove(r'Raspis.png')
- os.remove(r'cabinets.rar')
- @bot.message_handler(commands = ['start'])
- def answer(message):
- send(message.chat.id, 'Гениальный бот по расписанию')
- @bot.message_handler(content_types=['text','photo'])
- def main(message):
- global raspis
- id = message.chat.id
- msg = message.text
- if msg == 'Расписание':
- send(id, 'Ща напишу')
- day = str(datetime.strftime(datetime.now(), "%d"))
- otherDate = str(datetime.strftime(datetime.now(), "%m.%Y"))
- nameFile = str(int(day) + 1) + '.' + otherDate
- if os.path.isfile(str(nameFile)+'.txt')==True:
- with open(str(nameFile) + '.txt') as f:
- raspis = f.read()
- send(id,day+'.'+otherDate+'\n'+raspis)
- else:
- if os.path.isfile('Замены')==True:
- shutil.rmtree(r'Замены')
- if os.path.isfile('zameni.rar')==True:
- os.remove(r'zameni.rar')
- if os.path.isfile('zamen.csv')==True:
- os.remove(r'zamen.csv')
- raspisanie()
- day = str(datetime.strftime(datetime.now(), "%d"))
- otherDate = str(datetime.strftime(datetime.now(), "%m.%Y"))
- send(id,day+'.'+otherDate+'\n'+raspis) # сообщение
- nameFile = str(int(day) + 1) + '.' + otherDate
- f = open(str(nameFile) + '.txt', 'w')
- f.write(raspis)
- f.close()
- elif msg == 'Кабинеты':
- send(id, 'Ща найду')
- day = str(datetime.strftime(datetime.now(), "%d"))
- otherDate = str(datetime.strftime(datetime.now(), "%m.%Y"))
- nameFile = str(int(day) + 1) + '.' + otherDate
- if os.path.isfile('raspisWithView '+str(nameFile)+'.png')==True:
- photo = open('raspisWithView '+str(nameFile)+'.png', 'rb')
- bot.send_photo(id, photo)
- else:
- cabinet()
- photo = open('raspisWithView ' + str(nameFile) + '.png', 'rb')
- bot.send_photo(id, photo)
- bot.polling(none_stop=True)
Add Comment
Please, Sign In to add comment