pcs-annotator 2.0.0__tar.gz → 2.1.0__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.
Files changed (41) hide show
  1. {pcs_annotator-2.0.0 → pcs_annotator-2.1.0}/CHANGELOG.md +12 -0
  2. {pcs_annotator-2.0.0 → pcs_annotator-2.1.0}/PKG-INFO +11 -4
  3. {pcs_annotator-2.0.0 → pcs_annotator-2.1.0}/README.md +9 -2
  4. {pcs_annotator-2.0.0 → pcs_annotator-2.1.0}/examples/api_examples.py +2 -2
  5. {pcs_annotator-2.0.0 → pcs_annotator-2.1.0}/pcs_annotator/__init__.py +1 -1
  6. {pcs_annotator-2.0.0 → pcs_annotator-2.1.0}/pcs_annotator/cli.py +11 -4
  7. {pcs_annotator-2.0.0 → pcs_annotator-2.1.0}/pcs_annotator/tasks/builtin.py +5 -3
  8. {pcs_annotator-2.0.0 → pcs_annotator-2.1.0}/pcs_annotator/transforms/__init__.py +3 -2
  9. pcs_annotator-2.1.0/pcs_annotator/transforms/text.py +138 -0
  10. {pcs_annotator-2.0.0 → pcs_annotator-2.1.0}/pyproject.toml +2 -2
  11. {pcs_annotator-2.0.0 → pcs_annotator-2.1.0}/tests/test_cli.py +28 -0
  12. {pcs_annotator-2.0.0 → pcs_annotator-2.1.0}/tests/test_transforms.py +10 -0
  13. pcs_annotator-2.0.0/pcs_annotator/transforms/text.py +0 -58
  14. {pcs_annotator-2.0.0 → pcs_annotator-2.1.0}/.gitignore +0 -0
  15. {pcs_annotator-2.0.0 → pcs_annotator-2.1.0}/LICENSE +0 -0
  16. {pcs_annotator-2.0.0 → pcs_annotator-2.1.0}/examples/offline_demo.py +0 -0
  17. {pcs_annotator-2.0.0 → pcs_annotator-2.1.0}/pcs_annotator/backends/__init__.py +0 -0
  18. {pcs_annotator-2.0.0 → pcs_annotator-2.1.0}/pcs_annotator/backends/base.py +0 -0
  19. {pcs_annotator-2.0.0 → pcs_annotator-2.1.0}/pcs_annotator/backends/cache.py +0 -0
  20. {pcs_annotator-2.0.0 → pcs_annotator-2.1.0}/pcs_annotator/backends/openai_compat.py +0 -0
  21. {pcs_annotator-2.0.0 → pcs_annotator-2.1.0}/pcs_annotator/core/__init__.py +0 -0
  22. {pcs_annotator-2.0.0 → pcs_annotator-2.1.0}/pcs_annotator/core/engine.py +0 -0
  23. {pcs_annotator-2.0.0 → pcs_annotator-2.1.0}/pcs_annotator/core/result.py +0 -0
  24. {pcs_annotator-2.0.0 → pcs_annotator-2.1.0}/pcs_annotator/core/weights.py +0 -0
  25. {pcs_annotator-2.0.0 → pcs_annotator-2.1.0}/pcs_annotator/eval/__init__.py +0 -0
  26. {pcs_annotator-2.0.0 → pcs_annotator-2.1.0}/pcs_annotator/eval/baselines.py +0 -0
  27. {pcs_annotator-2.0.0 → pcs_annotator-2.1.0}/pcs_annotator/eval/crossval.py +0 -0
  28. {pcs_annotator-2.0.0 → pcs_annotator-2.1.0}/pcs_annotator/eval/metrics.py +0 -0
  29. {pcs_annotator-2.0.0 → pcs_annotator-2.1.0}/pcs_annotator/pcs.py +0 -0
  30. {pcs_annotator-2.0.0 → pcs_annotator-2.1.0}/pcs_annotator/tasks/__init__.py +0 -0
  31. {pcs_annotator-2.0.0 → pcs_annotator-2.1.0}/pcs_annotator/tasks/base.py +0 -0
  32. {pcs_annotator-2.0.0 → pcs_annotator-2.1.0}/pcs_annotator/transforms/_refactor_c.py +0 -0
  33. {pcs_annotator-2.0.0 → pcs_annotator-2.1.0}/pcs_annotator/transforms/align.py +0 -0
  34. {pcs_annotator-2.0.0 → pcs_annotator-2.1.0}/pcs_annotator/transforms/base.py +0 -0
  35. {pcs_annotator-2.0.0 → pcs_annotator-2.1.0}/pcs_annotator/transforms/code_c.py +0 -0
  36. {pcs_annotator-2.0.0 → pcs_annotator-2.1.0}/tests/test_backends.py +0 -0
  37. {pcs_annotator-2.0.0 → pcs_annotator-2.1.0}/tests/test_core.py +0 -0
  38. {pcs_annotator-2.0.0 → pcs_annotator-2.1.0}/tests/test_cpp_behavior.py +0 -0
  39. {pcs_annotator-2.0.0 → pcs_annotator-2.1.0}/tests/test_eval.py +0 -0
  40. {pcs_annotator-2.0.0 → pcs_annotator-2.1.0}/tests/test_refactor_c.py +0 -0
  41. {pcs_annotator-2.0.0 → pcs_annotator-2.1.0}/tests/test_tasks_pcs.py +0 -0
