File size: 5,707 Bytes
796ec76 |
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 |
import pandas as pd
import os
import gzip
import random
import re
from tqdm import tqdm
from collections import defaultdict
def get_all_files_in_directory(directory, ext=''):
all_files = []
for root, dirs, files in os.walk(directory):
root = root[len(directory):]
if root.startswith('\\') or root.startswith('/'):
root = root[1:]
for file in files:
if file.endswith(ext):
file_path = os.path.join(root, file)
all_files.append(file_path)
return all_files
reg_q = re.compile(r'''['"“”‘’「」『』]''')
reg_e = re.compile(r'''[?!。?!]''')
def readOne(filePath):
with gzip.open(filePath, 'rt', encoding='utf-8') if filePath.endswith('.gz') else open(filePath,
encoding='utf-8') as f:
retn = []
cache = ''
for line in f:
line = reg_q.sub('', line) # 删除引号
if len(cache) + len(line) < 384:
cache += line
continue
if not bool(reg_e.findall(line)):
cache += line
retn.append(cache.strip())
cache = ''
continue
i = 1
s = 0
while i <= len(line):
if len(cache) + (i - s) < 384: # 每 384 切一行
i = (384 - len(cache)) + s
if i > len(line):
break
cache += line[s:i]
s = i
if line[i-1] in ('?', '!', '。', '?', '!'):
cache += line[s:i]
s = i
retn.append(cache.strip())
cache = ''
i += 1
if len(line) > s:
cache += line[s:]
cache = cache.strip()
if cache:
retn.append(cache)
return retn
def load_dataset(path):
df = pd.read_parquet(path, engine="pyarrow")
return df
def load_all_dataset(path, convert=False):
qrels_pd = load_dataset(path + r'\qrels.parquet')
corpus = load_dataset(path + r'\corpus.parquet')
queries = load_dataset(path + r'\queries.parquet')
if convert:
qrels = defaultdict(dict)
for i, e in tqdm(qrels_pd.iterrows(), desc="load_all_dataset: Converting"):
qrels[e['qid']][e['cid']] = e['score']
else:
qrels = qrels_pd
return corpus, queries, qrels
def save_dataset(path, df):
return df.to_parquet(
path,
engine="pyarrow",
compression="gzip",
index=False
)
def save_all_dataset(path, corpus, queries, qrels):
save_dataset(path + r"\corpus.parquet", corpus)
save_dataset(path + r"\queries.parquet", queries)
save_dataset(path + r"\qrels.parquet", qrels)
def create_dataset(corpus, queries, qrels):
corpus_pd = pd.DataFrame(corpus, columns=['cid', 'text'])
queries_pd = pd.DataFrame(queries, columns=['qid', 'text'])
qrels_pd = pd.DataFrame(qrels, columns=['qid', 'cid', 'score'])
corpus_pd['cid'] = corpus_pd['cid'].astype(str)
queries_pd['qid'] = queries_pd['qid'].astype(str)
qrels_pd['qid'] = qrels_pd['qid'].astype(str)
qrels_pd['cid'] = qrels_pd['cid'].astype(str)
qrels_pd['score'] = qrels_pd['score'].astype(int)
return corpus_pd, queries_pd, qrels_pd
def sample_from_dataset(corpus, queries, qrels, k=2000):
sample_k = sorted(random.sample(queries['qid'].to_list(), k=k))
queries_pd = queries[queries['qid'].isin(sample_k)]
qrels_pd = qrels[qrels['qid'].isin(sample_k)]
corpus_pd = corpus[corpus['cid'].isin(qrels_pd['cid'])]
return corpus_pd, queries_pd, qrels_pd
path = r'D:\datasets\v-corpus-zh'
rawcorpus = get_all_files_in_directory(path, '.txt.gz')
corpus = []
queries = []
qrels = []
for sub_path in tqdm(rawcorpus, desc="Reading all data..."):
s_sub_path = sub_path.split('\\')
会社 = s_sub_path[0]
if len(s_sub_path) == 3:
系列 = None
作品 = s_sub_path[-2]
篇章 = s_sub_path[-1]
elif len(s_sub_path) == 4:
系列 = s_sub_path[1]
作品 = s_sub_path[-2]
篇章 = s_sub_path[-1]
else:
print(s_sub_path)
raise ValueError('s_sub_path != 3 or 4')
print(会社, 系列, 作品, 篇章)
tmp = readOne(os.path.join(path, sub_path))
阈值 = max(len(tmp) // 40, 4)
print(阈值)
old_rand = None
for i in range(len(tmp)):
rand = random.randint(0, 阈值)
if rand == 0:
queries.append((会社, 系列, 作品, 篇章, i/(len(tmp)-1), tmp[i]))
elif rand <= 4 or old_rand == 0:
corpus.append((会社, 系列, 作品, 篇章, i/(len(tmp)-1), tmp[i]))
else:
pass
old_rand = rand
for qid, q in tqdm(enumerate(queries), desc="计算 qrels 中..."):
for cid, c in enumerate(corpus):
if q[0] == c[0]:
s = 1
if q[1] is not None and q[1] == c[1]:
s += 4
if q[2] == q[2]:
s += 8
if q[3] == q[3]:
s += 8
ss = 1 - abs(q[4] - c[4])
s += (79 * ss)
qrels.append((qid, cid, s))
corpus_ = [(cid, c[5]) for cid, c in enumerate(corpus)]
queries_ = [(qid, q[5]) for qid, q in enumerate(queries)]
path = r'D:\datasets\G2Retrieval'
corpus_pd, queries_pd, qrels_pd = create_dataset(corpus_, queries_, qrels)
save_all_dataset(path + r'\data', corpus_pd, queries_pd, qrels_pd)
save_all_dataset(path + r'\data_sample2k', *sample_from_dataset(corpus_pd, queries_pd, qrels_pd))
|