Refactor code structure for improved readability and maintainability

This commit is contained in:
2026-06-22 18:20:08 +04:00
parent 74edbde327
commit fcd8edbc5d
14 changed files with 7572 additions and 145 deletions
+2
View File
@@ -2,6 +2,8 @@ venv/
result/logs/
result/report*
input/stat*
input/schedule*
*.pyc
__pycache__/
.vscode/
+26 -26
View File
@@ -1,26 +1,26 @@
id,class,description,part,computers,section,prefix,ip_group
"3-111","3/111 (Наб.р.Свияги,3корп","ауд. 3/111","ОСУП",13,okk1,111k,""
"3-115","3/115 (Наб.р.Свияги,3корп","ауд. 3/115","ОСУП",15,okk1,115k,""
"3-118","3/118 (Наб.р.Свияги,3корп","ауд. 3/118","ОСУП",16,okk1,118k,""
"3-127","3/127 (Наб.р.Свияги,3корп","ауд. 3/127","ОСУП",13,okk1,127k,""
"3-522","3/522 (Наб.р.Свияги,3корп","ауд. 3/522","ОСУП",11,okk1,522k,""
"1-301","301 (Наб.р.Свияги,1корп)", "ауд. 1/301","ОСУП",10,okk1,301k,""
"1-303","303 (Наб.р.Свияги,1корп)", "ауд. 1/303","ОСУП",10,okk1,303k,""
"1-503","503 (Наб.р.Свияги,1корп)", "ауд. 1/503","ОСУП",10,okk1,503k,""
"1-505","505 (Наб.р.Свияги,1корп)", "ауд. 1/505","ОСУП",10,okk1,505k,""
"4а-402","402 (Пушкинская,4А)","ул. Пушкинская, д. 4а, ауд. 402 (ОСУП)","ОСУП",16,m1,pu-402-,pu
"4а-407","407 (Пушкинская,4А)","ул. Пушкинская, д. 4а, ауд. 407 (ОСУП)","ОСУП",15,m1,pu-407-,pu
"4а-806","806 (Пушкинская,4А)","ул. Пушкинская, д. 4а, ауд. 806 (ОСУП)","ОСУП",16,m1,pu-806-,pu
"ИЭиБ-10","10 (Федерации,29)","ул. Федерации, д. 29, ауд. 10 (ИЭиБ)","Факультеты",10,m1,fe-1-,fe
"МФ-207","207 (Ливчака,2/1)","ул. Архитектора Ливчака, д. 2/1, ауд. 207 (МФ)","Факультеты",10,m1,kl-207-,kl
"ЮФ-309","309 (Гончарова,40/9)","ул. Гончарова, д. 40/9, ауд. 309 (ЮФ)","Факультеты",11,m1,km-309-,km
"МУ-21","21 (Гимова,1)","ул. Гимова, д. 1, ауд. 21 (Муз. училище)","Факультеты",10,m1,mu-21-,mu
"ЭГФ-11","11 (Львовский,5)","ул. Бульвар Львовский, д. 5, ауд. 11 (Зав. ЭГФ)","Факультеты",11,m1,lv-11-,lv
"ЭГФ-14","14 (Львовский,5)","ул. Бульвар Львовский, д. 5, ауд. 14 (Зав. ЭГФ)","Факультеты",10,m1,lv-14-,lv
"МК-26","26 (Аблукова,31)","ул. Аблукова, д. 31, ауд. 26 (Мед. колледж)","Факультеты",9,m1,mk-26-,mk
"МК-28","28 (Аблукова,31)","ул. Аблукова, д. 31, ауд. 28 (Мед. колледж)","Факультеты",10,m1,mk-28-,mk
"АМТ-33","33 (Наб.р.Свияги,158)","ул. Набережная р. Свияги, д. 158, ауд. 33 (АМТ)","АМТ",9,m1,amt,amt
"АМТ-34","34 (Наб.р.Свияги,158)","ул. Набережная р. Свияги, д. 158, ауд. 34 (АМТ)","АМТ",11,m1,amt,amt
"АМТ-35","35 (Наб.р.Свияги,158)","ул. Набережная р. Свияги, д. 158, ауд. 35 (АМТ)","АМТ",15,m1,amt,amt
"АМТ-36","36 (Наб.р.Свияги,158)","ул. Набережная р. Свияги, д. 158, ауд. 36 (АМТ)","АМТ",11,m1,amt,amt
"АМТ-39","39 (Наб.р.Свияги,158)","ул. Набережная р. Свияги, д. 158, ауд. 39 (АМТ)","АМТ",11,m1,amt,amt
"id","class","description","part","computers","section","prefix","ip_group"
"3-111","3/111 (Наб.р.Свияги,3корп","ауд. 3/111","ОСУП","13","okk1","111k",""
"3-115","3/115 (Наб.р.Свияги,3корп","ауд. 3/115","ОСУП","15","okk1","115k",""
"3-118","3/118 (Наб.р.Свияги,3корп","ауд. 3/118","ОСУП","16","okk1","118k",""
"3-127","3/127 (Наб.р.Свияги,3корп","ауд. 3/127","ОСУП","13","okk1","127k",""
"3-522","3/522 (Наб.р.Свияги,3корп","ауд. 3/522","ОСУП","11","okk1","522k",""
"1-301","301 (Наб.р.Свияги,1корп)"," ""ауд. 1/301""","ОСУП","10","okk1","301k",""
"1-303","303 (Наб.р.Свияги,1корп)"," ""ауд. 1/303""","ОСУП","10","okk1","303k",""
"1-503","503 (Наб.р.Свияги,1корп)"," ""ауд. 1/503""","ОСУП","10","okk1","503k",""
"1-505","505 (Наб.р.Свияги,1корп)"," ""ауд. 1/505""","ОСУП","10","okk1","505k",""
"4а-402","402 (Пушкинская,4А)","ул. Пушкинская, д. 4а, ауд. 402 (ОСУП)","ОСУП","16","m1","pu-402-","pu"
"4а-407","407 (Пушкинская,4А)","ул. Пушкинская, д. 4а, ауд. 407 (ОСУП)","ОСУП","15","m1","pu-407-","pu"
"4а-806","806 (Пушкинская,4А)","ул. Пушкинская, д. 4а, ауд. 806 (ОСУП)","ОСУП","16","m1","pu-806-","pu"
"ИЭиБ-10","10 (Федерации,29)","ул. Федерации, д. 29, ауд. 10 (ИЭиБ)","Факультеты","10","m1","fe-1-","fe"
"МФ-207","207 (Ливчака,2/1)","ул. Архитектора Ливчака, д. 2/1, ауд. 207 (МФ)","Факультеты","10","m1","kl-207-","kl"
"ЮФ-309","309а (Гончарова,40/9)","ул. Гончарова, д. 40/9, ауд. 309 (ЮФ)","Факультеты","11","m1","km-309-","km"
"МУ-21","21 (Гимова,1)","ул. Гимова, д. 1, ауд. 21 (Муз. училище)","Факультеты","10","m1","mu-21-","mu"
"ЭГФ-11","11 (Львовский,5)","ул. Бульвар Львовский, д. 5, ауд. 11 (Зав. ЭГФ)","Факультеты","11","m1","lv-11-","lv"
"ЭГФ-14","14 (Львовский,5)","ул. Бульвар Львовский, д. 5, ауд. 14 (Зав. ЭГФ)","Факультеты","10","m1","lv-14-","lv"
"МК-26","26 (Аблукова,31)","ул. Аблукова, д. 31, ауд. 26 (Мед. колледж)","Факультеты","9","m1","mk-26-","mk"
"МК-28","28 (Аблукова,31)","ул. Аблукова, д. 31, ауд. 28 (Мед. колледж)","Факультеты","10","m1","mk-28-","mk"
"АМТ-33","33 (Наб.р.Свияги,158)","ул. Набережная р. Свияги, д. 158, ауд. 33 (АМТ)","АМТ","9","m1","amt","amt"
"АМТ-34","34 (Наб.р.Свияги,158)","ул. Набережная р. Свияги, д. 158, ауд. 34 (АМТ)","АМТ","11","m1","amt","amt"
"АМТ-35","35 (Наб.р.Свияги,158)","ул. Набережная р. Свияги, д. 158, ауд. 35 (АМТ)","АМТ","15","m1","amt","amt"
"АМТ-36","36 (Наб.р.Свияги,158)","ул. Набережная р. Свияги, д. 158, ауд. 36 (АМТ)","АМТ","11","m1","amt","amt"
"АМТ-39","39 (Наб.р.Свияги,158)","ул. Набережная р. Свияги, д. 158, ауд. 39 (АМТ)","АМТ","11","m1","amt","amt"
1 id class description part computers section prefix ip_group
2 3-111 3/111 (Наб.р.Свияги,3корп ауд. 3/111 ОСУП 13 okk1 111k
3 3-115 3/115 (Наб.р.Свияги,3корп ауд. 3/115 ОСУП 15 okk1 115k
4 3-118 3/118 (Наб.р.Свияги,3корп ауд. 3/118 ОСУП 16 okk1 118k
5 3-127 3/127 (Наб.р.Свияги,3корп ауд. 3/127 ОСУП 13 okk1 127k
6 3-522 3/522 (Наб.р.Свияги,3корп ауд. 3/522 ОСУП 11 okk1 522k
7 1-301 301 (Наб.р.Свияги,1корп) ауд. 1/301 "ауд. 1/301" ОСУП 10 okk1 301k
8 1-303 303 (Наб.р.Свияги,1корп) ауд. 1/303 "ауд. 1/303" ОСУП 10 okk1 303k
9 1-503 503 (Наб.р.Свияги,1корп) ауд. 1/503 "ауд. 1/503" ОСУП 10 okk1 503k
10 1-505 505 (Наб.р.Свияги,1корп) ауд. 1/505 "ауд. 1/505" ОСУП 10 okk1 505k
11 4а-402 402 (Пушкинская,4А) ул. Пушкинская, д. 4а, ауд. 402 (ОСУП) ОСУП 16 m1 pu-402- pu
12 4а-407 407 (Пушкинская,4А) ул. Пушкинская, д. 4а, ауд. 407 (ОСУП) ОСУП 15 m1 pu-407- pu
13 4а-806 806 (Пушкинская,4А) ул. Пушкинская, д. 4а, ауд. 806 (ОСУП) ОСУП 16 m1 pu-806- pu
14 ИЭиБ-10 10 (Федерации,29) ул. Федерации, д. 29, ауд. 10 (ИЭиБ) Факультеты 10 m1 fe-1- fe
15 МФ-207 207 (Ливчака,2/1) ул. Архитектора Ливчака, д. 2/1, ауд. 207 (МФ) Факультеты 10 m1 kl-207- kl
16 ЮФ-309 309 (Гончарова,40/9) 309а (Гончарова,40/9) ул. Гончарова, д. 40/9, ауд. 309 (ЮФ) Факультеты 11 m1 km-309- km
17 МУ-21 21 (Гимова,1) ул. Гимова, д. 1, ауд. 21 (Муз. училище) Факультеты 10 m1 mu-21- mu
18 ЭГФ-11 11 (Львовский,5) ул. Бульвар Львовский, д. 5, ауд. 11 (Зав. ЭГФ) Факультеты 11 m1 lv-11- lv
19 ЭГФ-14 14 (Львовский,5) ул. Бульвар Львовский, д. 5, ауд. 14 (Зав. ЭГФ) Факультеты 10 m1 lv-14- lv
20 МК-26 26 (Аблукова,31) ул. Аблукова, д. 31, ауд. 26 (Мед. колледж) Факультеты 9 m1 mk-26- mk
21 МК-28 28 (Аблукова,31) ул. Аблукова, д. 31, ауд. 28 (Мед. колледж) Факультеты 10 m1 mk-28- mk
22 АМТ-33 33 (Наб.р.Свияги,158) ул. Набережная р. Свияги, д. 158, ауд. 33 (АМТ) АМТ 9 m1 amt amt
23 АМТ-34 34 (Наб.р.Свияги,158) ул. Набережная р. Свияги, д. 158, ауд. 34 (АМТ) АМТ 11 m1 amt amt
24 АМТ-35 35 (Наб.р.Свияги,158) ул. Набережная р. Свияги, д. 158, ауд. 35 (АМТ) АМТ 15 m1 amt amt
25 АМТ-36 36 (Наб.р.Свияги,158) ул. Набережная р. Свияги, д. 158, ауд. 36 (АМТ) АМТ 11 m1 amt amt
26 АМТ-39 39 (Наб.р.Свияги,158) ул. Набережная р. Свияги, д. 158, ауд. 39 (АМТ) АМТ 11 m1 amt amt
+3 -1
View File
@@ -526,6 +526,7 @@ def run_stage(
"source_logs_dir": str(logs_dir),
"report_start": report_start.isoformat(),
"report_end": report_end.isoformat(),
"schedule_details": schedule.get("schedule_details", {}),
"report": _build_class_report(items, len(all_users)),
}
@@ -542,7 +543,8 @@ def run_stage(
print(f" - JSON files: {group_json.name}, {class_json.name}")
print(f" - Class report items: {len(items)}")
print(f" - Report period: {report_start.isoformat()} .. {report_end.isoformat()}")
print(" - Group report: schedule not available yet")
schedule_available = bool(schedule.get("available"))
print(f" - Schedule data: {'✓ available' if schedule_available else '✗ not available'}")
return {
"group_json": str(group_json),
+323 -45
View File
@@ -217,36 +217,105 @@ def _normalize_week_data(week: Dict[str, Any]) -> Dict[str, Any]:
}
def _build_scheme_table(week: Dict[str, Any]) -> str:
rows = []
def _build_scheme_table(
week: Dict[str, Any],
group_id: str,
schedule_details: Dict[str, List[Dict[str, str]]],
) -> str:
# Header row with lesson numbers
header_cells = "<th></th>" + "".join(
f"<th class='lesson-num'>{i}</th>" for i in range(1, 9)
)
rows = [f"<thead><tr>{header_cells}</tr></thead><tbody>"]
for day in week.get("days", []) or []:
codes = list(day.get("codes", []))[:8]
while len(codes) < 8:
codes.append("0")
cells = "".join(
f"<td><span class='scheme-cell code-{code}' title='Тип {code}'></span></td>"
for code in codes
)
rows.append(f"<tr><th>{day.get('weekday')}</th>{cells}</tr>")
date_str = day.get("date", "")
cells_list = []
for lesson_idx, code in enumerate(codes, start=1):
# Build tooltip
tip_parts = []
code_labels = {"0": "Нет пары", "1": "Пропуск", "2": "Не по расписанию", "3": "Проведено"}
tip_parts.append(code_labels.get(code, f"Тип {code}"))
if code in ("1", "3"):
# Look up schedule details for this slot
detail_key = f"{group_id}:{date_str}:{lesson_idx}"
details = schedule_details.get(detail_key, [])
for det in details:
t = det.get("teacher", "")
g = det.get("group", "")
parts = []
if t:
parts.append(t)
if g:
parts.append(g)
if parts:
tip_parts.append(" | ".join(parts))
title = " — ".join(tip_parts)
cells_list.append(
f"<td><span class='scheme-cell code-{code}' title='{title}'></span></td>"
)
# Append date to weekday label, e.g. "СР (09.04)"
d_str = day.get("date", "")
day_label = day.get("weekday", "")
if d_str and len(d_str) >= 10:
try:
d = date.fromisoformat(d_str)
day_label = f"{day_label} ({d.strftime('%d.%m')})"
except ValueError:
pass
rows.append(f"<tr><th>{day_label}</th>{''.join(cells_list)}</tr>")
return (
"<table class='scheme-table'><tbody>"
"<table class='scheme-table'>"
+ "".join(rows)
+ "</tbody></table>"
)
def _build_class_block(item: Dict[str, Any]) -> Dict[str, Any]:
def _build_class_block(
item: Dict[str, Any],
schedule_details: Optional[Dict[str, List[Dict[str, str]]]] = None,
group_description: str = "",
) -> Dict[str, Any]:
raw_weeks = item.get("weeks", []) or []
weeks = [_normalize_week_data(week) for week in raw_weeks]
group_id = item.get("id", "")
sched_details = schedule_details or {}
total_code1 = 0
total_code3 = 0
for week in weeks:
total = int(week.get("total_pairs", 0))
week["conducted_display"] = _format_percent(int(week.get("conducted", 0)), total)
week["missed_display"] = _format_percent(int(week.get("missed", 0)), total)
week["other_display"] = _format_percent(int(week.get("other", 0)), total)
week["scheme_html"] = _build_scheme_table(week)
week["other_label"] = "Не по расписанию"
week["scheme_html"] = _build_scheme_table(week, group_id, sched_details)
total_code1 += int(week.get("missed", 0))
total_code3 += int(week.get("conducted", 0))
# Warning banner for classes/groups with no schedule data at all
no_schedule = total_code1 == 0 and total_code3 == 0
# Aggregate totals across all weeks for legend
total_missed = sum(int(w.get("missed", 0)) for w in weeks)
total_conducted = sum(int(w.get("conducted", 0)) for w in weeks)
total_other = sum(int(w.get("other", 0)) for w in weeks)
grand_total = total_missed + total_conducted + total_other
if grand_total > 0:
item["pct_missed"] = round(total_missed * 100 / grand_total)
item["pct_conducted"] = round(total_conducted * 100 / grand_total)
item["pct_other"] = round(total_other * 100 / grand_total)
else:
item["pct_missed"] = 0
item["pct_conducted"] = 0
item["pct_other"] = 0
item["weeks"] = weeks
item["no_schedule_warning"] = no_schedule
item["description"] = group_description
item["chart_data"] = {
"labels": [str(week.get("short") or week.get("long") or "") for week in weeks],
"missed": [int(week.get("missed", 0)) for week in weeks],
@@ -256,7 +325,14 @@ def _build_class_block(item: Dict[str, Any]) -> Dict[str, Any]:
return item
def _aggregate_item(source_items: List[Dict[str, Any]], item_id: str, label: str, part_title: str) -> Dict[str, Any]:
def _aggregate_item(
source_items: List[Dict[str, Any]],
item_id: str,
label: str,
part_title: str,
schedule_details: Optional[Dict[str, List[Dict[str, str]]]] = None,
group_description: str = "",
) -> Dict[str, Any]:
return _build_class_block(
{
"id": item_id,
@@ -266,10 +342,69 @@ def _aggregate_item(source_items: List[Dict[str, Any]], item_id: str, label: str
"section_title": part_title,
"weeks": _merge_weeks(source_items),
"is_aggregate": True,
}
},
schedule_details=schedule_details,
group_description=group_description,
)
def _filter_days_in_weeks(
weeks: List[Dict[str, Any]],
*,
max_date: Optional[date] = None,
min_date: Optional[date] = None,
) -> List[Dict[str, Any]]:
"""Remove days outside the given date range and recompute week statistics."""
filtered: List[Dict[str, Any]] = []
for week in weeks:
kept_days = []
for day in week.get("days", []) or []:
d_str = day.get("date") or ""
try:
d = date.fromisoformat(d_str)
except (ValueError, TypeError):
continue
if max_date is not None and d >= max_date:
continue
if min_date is not None and d < min_date:
continue
kept_days.append(day)
if not kept_days:
continue
# recompute code_counts from kept days
code_counts: Dict[str, int] = {"0": 0, "1": 0, "2": 0, "3": 0}
for day in kept_days:
codes = list(str(day.get("codes") or day.get("lessons") or ""))[:8]
for c in codes:
if c in code_counts:
code_counts[c] += 1
filtered.append({
**week,
"days": kept_days,
"daily_summary": [
"".join(
list(str(day.get("codes") or day.get("lessons") or ""))[:8]
)
for day in kept_days
],
"code_counts": code_counts,
"total_pairs": sum(code_counts.values()),
"conducted": code_counts.get("3", 0),
"missed": code_counts.get("1", 0),
"other": code_counts.get("2", 0),
})
return filtered
def _ip_group_label(settings: Dict[str, Any], ipg: str) -> str:
"""Return display label for an ip_group from ``texts/ip_groups``."""
texts = (settings.get("texts") or {}).get("ip_groups") or {}
return str(texts.get(ipg, ipg))
def _build_class_report_model(workspace_root: Path, context: Dict[str, Any] | None) -> Dict[str, Any]:
config = _load_context_config(workspace_root, context)
classes_df: pd.DataFrame = config["classes"]
@@ -278,46 +413,186 @@ def _build_class_report_model(workspace_root: Path, context: Dict[str, Any] | No
report_json = _load_json(workspace_root / "result" / "reports" / "report_classes.json")
raw_items = report_json.get("report", {}).get("items", []) or []
raw_by_id = {str(item.get("group_id") or ""): item for item in raw_items}
schedule_details: Dict[str, List[Dict[str, str]]] = report_json.get("schedule_details", {}) or {}
part_order = [str(part).strip() for part in classes_df["part"].fillna("").tolist() if str(part).strip()]
ordered_parts: List[str] = []
for part in part_order:
if part not in ordered_parts:
ordered_parts.append(part)
# Parse switch date
processing = settings.get("processing", {}) or {}
switch_raw = processing.get("m1_ip_to_name_switch_date", "2026-04-08")
switch_date = _parse_date(switch_raw) or date(2026, 4, 8)
order_map = _row_order_map(classes_df)
# Collect ip_groups whose classes appear in schedule data
# (class column contains the room name used in schedule.xlsx)
ip_groups_with_schedule: set[str] = set()
for _, row in classes_df.iterrows():
ipg = str(row.get("ip_group") or "").strip()
class_room = str(row.get("class") or "").strip()
if ipg and class_room:
ip_groups_with_schedule.add(ipg)
# Build description lookup: group_id -> description from classes.csv
group_description: Dict[str, str] = {}
for _, row in classes_df.iterrows():
cid = str(row.get("id") or "").strip()
ipg = str(row.get("ip_group") or "").strip()
desc = str(row.get("description") or "").strip()
if cid:
group_description[cid] = desc
if ipg:
group_description[ipg] = desc
sections: List[Dict[str, Any]] = []
for part in ordered_parts:
entries: List[Dict[str, Any]] = []
if part == "Факультеты":
faculty_sources = [raw_by_id[g] for g in ["fe", "kl", "km", "lv", "mk", "mu"] if g in raw_by_id]
if faculty_sources:
entries.append(_aggregate_item(faculty_sources, "before_804", "до 8.04", part))
for raw in raw_items:
group_id = str(raw.get("group_id") or "")
if _part_name(classes_df, group_id) != part:
continue
entries.append(
_build_class_block(
{
"id": group_id,
"label": _display_label(classes_df, group_id),
"title": str(raw.get("title") or group_id),
"part_id": part,
"section_title": part,
"weeks": raw.get("weeks", []) or [],
"order": order_map.get(group_id, 9999),
"is_aggregate": False,
}
)
# ==================================================================
# 1. ОСУП — classes only, no ip_group duplicates
# ==================================================================
osup_entries: List[Dict[str, Any]] = []
for raw in raw_items:
group_id = str(raw.get("group_id") or "")
if _part_name(classes_df, group_id) != "ОСУП":
continue
# Skip ip_group entries whose classes are listed individually
if str(raw.get("kind") or "") == "ip_group" and group_id in ip_groups_with_schedule:
continue
osup_entries.append(
_build_class_block({
"id": group_id,
"label": _display_label(classes_df, group_id),
"title": str(raw.get("title") or group_id),
"part_id": "ОСУП",
"section_title": "ОСУП",
"weeks": raw.get("weeks", []) or [],
"is_aggregate": False,
},
schedule_details=schedule_details,
group_description=group_description.get(group_id, ""),
)
)
if osup_entries:
sections.append({"id": "ОСУП", "title": "ОСУП", "entries": osup_entries})
entries.sort(key=lambda item: (0 if item.get("is_aggregate") else 1, item.get("order", 9999), item.get("label", "")))
if entries:
sections.append({"id": part, "title": part, "entries": entries})
# ==================================================================
# 2. Факультеты (до 8.04) — grouped by ip_group, pre-switch only
# ==================================================================
faculty_ip_groups = ["fe", "kl", "km", "lv", "mk", "mu"]
pre_entries: List[Dict[str, Any]] = []
for ipg in faculty_ip_groups:
if ipg not in raw_by_id:
continue
raw = raw_by_id[ipg]
label = _ip_group_label(settings, ipg)
weeks = _filter_days_in_weeks(
raw.get("weeks", []) or [],
max_date=switch_date, # only days BEFORE switch_date
)
if not weeks:
continue
pre_entries.append(
_build_class_block({
"id": ipg,
"label": label,
"title": label,
"part_id": "Факультеты",
"section_title": "Факультеты (до 8.04)",
"weeks": weeks,
"is_aggregate": False,
},
schedule_details=schedule_details,
group_description=group_description.get(ipg, ""),
)
)
if pre_entries:
sections.append({
"id": "Факультеты_до_8_04",
"title": "Факультеты (до 8.04)",
"entries": pre_entries,
})
# ==================================================================
# 3. Факультеты (после 8.04) — class entries, post-switch only
# ==================================================================
# Collect all Факультеты class IDs from classes.csv (even those with no data)
faculty_class_ids: List[str] = []
for _, row in classes_df.iterrows():
if str(row.get("part") or "").strip() == "Факультеты":
cid = str(row.get("id") or "").strip()
if cid and cid not in faculty_class_ids:
faculty_class_ids.append(cid)
# Build a template for empty weeks (from the first available item)
empty_weeks_template: List[Dict[str, Any]] = []
for raw in raw_items:
ww = raw.get("weeks", []) or []
if ww:
empty_weeks_template = ww
break
post_entries: List[Dict[str, Any]] = []
for group_id in faculty_class_ids:
if group_id in raw_by_id:
raw = raw_by_id[group_id]
weeks = _filter_days_in_weeks(
raw.get("weeks", []) or [],
min_date=switch_date,
)
elif empty_weeks_template:
# Create empty weeks for classes with no data at all
weeks = _filter_days_in_weeks(
empty_weeks_template,
min_date=switch_date,
)
# Zero out all codes
for wk in weeks:
for day in wk.get("days", []):
day["codes"] = ["0"] * 8
day["lessons"] = "0" * 8
wk["code_counts"] = {"0": 48, "1": 0, "2": 0, "3": 0}
else:
continue
label = _display_label(classes_df, group_id)
post_entries.append(
_build_class_block({
"id": group_id,
"label": label,
"title": label,
"part_id": "Факультеты",
"section_title": "Факультеты (после 8.04)",
"weeks": weeks,
"is_aggregate": False,
},
schedule_details=schedule_details,
group_description=group_description.get(group_id, ""),
)
)
if post_entries:
sections.append({
"id": "Факультеты_после_8_04",
"title": "Факультеты (после 8.04)",
"entries": post_entries,
})
# ==================================================================
# 4. АМТ
# ==================================================================
amt_entries: List[Dict[str, Any]] = []
if "amt" in raw_by_id:
raw = raw_by_id["amt"]
amt_entries.append(
_build_class_block({
"id": "amt",
"label": "АМТ",
"title": "АМТ",
"part_id": "АМТ",
"section_title": "АМТ",
"weeks": raw.get("weeks", []) or [],
"is_aggregate": False,
},
schedule_details=schedule_details,
group_description=group_description.get("amt", ""),
)
)
if amt_entries:
sections.append({"id": "АМТ", "title": "АМТ", "entries": amt_entries})
active_section = sections[0]["id"] if sections else ""
active_class = sections[0]["entries"][0]["id"] if sections and sections[0]["entries"] else ""
@@ -363,6 +638,7 @@ def run_stage(workspace_root: Path, context: Dict[str, Any] | None = None) -> Di
template_dir / "report_class.jinja",
template_dir / "report_group.jinja",
template_dir / "report.css",
template_dir / "chart.umd.min.js",
template_dir / "report_class.js",
template_dir / "report_group.js",
]
@@ -373,6 +649,7 @@ def run_stage(workspace_root: Path, context: Dict[str, Any] | None = None) -> Di
css_text = _load_text(template_dir / "report.css")
class_js = _load_text(template_dir / "report_class.js")
group_js = _load_text(template_dir / "report_group.js")
chart_js_content = _load_text(template_dir / "chart.umd.min.js")
class_report = _build_class_report_model(workspace_root, context)
group_report = _build_group_report_model(workspace_root)
@@ -383,6 +660,7 @@ def run_stage(workspace_root: Path, context: Dict[str, Any] | None = None) -> Di
"title": class_report["title"],
"hint": f"Период: {class_report['period']['start']} — {class_report['period']['end']}",
"css_text": css_text,
"chart_js_content": chart_js_content,
"js_text": class_js,
"report": class_report,
"report_json": json.dumps(class_report, ensure_ascii=False),
+4
View File
@@ -91,4 +91,8 @@ def run_stage(
print(f" - Classes: {len(config['classes'])}")
print(f" - IP ranges: {len(config['settings'].get('class_ips', {}))}")
# Count classes with a non-empty class column (room name for schedule matching)
mapped = config["classes"]["class"].notna() & (config["classes"]["class"] != "")
print(f" - Classes with room name: {mapped.sum()} / {len(config['classes'])}")
return config
+264 -34
View File
@@ -1,26 +1,249 @@
"""Stage 3: Prepare university schedule data.
"""Stage 3: Parse university schedule export (XLSX) into structured lesson data.
This stage is intentionally a placeholder for the time being. The project
already stores lesson time windows in settings.yaml, but the actual university
schedule export is not available yet.
Reads the schedule from ``input/schedule.xlsx``, filters rows matching the
computer-class rooms listed in ``classes.csv`` (column ``class``),
and produces a list of ``group_lessons`` entries that later stages use to
determine whether a lesson was scheduled for a given class/date/lesson.
"""
from __future__ import annotations
from datetime import datetime, timezone
import re
from datetime import datetime, time, timezone, date as date_type
from pathlib import Path
from typing import Dict, Any
from typing import Any, Dict, List, Optional, Tuple
import pandas as pd
from lib.stage_load_settings import SettingsLoader
def _normalize_schedule(settings: Dict[str, Any]) -> Dict[str, Any]:
"""Extract the schedule section from settings in a stable JSON-friendly form."""
year = settings.get("year", {}) if isinstance(settings, dict) else {}
lessons = []
# ---------------------------------------------------------------------------
# helpers
# ---------------------------------------------------------------------------
_TIME_WINDOW_RE = re.compile(
r"^(?P<start>\d{2}:\d{2})\s*-\s*(?P<end>\d{2}:\d{2})\s*\((?P<day>\d)\)$"
)
_SCHEDULE_XLSX = "input" / Path("schedule.xlsx")
def _parse_time_window(
raw: str,
) -> Optional[Tuple[int, int, int]]:
"""Parse a time-window string.
Expected format: ``HH:MM - HH:MM (D)`` where *D* is the day-of-week
(1 = Monday … 6 = Saturday).
Returns ``(weekday, start_hour, start_minute)`` or ``None``.
"""
m = _TIME_WINDOW_RE.match(raw.strip())
if not m:
return None
weekday = int(m.group("day"))
if not (1 <= weekday <= 6):
return None
sh, sm = m.group("start").split(":")
return (weekday, int(sh), int(sm))
def _lesson_number(
start_hour: int, start_minute: int, lesson_windows: List[Dict[str, Any]]
) -> Optional[int]:
"""Map a start time to a lesson number (1‑based) using the configured windows."""
for entry in lesson_windows:
raw = str(entry.get("start", ""))
# handle ISO‑format with timezone offset
raw = raw.split("+")[0].split("-")[0].strip()
try:
t = time.fromisoformat(raw)
except (ValueError, TypeError):
continue
if t.hour == start_hour and t.minute == start_minute:
try:
return int(entry["lesson"])
except (TypeError, ValueError):
return None
return None
def _build_room_map(classes_df: pd.DataFrame) -> Dict[str, List[str]]:
"""Build ``{room_name: [class_id, …]}`` mapping from *classes_df*.
The room name is taken from the ``class`` column (e.g. ``402 (Пушкинская,4А)``).
Each room may map to **multiple** class identifiers:
* the class ``id`` (e.g. ``4а-402``) – used for post‑switch per‑class CSV files
* the ``ip_group`` (e.g. ``pu``) – used for pre‑switch IP‑group CSV files
This ensures schedule lookups work regardless of which grouping key the
later stages use as the output filename stem.
"""
mapping: Dict[str, List[str]] = {}
for _, row in classes_df.iterrows():
room = str(row.get("class") or "").strip()
if not room:
continue
if room not in mapping:
mapping[room] = []
class_id = str(row["id"])
if class_id not in mapping[room]:
mapping[room].append(class_id)
ip_group = str(row.get("ip_group") or "").strip()
if ip_group and ip_group not in mapping[room]:
mapping[room].append(ip_group)
return mapping
# ---------------------------------------------------------------------------
# XLSX reader
# ---------------------------------------------------------------------------
def _parse_xlsx(
xlsx_path: Path,
lesson_windows: List[Dict[str, Any]],
room_map: Dict[str, List[str]],
) -> Tuple[List[Dict[str, Any]], Dict[str, List[Dict[str, str]]]]:
"""Iterate over *xlsx_path* and yield schedule entries for known rooms.
For each matching row one entry per mapped class identifier is created
(both the class ``id`` and the ``ip_group`` if set).
Returns a tuple ``(group_lessons, schedule_details)`` where
``schedule_details`` maps ``"class_id:date:lesson"`` to a list of
``{"teacher": …, "group": …}`` dicts (for tooltips).
"""
import openpyxl
group_lessons: List[Dict[str, Any]] = []
schedule_details: Dict[str, List[Dict[str, str]]] = {}
stats_known = 0
stats_unknown = 0
stats_parse_error = 0
wb = openpyxl.load_workbook(xlsx_path, read_only=True, data_only=True)
ws = wb["Расписание"]
for row in ws.iter_rows(min_row=2, values_only=True):
vals = [str(v) if v is not None else "" for v in row]
if len(vals) < 7:
continue
raw_date = vals[0][:10] if vals[0] else ""
raw_time = vals[1]
raw_room = vals[4]
raw_group = vals[2]
raw_teacher = vals[3]
if not raw_date or not raw_time or not raw_room:
continue
# ---- skip rooms we do not track -----------------------------------
class_ids = room_map.get(raw_room)
if class_ids is None:
stats_unknown += 1
continue
# ---- parse date ---------------------------------------------------
try:
lesson_date = date_type.fromisoformat(raw_date)
except (ValueError, TypeError):
stats_parse_error += 1
continue
# ---- parse time window --------------------------------------------
parsed = _parse_time_window(raw_time)
if parsed is None:
stats_parse_error += 1
continue
weekday_num, start_hour, start_min = parsed
# sanity check: weekday from time window must match the actual date
actual_weekday = lesson_date.isoweekday() # 1=Mon…7=Sun
if actual_weekday == 7: # Sunday – skip
stats_parse_error += 1
continue
if weekday_num != actual_weekday:
# data inconsistency – skip
stats_parse_error += 1
continue
# ---- resolve lesson number ----------------------------------------
lesson = _lesson_number(start_hour, start_min, lesson_windows)
if lesson is None:
stats_parse_error += 1
continue
# ---- create one entry per mapped class identifier -----------------
for cid in class_ids:
group_lessons.append(
{
"class_id": cid,
"date": lesson_date.isoformat(),
"lesson": lesson,
"weekday": weekday_num,
}
)
# Collect teacher/group for tooltips
detail_key = f"{cid}:{lesson_date.isoformat()}:{lesson}"
if detail_key not in schedule_details:
schedule_details[detail_key] = []
# Avoid duplicate teacher+group within the same key
detail_entry = {"teacher": raw_teacher, "group": raw_group}
if detail_entry not in schedule_details[detail_key]:
schedule_details[detail_key].append(detail_entry)
stats_known += 1
wb.close()
# deduplicate (same class/date/lesson may appear multiple times)
seen: set[Tuple[str, str, int]] = set()
deduped: List[Dict[str, Any]] = []
for entry in group_lessons:
key = (entry["class_id"], entry["date"], entry["lesson"])
if key not in seen:
seen.add(key)
deduped.append(entry)
print(f" - XLSX rows matched to known rooms : {stats_known}")
print(f" - XLSX rows skipped (unknown room) : {stats_unknown}")
print(f" - XLSX rows skipped (parse error) : {stats_parse_error}")
print(f" - Unique (class_id, date, lesson) : {len(deduped)}")
return deduped, schedule_details
# ---------------------------------------------------------------------------
# public stage entry point
# ---------------------------------------------------------------------------
def run_stage(
workspace_root: Path,
context: Dict[str, Any] | None = None,
) -> Dict[str, Any]:
"""Parse the XLSX schedule export and produce structured lesson data."""
if context and "stage_load_settings" in context:
config = context["stage_load_settings"]
else:
loader = SettingsLoader(workspace_root)
config = loader.get_config()
settings = config["settings"]
classes_df = config["classes"]
# -- lesson windows from settings ---------------------------------------
year = settings.get("year", {}) if isinstance(settings, dict) else {}
lesson_windows: List[Dict[str, Any]] = []
for item in year.get("schedule", []) or []:
lessons.append(
lesson_windows.append(
{
"lesson": item.get("lesson"),
"start": str(item.get("start")),
@@ -28,31 +251,38 @@ def _normalize_schedule(settings: Dict[str, Any]) -> Dict[str, Any]:
}
)
return {
"available": False,
"source": None,
# -- room -> class_id map -----------------------------------------------
room_map = _build_room_map(classes_df)
print(f" - Known schedule rooms: {len(room_map)}")
# -- parse XLSX ---------------------------------------------------------
xlsx_path = workspace_root / _SCHEDULE_XLSX
if not xlsx_path.exists():
print(" - ⚠ schedule.xlsx not found – falling back to empty schedule")
group_lessons: List[Dict[str, Any]] = []
schedule_details: Dict[str, List[Dict[str, str]]] = {}
else:
group_lessons, schedule_details = _parse_xlsx(xlsx_path, lesson_windows, room_map)
schedule: Dict[str, Any] = {
"available": bool(group_lessons),
"source": str(xlsx_path),
"generated_at": datetime.now(timezone.utc).isoformat(),
"lesson_windows": lessons,
"group_lessons": [],
"note": "University schedule export is not available yet.",
"lesson_windows": lesson_windows,
"group_lessons": group_lessons,
"schedule_details": schedule_details,
"note": (
f"Parsed {len(group_lessons)} unique schedule entries "
f"from {xlsx_path.name}"
if group_lessons
else "No schedule entries found."
),
}
def run_stage(
workspace_root: Path,
context: Dict[str, Any] | None = None,
) -> Dict[str, Any]:
"""Create a placeholder schedule payload for the later stages."""
if context and "stage_load_settings" in context:
config = context["stage_load_settings"]
else:
loader = SettingsLoader(workspace_root)
config = loader.get_config()
schedule = _normalize_schedule(config["settings"])
print("✓ Schedule stage initialized")
print(" - Source export: not available yet")
print(f" - Lesson windows: {len(schedule['lesson_windows'])}")
print("✓ Schedule stage completed")
print(f" - Source: {xlsx_path.name}")
print(f" - Lesson windows : {len(lesson_windows)}")
print(f" - Group lessons : {len(group_lessons)}")
print(f" - Detail entries : {len(schedule_details)}")
return {"schedule": schedule}
+7 -6
View File
@@ -204,9 +204,9 @@ class LogProcessor:
prefix_part = match.group(1) # e.g., "303k"
# Find matching class by prefix
# Find matching class by prefix (case-insensitive)
for _, row in self.classes_df.iterrows():
if row["prefix"] == prefix_part:
if str(row["prefix"]).lower() == prefix_part.lower():
return row["id"]
elif section == "m1":
# For m1, format is like "pu-402-1" (prefix-class-station)
@@ -219,14 +219,15 @@ class LogProcessor:
# "pu-402-1" -> look for class with prefix starting with "pu"
prefix_start = parts[0]
# Find matching class
# Find matching class (case-insensitive)
comp_lower = computer.lower()
for _, row in self.classes_df.iterrows():
row_prefix = row["prefix"]
row_prefix = str(row["prefix"]).lower()
# Check if the computer prefix matches this class
# e.g., row_prefix "pu-402-" matches computer "pu-402-1"
if row_prefix.startswith(prefix_start + "-"):
if row_prefix.startswith(prefix_start.lower() + "-"):
# Check if the class part matches
if computer.startswith(row_prefix):
if comp_lower.startswith(row_prefix):
return row["id"]
return None
File diff suppressed because one or more lines are too long
Binary file not shown.
+11 -1
View File
@@ -1,5 +1,5 @@
report_start: 2026-02-09
report_end: 2026-04-17
report_end: 2026-06-21
year:
first_week: 2026-01-05
@@ -56,3 +56,13 @@ processing:
m1_ip_to_name_switch_date: 2026-04-08
amt_group_id: amt
amt_class_id: АМТ-33
texts:
ip_groups:
pu: Пушкинская
fe: ИЭиБ
kl: МФ
km: ЮФ
mu: Муз. училище
lv: Зав. ЭГФ
mk: Мед. колледж
+20
View File
File diff suppressed because one or more lines are too long
+117 -11
View File
@@ -223,6 +223,43 @@ body {
color: var(--muted);
font-size: 13px;
}
.class-note.desc {
color: var(--text);
font-size: 12px;
opacity: 0.75;
}
.class-note.warning {
color: #b45309;
background: #fffbeb;
border: 1px solid #fde68a;
border-radius: 6px;
padding: 6px 10px;
margin-top: 8px;
font-size: 13px;
}
.class-legend {
display: flex;
gap: 16px;
margin-top: 8px;
font-size: 12px;
}
.legend-item {
padding: 2px 8px;
border-radius: 4px;
}
.legend-conducted {
background: #dcfce7;
color: #166534;
}
.legend-missed {
background: #fef2f2;
color: #991b1b;
}
.legend-other {
background: #fffbeb;
color: #92400e;
}
.class-chart {
position: relative;
@@ -235,26 +272,21 @@ body {
height: 320px;
}
.class-table,
.scheme-table,
.table {
width: 100%;
border-collapse: collapse;
}
.class-table th,
.class-table td,
.scheme-table th,
.scheme-table td,
.table th,
.table td {
border-bottom: 1px solid var(--line);
padding: 10px 12px;
vertical-align: top;
text-align: left;
}
.class-table th,
.scheme-table th,
.table th {
font-size: 13px;
@@ -285,7 +317,7 @@ body {
.scheme-table th,
.scheme-table td {
padding: 6px;
padding: 3px 4px;
text-align: center;
}
@@ -294,16 +326,64 @@ body {
text-align: left;
white-space: nowrap;
}
.lesson-num {
font-size: 11px;
color: var(--muted);
font-weight: 400;
padding: 2px 6px !important;
}
.scheme-cell {
display: inline-block;
width: 18px;
height: 18px;
width: 14px;
height: 14px;
border-radius: 4px;
background: var(--empty);
border: 1px solid rgba(0, 0, 0, 0.06);
}
.class-weeks {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 10px;
}
.week-block {
border: 1px solid var(--line);
border-radius: 8px;
padding: 8px 10px;
}
.week-header {
font-weight: 600;
font-size: 13px;
margin-bottom: 4px;
}
.week-stats {
display: flex;
gap: 12px;
flex-wrap: wrap;
margin-bottom: 6px;
font-size: 12px;
}
.stat {
padding: 1px 6px;
border-radius: 3px;
}
.stat-cond {
background: #dcfce7;
color: #166534;
}
.stat-miss {
background: #fef2f2;
color: #991b1b;
}
.stat-oth {
background: #fffbeb;
color: #92400e;
}
.stat-total {
color: var(--muted);
}
.scheme-cell.code-0 {
background: var(--empty);
}
@@ -356,6 +436,13 @@ body {
}
@media print {
@page {
margin: 10mm;
}
* {
-webkit-print-color-adjust: exact !important;
print-color-adjust: exact !important;
}
body {
background: #fff;
}
@@ -381,8 +468,27 @@ body {
.print-nav {
box-shadow: none;
}
.table th,
.class-table th {
position: static;
.week-block {
break-inside: avoid;
page-break-inside: avoid;
}
.class-weeks {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 6px;
}
.class-chart {
min-height: auto;
margin-bottom: 4px;
padding: 0;
}
.class-chart img {
max-width: 100%;
width: 100% !important;
height: auto !important;
margin: 0;
}
.week-chart {
margin: 0;
}
}
+28 -18
View File
@@ -7,7 +7,7 @@
<style>
{{ css_text | safe }}
</style>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>{{ chart_js_content | safe }}</script>
</head>
<body>
<div class="page">
@@ -84,33 +84,43 @@
<div>
<div class="class-kicker">{{ section.title }}</div>
<h3>{{ item.label }}</h3>
{% if item.description %}
<div class="class-note desc">{{ item.description }}</div>
{% endif %}
{% if item.no_schedule_warning %}
<div class="class-note warning">
⚠ Нет данных о расписании в этих аудиториях
</div>
{% endif %}
{% if item.source_labels %}
<div class="class-note">
{{ item.source_labels | join(', ') }}
</div>
{% endif %}
<div class="class-legend">
<span class="legend-item legend-conducted">Проведено {{ item.pct_conducted }}%</span>
<span class="legend-item legend-missed">Пропущено {{ item.pct_missed }}%</span>
<span class="legend-item legend-other">Не по расписанию {{ item.pct_other }}%</span>
</div>
</div>
</div>
<div class="class-chart">
<canvas class="week-chart" data-chart-for="{{ item.id }}"></canvas>
</div>
<div class="class-table-wrap">
<table class="class-table">
<tbody>
{% for week in item.weeks %}
<tr>
<td class="week-label">{{ week.long }}</td>
<td class="num">{{ week.total_pairs }}</td>
<td class="num">{{ week.conducted_display }}</td>
<td class="num">{{ week.missed_display }}</td>
<td class="num">{{ week.other_display }}</td>
<td class="scheme-cell-wrap">
{{ week.scheme_html | safe }}
</td>
</tr>
{% endfor %}
</tbody>
</table>
<div class="class-weeks">
{% for week in item.weeks %}
<div class="week-block">
<div class="week-header">{{ week.long }}</div>
<div class="week-stats">
<span class="stat stat-cond">Проведено {{ week.conducted_display }}</span>
<span class="stat stat-miss">Пропущено {{ week.missed_display }}</span>
<span class="stat stat-oth">Не по расписанию {{ week.other_display }}</span>
</div>
<div class="scheme-cell-wrap">
{{ week.scheme_html | safe }}
</div>
</div>
{% endfor %}
</div>
</article>
{% endfor %}
+79 -2
View File
@@ -56,7 +56,7 @@
borderRadius: 4,
},
{
label: "Иное",
label: "Не по расписанию",
data: other,
backgroundColor: "#f59e0b",
stack: "pairs",
@@ -74,6 +74,7 @@
options: {
responsive: true,
maintainAspectRatio: false,
animation: false,
interaction: {
mode: "index",
intersect: false,
@@ -156,8 +157,84 @@
}
}
// ---- Print support: convert canvases to static images ----
function prepareForPrint() {
var report = window.__CLASS_REPORT__ || {};
var sections = Array.isArray(report.sections) ? report.sections : [];
var allEntries = sections.flatMap(function (s) {
return s.entries || [];
});
// Activate each class one-by-one, build its chart, capture the image,
// then move on. This ensures Chart.js renders each canvas properly.
var idx = 0;
var storedImages = {};
function processNext() {
if (idx >= allEntries.length) {
// All done — replace canvases with stored images
Object.keys(storedImages).forEach(function (classId) {
var canvas = qs('.week-chart[data-chart-for="' + classId + '"]');
if (!canvas) return;
var img = document.createElement("img");
img.src = storedImages[classId];
img.alt = "Chart";
img.style.width = "100%";
img.style.height = "320px";
img.style.objectFit = "contain";
canvas.parentNode.replaceChild(img, canvas);
});
// Restore original class
if (originalClassId) {
setActiveClass(originalClassId, false, report);
}
// Short delay then open print dialog
setTimeout(function () {
window.print();
}, 50);
return;
}
var entry = allEntries[idx];
var cid = entry.id;
if (!cid) {
idx++;
processNext();
return;
}
// Switch to this class to make its canvas visible
setActiveClass(cid, false, report);
// Wait for layout + Chart.js to render
setTimeout(function () {
// Build chart if not already built
buildChartForClass(cid, report);
// Wait again for chart animation to finish
setTimeout(function () {
var chart = chartStore.get(cid);
if (chart) {
storedImages[cid] = chart.toBase64Image();
}
idx++;
processNext();
}, 100);
}, 50);
}
// Remember which class was active
var originalClassId = null;
var activeBlock = qs(".class-block.active");
if (activeBlock) originalClassId = activeBlock.dataset.classId;
// Start sequential processing from first entry
idx = 0;
processNext();
}
window.printReport = function printReport() {
window.print();
prepareForPrint();
// print dialog opens inside prepareForPrint after all charts are processed
};
if (document.readyState === "loading") {