llmvalidate 1.3.0__tar.gz → 1.3.1__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: llmvalidate
3
- Version: 1.3.0
3
+ Version: 1.3.1
4
4
  Summary: Oncoshot LLM validation framework
5
5
  License: MIT
6
6
  Project-URL: Homepage, https://github.com/Oncoshot/llm-validation-framework
@@ -480,7 +480,10 @@ llm-validation-framework/
480
480
  |-------|----------|
481
481
  | **"Cannot infer fields"** | Ensure DataFrame has both `{Field}` and `Res: {Field}` columns when `structure_callback=None` |
482
482
  | **"Missing fields"** | Verify `fields` parameter contains column names that exist in your DataFrame |
483
+ | **"have no result column to score"** / **"were not scored"** | Make `structure_callback` return a key named exactly as each field in `fields` (or score the field in a `comparison_callback`), or remove the field from `fields` |
484
+ | **"source_df has no rows"** | Pass a DataFrame with at least one case; the message names the fields that have no rows to score |
483
485
  | **"Duplicate index"** | Use `df.reset_index(drop=True)` or ensure your DataFrame index has unique values |
486
+ | **"Please remove duplicate column names"** | Rename or drop the columns named in the message so every column name is unique |
484
487
  | **Import/dependency errors** | Run `pip install -r requirements.txt` and verify Python 3.11+ |
485
488
  | **Slow performance** | Enable parallel processing with `max_workers=None` and `use_threads=True` for LLM API calls |
486
489
 
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "llmvalidate"
7
- version = "1.3.0"
7
+ version = "1.3.1"
8
8
  description = "Oncoshot LLM validation framework"
9
9
  readme = "readme.md"
10
10
  requires-python = ">=3.11"
@@ -456,7 +456,10 @@ llm-validation-framework/
456
456
  |-------|----------|
457
457
  | **"Cannot infer fields"** | Ensure DataFrame has both `{Field}` and `Res: {Field}` columns when `structure_callback=None` |
458
458
  | **"Missing fields"** | Verify `fields` parameter contains column names that exist in your DataFrame |
459
+ | **"have no result column to score"** / **"were not scored"** | Make `structure_callback` return a key named exactly as each field in `fields` (or score the field in a `comparison_callback`), or remove the field from `fields` |
460
+ | **"source_df has no rows"** | Pass a DataFrame with at least one case; the message names the fields that have no rows to score |
459
461
  | **"Duplicate index"** | Use `df.reset_index(drop=True)` or ensure your DataFrame index has unique values |
462
+ | **"Please remove duplicate column names"** | Rename or drop the columns named in the message so every column name is unique |
460
463
  | **Import/dependency errors** | Run `pip install -r requirements.txt` and verify Python 3.11+ |
461
464
  | **Slow performance** | Enable parallel processing with `max_workers=None` and `use_threads=True` for LLM API calls |
462
465
 
@@ -1,7 +1,7 @@
1
1
  # Managed by python-semantic-release — do not edit by hand; the release workflow rewrites
2
2
  # this line. Set to 0.7.0 once by hand to clear the drift from ONC-12379, during which the
3
3
  # release never reached this file and it stayed at 0.0.0 across every published version.
4
- __version__ = "1.3.0"
4
+ __version__ = "1.3.1"
5
5
 
6
6
  # `structured` is pydantic-only and cheap, so it is imported eagerly: consumers that
7
7
  # only need the extraction contract (StructuredResult / StructuredField) get it without
@@ -64,6 +64,28 @@ def calculate_binary_metrics(TP, FP, FN, TN):
64
64
 
65
65
  return precision, recall, f1_score, f2_score, accuracy, specificity
66
66
 
