import shutil from rocksdict import Rdict, Options, SliceTransform, PlainTableFactoryOptions, DBCompressionType import os import argparse import numpy as np import pandas as pd import smart_open import json import hashlib import tqdm from indexed_zstd import IndexedZstdFile def db_options(): opt = Options() # create table opt.create_if_missing(True) # config to more jobs opt.set_max_background_jobs(8) # configure mem-table to a large value (1024 MB) opt.set_write_buffer_size(1024*1024*1024) # configure l0 and l1 size, let them have the same size (1 GB) opt.set_max_bytes_for_level_base(1024*1024*1024) # 1024 MB file size opt.set_target_file_size_base(1024*1024*1024) # use a smaller compaction multiplier opt.set_max_bytes_for_level_multiplier(4.0) # use 8-byte prefix (2 ^ 64 is far enough for transaction counts) opt.set_prefix_extractor(SliceTransform.create_max_len_prefix(8)) opt.set_compression_type(DBCompressionType.none()) return opt # create DB emb_db = Rdict("emb_rdict/", db_options()) existing_keys = set() for key in tqdm.tqdm(emb_db.keys(), desc="add keys in memory"): existing_keys.add(key) parser = argparse.ArgumentParser(description='Add data to Rdict database.') parser.add_argument('--input', type=str, nargs="+") parser.add_argument('--emb', type=str, nargs="+") args = parser.parse_args() input_paths = sorted(args.input) emb_paths = sorted(args.emb) assert len(input_paths) == len(emb_paths) for input_path, emb_path in tqdm.tqdm(zip(input_paths, emb_paths), total=len(input_paths), desc="process files"): print(f"Open input {input_path} with {emb_path}") emb = np.load(emb_path) print("Embeddings:", len(emb)) #Load the texts if input_path.endswith(".parquet"): print("Read parquet") df = pd.read_parquet(input_path) texts = [t.strip() for t in df['text']] elif input_path.endswith(".jsonl") or input_path.endswith(".jsonl.gz"): texts = [] with smart_open.open(input_path, "rt") as fIn: for line in fIn: texts.append(json.loads(line)['text'].strip()) elif input_path.endswith(".zst"): texts = [] with IndexedZstdFile(input_path) as fIn: for line in fIn: texts.append(json.loads(line)['text'].strip()) else: raise ValueError("Unknown input format") assert len(texts) == len(emb) #Add embeddings to the embeddings DB for idx in tqdm.trange(len(texts), desc="add to rdict"): emb_id = hashlib.md5(texts[idx].encode()).digest() if emb_id not in existing_keys: emb_db[emb_id] = emb[idx] existing_keys.add(emb_id) print("DONE")