@@ -1,5 +1,17 @@
1
1
  # Changelog
2
2
 
3
+ ## 2.1.0
4
+
5
+ **Changed**
6
+ - New default prompts for the text rewrites M1-M3. Each asks for one meaning-preserving edit in every eligible
7
+ sentence and lists the safe forms; a judge model found the meaning kept in 96% (M1), 84% (M2) and 98% (M3) of 50
8
+ rewrites each. The prompts of 2.0.0 stay available as `mr_prompts="original"` (`--mr-prompts original`).
9
+ - Recommended rewriter: `openai/gpt-6-luna` with no temperature, reasoning off and `max_tokens=1500`
10
+ (`transforms.REWRITER_MODEL`, `transforms.REWRITER_SETTINGS`). The command line uses it by default
11
+ (was LLaMA-3.1-8B at temperature 0.2); `--rewriter-temperature` and `--rewriter-max-tokens` change the settings.
12
+ - Author order in the package metadata now follows the paper (and LICENSE): Sina Salimian, Anik Islam, Gias Uddin,
13
+ Shaina Raza, Henry Leung.
14
+
3
15
  ## 2.0.0
4
16
 
5
17
  A rewrite that extends PCS from text classification to source code.
@@ -1,11 +1,11 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: pcs-annotator
3
- Version: 2.0.0
3
+ Version: 2.1.0
4
4
  Summary: Perceived Confidence Scoring (PCS) for black-box LLMs on text classification, C/C++ vulnerability classification and C/C++ bug localization
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
7
7
  Project-URL: Changelog, https://github.com/salsina/PCS-Python-Library/blob/main/CHANGELOG.md
8
- Author: Anik Islam, Sina Salimian, Gias Uddin, Shaina Raza, Henry Leung
8
+ Author: Sina Salimian, Anik Islam, Gias Uddin, Shaina Raza, Henry Leung
9
9
  License-Expression: MIT
10
10
  License-File: LICENSE
11
11
  Keywords: bug localization,confidence,llm,metamorphic testing,uncertainty,vulnerability detection
@@ -90,7 +90,8 @@ from pcs_annotator import PCS
90
90
  from pcs_annotator.backends import OpenAICompatible
91
91
  from pcs_annotator.tasks import NEWS_PROMPT, TextClassification
92
92
 
