Skip to content

Commit

Permalink
perf: improve cropText performance
Browse files Browse the repository at this point in the history
  • Loading branch information
josStorer committed Mar 14, 2023
1 parent 38642f0 commit f565de2
Showing 1 changed file with 4 additions and 5 deletions.
9 changes: 4 additions & 5 deletions src/utils/crop-text.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -31,18 +31,17 @@ export function cropText(
endLength = 300,
tiktoken = true,
) {
let length = tiktoken ? encode(text).length : text.length
if (length <= maxLength) return text

const splits = text.split(/[,,.。??!!;;\n]/).map((s) => s.trim())
const splitsLength = splits.map((s) => (tiktoken ? encode(s).length : s.length))
length = splitsLength.reduce((sum, length) => sum + length, 0)
const length = splitsLength.reduce((sum, length) => sum + length, 0)

const cropLength = length - startLength - endLength
const cropTargetLength = maxLength - startLength - endLength
const cropPercentage = cropTargetLength / cropLength
const cropStep = Math.max(0, 1 / cropPercentage - 1)

if (cropStep === 0) return text

let croppedText = ''
let currentLength = 0
let currentIndex = 0
Expand Down Expand Up @@ -76,7 +75,7 @@ export function cropText(

console.log(
`maxLength: ${maxLength}\n` +
`croppedTextLength: ${tiktoken ? encode(croppedText).length : croppedText.length}\n` +
// `croppedTextLength: ${tiktoken ? encode(croppedText).length : croppedText.length}\n` +
`desiredLength: ${currentLength}\n` +
`content: ${croppedText}`,
)
Expand Down

0 comments on commit f565de2

Please sign in to comment.