Datasets:

ArXiv:
License:
dp-bench / scripts /utils.py
mer9ury
refactor: Sync evaluation pipeline, scripts, and docs from private repo
1e9a6e5
raw
history blame
3.91 kB
import os
import json
from pathlib import Path
from typing import List
def read_file_paths(path: str, supported_formats: List[str] = [".jpg"]) -> List[str]:
"""Read files in a directory and return their content as a list of strings
Args:
path (str): the path to the directory containing the file paths to read
supported_formats (List[str], optional): the supported file formats. Defaults to [".jpg"].
Returns:
list: list of valid file paths
Raises:
FileNotFoundError: if the directory does not exist
"""
path = Path(path)
# check if the directory exists and is a directory
if not path.exists() or not path.is_dir():
raise FileNotFoundError(f"Directory {path} not found")
# get the list of files in the directory
file_paths = [file for file in path.iterdir() if file.is_file()]
# filter file paths based on the supported formats
if supported_formats:
file_paths = [file for file in file_paths if file.suffix in supported_formats]
else:
file_paths = []
# sort by filename for deterministic ordering
file_paths.sort(key=lambda f: f.name)
return file_paths
def validate_json_save_path(path: str) -> None:
# Check if the path ends with .json
if not path.endswith('.json'):
raise ValueError(f"The file '{path}' does not have a .json extension.")
# Get the directory part of the path
directory = os.path.dirname(path)
# Check if the directory exists or create it if requested
if directory and not os.path.exists(directory):
os.makedirs(directory)
def load_json_file(path: str) -> dict:
# Check if the file exists
if os.path.isfile(path):
try:
# Open and load the JSON file
with open(path, 'r') as file:
return json.load(file)
except (json.JSONDecodeError, OSError) as e:
print(f"Error loading JSON from '{path}': {e}")
return {}
else:
# If the file does not exist, return an empty dictionary
return {}
def get_interim_dir_path(save_path: str) -> Path:
"""Get the interim directory path based on the output filename"""
save_path_obj = Path(save_path)
interim_dir_name = save_path_obj.stem # Get filename without extension
return save_path_obj.parent / interim_dir_name
def get_interim_file_path(interim_dir: Path, filename: str) -> Path:
"""Get the interim file path for a specific document"""
safe_filename = filename.replace('/', '_').replace('\\', '_') # Handle path separators
return interim_dir / f"{safe_filename}.json"
def save_interim_result(interim_dir: Path, filename: str, result: dict) -> None:
"""Save individual API result to interim JSON file"""
interim_path = get_interim_file_path(interim_dir, filename)
with open(interim_path, "w", encoding="utf-8") as f:
json.dump(result, f, ensure_ascii=False, indent=4)
def load_interim_result(interim_dir: Path, filename: str) -> dict:
"""Load individual API result from interim JSON file"""
interim_path = get_interim_file_path(interim_dir, filename)
if interim_path.exists():
with open(interim_path, "r", encoding="utf-8") as f:
return json.load(f)
return None
def collect_all_interim_results(interim_dir: Path) -> dict:
"""Collect all interim results from the interim directory"""
result_dict = {}
# Load all interim results
if interim_dir.exists():
for interim_file in interim_dir.glob("*.json"):
filename = interim_file.stem # Remove .json extension
try:
with open(interim_file, "r", encoding="utf-8") as f:
result_dict[filename] = json.load(f)
except Exception as e:
print(f"Error loading interim file {interim_file}: {e}")
return result_dict