93
- rewriter = OpenAICompatible("meta-llama/llama-3.1-8b-instruct", temperature=0.2, max_tokens=800)
93
+ off = {"reasoning": {"enabled": False}}
94
+ rewriter = OpenAICompatible("openai/gpt-6-luna", temperature=None, max_tokens=1500, extra=off)
94
95
  annotators = [
95
96
  OpenAICompatible("anthropic/claude-haiku-5.5", temperature=None, max_tokens=160, name="haiku"),
96
97
  OpenAICompatible("deepseek/deepseek-v4.1-flash", temperature=1.0, max_tokens=32, name="deepseek"),
@@ -179,9 +180,15 @@ The key is read from an environment variable (or a `.env` file loaded by your ow
179
180
  ## 🔹 Text Mutator (`rewriter`)
180
181
  Determines the LLM that writes the text rewrites M1–M3. The code tasks need no rewriter, because their rewrites are
181
182
  rule-based.
182
- * **Recommended Model**: `"meta-llama/llama-3.1-8b-instruct"` at temperature 0.2, as in the paper.
183
+ * **Recommended Model**: `"openai/gpt-6-luna"` with no temperature, reasoning off and `max_tokens=1500`, as in the
184
+ paper (`pcs_annotator.transforms.REWRITER_MODEL` and `REWRITER_SETTINGS`).
185
+ * **Prompts**: each prompt asks for one meaning-preserving edit in every eligible sentence and lists the safe forms
186
+ (M1 voice change, M2 double negation such as "did not fail to", M3 true synonyms). A judge model found the meaning
187
+ kept in 96% (M1), 84% (M2) and 98% (M3) of 50 rewrites each.
183
188
  * **Customization**:
184
189
  * Pass any model as `rewriter=`. With a cache, each text is rewritten only once.
190
+ * `TextClassification(..., mr_prompts="original")` uses the prompts of version 2.0.0 (written for
191
+ `"meta-llama/llama-3.1-8b-instruct"` at temperature 0.2). On the command line: `--mr-prompts original`.
185
192
 
186
193
  ## ⚙️ Weights (`weights` and `calibrate`)
187
194
 
@@ -61,7 +61,8 @@ from pcs_annotator import PCS
61
61
  from pcs_annotator.backends import OpenAICompatible
62
62
  from pcs_annotator.tasks import NEWS_PROMPT, TextClassification
63
63
 
64
- rewriter = OpenAICompatible("meta-llama/llama-3.1-8b-instruct", temperature=0.2, max_tokens=800)
64
+ off = {"reasoning": {"enabled": False}}
65
+ rewriter = OpenAICompatible("openai/gpt-6-luna", temperature=None, max_tokens=1500, extra=off)
65
66
  annotators = [
66
67
  OpenAICompatible("anthropic/claude-haiku-5.5", temperature=None, max_tokens=160, name="haiku"),
67
68
  OpenAICompatible("deepseek/deepseek-v4.1-flash", temperature=1.0, max_tokens=32, name="deepseek"),
@@ -150,9 +151,15 @@ The key is read from an environment variable (or a `.env` file loaded by your ow
150
151
  ## 🔹 Text Mutator (`rewriter`)
151
152
  Determines the LLM that writes the text rewrites M1–M3. The code tasks need no rewriter, because their rewrites are
152
153
  rule-based.
153
- * **Recommended Model**: `"meta-llama/llama-3.1-8b-instruct"` at temperature 0.2, as in the paper.
154
+ * **Recommended Model**: `"openai/gpt-6-luna"` with no temperature, reasoning off and `max_tokens=1500`, as in the
155
+ paper (`pcs_annotator.transforms.REWRITER_MODEL` and `REWRITER_SETTINGS`).
156
+ * **Prompts**: each prompt asks for one meaning-preserving edit in every eligible sentence and lists the safe forms
157
+ (M1 voice change, M2 double negation such as "did not fail to", M3 true synonyms). A judge model found the meaning
158
+ kept in 96% (M1), 84% (M2) and 98% (M3) of 50 rewrites each.
154
159
  * **Customization**:
155
160
  * Pass any model as `rewriter=`. With a cache, each text is rewritten only once.
161
+ * `TextClassification(..., mr_prompts="original")` uses the prompts of version 2.0.0 (written for
162
+ `"meta-llama/llama-3.1-8b-instruct"` at temperature 0.2). On the command line: `--mr-prompts original`.
156
163
 
157
164
  ## ⚙️ Weights (`weights` and `calibrate`)
158
165
 
@@ -14,8 +14,8 @@ haiku = OpenAICompatible("anthropic/claude-haiku-5.5", temperature=None, max_tok
14
14
  deepseek = OpenAICompatible("deepseek/deepseek-v4.1-flash", max_tokens=32, extra=off, cache=cache, budget=budget,
15
15
  name="deepseek")
16
16
 
17
- # 1. Text classification: M1-M3 written by LLaMA-3.1-8B at temperature 0.2
18
- rewriter = OpenAICompatible("meta-llama/llama-3.1-8b-instruct", temperature=0.2, max_tokens=800, cache=cache,
17
+ # 1. Text classification: M1-M3 written by GPT-6 Luna (no temperature, reasoning off, as in the paper)
18
+ rewriter = OpenAICompatible("openai/gpt-6-luna", temperature=None, max_tokens=1500, extra=off, cache=cache,
19
19
  budget=budget, name="rewriter")
20
20
  news = PCS(TextClassification(["Fake", "Real"], NEWS_PROMPT, rewriter=rewriter), haiku)
21
21
  print(news.predict("Aliens landed in New York yesterday, officials confirmed."))
@@ -10,6 +10,6 @@
10
10
  from .core import Result, Weights, fit_joint, fit_single, majority, multi_predict, multi_scores, predict, scores
11
11
  from .pcs import PCS, Collected
12
12
 
13
- __version__ = "2.0.0"
13
+ __version__ = "2.1.0"
14
14
  __all__ = ["PCS", "Collected", "Result", "Weights", "fit_joint", "fit_single", "majority", "multi_predict",
15
15
  "multi_scores", "predict", "scores", "__version__"]
@@ -20,6 +20,7 @@ from .backends import OPENROUTER, Budget, Cache, OpenAICompatible
20
20
  from .core.weights import Weights
21
21
  from .pcs import PCS
22
22
  from .tasks import NEWS_PROMPT, SENTIMENT_PROMPT, BugLocalization, TextClassification, VulnClassification
23
+ from .transforms.text import PROMPT_SETS, REWRITER_MODEL
23
24
 
24
25
  PRESETS = {"news": (NEWS_PROMPT, ["Fake", "Real"]), "sentiment": (SENTIMENT_PROMPT, ["Positive", "Negative", "Neutral"])}
25
26
 
@@ -36,9 +37,11 @@ def build(a):
36
37
  labels = a.labels or labels
37
38
  if not prompt or not labels:
38
39
  sys.exit("text tasks need --preset, or --prompt and --labels")
39
- rewriter = OpenAICompatible(a.rewriter, base_url=a.base_url, api_key_env=a.key_env, temperature=0.2,
40
- max_tokens=800, extra=extra, cache=cache, budget=budget, name="rewriter")
41
- task = TextClassification(labels, prompt, rewriter=rewriter)
40
+ rw_extra = extra or ({"reasoning": {"enabled": False}} if a.base_url == OPENROUTER else {})
41
+ rewriter = OpenAICompatible(a.rewriter, base_url=a.base_url, api_key_env=a.key_env,
42
+ temperature=a.rewriter_temperature, max_tokens=a.rewriter_max_tokens,
43
+ extra=rw_extra, cache=cache, budget=budget, name="rewriter")
44
+ task = TextClassification(labels, prompt, rewriter=rewriter, mr_prompts=a.mr_prompts)
42
45
  elif a.task == "vuln":
43
46
  task = VulnClassification(braces_first=not a.swap_only, lang=a.lang)
44
47
  else:
@@ -74,7 +77,11 @@ def main(argv=None):
74
77
  p.add_argument("--preset", choices=list(PRESETS))
75
78
  p.add_argument("--prompt")
76
79
  p.add_argument("--labels", nargs="+")
77
- p.add_argument("--rewriter", default="meta-llama/llama-3.1-8b-instruct")
80
+ p.add_argument("--rewriter", default=REWRITER_MODEL, help="model that writes the text rewrites M1-M3")
81
+ p.add_argument("--rewriter-temperature", type=float, default=None, help="default: omitted (GPT-6 Luna)")
82
+ p.add_argument("--rewriter-max-tokens", type=int, default=1500)
83
+ p.add_argument("--mr-prompts", choices=list(PROMPT_SETS), default="default",
84
+ help="M1-M3 prompts: default, or original (version 2.0.0, with LLaMA-3.1-8B at temperature 0.2)")
78
85
  p.add_argument("--data", help="JSONL file")
79
86
  if name == "predict":
80
87
  p.add_argument("--input", help="a single input file (C function or text)")
@@ -40,16 +40,18 @@ def parse_label(raw: Optional[str], labels: Sequence[str]) -> Optional[str]:
40
40
  class TextClassification(ClassificationTask):
41
41
  """Label a text. ``prompt`` must contain {text} and ask for <label>...</label>.
42
42
 
43
- transforms: by default M1-M3 written by ``rewriter`` (the paper: LLaMA-3.1-8B-Instruct, temperature 0.2)."""
43
+ transforms: by default M1-M3 written by ``rewriter`` (recommended: GPT-6 Luna, see transforms.text.REWRITER_MODEL).
44
+ mr_prompts: "default" (the paper's prompts) or "original" (the prompts of version 2.0.0)."""
44
45
 
45
46
  name = "text_classification"
46
47
 
47
48
  def __init__(self, labels: Sequence[str], prompt: str, rewriter: Optional[Backend] = None,
48
- transforms: Optional[Sequence[Transform]] = None, system: Optional[str] = None):
49
+ transforms: Optional[Sequence[Transform]] = None, system: Optional[str] = None,
50
+ mr_prompts: str = "default"):
49
51
  if transforms is None:
50
52
  if rewriter is None:
51
53
  raise ValueError("give a rewriter backend for M1-M3, or your own transforms")
52
- transforms = text_transforms(rewriter)
54
+ transforms = text_transforms(rewriter, prompts=mr_prompts)
53
55
  if "{text}" not in prompt:
54
56
  raise ValueError("the prompt must contain {text}")
55
57
  super().__init__(labels, transforms)
@@ -1,7 +1,8 @@
1
1
  from .align import align_line, line_map, lines_of, numbered
2
2
  from .base import Identity, Transform
3
3
  from .code_c import CodeInput, CodeTransform, code_of, code_transforms
4
- from .text import LLMRewrite, rewrite_text, text_transforms
4
+ from .text import REWRITER_MODEL, REWRITER_SETTINGS, LLMRewrite, rewrite_text, text_transforms
5
5
 
6
6
  __all__ = ["align_line", "line_map", "lines_of", "numbered", "Identity", "Transform", "CodeInput", "CodeTransform",
7
- "code_of", "code_transforms", "LLMRewrite", "rewrite_text", "text_transforms"]
7
+ "code_of", "code_transforms", "LLMRewrite", "REWRITER_MODEL", "REWRITER_SETTINGS", "rewrite_text",
8
+ "text_transforms"]
@@ -0,0 +1,138 @@
1
+ """Linguistic metamorphic relations M1-M3 (paper Sec. 4.2).
2
+
3
+ The variants are written by a separate LLM, once per input, and reused for every annotating model. With a cached
4
+ backend, rewriting the same text again costs nothing. Recommended rewriter: ``REWRITER_MODEL`` with
5
+ ``REWRITER_SETTINGS`` (as in the paper's experiments). The prompts of version 2.0.0 are kept as
6
+ ``prompts="original"``.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ from typing import Optional
12
+
13
+ from ..backends.base import Backend
14
+ from .base import Transform
15
+
16
+ REWRITER_MODEL = "openai/gpt-6-luna"
17
+ REWRITER_SETTINGS = {"temperature": None, "max_tokens": 1500, "extra": {"reasoning": {"enabled": False}}}
18
+
19
+ # Default since 2.1.0: GPT-6 Luna (no temperature, reasoning off) with these prompts. Each prompt asks for an edit in
20
+ # every eligible sentence and lists the forms that keep the meaning; a judge model (Gemma 4 31B) found the meaning
21
+ # kept in 96% (M1), 84% (M2) and 98% (M3) of 50 rewrites each.
22
+ M1_VOICE = """Rewrite the text below so that some sentences change voice (active to passive, or passive to active), while the meaning stays exactly the same.
23
+
24
+ Rules:
25
+ 1. Change the voice of every eligible sentence; leave a sentence unchanged only if its voice cannot be changed. Copy everything else word for word.
26
+ 2. Only rearrange the words of those sentences. Do not replace words with other words.
27
+ 3. Keep every fact, person, number, date, title and the tense unchanged. Do not add or remove information.
28
+ 4. Leave headlines, questions and text inside quotation marks unchanged.
29
+
30
+ Example:
31
+ Original: The committee approved the plan.
32
+ Rewritten: The plan was approved by the committee.
33
+
34
+ Provide only the revised text, starting with the term “new text:”
35
+
36
+ Original Text:
37
+ {text}"""
38
+
39
+ M2_DOUBLE_NEGATION = """Rewrite the text below so that every eligible sentence gets one affirmative phrase turned into a double negation, while the meaning stays exactly the same. Copy everything else word for word.
40
+
41
+ A double negation has TWO negative parts that cancel out. Use only these safe forms:
42
+ A. "did not fail to" + verb: "met" -> "did not fail to meet"; "has kept" -> "has not failed to keep".
43
+ B. "not" + the exact opposite word: "won" -> "did not lose"; "is good" -> "is not bad"; "remembered" -> "did not forget"; "is true" -> "is not false".
44
+ C. "not" + the same word with a negative prefix (un-, in-, im-, dis-): "is possible" -> "is not impossible"; "is likely" -> "is not unlikely"; "agreed" -> "did not disagree".
45
+ If you are unsure that a word has an exact opposite, use form A (for verbs) or C (for adjectives).
46
+
47
+ Never do this:
48
+ - Add one "not" without an opposite word: "spared him" -> "did not spare him" reverses the meaning.
49
+ - Use a word that is only roughly opposite: "teased" -> "not concealed", "dragged into a stalemate" -> "not ended" change the meaning.
50
+
51
+ Self-check every change before you answer: remove both negative parts from your new phrase. You must get back exactly the original phrase. If not, undo the change and pick another phrase.
52
+
53
+ Rules:
54
+ 1. Change one phrase in every eligible sentence; leave a sentence unchanged only if no phrase in it fits form A or B. Always change at least one phrase; form A works for almost any past-tense verb.
55
+ 2. Keep all names, numbers, dates, titles and text inside quotation marks unchanged.
56
+ 3. Leave headlines, questions and sentences that are already negative unchanged.
57
+ 4. Do not add or remove information, sentences or comments.
58
+
59
+ Example:
60
+ Original: The team won the final. The coach praised the players, and the fans were happy.
61
+ Rewritten: The team did not lose the final. The coach did not fail to praise the players, and the fans were not unhappy.
62
+
63
+ Provide only the revised text, starting with the term “new text:”
64
+
65
+ Original Text:
66
+ {text}"""
67
+
68
+ M3_SYNONYM = """Rewrite the text below by replacing a few words with true synonyms, while the meaning stays exactly the same.
69
+
70
+ Rules:
71
+ 1. Replace one word in every eligible sentence; leave a sentence unchanged only if no word in it has a true synonym. Copy everything else word for word.
72
+ 2. Each replacement must be a true synonym that means exactly the same in that sentence.
73
+ 3. Never replace names, places, organisations, sports, products, numbers, dates or titles.
74
+ 4. Leave text inside quotation marks unchanged. Do not add or remove information.
75
+
76
+ Example:
77
+ Original: The company bought a large building.
78
+ Rewritten: The company purchased a big building.
79
+
80
+ Provide only the revised text, starting with the term “new text:”
81
+
82
+ Original Text:
83
+ {text}"""
84
+
85
+ PROMPTS = {"passive_active": M1_VOICE, "double_negation": M2_DOUBLE_NEGATION, "synonym": M3_SYNONYM}
86
+
87
+ # The prompts of toolbox 2.0.0 and the first paper version (LLaMA-3.1-8B-Instruct at temperature 0.2).
88
+ ORIGINAL_PROMPTS = {
89
+ "passive_active": (
90
+ "Review the text below and transform all sentences by converting active voice to passive voice and vice versa, "
91
+ "where appropriate.\nProvide only the revised text, starting with the term “new text:”\n\nOriginal Text:\n{text}"),
92
+ "double_negation": (
93
+ "Review the text below and transform affirmative sentences into double negation sentences. (Double negation "
94
+ "means using two negative elements within a clause or sentence, typically leading to a positive implication.) "
95
+ "Ensure that the transformations maintain equivalent meanings.\nProvide only the revised text, starting with "
96
+ "the term “new text:”\n\nOriginal Text:\n{text}"),
97
+ "synonym": (
98
+ "Review the text below and replace keywords with their synonyms. Ensure that the transformed sentences retain "
99
+ "equivalent meanings.\nProvide only the revised text, without extra information, starting with the term "
100
+ "”new text:”\n\nOriginal Text:\n{text}"),
101
+ }
102
+ PROMPT_SETS = {"default": PROMPTS, "original": ORIGINAL_PROMPTS}
103
+ PAPER_IDS = {"passive_active": "M1", "double_negation": "M2", "synonym": "M3"}
104
+
105
+
106
+ def rewrite_text(raw: Optional[str]) -> Optional[str]:
107
+ """The rewritten text in a rewriter reply: everything after 'new text:' (if present), whitespace collapsed."""
108
+ if not raw:
109
+ return None
110
+ m = re.search(r"new[ _]text\s*[:\-]", raw, re.I)
111
+ t = raw[m.end():] if m else raw
112
+ t = " ".join(t.strip().strip('"“”').split())
113
+ return t or None
114
+
115
+
116
+ class LLMRewrite(Transform):
117
+ """A text relation generated by an LLM. If the rewriter fails or returns nothing, the original text is used
118
+ (the version is then identical to the original, as for a code relation that does not apply)."""
119
+
120
+ def __init__(self, name: str, prompt: str, rewriter: Backend, paper_id: str = ""):
121
+ if "{text}" not in prompt:
122
+ raise ValueError("the prompt must contain {text}")
123
+ self.name, self.prompt, self.rewriter, self.paper_id = name, prompt, rewriter, paper_id
124
+
125
+ def apply(self, x: str) -> str:
126
+ r = self.rewriter.complete([{"role": "user", "content": self.prompt.format(text=x)}])
127
+ return rewrite_text(r.text) or x
128
+
129
+
130
+ def text_transforms(rewriter: Backend, include: Optional[list[str]] = None,
131
+ prompts: str = "default") -> list[LLMRewrite]:
132
+ """M1-M3. ``prompts``: "default" (the paper's experiments) or "original" (version 2.0.0). Add your own relations
133
+ with ``LLMRewrite(name, prompt, rewriter)``."""
134
+ if prompts not in PROMPT_SETS:
135
+ raise ValueError(f"prompts must be one of {list(PROMPT_SETS)}")
136
+ chosen = PROMPT_SETS[prompts]
137
+ names = include or list(chosen)
138
+ return [LLMRewrite(n, chosen[n], rewriter, PAPER_IDS.get(n, "")) for n in names]
@@ -4,14 +4,14 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "pcs-annotator"
7
- version = "2.0.0"
7
+ version = "2.1.0"
8
8
  description = "Perceived Confidence Scoring (PCS) for black-box LLMs on text classification, C/C++ vulnerability classification and C/C++ bug localization"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.10"
11
11
  license = "MIT"
12
12
  authors = [
13
- { name = "Anik Islam" },
14
13
  { name = "Sina Salimian" },
14
+ { name = "Anik Islam" },
15
15
  { name = "Gias Uddin" },
16
16
  { name = "Shaina Raza" },
17
17
  { name = "Henry Leung" },
@@ -43,6 +43,34 @@ class TestCLI(unittest.TestCase):
43
43
  self.assertEqual((r["prediction"], r["confidence"]), (None, 0.0)) # unreadable label -> confidence 0
44
44
  self.assertEqual(len(srv.requests), n_before) # same prompts: served from the cache
45
45
 
46
+ def test_text_rewriter_defaults(self):
47
+ srv = FakeServer()
48
+ out = self.run_cli("predict", "--task", "text", "--preset", "news", "--model", "m", "--base-url", srv.url,
49
+ "--key-env", "PCS_TEST_KEY", "--cache", "", "--input", str(self._text_file()))
50
+ srv.close()
51
+ self.assertEqual(json.loads(out.splitlines()[0])["prediction"], "Real")
52
+ rw = [r["body"] for r in srv.requests if r["body"]["model"] == "openai/gpt-6-luna"]
53
+ self.assertEqual(len(rw), 3) # M1-M3, once each
54
+ self.assertTrue(all("temperature" not in b and b["max_tokens"] == 1500 for b in rw))
55
+ self.assertIn("every eligible sentence", rw[0]["messages"][0]["content"])
56
+
57
+ def test_original_prompts_option(self):
58
+ srv = FakeServer()
59
+ self.run_cli("predict", "--task", "text", "--preset", "news", "--model", "m", "--base-url", srv.url,
60
+ "--key-env", "PCS_TEST_KEY", "--cache", "", "--input", str(self._text_file()),
61
+ "--mr-prompts", "original", "--rewriter", "meta-llama/llama-3.1-8b-instruct",
62
+ "--rewriter-temperature", "0.2", "--rewriter-max-tokens", "800")
63
+ srv.close()
64
+ rw = [r["body"] for r in srv.requests if r["body"]["model"] == "meta-llama/llama-3.1-8b-instruct"]
65
+ self.assertEqual(len(rw), 3)
66
+ self.assertTrue(all(b["temperature"] == 0.2 and b["max_tokens"] == 800 for b in rw))
67
+ self.assertTrue(rw[0]["messages"][0]["content"].startswith("Review the text below"))
68
+
69
+ def _text_file(self):
70
+ p = self.d / "t.txt"
71
+ p.write_text("The committee approved the plan.")
72
+ return p
73
+
46
74
 
47
75
  if __name__ == "__main__":
48
76
  unittest.main()
@@ -86,6 +86,16 @@ class TestTextTransforms(unittest.TestCase):
86
86
  empty = text_transforms(FunctionBackend(lambda m: None))
87
87
  self.assertEqual(empty[1].apply("x"), "x")
88
88
 
89
+ def test_prompt_sets(self):
90
+ from pcs_annotator.transforms.text import ORIGINAL_PROMPTS, PROMPTS
91
+ rw = FunctionBackend(lambda m: "new text: x")
92
+ self.assertEqual([t.prompt for t in text_transforms(rw)], list(PROMPTS.values()))
93
+ self.assertEqual([t.prompt for t in text_transforms(rw, prompts="original")], list(ORIGINAL_PROMPTS.values()))
94
+ self.assertTrue(all(p.count("{text}") == 1 and p.format(text="T").endswith("Original Text:\nT")
95
+ for p in [*PROMPTS.values(), *ORIGINAL_PROMPTS.values()]))
96
+ with self.assertRaises(ValueError):
97
+ text_transforms(rw, prompts="b3")
98
+
89
99
 
90
100
  @unittest.skipUnless((REPO / "pcs_experiment/juliet_locate_cwe/cases.parquet").exists(), "paper data not available")
91
101
  class TestPaperParity(unittest.TestCase):
@@ -1,58 +0,0 @@
1
- """Linguistic metamorphic relations M1-M3 (paper Sec. 4.2, Appendix A.1, prompts B.1-B.3).
2
-
3
- The variants are written by a separate LLM (the paper: LLaMA-3.1-8B-Instruct at temperature 0.2), once per input,
4
- and reused for every annotating model. With a cached backend, rewriting the same text again costs nothing.
5
- """
6
- from __future__ import annotations
7
-
8
- import re
9
- from typing import Optional
10
-
11
- from ..backends.base import Backend
12
- from .base import Transform
13
-
14
- PROMPTS = {
15
- "passive_active": (
16
- "Review the text below and transform all sentences by converting active voice to passive voice and vice versa, "
17
- "where appropriate.\nProvide only the revised text, starting with the term “new text:”\n\nOriginal Text:\n{text}"),
18
- "double_negation": (
19
- "Review the text below and transform affirmative sentences into double negation sentences. (Double negation "
20
- "means using two negative elements within a clause or sentence, typically leading to a positive implication.) "
21
- "Ensure that the transformations maintain equivalent meanings.\nProvide only the revised text, starting with "
22
- "the term “new text:”\n\nOriginal Text:\n{text}"),
23
- "synonym": (
24
- "Review the text below and replace keywords with their synonyms. Ensure that the transformed sentences retain "
25
- "equivalent meanings.\nProvide only the revised text, without extra information, starting with the term "
26
- "”new text:”\n\nOriginal Text:\n{text}"),
27
- }
28
- PAPER_IDS = {"passive_active": "M1", "double_negation": "M2", "synonym": "M3"}
29
-
30
-
31
- def rewrite_text(raw: Optional[str]) -> Optional[str]:
32
- """The rewritten text in a rewriter reply: everything after 'new text:' (if present), whitespace collapsed."""
33
- if not raw:
34
- return None
35
- m = re.search(r"new[ _]text\s*[:\-]", raw, re.I)
36
- t = raw[m.end():] if m else raw
37
- t = " ".join(t.strip().strip('"“”').split())
38
- return t or None
39
-
40
-
41
- class LLMRewrite(Transform):
42
- """A text relation generated by an LLM. If the rewriter fails or returns nothing, the original text is used
43
- (the version is then identical to the original, as for a code relation that does not apply)."""
44
-
45
- def __init__(self, name: str, prompt: str, rewriter: Backend, paper_id: str = ""):
46
- if "{text}" not in prompt:
47
- raise ValueError("the prompt must contain {text}")
48
- self.name, self.prompt, self.rewriter, self.paper_id = name, prompt, rewriter, paper_id
49
-
50
- def apply(self, x: str) -> str:
51
- r = self.rewriter.complete([{"role": "user", "content": self.prompt.format(text=x)}])
52
- return rewrite_text(r.text) or x
53
-
54
-
55
- def text_transforms(rewriter: Backend, include: Optional[list[str]] = None) -> list[LLMRewrite]:
56
- """M1-M3 with the paper's prompts. Add your own relations with ``LLMRewrite(name, prompt, rewriter)``."""
57
- names = include or list(PROMPTS)
58
- return [LLMRewrite(n, PROMPTS[n], rewriter, PAPER_IDS.get(n, "")) for n in names]
File without changes
File without changes