Datasets:

ArXiv:
License:
File size: 3,905 Bytes
b837da3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1e9a6e5
 
 
b837da3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1e9a6e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
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