| """ |
| 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, |
| table_file: str, |
| pkl_dir: str, |
| enable_query_decompose: bool = True, |
| enable_emebdding: bool = True, |
| log_dir: str = LOG_DIR |
| ): |
| |
| qid = qa_pair["id"] |
| tid = qa_pair['table_id'] |
| query = qa_pair["query"] |
|
|
| |
| 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}") |
|
|
| |
| 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, |
| input_jsonl: str, |
| output_jsonl: str, |
| pkl_dir: str, |
| enable_emebdding: bool = True, |
| cache_dir: str = CACHE_DIR, |
| log_dir: str = LOG_DIR, |
| process_from_scratch: bool = False, |
| qa_from_scratch: bool = False, |
| ): |
|
|
| 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) |
|
|
| |
| 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"]) |
|
|
| |
| table_files = sorted(glob.glob(table_dir + "/*")) |
|
|
| |
| 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 |
|
|
| |
| 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]) |
|
|
| |
| 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")) |
|
|
| |
| for table_file in table_files: |
| table_id = os.path.basename(table_file).split('.')[0] |
|
|
| |
| 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!!!") |
|
|
| |
| 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) |
|
|
| |
| for qa_pair in input_list: |
| table_id = qa_pair['table_id'] |
| |
| |
| if not qa_from_scratch and qa_pair['id'] in qid_set: |
| continue |
|
|
| |
| record = answer_question( |
| qa_pair=qa_pair, |
| table_file=table_file, |
| pkl_dir=pkl_dir, |
| enable_emebdding=enable_emebdding, |
| log_dir=log_dir |
| ) |
|
|
| |
| 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(): |
| |
| 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() |
| |