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):
if response.text:
bot.send_message(id, response.text)
self.bot.send_message(id, response.text)
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
response.thread['id'] = id
threads.append(response.thread)
self.threads.append(response.thread)
def check_threads(self, threads):
for thread in threads:
if thread['finish_event'].is_set():
response = thread['thread'].join()
reply(thread['id'], response)
self.reply(thread['id'], response)
thread['finish_event'].clear()
del thread
def main(self, id, text):
text = text.lower()
if Command.isRepeat(text):
reply(id, memory[0]['response']);
self.reply(id, self.memory[0]['response']);
return
if memory:
response = memory[0]['response']
if self.memory:
response = self.memory[0]['response']
if response.callback:
if new_response := response.callback.answer(text):
reply(id, new_response)
self.reply(id, new_response)
memory.insert(0, {
'cmd': response.callback,
'params': None,
@ -56,13 +57,13 @@ class TelegramBot(Control):
})
return
try:
cmd, params = memory[0]['cmd'].checkContext(text).values()
if memory[0].get('params'): params = {**memory[0].get('params'), **params}
cmd, params = self.memory[0]['cmd'].checkContext(text).values()
if self.memory[0].get('params'): params = {**memory[0].get('params'), **params}
except:
cmd, params = Command.reg_find(text).values()
response = cmd.start(params)
reply(id, response)
memory.insert(0, {
self.reply(id, response)
self.memory.insert(0, {
'cmd': cmd,
'params': params,
'response': response,
@ -82,13 +83,13 @@ class TelegramBot(Control):
@bot.message_handler(content_types = ['text'])
def execute(msg):
main(msg.chat.id, msg.text)
TelegramBot().main(msg.chat.id, msg.text)
def start(self):
while True:
try:
print("Start polling...")
bot.polling(callback = check_threads, args = (threads,) )
self.bot.polling(callback = self.check_threads, args = (self.threads,) )
except Exception as e:
print(e, "\nPolling failed")
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 xlwt
from xlutils.copy import copy
from datetime import datetime
from datetime import datetime, timedelta
class Zieit (Command):
lessonsStartTime = ['07:55','09:25','11:05','12:35','14:05','15:45','17:15']
lessonsEndTime = ['09:15','10:45','12:25','13:55','15:25','17:05','18:35']
lessonsStartTime = ['08:00', '09:30', '11:10', '12:40', '14:10', '15:50', '17:20']
lessonsEndTime = ['09:20', '10:50', '12:30', '14:00', '15:30', '17:10', '18:40']
weekdays = ["Неділя", "Понеділок", "Вівторок", "Середа", "Четвер", "П'ятниця", "Субота"]
def start(self, string): # main method
@ -15,7 +15,7 @@ class Zieit (Command):
@classmethod
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]
urllib.request.urlretrieve(url, name)
@ -56,18 +56,29 @@ class Zieit (Command):
lesson['subject'] = row[14]
elif rownum%4 == 0:
lesson['type'] = row[14]
lesson['index'] = int(row[2])
lesson['time'] = str(row[3])
return week
@classmethod
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()
for d, lessons in week.items():
today = datetime.now().date()
try:
date = datetime.strptime(d, "%d.%m.%Y").date()
if date == today: return lessons
if date == target_date: return lessons
except:
if self.weekdays.index(d) == today.isoweekday():
if self.weekdays.index(d) == target_date.isoweekday():
return lessons
return None
@ -87,6 +98,11 @@ class Zieit (Command):
def fullNames(self, string):
string = string.lower()
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 *
################################################################################
def nextLessonMethod(params):
lesson = Zieit.getNextLesson(Zieit.lessonsStartTime)
def formatLesson(lesson):
if lesson == None: voice = text = 'Сегодня пар нет'
else:
index = lesson['index']
time = lesson['time'].replace('.', ':')
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}'
voice = Zieit.fullNames(f'{type} по предмету {subject} в аудитории {auditory} в {time}')
text = Zieit.fullNames(f'{index}. [{time}] {subject}\n{teacher}\n{auditory}\n{type}')
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 = {}
patterns = ['* следующ* (предмет|урок|пара)']
nextLesson = Zieit('Next Lesson', keywords, patterns)
nextLesson.setStart(nextLessonMethod)
nextLesson.setStart(nextLessonFunc)
################################################################################
def currentLessonMethod(params):
lesson = 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)
def currentLessonFunc(params):
return formatLesson(Zieit.getNextLesson(Zieit.lessonsEndTime))
keywords = {}
patterns = ['* (текущ*|сейчас) (предмет|урок|пара)']
currentLesson = Zieit('Current Lesson', keywords, patterns)
currentLesson.setStart(currentLessonMethod)
currentLesson.setStart(currentLessonFunc)
################################################################################
def todaysSheduleMethod(params):
lessons = Zieit.getTodaysShedule()
text = voice = ''
if not lessons:
voice = text = 'Сегодня пар нет'
def todaysSheduleFunc(params):
if lessons := Zieit.getTodaysShedule():
return formatDay(lessons)
else:
text = 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 = {}
patterns = ['* сегодня (предметы|уроки|пары|расписание)']
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 Response
from .Media import Media

View File

@ -15,19 +15,22 @@ class Speech:
if(standart): Speech.append(self)
def speak(self):
if( os.path.exists(self._path) ):
with open(self._path) as f:
with mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as audio:
mixer.init()
mixer.music.load(audio)
mixer.music.set_volume(config.voice_volume)
mixer.music.play()
while mixer.music.get_busy():
sleep(0.1)
if(not self._standart): os.remove(self._path)
if not os.path.exists(self._path): return
with open(self._path) as f:
with mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as audio:
mixer.init()
mixer.music.load(audio)
mixer.music.set_volume(config.voice_volume)
mixer.music.play()
while mixer.music.get_busy():
sleep(0.1)
if(not self._standart): os.remove(self._path)
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):
return self._path

View File

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