cloud-data-janitor / utils /helpers.py
Afifa Kureshi
Initial clean submission
c5997d8
Raw History Blame Contribute Delete
5.88 kB
# utils/helpers.py
import json
import os
from datetime import datetime, timedelta
from typing import Any
from config import OLD_FILE_THRESHOLD_YEARS, RECENT_DAYS_THRESHOLD, FILE_CATEGORIES
def load_json(filepath: str) -> dict:
"""Load and return a JSON file as a dict."""
with open(filepath, "r") as f:
return json.load(f)
def save_json(data: dict, filepath: str):
"""Save a dict to a JSON file (creates parent dirs if needed)."""
os.makedirs(os.path.dirname(filepath), exist_ok=True)
with open(filepath, "w") as f:
json.dump(data, f, indent=2)
def parse_date(date_str: str) -> datetime:
"""Parse an ISO-format date string to a datetime object."""
try:
return datetime.fromisoformat(date_str)
except (ValueError, TypeError):
return datetime.min
def is_old_file(last_accessed_str: str, threshold_years: int = OLD_FILE_THRESHOLD_YEARS) -> bool:
"""Return True if the file hasn't been accessed within the threshold."""
last_accessed = parse_date(last_accessed_str)
cutoff = datetime.now() - timedelta(days=365 * threshold_years)
return last_accessed < cutoff
def is_recent_file(last_accessed_str: str, threshold_days: int = RECENT_DAYS_THRESHOLD) -> bool:
"""Return True if the file was accessed within the recent threshold."""
last_accessed = parse_date(last_accessed_str)
cutoff = datetime.now() - timedelta(days=threshold_days)
return last_accessed >= cutoff
def get_category_for_extension(extension: str) -> str:
"""Return the folder category for a given file extension."""
ext = extension.lower()
for category, extensions in FILE_CATEGORIES.items():
if ext in extensions:
return category
return "Misc"
def format_size(size_mb: float) -> str:
"""Human-readable file size."""
if size_mb >= 1024:
return f"{size_mb / 1024:.2f} GB"
if size_mb >= 1:
return f"{size_mb:.2f} MB"
return f"{size_mb * 1024:.2f} KB"
def flatten_file_list(root: dict, path: str = "") -> list:
"""
Recursively flatten the file system tree into a list of file dicts.
Each entry: {name, path, type, extension, size_mb, created_date, last_accessed}
"""
results = []
for name, meta in root.items():
current_path = f"{path}/{name}" if path else name
if not isinstance(meta, dict):
continue
if meta.get("type") == "file":
results.append({
"name": name,
"path": current_path,
**meta,
})
elif meta.get("type") == "folder":
results.extend(flatten_file_list(meta.get("contents", {}), current_path))
return results
def find_duplicates(file_list: list) -> list:
"""
Find duplicate files: same base name (ignoring trailing numbers like (1), (2))
and same size.
Returns a list of lists, where each sub-list is a group of duplicate paths.
"""
import re
groups: dict[tuple, list] = {}
for f in file_list:
if f.get("type") != "file":
continue
name = f["name"]
size = f.get("size_mb", 0)
# Strip trailing duplicate markers: "file(1).pdf" → "file.pdf"
base = re.sub(r"\(\d+\)(\.[^.]+)$", r"\1", name)
key = (base.lower(), round(size, 3))
groups.setdefault(key, []).append(f)
return [group for group in groups.values() if len(group) > 1]
def total_size_mb(file_list: list) -> float:
"""Return the total size in MB of a list of file dicts."""
return sum(f.get("size_mb", 0) for f in file_list)
def summarize_filesystem(root: dict) -> dict:
"""Return a high-level summary of the filesystem."""
all_files = flatten_file_list(root)
total_files = len(all_files)
total_mb = total_size_mb(all_files)
by_category: dict[str, float] = {}
for f in all_files:
cat = get_category_for_extension(f.get("extension", ""))
by_category[cat] = by_category.get(cat, 0) + f.get("size_mb", 0)
return {
"total_files": total_files,
"total_size_mb": round(total_mb, 2),
"total_size_human": format_size(total_mb),
"by_category": {k: round(v, 2) for k, v in by_category.items()},
}
def build_prompt_context(observation: dict) -> str:
"""Convert the observation dict into a compact string for LLM prompts."""
root = observation.get("root", {})
summary = summarize_filesystem(root)
all_files = flatten_file_list(root)
lines = [
f"Total files: {summary['total_files']}",
f"Total size: {summary['total_size_human']}",
"Files:",
]
for f in all_files:
accessed = f.get("last_accessed", "unknown")
size = format_size(f.get("size_mb", 0))
lines.append(f" - {f['path']} | {size} | last accessed: {accessed}")
return "\n".join(lines)
# ------------------------------------------------------------------
# OpenEnv helpers
# ------------------------------------------------------------------
from config import INITIAL_STATE_FILE
import os
def load_initial_state():
"""
Load the initial filesystem state from JSON.
"""
if not os.path.exists(INITIAL_STATE_FILE):
raise FileNotFoundError(
f"Initial state file not found: {INITIAL_STATE_FILE}"
)
with open(INITIAL_STATE_FILE, "r") as f:
return json.load(f)
def load_task_criteria(task_name: str):
"""
Load task criteria file based on task name.
Example:
data/criteria_easy.json
data/criteria_medium.json
data/criteria_hard.json
"""
filename = f"criteria_{task_name}.json"
path = os.path.join(
"data",
filename
)
if not os.path.exists(path):
# fallback empty criteria
return {}
with open(path, "r") as f:
return json.load(f)