pcs-annotator 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,40 @@
1
+ from LLM import LLM
2
+ from Tools import *
3
+
4
+ class Annotator(LLM):
5
+ def __init__(self, prompt, labels, model_name="llama3-8b-8192"):
6
+ super().__init__(model_name)
7
+
8
+ self.prompt = prompt
9
+ self.labels = labels
10
+
11
+ def truncate_to_5000_words(self, text):
12
+ try:
13
+ cleaned_text = ' '.join(text.split())
14
+ words = cleaned_text.split()
15
+ return ' '.join(words[:5000]) if len(words) > 5000 else cleaned_text
16
+
17
+ except Exception as e:
18
+ return ''
19
+ def annotate(self, text):
20
+ text = self.truncate_to_5000_words(text)
21
+ input_prompt = [
22
+ {"role": "user", "content": self.prompt},
23
+ {"role": "user", "content": text},
24
+ ]
25
+
26
+ try:
27
+ ans = self.llm.invoke(input_prompt)
28
+ ans = trim_text(ans)
29
+
30
+ label = extract_label(ans, labels=self.labels)
31
+ if label:
32
+ reasoning = extract_reasoning(ans)
33
+ return label, reasoning
34
+
35
+ return label, None
36
+
37
+ except Exception as e:
38
+
39
+ print(f"Error querying model: {e}")
40
+ return None, None
pcs_annotator/LLM.py ADDED
@@ -0,0 +1,74 @@
1
+ import os
2
+ from dotenv import load_dotenv
3
+ from langchain_groq import ChatGroq
4
+ from langchain_core.output_parsers import StrOutputParser
5
+ from langchain_openai import ChatOpenAI
6
+ from langchain_anthropic import ChatAnthropic
7
+ # from langchain_huggingface import HuggingFaceEndpoint
8
+ from huggingface_hub import InferenceClient # Use InferenceClient instead of HuggingFaceEndpoint
9
+ from langchain_huggingface import HuggingFaceEndpoint
10
+
11
+ # from langchain_huggingface import HuggingFacePipeline
12
+
13
+
14
+ class LLM:
15
+ def __init__(self, model_name):
16
+ load_dotenv()
17
+ self.model_name = model_name
18
+ self.llm = self._initialize_model()
19
+ parser = StrOutputParser()
20
+ self.llm = self.llm | parser
21
+
22
+ def _initialize_model(self):
23
+ """
24
+ Initialize the appropriate LLM model based on the model_name.
25
+ """
26
+ if self.model_name.startswith("llama"): # e.g., llama-3.1-8b-instant
27
+ key = os.getenv('GROQ_API_KEY')
28
+ if not key:
29
+ raise ValueError("Missing GROQ_API_KEY in environment variables.")
30
+ model = ChatGroq(api_key=key, model_name=self.model_name, temperature=0.1)
31
+
32
+ elif self.model_name.startswith("gpt"): # e.g., gpt-4
33
+ key = os.getenv('OPENAI_API_KEY')
34
+ if not key:
35
+ raise ValueError("Missing OPENAI_API_KEY in environment variables.")
36
+ model = ChatOpenAI(api_key=key, model=self.model_name, temperature=0.1)
37
+
38
+ elif self.model_name.startswith("claude"): # e.g., claude-3-5-sonnet-20241022
39
+ key = os.getenv('ANTHROPIC_API_KEY')
40
+ if not key:
41
+ raise ValueError("Missing ANTHROPIC_API_KEY in environment variables.")
42
+ model = ChatAnthropic(api_key=key, model=self.model_name, temperature=0.1)
43
+
44
+ elif self.model_name.startswith("mistral"): # e.g., mistralai/Mistral-7B-Instruct-v0.3
45
+ key = os.getenv('HUGGINGFACE_API_KEY')
46
+
47
+ if not key:
48
+ raise ValueError("Missing HUGGINGFACE_API_KEY in environment variables.")
49
+
50
+ model = HuggingFaceEndpoint(
51
+ repo_id="mistralai/Mistral-7B-Instruct-v0.3",
52
+ task="text-generation",
53
+ temperature=0.1,
54
+ huggingfacehub_api_token=key,
55
+ )
56
+
57
+
58
+
59
+ elif self.model_name.startswith("google"): # e.g., gemma-2-9b-it
60
+ key = os.getenv('HUGGINGFACE_API_KEY')
61
+ if not key:
62
+ raise ValueError("Missing HUGGINGFACE_API_KEY in environment variables.")
63
+
64
+ model = HuggingFaceEndpoint(
65
+ repo_id="google/gemma-2-9b-it",
66
+ task="text-generation",
67
+ temperature=0.1,
68
+ huggingfacehub_api_token=key,
69
+ )
70
+
71
+ else:
72
+ raise ValueError(f"Unsupported model name: {self.model_name}")
73
+
74
+ return model
pcs_annotator/PCS.py ADDED
@@ -0,0 +1,212 @@
1
+ from TextMutator import TextMutator
2
+ from Annotator import Annotator
3
+ import pandas as pd
4
+ import os
5
+ import numpy as np
6
+ from scipy.optimize import differential_evolution
7
+ from tqdm import tqdm
8
+
9
+
10
+
11
+ class PCS:
12
+ def __init__(self, prompt, dataset_path, annotators=["llama3-8b-8192", "mistralai/Mistral-7B-Instruct-v0.3", "google/gemma-2-9b-it"]):
13
+ self.prompt=prompt
14
+ if os.path.exists(dataset_path):
15
+ self.dataset_path = dataset_path
16
+ else:
17
+ raise FileNotFoundError(f"Invalid dataset path {dataset_path}")
18
+ self.annotator_model_names = annotators
19
+ self.annotators = []
20
+ self.textMutator = TextMutator()
21
+
22
+ self.annotations_filename = self.dataset_path.rsplit(".csv", 1)[0] + "_annotations.csv"
23
+ self.dataset = pd.read_csv(dataset_path)
24
+ self.possible_labels = self.dataset["label"].unique().tolist()
25
+ for annotator_model_name in self.annotator_model_names:
26
+ self.annotators.append(Annotator(prompt=self.prompt, labels=self.possible_labels, model_name=annotator_model_name))
27
+ self.optimal_llm_weights = [1] * len(self.annotators)
28
+ self.optimal_mr_weights = [1] * 4
29
+ self.optimal_label_thresholds = [0.5] * len(self.possible_labels)
30
+
31
+ print("Labelling the dataset...")
32
+ self.create_annotations()
33
+ print("Generated the dataset annotations.")
34
+
35
+ print("Optimizing weights...")
36
+ self.PDE()
37
+ print("Done Optimizing weights.")
38
+
39
+ def create_annotations(self):
40
+ csv_filename = self.annotations_filename
41
+
42
+ if os.path.exists(csv_filename):
43
+ # Read the existing dataset
44
+ existing_df = pd.read_csv(csv_filename)
45
+ if not existing_df.empty:
46
+ last_index = existing_df.index[-1] + 1 # Get last index and continue from there
47
+ else:
48
+ last_index = 0
49
+ else:
50
+ columns = ["label", "text", "text_mr1", "text_mr2", "text_mr3"]
51
+ for annotator in self.annotators:
52
+ columns.append(annotator.model_name+"_text")
53
+ columns.append(annotator.model_name+"_text_mr1")
54
+ columns.append(annotator.model_name+"_text_mr2")
55
+ columns.append(annotator.model_name+"_text_mr3")
56
+
57
+ existing_df = pd.DataFrame(columns=columns)
58
+ existing_df.to_csv(csv_filename, index=False)
59
+ last_index = 0
60
+
61
+ with tqdm(total=len(self.dataset), initial=last_index, desc="Processing Annotations", unit="sample") as pbar:
62
+
63
+ for index in range(last_index, len(self.dataset)):
64
+ row = self.dataset.iloc[index]
65
+ label = row['label']
66
+ text = row['text']
67
+ text_mr1 = self.textMutator.MutateText(text=text, mr="passive_active")
68
+ text_mr2 = self.textMutator.MutateText(text=text, mr="double_negation")
69
+ text_mr3 = self.textMutator.MutateText(text=text, mr="synonym")
70
+
71
+ existing_df.at[index, "label"] = label
72
+ existing_df.at[index, "text"] = text
73
+ existing_df.at[index, "text_mr1"] = text_mr1
74
+ existing_df.at[index, "text_mr2"] = text_mr2
75
+ existing_df.at[index, "text_mr3"] = text_mr3
76
+
77
+ for annotator in self.annotators:
78
+ existing_df.at[index, annotator.model_name+"_text"] = annotator.annotate(text)[0]
79
+ existing_df.at[index, annotator.model_name+"_text_mr1"] = annotator.annotate(text_mr1)[0]
80
+ existing_df.at[index, annotator.model_name+"_text_mr2"] = annotator.annotate(text_mr2)[0]
81
+ existing_df.at[index, annotator.model_name+"_text_mr3"] = annotator.annotate(text_mr3)[0]
82
+
83
+ row_df = existing_df.iloc[[index]]
84
+ row_df.to_csv(csv_filename, mode='a', index=False, header=not os.path.exists(csv_filename))
85
+
86
+ pbar.update(1) # Update progress bar
87
+
88
+
89
+ def get_majority_vote_label(self, majority_votes, possible_labels=None):
90
+ if not possible_labels:
91
+ possible_labels = self.possible_labels
92
+
93
+ vote_counts = {label.strip().lower(): 0 for label in possible_labels}
94
+
95
+ for vote in majority_votes:
96
+ if not pd.isna(vote):
97
+ lowered_vote = vote.strip().lower()
98
+ if lowered_vote in vote_counts:
99
+ vote_counts[lowered_vote] += 1
100
+
101
+ max_votes = max(vote_counts.values())
102
+
103
+ for label, count in vote_counts.items():
104
+ if count == max_votes:
105
+ return label
106
+
107
+ def get_pcs_label(self, llm_labels, w_llms=None, w_mrs=None, label_thresholds=None, possible_labels=None):
108
+ if possible_labels is None:
109
+ possible_labels = self.possible_labels
110
+ if w_llms is None:
111
+ w_llms = self.optimal_llm_weights
112
+ if w_mrs is None:
113
+ w_mrs = self.optimal_mr_weights
114
+ if label_thresholds is None:
115
+ label_thresholds = self.optimal_label_thresholds
116
+
117
+ num_labels = len(possible_labels)
118
+ pcs_labels = [0] * num_labels
119
+
120
+ for i in range(len(w_llms)):
121
+ pcs_label_llm = [0] * num_labels
122
+ for j in range(len(llm_labels[i])): #Iterate through MR labels
123
+ for k in range(len(pcs_label_llm)):
124
+ if not pd.isna(llm_labels[i][j]):
125
+ if llm_labels[i][j].strip().lower() == possible_labels[k].strip().lower():
126
+ pcs_label_llm[k] += w_mrs[j]
127
+
128
+ for j in range(len(pcs_label_llm)):
129
+ # pcs_label_llm[j] = pcs_label_llm[j]/sum(w_mrs)
130
+ if sum(w_mrs) != 0:
131
+ pcs_label_llm[j] = pcs_label_llm[j] / sum(w_mrs)
132
+ else:
133
+ pcs_label_llm[j] = 0
134
+
135
+ for j in range(len(pcs_label_llm)):
136
+ pcs_labels[j] += w_llms[i] * pcs_label_llm[j]
137
+
138
+ for i in range(num_labels):
139
+ if sum(w_llms) != 0:
140
+ pcs_labels[i] = pcs_labels[i]/sum(w_llms)
141
+ else:
142
+ pcs_labels[i] = 0
143
+
144
+ for i in range(num_labels):
145
+ if pcs_labels[i] > label_thresholds[i]:
146
+ final_pred = possible_labels[i]
147
+ return final_pred
148
+
149
+ majority_votes = []
150
+ for i in range(len(w_llms)):
151
+ majority_votes.append(llm_labels[i][0])
152
+
153
+ return self.get_majority_vote_label(majority_votes, possible_labels)
154
+
155
+
156
+ def Objective(self, params, llm_preds, NUM_LLMS, NUM_MRS, manual_labels):
157
+ w_mrs = params[:NUM_MRS] # Weights for 4 MRs
158
+ w_llms = params[NUM_MRS:NUM_MRS+NUM_LLMS] # Weights for 3 LLMs
159
+ label_thresholds = params[NUM_MRS+NUM_LLMS:NUM_MRS+NUM_LLMS+len(self.possible_labels)]
160
+ predictions = []
161
+
162
+ predictions = [
163
+ self.get_pcs_label(llm_preds[i, :], w_llms, w_mrs, label_thresholds)
164
+ for i in range(len(manual_labels))
165
+ ]
166
+
167
+ # Calculate accuracy
168
+ accuracy = np.mean([
169
+ manual_labels[i].strip().lower() == predictions[i].strip().lower()
170
+ for i in range(len(manual_labels))
171
+ ])
172
+ return -accuracy # We want to maximize accuracy, so we minimize negative accuracy
173
+
174
+ def PDE(self):
175
+ df = pd.read_csv(self.annotations_filename)
176
+
177
+ # Define model column mappings
178
+ model_columns = []
179
+ for annotator in self.annotators:
180
+ model_columns.append(df[[f"{annotator.model_name}_text", f"{annotator.model_name}_text_mr1", f"{annotator.model_name}_text_mr2", f"{annotator.model_name}_text_mr3"]])
181
+ llm_preds = np.stack(model_columns, axis=1)
182
+
183
+ manual_labels = df['label'].values
184
+ size, NUM_LLMS, NUM_MRS = llm_preds.shape[:3]
185
+
186
+ bounds = [(0, 1)] * (NUM_LLMS + NUM_MRS + len(self.possible_labels))
187
+
188
+ result = differential_evolution(self.Objective, bounds, args=(llm_preds, NUM_LLMS, NUM_MRS, manual_labels))
189
+
190
+ optimal_params = result.x
191
+
192
+ self.optimal_mr_weights = optimal_params[:NUM_MRS]
193
+ self.optimal_llm_weights = optimal_params[NUM_MRS:NUM_MRS+NUM_LLMS]
194
+ self.optimal_label_thresholds = optimal_params[NUM_MRS+NUM_LLMS:NUM_MRS+NUM_LLMS+len(self.possible_labels)]
195
+ self.Accuracy = -result.fun
196
+
197
+ def annotate(self, text):
198
+ text_mr1 = self.textMutator.MutateText(text=text, mr="passive_active")
199
+ text_mr2 = self.textMutator.MutateText(text=text, mr="double_negation")
200
+ text_mr3 = self.textMutator.MutateText(text=text, mr="synonym")
201
+ llm_preds = []
202
+ for annotator in self.annotators:
203
+ annotations = []
204
+ annotations.append(annotator.annotate(text)[0])
205
+ annotations.append(annotator.annotate(text_mr1)[0])
206
+ annotations.append(annotator.annotate(text_mr2)[0])
207
+ annotations.append(annotator.annotate(text_mr3)[0])
208
+ llm_preds.append(annotations)
209
+
210
+ pcs_label = self.get_pcs_label(llm_preds)
211
+ return pcs_label
212
+
@@ -0,0 +1,55 @@
1
+ from LLM import LLM
2
+ from Tools import *
3
+
4
+ class TextMutator(LLM):
5
+ def __init__(self, model_name="llama-3.1-8b-instant"):
6
+ super().__init__(model_name)
7
+
8
+
9
+ def MutateText(self, text, mr, custom_prompt=None):
10
+ if mr == "passive_active":
11
+ prompt = f"""Review the text below and transform all sentences by converting active voice to passive voice and vice versa, where appropriate.
12
+
13
+ Provide only the revised text, without extra information, starting with the term "new_text:"
14
+
15
+ Original Text:
16
+ {text}
17
+ """
18
+
19
+ if mr == "double_negation":
20
+ prompt = f"""Review the text below and transform affirmative sentences into double negation sentences. (Double negation means using two negative elements within a clause or sentence, typically leading to a positive implication.) Ensure that the transformations maintain equivalent meanings.
21
+
22
+ Provide only the revised text, without extra information, starting with the term "new_text:"
23
+
24
+ Original Text:
25
+ {text}
26
+ """
27
+
28
+
29
+ if mr == "synonym":
30
+ prompt = f"""Review the text below and Replace key words with their synonyms. Ensure that the transformed sentences retain equivalent meanings.
31
+
32
+ Provide only the revised text, without extra information, starting with the term "new_text:"
33
+
34
+ Original Text:
35
+ {text}
36
+ """
37
+
38
+ try:
39
+ ans = self.llm.invoke(prompt)
40
+ if "new_text:" in ans:
41
+ ans = ans.split("new_text:")[1]
42
+ elif "New Text:" in ans:
43
+ ans = ans.split("New Text:")[1]
44
+ elif "New_Text:" in ans:
45
+ ans = ans.split("New_Text:")[1]
46
+
47
+ ans = trim_text(ans)
48
+
49
+ return ans
50
+
51
+ except Exception as e:
52
+
53
+ print(f"Error querying model: {e}")
54
+ return None
55
+
pcs_annotator/Tools.py ADDED
@@ -0,0 +1,43 @@
1
+ def trim_text(response):
2
+ return response.strip("\n ")
3
+
4
+ def extract_label(response, labels):
5
+ response = response.lower()
6
+
7
+ if "<label>" in response:
8
+ label_section = response.split("<label>")[1]
9
+ elif "label:" in response:
10
+ label_section = response.split("label:")[1]
11
+ else:
12
+ return None
13
+
14
+ for label in labels:
15
+ if label.lower() in label_section:
16
+ return label
17
+
18
+ return None
19
+
20
+
21
+ def extract_reasoning(response):
22
+ reasons = []
23
+ response = response.lower()
24
+ if "<reasoning>" in response and "</reasoning>" in response:
25
+ reasoning_section = response.split("<reasoning>")[1].split("</reasoning>")[0]
26
+ reasons = reasoning_section.strip().split('\n')
27
+
28
+ elif "reasoning:" in response:
29
+ reasoning_section = response.split("reasoning:")[1]
30
+ reasons = reasoning_section.strip().split('\n')
31
+
32
+ return reasons
33
+
34
+ def extract_judgement(response):
35
+ lines = response.split('\n')
36
+ for line in lines:
37
+ if line.strip():
38
+ if "no" in line.lower():
39
+ return "No"
40
+ elif "yes" in line.lower():
41
+ return "Yes"
42
+
43
+ return "Undefined"
@@ -0,0 +1,3 @@
1
+ from .PCS import PCS # Importing the main PCS class
2
+
3
+ __all__ = ["PCS"] # Controls what gets imported with 'from pcs_annotator import *'
@@ -0,0 +1,24 @@
1
+ Metadata-Version: 2.4
2
+ Name: pcs-annotator
3
+ Version: 0.0.1
4
+ Summary: A Python library for classification tasks using multiple LLMs
5
+ Project-URL: Homepage, https://github.com/salsina/PCS-Python-Library
6
+ Project-URL: Issues, https://github.com/salsina/PCS-Python-Library/issues
7
+ Author-email: Sina Salimian <sina99.sn@gmail.com>
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Programming Language :: Python :: 3
12
+ Requires-Python: >=3.8
13
+ Requires-Dist: langchain
14
+ Requires-Dist: langchain-anthropic
15
+ Requires-Dist: langchain-community
16
+ Requires-Dist: langchain-groq
17
+ Requires-Dist: langchain-huggingface
18
+ Requires-Dist: langchain-openai
19
+ Requires-Dist: python-dotenv
20
+ Description-Content-Type: text/markdown
21
+
22
+ This is a simple example package. You can use
23
+ [GitHub-flavored Markdown](https://guides.github.com/features/mastering-markdown/)
24
+ to write your content.
@@ -0,0 +1,10 @@
1
+ pcs_annotator/Annotator.py,sha256=KiV3Hi3N4OK3d6QVUAVqRlY6VWc828xOF-Mo62ndoVQ,1218
2
+ pcs_annotator/LLM.py,sha256=W92f_D6tSPFs-j_nAD-DYcQzxGQPscg6ZDZQuYcnP9I,2914
3
+ pcs_annotator/PCS.py,sha256=Ukmm6Nf2C0QcEimMS7tLJ3bBHeA34K6ivB5ZjZ6GX78,9125
4
+ pcs_annotator/TextMutator.py,sha256=xHZv0QgXGAovLUur9D2HxmYrurUgpcUnsp3A02xbuIU,1962
5
+ pcs_annotator/Tools.py,sha256=oRsMhngzJ0rrfe4KeMUYgkl54BhvzknidFv7BymH8hY,1200
6
+ pcs_annotator/__init__.py,sha256=ff7LaQ_3eKcDnArfl7348gfG_wz3aYT-bsBRd89pUCU,138
7
+ pcs_annotator-0.0.1.dist-info/METADATA,sha256=Og74ohBqkWI_PKaU03PyKDuKGHYaAtzBarJsETtIgkk,901
8
+ pcs_annotator-0.0.1.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
9
+ pcs_annotator-0.0.1.dist-info/licenses/LICENSE,sha256=xQL2HfZyWEOYJzNPEMLKB5ba8VKoSbE0UqMc2UycE00,1056
10
+ pcs_annotator-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.27.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,19 @@
1
+ Copyright (c) 2025 Sina Salimian
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ of this software and associated documentation files (the "Software"), to deal
5
+ in the Software without restriction, including without limitation the rights
6
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ copies of the Software, and to permit persons to whom the Software is
8
+ furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in all
11
+ copies or substantial portions of the Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19
+ SOFTWARE.