67
+ def _raise_on_duplicate_columns(df):
68
+ """Raises ValueError naming the column names 'df' has more than once.
69
+
70
+ A row is scored by column name, so with a name used twice there is no telling which of
71
+ the columns a label, a result or a count belongs to.
72
+ """
73
+ duplicated = df.columns[df.columns.duplicated()].unique().tolist()
74
+ if duplicated:
75
+ raise ValueError(f"Please remove duplicate column names: {duplicated}")
76
+
77
+
78
+ def _row_cells(row):
79
+ """The cells of 'row' by column, each value exactly as the row holds it.
80
+
81
+ A NumPy scalar stays the NumPy scalar it is (`row.to_dict()` would turn it into a Python
82
+ number): `np.float32(0.1)` equals the prediction `0.1`, while the Python float it
83
+ converts to, `0.10000000149011612`, does not. A missing value likewise stays the
84
+ `pd.NA`, NaN or None it is.
85
+ """
86
+ return dict(zip(row.index, row.array))
87
+
88
+
67
89
  def compare_results_all(df, fields, hierarchy={}, comparison_callback=None, raw_text_column_name: str = "raw_text"):
68
90
  """ For each case from df calls and for each field from 'fields' compares results with 'Res: '+field
69
91
  and adds columns 'Inc: '+field, 'Cor: '+field, 'Mis: '+field, 'Spu: '+field, 'Par: '+field
@@ -83,8 +105,15 @@ def compare_results_all(df, fields, hierarchy={}, comparison_callback=None, raw_
83
105
  'Spu: ' for Spurious
84
106
  'Par: ' for Partial (only when the field has a hierarchy entry)
85
107
  'TN: ' for True Negative (scalar fields only; not defined for list fields)
108
+ A count that is not defined for a case (the case has no label for the field) is NaN,
109
+ and so is a per-case score with nothing to divide by; the '... items' cell of such
110
+ a case is None.
111
+
112
+ Raises ValueError if 'df' has duplicate column names.
86
113
  """
87
114
 
115
+ _raise_on_duplicate_columns(df)
116
+
88
117
  fields = [f for f in fields if f in df] #ignore fields which are not in columns (they may be added later by comparison_callback)
89
118
 
90
119
  # hierarchy is a per-field map {field: {child: parent}}; fail fast with a clear
