lhpku20010120's picture
Release WorkSurface-Build v0.1.0 public benchmark inputs
b6beed8 verified
Raw
History Blame Contribute Delete
8.31 kB
"""
The Query Answering Pipeline
"""
import os
import re
import json
import glob
import pickle
from tqdm import tqdm
from loguru import logger
from query.primitive_pipeline import *
from table2tree.extract_excel import *
from table2tree.feature_tree import *
from utils.constants import DELIMITER
def answer_question(
qa_pair: dict, # A single QA pair
table_file: str, # Original table file path
pkl_dir: str, # Path for storing HO-Tree intermediate results
enable_query_decompose: bool = True, # Whether to enable query decomposition
enable_emebdding: bool = True, # Whether to enable the embedding mechanism
log_dir: str = LOG_DIR # Log directory
):
qid = qa_pair["id"]
tid = qa_pair['table_id']
query = qa_pair["query"]
##### Create a log file named table_id_question_id.log
log_file = os.path.join(log_dir, f'{tid}_{qid}.log')
log_file_handler = logger.add(log_file)
logger.info(f"{DELIMITER} Start answering the question {DELIMITER}")
start_time = time.time()
logger.info(f"Question ID: {qid}")
logger.info(f"Table ID: {tid}")
logger.info(f"Question: {query}")
##### Load the HO-Tree
pkl_file = os.path.join(pkl_dir, f'{tid}.pkl')
embedding_cache_file = os.path.join(pkl_dir, f'{tid}_embedding.json')
with open(pkl_file, 'rb') as file:
ho_tree = pickle.load(file)
logger.info(f"Loading PKL File: {pkl_file}")
logger.info(f"Loading Embedding Cache File: {embedding_cache_file}")
final_answer, _, reliability = qa_RWP(
query=query,
ho_tree=ho_tree,
table_file=table_file,
embedding_cache_file=embedding_cache_file,
enable_emebdding=enable_emebdding,
enable_query_decompose=enable_query_decompose,
)
qa_pair["reliability"] = reliability
qa_pair["model_output"] = final_answer
end_time = time.time()
logger.info(f"{DELIMITER} Question answered successfully! {DELIMITER}")
logger.info(f"Cost time: {end_time - start_time}")
logger.remove(log_file_handler)
return qa_pair
def benchmark(
table_dir: str, # Directory containing table files, where each filename is the unique table identifier
input_jsonl: str, # JSONL file that stores input QA pairs; each record requires id, table_id, query, and label
output_jsonl: str, # File for saving QA pair model inference results
pkl_dir: str, # Path for saving converted HO-Tree intermediates and the embedding cache
enable_emebdding: bool = True, # Whether to enable the embedding mechanism, corresponding to two-stage forward verification
cache_dir: str = CACHE_DIR, # Cache storage path
log_dir: str = LOG_DIR, # Log storage path
process_from_scratch: bool = False, # Whether to rerun HO-Tree generation and preprocessing
qa_from_scratch: bool = False, # Whether to rerun QA from scratch
):
if not os.path.exists(pkl_dir): os.makedirs(pkl_dir)
if not os.path.exists(cache_dir): os.makedirs(cache_dir)
if not os.path.exists(log_dir): os.makedirs(log_dir)
##### Load QA pairs to be processed
input_list = []
with open(input_jsonl, "r", encoding="utf-8") as file:
for line in file:
input_list.append(json.loads(line))
input_list.sort(key=lambda x: x["table_id"]) # Sort by table_id
##### Load the full list of table files
table_files = sorted(glob.glob(table_dir + "/*"))
# Process different input formats by converting them all to Excel format
new_table_files = []
for table_file in table_files:
last_dot_idx = os.path.basename(table_file).rfind('.')
new_table_file = os.path.join(table_dir, os.path.basename(table_file)[:last_dot_idx] + '.xlsx')
if table_file.endswith(".xlsx"):
pass
elif table_file.endswith(".csv"):
df = pd.read_csv(new_table_file)
df.to_excel(new_table_file, index=False, engine='openpyxl')
elif table_file.endswith(".html"):
html_content = open(table_file).read()
html2workbook(html_content).save(new_table_file)
elif table_file.endswith(".md"):
markdown_content = open(table_file).read()
table = extract_markdown_tables(markdown_content)
with pd.ExcelWriter(new_table_file, engine='openpyxl') as writer:
sheet_name = f'sheet'
df = pd.DataFrame(table[1:], columns=table[0])
df.to_excel(writer, sheet_name=sheet_name, index=False)
new_table_files.append(new_table_file)
table_files = new_table_files
##### Load already processed QA pairs
output_data = []
qid_set = set()
if not qa_from_scratch and os.path.exists(output_jsonl):
with open(output_jsonl, 'r', encoding='utf-8') as file:
for line in file:
output_data.append(json.loads(line))
qid_set = set([r['id'] for r in output_data])
##### Try to load HO-Tree intermediate files
pkl_files = []
embedding_cache_files = []
if not process_from_scratch and pkl_dir is not None:
pkl_files = sorted(glob.glob(pkl_dir + "/*.pkl"))
embedding_cache_files = sorted(glob.glob(pkl_dir + "/*_embedding.json"))
##### Process each table one by one
for table_file in table_files:
table_id = os.path.basename(table_file).split('.')[0]
##### Table preprocessing: Table -> HO-Tree
if os.path.join(pkl_dir, f'{table_id}.pkl') not in pkl_files:
try:
ho_tree = get_excel_feature_tree(table_file, log_dir=log_dir, vlm_cache=False)
tree_json = ho_tree.__json__()
tree_str = ho_tree.__str__([1])
with open(os.path.join(pkl_dir, f"{table_id}.pkl"), "wb") as f:
pickle.dump(ho_tree, f)
with open(os.path.join(pkl_dir, f"{table_id}.txt"), "w", encoding='utf-8') as f:
f.write(tree_str)
with open(os.path.join(pkl_dir, f"{table_id}.json"), "w", encoding='utf-8') as f:
json.dump(tree_json, f, indent=4, ensure_ascii=False)
except Exception as e:
import traceback; traceback.print_exc()
logger.error(f"File: {table_file} Error: {e}")
continue
else:
logger.info(f"File: {table_file} has already been converted into an HO-Tree!!!")
##### Generate embeddings for table content
if os.path.join(pkl_dir, f'{table_id}_embedding.json') not in embedding_cache_files:
embedding_dict = EmbeddingModel().get_embedding_dict(ho_tree.all_value_list())
with open(os.path.join(pkl_dir, f"{table_id}_embedding.json"), "w", encoding='utf-8') as f:
json.dump(embedding_dict, f, ensure_ascii=False)
##### Process each question one by one
for qa_pair in input_list:
table_id = qa_pair['table_id']
##### Prevent duplicate question answering
if not qa_from_scratch and qa_pair['id'] in qid_set:
continue
##### Execute question answering #####
record = answer_question(
qa_pair=qa_pair,
table_file=table_file,
pkl_dir=pkl_dir,
enable_emebdding=enable_emebdding,
log_dir=log_dir
)
##### Save QA results
output_data.append(record)
qid_set.add(record['id'])
with open(output_jsonl, "a", encoding="utf-8") as file:
file.write(f"{json.dumps(record, ensure_ascii=False)}\n")
def main():
##### Update these paths as needed
input_jsonl ="data/SSTQA-en/test.jsonl"
table_dir = "data/SSTQA-en/table"
pkl_dir = "data/SSTQA-en/pkl"
output_jsonl = "SSTQA-en/output.jsonl"
log_dir = "data/SSTQA-en/log"
benchmark(
table_dir=table_dir,
input_jsonl=input_jsonl,
output_jsonl=output_jsonl,
pkl_dir=pkl_dir,
cache_dir=CACHE_DIR,
log_dir=log_dir,
)
if __name__ == "__main__":
main()
# run()