feat: Add stages for processing university schedule and authentication logs
- Implemented `stage_parse_schedule.py` to normalize and prepare university schedule data. - Created `stage_process_logs.py` for processing authentication logs and generating session records. - Added necessary classes and methods for log entry parsing, session extraction, and CSV output. - Updated `settings.yaml` with new schedule and processing configurations. - Introduced new templates and styles for report generation, including HTML and CSS files. - Added main entry point `run.py` to execute the attendance processing pipeline. - Included `.gitkeep` files in `output` and `result` directories to maintain structure.
This commit is contained in:
@@ -0,0 +1 @@
|
||||
"""Library for processing computer class attendance data."""
|
||||
+149
@@ -0,0 +1,149 @@
|
||||
"""Main pipeline for processing attendance data."""
|
||||
|
||||
from pathlib import Path
|
||||
from typing import Dict, Any, List
|
||||
from dataclasses import dataclass
|
||||
import inspect
|
||||
|
||||
|
||||
@dataclass
|
||||
class Stage:
|
||||
"""Represents a processing stage."""
|
||||
|
||||
name: str
|
||||
description: str
|
||||
module_name: str
|
||||
run_function: str = "run_stage"
|
||||
|
||||
|
||||
class Pipeline:
|
||||
"""Manages the execution of sequential processing stages."""
|
||||
|
||||
def __init__(self, workspace_root: Path):
|
||||
"""
|
||||
Initialize the pipeline.
|
||||
|
||||
Args:
|
||||
workspace_root: Root directory of the project
|
||||
"""
|
||||
self.workspace_root = Path(workspace_root)
|
||||
self.stages: List[Stage] = []
|
||||
self.context: Dict[str, Any] = {"workspace_root": workspace_root}
|
||||
|
||||
def add_stage(self, stage: Stage) -> None:
|
||||
"""
|
||||
Add a stage to the pipeline.
|
||||
|
||||
Args:
|
||||
stage: Stage to add
|
||||
"""
|
||||
self.stages.append(stage)
|
||||
|
||||
def run(self) -> Dict[str, Any]:
|
||||
"""
|
||||
Execute all stages in sequence.
|
||||
|
||||
Returns:
|
||||
Final context with results from all stages
|
||||
"""
|
||||
print("=" * 60)
|
||||
print("ATTENDANCE PROCESSING PIPELINE")
|
||||
print("=" * 60)
|
||||
|
||||
for i, stage in enumerate(self.stages, 1):
|
||||
print(f"\n[Stage {i}] {stage.name}")
|
||||
print(f"Description: {stage.description}")
|
||||
print("-" * 60)
|
||||
|
||||
try:
|
||||
# Dynamically import and run the stage
|
||||
module = self._import_stage(stage.module_name)
|
||||
run_func = getattr(module, stage.run_function)
|
||||
|
||||
# Run the stage with current context.
|
||||
# Stages may accept either (workspace_root) or (workspace_root, context).
|
||||
params = inspect.signature(run_func).parameters
|
||||
if len(params) >= 2:
|
||||
result = run_func(self.workspace_root, self.context)
|
||||
else:
|
||||
result = run_func(self.workspace_root)
|
||||
|
||||
# Store result in context
|
||||
self.context[stage.module_name] = result
|
||||
|
||||
print(f"✓ Stage completed successfully\n")
|
||||
|
||||
except Exception as e:
|
||||
print(f"✗ Stage failed with error: {str(e)}\n")
|
||||
raise
|
||||
|
||||
print("=" * 60)
|
||||
print("PIPELINE COMPLETED SUCCESSFULLY")
|
||||
print("=" * 60)
|
||||
|
||||
return self.context
|
||||
|
||||
def _import_stage(self, module_name: str):
|
||||
"""
|
||||
Dynamically import a stage module.
|
||||
|
||||
Args:
|
||||
module_name: Name of the module to import
|
||||
|
||||
Returns:
|
||||
Imported module
|
||||
"""
|
||||
import importlib
|
||||
|
||||
full_module_name = f"lib.{module_name}"
|
||||
return importlib.import_module(full_module_name)
|
||||
|
||||
|
||||
def create_default_pipeline(workspace_root: Path) -> Pipeline:
|
||||
"""
|
||||
Create a pipeline with default stages.
|
||||
|
||||
Args:
|
||||
workspace_root: Root directory of the project
|
||||
|
||||
Returns:
|
||||
Configured pipeline ready to run
|
||||
"""
|
||||
pipeline = Pipeline(workspace_root)
|
||||
|
||||
# Stage 1: Load settings
|
||||
pipeline.add_stage(Stage(
|
||||
name="Load Settings",
|
||||
description="Load configuration from settings.yaml and class data from classes.csv",
|
||||
module_name="stage_load_settings"
|
||||
))
|
||||
|
||||
# Stage 2: Process logs
|
||||
pipeline.add_stage(Stage(
|
||||
name="Process Authentication Logs",
|
||||
description="Extract sessions from Windows authentication logs and group by class",
|
||||
module_name="stage_process_logs"
|
||||
))
|
||||
|
||||
# Stage 3: Parse university schedule export (placeholder for now)
|
||||
pipeline.add_stage(Stage(
|
||||
name="Parse University Schedule",
|
||||
description="Prepare schedule data for future group attendance calculations",
|
||||
module_name="stage_parse_schedule"
|
||||
))
|
||||
|
||||
# Stage 4: Build report data
|
||||
pipeline.add_stage(Stage(
|
||||
name="Build Report Data",
|
||||
description="Aggregate processed sessions into JSON report data",
|
||||
module_name="stage_build_report_data"
|
||||
))
|
||||
|
||||
# Stage 5: Generate HTML reports
|
||||
pipeline.add_stage(Stage(
|
||||
name="Generate HTML Reports",
|
||||
description="Create standalone HTML reports for groups and classes",
|
||||
module_name="stage_generate_reports_html"
|
||||
))
|
||||
|
||||
return pipeline
|
||||
@@ -0,0 +1,552 @@
|
||||
"""Stage 4: Build JSON data used by HTML reports."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import csv
|
||||
import json
|
||||
from dataclasses import asdict, dataclass
|
||||
from datetime import datetime, timezone, date, timedelta, time
|
||||
from pathlib import Path
|
||||
from typing import Dict, Any, List, Optional, Tuple
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from lib.stage_load_settings import SettingsLoader
|
||||
|
||||
|
||||
@dataclass
|
||||
class ReportItem:
|
||||
"""Aggregated statistics for one output group/class file."""
|
||||
|
||||
group_id: str
|
||||
kind: str
|
||||
title: str
|
||||
source_rows: int
|
||||
unique_users: int
|
||||
unique_stations: int
|
||||
total_minutes: float
|
||||
first_start: Optional[str]
|
||||
last_end: Optional[str]
|
||||
by_date: Dict[str, int]
|
||||
top_users: List[Dict[str, Any]]
|
||||
weeks: List[Dict[str, Any]]
|
||||
|
||||
|
||||
def _load_context_config(
|
||||
workspace_root: Path, context: Dict[str, Any] | None
|
||||
) -> Dict[str, Any]:
|
||||
if context and "stage_load_settings" in context:
|
||||
return context["stage_load_settings"]
|
||||
loader = SettingsLoader(workspace_root)
|
||||
return loader.get_config()
|
||||
|
||||
|
||||
def _safe_float_minutes(start: str, end: str) -> float:
|
||||
try:
|
||||
start_dt = datetime.fromisoformat(start)
|
||||
end_dt = datetime.fromisoformat(end)
|
||||
except ValueError:
|
||||
return 0.0
|
||||
|
||||
delta = end_dt - start_dt
|
||||
return max(delta.total_seconds() / 60.0, 0.0)
|
||||
|
||||
|
||||
def _parse_dt(value: str) -> Optional[datetime]:
|
||||
try:
|
||||
return datetime.fromisoformat(value)
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
def _parse_date_value(value: Any) -> Optional[date]:
|
||||
if isinstance(value, datetime):
|
||||
return value.date()
|
||||
if hasattr(value, "year") and hasattr(value, "month") and hasattr(value, "day"):
|
||||
try:
|
||||
return date(value.year, value.month, value.day)
|
||||
except ValueError:
|
||||
return None
|
||||
if value is None:
|
||||
return None
|
||||
|
||||
text = str(value).strip()
|
||||
if not text:
|
||||
return None
|
||||
|
||||
for fmt in ("%Y-%m-%d", "%d.%m.%Y"):
|
||||
try:
|
||||
return datetime.strptime(text, fmt).date()
|
||||
except ValueError:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def _normalize_week_type(value: Any) -> Optional[str]:
|
||||
if value is None:
|
||||
return None
|
||||
|
||||
text = str(value).strip().upper()
|
||||
mapping = {
|
||||
"I": "I",
|
||||
"1": "I",
|
||||
"Н": "I",
|
||||
"НЕЧЕТ": "I",
|
||||
"НЕЧЁТ": "I",
|
||||
"НЕЧЕТНАЯ": "I",
|
||||
"НЕЧЁТНАЯ": "I",
|
||||
"II": "II",
|
||||
"2": "II",
|
||||
"Ч": "II",
|
||||
"ЧЕТ": "II",
|
||||
"ЧЁТ": "II",
|
||||
"ЧЕТНАЯ": "II",
|
||||
"ЧЁТНАЯ": "II",
|
||||
}
|
||||
return mapping.get(text)
|
||||
|
||||
|
||||
def _weekday_from_value(value: Any) -> Optional[int]:
|
||||
if value is None:
|
||||
return None
|
||||
|
||||
if isinstance(value, int):
|
||||
if 1 <= value <= 6:
|
||||
return value
|
||||
if 0 <= value <= 5:
|
||||
return value + 1
|
||||
|
||||
text = str(value).strip().upper()
|
||||
mapping = {
|
||||
"1": 1,
|
||||
"2": 2,
|
||||
"3": 3,
|
||||
"4": 4,
|
||||
"5": 5,
|
||||
"6": 6,
|
||||
"ПН": 1,
|
||||
"ПОНЕДЕЛЬНИК": 1,
|
||||
"ВТ": 2,
|
||||
"ВТОРНИК": 2,
|
||||
"СР": 3,
|
||||
"СРЕДА": 3,
|
||||
"ЧТ": 4,
|
||||
"ЧЕТВЕРГ": 4,
|
||||
"ЧЕТВЕРК": 4,
|
||||
"ПТ": 5,
|
||||
"ПЯТНИЦА": 5,
|
||||
"СБ": 6,
|
||||
"СУББОТА": 6,
|
||||
}
|
||||
return mapping.get(text)
|
||||
|
||||
|
||||
def _normalize_lesson_windows(settings: Dict[str, Any]) -> List[Tuple[int, time, time]]:
|
||||
year = settings.get("year", {}) if isinstance(settings, dict) else {}
|
||||
windows: List[Tuple[int, time, time]] = []
|
||||
|
||||
for item in year.get("schedule", []) or []:
|
||||
lesson = item.get("lesson")
|
||||
if lesson is None:
|
||||
continue
|
||||
try:
|
||||
lesson_num = int(lesson)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
|
||||
start_raw = str(item.get("start", "")).strip()
|
||||
end_raw = str(item.get("end", "")).strip()
|
||||
if not start_raw or not end_raw:
|
||||
continue
|
||||
|
||||
try:
|
||||
start_t = time.fromisoformat(start_raw).replace(tzinfo=None)
|
||||
end_t = time.fromisoformat(end_raw).replace(tzinfo=None)
|
||||
except ValueError:
|
||||
continue
|
||||
|
||||
windows.append((lesson_num, start_t, end_t))
|
||||
|
||||
windows.sort(key=lambda x: x[0])
|
||||
return windows
|
||||
|
||||
|
||||
def _compute_week_type(monday: date, first_week: date) -> str:
|
||||
first_monday = first_week - timedelta(days=first_week.weekday())
|
||||
delta_weeks = (monday - first_monday).days // 7
|
||||
return "I" if delta_weeks % 2 == 0 else "II"
|
||||
|
||||
|
||||
def _parse_schedule_rules(schedule: Dict[str, Any]) -> Dict[str, Any]:
|
||||
exact: Dict[Tuple[str, str], set[int]] = {}
|
||||
recurring: List[Dict[str, Any]] = []
|
||||
|
||||
for entry in schedule.get("group_lessons", []) or []:
|
||||
if not isinstance(entry, dict):
|
||||
continue
|
||||
|
||||
class_id = (
|
||||
entry.get("class_id")
|
||||
or entry.get("class")
|
||||
or entry.get("room_id")
|
||||
or entry.get("room")
|
||||
)
|
||||
if not class_id:
|
||||
continue
|
||||
|
||||
lesson_raw = entry.get("lesson") or entry.get("pair")
|
||||
try:
|
||||
lesson = int(lesson_raw)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
|
||||
date_value = _parse_date_value(entry.get("date"))
|
||||
if date_value:
|
||||
key = (str(class_id), date_value.isoformat())
|
||||
if key not in exact:
|
||||
exact[key] = set()
|
||||
exact[key].add(lesson)
|
||||
continue
|
||||
|
||||
weekday = _weekday_from_value(entry.get("weekday") or entry.get("day"))
|
||||
week_type = _normalize_week_type(entry.get("week_type") or entry.get("week"))
|
||||
recurring.append(
|
||||
{
|
||||
"class_id": str(class_id),
|
||||
"lesson": lesson,
|
||||
"weekday": weekday,
|
||||
"week_type": week_type,
|
||||
}
|
||||
)
|
||||
|
||||
return {"exact": exact, "recurring": recurring}
|
||||
|
||||
|
||||
def _has_schedule_lesson(
|
||||
schedule_rules: Dict[str, Any],
|
||||
class_id: str,
|
||||
target_date: date,
|
||||
lesson: int,
|
||||
week_type: str,
|
||||
) -> bool:
|
||||
exact = schedule_rules.get("exact", {})
|
||||
recurring = schedule_rules.get("recurring", [])
|
||||
|
||||
key = (class_id, target_date.isoformat())
|
||||
lessons = exact.get(key)
|
||||
if lessons and lesson in lessons:
|
||||
return True
|
||||
|
||||
weekday_num = target_date.weekday() + 1
|
||||
for rule in recurring:
|
||||
if rule.get("class_id") != class_id:
|
||||
continue
|
||||
if rule.get("lesson") != lesson:
|
||||
continue
|
||||
|
||||
rule_weekday = rule.get("weekday")
|
||||
if rule_weekday and rule_weekday != weekday_num:
|
||||
continue
|
||||
|
||||
rule_week_type = rule.get("week_type")
|
||||
if rule_week_type and rule_week_type != week_type:
|
||||
continue
|
||||
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
|
||||
def _session_overlaps_lesson(
|
||||
start_dt: datetime,
|
||||
end_dt: datetime,
|
||||
target_date: date,
|
||||
lesson_start: time,
|
||||
lesson_end: time,
|
||||
) -> bool:
|
||||
lesson_start_dt = datetime.combine(target_date, lesson_start)
|
||||
lesson_end_dt = datetime.combine(target_date, lesson_end)
|
||||
return start_dt <= lesson_end_dt and end_dt >= lesson_start_dt
|
||||
|
||||
|
||||
def _class_display_name(classes_df: pd.DataFrame, group_id: str) -> Dict[str, str]:
|
||||
"""Return a display label and type for a CSV output file."""
|
||||
class_rows = classes_df[classes_df["id"] == group_id]
|
||||
if not class_rows.empty:
|
||||
row = class_rows.iloc[0]
|
||||
return {
|
||||
"kind": "class",
|
||||
"title": str(row.get("class") or row.get("description") or group_id),
|
||||
}
|
||||
|
||||
ip_rows = classes_df[classes_df["ip_group"] == group_id]
|
||||
if not ip_rows.empty:
|
||||
labels = [str(value) for value in ip_rows["id"].tolist()]
|
||||
room_name = str(ip_rows.iloc[0].get("section") or group_id)
|
||||
title = f"{group_id} ({', '.join(labels)})"
|
||||
return {"kind": "ip_group", "title": title}
|
||||
|
||||
return {"kind": "unknown", "title": group_id}
|
||||
|
||||
|
||||
def _aggregate_csv(
|
||||
file_path: Path,
|
||||
classes_df: pd.DataFrame,
|
||||
report_start: date,
|
||||
report_end: date,
|
||||
first_week: date,
|
||||
lesson_windows: List[Tuple[int, time, time]],
|
||||
schedule_rules: Dict[str, Any],
|
||||
) -> Tuple[ReportItem, set[str]]:
|
||||
group_id = file_path.stem
|
||||
display = _class_display_name(classes_df, group_id)
|
||||
|
||||
with open(file_path, "r", encoding="utf-8", newline="") as f:
|
||||
reader = csv.DictReader(f)
|
||||
rows = [row for row in reader if row]
|
||||
|
||||
filtered_rows = []
|
||||
for row in rows:
|
||||
start_value = str(row.get("start", ""))
|
||||
start_dt = _parse_dt(start_value)
|
||||
if not start_dt:
|
||||
continue
|
||||
if report_start <= start_dt.date() <= report_end:
|
||||
filtered_rows.append(row)
|
||||
|
||||
users_set: set[str] = set()
|
||||
|
||||
users = [str(row.get("user", "")) for row in filtered_rows if row.get("user")]
|
||||
stations = [str(row.get("station", "")) for row in filtered_rows if row.get("station")]
|
||||
for user in users:
|
||||
clean_user = user.strip()
|
||||
if clean_user:
|
||||
users_set.add(clean_user)
|
||||
|
||||
by_date: Dict[str, int] = {}
|
||||
total_minutes = 0.0
|
||||
starts: List[datetime] = []
|
||||
ends: List[datetime] = []
|
||||
auth_presence: Dict[date, Dict[int, bool]] = {}
|
||||
|
||||
for row in filtered_rows:
|
||||
start_value = str(row.get("start", ""))
|
||||
end_value = str(row.get("end", ""))
|
||||
start_dt = _parse_dt(start_value)
|
||||
end_dt = _parse_dt(end_value)
|
||||
if not start_dt or not end_dt:
|
||||
continue
|
||||
|
||||
total_minutes += _safe_float_minutes(start_value, end_value)
|
||||
|
||||
if start_dt:
|
||||
starts.append(start_dt)
|
||||
by_date[start_dt.date().isoformat()] = by_date.get(start_dt.date().isoformat(), 0) + 1
|
||||
if end_dt:
|
||||
ends.append(end_dt)
|
||||
|
||||
target_date = start_dt.date()
|
||||
if target_date not in auth_presence:
|
||||
auth_presence[target_date] = {}
|
||||
for lesson_num, lesson_start, lesson_end in lesson_windows:
|
||||
if _session_overlaps_lesson(start_dt, end_dt, target_date, lesson_start, lesson_end):
|
||||
auth_presence[target_date][lesson_num] = True
|
||||
|
||||
weeks: List[Dict[str, Any]] = []
|
||||
weekday_names = ["ПН", "ВТ", "СР", "ЧТ", "ПТ", "СБ"]
|
||||
monday = report_start - timedelta(days=report_start.weekday())
|
||||
while monday <= report_end:
|
||||
saturday = monday + timedelta(days=5)
|
||||
week_type = _compute_week_type(monday, first_week)
|
||||
|
||||
daily_rows: List[str] = []
|
||||
days_payload: List[Dict[str, Any]] = []
|
||||
code_counts = {"0": 0, "1": 0, "2": 0, "3": 0}
|
||||
|
||||
for day_offset in range(6):
|
||||
current_day = monday + timedelta(days=day_offset)
|
||||
weekday_name = weekday_names[day_offset]
|
||||
|
||||
row_codes: List[str] = []
|
||||
for lesson_num in range(1, 9):
|
||||
in_period = report_start <= current_day <= report_end
|
||||
has_schedule = (
|
||||
_has_schedule_lesson(schedule_rules, group_id, current_day, lesson_num, week_type)
|
||||
if in_period
|
||||
else False
|
||||
)
|
||||
has_auth = bool(auth_presence.get(current_day, {}).get(lesson_num, False)) if in_period else False
|
||||
|
||||
if not has_schedule and not has_auth:
|
||||
code = "0"
|
||||
elif has_schedule and not has_auth:
|
||||
code = "1"
|
||||
elif not has_schedule and has_auth:
|
||||
code = "2"
|
||||
else:
|
||||
code = "3"
|
||||
|
||||
row_codes.append(code)
|
||||
code_counts[code] += 1
|
||||
|
||||
row_text = "".join(row_codes)
|
||||
daily_rows.append(row_text)
|
||||
days_payload.append(
|
||||
{
|
||||
"date": current_day.isoformat(),
|
||||
"weekday": weekday_name,
|
||||
"lessons": row_text,
|
||||
}
|
||||
)
|
||||
|
||||
weeks.append(
|
||||
{
|
||||
"long": f"{monday.strftime('%d.%m.%Y')} - {saturday.strftime('%d.%m.%Y')} ({week_type})",
|
||||
"short": f"{monday.strftime('%d.%m')} ({week_type})",
|
||||
"week_type": week_type,
|
||||
"monday": monday.isoformat(),
|
||||
"saturday": saturday.isoformat(),
|
||||
"days": days_payload,
|
||||
"daily_summary": daily_rows,
|
||||
"code_counts": code_counts,
|
||||
}
|
||||
)
|
||||
|
||||
monday += timedelta(days=7)
|
||||
|
||||
user_counts = pd.Series(users).value_counts() if users else pd.Series(dtype=int)
|
||||
top_users = [
|
||||
{"user": str(name), "sessions": int(count)}
|
||||
for name, count in user_counts.head(10).items()
|
||||
]
|
||||
|
||||
return ReportItem(
|
||||
group_id=group_id,
|
||||
kind=display["kind"],
|
||||
title=display["title"],
|
||||
source_rows=len(filtered_rows),
|
||||
unique_users=len(set(users)),
|
||||
unique_stations=len(set(stations)),
|
||||
total_minutes=round(total_minutes, 1),
|
||||
first_start=min(starts).isoformat(sep=" ") if starts else None,
|
||||
last_end=max(ends).isoformat(sep=" ") if ends else None,
|
||||
by_date=dict(sorted(by_date.items())),
|
||||
top_users=top_users,
|
||||
weeks=weeks,
|
||||
), users_set
|
||||
|
||||
|
||||
def _build_group_report(schedule: Dict[str, Any]) -> Dict[str, Any]:
|
||||
return {
|
||||
"available": bool(schedule.get("available")),
|
||||
"lesson_windows": schedule.get("lesson_windows", []),
|
||||
"group_lessons": schedule.get("group_lessons", []),
|
||||
"items": [],
|
||||
"note": schedule.get("note", "Schedule data is not available yet."),
|
||||
}
|
||||
|
||||
|
||||
def _build_class_report(items: List[ReportItem], total_users: int) -> Dict[str, Any]:
|
||||
total_sessions = sum(item.source_rows for item in items)
|
||||
|
||||
return {
|
||||
"available": True,
|
||||
"summary": {
|
||||
"files": len(items),
|
||||
"sessions": total_sessions,
|
||||
"users": total_users,
|
||||
},
|
||||
"items": [asdict(item) for item in items],
|
||||
}
|
||||
|
||||
|
||||
def run_stage(
|
||||
workspace_root: Path,
|
||||
context: Dict[str, Any] | None = None,
|
||||
) -> Dict[str, Any]:
|
||||
"""Aggregate processed sessions into JSON files for later HTML rendering."""
|
||||
config = _load_context_config(workspace_root, context)
|
||||
settings = config["settings"]
|
||||
classes_df = config["classes"]
|
||||
|
||||
logs_dir = workspace_root / "result" / "logs"
|
||||
reports_dir = workspace_root / "result" / "reports"
|
||||
reports_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
report_start = _parse_date_value(settings.get("report_start"))
|
||||
report_end = _parse_date_value(settings.get("report_end"))
|
||||
first_week = _parse_date_value(settings.get("year", {}).get("first_week"))
|
||||
|
||||
if report_start is None or report_end is None:
|
||||
raise ValueError("settings.yaml must contain report_start and report_end")
|
||||
if first_week is None:
|
||||
raise ValueError("settings.yaml must contain year.first_week")
|
||||
if report_start > report_end:
|
||||
raise ValueError("report_start cannot be later than report_end")
|
||||
|
||||
lesson_windows = _normalize_lesson_windows(settings)
|
||||
|
||||
schedule = {}
|
||||
if context and "stage_parse_schedule" in context:
|
||||
schedule = context["stage_parse_schedule"].get("schedule", {})
|
||||
schedule_rules = _parse_schedule_rules(schedule)
|
||||
|
||||
items: List[ReportItem] = []
|
||||
all_users: set[str] = set()
|
||||
if logs_dir.exists():
|
||||
for file_path in sorted(logs_dir.glob("*.csv")):
|
||||
try:
|
||||
item, users_set = _aggregate_csv(
|
||||
file_path=file_path,
|
||||
classes_df=classes_df,
|
||||
report_start=report_start,
|
||||
report_end=report_end,
|
||||
first_week=first_week,
|
||||
lesson_windows=lesson_windows,
|
||||
schedule_rules=schedule_rules,
|
||||
)
|
||||
items.append(item)
|
||||
all_users.update(users_set)
|
||||
except Exception as exc:
|
||||
print(f"Warning: failed to aggregate {file_path.name}: {exc}")
|
||||
|
||||
group_report = {
|
||||
"generated_at": datetime.now(timezone.utc).isoformat(),
|
||||
"workspace_root": str(workspace_root),
|
||||
"source_logs_dir": str(logs_dir),
|
||||
"report_start": report_start.isoformat(),
|
||||
"report_end": report_end.isoformat(),
|
||||
"schedule": schedule,
|
||||
"report": _build_group_report(schedule),
|
||||
}
|
||||
|
||||
class_report = {
|
||||
"generated_at": datetime.now(timezone.utc).isoformat(),
|
||||
"workspace_root": str(workspace_root),
|
||||
"source_logs_dir": str(logs_dir),
|
||||
"report_start": report_start.isoformat(),
|
||||
"report_end": report_end.isoformat(),
|
||||
"report": _build_class_report(items, len(all_users)),
|
||||
}
|
||||
|
||||
group_json = reports_dir / "report_groups.json"
|
||||
class_json = reports_dir / "report_classes.json"
|
||||
|
||||
with open(group_json, "w", encoding="utf-8") as f:
|
||||
json.dump(group_report, f, ensure_ascii=False, indent=2)
|
||||
|
||||
with open(class_json, "w", encoding="utf-8") as f:
|
||||
json.dump(class_report, f, ensure_ascii=False, indent=2)
|
||||
|
||||
print("✓ Report data built")
|
||||
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")
|
||||
|
||||
return {
|
||||
"group_json": str(group_json),
|
||||
"class_json": str(class_json),
|
||||
"group_report": group_report,
|
||||
"class_report": class_report,
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,393 @@
|
||||
"""Stage 5: Generate standalone HTML reports using Jinja2 templates."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from collections import defaultdict
|
||||
from datetime import date, datetime, timedelta
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
import pandas as pd
|
||||
from jinja2 import Environment, FileSystemLoader, select_autoescape
|
||||
|
||||
from lib.stage_load_settings import SettingsLoader
|
||||
|
||||
|
||||
def _load_json(path: Path) -> Dict[str, Any]:
|
||||
with open(path, "r", encoding="utf-8") as f:
|
||||
return json.load(f)
|
||||
|
||||
|
||||
def _load_text(path: Path) -> str:
|
||||
with open(path, "r", encoding="utf-8") as f:
|
||||
return f.read()
|
||||
|
||||
|
||||
def _parse_date(value: Any) -> Optional[date]:
|
||||
if isinstance(value, datetime):
|
||||
return value.date()
|
||||
if hasattr(value, "year") and hasattr(value, "month") and hasattr(value, "day"):
|
||||
try:
|
||||
return date(value.year, value.month, value.day)
|
||||
except ValueError:
|
||||
return None
|
||||
if value is None:
|
||||
return None
|
||||
|
||||
text = str(value).strip()
|
||||
if not text:
|
||||
return None
|
||||
|
||||
for fmt in ("%Y-%m-%d", "%d.%m.%Y"):
|
||||
try:
|
||||
return datetime.strptime(text, fmt).date()
|
||||
except ValueError:
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
def _load_context_config(workspace_root: Path, context: Dict[str, Any] | None) -> Dict[str, Any]:
|
||||
if context and "stage_load_settings" in context:
|
||||
return context["stage_load_settings"]
|
||||
loader = SettingsLoader(workspace_root)
|
||||
return loader.get_config()
|
||||
|
||||
|
||||
def _part_name(classes_df: pd.DataFrame, group_id: str) -> str:
|
||||
class_rows = classes_df[classes_df["id"] == group_id]
|
||||
if not class_rows.empty:
|
||||
return str(class_rows.iloc[0].get("part") or "")
|
||||
|
||||
ip_rows = classes_df[classes_df["ip_group"] == group_id]
|
||||
if not ip_rows.empty:
|
||||
return str(ip_rows.iloc[0].get("part") or "")
|
||||
|
||||
return ""
|
||||
|
||||
|
||||
def _display_label(classes_df: pd.DataFrame, group_id: str) -> str:
|
||||
if group_id == "amt":
|
||||
return "АМТ"
|
||||
|
||||
class_rows = classes_df[classes_df["id"] == group_id]
|
||||
if not class_rows.empty:
|
||||
return str(class_rows.iloc[0].get("id") or group_id)
|
||||
|
||||
ip_rows = classes_df[classes_df["ip_group"] == group_id]
|
||||
if not ip_rows.empty:
|
||||
row = ip_rows.iloc[0]
|
||||
return str(row.get("id") or group_id)
|
||||
|
||||
return group_id
|
||||
|
||||
|
||||
def _row_order_map(classes_df: pd.DataFrame) -> Dict[str, int]:
|
||||
order: Dict[str, int] = {}
|
||||
for idx, row in classes_df.reset_index(drop=True).iterrows():
|
||||
gid = str(row.get("id") or "").strip()
|
||||
ipg = str(row.get("ip_group") or "").strip()
|
||||
if gid and gid not in order:
|
||||
order[gid] = idx
|
||||
if ipg and ipg not in order:
|
||||
order[ipg] = idx
|
||||
return order
|
||||
|
||||
|
||||
def _merge_code(a: str, b: str) -> str:
|
||||
values = [str(x) for x in (a, b) if str(x)]
|
||||
if "3" in values:
|
||||
return "3"
|
||||
if "2" in values:
|
||||
return "2"
|
||||
if "1" in values:
|
||||
return "1"
|
||||
return "0"
|
||||
|
||||
|
||||
def _merge_weeks(source_items: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
|
||||
merged: Dict[str, Dict[str, Any]] = {}
|
||||
|
||||
for item in source_items:
|
||||
for week in item.get("weeks", []) or []:
|
||||
key = week.get("monday") or week.get("long") or week.get("short")
|
||||
if key not in merged:
|
||||
merged[key] = {
|
||||
"long": week.get("long"),
|
||||
"short": week.get("short"),
|
||||
"week_type": week.get("week_type"),
|
||||
"monday": week.get("monday"),
|
||||
"saturday": week.get("saturday"),
|
||||
"days": [
|
||||
{
|
||||
"date": day.get("date"),
|
||||
"weekday": day.get("weekday"),
|
||||
"codes": list(str(day.get("lessons", "")))[:8],
|
||||
}
|
||||
for day in week.get("days", []) or []
|
||||
],
|
||||
"code_counts": {"0": 0, "1": 0, "2": 0, "3": 0},
|
||||
}
|
||||
else:
|
||||
current_days = merged[key]["days"]
|
||||
for idx, day in enumerate(week.get("days", []) or []):
|
||||
incoming = list(str(day.get("lessons", "")))[:8]
|
||||
if idx >= len(current_days):
|
||||
current_days.append({
|
||||
"date": day.get("date"),
|
||||
"weekday": day.get("weekday"),
|
||||
"codes": incoming,
|
||||
})
|
||||
else:
|
||||
current_days[idx]["codes"] = [
|
||||
_merge_code(prev, new)
|
||||
for prev, new in zip(current_days[idx]["codes"], incoming)
|
||||
]
|
||||
|
||||
for code, count in (week.get("code_counts", {}) or {}).items():
|
||||
merged[key]["code_counts"][str(code)] += int(count)
|
||||
|
||||
ordered = sorted(merged.values(), key=lambda item: item.get("monday") or item.get("long") or "")
|
||||
for week in ordered:
|
||||
week["daily_summary"] = ["".join(day["codes"]) for day in week.get("days", [])]
|
||||
week["total_pairs"] = sum(int(v) for v in week.get("code_counts", {}).values())
|
||||
week["conducted"] = int(week.get("code_counts", {}).get("3", 0))
|
||||
week["missed"] = int(week.get("code_counts", {}).get("1", 0))
|
||||
week["other"] = int(week.get("code_counts", {}).get("2", 0))
|
||||
return ordered
|
||||
|
||||
|
||||
def _format_percent(value: int, total: int) -> str:
|
||||
if total <= 0:
|
||||
return f"{value} (0%)"
|
||||
return f"{value} ({round(value * 100 / total)}%)"
|
||||
|
||||
|
||||
def _build_week_chart(weeks: List[Dict[str, Any]]) -> str:
|
||||
if not weeks:
|
||||
return "<div class='muted'>Нет данных.</div>"
|
||||
|
||||
width = max(720, len(weeks) * 92)
|
||||
height = 280
|
||||
bar_width = 42
|
||||
max_value = max(
|
||||
max(int(w.get("conducted", 0)), int(w.get("missed", 0)), int(w.get("other", 0)))
|
||||
for w in weeks
|
||||
) or 1
|
||||
|
||||
def bar_height(value: int) -> int:
|
||||
return max(2, round((value / max_value) * 180)) if value else 0
|
||||
|
||||
pieces = [
|
||||
f"<svg class='week-chart' viewBox='0 0 {width} {height}' preserveAspectRatio='xMinYMin meet'>"
|
||||
]
|
||||
baseline = 210
|
||||
for index, week in enumerate(weeks):
|
||||
x = 70 + index * 92
|
||||
current_bottom = baseline
|
||||
pieces.append(
|
||||
f"<text class='chart-week-label' x='{x + bar_width / 2}' y='{baseline + 28}' text-anchor='middle'>{week.get('short')}</text>"
|
||||
)
|
||||
for cls_name, value in [("code-1", int(week.get("missed", 0))), ("code-2", int(week.get("other", 0))), ("code-3", int(week.get("conducted", 0)))]:
|
||||
h = bar_height(value)
|
||||
if h:
|
||||
pieces.append(
|
||||
f"<rect class='week-bar {cls_name}' x='{x}' y='{current_bottom - h}' width='{bar_width}' height='{h}' rx='5'></rect>"
|
||||
)
|
||||
current_bottom -= h
|
||||
pieces.append(
|
||||
f"<text class='chart-count' x='{x + bar_width / 2}' y='{current_bottom - 8}' text-anchor='middle'>{int(week.get('total_pairs', 0))}</text>"
|
||||
)
|
||||
pieces.append("</svg>")
|
||||
return "".join(pieces)
|
||||
|
||||
|
||||
def _build_scheme_table(week: Dict[str, Any]) -> str:
|
||||
rows = []
|
||||
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>")
|
||||
|
||||
return (
|
||||
"<table class='scheme-table'><thead><tr><th>День</th>"
|
||||
+ "".join(f"<th>{i}</th>" for i in range(1, 9))
|
||||
+ "</tr></thead><tbody>"
|
||||
+ "".join(rows)
|
||||
+ "</tbody></table>"
|
||||
)
|
||||
|
||||
|
||||
def _build_class_block(item: Dict[str, Any]) -> Dict[str, Any]:
|
||||
weeks = item.get("weeks", []) or []
|
||||
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)
|
||||
|
||||
item["weeks"] = weeks
|
||||
item["chart_svg"] = _build_week_chart(weeks)
|
||||
return item
|
||||
|
||||
|
||||
def _aggregate_item(source_items: List[Dict[str, Any]], item_id: str, label: str, part_title: str) -> Dict[str, Any]:
|
||||
return _build_class_block(
|
||||
{
|
||||
"id": item_id,
|
||||
"label": label,
|
||||
"title": label,
|
||||
"part_id": part_title,
|
||||
"section_title": part_title,
|
||||
"weeks": _merge_weeks(source_items),
|
||||
"is_aggregate": True,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
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"]
|
||||
settings = config["settings"]
|
||||
|
||||
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}
|
||||
|
||||
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)
|
||||
|
||||
order_map = _row_order_map(classes_df)
|
||||
|
||||
sections: List[Dict[str, Any]] = []
|
||||
for part in ordered_parts:
|
||||
section_items: 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:
|
||||
section_items.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
|
||||
section_items.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,
|
||||
}
|
||||
)
|
||||
)
|
||||
|
||||
section_items.sort(key=lambda item: (0 if item.get("is_aggregate") else 1, item.get("order", 9999), item.get("label", "")))
|
||||
if section_items:
|
||||
sections.append({"id": part, "title": part, "items": section_items})
|
||||
|
||||
active_section = sections[0]["id"] if sections else ""
|
||||
active_class = sections[0]["items"][0]["id"] if sections and sections[0]["items"] else ""
|
||||
|
||||
report = {
|
||||
"title": "Отчёт по классам",
|
||||
"period": {
|
||||
"start": report_json.get("report_start"),
|
||||
"end": report_json.get("report_end"),
|
||||
},
|
||||
"sections": sections,
|
||||
"active_section": active_section,
|
||||
"active_class": active_class,
|
||||
"group_count": len(raw_items),
|
||||
"class_count": len(sections),
|
||||
}
|
||||
return report
|
||||
|
||||
|
||||
def _build_group_report_model(workspace_root: Path) -> Dict[str, Any]:
|
||||
group_json = _load_json(workspace_root / "result" / "reports" / "report_groups.json")
|
||||
schedule = group_json.get("schedule", {}) or {}
|
||||
return {
|
||||
"title": "Отчёт по группам",
|
||||
"note": schedule.get("note", "Schedule data is not available yet."),
|
||||
"lesson_windows": schedule.get("lesson_windows", []) or [],
|
||||
}
|
||||
|
||||
|
||||
def _render_jinja(template_path: Path, context: Dict[str, Any]) -> str:
|
||||
env = Environment(
|
||||
loader=FileSystemLoader(str(template_path.parent)),
|
||||
autoescape=select_autoescape(["html", "xml"]),
|
||||
)
|
||||
template = env.get_template(template_path.name)
|
||||
return template.render(**context)
|
||||
|
||||
|
||||
def run_stage(workspace_root: Path, context: Dict[str, Any] | None = None) -> Dict[str, Any]:
|
||||
"""Generate standalone HTML reports from Jinja templates."""
|
||||
template_dir = workspace_root / "template"
|
||||
required = [
|
||||
template_dir / "report_class.html",
|
||||
template_dir / "report_group.html",
|
||||
template_dir / "report.css",
|
||||
template_dir / "report_class.js",
|
||||
template_dir / "report_group.js",
|
||||
]
|
||||
missing = [str(path) for path in required if not path.exists()]
|
||||
if missing:
|
||||
raise FileNotFoundError("Template files are missing:\n" + "\n".join(missing))
|
||||
|
||||
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")
|
||||
|
||||
class_report = _build_class_report_model(workspace_root, context)
|
||||
group_report = _build_group_report_model(workspace_root)
|
||||
|
||||
class_html = _render_jinja(
|
||||
template_dir / "report_class.html",
|
||||
{
|
||||
"title": class_report["title"],
|
||||
"hint": f"Период: {class_report['period']['start']} — {class_report['period']['end']}",
|
||||
"css_text": css_text,
|
||||
"js_text": class_js,
|
||||
"report": class_report,
|
||||
"report_json": json.dumps(class_report, ensure_ascii=False),
|
||||
},
|
||||
)
|
||||
group_html = _render_jinja(
|
||||
template_dir / "report_group.html",
|
||||
{
|
||||
"title": group_report["title"],
|
||||
"hint": group_report["note"],
|
||||
"css_text": css_text,
|
||||
"js_text": group_js,
|
||||
"report": group_report,
|
||||
"report_json": json.dumps(group_report, ensure_ascii=False),
|
||||
},
|
||||
)
|
||||
|
||||
out_group = workspace_root / "result" / "report_groups.html"
|
||||
out_class = workspace_root / "result" / "report_classes.html"
|
||||
out_group.write_text(group_html, encoding="utf-8")
|
||||
out_class.write_text(class_html, encoding="utf-8")
|
||||
|
||||
print("✓ HTML reports generated")
|
||||
print(f" - {out_group.name}")
|
||||
print(f" - {out_class.name}")
|
||||
|
||||
return {"group_html": str(out_group), "class_html": str(out_class)}
|
||||
@@ -0,0 +1,94 @@
|
||||
"""Stage 1: Load configuration settings and class information."""
|
||||
|
||||
import yaml
|
||||
import pandas as pd
|
||||
from pathlib import Path
|
||||
from typing import Dict, Any
|
||||
|
||||
|
||||
class SettingsLoader:
|
||||
"""Load and manage configuration settings and class data."""
|
||||
|
||||
def __init__(self, workspace_root: Path):
|
||||
"""
|
||||
Initialize the settings loader.
|
||||
|
||||
Args:
|
||||
workspace_root: Root directory of the project
|
||||
"""
|
||||
self.workspace_root = Path(workspace_root)
|
||||
self.settings = None
|
||||
self.classes_df = None
|
||||
|
||||
def load_settings(self) -> Dict[str, Any]:
|
||||
"""
|
||||
Load settings from settings.yaml.
|
||||
|
||||
Returns:
|
||||
Dictionary with configuration settings
|
||||
"""
|
||||
settings_path = self.workspace_root / "settings.yaml"
|
||||
|
||||
if not settings_path.exists():
|
||||
raise FileNotFoundError(f"Settings file not found: {settings_path}")
|
||||
|
||||
with open(settings_path, "r", encoding="utf-8") as f:
|
||||
self.settings = yaml.safe_load(f)
|
||||
|
||||
return self.settings
|
||||
|
||||
def load_classes(self) -> pd.DataFrame:
|
||||
"""
|
||||
Load class information from classes.csv.
|
||||
|
||||
Returns:
|
||||
DataFrame with class information
|
||||
"""
|
||||
classes_path = self.workspace_root / "data" / "classes.csv"
|
||||
|
||||
if not classes_path.exists():
|
||||
raise FileNotFoundError(f"Classes file not found: {classes_path}")
|
||||
|
||||
self.classes_df = pd.read_csv(classes_path)
|
||||
return self.classes_df
|
||||
|
||||
def get_config(self) -> Dict[str, Any]:
|
||||
"""
|
||||
Get complete configuration including settings and classes.
|
||||
|
||||
Returns:
|
||||
Dictionary with loaded configuration
|
||||
"""
|
||||
if self.settings is None:
|
||||
self.load_settings()
|
||||
if self.classes_df is None:
|
||||
self.load_classes()
|
||||
|
||||
return {
|
||||
"settings": self.settings,
|
||||
"classes": self.classes_df,
|
||||
}
|
||||
|
||||
|
||||
def run_stage(
|
||||
workspace_root: Path,
|
||||
context: Dict[str, Any] | None = None,
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Execute the settings loading stage.
|
||||
|
||||
Args:
|
||||
workspace_root: Root directory of the project
|
||||
|
||||
Returns:
|
||||
Dictionary with loaded configuration
|
||||
"""
|
||||
loader = SettingsLoader(workspace_root)
|
||||
config = loader.get_config()
|
||||
|
||||
print("✓ Settings loaded successfully")
|
||||
print(f" - Sections: {len(config['settings'].get('sections', []))}")
|
||||
print(f" - Classes: {len(config['classes'])}")
|
||||
print(f" - IP ranges: {len(config['settings'].get('class_ips', {}))}")
|
||||
|
||||
return config
|
||||
@@ -0,0 +1,58 @@
|
||||
"""Stage 3: Prepare university schedule 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.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Dict, Any
|
||||
|
||||
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 = []
|
||||
|
||||
for item in year.get("schedule", []) or []:
|
||||
lessons.append(
|
||||
{
|
||||
"lesson": item.get("lesson"),
|
||||
"start": str(item.get("start")),
|
||||
"end": str(item.get("end")),
|
||||
}
|
||||
)
|
||||
|
||||
return {
|
||||
"available": False,
|
||||
"source": None,
|
||||
"generated_at": datetime.now(timezone.utc).isoformat(),
|
||||
"lesson_windows": lessons,
|
||||
"group_lessons": [],
|
||||
"note": "University schedule export is not available yet.",
|
||||
}
|
||||
|
||||
|
||||
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'])}")
|
||||
|
||||
return {"schedule": schedule}
|
||||
@@ -0,0 +1,508 @@
|
||||
"""Stage 2: Process authentication logs and create session records."""
|
||||
|
||||
import re
|
||||
from pathlib import Path
|
||||
from typing import Dict, Any, List, Tuple, Optional
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
import pandas as pd
|
||||
import ipaddress
|
||||
|
||||
|
||||
@dataclass
|
||||
class LogEntry:
|
||||
"""Represents a single log entry."""
|
||||
|
||||
timestamp: datetime
|
||||
username: str
|
||||
computer: str
|
||||
ip_address: Optional[str] = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class Session:
|
||||
"""Represents a user session."""
|
||||
|
||||
station: str
|
||||
user: str
|
||||
start: datetime
|
||||
end: datetime
|
||||
|
||||
|
||||
class LogProcessor:
|
||||
"""Process authentication logs and generate session records."""
|
||||
|
||||
def __init__(self, workspace_root: Path, config: Dict[str, Any]):
|
||||
"""
|
||||
Initialize the log processor.
|
||||
|
||||
Args:
|
||||
workspace_root: Root directory of the project
|
||||
config: Configuration dictionary from stage 1
|
||||
"""
|
||||
self.workspace_root = Path(workspace_root)
|
||||
self.config = config
|
||||
self.settings = config["settings"]
|
||||
self.classes_df = config["classes"]
|
||||
self.processing = self.settings.get("processing", {})
|
||||
switch_date_value = self.processing.get("m1_ip_to_name_switch_date", "2026-04-08")
|
||||
if isinstance(switch_date_value, datetime):
|
||||
self.m1_ip_to_name_switch_date = switch_date_value.date()
|
||||
elif hasattr(switch_date_value, "year") and hasattr(switch_date_value, "month") and hasattr(switch_date_value, "day"):
|
||||
self.m1_ip_to_name_switch_date = switch_date_value
|
||||
else:
|
||||
self.m1_ip_to_name_switch_date = datetime.strptime(str(switch_date_value), "%Y-%m-%d").date()
|
||||
self.amt_group_id = self.processing.get("amt_group_id", "amt")
|
||||
self.amt_class_id = self.processing.get("amt_class_id", "АМТ-33")
|
||||
|
||||
# Build IP to class mapping
|
||||
self._build_ip_class_mapping()
|
||||
|
||||
def _build_ip_class_mapping(self) -> None:
|
||||
"""Build a mapping from IP prefixes to class information."""
|
||||
self.ip_to_classes = {}
|
||||
|
||||
class_ips = self.settings.get("class_ips", {})
|
||||
|
||||
# Create a mapping from IP prefix to classes that use it
|
||||
for _, row in self.classes_df.iterrows():
|
||||
prefix = row["prefix"]
|
||||
|
||||
# Extract the IP prefix from the full prefix
|
||||
# e.g., "pu-402-" -> "pu", "amt" -> "amt"
|
||||
ip_prefix = prefix.split("-")[0]
|
||||
|
||||
if ip_prefix in class_ips:
|
||||
ip_subnet = class_ips[ip_prefix]
|
||||
if ip_subnet not in self.ip_to_classes:
|
||||
self.ip_to_classes[ip_subnet] = []
|
||||
self.ip_to_classes[ip_subnet].append(row)
|
||||
|
||||
def _parse_log_entry(self, line: str, section: str) -> Optional[LogEntry]:
|
||||
"""
|
||||
Parse a single log entry line.
|
||||
|
||||
Args:
|
||||
line: Log line to parse
|
||||
section: Section (okk1 or m1)
|
||||
|
||||
Returns:
|
||||
LogEntry or None if line is empty/invalid
|
||||
"""
|
||||
line = line.strip()
|
||||
if not line:
|
||||
return None
|
||||
|
||||
# Parse: YYYY-MM-DD HH:MM:SS username computer_or_ip
|
||||
parts = line.split()
|
||||
|
||||
if len(parts) < 2:
|
||||
return None
|
||||
|
||||
try:
|
||||
timestamp = datetime.fromisoformat(f"{parts[0]} {parts[1]}")
|
||||
except (ValueError, IndexError):
|
||||
return None
|
||||
|
||||
# Handle cases where username or computer might be missing
|
||||
username = ""
|
||||
computer = ""
|
||||
ip_address = None
|
||||
|
||||
if len(parts) >= 3:
|
||||
username = parts[2]
|
||||
if len(parts) >= 4:
|
||||
fourth_field = parts[3]
|
||||
|
||||
# Check if it's an IP address
|
||||
if self._is_ip_address(fourth_field):
|
||||
ip_address = fourth_field
|
||||
computer = fourth_field
|
||||
else:
|
||||
computer = fourth_field
|
||||
|
||||
# Skip entries without username or computer
|
||||
if not username or not computer:
|
||||
return None
|
||||
|
||||
return LogEntry(
|
||||
timestamp=timestamp,
|
||||
username=username,
|
||||
computer=computer,
|
||||
ip_address=ip_address
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _is_ip_address(s: str) -> bool:
|
||||
"""Check if a string is an IP address."""
|
||||
try:
|
||||
ipaddress.ip_address(s)
|
||||
return True
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
def _find_class_for_ip(self, ip_address: str) -> Optional[str]:
|
||||
"""
|
||||
Find class ID for a given IP address.
|
||||
|
||||
Args:
|
||||
ip_address: IP address to look up
|
||||
|
||||
Returns:
|
||||
Class ID or None if not found
|
||||
"""
|
||||
try:
|
||||
ip = ipaddress.ip_address(ip_address)
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
# Check exact matches first
|
||||
for subnet_str, classes in self.ip_to_classes.items():
|
||||
# Convert subnet string to a proper network
|
||||
try:
|
||||
# If it's just an IP without CIDR, try to match Class C subnet (/24)
|
||||
if "/" not in subnet_str:
|
||||
# Try as exact IP first
|
||||
if str(ip) == subnet_str:
|
||||
return classes[0]["id"] if classes else None
|
||||
|
||||
# Try as network address with /24
|
||||
try:
|
||||
subnet = ipaddress.ip_network(f"{subnet_str}/24", strict=False)
|
||||
if ip in subnet:
|
||||
return classes[0]["id"] if classes else None
|
||||
except ValueError:
|
||||
pass
|
||||
else:
|
||||
# For subnets with explicit CIDR, check if IP is in range
|
||||
subnet = ipaddress.ip_network(subnet_str, strict=False)
|
||||
if ip in subnet:
|
||||
return classes[0]["id"] if classes else None
|
||||
except ValueError:
|
||||
continue
|
||||
|
||||
return None
|
||||
|
||||
def _find_class_for_computer(self, computer: str, section: str) -> Optional[str]:
|
||||
"""
|
||||
Find class ID for a computer in a given section.
|
||||
|
||||
Args:
|
||||
computer: Computer name (e.g., "303k1" for okk1, "pu-402-1" for m1)
|
||||
section: Section (okk1 or m1)
|
||||
|
||||
Returns:
|
||||
Class ID or None
|
||||
"""
|
||||
if section == "okk1":
|
||||
# For okk1, extract prefix from computer name
|
||||
# e.g., "303k1" -> "303k" (but we need to find the exact class)
|
||||
# Extract the room/class part (digits only at end)
|
||||
match = re.match(r"^(.+?)(\d+)$", computer)
|
||||
if not match:
|
||||
return None
|
||||
|
||||
prefix_part = match.group(1) # e.g., "303k"
|
||||
|
||||
# Find matching class by prefix
|
||||
for _, row in self.classes_df.iterrows():
|
||||
if row["prefix"] == prefix_part:
|
||||
return row["id"]
|
||||
elif section == "m1":
|
||||
# For m1, format is like "pu-402-1" (prefix-class-station)
|
||||
if computer == "amt":
|
||||
return self.amt_class_id
|
||||
|
||||
parts = computer.split("-")
|
||||
if len(parts) >= 2:
|
||||
# Reconstruct the prefix from parts
|
||||
# "pu-402-1" -> look for class with prefix starting with "pu"
|
||||
prefix_start = parts[0]
|
||||
|
||||
# Find matching class
|
||||
for _, row in self.classes_df.iterrows():
|
||||
row_prefix = row["prefix"]
|
||||
# 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 + "-"):
|
||||
# Check if the class part matches
|
||||
if computer.startswith(row_prefix):
|
||||
return row["id"]
|
||||
|
||||
return None
|
||||
|
||||
def process_files(self) -> Dict[str, List[Session]]:
|
||||
"""
|
||||
Process all log files and extract sessions.
|
||||
|
||||
Returns:
|
||||
Dictionary mapping class/group IDs to lists of sessions
|
||||
"""
|
||||
sessions_by_group = {}
|
||||
|
||||
input_dir = self.workspace_root / "input"
|
||||
|
||||
# Process both sections
|
||||
for section_dir in ["stat_m1", "stat_okk1"]:
|
||||
section_path = input_dir / section_dir
|
||||
|
||||
if not section_path.exists():
|
||||
continue
|
||||
|
||||
section = section_dir.split("_")[1] # Extract okk1 or m1
|
||||
|
||||
# Process each month directory
|
||||
for month_dir in sorted(section_path.iterdir()):
|
||||
if not month_dir.is_dir():
|
||||
continue
|
||||
|
||||
# Process each day file
|
||||
for day_file in sorted(month_dir.glob("*.txt")):
|
||||
entries = self._read_log_file(day_file, section)
|
||||
sessions = self._extract_sessions(entries, section, day_file)
|
||||
|
||||
# Group by class
|
||||
for session in sessions:
|
||||
if session.station:
|
||||
# Determine class ID from session data
|
||||
class_info = self._find_class_from_session(
|
||||
session, section, day_file
|
||||
)
|
||||
if class_info:
|
||||
session_date = class_info.get('date')
|
||||
group_id = class_info['class_id']
|
||||
|
||||
# For m1 before the switch date, group by ip_group.
|
||||
if section == "m1" and class_info.get('ip_group'):
|
||||
if class_info['ip_group'] == self.amt_group_id:
|
||||
group_id = self.amt_group_id
|
||||
elif session_date and session_date < self.m1_ip_to_name_switch_date:
|
||||
group_id = class_info['ip_group']
|
||||
|
||||
if group_id:
|
||||
if group_id not in sessions_by_group:
|
||||
sessions_by_group[group_id] = []
|
||||
sessions_by_group[group_id].append(session)
|
||||
|
||||
return sessions_by_group
|
||||
|
||||
def _read_log_file(
|
||||
self, file_path: Path, section: str
|
||||
) -> List[Tuple[str, LogEntry]]:
|
||||
"""
|
||||
Read and parse a log file.
|
||||
|
||||
Args:
|
||||
file_path: Path to log file
|
||||
section: Section (okk1 or m1)
|
||||
|
||||
Returns:
|
||||
List of (computer_identifier, LogEntry) tuples
|
||||
"""
|
||||
entries = {}
|
||||
|
||||
try:
|
||||
with open(file_path, "r", encoding="utf-8", errors="ignore") as f:
|
||||
for line in f:
|
||||
entry = self._parse_log_entry(line, section)
|
||||
if entry:
|
||||
key = f"{entry.username}:{entry.computer}"
|
||||
if key not in entries:
|
||||
entries[key] = []
|
||||
entries[key].append(entry)
|
||||
except Exception as e:
|
||||
print(f"Warning: Error reading {file_path}: {e}")
|
||||
|
||||
# Flatten to list of entries
|
||||
result = []
|
||||
for entries_list in entries.values():
|
||||
for entry in entries_list:
|
||||
result.append((entry.computer, entry))
|
||||
|
||||
return result
|
||||
|
||||
def _extract_sessions(
|
||||
self, entries: List[Tuple[str, LogEntry]], section: str, file_path: Path
|
||||
) -> List[Session]:
|
||||
"""
|
||||
Extract sessions from log entries.
|
||||
|
||||
Args:
|
||||
entries: List of parsed log entries
|
||||
section: Section (okk1 or m1)
|
||||
file_path: Path to the log file
|
||||
|
||||
Returns:
|
||||
List of extracted sessions
|
||||
"""
|
||||
sessions = []
|
||||
|
||||
# Group entries by (username, computer)
|
||||
grouped = {}
|
||||
for computer, entry in entries:
|
||||
key = (entry.username, computer)
|
||||
if key not in grouped:
|
||||
grouped[key] = []
|
||||
grouped[key].append(entry)
|
||||
|
||||
# Extract sessions from grouped entries
|
||||
for (username, computer), entry_list in grouped.items():
|
||||
# Sort by timestamp
|
||||
entry_list.sort(key=lambda e: e.timestamp)
|
||||
|
||||
# Pair consecutive entries
|
||||
for i in range(0, len(entry_list) - 1, 2):
|
||||
start_entry = entry_list[i]
|
||||
end_entry = entry_list[i + 1]
|
||||
|
||||
sessions.append(Session(
|
||||
station=computer,
|
||||
user=username,
|
||||
start=start_entry.timestamp,
|
||||
end=end_entry.timestamp
|
||||
))
|
||||
|
||||
return sessions
|
||||
|
||||
def _find_class_from_session(
|
||||
self, session: Session, section: str, file_path: Path
|
||||
) -> Optional[dict]:
|
||||
"""
|
||||
Find the class ID for a session.
|
||||
|
||||
Args:
|
||||
session: Session to find class for
|
||||
section: Section (okk1 or m1)
|
||||
file_path: Path to the log file being processed
|
||||
|
||||
Returns:
|
||||
Dict with 'class_id', 'ip_group', and 'date', or None
|
||||
"""
|
||||
# Extract date from file path
|
||||
date_str = file_path.stem # e.g., "13"
|
||||
month_str = file_path.parent.name # e.g., "m1_202601"
|
||||
|
||||
# Try to parse the date
|
||||
try:
|
||||
month_part = month_str.split("_")[1] # e.g., "202601"
|
||||
session_date = datetime.strptime(
|
||||
f"{month_part}{date_str:0>2}", "%Y%m%d"
|
||||
).date()
|
||||
except (ValueError, IndexError):
|
||||
session_date = None
|
||||
|
||||
# For IP addresses, use IP-based lookup
|
||||
if self._is_ip_address(session.station):
|
||||
# Check the date cutoff for m1 (08.04.2026)
|
||||
cutoff_date = datetime.strptime("20260408", "%Y%m%d").date()
|
||||
|
||||
if session_date and session_date < cutoff_date:
|
||||
class_id = self._find_class_for_ip(session.station)
|
||||
if class_id:
|
||||
# Get ip_group for this class
|
||||
class_row = self.classes_df[self.classes_df['id'] == class_id]
|
||||
if not class_row.empty:
|
||||
ip_group = class_row.iloc[0].get('ip_group', '')
|
||||
return {
|
||||
'class_id': class_id,
|
||||
'ip_group': ip_group if ip_group else None,
|
||||
'date': session_date
|
||||
}
|
||||
return None
|
||||
|
||||
# For computer names, extract class
|
||||
if section == "m1" and session.station == "amt":
|
||||
return {
|
||||
'class_id': self.amt_class_id,
|
||||
'ip_group': self.amt_group_id,
|
||||
'date': session_date
|
||||
}
|
||||
class_id = self._find_class_for_computer(session.station, section)
|
||||
if class_id:
|
||||
return {
|
||||
'class_id': class_id,
|
||||
'ip_group': None,
|
||||
'date': session_date
|
||||
}
|
||||
|
||||
return None
|
||||
|
||||
def write_results(self, sessions_by_class: Dict[str, List[Session]]) -> None:
|
||||
"""
|
||||
Write session results to CSV files.
|
||||
|
||||
Args:
|
||||
sessions_by_class: Dictionary mapping class/group IDs to sessions
|
||||
"""
|
||||
output_dir = self.workspace_root / "result" / "logs"
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
for group_id, sessions in sessions_by_class.items():
|
||||
# Create safe filename from group_id
|
||||
# Escape any problematic characters
|
||||
safe_filename = group_id.replace("/", "-").replace(" ", "_")
|
||||
output_file = output_dir / f"{safe_filename}.csv"
|
||||
|
||||
# Create DataFrame
|
||||
data = [
|
||||
{
|
||||
"station": session.station,
|
||||
"user": session.user,
|
||||
"start": session.start.isoformat(sep=" "),
|
||||
"end": session.end.isoformat(sep=" "),
|
||||
}
|
||||
for session in sessions
|
||||
]
|
||||
|
||||
df = pd.DataFrame(data)
|
||||
df = df.sort_values(["start"])
|
||||
|
||||
# Write to CSV
|
||||
df.to_csv(output_file, index=False)
|
||||
|
||||
|
||||
def run_stage(
|
||||
workspace_root: Path,
|
||||
context: Dict[str, Any] | None = None,
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Execute the log processing stage.
|
||||
|
||||
Args:
|
||||
workspace_root: Root directory of the project
|
||||
|
||||
Returns:
|
||||
Dictionary with processing results
|
||||
"""
|
||||
# Load config from stage 1, if it is already present in the pipeline context.
|
||||
if context and "stage_load_settings" in context:
|
||||
config = context["stage_load_settings"]
|
||||
else:
|
||||
from lib.stage_load_settings import SettingsLoader
|
||||
|
||||
loader = SettingsLoader(workspace_root)
|
||||
config = loader.get_config()
|
||||
|
||||
# Process logs
|
||||
processor = LogProcessor(workspace_root, config)
|
||||
sessions_by_group = processor.process_files()
|
||||
processor.write_results(sessions_by_group)
|
||||
|
||||
# Print statistics
|
||||
total_sessions = sum(len(sessions) for sessions in sessions_by_group.values())
|
||||
|
||||
print("✓ Logs processed successfully")
|
||||
print(f" - Groups/Classes with data: {len(sessions_by_group)}")
|
||||
print(f" - Total sessions: {total_sessions}")
|
||||
|
||||
# Also show per-group statistics
|
||||
for group_id in sorted(sessions_by_group.keys()):
|
||||
count = len(sessions_by_group[group_id])
|
||||
# Try to identify if it's ip_group by checking if value is single letter
|
||||
group_type = "(ip_group)" if group_id == "amt" or (len(group_id) <= 3 and group_id.islower()) else "(class)"
|
||||
print(f" • {group_id}: {count} sessions {group_type}")
|
||||
|
||||
return {
|
||||
"sessions_by_group": sessions_by_group,
|
||||
"output_dir": str(workspace_root / "result" / "logs"),
|
||||
}
|
||||
Reference in New Issue
Block a user