Update utils/sector_classifier.py
Browse files- utils/sector_classifier.py +107 -108
utils/sector_classifier.py
CHANGED
|
@@ -1,108 +1,107 @@
|
|
| 1 |
-
from haystack.schema import Document
|
| 2 |
-
from typing import List, Tuple
|
| 3 |
-
from typing_extensions import Literal
|
| 4 |
-
import logging
|
| 5 |
-
import pandas as pd
|
| 6 |
-
from pandas import DataFrame, Series
|
| 7 |
-
from utils.config import getconfig
|
| 8 |
-
from utils.preprocessing import processingpipeline
|
| 9 |
-
import streamlit as st
|
| 10 |
-
from
|
| 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 |
-
haystack_doc['
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
truth_df =
|
| 98 |
-
truth_df = truth_df.
|
| 99 |
-
truth_df = truth_df.astype(
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
return df
|
|
|
|
| 1 |
+
from haystack.schema import Document
|
| 2 |
+
from typing import List, Tuple
|
| 3 |
+
from typing_extensions import Literal
|
| 4 |
+
import logging
|
| 5 |
+
import pandas as pd
|
| 6 |
+
from pandas import DataFrame, Series
|
| 7 |
+
from utils.config import getconfig
|
| 8 |
+
from utils.preprocessing import processingpipeline
|
| 9 |
+
import streamlit as st
|
| 10 |
+
from transformers import pipeline
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
@st.cache_resource
|
| 14 |
+
def load_sectorClassifier(config_file:str = None, classifier_name:str = None):
|
| 15 |
+
"""
|
| 16 |
+
loads the document classifier using haystack, where the name/path of model
|
| 17 |
+
in HF-hub as string is used to fetch the model object.Either configfile or
|
| 18 |
+
model should be passed.
|
| 19 |
+
1. https://docs.haystack.deepset.ai/reference/document-classifier-api
|
| 20 |
+
2. https://docs.haystack.deepset.ai/docs/document_classifier
|
| 21 |
+
Params
|
| 22 |
+
--------
|
| 23 |
+
config_file: config file path from which to read the model name
|
| 24 |
+
classifier_name: if modelname is passed, it takes a priority if not \
|
| 25 |
+
found then will look for configfile, else raise error.
|
| 26 |
+
Return: document classifier model
|
| 27 |
+
"""
|
| 28 |
+
if not classifier_name:
|
| 29 |
+
if not config_file:
|
| 30 |
+
logging.warning("Pass either model name or config file")
|
| 31 |
+
return
|
| 32 |
+
else:
|
| 33 |
+
config = getconfig(config_file)
|
| 34 |
+
classifier_name = config.get('sector','MODEL')
|
| 35 |
+
|
| 36 |
+
logging.info("Loading sector classifier")
|
| 37 |
+
# we are using the pipeline as the model is multilabel and DocumentClassifier
|
| 38 |
+
# from Haystack doesnt support multilabel
|
| 39 |
+
# in pipeline we use 'sigmoid' to explicitly tell pipeline to make it multilabel
|
| 40 |
+
# if not then it will automatically use softmax, which is not a desired thing.
|
| 41 |
+
# doc_classifier = TransformersDocumentClassifier(
|
| 42 |
+
# model_name_or_path=classifier_name,
|
| 43 |
+
# task="text-classification",
|
| 44 |
+
# top_k = None)
|
| 45 |
+
|
| 46 |
+
doc_classifier = pipeline("text-classification",
|
| 47 |
+
model=classifier_name,
|
| 48 |
+
return_all_scores=True,
|
| 49 |
+
function_to_apply= "sigmoid")
|
| 50 |
+
|
| 51 |
+
return doc_classifier
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
@st.cache_data
|
| 55 |
+
def sector_classification(haystack_doc:pd.DataFrame,
|
| 56 |
+
threshold:float = 0.5,
|
| 57 |
+
classifier_model:pipeline= None
|
| 58 |
+
)->Tuple[DataFrame,Series]:
|
| 59 |
+
"""
|
| 60 |
+
Text-Classification on the list of texts provided. Classifier provides the
|
| 61 |
+
most appropriate label for each text. these labels are in terms of if text
|
| 62 |
+
belongs to which particular Sustainable Devleopment Goal (SDG).
|
| 63 |
+
Params
|
| 64 |
+
---------
|
| 65 |
+
haystack_doc: List of haystack Documents. The output of Preprocessing Pipeline
|
| 66 |
+
contains the list of paragraphs in different format,here the list of
|
| 67 |
+
Haystack Documents is used.
|
| 68 |
+
threshold: threshold value for the model to keep the results from classifier
|
| 69 |
+
classifiermodel: you can pass the classifier model directly,which takes priority
|
| 70 |
+
however if not then looks for model in streamlit session.
|
| 71 |
+
In case of streamlit avoid passing the model directly.
|
| 72 |
+
Returns
|
| 73 |
+
----------
|
| 74 |
+
df: Dataframe with two columns['SDG:int', 'text']
|
| 75 |
+
x: Series object with the unique SDG covered in the document uploaded and
|
| 76 |
+
the number of times it is covered/discussed/count_of_paragraphs.
|
| 77 |
+
"""
|
| 78 |
+
logging.info("Working on Sector Identification")
|
| 79 |
+
haystack_doc['Sector Label'] = 'NA'
|
| 80 |
+
df1 = haystack_doc[haystack_doc['Target Label'] == 'TARGET']
|
| 81 |
+
df = haystack_doc[haystack_doc['Target Label'] == 'NEGATIVE']
|
| 82 |
+
if not classifier_model:
|
| 83 |
+
classifier_model = st.session_state['sector_classifier']
|
| 84 |
+
|
| 85 |
+
predictions = classifier_model(list(df1.text))
|
| 86 |
+
|
| 87 |
+
list_ = []
|
| 88 |
+
for i in range(len(predictions)):
|
| 89 |
+
|
| 90 |
+
temp = predictions[i]
|
| 91 |
+
placeholder = {}
|
| 92 |
+
for j in range(len(temp)):
|
| 93 |
+
placeholder[temp[j]['label']] = temp[j]['score']
|
| 94 |
+
list_.append(placeholder)
|
| 95 |
+
labels_ = [{**list_[l]} for l in range(len(predictions))]
|
| 96 |
+
truth_df = DataFrame.from_dict(labels_)
|
| 97 |
+
truth_df = truth_df.round(2)
|
| 98 |
+
truth_df = truth_df.astype(float) >= threshold
|
| 99 |
+
truth_df = truth_df.astype(str)
|
| 100 |
+
categories = list(truth_df.columns)
|
| 101 |
+
truth_df['Sector Label'] = truth_df.apply(lambda x: {i if x[i]=='True' else
|
| 102 |
+
None for i in categories}, axis=1)
|
| 103 |
+
truth_df['Sector Label'] = truth_df.apply(lambda x: list(x['Sector Label']
|
| 104 |
+
-{None}),axis=1)
|
| 105 |
+
df1['Sector Label'] = list(truth_df['Sector Label'])
|
| 106 |
+
df = pd.concat([df,df1])
|
| 107 |
+
return df
|
|
|