-
-
Save theskcd/04171213faf2eb1d543896094ad1af73 to your computer and use it in GitHub Desktop.
code to run in playground
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class A { | |
private static transformer<T>(map: (chunk: HuggingFaceTextGenerationTypes.Chunk) => T) { | |
let buffer: string[] = []; | |
const decoder = new TextDecoder(); | |
return (bytes: Uint8Array, controller: TransformStreamDefaultController<T>) => { | |
const chunk = decoder.decode(bytes); | |
for (let i = 0, len = chunk.length; i < len; ++i) { | |
const bufferLength = buffer.length; | |
// HF streams separator is `\n\n` (at least with the currently tested model) | |
const isSeparator = chunk[i] === '\n' && buffer[bufferLength] === '\n'; | |
// Keep buffering unless we've hit the end of a data chunk | |
if (!isSeparator) { | |
buffer.push(chunk[i]); | |
continue; | |
} | |
// Decode the object into the expected JSON type | |
const parsedChunk = HuggingFaceDecoderStream.parseChunk(buffer.join('')); | |
if (parsedChunk) { | |
controller.enqueue(map(parsedChunk)); | |
} | |
buffer = []; | |
} | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment