-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkeywords_pipe.py
158 lines (117 loc) · 4.92 KB
/
keywords_pipe.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
146
147
148
149
150
151
152
153
154
155
from keybert import KeyBERT
from sklearn.feature_extraction.text import TfidfVectorizer
import numpy as np
import spacy
import keyword_spacy
import json
import os
import re
import argparse
from llm_test import get_key_llm, get_model_and_tokenizer, get_key_stage2_llm
from keywords_filter import filter_file
from tqdm import tqdm
import glob
def get_keywords_tfidf(text: str):
vectorizer = TfidfVectorizer(ngram_range=(1, 2))
tfidf_matrix = vectorizer.fit_transform([text])
feature_names = vectorizer.get_feature_names_out()
tfidf_array = tfidf_matrix.toarray()
avg_tfidf_values = np.mean(tfidf_array, axis=0)
tfidf_dict = dict(zip(feature_names, avg_tfidf_values))
sorted_tfidf_dict = dict(
sorted(tfidf_dict.items(), key=lambda x: x[1], reverse=True)
)
lowest_tfidf_words = list(sorted_tfidf_dict.keys())
return lowest_tfidf_words
def get_keywords_spacy(text: str, nlp_spacy):
nlp_spacy.add_pipe(
"keyword_extractor",
last=True,
config={"top_n": 11, "min_ngram": 1, "max_ngram": 2},
)
doc = nlp_spacy(text.lower())
keywords = [d[0] for d in doc._.keywords]
for sent in doc.sents:
keywords.extend([d[0] for d in sent._.sent_keywords])
return keywords
def get_keywords(
text: str,
lecture_name: str,
keywords_folder: str,
modes=["llm", "keybert", "tfidf", "spacy"],
all_paths={"llm": "./model_path", "keybert": "all-MiniLM-L6-v2"},
gen_description=True,
) -> list:
all_key_words = []
# clean text
nlp_spacy = spacy.load("ru_core_news_sm") # should be downloaded first?
raw_text = text
text = re.sub(r"[^\w\s]", "", text)
text = " ".join([w.text for w in nlp_spacy(text.lower()) if not w.is_stop])
if "llm" in modes:
print("Start processing LLM keywords")
print(keywords_folder)
llm_keywords_file = os.path.join(
keywords_folder, lecture_name + "_llm" + ".json"
)
print(llm_keywords_file)
if os.path.exists(llm_keywords_file):
with open(llm_keywords_file, encoding='utf-8') as f:
keywords = json.load(f)
else:
# load model every time (?)
model_llm, tokenizer_llm, device = get_model_and_tokenizer()
keywords, description = get_key_llm({'text': raw_text}, model_llm, tokenizer_llm, device, lecture_name, gen_description=gen_description)
del model_llm, tokenizer_llm, device
all_key_words.extend(keywords)
# keybert
if "keybert" in modes:
print("Start processing KeyBert keywords")
kw_model = KeyBERT(model="all-MiniLM-L6-v2")
keywords = kw_model.extract_keywords(
text, keyphrase_ngram_range=(1, 2), use_mmr=True, nr_candidates=10, top_n=10
)
keywords = [w[0] for w in keywords]
all_key_words.extend(keywords)
# tfidf
if "tfidf" in modes:
print("Start processing TfIdf keywords")
keywords = get_keywords_tfidf(text)[:20]
all_key_words.extend(keywords)
# spacy
if "spacy" in modes:
print("Start processing Spacy keywords")
keywords = get_keywords_spacy(text, nlp_spacy)
all_key_words.extend(keywords)
if description is not None:
return all_key_words, description
else:
return all_key_words
def parse_files(files_folder: str, save_dir: str):
for f_path in tqdm(glob.iglob(f"{files_folder}/*.json")):
with open(f_path, encoding='utf-8') as f:
text = json.load(f)["text"]
file_name = f_path.split("/")[-1]
file_name = file_name.split("\\")[-1]
print(file_name)
# win
if os.path.exists('data/textfiles/keywords/'):
filepath = 'data/textfiles/keywords/'
# mac
else:
filepath = './data/textfiles/keywords/'
lecture_keywords = get_keywords(text, file_name[:-5], filepath)
with open(os.path.join(save_dir, file_name), 'w', encoding='utf-8') as jsf:
lecture_keywords = list(set([d.strip() for d in lecture_keywords if len(d) > 2]))
json.dump(lecture_keywords, jsf, ensure_ascii=False, indent=4)
keywords_filtered, english_words = filter_file(f'./data/textfiles/raw/{file_name}',
f'./data/textfiles/keywords/{file_name}', '')
with open(os.path.join(save_dir, f'{file_name[:-5]}_final_keywords.json'), 'w', encoding='utf-8') as jsf:
model_llm, tokenizer_llm, device = get_model_and_tokenizer()
final_keywords = get_key_stage2_llm(keywords_filtered, {'text': text}, model_llm, tokenizer_llm, device, file_name)
final_keywords = [w.capitalize() for w in final_keywords]
del model_llm, tokenizer_llm, device
json.dump(final_keywords, jsf, ensure_ascii=False, indent=4)
if __name__ == "__main__":
parse_files('./data/textfiles/raw',
'./data/textfiles/keywords')