1
0
mirror of https://github.com/MarkParker5/STARK.git synced 2024-11-24 08:12:13 +02:00

zieit tomorrows shedule

This commit is contained in:
MarkParker5 2021-09-12 17:31:16 +03:00
parent 1fd2ecb39b
commit 49caea94ea
10 changed files with 124 additions and 77 deletions

View File

@ -24,31 +24,32 @@ class TelegramBot(Control):
def reply(self, id, response): def reply(self, id, response):
if response.text: if response.text:
bot.send_message(id, response.text) self.bot.send_message(id, response.text)
if response.voice: if response.voice:
bot.send_voice(id, voice.generate(response.voice).getBytes() ) if bytes := self.voice.generate(response.voice).getBytes():
self.bot.send_voice(id, bytes)
if response.thread: # add background thread to list if response.thread: # add background thread to list
response.thread['id'] = id response.thread['id'] = id
threads.append(response.thread) self.threads.append(response.thread)
def check_threads(self, threads): def check_threads(self, threads):
for thread in threads: for thread in threads:
if thread['finish_event'].is_set(): if thread['finish_event'].is_set():
response = thread['thread'].join() response = thread['thread'].join()
reply(thread['id'], response) self.reply(thread['id'], response)
thread['finish_event'].clear() thread['finish_event'].clear()
del thread del thread
def main(self, id, text): def main(self, id, text):
text = text.lower() text = text.lower()
if Command.isRepeat(text): if Command.isRepeat(text):
reply(id, memory[0]['response']); self.reply(id, self.memory[0]['response']);
return return
if memory: if self.memory:
response = memory[0]['response'] response = self.memory[0]['response']
if response.callback: if response.callback:
if new_response := response.callback.answer(text): if new_response := response.callback.answer(text):
reply(id, new_response) self.reply(id, new_response)
memory.insert(0, { memory.insert(0, {
'cmd': response.callback, 'cmd': response.callback,
'params': None, 'params': None,
@ -56,13 +57,13 @@ class TelegramBot(Control):
}) })
return return
try: try:
cmd, params = memory[0]['cmd'].checkContext(text).values() cmd, params = self.memory[0]['cmd'].checkContext(text).values()
if memory[0].get('params'): params = {**memory[0].get('params'), **params} if self.memory[0].get('params'): params = {**memory[0].get('params'), **params}
except: except:
cmd, params = Command.reg_find(text).values() cmd, params = Command.reg_find(text).values()
response = cmd.start(params) response = cmd.start(params)
reply(id, response) self.reply(id, response)
memory.insert(0, { self.memory.insert(0, {
'cmd': cmd, 'cmd': cmd,
'params': params, 'params': params,
'response': response, 'response': response,
@ -82,13 +83,13 @@ class TelegramBot(Control):
@bot.message_handler(content_types = ['text']) @bot.message_handler(content_types = ['text'])
def execute(msg): def execute(msg):
main(msg.chat.id, msg.text) TelegramBot().main(msg.chat.id, msg.text)
def start(self): def start(self):
while True: while True:
try: try:
print("Start polling...") print("Start polling...")
bot.polling(callback = check_threads, args = (threads,) ) self.bot.polling(callback = self.check_threads, args = (self.threads,) )
except Exception as e: except Exception as e:
print(e, "\nPolling failed") print(e, "\nPolling failed")
time.sleep(10) time.sleep(10)

View File

@ -0,0 +1,2 @@
from . import gitpull
from . import tv

View File

@ -0,0 +1,2 @@
from . import hello
from . import ctime

View File

@ -0,0 +1,4 @@
from . import alarmclock
from . import light
from . import main_light
from . import window

View File

@ -3,11 +3,11 @@ import urllib.request
import xlrd import xlrd
import xlwt import xlwt
from xlutils.copy import copy from xlutils.copy import copy
from datetime import datetime from datetime import datetime, timedelta
class Zieit (Command): class Zieit (Command):
lessonsStartTime = ['07:55','09:25','11:05','12:35','14:05','15:45','17:15'] lessonsStartTime = ['08:00', '09:30', '11:10', '12:40', '14:10', '15:50', '17:20']
lessonsEndTime = ['09:15','10:45','12:25','13:55','15:25','17:05','18:35'] lessonsEndTime = ['09:20', '10:50', '12:30', '14:00', '15:30', '17:10', '18:40']
weekdays = ["Неділя", "Понеділок", "Вівторок", "Середа", "Четвер", "П'ятниця", "Субота"] weekdays = ["Неділя", "Понеділок", "Вівторок", "Середа", "Четвер", "П'ятниця", "Субота"]
def start(self, string): # main method def start(self, string): # main method
@ -15,7 +15,7 @@ class Zieit (Command):
@classmethod @classmethod
def getShedule(self): def getShedule(self):
url = 'https://www.zieit.edu.ua/wp-content/uploads/Rozklad/2k.xls' url = 'https://www.zieit.edu.ua/wp-content/uploads/Rozklad/3k.xls'
name = url.split('/')[-1] name = url.split('/')[-1]
urllib.request.urlretrieve(url, name) urllib.request.urlretrieve(url, name)
@ -56,18 +56,29 @@ class Zieit (Command):
lesson['subject'] = row[14] lesson['subject'] = row[14]
elif rownum%4 == 0: elif rownum%4 == 0:
lesson['type'] = row[14] lesson['type'] = row[14]
lesson['index'] = int(row[2])
lesson['time'] = str(row[3])
return week return week
@classmethod @classmethod
def getTodaysShedule(self): def getTodaysShedule(self):
today = datetime.now().date()
return self.getSheduleForDate(today)
@classmethod
def getTomorrowsShedule(self):
tomorrow = datetime.now().date() + timedelta(days = 1)
return self.getSheduleForDate(tomorrow)
@classmethod
def getSheduleForDate(self, target_date):
week = self.getShedule() week = self.getShedule()
for d, lessons in week.items(): for d, lessons in week.items():
today = datetime.now().date()
try: try:
date = datetime.strptime(d, "%d.%m.%Y").date() date = datetime.strptime(d, "%d.%m.%Y").date()
if date == today: return lessons if date == target_date: return lessons
except: except:
if self.weekdays.index(d) == today.isoweekday(): if self.weekdays.index(d) == target_date.isoweekday():
return lessons return lessons
return None return None
@ -87,6 +98,11 @@ class Zieit (Command):
def fullNames(self, string): def fullNames(self, string):
string = string.lower() string = string.lower()
names = { names = {
'алгоритми та структури даних': 'Алгоритмы и структуры данных',
'філософія': 'Философия',
'архітектура комп\'ютерів': 'Архитектура компьютеров',
'web-програмування': 'WEB-программирование',
'бази даних': 'Базы данных',
'укр мова': 'украинский язык', 'укр мова': 'украинский язык',
'дискретна': 'дискретная', 'дискретна': 'дискретная',
'безпека життєдіяльності та основи охорони праці':'обж', 'безпека життєдіяльності та основи охорони праці':'обж',
@ -102,8 +118,6 @@ class Zieit (Command):
'викл.':'', 'викл.':'',
'ст.в.':'', 'ст.в.':'',
'(шк)':'', '(шк)':'',
'(': '',
')': '',
'і':'и', 'і':'и',
'ауд.': '', 'ауд.': '',
' ': ' ', ' ': ' ',

View File

@ -0,0 +1 @@
from . import myshedule

View File

@ -1,59 +1,78 @@
from .Zieit import * from .Zieit import *
################################################################################
def nextLessonMethod(params): def formatLesson(lesson):
lesson = Zieit.getNextLesson(Zieit.lessonsStartTime)
if lesson == None: voice = text = 'Сегодня пар нет' if lesson == None: voice = text = 'Сегодня пар нет'
else: else:
index = lesson['index']
time = lesson['time'].replace('.', ':')
subject = lesson['subject'] subject = lesson['subject']
teacher = lesson['teacher'] teacher = lesson['teacher']
auditory = lesson['auditory'] auditory = lesson['auditory']
type = lesson['type'] type = lesson['type']
voice = Zieit.fullNames(f'{type} по предмету {subject} в аудитории {auditory}') voice = Zieit.fullNames(f'{type} по предмету {subject} в аудитории {auditory} в {time}')
text = f'{subject}\n{teacher}\n{auditory}\n{type}' text = Zieit.fullNames(f'{index}. [{time}] {subject}\n{teacher}\n{auditory}\n{type}')
return Response(text = text, voice = voice) return Response(text = text, voice = voice)
def formatDay(lessons):
text = voice = ''
if not lessons:
return None
for i, lesson in lessons.items():
index = lesson['index']
time = lesson['time'].replace('.', ':')
subject = lesson['subject']
teacher = lesson['teacher']
auditory = lesson['auditory']
type = lesson['type']
voice += Zieit.fullNames(f'{index}, {type} по предмету {subject} в аудитории {auditory}.\n').capitalize()
text += Zieit.fullNames(f'\n{index}. [{time}] {subject}\n....{type} ({auditory})\n....') + teacher
return Response(text = text, voice = voice)
################################################################################
def nextLessonFunc(params):
return formatLesson(Zieit.getNextLesson(Zieit.lessonsStartTime))
keywords = {} keywords = {}
patterns = ['* следующ* (предмет|урок|пара)'] patterns = ['* следующ* (предмет|урок|пара)']
nextLesson = Zieit('Next Lesson', keywords, patterns) nextLesson = Zieit('Next Lesson', keywords, patterns)
nextLesson.setStart(nextLessonMethod) nextLesson.setStart(nextLessonFunc)
################################################################################ ################################################################################
def currentLessonMethod(params): def currentLessonFunc(params):
lesson = Zieit.getNextLesson(Zieit.lessonsEndTime) return formatLesson(Zieit.getNextLesson(Zieit.lessonsEndTime))
if lesson == None: voice = text = 'Сегодня пар нет'
else:
subject = lesson['subject']
teacher = lesson['teacher']
auditory = lesson['auditory']
type = lesson['type']
voice = Zieit.fullNames(f'{type} по предмету {subject} в аудитории {auditory}')
text = f'{subject}\n{teacher}\n{auditory}\n{type}'
return Response(text = text, voice = voice)
keywords = {} keywords = {}
patterns = ['* (текущ*|сейчас) (предмет|урок|пара)'] patterns = ['* (текущ*|сейчас) (предмет|урок|пара)']
currentLesson = Zieit('Current Lesson', keywords, patterns) currentLesson = Zieit('Current Lesson', keywords, patterns)
currentLesson.setStart(currentLessonMethod) currentLesson.setStart(currentLessonFunc)
################################################################################ ################################################################################
def todaysSheduleMethod(params): def todaysSheduleFunc(params):
lessons = Zieit.getTodaysShedule() if lessons := Zieit.getTodaysShedule():
text = voice = '' return formatDay(lessons)
if not lessons: else:
voice = text = 'Сегодня пар нет' text = voice = 'Сегодня пар нет'
return Response(text = text, voice = voice) return Response(text = text, voice = voice)
for i, lesson in lessons.items():
subject = lesson['subject']
teacher = lesson['teacher']
auditory = lesson['auditory']
type = lesson['type']
voice += Zieit.fullNames(f'{type} по предмету {subject} в аудитории {auditory}.\n').capitalize()
text += f'{subject} ({auditory})\n'
return Response(text = text, voice = voice)
keywords = {} keywords = {}
patterns = ['* сегодня (предметы|уроки|пары|расписание)'] patterns = ['* сегодня (предметы|уроки|пары|расписание)', '* (предметы|уроки|пары|расписание) * сегодня *']
todaysShedule = Zieit('Todays Shedule', keywords, patterns) todaysShedule = Zieit('Todays Shedule', keywords, patterns)
todaysShedule.setStart(todaysSheduleMethod) todaysShedule.setStart(todaysSheduleFunc)
################################################################################
def tomorrowsSheduleFunc(params):
if lessons := Zieit.getTomorrowsShedule():
return formatDay(lessons)
else:
text = voice = 'Завтра пар нет'
return Response(text = text, voice = voice)
keywords = {}
patterns = ['* завтра (предметы|уроки|пары|расписание)', '* (предметы|уроки|пары|расписание) * завтра *']
tomorrowsShedule = Zieit('Todays Shedule', keywords, patterns)
tomorrowsShedule.setStart(tomorrowsSheduleFunc)

View File

@ -1,5 +1,4 @@
from .Command import Command from .Command import Command
from .Command import Command
from .Command import Response from .Command import Response
from .Media import Media from .Media import Media

View File

@ -15,19 +15,22 @@ class Speech:
if(standart): Speech.append(self) if(standart): Speech.append(self)
def speak(self): def speak(self):
if( os.path.exists(self._path) ): if not os.path.exists(self._path): return
with open(self._path) as f: with open(self._path) as f:
with mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as audio: with mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as audio:
mixer.init() mixer.init()
mixer.music.load(audio) mixer.music.load(audio)
mixer.music.set_volume(config.voice_volume) mixer.music.set_volume(config.voice_volume)
mixer.music.play() mixer.music.play()
while mixer.music.get_busy(): while mixer.music.get_busy():
sleep(0.1) sleep(0.1)
if(not self._standart): os.remove(self._path) if(not self._standart): os.remove(self._path)
def getBytes(self): def getBytes(self):
return open(self._path, 'rb') if not os.path.exists(self._path): return None
with open(self._path, 'rb') as b:
bytes = b
return bytes
def getPath(self): def getPath(self):
return self._path return self._path

View File

@ -1,20 +1,22 @@
#!/usr/local/bin/python3.8 #!/usr/local/bin/python3.8
# entry point # entry point
import multiprocessing
import multiprocessing
import Controls import Controls
import Features
# TODO: # TODO:
# import subprocess
# start oll controls in own thread or subprocess: # start oll controls in own thread or subprocess:
# voice assistant, telegram bot, django(api and ui) # voice assistant, telegram bot, django(api and ui)
telegram = multiprocessing.Process(target = Controls.TelegramBot().start) def main():
voiceAssistant = multiprocessing.Process(target = Controls.VoiceAssistant().start) telegram = multiprocessing.Process(target = Controls.TelegramBot().start)
voiceAssistant = multiprocessing.Process(target = Controls.VoiceAssistant().start)
telegram.start() telegram.start()
voiceAssistant.start() #voiceAssistant.start()
# telegram.join() telegram.join()
# voiceAssistant.join() #voiceAssistant.join()
if __name__ =='__main__': main()