Spaces:
Running
Running
File size: 14,661 Bytes
599f646 e23b66d 599f646 5db7074 599f646 ae7d3b8 599f646 ae7d3b8 599f646 ae7d3b8 599f646 5db7074 599f646 5db7074 599f646 5db7074 599f646 5db7074 599f646 5db7074 599f646 5db7074 599f646 5db7074 599f646 5db7074 599f646 5db7074 599f646 5db7074 4d12df4 5db7074 ba53458 5db7074 599f646 5db7074 599f646 5db7074 599f646 5db7074 599f646 5db7074 599f646 5db7074 599f646 5db7074 599f646 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 |
/**
*
* Copyright 2023-2025 InspectorRAGet Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**/
import { countBy, isNumber } from 'lodash';
import { Metric, MetricValue } from '@/src/types';
export const MetricDefinitions = {
coherence: 'The response is coherent, natural, and not dismissive.',
naturalness: 'The response is coherent, natural, and not dismissive.',
specificity:
'The response provides appropriate amount of useful information.',
appropriateness:
'The response provides appropriate amount of useful information.',
faithfulness: 'The response is faithful and grounded on the context.',
feedback:
"Annotator's comments about quality of response, potential issues etc.",
};
export const AgreementLevels = {
ABSOLUTE_AGREEMENT: 3,
HIGH_AGREEMENT: 2,
LOW_AGREEMENT: 1,
NO_AGREEMENT: 0,
};
export const AgreementLevelDefinitions = {
Absolute: 'All annotators selected a same value for a given metric.',
High: 'Majority of annotators selected a same value for a given metric and the most common value and the 2nd most common value were less that 2 units apart.',
Low: 'Majority of annotators selected a same value for a given metric.',
No: 'Majority of annotators selected different values for a given metric.',
};
export function extractMetricDisplayValue(
value: string | number,
references?: MetricValue[],
): string {
// If value is of type "string"
if (typeof value === 'string') {
// Step 1: Check if references are provided to convert "string" value to "numeric" value
if (references) {
// Step 1.a: Find appropriate reference by comparing "string" values
const reference = references.find((entry) => entry.value === value);
// Step 1.b: If numeric value exists in reference, then return it
if (reference && reference.displayValue) {
return reference.displayValue;
} else {
return value;
}
} else {
return value;
}
} else {
// Value is of type "number"
return parseFloat(value.toFixed(2)).toString();
}
}
export function extractMetricDisplayName(metric: Metric): string {
return metric.displayName
? metric.displayName
: metric.name.charAt(0).toUpperCase() + metric.name.slice(1).toLowerCase();
}
/**
* Converts numeric value to metric value using references in case of 'categorical' metrics
* @param value numeric value to convert
* @param references reference metric values
* @returns metric value
*/
export function castToValue(
value: number,
references?: MetricValue[],
): string | number {
// Step 1: Check if references are provided to convert "numeric" value to "string" value
if (references) {
// Step 1.a: Find appropriate reference by comparing "string" values
const reference = references.find((entry) => entry.numericValue === value);
// Step 1.b: If value exists in reference, then return it
if (reference && reference.value) {
return reference.value;
} else {
return value;
}
}
// Default return
return value;
}
export function castToNumber(
value: string | number,
references?: MetricValue[],
key?: 'value' | 'displayValue',
): number {
// If value is of type "string"
if (typeof value === 'string') {
// Step 1: Check if references are provided to convert "string" value to "numeric" value
if (references) {
// Step 1.a: Find appropriate reference by comparing "string" values
const reference = references.find((entry) =>
key ? entry[key] === value : entry.value === value,
);
// Step 1.b: If numeric value exists in reference, then return it
if (
reference &&
reference.hasOwnProperty('numericValue') &&
typeof reference.numericValue === 'number'
) {
return reference.numericValue;
} else {
return parseFloat(value);
}
}
// Step 2: Cast to int, if references are absent
else if (value === 'N/A' || value === '') {
return 0;
} else {
return parseFloat(value);
}
}
// Value is of type "number"
else {
return value;
}
}
/**
* Compute mean value
* @param metric metric under consideration
* @param scores distribution of values
* @returns
*/
function computeMean(
metric: Metric,
scores: string[] | number[],
): { level: number; value: number | string } {
// Step 1: Create counter
const counter: { [key: string]: number } = countBy(scores);
// Step 2: Sort counter values
const sorted_counter = Object.entries(counter);
sorted_counter.sort((x, y) => {
return y[1] - x[1];
});
// Step 3: Number of unique values, most common value and its count
const numberOfUniqueValues = sorted_counter.length;
const mostCommonValueCount = sorted_counter[0][1];
// Step 4: Calculate mean
let sum: number = 0;
for (const [value, count] of Object.entries(counter)) {
sum +=
(typeof value === 'string' ? castToNumber(value, metric.values) : value) *
count;
}
const mean = Math.round((sum / scores.length + Number.EPSILON) * 100) / 100;
// Step 5: Common patterns
// Step 5.a: Absolute agreement
if (mostCommonValueCount === scores.length)
return {
level: AgreementLevels.ABSOLUTE_AGREEMENT,
value: mean,
};
// Step 5.b: Absolute disagreement/No agreement
if (numberOfUniqueValues === scores.length)
return {
level: AgreementLevels.NO_AGREEMENT,
value: mean,
};
// Step 6: Default return
return {
level: AgreementLevels.HIGH_AGREEMENT,
value: mean,
};
}
/**
* Compute median value
* @param metric metric under consideration
* @param counter distribution of values
* @returns
*/
function computeMedian(
metric: Metric,
scores: string[] | number[],
): { level: number; value: number | string } {
// Step 1: Create counter
const counter: { [key: string]: number } = countBy(scores);
// Step 2: Sort counter values
const sorted_counter = Object.entries(counter);
sorted_counter.sort((x, y) => {
return y[1] - x[1];
});
// Step 3: Number of unique values, most common value and its count
const numberOfUniqueValues = sorted_counter.length;
const mostCommonValueCount = sorted_counter[0][1];
// Step 4: Cast score to numbers
const numericScores = scores.map((score) =>
typeof score === 'string' ? castToNumber(score, metric.values) : score,
);
// Step 5: Sort the numeric scores
const sortedNumericScores = numericScores.toSorted((a, b) => a - b);
// Step 6: Calculate median
const median =
sortedNumericScores.length % 2 == 0
? sortedNumericScores[sortedNumericScores.length / 2 - 1]
: sortedNumericScores[(sortedNumericScores.length + 1) / 2 - 1];
// Step 7: Common patterns
// Step 7.a: Absolute agreement
if (mostCommonValueCount === scores.length)
return {
level: AgreementLevels.ABSOLUTE_AGREEMENT,
value: castToValue(median, metric.values),
};
// Step 7.b: Absolute disagreement/No agreement
if (numberOfUniqueValues === scores.length)
return {
level: AgreementLevels.NO_AGREEMENT,
value: castToValue(median, metric.values),
};
// Step 8: Default return
return {
level: AgreementLevels.HIGH_AGREEMENT,
value: castToValue(median, metric.values),
};
}
/**
* Compute majority value
* @param metric metric under consideration
* @param counter distribution of values
* @param numberOfAnnotators number of annotators
* @returns
*/
function computeMajority(
metric: Metric,
counter: { [key: string]: number },
numberOfAnnotators: number,
): { level: number; value: number | string } {
// Step 0: Sort counter values
const sorted_counter = Object.entries(counter);
sorted_counter.sort((x, y) => {
return y[1] - x[1];
});
// Step 1: Number of unique values, most common value and its count
const numberOfUniqueValues = sorted_counter.length;
const mostCommonValue = sorted_counter[0][0];
const mostCommonValueCount = sorted_counter[0][1];
// Step 2: Common patterns
// Step 2.a: Absolute agreement
if (mostCommonValueCount === numberOfAnnotators)
return {
level: AgreementLevels.ABSOLUTE_AGREEMENT,
value: mostCommonValue,
};
// Step 2.b: Absolute disagreement/No agreement
if (numberOfUniqueValues === numberOfAnnotators)
return {
level: AgreementLevels.NO_AGREEMENT,
value: 'Indeterminate',
};
// Step 3: Calculate agreement levels
// Step 3.a: No agreement
// * More than half annotators selected different values
// OR
// * Less than half annotators selected same value and Top-2 most common values are greater than 1 unit apart
if (
numberOfUniqueValues > Math.ceil(numberOfAnnotators / 2) ||
(mostCommonValueCount < Math.ceil(numberOfAnnotators / 2) &&
numberOfUniqueValues === Math.ceil(numberOfAnnotators / 2) &&
Math.abs(
castToNumber(mostCommonValue, metric.values) -
castToNumber(sorted_counter[1][0], metric.values),
) > 1)
) {
return {
level: AgreementLevels.NO_AGREEMENT,
value: 'Indeterminate',
};
}
// Step 3.b: High agreement
// * Maximum two unique values and those are less than 2 unit apart
if (
numberOfUniqueValues == 2 &&
Math.abs(
castToNumber(mostCommonValue, metric.values) -
castToNumber(sorted_counter[1][0], metric.values),
) < 2
) {
return {
level: AgreementLevels.HIGH_AGREEMENT,
value: mostCommonValue,
};
}
// Step 3.c: Default return
return {
level: AgreementLevels.LOW_AGREEMENT,
value: mostCommonValue,
};
}
export function calculateAggregateValue(
metric: Metric,
entries: { [key: string]: any },
) {
if (metric.author === 'algorithm') {
if (metric.aggregator) {
let scores: string[] | number[] = Object.values(entries).map(
(entry) => entry.value,
);
if (metric.aggregator === 'average' || metric.aggregator === 'mean') {
return computeMean(metric, scores);
} else if (metric.aggregator === 'median') {
return computeMedian(metric, scores);
} else {
return computeMajority(metric, countBy(scores), scores.length);
}
} else {
return {
level: AgreementLevels.NO_AGREEMENT,
value: undefined,
};
}
} else {
if (metric.aggregator) {
let scores: string[] | number[] = Object.values(entries).map(
(entry) => entry.value,
);
if (metric.aggregator === 'average' || metric.aggregator === 'mean') {
return computeMean(metric, scores);
} else if (metric.aggregator === 'median') {
return computeMedian(metric, scores);
} else {
return computeMajority(metric, countBy(scores), scores.length);
}
} else {
return {
level: AgreementLevels.NO_AGREEMENT,
value: undefined,
};
}
}
}
export function mergeAgreementObjects({
source,
target,
}: {
source: object;
target: object;
}) {
if (source) {
Object.entries(source).forEach(([group, entry]) => {
for (const [key, value] of Object.entries(entry)) {
if (target.hasOwnProperty(group)) {
if (target[group].hasOwnProperty(key)) {
target[group][key] += value;
} else {
target[group][key] = value;
}
} else {
target[group] = { [key]: value };
}
}
});
}
}
export function bin(value: number | string, metric: Metric, n?: number) {
if (typeof value === 'number' && metric.type === 'numerical') {
if (metric.range && metric.range.length == 3) {
for (
let idx: number = 0;
metric.range[0] + idx * metric.range[2] + metric.range[2] <=
metric.range[1];
idx++
) {
const start: number = parseFloat(
(metric.range[0] + idx * metric.range[2]).toFixed(2),
);
const end: number = parseFloat(
(metric.range[0] + idx * metric.range[2] + metric.range[2]).toFixed(
2,
),
);
if (start <= value && value <= end) {
return `${start}-${end}`;
}
}
}
}
return value;
}
export function compareMetricAggregatedValues(
a: { key: string | number; value: number },
b: { key: string | number; value: number },
metric: Metric,
): number {
if (metric.aggregator && metric.aggregator === 'average') {
if (typeof a.key === 'number' && typeof b.key === 'number') {
return a.key - b.key;
} else if (typeof a.key === 'string' && typeof b.key === 'string') {
return parseFloat(a.key) - parseFloat(b.key);
} else {
return 0;
}
} else if (metric.aggregator && metric.aggregator === 'majority') {
if (typeof a.key === 'string' && typeof b.key === 'string') {
if (a.key === 'Indeterminate' || b.key === 'Indeterminate') {
if (b.key === 'Indeterminate' && a.key != 'Indeterminate') {
return 1;
} else if (a.key === 'Indeterminate' && b.key != 'Indeterminate') {
return -1;
}
return 0;
}
const aValue = metric.values?.find((entry) => entry.value == a.key);
const bValue = metric.values?.find((entry) => entry.value == b.key);
if (aValue && bValue) {
// Do direct value comparison in numerical values exists
if (
(aValue.numericValue != undefined || aValue.numericValue != null) &&
isNumber(aValue.numericValue) &&
(bValue.numericValue != undefined || bValue.numericValue != null) &&
isNumber(bValue.numericValue)
) {
return aValue.numericValue - bValue.numericValue;
}
// For numerical values, do direct value comparison
else if (typeof a.value === 'number' && typeof b.value === 'number') {
return a.value - b.value;
} else {
return a.key.localeCompare(b.key);
}
}
// Do string comparison with non-ASCII support
return a.key.localeCompare(b.key);
}
// Default: Preserve same order
return 0;
}
return a.key > b.key ? 1 : -1;
}
|