Skip to content

The open alternative to Salesforce, designed for AI.

2.8 KB
Raw Blame
import { type NormalizationRule } from '../types/normalization-rule.type';

// Machine-translator envelope residue; only stripped when the source does not end the same way.
const DEBRIS_CHARACTERS = new Set([
  ' ',
  '\t',
  '\n',
  '\r',
  ' ',
  '`',
  ']',
  "'",
  '"',
]);

// A salvaged prefix carrying one of these was cut inside the envelope rather than after it.
const ENVELOPE_REGEX = /pluralForm|```|\\",\\"|\[/;

const ICU_ARGUMENT_REGEX = /\{\s*([A-Za-z0-9_]+)\s*[,}]/g;
const ICU_TAG_REGEX = /<\/?\d+>/g;

function hasBalancedBraces(text: string): boolean {
  let depth = 0;

  for (const character of text) {
    if (character === '{') {
      depth += 1;
      continue;
    }

    if (character === '}') {
      depth -= 1;

      if (depth < 0) {
        return false;
      }
    }
  }

  return depth === 0;
}

// The first unmatched '}' is where the translation ends and the envelope begins.
function cutAtUnmatchedBrace(text: string): string | undefined {
  let depth = 0;

  for (let index = 0; index < text.length; index += 1) {
    const character = text[index];

    if (character === '{') {
      depth += 1;
      continue;
    }

    if (character === '}') {
      if (depth === 0) {
        return text.slice(0, index);
      }

      depth -= 1;
    }
  }

  return undefined;
}

function trimDebris(text: string, sourceText: string): string {
  let end = text.length;

  while (
    end > 0 &&
    DEBRIS_CHARACTERS.has(text[end - 1]) &&
    !sourceText.endsWith(text[end - 1])
  ) {
    end -= 1;
  }

  return text.slice(0, end);
}

function icuShape(text: string): string {
  const argumentNames = [...text.matchAll(ICU_ARGUMENT_REGEX)]
    .map(([, name]) => name)
    .sort();
  const tags = [...text.matchAll(ICU_TAG_REGEX)].map(([tag]) => tag).sort();

  return JSON.stringify([argumentNames, tags]);
}

function isCorrupted(text: string, sourceText?: string): boolean {
  return (
    sourceText !== undefined &&
    hasBalancedBraces(sourceText) &&
    !hasBalancedBraces(text)
  );
}

function salvage(text: string, sourceText?: string): string {
  const source = sourceText ?? '';
  const cutText = cutAtUnmatchedBrace(text);

  // An unclosed '{' with no clean tail is dropped rather than guessed at.
  if (cutText === undefined) {
    return hasBalancedBraces(text) ? text : '';
  }

  const salvagedText = trimDebris(cutText, source);

  const isSalvageable =
    salvagedText !== '' &&
    hasBalancedBraces(salvagedText) &&
    (!ENVELOPE_REGEX.test(salvagedText) || ENVELOPE_REGEX.test(source)) &&
    icuShape(salvagedText) === icuShape(source);

  return isSalvageable ? salvagedText : '';
}

export const CORRUPTED_MODEL_OUTPUT_RULE: NormalizationRule = {
  name: 'corrupted-model-output',
  formats: ['po'],
  needsSourceText: true,
  detect: isCorrupted,
  fix: salvage,
};