Spaces:
Sleeping
Sleeping
Comment out added enhanced_ner part
Browse files- keyword_extraction.py +132 -132
keyword_extraction.py
CHANGED
@@ -1,133 +1,133 @@
|
|
1 |
-
from nltk.corpus import stopwords
|
2 |
-
from rake_nltk import Rake
|
3 |
-
from sklearn.feature_extraction.text import TfidfVectorizer
|
4 |
-
import spacy
|
5 |
-
from transformers import pipeline
|
6 |
-
from gliner import GLiNER
|
7 |
-
from load_models import load_nlp_models
|
8 |
-
|
9 |
-
nlp, s2v = load_nlp_models()
|
10 |
-
|
11 |
-
def filter_keywords(extracted_keywords):
|
12 |
-
unwanted_keywords =[
|
13 |
-
# Common punctuation marks
|
14 |
-
'.', ',', '!', '?', ':', ';', '-', '_', '(', ')', '[', ']', '{', '}',
|
15 |
-
'/', '\\', '|', '@', '#', '$', '%', '^', '&', '*', '+', '=', '<', '>',
|
16 |
-
'`', '~', '"', "'",
|
17 |
-
|
18 |
-
# Common contractions (if not already removed as stopwords)
|
19 |
-
"n't", "'s", "'m", "'re", "'ll", "'ve", "'d",
|
20 |
-
|
21 |
-
# Common abbreviations
|
22 |
-
'etc', 'eg', 'ie', 'ex', 'vs', 'viz',
|
23 |
-
|
24 |
-
'tbd', 'tba', # To be determined/announced
|
25 |
-
'na', 'n/a', # Not applicable
|
26 |
-
|
27 |
-
# Single characters
|
28 |
-
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
|
29 |
-
|
30 |
-
# HTML-related tags (if the text contains any HTML content)
|
31 |
-
'<html>', '</html>', '<body>', '</body>', '<head>', '</head>', '<div>', '</div>', '<p>', '</p>', '<br>', '<hr>', '<h1>', '</h1>', '<h2>', '</h2>', '<h3>', '</h3>',
|
32 |
-
|
33 |
-
# Random technical or common abbreviations that aren't meaningful keywords
|
34 |
-
'etc', 'e.g', 'i.e', 'vs', 'ex', 'vol', 'sec', 'pg', 'id', 'ref', 'eq',
|
35 |
-
|
36 |
-
# Miscellaneous tokens
|
37 |
-
'www', 'com', 'http', 'https', 'ftp', 'pdf', 'doc', 'img', 'gif', 'jpeg', 'jpg', 'png', 'mp4', 'mp3', 'org', 'net', 'edu',
|
38 |
-
'untitled', 'noname', 'unknown', 'undefined',
|
39 |
-
|
40 |
-
# Single letters commonly used in bullet points or references
|
41 |
-
'i', 'ii', 'iii', 'iv', 'v', 'vi', 'vii', 'viii', 'ix', 'x', 'xi', 'xii',
|
42 |
-
|
43 |
-
# Common file extensions (if filenames are included in the text)
|
44 |
-
'.jpg', '.png', '.pdf', '.doc', '.docx', '.ppt', '.pptx', '.xls', '.xlsx', '.csv', '.txt', '.zip', '.tar', '.gz', '.exe', '.bat', '.sh', '.py', '.cpp', '.java',
|
45 |
-
|
46 |
-
# Other tokens related to formatting or structure
|
47 |
-
'chapter', 'section', 'figure', 'table', 'appendix',
|
48 |
-
|
49 |
-
# Miscellaneous general noise terms
|
50 |
-
'note', 'item', 'items', 'number', 'numbers', 'figure', 'case', 'cases', 'example', 'examples', 'type', 'types', 'section', 'part', 'parts'
|
51 |
-
]
|
52 |
-
# Convert both lists to sets for efficient lookup
|
53 |
-
extracted_set = set(extracted_keywords)
|
54 |
-
unwanted_set = set(unwanted_keywords)
|
55 |
-
|
56 |
-
# Remove unwanted keywords
|
57 |
-
filtered_keywords = extracted_set - unwanted_set
|
58 |
-
|
59 |
-
# Convert back to a list and sort (optional)
|
60 |
-
return sorted(list(filtered_keywords))
|
61 |
-
|
62 |
-
|
63 |
-
def remove_stopwords(keywords):
|
64 |
-
stop_words = set(stopwords.words('english'))
|
65 |
-
modified_keywords = [''.join(keyword.split()) for keyword in keywords]
|
66 |
-
filtered_keywords = [keyword for keyword in modified_keywords if keyword.lower() not in stop_words]
|
67 |
-
original_keywords = []
|
68 |
-
for keyword in filtered_keywords:
|
69 |
-
for original_keyword in keywords:
|
70 |
-
if ''.join(original_keyword.split()).lower() == keyword.lower():
|
71 |
-
original_keywords.append(original_keyword)
|
72 |
-
break
|
73 |
-
return original_keywords
|
74 |
-
|
75 |
-
def enhanced_ner(text):
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
def extract_keywords(text, extract_all):
|
86 |
-
try:
|
87 |
-
text = text.lower()
|
88 |
-
enhanced_ner_entities = enhanced_ner(text)
|
89 |
-
print("Enhanced ner entities: ",enhanced_ner_entities)
|
90 |
-
enhanced_ner_entities = remove_stopwords(enhanced_ner_entities)
|
91 |
-
enhanced_ner_entities = filter_keywords(enhanced_ner_entities)
|
92 |
-
print("Enhanced ner entities after applying filter and stopwords removal: ",enhanced_ner_entities)
|
93 |
-
|
94 |
-
gliner_model = GLiNER.from_pretrained("knowledgator/gliner-multitask-large-v0.5")
|
95 |
-
labels = ["person", "organization", "phone number", "address", "email", "date of birth",
|
96 |
-
"mobile phone number", "medication", "ip address", "email address",
|
97 |
-
"landline phone number", "blood type", "digital signature", "postal code",
|
98 |
-
"date"]
|
99 |
-
entities = gliner_model.predict_entities(text, labels, threshold=0.5)
|
100 |
-
|
101 |
-
gliner_keywords = set(remove_stopwords([ent["text"] for ent in entities]))
|
102 |
-
print(f"Gliner keywords:{gliner_keywords}")
|
103 |
-
|
104 |
-
# if extract_all is False:
|
105 |
-
# return list(gliner_keywords)
|
106 |
-
|
107 |
-
doc = nlp(text)
|
108 |
-
spacy_keywords = set(remove_stopwords([ent.text for ent in doc.ents]))
|
109 |
-
print(f"\n\nSpacy Entities: {spacy_keywords} \n\n")
|
110 |
-
|
111 |
-
if extract_all is False:
|
112 |
-
combined_keywords_without_all = list(spacy_keywords.union(gliner_keywords).union(enhanced_ner_entities))
|
113 |
-
filtered_results = filter_keywords(combined_keywords_without_all)
|
114 |
-
print("Keywords returned: ",filtered_results)
|
115 |
-
return list(filtered_results)
|
116 |
-
|
117 |
-
rake = Rake()
|
118 |
-
rake.extract_keywords_from_text(text)
|
119 |
-
rake_keywords = set(remove_stopwords(rake.get_ranked_phrases()))
|
120 |
-
print(f"\n\nRake Keywords: {rake_keywords} \n\n")
|
121 |
-
|
122 |
-
vectorizer = TfidfVectorizer(stop_words='english')
|
123 |
-
X = vectorizer.fit_transform([text])
|
124 |
-
tfidf_keywords = set(remove_stopwords(vectorizer.get_feature_names_out()))
|
125 |
-
print(f"\n\nTFIDF Entities: {tfidf_keywords} \n\n")
|
126 |
-
|
127 |
-
combined_keywords = list(rake_keywords.union(spacy_keywords).union(tfidf_keywords).union(gliner_keywords))
|
128 |
-
filtered_results = filter_keywords(combined_keywords)
|
129 |
-
print("Keywords returned: ",filtered_results)
|
130 |
-
return list(filtered_results)
|
131 |
-
|
132 |
-
except Exception as e:
|
133 |
raise Exception(f"Error in keyword extraction: {str(e)}")
|
|
|
1 |
+
from nltk.corpus import stopwords
|
2 |
+
from rake_nltk import Rake
|
3 |
+
from sklearn.feature_extraction.text import TfidfVectorizer
|
4 |
+
import spacy
|
5 |
+
from transformers import pipeline
|
6 |
+
from gliner import GLiNER
|
7 |
+
from load_models import load_nlp_models
|
8 |
+
|
9 |
+
nlp, s2v = load_nlp_models()
|
10 |
+
|
11 |
+
def filter_keywords(extracted_keywords):
|
12 |
+
unwanted_keywords =[
|
13 |
+
# Common punctuation marks
|
14 |
+
'.', ',', '!', '?', ':', ';', '-', '_', '(', ')', '[', ']', '{', '}',
|
15 |
+
'/', '\\', '|', '@', '#', '$', '%', '^', '&', '*', '+', '=', '<', '>',
|
16 |
+
'`', '~', '"', "'",
|
17 |
+
|
18 |
+
# Common contractions (if not already removed as stopwords)
|
19 |
+
"n't", "'s", "'m", "'re", "'ll", "'ve", "'d",
|
20 |
+
|
21 |
+
# Common abbreviations
|
22 |
+
'etc', 'eg', 'ie', 'ex', 'vs', 'viz',
|
23 |
+
|
24 |
+
'tbd', 'tba', # To be determined/announced
|
25 |
+
'na', 'n/a', # Not applicable
|
26 |
+
|
27 |
+
# Single characters
|
28 |
+
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
|
29 |
+
|
30 |
+
# HTML-related tags (if the text contains any HTML content)
|
31 |
+
'<html>', '</html>', '<body>', '</body>', '<head>', '</head>', '<div>', '</div>', '<p>', '</p>', '<br>', '<hr>', '<h1>', '</h1>', '<h2>', '</h2>', '<h3>', '</h3>',
|
32 |
+
|
33 |
+
# Random technical or common abbreviations that aren't meaningful keywords
|
34 |
+
'etc', 'e.g', 'i.e', 'vs', 'ex', 'vol', 'sec', 'pg', 'id', 'ref', 'eq',
|
35 |
+
|
36 |
+
# Miscellaneous tokens
|
37 |
+
'www', 'com', 'http', 'https', 'ftp', 'pdf', 'doc', 'img', 'gif', 'jpeg', 'jpg', 'png', 'mp4', 'mp3', 'org', 'net', 'edu',
|
38 |
+
'untitled', 'noname', 'unknown', 'undefined',
|
39 |
+
|
40 |
+
# Single letters commonly used in bullet points or references
|
41 |
+
'i', 'ii', 'iii', 'iv', 'v', 'vi', 'vii', 'viii', 'ix', 'x', 'xi', 'xii',
|
42 |
+
|
43 |
+
# Common file extensions (if filenames are included in the text)
|
44 |
+
'.jpg', '.png', '.pdf', '.doc', '.docx', '.ppt', '.pptx', '.xls', '.xlsx', '.csv', '.txt', '.zip', '.tar', '.gz', '.exe', '.bat', '.sh', '.py', '.cpp', '.java',
|
45 |
+
|
46 |
+
# Other tokens related to formatting or structure
|
47 |
+
'chapter', 'section', 'figure', 'table', 'appendix',
|
48 |
+
|
49 |
+
# Miscellaneous general noise terms
|
50 |
+
'note', 'item', 'items', 'number', 'numbers', 'figure', 'case', 'cases', 'example', 'examples', 'type', 'types', 'section', 'part', 'parts'
|
51 |
+
]
|
52 |
+
# Convert both lists to sets for efficient lookup
|
53 |
+
extracted_set = set(extracted_keywords)
|
54 |
+
unwanted_set = set(unwanted_keywords)
|
55 |
+
|
56 |
+
# Remove unwanted keywords
|
57 |
+
filtered_keywords = extracted_set - unwanted_set
|
58 |
+
|
59 |
+
# Convert back to a list and sort (optional)
|
60 |
+
return sorted(list(filtered_keywords))
|
61 |
+
|
62 |
+
|
63 |
+
def remove_stopwords(keywords):
|
64 |
+
stop_words = set(stopwords.words('english'))
|
65 |
+
modified_keywords = [''.join(keyword.split()) for keyword in keywords]
|
66 |
+
filtered_keywords = [keyword for keyword in modified_keywords if keyword.lower() not in stop_words]
|
67 |
+
original_keywords = []
|
68 |
+
for keyword in filtered_keywords:
|
69 |
+
for original_keyword in keywords:
|
70 |
+
if ''.join(original_keyword.split()).lower() == keyword.lower():
|
71 |
+
original_keywords.append(original_keyword)
|
72 |
+
break
|
73 |
+
return original_keywords
|
74 |
+
|
75 |
+
# def enhanced_ner(text):
|
76 |
+
# nlp = spacy.load("en_core_web_trf")
|
77 |
+
# ner_pipeline = pipeline("ner", model="dbmdz/bert-large-cased-finetuned-conll03-english")
|
78 |
+
# doc = nlp(text)
|
79 |
+
# spacy_entities = set((ent.text, ent.label_) for ent in doc.ents)
|
80 |
+
# hf_entities = set((ent['word'], ent['entity']) for ent in ner_pipeline(text))
|
81 |
+
# combined_entities = spacy_entities.union(hf_entities)
|
82 |
+
# keywords = [entity[0] for entity in combined_entities]
|
83 |
+
# return list(keywords)
|
84 |
+
|
85 |
+
def extract_keywords(text, extract_all):
|
86 |
+
try:
|
87 |
+
text = text.lower()
|
88 |
+
# enhanced_ner_entities = enhanced_ner(text)
|
89 |
+
# print("Enhanced ner entities: ",enhanced_ner_entities)
|
90 |
+
# enhanced_ner_entities = remove_stopwords(enhanced_ner_entities)
|
91 |
+
# enhanced_ner_entities = filter_keywords(enhanced_ner_entities)
|
92 |
+
# print("Enhanced ner entities after applying filter and stopwords removal: ",enhanced_ner_entities)
|
93 |
+
|
94 |
+
gliner_model = GLiNER.from_pretrained("knowledgator/gliner-multitask-large-v0.5")
|
95 |
+
labels = ["person", "organization", "phone number", "address", "email", "date of birth",
|
96 |
+
"mobile phone number", "medication", "ip address", "email address",
|
97 |
+
"landline phone number", "blood type", "digital signature", "postal code",
|
98 |
+
"date"]
|
99 |
+
entities = gliner_model.predict_entities(text, labels, threshold=0.5)
|
100 |
+
|
101 |
+
gliner_keywords = set(remove_stopwords([ent["text"] for ent in entities]))
|
102 |
+
print(f"Gliner keywords:{gliner_keywords}")
|
103 |
+
|
104 |
+
# if extract_all is False:
|
105 |
+
# return list(gliner_keywords)
|
106 |
+
|
107 |
+
doc = nlp(text)
|
108 |
+
spacy_keywords = set(remove_stopwords([ent.text for ent in doc.ents]))
|
109 |
+
print(f"\n\nSpacy Entities: {spacy_keywords} \n\n")
|
110 |
+
|
111 |
+
if extract_all is False:
|
112 |
+
combined_keywords_without_all = list(spacy_keywords.union(gliner_keywords).union(enhanced_ner_entities))
|
113 |
+
filtered_results = filter_keywords(combined_keywords_without_all)
|
114 |
+
print("Keywords returned: ",filtered_results)
|
115 |
+
return list(filtered_results)
|
116 |
+
|
117 |
+
rake = Rake()
|
118 |
+
rake.extract_keywords_from_text(text)
|
119 |
+
rake_keywords = set(remove_stopwords(rake.get_ranked_phrases()))
|
120 |
+
print(f"\n\nRake Keywords: {rake_keywords} \n\n")
|
121 |
+
|
122 |
+
vectorizer = TfidfVectorizer(stop_words='english')
|
123 |
+
X = vectorizer.fit_transform([text])
|
124 |
+
tfidf_keywords = set(remove_stopwords(vectorizer.get_feature_names_out()))
|
125 |
+
print(f"\n\nTFIDF Entities: {tfidf_keywords} \n\n")
|
126 |
+
|
127 |
+
combined_keywords = list(rake_keywords.union(spacy_keywords).union(tfidf_keywords).union(gliner_keywords))
|
128 |
+
filtered_results = filter_keywords(combined_keywords)
|
129 |
+
print("Keywords returned: ",filtered_results)
|
130 |
+
return list(filtered_results)
|
131 |
+
|
132 |
+
except Exception as e:
|
133 |
raise Exception(f"Error in keyword extraction: {str(e)}")
|