Refactor code structure for improved readability and maintainability
This commit is contained in:
@@ -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),
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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
@@ -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}
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user