leavoigt commited on
Commit
cd7bf6b
1 Parent(s): f1e641d

Upload utils_target_classifier.py

Browse files
Files changed (1) hide show
  1. utils/utils_target_classifier.py +90 -0
utils/utils_target_classifier.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List, Tuple
2
+ from typing_extensions import Literal
3
+ import logging
4
+ import pandas as pd
5
+ from pandas import DataFrame, Series
6
+ from utils.config import getconfig
7
+ from utils.preprocessing import processingpipeline
8
+ import streamlit as st
9
+ from transformers import pipeline
10
+
11
+ ## Labels dictionary ###
12
+ _lab_dict = {
13
+ 'NEGATIVE':'NO TARGET INFO',
14
+ 'TARGET':'TARGET',
15
+ }
16
+
17
+ @st.cache_resource
18
+ def load_targetClassifier(config_file:str = None, classifier_name:str = None):
19
+ """
20
+ loads the document classifier using haystack, where the name/path of model
21
+ in HF-hub as string is used to fetch the model object.Either configfile or
22
+ model should be passed.
23
+ 1. https://docs.haystack.deepset.ai/reference/document-classifier-api
24
+ 2. https://docs.haystack.deepset.ai/docs/document_classifier
25
+ Params
26
+ --------
27
+ config_file: config file path from which to read the model name
28
+ classifier_name: if modelname is passed, it takes a priority if not \
29
+ found then will look for configfile, else raise error.
30
+ Return: document classifier model
31
+ """
32
+ if not classifier_name:
33
+ if not config_file:
34
+ logging.warning("Pass either model name or config file")
35
+ return
36
+ else:
37
+ config = getconfig(config_file)
38
+ classifier_name = config.get('target','MODEL')
39
+
40
+ logging.info("Loading classifier")
41
+
42
+ doc_classifier = pipeline("text-classification",
43
+ model=classifier_name,
44
+ top_k =1)
45
+
46
+ return doc_classifier
47
+
48
+
49
+ @st.cache_data
50
+ def target_classification(haystack_doc:pd.DataFrame,
51
+ threshold:float = 0.5,
52
+ classifier_model:pipeline= None
53
+ )->Tuple[DataFrame,Series]:
54
+ """
55
+ Text-Classification on the list of texts provided. Classifier provides the
56
+ most appropriate label for each text. these labels are in terms of if text
57
+ belongs to which particular Sustainable Devleopment Goal (SDG).
58
+ Params
59
+ ---------
60
+ haystack_doc: List of haystack Documents. The output of Preprocessing Pipeline
61
+ contains the list of paragraphs in different format,here the list of
62
+ Haystack Documents is used.
63
+ threshold: threshold value for the model to keep the results from classifier
64
+ classifiermodel: you can pass the classifier model directly,which takes priority
65
+ however if not then looks for model in streamlit session.
66
+ In case of streamlit avoid passing the model directly.
67
+ Returns
68
+ ----------
69
+ df: Dataframe with two columns['SDG:int', 'text']
70
+ x: Series object with the unique SDG covered in the document uploaded and
71
+ the number of times it is covered/discussed/count_of_paragraphs.
72
+ """
73
+ logging.info("Working on Target Extraction")
74
+ if not classifier_model:
75
+ classifier_model = st.session_state['target_classifier']
76
+
77
+ results = classifier_model(list(haystack_doc.text))
78
+ labels_= [(l[0]['label'],
79
+ l[0]['score']) for l in results]
80
+
81
+
82
+ df1 = DataFrame(labels_, columns=["Target Label","Target Score"])
83
+ df = pd.concat([haystack_doc,df1],axis=1)
84
+
85
+ df = df.sort_values(by="Target Score", ascending=False).reset_index(drop=True)
86
+ df['Target Score'] = df['Target Score'].round(2)
87
+ df.index += 1
88
+ # df['Label_def'] = df['Target Label'].apply(lambda i: _lab_dict[i])
89
+
90
+ return df