Here's the corrected and optimized version of your code. I've refactored it to eliminate duplicates, renamed variables to follow PEP8 guidelines, and improved efficiency. Additionally, I've provided suggestions on replacing openpyxl with pandas for better performance when working with Excel files.
app.py:
import datetime
from aiogram import Router, types
from aiogram.enums import ParseMode
from aiogram.filters import CommandStart
from aiogram.types import Message
import app.keyboards as kb
from data import config
from utils.table_utils import (
get_column_by_course_group_subgroup,
get_schedule_by_column_week_day,
)
router = Router()
# Define constants at the module level
DAYS_OF_WEEK = {
1: "Понедельник",
2: "Вторник",
3: "Среда",
4: "Четверг",
5: "Пятница",
6: "Суббота",
}
DAYS_SHORT = {day[:3]: day for day in DAYS_OF_WEEK.values()}
@router.message(CommandStart())
async def cmd_start(message: Message):
await message.reply("Выберите свой курс:", reply_markup=kb.main_keyboard)
@router.callback_query()
async def process_course_selection(callback_query: types.CallbackQuery):
selected = [item.replace("_", " ") for item in callback_query.data.split("-")]
selected_course = selected[0] if len(selected) > 0 else None
selected_group = selected[1] if len(selected) > 1 else None
selected_subgroup = selected[2] if len(selected) > 2 else None
selected_day = selected[3] if len(selected) > 3 else None
selected_week_type = selected[4] if len(selected) > 4 else None
if len(selected) == 1:
await callback_query.message.reply(
text=f"Вы выбрали курс '{selected_course}'. Выберите группу:",
reply_markup=kb.get_groups_by_course(selected_course),
)
elif len(selected) == 2:
await callback_query.message.reply(
text=f"Вы выбрали курс '{selected_course}', группу '{selected_group}'. Выберите подгруппу:",
reply_markup=kb.get_subgroups_by_course_and_group(selected_course, selected_group),
)
else:
if len(selected) == 3:
# Use current day and week type
current_day = DAYS_OF_WEEK[datetime.datetime.now().isoweekday()]
week_type = config.week
elif len(selected) >= 4:
# Use selected day and week type
current_day = DAYS_SHORT.get(selected_day, selected_day)
week_type = "Числитель" if selected_week_type == "Ч" else "Знаменатель" if selected_week_type == "З" else config.week
column = get_column_by_course_group_subgroup(selected_course, selected_group, selected_subgroup)
info, schedule = get_schedule_by_column_week_day(column, week_type, current_day)
message_text = format_schedule_message(info, schedule)
reply_markup = None
if len(selected) == 3:
reply_markup = kb.get_days_keyboard(selected_course, selected_group, selected_subgroup)
elif len(selected) == 4:
reply_markup = kb.get_week_type_keyboard(selected_course, selected_group, selected_subgroup, selected_day)
elif len(selected) == 5:
reply_markup = kb.get_week_type_keyboard(selected_course, selected_group, selected_subgroup, selected_day)
await callback_query.message.reply(
message_text,
parse_mode=ParseMode.HTML,
reply_markup=reply_markup,
)
def format_schedule_message(info, schedule):
info_text = "\n".join([f"<b>{item[0]}</b> - {item[1] if item[1] else 'Нет'}" for item in info])
schedule_text = "\n".join(
[f"<b>{time.split()[0]} {time.split()[1]} пара {time.split()[3]}</b> - {subject}" for time, subject in schedule]
)
return f"{info_text}\n\n{schedule_text}"
keyboards.py:
from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton
from utils.table_utils import get_courses_dict
main_keyboard = InlineKeyboardMarkup(
inline_keyboard=[
[
InlineKeyboardButton(
text=course,
callback_data=course.replace(" ", "_")
)
for course in get_courses_dict().keys()
]
],
resize_keyboard=True
)
def get_groups_by_course(course_name):
groups = get_courses_dict()[course_name].keys()
keyboard = InlineKeyboardMarkup(row_width=4)
buttons = [
InlineKeyboardButton(
text=group,
callback_data=f"{course_name.replace(' ', '_')}-{group.replace(' ', '_')}"
)
for group in groups
]
keyboard.add(*buttons)
return keyboard
def get_subgroups_by_course_and_group(course, group):
subgroups = get_courses_dict()[course][group]
keyboard = InlineKeyboardMarkup(row_width=2)
buttons = [
InlineKeyboardButton(
text=subgroup,
callback_data=f"{course.replace(' ', '_')}-{group.replace(' ', '_')}-{subgroup.replace(' ', '_')}"
)
for subgroup in subgroups
]
keyboard.add(*buttons)
return keyboard
def get_days_keyboard(course, group, subgroup):
keyboard = InlineKeyboardMarkup(row_width=2)
buttons = [
InlineKeyboardButton(
text=day_short,
callback_data=f"{course.replace(' ', '_')}-{group.replace(' ', '_')}-{subgroup.replace(' ', '_')}-{day_short}"
)
for day_short in DAYS_SHORT.keys()
]
keyboard.add(*buttons)
return keyboard
def get_week_type_keyboard(course, group, subgroup, day):
keyboard = InlineKeyboardMarkup(row_width=2)
buttons = [
InlineKeyboardButton(
text="Числитель",
callback_data=f"{course.replace(' ', '_')}-{group.replace(' ', '_')}-{subgroup.replace(' ', '_')}-{day}-Ч"
),
InlineKeyboardButton(
text="Знаменатель",
callback_data=f"{course.replace(' ', '_')}-{group.replace(' ', '_')}-{subgroup.replace(' ', '_')}-{day}-З"
)
]
keyboard.add(*buttons)
return keyboard
utils/table_utils.py:
import pandas as pd
from functools import lru_cache
# Load the Excel file once and cache it
@lru_cache(maxsize=None)
def load_sheets():
data_path = r"C:\Users\user\PycharmProjects\botSheduleVsuFkn\data\tables\table.xlsx"
sheet_courses = pd.read_excel(data_path, sheet_name="Расписание норм")
sheet_schedule = pd.read_excel(data_path, sheet_name="Лист2")
return sheet_courses, sheet_schedule
@lru_cache(maxsize=None)
def get_courses_dict():
sheet_courses, _ = load_sheets()
courses_dict = {}
for col in sheet_courses.columns[1:]:
course = sheet_courses[col][0]
group = sheet_courses[col][1]
subgroup = sheet_courses[col][2]
profile = sheet_courses[col][3] if pd.notna(sheet_courses[col][3]) else "Профиля нет."
courses_dict.setdefault(course, {}).setdefault(group, []).append(subgroup)
return courses_dict
def get_column_by_course_group_subgroup(course, group, subgroup):
sheet_courses, _ = load_sheets()
for col in sheet_courses.columns:
if (
sheet_courses[col][0] == course
and sheet_courses[col][1] == group
and sheet_courses[col][2] == subgroup
):
return col
return None
def get_schedule_by_column_week_day(column, week, day_of_week):
_, sheet_schedule = load_sheets()
day_schedule = sheet_schedule[
(sheet_schedule['Day'] == day_of_week) & (sheet_schedule['Week'] == week)
][['Time', column]].dropna()
info = [] # Add any additional information you need
schedule = list(zip(day_schedule['Time'], day_schedule[column]))
return info, schedule
Suggestions:
-
Variable Naming and Code Style: All variable names have been updated to follow the PEP8 naming conventions, which use lowercase letters and underscores (snake_case). Constants are in uppercase.
-
Duplicate Code Removal: Duplicated code in the process_course_selection function has been refactored. Now, the function uses a unified approach to handle different lengths of the selected list, reducing redundancy.
-
Improving Callback Data Handling: Instead of removing spaces, we replace spaces with underscores (_) when creating callback_data. This avoids issues when reconstructing the original strings.
-
Caching and Performance Optimization:
- Use
@lru_cache to cache the results of functions that load data. This ensures that the Excel file is read only once, improving performance.
- Consider loading the data at startup or storing it in a more efficient format if the data doesn't change frequently.
-
Replacing openpyxl with pandas: Reading Excel files with pandas is generally faster and more efficient than openpyxl. It also simplifies data handling since pandas provides powerful data manipulation capabilities.
-
Converting Excel to CSV: If you prefer working with CSV files for even better performance, you can convert your Excel sheets to CSV format using pandas:
def convert_excel_to_csv():
data_path = r"C:\Users\user\PycharmProjects\botSheduleVsuFkn\data\tables\table.xlsx"
sheet_names = ["Расписание норм", "Лист2"]
for sheet_name in sheet_names:
df = pd.read_excel(data_path, sheet_name=sheet_name)
csv_path = f"{sheet_name}.csv"
df.to_csv(csv_path, index=False)
After conversion, you can use Python's built-in csv module or pandas to read the CSV files, which is faster than reading Excel files.
-
Additional Optimizations:
- Ensure that you're not reading from or writing to disk inside loops.
- Preprocess and validate data once rather than multiple times.
By implementing these changes, your code should run faster, be more readable, and adhere to standard coding conventions.