Spaces:
Sleeping
Sleeping
Download grader/grader.py from hackrock18/cloud-data-janitor: direct link, hf CLI and curl.
- Browser
- Download file 10.9 kB
-
https://huggingface.co/spaces/hackrock18/cloud-data-janitor/resolve/main/grader/grader.py
- Command line
-
hf download hf://spaces/hackrock18/cloud-data-janitor/grader/grader.py
-
curl -L -o grader.py https://huggingface.co/spaces/hackrock18/cloud-data-janitor/resolve/main/grader/grader.py
10.9 kB
| # grader/grader.py | |
| import json | |
| from datetime import datetime, timedelta | |
| from utils.helpers import flatten_file_list, total_size_mb, format_size | |
| from config import ( | |
| CORRECT_MOVE_SCORE, INCORRECT_PENALTY, | |
| TASK_EASY, TASK_MEDIUM, TASK_HARD, | |
| STORAGE_LIMIT_MB, RECENT_DAYS_THRESHOLD, OLD_FILE_THRESHOLD_YEARS, | |
| ) | |
| class Grader: | |
| """Evaluate the agent's performance on a given task.""" | |
| def __init__(self, task_type: str, initial_state: dict, criteria: dict): | |
| self.task_type = task_type | |
| self.initial_state = initial_state | |
| self.criteria = criteria | |
| # ------------------------------------------------------------------ | |
| # Public interface | |
| # ------------------------------------------------------------------ | |
| def grade(self, final_state: dict) -> dict: | |
| """Grade the final filesystem state and return a detailed report.""" | |
| if self.task_type == TASK_EASY: | |
| return self._grade_easy(final_state) | |
| elif self.task_type == TASK_MEDIUM: | |
| return self._grade_medium(final_state) | |
| elif self.task_type == TASK_HARD: | |
| return self._grade_hard(final_state) | |
| else: | |
| raise ValueError(f"Unknown task type: {self.task_type}") | |
| # ------------------------------------------------------------------ | |
| # Easy grader | |
| # ------------------------------------------------------------------ | |
| def _grade_easy(self, final_state: dict) -> dict: | |
| root = final_state.get("root", {}) | |
| all_files = flatten_file_list(root) | |
| file_locations: dict[str, str] = {f["name"]: f["path"] for f in all_files} | |
| score = 0.0 | |
| max_score = 0.0 | |
| details = [] | |
| # Check PDFs in Documents | |
| for fname in self.criteria["files_to_move_to_Documents"]: | |
| max_score += CORRECT_MOVE_SCORE | |
| path = file_locations.get(fname, "") | |
| if "Documents" in path: | |
| score += CORRECT_MOVE_SCORE | |
| details.append({"file": fname, "status": "β Correctly in Documents", "points": CORRECT_MOVE_SCORE}) | |
| else: | |
| details.append({"file": fname, "status": f"β Not in Documents (found at: {path or 'missing'})", "points": 0}) | |
| # Check JPGs in Images | |
| for fname in self.criteria["files_to_move_to_Images"]: | |
| max_score += CORRECT_MOVE_SCORE | |
| path = file_locations.get(fname, "") | |
| if "Images" in path: | |
| score += CORRECT_MOVE_SCORE | |
| details.append({"file": fname, "status": "β Correctly in Images", "points": CORRECT_MOVE_SCORE}) | |
| else: | |
| details.append({"file": fname, "status": f"β Not in Images (found at: {path or 'missing'})", "points": 0}) | |
| # Check non-target files are untouched | |
| collateral_damage = [] | |
| for fname in self.criteria["files_to_leave_untouched"]: | |
| if fname not in file_locations: | |
| collateral_damage.append(fname) | |
| score += INCORRECT_PENALTY | |
| details.append({"file": fname, "status": "β COLLATERAL DAMAGE β file was deleted!", "points": INCORRECT_PENALTY}) | |
| percentage = round((score / max_score) * 100, 1) if max_score > 0 else 0.0 | |
| return { | |
| "task": TASK_EASY, | |
| "score": round(score, 2), | |
| "max_score": round(max_score, 2), | |
| "percentage": percentage, | |
| "collateral_damage": collateral_damage, | |
| "details": details, | |
| "passed": percentage >= 90.0, | |
| } | |
| # ------------------------------------------------------------------ | |
| # Medium grader | |
| # ------------------------------------------------------------------ | |
| def _grade_medium(self, final_state: dict) -> dict: | |
| root = final_state.get("root", {}) | |
| all_files = flatten_file_list(root) | |
| remaining_names = {f["name"] for f in all_files} | |
| to_delete = set(self.criteria["files_to_delete"]) | |
| to_preserve = set(self.criteria["files_to_preserve"]) | |
| correctly_deleted = to_delete - remaining_names | |
| missed_duplicates = to_delete & remaining_names | |
| collateral_damage = to_preserve - remaining_names | |
| score = (len(correctly_deleted) * CORRECT_MOVE_SCORE | |
| - len(collateral_damage) * abs(INCORRECT_PENALTY)) | |
| max_score = len(to_delete) * CORRECT_MOVE_SCORE | |
| percentage = round((max(score, 0) / max_score) * 100, 1) if max_score > 0 else 0.0 | |
| return { | |
| "task": TASK_MEDIUM, | |
| "score": round(score, 2), | |
| "max_score": round(max_score, 2), | |
| "percentage": percentage, | |
| "correctly_deleted": sorted(correctly_deleted), | |
| "missed_duplicates": sorted(missed_duplicates), | |
| "collateral_damage": sorted(collateral_damage), | |
| "passed": percentage >= 90.0 and len(collateral_damage) == 0, | |
| } | |
| # ------------------------------------------------------------------ | |
| # Hard grader | |
| # ------------------------------------------------------------------ | |
| def _grade_hard(self, final_state: dict) -> dict: | |
| initial_root = self.initial_state.get("root", {}) | |
| final_root = final_state.get("root", {}) | |
| initial_files = flatten_file_list(initial_root) | |
| final_files = flatten_file_list(final_root) | |
| initial_total_mb = total_size_mb(initial_files) | |
| final_total_mb = total_size_mb(final_files) | |
| freed_mb = initial_total_mb - final_total_mb | |
| goal_mb = self.criteria.get("storage_goal_mb", STORAGE_LIMIT_MB) | |
| goal_met = freed_mb >= goal_mb | |
| # Check for protected folder violations | |
| protected = self.criteria.get("folders_to_protect", []) | |
| violations = [] | |
| for folder_name in protected: | |
| # Protected folder should still exist with same files | |
| initial_folder = initial_root.get(folder_name, {}) | |
| final_folder = final_root.get(folder_name, {}) | |
| if not final_folder: | |
| violations.append(f"Protected folder '{folder_name}' was deleted or moved!") | |
| continue | |
| initial_contents = set(initial_folder.get("contents", {}).keys()) | |
| final_contents = set(final_folder.get("contents", {}).keys()) | |
| missing = initial_contents - final_contents | |
| if missing: | |
| violations.append(f"Files removed from protected '{folder_name}': {missing}") | |
| # Check for recently accessed file violations | |
| cutoff = datetime.now() - timedelta(days=RECENT_DAYS_THRESHOLD) | |
| initial_names = {f["name"]: f for f in initial_files} | |
| final_names = {f["name"] for f in final_files} | |
| recent_deleted = [] | |
| for fname, fmeta in initial_names.items(): | |
| accessed_str = fmeta.get("last_accessed", "") | |
| try: | |
| accessed = datetime.fromisoformat(accessed_str) | |
| except (ValueError, TypeError): | |
| continue | |
| if accessed >= cutoff and fname not in final_names: | |
| recent_deleted.append(fname) | |
| # Score | |
| score = 0.0 | |
| max_score = 3.0 | |
| if goal_met: | |
| score += 1.0 | |
| if not violations: | |
| score += 1.0 | |
| if not recent_deleted: | |
| score += 1.0 | |
| percentage = round((score / max_score) * 100, 1) | |
| return { | |
| "task": TASK_HARD, | |
| "score": round(score, 2), | |
| "max_score": max_score, | |
| "percentage": percentage, | |
| "freed_mb": round(freed_mb, 2), | |
| "freed_human": format_size(freed_mb), | |
| "goal_mb": goal_mb, | |
| "goal_met": goal_met, | |
| "protected_folder_violations": violations, | |
| "recent_files_deleted": recent_deleted, | |
| "passed": goal_met and not violations and not recent_deleted, | |
| } | |
| # ------------------------------------------------------------------ | |
| # Convenience function | |
| # ------------------------------------------------------------------ | |
| def grade_from_files(task_type: str, initial_path: str, final_path: str, criteria: dict) -> dict: | |
| """Load state from JSON files and grade.""" | |
| with open(initial_path) as f: | |
| initial_state = json.load(f) | |
| with open(final_path) as f: | |
| final_state = json.load(f) | |
| grader = Grader(task_type, initial_state, criteria) | |
| return grader.grade(final_state) | |
| def print_report(report: dict): | |
| """Print a human-readable grade report.""" | |
| print("\n" + "=" * 60) | |
| print(f" GRADE REPORT β {report['task'].upper()} TASK") | |
| print("=" * 60) | |
| print(f" Score : {report['score']} / {report['max_score']}") | |
| print(f" Grade : {report['percentage']}%") | |
| print(f" Passed : {'β YES' if report['passed'] else 'β NO'}") | |
| if report["task"] == TASK_EASY: | |
| dmg = report.get("collateral_damage", []) | |
| print(f" Collateral damage: {len(dmg)} file(s)") | |
| for d in report.get("details", []): | |
| print(f" {d['status']} [{d['file']}]") | |
| elif report["task"] == TASK_MEDIUM: | |
| print(f" Correctly deleted : {len(report.get('correctly_deleted', []))}") | |
| print(f" Missed duplicates : {len(report.get('missed_duplicates', []))}") | |
| print(f" Collateral damage : {len(report.get('collateral_damage', []))}") | |
| elif report["task"] == TASK_HARD: | |
| goal = "β " if report["goal_met"] else "β" | |
| print(f" Storage freed : {report['freed_human']} {goal}") | |
| print(f" Goal : {format_size(report['goal_mb'])}") | |
| if report["protected_folder_violations"]: | |
| for v in report["protected_folder_violations"]: | |
| print(f" β οΈ {v}") | |
| if report["recent_files_deleted"]: | |
| print(f" β οΈ Recent files deleted: {report['recent_files_deleted']}") | |
| print("=" * 60 + "\n") | |
| def grade_state(fs, task_name): | |
| files = fs.list_files() | |
| total = len(files) | |
| if total == 0: | |
| return 0.5 | |
| progress = 0 | |
| # EASY β files moved to Documents | |
| if task_name == "easy": | |
| for f in files: | |
| path = f.get("path", "") | |
| if "Documents" in path: | |
| progress += 1 | |
| # MEDIUM β duplicates removed | |
| elif task_name == "medium": | |
| names = set() | |
| for f in files: | |
| names.add(f.get("name")) | |
| progress = len(names) | |
| # HARD β storage reduction | |
| elif task_name == "hard": | |
| initial_files = fs.initial_state.get("root", {}) | |
| initial_count = len(initial_files) | |
| current_count = total | |
| progress = max(0, initial_count - current_count) | |
| else: | |
| progress = total // 2 | |
| score = progress / max(total, 1) | |
| # Keep strictly between 0 and 1 | |
| if score <= 0: | |
| score = 0.05 | |
| if score >= 1: | |
| score = 0.95 | |
| return round(score, 2) |