File size: 12,859 Bytes
b6beed8 | 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 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 | import pickle
import os
import glob
import json
import multiprocessing
import time
import traceback
from loguru import logger
from tqdm import tqdm
from clean_cache import clear_cache_folder
from table2tree.feature_tree import *
from embedding import *
import logging
# Ignore warnings from the transformers package
logging.getLogger("transformers").setLevel(logging.ERROR)
import warnings
# Ignore all warnings
warnings.filterwarnings("ignore")
def excel2tree(
file,
pkl_dir=None,
convert_pkl=True,
json_dir : bool = None,
convert_json=True,
str_dir=None,
convert_str=True,
embedding_dir=None,
convert_embedding=True,
structured=False,
log=False,
vlm_cache=False,
):
""" Convert the input excel file into the HO-Tree (FeatureTree) object.
Args:
file (_type_): the input Excel file path
pkl_dir (_type_, optional): _description_. Output path for saving pkl files
convert_pkl (bool, optional): _description_. Whether to output the pkl file for the FeatureTree object
json_dir (_type_, optional): _description_. Output path for saving JSON files
convert_json (bool, optional): _description_. Defaults to True. Whether to output the serialized JSON file for the FeatureTree object
str_dir (_type_, optional): _description_. Output path for saving string files
convert_str (bool, optional): _description_. Defaults to True. Whether to output the serialized string file for the FeatureTree object
embedding_dir (_type_, optional): _description_. Output path for saving embedding files
convert_embedding (bool, optional): _description_. Defaults to True. Whether to save embeddings for each table cell for later question answering
structured (bool, optional): _description_. Defaults to True. Semi-structured tables by default
log (bool, optional): _description_. Defaults to True. Whether to output logs
vlm_cache (bool, optional): _description_. Defaults to True. Whether to use caching during VLM conversion
Returns:
FeatureTree: The convert HO-Tree of the input excel file.
"""
if not os.path.exists(pkl_dir): os.mkdir(pkl_dir)
if not os.path.exists(json_dir): os.mkdir(json_dir)
if not os.path.exists(str_dir): os.mkdir(str_dir)
if not os.path.exists(embedding_dir): os.mkdir(embedding_dir)
name = os.path.basename(file)[:-5]
flag = [False, False, False, False]
if (
convert_pkl and os.path.exists(os.path.join(pkl_dir, f"{name}.pkl"))
) or not convert_pkl:
flag[0] = True
if (
convert_json and os.path.exists(os.path.join(json_dir, f"{name}.json"))
) or not convert_json:
flag[1] = True
if (
convert_str and os.path.exists(os.path.join(str_dir, f"{name}.txt"))
) or not convert_str:
flag[2] = True
if (
convert_embedding
and os.path.exists(os.path.join(embedding_dir, f"{name}.embedding.json"))
) or not convert_embedding:
flag[3] = True
if flag == [True, True, True, True]:
return
try:
f_tree = get_excel_feature_tree(file, structured=structured, log=log, vlm_cache=vlm_cache)
tree_json = f_tree.__json__()
tree_str = f_tree.__str__()
except Exception as e:
logger.error(f"File: {name}.xlsx Error: {e}")
with open("./error.txt", "a") as f:
f.write(f"process_one_table() error: {name}.xlsx\n")
traceback.print_exc()
return
if convert_pkl:
with open(os.path.join(pkl_dir, f"{name}.pkl"), "wb") as f:
pickle.dump(f_tree, f)
if convert_json:
with open(os.path.join(json_dir, f"{name}.json"), "w") as f:
json.dump(tree_json, f, indent=4, ensure_ascii=False)
if convert_str:
with open(os.path.join(str_dir, f"{name}.txt"), "w") as f:
f.write(tree_str)
if convert_embedding:
embedding_dict = EmbeddingModel().get_embedding_dict(
f_tree.all_value_list()
)
EmbeddingModel().save_embedding_dict(
embedding_dict, os.path.join(embedding_dir, f"{name}.embedding.json")
)
return f_tree
def preprocess_one_pkl(
file,
json_dir=None,
convert_json=True,
str_dir=None,
convert_str=True,
embedding_dir=None,
convert_embedding=True,
):
"""_summary_
Args:
file (_type_): _description_
json_dir (_type_, optional): _description_. Defaults to None.
convert_json (bool, optional): _description_. Defaults to True.
str_dir (_type_, optional): _description_. Defaults to None.
convert_str (bool, optional): _description_. Defaults to True.
embedding_dir (_type_, optional): _description_. Defaults to None.
convert_embedding (bool, optional): _description_. Defaults to True.
Returns:
_type_: _description_
"""
name = os.path.basename(file)[:-4]
with open(os.path.join(file), "rb") as f:
f_tree: FeatureTree = pickle.load(f)
flag = [False, False, False]
if (
convert_json and os.path.exists(os.path.join(json_dir, f"{name}.json"))
) or not convert_json:
flag[0] = True
if (
convert_str and os.path.exists(os.path.join(str_dir, f"{name}.txt"))
) or not convert_str:
flag[1] = True
if (
convert_embedding
and os.path.exists(os.path.join(embedding_dir, f"{name}.embedding.json"))
) or not convert_embedding:
flag[2] = True
if flag == [True, True, True]:
return
try:
tree_json = f_tree.__json__()
tree_str = f_tree.__str__()
except Exception as e:
logger.error(f"File: {name}.xlsx Error: {e}")
with open("./error.txt", "a") as f:
f.write(f"process_one_pkl() error: {name}.xlsx\n")
traceback.print_exc()
return
if convert_json:
with open(os.path.join(json_dir, f"{name}.txt"), "w") as f:
f.write(tree_str)
if convert_str:
with open(os.path.join(json_dir, f"{name}.json"), "w") as f:
json.dump(tree_json, f, indent=4, ensure_ascii=False)
if convert_embedding:
embedding_dict = EmbeddingModel().get_embedding_dict(
f_tree.all_value_list()
)
EmbeddingModel().save_embedding_dict(
embedding_dict, os.path.join(embedding_dir, f"{name}.embedding.json")
)
return f_tree
def process_excel_files(
files,
pkl_dir=None,
convert_pkl=True,
json_dir : bool = None,
convert_json=True,
str_dir=None,
convert_str=True,
embedding_dir=None,
convert_embedding=True,
structured=False,
log=False,
vlm_cache=False,
):
""" Convert the input excel file list into the HO-Tree (FeatureTree) object.
Args:
file (_type_): the input Excel file path
pkl_dir (_type_, optional): _description_. Output path for saving pkl files
convert_pkl (bool, optional): _description_. Whether to output the pkl file for the FeatureTree object
json_dir (_type_, optional): _description_. Output path for saving JSON files
convert_json (bool, optional): _description_. Defaults to True. Whether to output the serialized JSON file for the FeatureTree object
str_dir (_type_, optional): _description_. Output path for saving string files
convert_str (bool, optional): _description_. Defaults to True. Whether to output the serialized string file for the FeatureTree object
embedding_dir (_type_, optional): _description_. Output path for saving embedding files
convert_embedding (bool, optional): _description_. Defaults to True. Whether to save embeddings for each table cell for later question answering
structured (bool, optional): _description_. Defaults to True. Semi-structured tables by default
log (bool, optional): _description_. Defaults to True. Whether to output logs
vlm_cache (bool, optional): _description_. Defaults to True. Whether to use caching during VLM conversion
"""
if convert_pkl:
os.makedirs(pkl_dir, exist_ok=True)
if convert_json:
os.makedirs(json_dir, exist_ok=True)
if convert_str:
os.makedirs(str_dir, exist_ok=True)
if convert_embedding:
os.makedirs(embedding_dir, exist_ok=True)
for file in tqdm(files, desc="Processing..."):
excel2tree(
file,
pkl_dir=pkl_dir,
convert_pkl=convert_pkl,
json_dir=json_dir,
convert_json=convert_json,
str_dir=str_dir,
convert_str=convert_str,
embedding_dir=embedding_dir,
convert_embedding=convert_embedding,
structured=structured,
log=log,
vlm_cache=vlm_cache,
)
def process_pkl_files(
files,
json_dir=None,
convert_json=True, # Whether to output the serialized JSON file for the FeatureTree object
str_dir=None,
convert_str=True, # Whether to output the serialized string file for the FeatureTree object
embedding_dir=None,
convert_embedding=True, # Whether to save embeddings for each table cell for later question answering
log=False, # Whether to output logs
vlm_cache=False, # Whether to use caching during VLM conversion
):
if convert_json:
os.makedirs(json_dir, exist_ok=True)
if convert_str:
os.makedirs(str_dir, exist_ok=True)
if convert_embedding:
os.makedirs(embedding_dir, exist_ok=True)
for file in tqdm(files, desc="Processing..."):
preprocess_one_pkl(
file,
json_dir=json_dir,
convert_json=convert_json,
str_dir=str_dir,
convert_str=convert_str,
embedding_dir=embedding_dir,
convert_embedding=convert_embedding,
)
def multi_process_process_excels(
files,
pkl_dir=None,
convert_pkl=True, # Whether to output the pkl file for the FeatureTree object
json_dir=None,
convert_json=True, # Whether to output the serialized JSON file for the FeatureTree object
str_dir=None,
convert_str=True, # Whether to output the serialized string file for the FeatureTree object
embedding_dir=None,
convert_embedding=True, # Whether to save embeddings for each table cell for later question answering
structured=False, # Semi-structured tables by default
log=False, # Whether to output logs
vlm_cache=False, # Whether to use caching during VLM conversion
n=6,
):
param_list = [
(
file,
pkl_dir,
convert_pkl,
json_dir,
convert_json,
str_dir,
convert_str,
embedding_dir,
convert_embedding,
log,
vlm_cache,
)
for file in files
]
with multiprocessing.Pool(processes=n) as pool:
pool.starmap(excel2tree, param_list)
print("All jobs completed!")
def multi_process_process_pkls(
files,
json_dir=None,
convert_json=True, # Whether to output the serialized JSON file for the FeatureTree object
str_dir=None,
convert_str=True, # Whether to output the serialized string file for the FeatureTree object
embedding_dir=None,
convert_embedding=True, # Whether to save embeddings for each table cell for later question answering
n=6,
):
param_list = [
(
file,
json_dir,
convert_json,
str_dir,
convert_str,
embedding_dir,
convert_embedding,
)
for file in files
]
with multiprocessing.Pool(processes=n) as pool:
pool.starmap(preprocess_one_pkl, param_list)
print("All jobs completed!")
def main():
clear_cache_folder(CACHE_DIR)
# dataset_dir = '/home/zirui/SemiTableQA/data/temptabqa-st/'
dataset_dir = '/home/zirui/SemiTableQA/data/wikitq-st-demo/'
table_dir = os.path.join(dataset_dir, 'table')
pkl_dir = os.path.join(dataset_dir, 'pkl')
json_dir = os.path.join(dataset_dir, 'json')
str_dir = os.path.join(dataset_dir, 'str')
embedding_dir = os.path.join(dataset_dir, 'embedding')
files = glob.glob(table_dir + '/*.xlsx')
for file in tqdm(files):
excel2tree(
file,
pkl_dir=pkl_dir,
convert_pkl=True,
json_dir=json_dir,
convert_json=True,
str_dir=str_dir,
convert_str=True,
embedding_dir=embedding_dir,
convert_embedding=True,
structured=False,
log=True,
vlm_cache=False,
)
if __name__ == '__main__':
main()
|