-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathp6_sum.py
More file actions
166 lines (130 loc) · 4.58 KB
/
Copy pathp6_sum.py
File metadata and controls
166 lines (130 loc) · 4.58 KB
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
# %%
from pathlib import Path
from typing import List
from vadis_logger import vadis_logger
from helper import save_json
from config import config
import json
import requests
from pydantic import BaseModel
from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
from schnitsum import SchnitSum
from summarizer.sbert import SBertSummarizer
import langdetect
from transformers.pipelines import pipeline
# %%
process = 'Summarization'
vadis_logger.info(f'PROCESS STARTED: {process}.')
l_lang = config['languages']
f_pub_list = Path('vadis_app_ssoar_list.json')
f_metadata = Path('metadata.json')
grobid_config_path = config['grobid']['config_path']
grobid_process_type = config['grobid']['process_type']
dir_pdf_raw = config['corpus_paths']['pdf_raw']
dir_json_raw = config['corpus_paths']['json_raw']
dir_json_text = config['corpus_paths']['json_text']
dir_filtered_json_text = config['corpus_paths']['filtered_json_text']
with open(f_metadata, 'r') as f:
d_metadata = json.load(f)
with open('d_summaries_all.json', 'r') as f:
d_pre = json.load(f)
# %%
class Texts(BaseModel):
documents: List[str]
lang2model_name = {
"en": "sobamchan/bart-large-scitldr",
"de": "sobamchan/mbart-large-xscitldr-de",
}
lang2lang_code = {
"en": "en_XX",
"de": "de_DE",
"ja": "ja_XX",
"it": "it_IT",
"zh": "zh_CN",
}
class Model:
def __init__(self, tgt_lang: str = "en", use_gpu=False):
print(f"Initializing a model in {tgt_lang}...")
# model_name = lang2model_name[tgt_lang]
model_name = lang2model_name[tgt_lang]
self.schnitsum_model = SchnitSum(model_name, tgt_lang=tgt_lang, use_gpu=use_gpu)
self.use_gpu = use_gpu
self.tgt_lang = tgt_lang
self.model_name = model_name
self.translator = None
print("loaded!")
def summarize(self, text: str) -> str:
do_translation = True if langdetect.detect(text) == "de" else False
if do_translation:
# print("German!!! Translate to English first.")
if self.translator is None:
self.translator = pipeline(model="facebook/wmt19-de-en")
text = self.translator([text])[0]["translation_text"]
# print(text)
return self.schnitsum_model([text])[0]
def summarize_batch(self, texts: List[str]) -> List[str]:
return self.schnitsum_model(texts)
# %%
model_en = Model(tgt_lang='en')
model_de = Model(tgt_lang='de')
# %%
ext_model = SBertSummarizer("all-distilroberta-v1")
# %%
# %% TRY LATER
lang = 'en'
print(f"Initializing a model in {lang}...")
model_name_en = lang2model_name[lang]
tokenizer_en = AutoTokenizer.from_pretrained(model_name_en, use_auth_token=True)
bart_en = AutoModelForSeq2SeqLM.from_pretrained(model_name_en, use_auth_token=True)
lang = 'de'
print(f"Initializing a model in {lang}...")
model_name_de = lang2model_name[lang]
tokenizer_de = AutoTokenizer.from_pretrained(model_name_de, use_auth_token=True)
bart_de = AutoModelForSeq2SeqLM.from_pretrained(model_name_de, use_auth_token=True)
# %%
'''def summarize_batch(tokenizer, bart, texts: List[str]) -> List[str]:
inputs = tokenizer(
texts, padding="max_length", truncation=True, return_tensors="pt"
)
summary_ids = bart.generate(
inputs["input_ids"],
max_length=50,
num_beams=1,
early_stopping=True,
)
return tokenizer.batch_decode(summary_ids, skip_special_tokens=True)'''
# %%
l_valid_pub_ids = [k for k, v in d_metadata.items() if 'parsed_json_raw' in v.keys() and v['parsed_json_raw']]
l_valid_pub_ids = [k for k, v in d_metadata.items() if 'all_related_research_datasets_list' in v.keys() and len(v['all_related_research_datasets_list'])>0 and 'ssoar' in k and k not in d_pre.keys()]
# %%
url_gsq = config['urls']['gesis_search_query']
d_id_bs = {}
l_abs = []
for id in l_valid_pub_ids[:]:
try:
print(id)
response = requests.post(url_gsq + id, timeout=15)
abstract = response.json()['hits']['hits'][0]['_source']['abstract']
# fulltext = response.json()['hits']['hits'][0]['_source']['fulltext']
l_abs.append(abstract)
d_id_bs[id] = abstract
except Exception as err:
vadis_logger.error(err)
print('fail')
# %%
d_id_sum = {}
model = model_en
for id, abs in d_id_bs.items():
print(d_metadata[id]['lang'])
if d_metadata[id]['lang'] == 'de':
model = model_de
else:
model = model_en
sum = {}
sum['gen_sum'] = model.summarize(abs)
sum['ext_sum'] = ext_model(abs, num_sentences=1)
d_id_sum[id] = sum
print(id)
# %%
save_json(d_id_sum, 'data/summaries_.json')
# %%