-
Notifications
You must be signed in to change notification settings - Fork 6
/
new_es_retrieval.py
145 lines (117 loc) · 4.8 KB
/
new_es_retrieval.py
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
import os
from subprocess import Popen, PIPE, STDOUT
import time
from elasticsearch import Elasticsearch
import json
import pandas as pd
from tqdm import tqdm
from haystack.document_store.elasticsearch import ElasticsearchDocumentStore
from haystack.retriever import ElasticsearchRetriever
from haystack.pipeline import DocumentSearchPipeline
from datasets import load_from_disk
def es_retrieval():
es_server = Popen(['elasticsearch-7.9.2/bin/elasticsearch'],
stdout=PIPE, stderr=STDOUT,
preexec_fn=lambda: os.setuid(1) # as daemon
)
print("wait until ES has started")
time.sleep(30)
print("end until ES has started")
es = Elasticsearch('localhost:9200')
mapping = {
'settings':{
'analysis':{
'analyzer':{
'my_analyzer':{
"type": "custom",
'tokenizer':'nori_tokenizer',
'decompound_mode':'mixed',
'stopwords':'_korean_',
"filter": ["lowercase",
"my_shingle_f",
"nori_readingform",
"nori_number"]
}
},
'filter':{
'my_shingle_f':{
"type": "shingle"
}
}
},
'similarity':{
'my_similarity':{
'type':'IB',
}
}
},
'mappings':{
'properties':{
'title':{
'type':'text',
'analyzer':'my_analyzer',
'similarity':'my_similarity'
},
'text':{
'type':'text',
'analyzer':'my_analyzer',
'similarity':'my_similarity'
}
}
}
}
print("------------document_store------------")
# Connect to Elasticsearch
document_store = ElasticsearchDocumentStore(host="localhost", username="", password="", index="document", custom_mapping=mapping)
with open('/opt/ml/data/wikipedia_documents.json', "r") as f:
wiki = json.load(f)
# contexts = list(dict.fromkeys([v['text'] for v in wiki.values()]))
contexts = list(dict.fromkeys([v["title"] + ": " + v["text"] for v in wiki.values()]))
dicts = [
{
'text': context,
#'meta': {}
} for context in tqdm(contexts)
]
# Now, let's write the docs to our DB.
document_store.write_documents(dicts)
retriever = ElasticsearchRetriever(document_store)
pipe = DocumentSearchPipeline(retriever)
testset=load_from_disk('/opt/ml/data/test_dataset')
testset=testset['validation']
total = []
print("------------save_doc------------")
for idx, example in enumerate(tqdm(testset, desc="elasticsearch: ")):
# relev_doc_ids = [el for i, el in enumerate(self.ids) if i in doc_indices[idx]]
question=example["question"]
top_k_docs = pipe.run(question, params={"retriever": {"top_k": 10}})
query = {
'query':{
'bool':{
'must':[
{'match':{'text':question}}
],
'should':[
{'match':{'text':question}}
]
}
}
}
doc = es.search(index='document',body=query,size=30)['hits']['hits']
cc = ''
for i in range(5):
cc += doc[i]['_source']['text']
tmp = {
"question": example["question"],
"id": example['id'],
"context_id": doc[0]['_id'], # retrieved id
"context": cc # retrieved doument
}
if 'context' in example.keys() and 'answers' in example.keys():
tmp["original_context"] = example['context'] # original document
tmp["answers"] = example['answers'] # original answer
total.append(tmp)
print("finish_retrieve")
cqas = pd.DataFrame(total)
cqas.to_csv('context_IB.csv')
return cqas