pcs-annotator 0.2.0__tar.gz → 0.2.2__tar.gz
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.
- {pcs_annotator-0.2.0 → pcs_annotator-0.2.2}/PKG-INFO +55 -9
- {pcs_annotator-0.2.0 → pcs_annotator-0.2.2}/README.md +54 -8
- {pcs_annotator-0.2.0 → pcs_annotator-0.2.2}/pcs_annotator/PCS.py +10 -11
- pcs_annotator-0.2.2/pcs_annotator/TextMutator.py +53 -0
- {pcs_annotator-0.2.0 → pcs_annotator-0.2.2}/pyproject.toml +1 -1
- pcs_annotator-0.2.0/pcs_annotator/TextMutator.py +0 -55
- {pcs_annotator-0.2.0 → pcs_annotator-0.2.2}/LICENSE +0 -0
- {pcs_annotator-0.2.0 → pcs_annotator-0.2.2}/pcs_annotator/Annotator.py +0 -0
- {pcs_annotator-0.2.0 → pcs_annotator-0.2.2}/pcs_annotator/LLM.py +0 -0
- {pcs_annotator-0.2.0 → pcs_annotator-0.2.2}/pcs_annotator/Tools.py +0 -0
- {pcs_annotator-0.2.0 → pcs_annotator-0.2.2}/pcs_annotator/__init__.py +0 -0
- {pcs_annotator-0.2.0 → pcs_annotator-0.2.2}/requirements.txt +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: pcs-annotator
|
|
3
|
-
Version: 0.2.
|
|
3
|
+
Version: 0.2.2
|
|
4
4
|
Summary: A Python library for classification tasks using multiple LLMs
|
|
5
5
|
Project-URL: Homepage, https://github.com/salsina/PCS-Python-Library
|
|
6
6
|
Project-URL: Issues, https://github.com/salsina/PCS-Python-Library/issues
|
|
@@ -38,8 +38,7 @@ from pcs_annotator import PCS
|
|
|
38
38
|
```python
|
|
39
39
|
prompt = """Analyze the news article and determine whether it is 'Fake' or 'Real.'
|
|
40
40
|
Label the article using the tag format: <label>Fake</label> or <label>Real</label>.
|
|
41
|
-
|
|
42
|
-
Respond only with the label and the reasoning.
|
|
41
|
+
Respond only with the label.
|
|
43
42
|
"""
|
|
44
43
|
```
|
|
45
44
|
|
|
@@ -59,17 +58,25 @@ The `PCS` class allows you to customize various hyperparameters, including the c
|
|
|
59
58
|
pcs = PCS(
|
|
60
59
|
prompt="Your classification prompt here",
|
|
61
60
|
dataset_path="path/to/dataset.csv",
|
|
62
|
-
annotators=["llama3-8b-8192", "mistralai/Mistral-7B-Instruct-v0.3", "
|
|
61
|
+
annotators=["llama3-8b-8192", "mistralai/Mistral-7B-Instruct-v0.3", "gemma-2-9b-it"],
|
|
63
62
|
textmutator="llama-3.1-8b-instant",
|
|
64
63
|
GROQ_API_KEY=None,
|
|
65
64
|
OPENAI_API_KEY=None,
|
|
66
65
|
ANTHROPIC_API_KEY=None,
|
|
67
66
|
HUGGINGFACE_API_KEY=None,
|
|
68
|
-
|
|
67
|
+
generate_annotations=True,
|
|
68
|
+
Optimizer="LR" # or "GA"
|
|
69
69
|
)
|
|
70
70
|
|
|
71
71
|
print(pcs.annotate("America is a country"))
|
|
72
72
|
```
|
|
73
|
+
### 🖨️ Output
|
|
74
|
+
|
|
75
|
+
The `.annotate()` function returns a dictionary of confidence scores for each label:
|
|
76
|
+
|
|
77
|
+
```python
|
|
78
|
+
{'Real': 0.87, 'Fake': 0.13}
|
|
79
|
+
|
|
73
80
|
|
|
74
81
|
# Configuration
|
|
75
82
|
|
|
@@ -93,14 +100,53 @@ To access certain LLM models, you need to provide API keys. These can be passed
|
|
|
93
100
|
|
|
94
101
|
| API Key | Purpose |
|
|
95
102
|
|---------|---------|
|
|
96
|
-
| `GROQ_API_KEY` | Required for **Llama models**. Set via argument or `.env` file. |
|
|
103
|
+
| `GROQ_API_KEY` | Required for **Llama and Google Gemma models**. Set via argument or `.env` file. |
|
|
97
104
|
| `OPENAI_API_KEY` | Required for **OpenAI models** (e.g., `"gpt-4"`). |
|
|
98
105
|
| `ANTHROPIC_API_KEY` | Required for **Anthropic models** (e.g., `"claude-3-5-sonnet-20241022"`). |
|
|
99
|
-
| `HUGGINGFACE_API_KEY` | Required for **Mistral
|
|
106
|
+
| `HUGGINGFACE_API_KEY` | Required for **Mistral models**. |
|
|
100
107
|
|
|
101
108
|
|
|
102
|
-
## 🔹 Continue the Training (`
|
|
103
|
-
Determines whether to continue
|
|
109
|
+
## 🔹 Continue the Training (`generate_annotations`)
|
|
110
|
+
Determines whether to continue generating more annotations in the dataset or not
|
|
104
111
|
* **Default Value**: `True`
|
|
105
112
|
* **Customization**:
|
|
106
113
|
* You can change to `False`
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
## ⚙️ Optimizer (`Optimizer`)
|
|
118
|
+
|
|
119
|
+
The `PCS` class supports weight optimization strategies for combining LLM predictions and Metamorphic Relation (MR) outputs. You can choose the optimizer during initialization using the `Optimizer` parameter.
|
|
120
|
+
|
|
121
|
+
### 🔧 Options
|
|
122
|
+
|
|
123
|
+
| Value | Description |
|
|
124
|
+
|---------|-----------------------------------------------------------------------------|
|
|
125
|
+
| `"LR"` | **Linear Regression** – Optimizes annotator and MR weights via regression. *(default)* |
|
|
126
|
+
| `"GA"` | **Genetic Algorithm** – Uses evolutionary search to find optimal weights. |
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
## ➕ Adding a Custom Metamorphic Relation (MR)
|
|
131
|
+
|
|
132
|
+
You can define and register your own MR by passing a custom prompt-generation function to the `TextMutator` class:
|
|
133
|
+
|
|
134
|
+
```python
|
|
135
|
+
from pcs_annotator.TextMutator import TextMutator
|
|
136
|
+
|
|
137
|
+
# Define a new MR prompt
|
|
138
|
+
def custom_negation_prompt(text):
|
|
139
|
+
return f"""Transform all affirmative statements in the following text into their negated forms.
|
|
140
|
+
Start the response with 'new_text:' and include only the revised text.
|
|
141
|
+
|
|
142
|
+
Original Text:
|
|
143
|
+
{text}
|
|
144
|
+
"""
|
|
145
|
+
|
|
146
|
+
# Initialize a mutator and register the new MR
|
|
147
|
+
mutator = TextMutator(model_name="llama-3.1-8b-instant", token="your_groq_api_key")
|
|
148
|
+
mutator.register_mr("custom_negation", custom_negation_prompt)
|
|
149
|
+
|
|
150
|
+
# Apply the new MR
|
|
151
|
+
mutated_text = mutator.MutateText("The cat is on the table.", "custom_negation")
|
|
152
|
+
print(mutated_text)
|
|
@@ -17,8 +17,7 @@ from pcs_annotator import PCS
|
|
|
17
17
|
```python
|
|
18
18
|
prompt = """Analyze the news article and determine whether it is 'Fake' or 'Real.'
|
|
19
19
|
Label the article using the tag format: <label>Fake</label> or <label>Real</label>.
|
|
20
|
-
|
|
21
|
-
Respond only with the label and the reasoning.
|
|
20
|
+
Respond only with the label.
|
|
22
21
|
"""
|
|
23
22
|
```
|
|
24
23
|
|
|
@@ -38,17 +37,25 @@ The `PCS` class allows you to customize various hyperparameters, including the c
|
|
|
38
37
|
pcs = PCS(
|
|
39
38
|
prompt="Your classification prompt here",
|
|
40
39
|
dataset_path="path/to/dataset.csv",
|
|
41
|
-
annotators=["llama3-8b-8192", "mistralai/Mistral-7B-Instruct-v0.3", "
|
|
40
|
+
annotators=["llama3-8b-8192", "mistralai/Mistral-7B-Instruct-v0.3", "gemma-2-9b-it"],
|
|
42
41
|
textmutator="llama-3.1-8b-instant",
|
|
43
42
|
GROQ_API_KEY=None,
|
|
44
43
|
OPENAI_API_KEY=None,
|
|
45
44
|
ANTHROPIC_API_KEY=None,
|
|
46
45
|
HUGGINGFACE_API_KEY=None,
|
|
47
|
-
|
|
46
|
+
generate_annotations=True,
|
|
47
|
+
Optimizer="LR" # or "GA"
|
|
48
48
|
)
|
|
49
49
|
|
|
50
50
|
print(pcs.annotate("America is a country"))
|
|
51
51
|
```
|
|
52
|
+
### 🖨️ Output
|
|
53
|
+
|
|
54
|
+
The `.annotate()` function returns a dictionary of confidence scores for each label:
|
|
55
|
+
|
|
56
|
+
```python
|
|
57
|
+
{'Real': 0.87, 'Fake': 0.13}
|
|
58
|
+
|
|
52
59
|
|
|
53
60
|
# Configuration
|
|
54
61
|
|
|
@@ -72,14 +79,53 @@ To access certain LLM models, you need to provide API keys. These can be passed
|
|
|
72
79
|
|
|
73
80
|
| API Key | Purpose |
|
|
74
81
|
|---------|---------|
|
|
75
|
-
| `GROQ_API_KEY` | Required for **Llama models**. Set via argument or `.env` file. |
|
|
82
|
+
| `GROQ_API_KEY` | Required for **Llama and Google Gemma models**. Set via argument or `.env` file. |
|
|
76
83
|
| `OPENAI_API_KEY` | Required for **OpenAI models** (e.g., `"gpt-4"`). |
|
|
77
84
|
| `ANTHROPIC_API_KEY` | Required for **Anthropic models** (e.g., `"claude-3-5-sonnet-20241022"`). |
|
|
78
|
-
| `HUGGINGFACE_API_KEY` | Required for **Mistral
|
|
85
|
+
| `HUGGINGFACE_API_KEY` | Required for **Mistral models**. |
|
|
79
86
|
|
|
80
87
|
|
|
81
|
-
## 🔹 Continue the Training (`
|
|
82
|
-
Determines whether to continue
|
|
88
|
+
## 🔹 Continue the Training (`generate_annotations`)
|
|
89
|
+
Determines whether to continue generating more annotations in the dataset or not
|
|
83
90
|
* **Default Value**: `True`
|
|
84
91
|
* **Customization**:
|
|
85
92
|
* You can change to `False`
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
## ⚙️ Optimizer (`Optimizer`)
|
|
97
|
+
|
|
98
|
+
The `PCS` class supports weight optimization strategies for combining LLM predictions and Metamorphic Relation (MR) outputs. You can choose the optimizer during initialization using the `Optimizer` parameter.
|
|
99
|
+
|
|
100
|
+
### 🔧 Options
|
|
101
|
+
|
|
102
|
+
| Value | Description |
|
|
103
|
+
|---------|-----------------------------------------------------------------------------|
|
|
104
|
+
| `"LR"` | **Linear Regression** – Optimizes annotator and MR weights via regression. *(default)* |
|
|
105
|
+
| `"GA"` | **Genetic Algorithm** – Uses evolutionary search to find optimal weights. |
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
## ➕ Adding a Custom Metamorphic Relation (MR)
|
|
110
|
+
|
|
111
|
+
You can define and register your own MR by passing a custom prompt-generation function to the `TextMutator` class:
|
|
112
|
+
|
|
113
|
+
```python
|
|
114
|
+
from pcs_annotator.TextMutator import TextMutator
|
|
115
|
+
|
|
116
|
+
# Define a new MR prompt
|
|
117
|
+
def custom_negation_prompt(text):
|
|
118
|
+
return f"""Transform all affirmative statements in the following text into their negated forms.
|
|
119
|
+
Start the response with 'new_text:' and include only the revised text.
|
|
120
|
+
|
|
121
|
+
Original Text:
|
|
122
|
+
{text}
|
|
123
|
+
"""
|
|
124
|
+
|
|
125
|
+
# Initialize a mutator and register the new MR
|
|
126
|
+
mutator = TextMutator(model_name="llama-3.1-8b-instant", token="your_groq_api_key")
|
|
127
|
+
mutator.register_mr("custom_negation", custom_negation_prompt)
|
|
128
|
+
|
|
129
|
+
# Apply the new MR
|
|
130
|
+
mutated_text = mutator.MutateText("The cat is on the table.", "custom_negation")
|
|
131
|
+
print(mutated_text)
|
|
@@ -9,7 +9,7 @@ from sklearn.linear_model import LinearRegression
|
|
|
9
9
|
|
|
10
10
|
|
|
11
11
|
class PCS:
|
|
12
|
-
def __init__(self, prompt, dataset_path, annotators=["llama3-8b-8192", "mistralai/Mistral-7B-Instruct-v0.3", "
|
|
12
|
+
def __init__(self, prompt, dataset_path, annotators=["llama3-8b-8192", "mistralai/Mistral-7B-Instruct-v0.3", "gemma-2-9b-it"], textmutator="llama-3.1-8b-instant", GROQ_API_KEY=None, OPENAI_API_KEY=None, ANTHROPIC_API_KEY=None, HUGGINGFACE_API_KEY=None, generate_annotations=True, Optimizer="LR"):
|
|
13
13
|
self.prompt=prompt
|
|
14
14
|
if os.path.exists(dataset_path):
|
|
15
15
|
self.dataset_path = dataset_path
|
|
@@ -50,14 +50,16 @@ class PCS:
|
|
|
50
50
|
self.optimal_mr_weights = [1] * 4
|
|
51
51
|
# self.optimal_label_thresholds = [0.5] * len(self.possible_labels)
|
|
52
52
|
|
|
53
|
-
if
|
|
54
|
-
print("
|
|
53
|
+
if generate_annotations:
|
|
54
|
+
print("Generating annotations...")
|
|
55
55
|
self.create_annotations()
|
|
56
56
|
print("Generated the dataset annotations.")
|
|
57
57
|
|
|
58
58
|
print("Optimizing weights...")
|
|
59
|
-
|
|
60
|
-
|
|
59
|
+
if Optimizer == "LR":
|
|
60
|
+
self.LR()
|
|
61
|
+
elif Optimizer == "GA":
|
|
62
|
+
self.GA()
|
|
61
63
|
print("Done Optimizing weights.")
|
|
62
64
|
|
|
63
65
|
def create_annotations(self):
|
|
@@ -148,11 +150,10 @@ class PCS:
|
|
|
148
150
|
def Objective(self, params, llm_preds, NUM_LLMS, NUM_MRS, manual_labels):
|
|
149
151
|
w_mrs = params[:NUM_MRS] # Weights for 4 MRs
|
|
150
152
|
w_llms = params[NUM_MRS:NUM_MRS+NUM_LLMS] # Weights for 3 LLMs
|
|
151
|
-
label_thresholds = params[NUM_MRS+NUM_LLMS:NUM_MRS+NUM_LLMS+len(self.possible_labels)]
|
|
152
153
|
predictions = []
|
|
153
154
|
|
|
154
155
|
predictions = [
|
|
155
|
-
self.get_pcs_label(llm_preds[i, :], w_llms, w_mrs
|
|
156
|
+
self.get_pcs_label(llm_preds[i, :], w_llms, w_mrs)
|
|
156
157
|
for i in range(len(manual_labels))
|
|
157
158
|
]
|
|
158
159
|
|
|
@@ -163,7 +164,7 @@ class PCS:
|
|
|
163
164
|
])
|
|
164
165
|
return -accuracy # We want to maximize accuracy, so we minimize negative accuracy
|
|
165
166
|
|
|
166
|
-
def
|
|
167
|
+
def GA(self):
|
|
167
168
|
if os.path.exists(self.annotations_filename):
|
|
168
169
|
df = pd.read_csv(self.annotations_filename)
|
|
169
170
|
else:
|
|
@@ -177,7 +178,7 @@ class PCS:
|
|
|
177
178
|
manual_labels = df['label'].values
|
|
178
179
|
size, NUM_LLMS, NUM_MRS = llm_preds.shape[:3]
|
|
179
180
|
|
|
180
|
-
bounds = [(0, 1)] * (NUM_LLMS + NUM_MRS
|
|
181
|
+
bounds = [(0, 1)] * (NUM_LLMS + NUM_MRS)
|
|
181
182
|
|
|
182
183
|
result = differential_evolution(self.Objective, bounds, args=(llm_preds, NUM_LLMS, NUM_MRS, manual_labels))
|
|
183
184
|
|
|
@@ -185,8 +186,6 @@ class PCS:
|
|
|
185
186
|
|
|
186
187
|
self.optimal_mr_weights = optimal_params[:NUM_MRS]
|
|
187
188
|
self.optimal_llm_weights = optimal_params[NUM_MRS:NUM_MRS+NUM_LLMS]
|
|
188
|
-
self.optimal_label_thresholds = optimal_params[NUM_MRS+NUM_LLMS:NUM_MRS+NUM_LLMS+len(self.possible_labels)]
|
|
189
|
-
self.Accuracy = -result.fun
|
|
190
189
|
|
|
191
190
|
|
|
192
191
|
def compute_features(self, llm_preds, selected_indices, optimize_params=["LLM", "MR"]):
|
|
@@ -0,0 +1,53 @@
|
|
|
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", token=None):
|
|
6
|
+
super().__init__(model_name, token)
|
|
7
|
+
self.mr_templates = {
|
|
8
|
+
"passive_active": self._passive_active_prompt,
|
|
9
|
+
"double_negation": self._double_negation_prompt,
|
|
10
|
+
"synonym": self._synonym_prompt
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
def register_mr(self, mr_name, template_fn):
|
|
14
|
+
"""Allows users to register a new MR and its template-generating function."""
|
|
15
|
+
self.mr_templates[mr_name] = template_fn
|
|
16
|
+
|
|
17
|
+
def MutateText(self, text, mr):
|
|
18
|
+
if mr not in self.mr_templates:
|
|
19
|
+
raise ValueError(f"Unknown MR: {mr}. Please register it using `register_mr()`.")
|
|
20
|
+
|
|
21
|
+
prompt = self.mr_templates[mr](text)
|
|
22
|
+
|
|
23
|
+
try:
|
|
24
|
+
ans = self.llm.invoke(prompt)
|
|
25
|
+
for key in ["new_text:", "New Text:", "New_Text:"]:
|
|
26
|
+
if key in ans:
|
|
27
|
+
ans = ans.split(key)[1]
|
|
28
|
+
break
|
|
29
|
+
return trim_text(ans)
|
|
30
|
+
except Exception as e:
|
|
31
|
+
print(f"Error querying model: {e}")
|
|
32
|
+
return None
|
|
33
|
+
|
|
34
|
+
def _passive_active_prompt(self, text):
|
|
35
|
+
return f"""Review the text below and transform all sentences by converting active voice to passive voice and vice versa, where appropriate.
|
|
36
|
+
Provide only the revised text, without extra information, starting with the term "new_text:"
|
|
37
|
+
Original Text:
|
|
38
|
+
{text}
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
def _double_negation_prompt(self, text):
|
|
42
|
+
return f"""Review the text below and transform affirmative sentences into double negation sentences.
|
|
43
|
+
Provide only the revised text, without extra information, starting with the term "new_text:"
|
|
44
|
+
Original Text:
|
|
45
|
+
{text}
|
|
46
|
+
"""
|
|
47
|
+
|
|
48
|
+
def _synonym_prompt(self, text):
|
|
49
|
+
return f"""Review the text below and replace key words with their synonyms. Ensure that the transformed sentences retain equivalent meanings.
|
|
50
|
+
Provide only the revised text, without extra information, starting with the term "new_text:"
|
|
51
|
+
Original Text:
|
|
52
|
+
{text}
|
|
53
|
+
"""
|
|
@@ -1,55 +0,0 @@
|
|
|
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", token=None):
|
|
6
|
-
super().__init__(model_name, token)
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
def MutateText(self, text, mr):
|
|
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
|
-
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|