исправь и оптимизируй код, измени так чтобы не было дубликатов, измени названия переменных чтобы они все были в 1 стиле который рекомендуется pep8 и чтобы работало быстрее, потому что метод с openpyxl медленный
app.py:
import datetime
from aiogram import Router, types
from aiogram.enums import ParseMode
from aiogram.filters import CommandStart
from aiogram.types import Message
from select import select
import app.keyboards as kb
from data import config
from utils.table_utils import get_column_by_course_group_subgroup, get_shedule_by_column_week_day_of_week
router = Router()
@router.message(CommandStart())
async def cmd_start(message: Message):
await message.reply("Выбери свой курс:", reply_markup=kb.main)
s = f"""{"\n".join([f"{i[0]} - {i[1] if i[1] != '' else 'Нет'}" for i in info])}
{"\n".join([f"{i.split()[0]} {i.split()[1]} пара {i.split()[3]} - {j}" for i, j in schedule])}
"""
await callback_query.message.reply(s, parse_mode=ParseMode.HTML,
reply_markup=kb.get_days_by_subgroup_course_and_group(selected_course,
selected_group,
selected_subgroup))
daysSokr = {i[:3]: i for i in daysOfWeek.values()}
nowDayOfWeek = daysSokr[selected_day]
chOrZn = "Числитель" if selected_chOrZn == "Ч" else "Знаменатель"
s = f"""{"\n".join([f"{i[0]} - {i[1] if i[1] != '' else 'Нет'}" for i in info])}
{"\n".join([f"{i.split()[0]} {i.split()[1]} пара {i.split()[3]} - {j}" for i, j in schedule])}
"""
await callback_query.message.reply(s,
parse_mode=ParseMode.HTML,
reply_markup=kb.get_chOrZn_by_days_subgroup_course_and_group(selected_course,
selected_group,
selected_subgroup,
selected_day))
from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton, ReplyKeyboardMarkup, KeyboardButton
from utils.table_utils import get_dict
main = InlineKeyboardMarkup(
inline_keyboard=[
[InlineKeyboardButton(text=i, callback_data=i.replace(" ", "")) for i in get_dict().keys()]
],
resize_keyboard=True,
input_field_placeholder="Выберите свой курс",
one_time_keyboard=True
)
def get_groups_by_course(course_name):
a = get_dict()[course_name.replace("", " ")]
keys = list(a.keys()) # Преобразуем dict_keys в список
num_rows = 4
num_keys = len(keys)
num_buttons_per_row = (num_keys + num_rows - 1) // num_rows # Округляем вверх
keyboard = InlineKeyboardMarkup(
inline_keyboard=[
[InlineKeyboardButton(text=keys[i * num_buttons_per_row + j],
callback_data=f"{course_name.replace(" ", "")}-{keys[i * num_buttons_per_row + j].replace(" ", "")}")
for j in range(num_buttons_per_row)
if i * num_buttons_per_row + j < num_keys]
for i in range(num_rows)
],
resize_keyboard=True,
input_field_placeholder="Выберите свою группу",
one_time_keyboard=True
)
def get_column_by_course_group_subgroup(course, group, subgroup):
sheet, sheetRasp = get_sheet()
data = [sheet.cell(1, _) for _ in range(1, sheet.max_column) if
sheet.cell(1, _).value == course and sheet.cell(2, _).value == group]
if subgroup == "1 подгруппа":
return data[0].column
else:
return data[1].column
def get_shedule_by_column_week_day_of_week(column, week, day_of_week):
sheet, sheetRasp = get_sheet()
day_of_week = str(day_of_week)
dataRasp = [sheetRasp.cell(row=i, column=1).value for i in range(1, 103)]
dataOfGroup = [[str(dataRasp[i - 1]), str(sheet.cell(row=i, column=column).value).replace("\n", "")]
for i in range(1, sheet.max_row)][:4]
dataOfShedule = [[str(dataRasp[i - 1]), str(sheet.cell(row=i, column=column).value).replace("\n", "")]
for i in range(1, sheet.max_row) if sheet.cell(row=i, column=column).value is not None][4:]
returned = [[i, j] for i,j in dataOfShedule if i.split()[0] == str(day_of_week) and i.split()[2] == week]
return dataOfGroup, returned
Certainly! Here's the corrected and optimized code that adheres to PEP8 standards, removes duplicates, and improves performance by replacing openpyxl with pandas for faster Excel file processing.
Changes Made:
PEP8 Compliance: Renamed variables to use snake_case. Adjusted indentation and line lengths. Removed unnecessary imports.
Removed Duplicates: Refactored the process_course_selection function to eliminate duplicated code by creating helper functions.
Performance Optimization: Replaced openpyxl with pandas for Excel file processing, which is significantly faster. Cached the data by reading the Excel file once when the module is imported.
Code Organization: Organized the code into functions for better readability and maintenance.
app.py:
python
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_of_week,
)
router = Router()
DAYS_OF_WEEK = {
1: "Понедельник",
2: "Вторник",
3: "Среда",
4: "Четверг",
5: "Пятница",
6: "Суббота",
}
DAYS_ABBR = {v[:3]: v for v in DAYS_OF_WEEK.values()}
@router.message(CommandStart())
async def cmd_start(message: Message):
await message.reply("Выбери свой курс:", reply_markup=kb.main)
async def send_schedule(
callback_query,
selected_course,
selected_group,
selected_subgroup,
day_of_week,
week,
reply_markup,
):
column = get_column_by_course_group_subgroup(
selected_course, selected_group, selected_subgroup
)
info, schedule = get_schedule_by_column_week_day_of_week(
column, week, day_of_week
)
schedule_text = "\n".join(
[f"<b>{i[0]}</b> - {i[1] if i[1] != '' else 'Нет'}" for i in info]
)
schedule_items = "\n".join(
[
f"<b>{i.split()[0]} {i.split()[1]} пара {i.split()[3]}</b> - {j}"
for i, j in schedule
]
)
message_text = f"{schedule_text}\n\n{schedule_items}"
await callback_query.message.reply(
message_text,
parse_mode=ParseMode.HTML,
reply_markup=reply_markup,
)
@router.callback_query()
async def process_course_selection(callback_query: types.CallbackQuery):
selected = callback_query.data.split("-")
if len(selected) == 1:
selected_course = selected[0]
await callback_query.message.reply(
text=f"Вы выбрали курс '{selected_course}', выберите группу:",
reply_markup=kb.get_groups_by_course(selected_course),
)
elif len(selected) == 2:
selected_course = selected[0]
selected_group = selected[1]
await callback_query.message.reply(
text=(
f"Вы выбрали курс '{selected_course}', группу '{selected_group}', "
"выберите подгруппу:"
),
reply_markup=kb.get_subgroup_by_course_and_group(
selected_course, selected_group
),
)
elif len(selected) >= 3:
selected_course = selected[0]
selected_group = selected[1]
selected_subgroup = selected[2]
if len(selected) == 3:
# Only subgroup selected, use current day and default week
day_of_week = DAYS_OF_WEEK[datetime.datetime.now().isoweekday()]
week = config.week
reply_markup = kb.get_days_by_subgroup_course_and_group(
selected_course, selected_group, selected_subgroup
)
elif len(selected) == 4:
# Day is selected
selected_day_abbr = selected[3]
day_of_week = DAYS_ABBR[selected_day_abbr]
week = config.week
reply_markup = kb.get_week_type_markup(
selected_course, selected_group, selected_subgroup, selected_day_abbr
)
elif len(selected) == 5:
selected_day_abbr = selected[3]
day_of_week = DAYS_ABBR[selected_day_abbr]
selected_week_abbr = selected[4]
week = "Числитель" if selected_week_abbr == "Ч" else "Знаменатель"
reply_markup = kb.get_week_type_markup(
selected_course, selected_group, selected_subgroup, selected_day_abbr
)
else:
# Should not happen
return
await send_schedule(
callback_query,
selected_course,
selected_group,
selected_subgroup,
day_of_week,
week,
reply_markup,
)
app/keyboards.py:
python
from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton
from utils.table_utils import get_dict
main = InlineKeyboardMarkup(
inline_keyboard=[
[InlineKeyboardButton(text=course, callback_data=course) for course in get_dict().keys()]
],
resize_keyboard=True,
input_field_placeholder="Выберите свой курс",
one_time_keyboard=True,
)
def get_groups_by_course(course_name):
course_data = get_dict()[course_name]
groups = list(course_data.keys())
num_buttons_per_row = 4
keyboard = InlineKeyboardMarkup(resize_keyboard=True)
for i in range(0, len(groups), num_buttons_per_row):
group_buttons = [
InlineKeyboardButton(
text=group,
callback_data=f"{course_name}-{group}"
)
for group in groups[i:i + num_buttons_per_row]
]
keyboard.add(*group_buttons)
return keyboard
def get_subgroup_by_course_and_group(selected_course, selected_group):
subgroups = ["1 подгруппа", "2 подгруппа"]
keyboard = InlineKeyboardMarkup(
inline_keyboard=[
[
InlineKeyboardButton(
text=subgroup,
callback_data=f"{selected_course}-{selected_group}-{subgroup}"
) for subgroup in subgroups
]
],
resize_keyboard=True,
input_field_placeholder="Выберите свою подгруппу",
one_time_keyboard=True,
)
return keyboard
def get_days_by_subgroup_course_and_group(selected_course, selected_group, selected_subgroup):
days_abbr = ["Пон", "Вто", "Сре", "Чет", "Пят", "Суб"]
keyboard = InlineKeyboardMarkup(resize_keyboard=True)
for day in days_abbr:
keyboard.add(
InlineKeyboardButton(
text=day,
callback_data=f"{selected_course}-{selected_group}-{selected_subgroup}-{day}"
)
)
return keyboard
def get_week_type_markup(selected_course, selected_group, selected_subgroup, day_abbr):
week_types = {"Ч": "Числитель", "З": "Знаменатель"}
keyboard = InlineKeyboardMarkup(
inline_keyboard=[
[
InlineKeyboardButton(
text=week_type_name,
callback_data=(
f"{selected_course}-{selected_group}-{selected_subgroup}-"
f"{day_abbr}-{week_type_abbr}"
),
)
for week_type_abbr, week_type_name in week_types.items()
]
],
resize_keyboard=True,
input_field_placeholder="Выберите неделю",
one_time_keyboard=True,
)
return keyboard
utils/table_utils.py:
python
import pandas as pd
EXCEL_PATH = r"C:\Users\user\PycharmProjects\botSheduleVsuFkn\data\tables\table.xlsx"
# Load the Excel file once when the module is imported
xl = pd.ExcelFile(EXCEL_PATH)
df1 = xl.parse('Расписание норм', header=None)
df2 = xl.parse('Лист2', header=None)
# Transpose df1 if needed (depends on your Excel file structure)
# df1 = df1.transpose()
def get_dict():
result_dict = {}
num_cols = df1.shape[1]
for col in range(num_cols):
group = df1.iloc[0, col]
sub_group = df1.iloc[1, col]
item = df1.iloc[2, col]
profile = df1.iloc[3, col] if df1.iloc[3, col] != "" else "Профиля нет."
result_dict.setdefault(group, {}).setdefault(sub_group, {})[item] = profile
return result_dict
def get_column_by_course_group_subgroup(course, group, subgroup):
num_cols = df1.shape[1]
matching_columns = [
col for col in range(num_cols)
if df1.iloc[0, col] == course and df1.iloc[1, col] == group
]
if subgroup == "1 подгруппа":
return matching_columns[0]
else:
return matching_columns[1]
def get_schedule_by_column_week_day_of_week(column, week, day_of_week):
day_of_week = str(day_of_week)
data_rasp = df2.iloc[:, 0].tolist()
data_of_group = [
[str(data_rasp[i]), str(df1.iloc[i, column]).replace("\n", "")]
for i in range(len(data_rasp))
][:4]
data_of_schedule = [
[str(data_rasp[i]), str(df1.iloc[i, column]).replace("\n", "")]
for i in range(len(data_rasp))
if pd.notna(df1.iloc[i, column])
][4:]
schedule = [
[i, j]
for i, j in data_of_schedule
if i.split()[0] == day_of_week and i.split()[2] == week
]
return data_of_group, schedule
Explanation of Optimizations:
Excel Data Loading: By using pandas, we load the Excel data only once when the module is imported, which significantly improves performance compared to reading the file multiple times with openpyxl.
Data Processing with Pandas: Pandas provides efficient data access and manipulation, which speeds up the data processing steps in your functions.
Refactoring and Helper Functions: By creating helper functions like send_schedule, we eliminate duplicated code and improve maintainability.
Keyboard Generation: Simplified the keyboard generation functions in app/keyboards.py for clarity and efficiency.
Notes:
Ensure that the path to your Excel file (EXCEL_PATH) is correct.
Depending on the exact structure of your Excel sheets, you might need to adjust the data extraction logic, especially in the get_dict and get_schedule_by_column_week_day_of_week functions.
The code assumes that the days of the week abbreviations and full names match and that they are consistent throughout the data.
Remember to install pandas in your environment if it's not already installed:
bash
pip install pandas
If your Excel files are large, consider saving processed data to a serialized format (like pickles) if the data doesn't change often, to avoid reading from Excel on every startup.
This updated code should run faster due to the use of pandas and follows best practices as per PEP8 guidelines.
If you have any specific questions or need further adjustments, feel free to ask!