leavoigt commited on
Commit
1947876
·
1 Parent(s): cfcd3f8

Delete utils/keyword_extraction.py

Browse files
Files changed (1) hide show
  1. utils/keyword_extraction.py +0 -140
utils/keyword_extraction.py DELETED
@@ -1,140 +0,0 @@
1
- import pandas as pd
2
- # from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer
3
- # import nltk
4
- # nltk.download('stopwords')
5
- # from nltk.corpus import stopwords
6
- import pickle
7
- from typing import List, Text
8
- import logging
9
- from summa import keywords
10
-
11
- try:
12
- import streamlit as st
13
- except ImportError:
14
- logging.info("Streamlit not installed")
15
-
16
-
17
- def sort_coo(coo_matrix):
18
- """
19
- It takes Coordinate format scipy sparse matrix and extracts info from same.\
20
- 1. https://kavita-ganesan.com/python-keyword-extraction/#.Y2-TFHbMJPb
21
- """
22
- tuples = zip(coo_matrix.col, coo_matrix.data)
23
- return sorted(tuples, key=lambda x: (x[1], x[0]), reverse=True)
24
-
25
- def extract_topn_from_vector(feature_names, sorted_items, top_n=10):
26
- """get the feature names and tf-idf score of top n items
27
-
28
- Params
29
- ---------
30
- feature_names: list of words from vectorizer
31
- sorted_items: tuple returned by sort_coo function defined in \
32
- keyword_extraction.py
33
- topn: topn words to be extracted using tfidf
34
-
35
- Return
36
- ----------
37
- results: top extracted keywords
38
-
39
- """
40
-
41
- #use only topn items from vector
42
- sorted_items = sorted_items[:top_n]
43
- score_vals = []
44
- feature_vals = []
45
-
46
- # word index and corresponding tf-idf score
47
- for idx, score in sorted_items:
48
-
49
- #keep track of feature name and its corresponding score
50
- score_vals.append(round(score, 3))
51
- feature_vals.append(feature_names[idx])
52
-
53
- results= {}
54
- for idx in range(len(feature_vals)):
55
- results[feature_vals[idx]]=score_vals[idx]
56
-
57
- return results
58
-
59
-
60
- def tfidf_keyword(textdata:str, vectorizer, tfidfmodel, top_n):
61
- """
62
- TFIDF based keywords extraction
63
-
64
- Params
65
- ---------
66
- vectorizer: trained cont vectorizer model
67
- tfidfmodel: TFIDF Tranformer model
68
- top_n: Top N keywords to be extracted
69
- textdata: text data to which needs keyword extraction
70
-
71
- Return
72
- ----------
73
- keywords: top extracted keywords
74
-
75
- """
76
- features = vectorizer.get_feature_names_out()
77
- tf_idf_vector=tfidfmodel.transform(vectorizer.transform(textdata))
78
- sorted_items=sort_coo(tf_idf_vector.tocoo())
79
- results=extract_topn_from_vector(features,sorted_items,top_n)
80
- keywords = [keyword for keyword in results]
81
- return keywords
82
-
83
- def keyword_extraction(sdg:int,sdgdata:List[Text], top_n:int=10):
84
- """
85
- TFIDF based keywords extraction
86
-
87
- Params
88
- ---------
89
- sdg: which sdg tfidf model to be used
90
- sdgdata: text data to which needs keyword extraction
91
-
92
-
93
- Return
94
- ----------
95
- keywords: top extracted keywords
96
-
97
- """
98
- model_path = "docStore/sdg{}/".format(sdg)
99
- vectorizer = pickle.load(open(model_path+'vectorizer.pkl', 'rb'))
100
- tfidfmodel = pickle.load(open(model_path+'tfidfmodel.pkl', 'rb'))
101
- features = vectorizer.get_feature_names_out()
102
- tf_idf_vector=tfidfmodel.transform(vectorizer.transform(sdgdata))
103
- sorted_items=sort_coo(tf_idf_vector.tocoo())
104
- top_n = top_n
105
- results=extract_topn_from_vector(features,sorted_items,top_n)
106
- keywords = [keyword for keyword in results]
107
- return keywords
108
-
109
- @st.cache(allow_output_mutation=True)
110
- def textrank(textdata:Text, ratio:float = 0.1, words:int = 0)->List[str]:
111
- """
112
- wrappper function to perform textrank, uses either ratio or wordcount to
113
- extract top keywords limited by words or ratio.
114
- 1. https://github.com/summanlp/textrank/blob/master/summa/keywords.py
115
-
116
- Params
117
- --------
118
- textdata: text data to perform the textrank.
119
- ratio: float to limit the number of keywords as proportion of total token \
120
- in textdata
121
- words: number of keywords to be extracted. Takes priority over ratio if \
122
- Non zero. Howevr incase the pagerank returns lesser keywords than \
123
- compared to fix value then ratio is used.
124
-
125
- Return
126
- --------
127
- results: extracted keywords
128
- """
129
- if words == 0:
130
- logging.info("Textrank using defulat ratio value = 0.1, as no words limit given")
131
- results = keywords.keywords(textdata, ratio= ratio).split("\n")
132
- else:
133
- try:
134
- results = keywords.keywords(textdata, words= words).split("\n")
135
- except:
136
- results = keywords.keywords(textdata, ratio = ratio).split("\n")
137
-
138
- return results
139
-
140
-