forked from SylphAI-Inc/AdalFlow
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile_io.py
194 lines (157 loc) · 5.83 KB
/
file_io.py
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
import json
import os
import pickle
import logging
from typing import Mapping, Any, Optional, List, Dict
from adalflow.utils.serialization import (
to_dict,
serialize,
)
log = logging.getLogger(__name__)
def save_json(obj: Mapping[str, Any], f: str = "task.json") -> None:
"""Save the object to a json file.
Args:
obj (Mapping[str, Any]): The object to be saved.
f (str, optional): The file name. Defaults to "task".
"""
os.makedirs(os.path.dirname(f) or ".", exist_ok=True)
try:
with open(f, "w") as file:
serialized_obj = serialize(obj)
file.write(serialized_obj)
except IOError as e:
raise IOError(f"Error saving object to JSON file {f}: {e}")
def save_csv(
obj: List[Dict[str, Any]], f: str = "task.csv", fieldnames: List[str] = None
) -> None:
"""Save the object to a csv file.
Args:
obj (List[Dict[str, Any]]): The object to be saved.
f (str, optional): The file name. Defaults to "task".
"""
import csv
os.makedirs(os.path.dirname(f) or ".", exist_ok=True)
try:
with open(f, "w", newline="") as csvfile:
writer = csv.DictWriter(csvfile, fieldnames=fieldnames or obj[0].keys())
writer.writeheader()
for row in obj:
filtered_row = {k: v for k, v in row.items() if k in fieldnames}
writer.writerow(filtered_row)
except IOError as e:
raise IOError(f"Error saving object to CSV file {f}: {e}")
def save_pickle(obj: Mapping[str, Any], f: str = "task.pickle") -> None:
"""Save the object to a pickle file.
Args:
obj (Mapping[str, Any]): The object to be saved.
f (str, optional): The file name. Defaults to "task".
"""
os.makedirs(os.path.dirname(f) or ".", exist_ok=True)
try:
with open(f, "wb") as file:
pickle.dump(obj, file)
except Exception as e:
raise Exception(f"Error saving object to pickle file {f}: {e}")
def save(obj: Mapping[str, Any], f: str = "task") -> None:
r"""Save the object to both a json and a pickle file.
We save two versions of the object:
- task.json: the object itself with Parameter serialized to dict
- task.pickle: the object itself with Parameter as is
"""
try:
save_json(obj, f=f"{f}.json")
save_pickle(obj, f=f"{f}.pickle")
except Exception as e:
raise Exception(f"Error saving object to json and pickle files: {e}")
def load_json(f: str = "task.json") -> Optional[Mapping[str, Any]]:
r"""Load the object from a json file.
Args:
f (str, optional): The file name. Defaults to "task".
"""
if not os.path.exists(f):
log.warning(f"File {f} does not exist.")
return None
try:
with open(f, "r") as file:
return json.load(file)
except Exception as e:
raise Exception(f"Error loading object from JSON file {f}: {e}")
def load_pickle(f: str = "task.pickle") -> Optional[Mapping[str, Any]]:
r"""Load the object from a pickle file.
Args:
f (str, optional): The file name. Defaults to "task".
"""
if not os.path.exists(f):
log.warning(f"File {f} does not exist.")
return None
try:
with open(f, "rb") as file:
return pickle.load(file)
except Exception as e:
raise Exception(f"Error loading object from pickle file {f}: {e}")
def load(f: str = "task") -> Optional[Mapping[str, Any]]:
r"""Load both the json and pickle files and return the object from the json file
Args:
f (str, optional): The file name. Defaults to "task".
"""
try:
json_obj = load_json(f=f"{f}.json")
obj = load_pickle(f=f"{f}.pickle")
return json_obj, obj
except Exception as e:
raise Exception(f"Error loading object from json and pickle files: {e}")
def load_jsonl(f: str = None) -> List[Dict[str, Any]]:
r"""Load a jsonl file and return a list of dictionaries.
Args:
f (str, optional): The file name. Defaults to None.
"""
try:
import jsonlines
except ImportError:
raise ImportError("Please install jsonlines to use this function.")
if not os.path.exists(f):
log.warning(f"File {f} does not exist.")
return []
try:
with jsonlines.open(f) as reader:
return list(reader)
except Exception as e:
log.error(f"Error loading jsonl file {f}: {e}")
return []
def append_to_jsonl(f: str, data: Dict[str, Any]) -> None:
r"""Append data to a jsonl file.
Used by the trace_generator_call decorator to log the generator calls.
Args:
f (str): The file name.
data (Dict[str, Any]): The data to be appended.
"""
try:
import jsonlines
except ImportError:
raise ImportError("Please install jsonlines to use this function.")
os.makedirs(os.path.dirname(f) or ".", exist_ok=True)
try:
with jsonlines.open(f, mode="a") as writer:
# call serialize to serialize the object
serialized_data = to_dict(data)
writer.write(serialized_data)
# writer.write(data)
except Exception as e:
log.error(f"Error appending data to jsonl file {f}: {e}")
def write_list_to_jsonl(f: str, data: List[Dict[str, Any]]) -> None:
r"""Write a list of dictionaries to a jsonl file.
Args:
f (str): The file name.
data (List[Dict[str, Any]]): The data to be written.
"""
try:
import jsonlines
except ImportError:
raise ImportError("Please install jsonlines to use this function.")
os.makedirs(os.path.dirname(f) or ".", exist_ok=True)
try:
with jsonlines.open(f, mode="w") as writer:
for d in data:
writer.write(d)
except Exception as e:
log.error(f"Error writing data to jsonl file {f}: {e}")