@@ -117,14 +146,19 @@ def compare_results_all(df, fields, hierarchy={}, comparison_callback=None, raw_
117
146
  modified_rows = []
118
147
  # Iterate over the rows of the DataFrame
119
148
  for i, row in df.iterrows():
149
+ # The cells of the row by column: the input cells, then every derived cell in the
150
+ # order it is first set. They are collected in a dict and the row is built from it
151
+ # once: a dict takes a new key in constant time, where a pandas Series is rebuilt,
152
+ # so the cost of a cell does not depend on how wide the row is.
153
+ cells = _row_cells(row)
120
154
 
121
155
  for field in fields:
122
- expected = row[field]
156
+ expected = cells[field]
123
157
 
124
- if 'Res: ' + field not in row:
158
+ if 'Res: ' + field not in cells:
125
159
  continue
126
160
 
127
- actual = row['Res: ' + field]
161
+ actual = cells['Res: ' + field]
128
162
 
129
163
  # Shape already validated up front; None/missing -> no hierarchy for this field.
130
164
  field_hierarchy = hierarchy.get(field) or {}
@@ -147,10 +181,10 @@ def compare_results_all(df, fields, hierarchy={}, comparison_callback=None, raw_
147
181
  res['Correct'], res['Partial'], res['Incorrect'], res['Spurious'], res['Missing'], TN_case
148
182
  )
149
183
 
150
- row['Precision: ' + field] = precision
151
- row['Recall: ' + field] = recall
152
- row['F1 score: ' + field] = f1_score
153
- row['F2 score: ' + field] = f2_score
184
+ cells['Precision: ' + field] = precision
185
+ cells['Recall: ' + field] = recall
186
+ cells['F1 score: ' + field] = f1_score
187
+ cells['F2 score: ' + field] = f2_score
154
188
 
155
189
  if not field_hierarchy:
156
190
  #we don't want useless columns if no hierarchy for this field anyway
@@ -169,12 +203,12 @@ def compare_results_all(df, fields, hierarchy={}, comparison_callback=None, raw_
169
203
  # None (undefined) when the case was not labeled for this field.
170
204
  # TN is not defined for list fields (see get_metrics).
171
205
  if res['Correct'] is None:
172
- row['TN: ' + field] = None
206
+ cells['TN: ' + field] = np.nan
173
207
  #row['TN: ' + field + ' items'] = None
174
208
  else:
175
209
  TN_case = 1 if (is_scalar_empty(normalize(expected))
176
210
  and is_scalar_empty(normalize(actual))) else 0
177
- row['TN: ' + field] = TN_case
211
+ cells['TN: ' + field] = TN_case
178
212
  # a TN case has no extracted item: the matched "item" is the
179
213
  # no-information marker itself therefore pointless to add
180
214
  # row['TN: ' + field + ' items'] = ['-'] if TN_case else []
@@ -182,14 +216,22 @@ def compare_results_all(df, fields, hierarchy={}, comparison_callback=None, raw_
182
216
  # Iterate over the key-value pairs in the result dictionary
183
217
  for key, value in res.items():
184
218
  # Create a new column in the DataFrame using the key
185
- # Assign the corresponding value to the column
186
- row[key[:3] + ': ' + field] = value
219
+ # Assign the corresponding value to the column. An undefined count is stored
220
+ # as NaN, so that arithmetic and comparisons on it in a comparison_callback
221
+ # give NaN and False where None would raise.
222
+ cells[key[:3] + ': ' + field] = np.nan if value is None else value
187
223
 
188
224
  # Iterate over the key-value pairs in the result items dictionary
189
225
  for key, value in res_items.items():
190
226
  # Create a new column in the DataFrame using the key
191
227
  # Assign the corresponding value to the column
192
- row[key[:3] + ': ' + field + ' items'] = value
228
+ cells[key[:3] + ': ' + field + ' items'] = value
229
+
230
+ # The callback gets the finished row: the input columns followed by every cell
231
+ # derived above, each value as it was read or set (an input cell keeps its type, a
232
+ # count stays an int whatever else the row holds). It may read it, overwrite cells
233
+ # and add its own.
234
+ row = pd.Series(cells, dtype=object, name=i)
193
235
 
194
236
  if comparison_callback:
195
237
  comparison_callback(row, i, raw_text_column_name)
@@ -286,6 +328,21 @@ def _confidence_column(field, columns):
286
328
  return None
287
329
 
288
330
 
331
+ def _fields_without_scores(columns, fields):
332
+ """Fields from 'fields' that `get_metrics` cannot aggregate from 'columns'.
333
+
334
+ `get_metrics` reads a field's counts unguarded: 'TP: ', 'FP: ' and 'FN: ' when a
335
+ 'TP: ' column exists for it, otherwise 'Cor: ', 'Mis: ' and 'Spu: '. A field lacking
336
+ any column of its set has not been scored.
337
+ """
338
+ unscored = []
339
+ for field in fields:
340
+ prefixes = ('TP: ', 'FP: ', 'FN: ') if 'TP: ' + field in columns else ('Cor: ', 'Mis: ', 'Spu: ')
341
+ if any(prefix + field not in columns for prefix in prefixes):
342
+ unscored.append(field)
343
+ return unscored
344
+
345
+
289
346
  def get_metrics(res_df, fields):
290
347
  """ For results dataframe generated by validate
291
348
  produces dataframe with metrics for all available confidence levels and overall
@@ -898,6 +955,10 @@ def validate(source_df, fields, structure_callback, output_folder=None, drop_col
898
955
 
899
956
  - **comparison_callback (callable, optional)**:
900
957
  A callback function that will be applied to each row to generate comparison results.
958
+ It receives the row after the built-in scoring and may score a field itself by
959
+ writing that field's ``TP:``/``FP:``/``FN:`` (or ``Cor:``/``Mis:``/``Spu:``) counts
960
+ onto the row. On the row it receives, a built-in count that is not defined for the
961
+ case (no label for the field) is NaN, and the matching ``... items`` cell is None.
901
962
 
902
963
  - **hierarchy (dict, optional)**:
903
964
  A PER-FIELD nested map ``{field: {child: parent}}`` enabling partial (hierarchical)
@@ -924,6 +985,29 @@ def validate(source_df, fields, structure_callback, output_folder=None, drop_col
924
985
  - The **results** DataFrame with row-level details.
925
986
  - The **metrics** DataFrame with aggregated performance statistics.
926
987
 
988
+ ### Raises:
989
+ - **ValueError** when a scored field cannot be scored, naming every such field instead
990
+ of a bare ``KeyError`` raised later from inside ``get_metrics``. A field is scored
991
+ either by the built-in comparison, which needs its ``Res: <field>`` column, or by the
992
+ ``comparison_callback`` writing its counts. So:
993
+ - with ``comparison_callback=None``, every field must have a ``Res: <field>`` column
994
+ once the structuring pass is done: ``structure_callback`` must return a key named
995
+ exactly as the field for at least one row, and the column must not be listed in
996
+ ``drop_columns``. This is reported before the comparison runs;
997
+ - with a ``comparison_callback``, a field with no ``Res: <field>`` column is accepted
998
+ as long as the callback writes its counts, so this is reported after the
999
+ comparison, for the fields that still have none.
1000
+ A field whose result is returned for some rows only has a ``Res: <field>`` column and
1001
+ is scored: the rows without a result count as an empty prediction.
1002
+ - **ValueError** / **TypeError** for the input mistakes described under the parameters
1003
+ above (duplicate index values, missing label or result columns, ``derived_fields``
1004
+ misuse).
1005
+ - **ValueError** naming the fields when ``source_df`` has no rows, so that none of them
1006
+ has a row to score. It is raised after the checks on columns and fields above, and
1007
+ before ``structure_callback`` is called or any file is written.
1008
+ - **ValueError** naming the duplicated names when ``source_df`` has duplicate column
1009
+ names, or when the structuring pass leaves the results with any.
1010
+
927
1011
  ### Notes:
928
1012
  - The output CSV files are saved with filenames prefixed by the current timestamp to avoid overwriting previous runs.
929
1013
  - The source df should have index with unique values for proper processing.
@@ -932,6 +1016,8 @@ def validate(source_df, fields, structure_callback, output_folder=None, drop_col
932
1016
  if source_df.index.has_duplicates:
933
1017
  raise ValueError("Please remove duplicate values in index column")
934
1018
 
1019
+ _raise_on_duplicate_columns(source_df)
1020
+
935
1021
  # derived_fields is a collection of field names, so a bare string is a caller mistake:
936
1022
  # it would iterate into single characters ('spans' -> 's', 'p', 'a', ...) and silently
937
1023
  # exempt names nobody declared. Fail fast with a clear message, the same way the
@@ -988,6 +1074,13 @@ def validate(source_df, fields, structure_callback, output_folder=None, drop_col
988
1074
  if missing_res_columns:
989
1075
  raise ValueError(f"When structure_callback is None, the following result columns must be present in source_df: {missing_res_columns}")
990
1076
 
1077
+ # With no rows there is nothing to structure and nothing to score. Reported here, after
1078
+ # the checks on columns and fields and before anything is run or written.
1079
+ if len(source_df) == 0 and len(fields) > 0:
1080
+ raise ValueError(
1081
+ f"source_df has no rows, so the following fields have no rows to score: {list(fields)}"
1082
+ )
1083
+
991
1084
  if output_folder:
992
1085
  os.makedirs(output_folder, exist_ok=True)
993
1086
 
@@ -1007,7 +1100,26 @@ def validate(source_df, fields, structure_callback, output_folder=None, drop_col
1007
1100
  # Save results
1008
1101
  if output_folder:
1009
1102
  res_df.to_csv(os.path.join(output_folder, f"{file_prefix} results.csv"))
1010
-
1103
+
1104
+ # Without a comparison_callback the built-in comparison is the only thing that scores a
1105
+ # field, and it skips a field that has no 'Res: ' column. Such a field is already known
1106
+ # here to end up without counts, so report it before the comparison runs. The results
1107
+ # saved just above stay on disk to show what the structuring pass did return.
1108
+ if comparison_callback is None:
1109
+ fields_without_result = [
1110
+ field for field in _fields_without_scores(res_df.columns, fields)
1111
+ if field not in res_df.columns or 'Res: ' + field not in res_df.columns
1112
+ ]
1113
+ if fields_without_result:
1114
+ raise ValueError(
1115
+ f"The following fields have no result column to score: {fields_without_result}. "
1116
+ "Each scored field needs a 'Res: <field>' column: structure_callback must "
1117
+ "return a key named exactly as the field for at least one row (if every row "
1118
+ "failed, see the 'Sys: exception' column) and the column must not be listed "
1119
+ "in drop_columns. Otherwise remove the field from fields, or score it in a "
1120
+ "comparison_callback"
1121
+ )
1122
+
1011
1123
  ###################################
1012
1124
  # Analyse the results and calculate the metrics
1013
1125
  res_df = compare_results_all(res_df, fields, hierarchy=hierarchy, comparison_callback=comparison_callback, raw_text_column_name=raw_text_column_name)
@@ -1023,6 +1135,20 @@ def validate(source_df, fields, structure_callback, output_folder=None, drop_col
1023
1135
  "check because comparison_callback was expected to create them during scoring"
1024
1136
  )
1025
1137
 
1138
+ # A comparison_callback may score a field itself, so a field with no 'Res: ' column is
1139
+ # only known to be unscored once the callback has run on every row. Report it here:
1140
+ # get_metrics reads the counts unguarded, so an unscored field would otherwise surface
1141
+ # as a bare `KeyError: 'Cor: <field>'` from deep inside it.
1142
+ unscored_fields = _fields_without_scores(res_df.columns, fields)
1143
+ if unscored_fields:
1144
+ raise ValueError(
1145
+ f"The following fields were not scored: {unscored_fields}. A field is scored "
1146
+ "from its 'Res: <field>' column, which structure_callback creates by "
1147
+ "returning a key named exactly as the field, or by a comparison_callback "
1148
+ "that writes its 'TP: '/'FP: '/'FN: ' (or 'Cor: '/'Mis: '/'Spu: ') counts "
1149
+ "onto the row. Provide one of the two, or remove the field from fields"
1150
+ )
1151
+
1026
1152
  # Save results
1027
1153
  if output_folder:
1028
1154
  res_df.to_csv(os.path.join(output_folder, f"{file_prefix} results.csv"))
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: llmvalidate
3
- Version: 1.3.0
3
+ Version: 1.3.1
4
4
  Summary: Oncoshot LLM validation framework
5
5
  License: MIT
6
6
  Project-URL: Homepage, https://github.com/Oncoshot/llm-validation-framework
@@ -480,7 +480,10 @@ llm-validation-framework/
480
480
  |-------|----------|
481
481
  | **"Cannot infer fields"** | Ensure DataFrame has both `{Field}` and `Res: {Field}` columns when `structure_callback=None` |
482
482
  | **"Missing fields"** | Verify `fields` parameter contains column names that exist in your DataFrame |
483
+ | **"have no result column to score"** / **"were not scored"** | Make `structure_callback` return a key named exactly as each field in `fields` (or score the field in a `comparison_callback`), or remove the field from `fields` |
484
+ | **"source_df has no rows"** | Pass a DataFrame with at least one case; the message names the fields that have no rows to score |
483
485
  | **"Duplicate index"** | Use `df.reset_index(drop=True)` or ensure your DataFrame index has unique values |
486
+ | **"Please remove duplicate column names"** | Rename or drop the columns named in the message so every column name is unique |
484
487
  | **Import/dependency errors** | Run `pip install -r requirements.txt` and verify Python 3.11+ |
485
488
  | **Slow performance** | Enable parallel processing with `max_workers=None` and `use_threads=True` for LLM API calls |
486
489
 
File without changes
File without changes