| 5 | 5 | import { DEFAULT_AVATAR_PATH } from './constants.js'; |
| 6 | 6 | import { extractFileFromZipBuffer, humanizedISO8601DateTime } from './util.js'; |
| 7 | 7 | |
| 8 | | -export const replaceByafMacros = (s) => |
| 8 | +/** |
| 9 | | - String(s || '') |
| 9 | + * A parser for BYAF (Backyard Archive Format) files. |
| 10 | | - .replace(/#{user}:/gi, '{{user}}:') |
| 10 | + */ |
| 11 | | - .replace(/#{character}:/gi, '{{char}}:') |
| 11 | +export class ByafParser { |
| 12 | | - .replace(/{character}(?!})/gi, '{{char}}') |
| 12 | + /** |
| 13 | | - .replace(/{user}(?!})/gi, '{{user}}'); |
| 13 | + * @param {ArrayBufferLike} data BYAF ZIP buffer |
| 14 | | - |
| 14 | + */ |
| 15 | | -export const formatByafExampleMessages = (examples) => { |
| 15 | + #data; |
| 16 | | - if (!Array.isArray(examples)) { |
| 16 | + |
| 17 | | - return ''; |
| 17 | + /** |
| 18 | + * Creates an instance of ByafParser. |
| 19 | + * @param {ArrayBufferLike} data BYAF ZIP buffer |
| 20 | + */ |
| 21 | + constructor(data) { |
| 22 | + this.#data = data; |
| 18 | 23 | } |
| 19 | 24 | |
| 20 | | - let formattedExamples = ''; |
| 25 | + /** |
| 26 | + * Replaces known macros in a string. |
| 27 | + * @param {string} [str] String to process |
| 28 | + * @returns {string} String with macros replaced |
| 29 | + * @private |
| 30 | + */ |
| 31 | + replaceMacros(str) { |
| 32 | + return String(str || '') |
| 33 | + .replace(/#{user}:/gi, '{{user}}:') |
| 34 | + .replace(/#{character}:/gi, '{{char}}:') |
| 35 | + .replace(/{character}(?!})/gi, '{{char}}') |
| 36 | + .replace(/{user}(?!})/gi, '{{user}}'); |
| 37 | + } |
| 21 | 38 | |
| 22 | | - examples.forEach((example) => { |
| 39 | + /** |
| 23 | | - if (!example?.text) { |
| 40 | + * Formats example messages for a character. |
| 24 | | - return; |
| 41 | + * @param {ByafExampleMessage[]} [examples] Array of example objects |
| 42 | + * @returns {string} Formatted example messages |
| 43 | + * @private |
| 44 | + */ |
| 45 | + formatExampleMessages(examples) { |
| 46 | + if (!Array.isArray(examples)) { |
| 47 | + return ''; |
| 25 | 48 | } |
| 26 | | - formattedExamples += `<START>\n${replaceByafMacros(example.text)}\n`; |
| 27 | | - }); |
| 28 | 49 | |
| 29 | | - return formattedExamples.trimEnd(); |
| 50 | + let formattedExamples = ''; |
| 30 | | -}; |
| 31 | 51 | |
| 32 | | -export const formatByafAlternateGreetings = (greetings) => { |
| 52 | + examples.forEach((example) => { |
| 33 | 53 | if (!Arrayexample?.isArray(greetings)text) { |
| 34 | | - return []; |
| 54 | + return; |
| 35 | 55 | } |
| 56 | + formattedExamples += `<START>\n${this.replaceMacros(example.text)}\n`; |
| 57 | + }); |
| 36 | 58 | |
| 37 | | - if (greetings.length <= 1) { |
| 59 | + return formattedExamples.trimEnd(); |
| 38 | | - return []; |
| 39 | 60 | } |
| 40 | 61 | |
| 41 | | - // Skip one because it goes into 'first_mes' |
| 62 | + /** |
| 42 | | - return greetings.slice(1).map(g => replaceByafMacros(g?.text)); |
| 63 | + * Formats alternate greetings for a character. |
| 43 | | -}; |
| 64 | + * @param {ByafExampleMessage[]} [greetings] Array of greeting objects |
| 65 | + * @returns {string[]} Formatted alternate greetings |
| 66 | + * @private |
| 67 | + */ |
| 68 | + formatAlternateGreetings(greetings) { |
| 69 | + if (!Array.isArray(greetings)) { |
| 70 | + return []; |
| 71 | + } |
| 44 | 72 | |
| 45 | | -export const convertByafCharacterBook = (items) => { |
| 73 | + if (greetings.length <= 1) { |
| 46 | | - if (!Array.isArray(items) || items.length === 0) { |
| 74 | + return []; |
| 47 | | - return null; |
| 75 | + } |
| 48 | | - } |
| 49 | 76 | |
| 50 | | - const book = { |
| 77 | + // Skip one because it goes into 'first_mes' |
| 51 | | - /** @type {any[]} */ |
| 78 | + return greetings.slice(1).map(g => this.replaceMacros(g?.text)); |
| 52 | | - entries: [], |
| 79 | + } |
| 53 | | - }; |
| 54 | 80 | |
| 55 | | - items.forEach((item, index) => { |
| 81 | + /** |
| 56 | | - if (!item) { |
| 82 | + * Converts character book items to a structured format. |
| 57 | | - return; |
| 83 | + * @param {ByafLoreItem[]} items Array of key-value pairs |
| 84 | + * @returns {CharacterBook|undefined} Converted character book or undefined if invalid |
| 85 | + * @private |
| 86 | + */ |
| 87 | + convertCharacterBook(items) { |
| 88 | + if (!Array.isArray(items) || items.length === 0) { |
| 89 | + return undefined; |
| 58 | 90 | } |
| 59 | | - book.entries.push({ |
| 91 | + |
| 60 | | - keys: replaceByafMacros(item?.key).split(',').map(key => key.trim()).filter(Boolean), |
| 92 | + /** @type {CharacterBook} */ |
| 61 | | - content: replaceByafMacros(item?.value), |
| 93 | + const book = { |
| 94 | + entries: [], |
| 62 | 95 | extensions: {}, |
| 63 | | - enabled: true, |
| 96 | + }; |
| 64 | | - insertion_order: index, |
| 97 | + |
| 98 | + items.forEach((item, index) => { |
| 99 | + if (!item) { |
| 100 | + return; |
| 101 | + } |
| 102 | + book.entries.push({ |
| 103 | + keys: this.replaceMacros(item?.key).split(',').map(key => key.trim()).filter(Boolean), |
| 104 | + content: this.replaceMacros(item?.value), |
| 105 | + extensions: {}, |
| 106 | + enabled: true, |
| 107 | + insertion_order: index, |
| 108 | + }); |
| 65 | 109 | }); |
| 66 | | - }); |
| 67 | 110 | |
| 68 | 111 | return book; |
| 69 | 112 | }; |
| 70 | 113 | |
| 71 | 114 | /** |
| 72 | 115 | * Extracts a character object from BYAF buffer. |
| 73 | 116 | * @param {ArrayBufferLikeByafManifest} datamanifest ZIPBYAF buffermanifest |
| 74 | | - * @param {object} manifest BYAF manifest |
| 117 | + * @returns {Promise<{character:ByafCharacter,characterPath:string}>} Character object |
| 75 | | - * @returns {Promise<{character:object,characterPath:string}>} Character object |
| 118 | + * @private |
| 76 | 119 | */ |
| 77 | 120 | export async function getCharacterFromByafManifestgetCharacterFromManifest(data, manifest) { |
| 78 | 121 | const charactersArray = manifest?.characters; |
| 79 | 122 | |
| 80 | 123 | if (!Array.isArray(charactersArray)) { |
| 81 | 124 | throw new Error('Invalid BYAF file: missing characters array'); |
| 82 | 125 | } |
| 83 | 126 | |
| 84 | 127 | if (charactersArray.length === 0) { |
| 85 | 128 | throw new Error('Invalid BYAF file: characters array is empty'); |
| 86 | 129 | } |
| 87 | 130 | |
| 88 | 131 | if (charactersArray.length > 1) { |
| 89 | 132 | console.warn('Warning: BYAF manifest contains more than one character, only the first one will be imported'); |
| 90 | 133 | } |
| 91 | 134 | |
| 92 | 135 | const characterPath = charactersArray[0]; |
| 93 | 136 | if (!characterPath) { |
| 94 | 137 | throw new Error('Invalid BYAF file: missing character path'); |
| 95 | 138 | } |
| 96 | 139 | |
| 97 | 140 | const characterBuffer = await extractFileFromZipBuffer(this.#data, characterPath); |
| 98 | 141 | if (!characterBuffer) { |
| 99 | 142 | throw new Error('Invalid BYAF file: failed to extract character JSON'); |
| 100 | 143 | } |
| 101 | 144 | |
| 102 | 145 | try { |
| 103 | 146 | const character = JSON.parse(characterBuffer.toString()); |
| 104 | 147 | return { character, characterPath }; |
| 105 | 148 | } catch (error) { |
| 106 | 149 | console.error('Failed to parse character JSON from BYAF:', error); |
| 107 | 150 | throw new Error('Invalid BYAF file: character is not a valid JSON'); |
| 151 | + } |
| 108 | 152 | } |
| 109 | | -} |
| 110 | 153 | |
| 111 | 154 | /** |
| 112 | 155 | * Extracts a scenario object from BYAF buffer. |
| 113 | 156 | * @param {ArrayBufferLikeByafManifest} datamanifest ZIPBYAF buffermanifest |
| 114 | | - * @param {object} manifest BYAF manifest |
| 157 | + * @returns {Promise<Partial<ByafScenario>>} Scenario object |
| 115 | | - * @returns {Promise<object>} Scenario object |
| 158 | + * @private |
| 116 | 159 | */ |
| 117 | 160 | export async function getScenarioFromByafManifestgetScenarioFromManifest(data, manifest) { |
| 118 | 161 | const scenariosArray = manifest?.scenarios; |
| 119 | 162 | |
| 120 | 163 | if (!Array.isArray(scenariosArray) || scenariosArray.length === 0) { |
| 121 | 164 | console.warn('Warning: BYAF manifest contains no scenarios'); |
| 122 | 165 | return {}; |
| 123 | 166 | } |
| 124 | 167 | |
| 125 | 168 | if (scenariosArray.length > 1) { |
| 126 | 169 | console.warn('Warning: BYAF manifest contains more than one scenario, only the first one will be imported'); |
| 127 | 170 | } |
| 128 | 171 | |
| 129 | 172 | const scenarioPath = scenariosArray[0]; |
| 130 | 173 | if (!scenarioPath) { |
| 131 | 174 | console.warn('Warning: missing BYAF scenario path'); |
| 132 | 175 | return {}; |
| 133 | 176 | } |
| 134 | 177 | |
| 135 | 178 | const scenarioBuffer = await extractFileFromZipBuffer(this.#data, scenarioPath); |
| 136 | 179 | if (!scenarioBuffer) { |
| 137 | 180 | console.warn('Warning: failed to extract BYAF scenario JSON'); |
| 138 | 181 | return {}; |
| 139 | 182 | } |
| 140 | 183 | |
| 141 | 184 | try { |
| 142 | 185 | return JSON.parse(scenarioBuffer.toString()); |
| 143 | 186 | } catch (error) { |
| 144 | 187 | console.warn('Warning: BYAF scenario is not a valid JSON', error); |
| 145 | 188 | return {}; |
| 189 | + } |
| 146 | 190 | } |
| 147 | | -} |
| 148 | 191 | |
| 149 | 192 | /** |
| 150 | 193 | * Extracts an image from BYAF buffer. |
| 151 | 194 | * @param {ArrayBufferLikeByafCharacter} datacharacter ZIPCharacter bufferobject |
| 152 | 195 | * @param {objectstring} characterPath Path to the character Characterin objectthe BYAF manifest |
| 153 | | - * @param {string} characterPath Path to the character in the BYAF manifest |
| 196 | + * @return {Promise<Buffer>} Image buffer |
| 154 | | - */ |
| 197 | + * @private |
| 155 | | -export async function getImageBufferFromByafCharacter(data, character, characterPath) { |
| 198 | + */ |
| 156 | | - const defaultAvatarBuffer = await fsPromises.readFile(DEFAULT_AVATAR_PATH); |
| 199 | + async getCharacterImage(character, characterPath) { |
| 157 | 200 | const characterImagesdefaultAvatarBuffer = character?await fsPromises.imagesreadFile(DEFAULT_AVATAR_PATH); |
| 201 | + const characterImages = character?.images; |
| 202 | + |
| 203 | + if (!Array.isArray(characterImages) || characterImages.length === 0) { |
| 204 | + console.warn('Warning: BYAF character has no images'); |
| 205 | + return defaultAvatarBuffer; |
| 206 | + } |
| 158 | 207 | |
| 159 | | - if (!Array.isArray(characterImages) || characterImages.length === 0) { |
| 208 | + const imagePath = characterImages[0]?.path; |
| 160 | | - console.warn('Warning: BYAF character has no images'); |
| 209 | + if (!imagePath) { |
| 161 | | - return defaultAvatarBuffer; |
| 210 | + console.warn('Warning: BYAF character image path is empty'); |
| 211 | + return defaultAvatarBuffer; |
| 212 | + } |
| 213 | + |
| 214 | + const fullImagePath = urlJoin(path.dirname(characterPath), imagePath); |
| 215 | + const imageBuffer = await extractFileFromZipBuffer(this.#data, fullImagePath); |
| 216 | + if (!imageBuffer) { |
| 217 | + console.warn('Warning: failed to extract BYAF character image'); |
| 218 | + return defaultAvatarBuffer; |
| 219 | + } |
| 220 | + |
| 221 | + return imageBuffer; |
| 162 | 222 | } |
| 163 | 223 | |
| 164 | | - const imagePath = characterImages[0]?.path; |
| 224 | + /** |
| 165 | | - if (!imagePath) { |
| 225 | + * Formats BYAF data as a character card. |
| 166 | | - console.warn('Warning: BYAF character image path is empty'); |
| 226 | + * @param {ByafManifest} manifest BYAF manifest |
| 167 | | - return defaultAvatarBuffer; |
| 227 | + * @param {ByafCharacter} character Character object |
| 228 | + * @param {Partial<ByafScenario>} scenario Scenario object |
| 229 | + * @return {TavernCardV2} Character card object |
| 230 | + * @private |
| 231 | + */ |
| 232 | + getCharacterCard(manifest, character, scenario) { |
| 233 | + return { |
| 234 | + spec: 'chara_card_v2', |
| 235 | + spec_version: '2.0', |
| 236 | + data: { |
| 237 | + name: sanitize(character?.name || character?.displayName || ''), |
| 238 | + description: this.replaceMacros(character?.persona), |
| 239 | + personality: '', |
| 240 | + scenario: this.replaceMacros(scenario?.narrative), |
| 241 | + first_mes: this.replaceMacros(scenario?.firstMessages?.[0]?.text), |
| 242 | + mes_example: this.formatExampleMessages(scenario?.exampleMessages), |
| 243 | + creator_notes: '', |
| 244 | + system_prompt: this.replaceMacros(scenario?.formattingInstructions), |
| 245 | + post_history_instructions: '', |
| 246 | + alternate_greetings: this.formatAlternateGreetings(scenario?.firstMessages), |
| 247 | + character_book: this.convertCharacterBook(character?.loreItems), |
| 248 | + tags: [], |
| 249 | + creator: manifest?.author?.name || '', |
| 250 | + character_version: '', |
| 251 | + extensions: {}, |
| 252 | + }, |
| 253 | + // @ts-ignore Non-standard spec extension |
| 254 | + create_date: humanizedISO8601DateTime(), |
| 255 | + }; |
| 168 | 256 | } |
| 169 | 257 | |
| 170 | | - const fullImagePath = urlJoin(path.dirname(characterPath), imagePath); |
| 258 | + /** |
| 171 | | - const imageBuffer = await extractFileFromZipBuffer(data, fullImagePath); |
| 259 | + * Gets the manifest from the BYAF data. |
| 172 | | - if (!imageBuffer) { |
| 260 | + * @returns {Promise<ByafManifest>} Parsed manifest |
| 173 | | - console.warn('Warning: failed to extract BYAF character image'); |
| 261 | + * @private |
| 174 | | - return defaultAvatarBuffer; |
| 262 | + */ |
| 263 | + async getManifest() { |
| 264 | + const manifestBuffer = await extractFileFromZipBuffer(this.#data, 'manifest.json'); |
| 265 | + if (!manifestBuffer) { |
| 266 | + throw new Error('Failed to extract manifest.json from BYAF file'); |
| 267 | + } |
| 268 | + |
| 269 | + const manifest = JSON.parse(manifestBuffer.toString()); |
| 270 | + if (!manifest || typeof manifest !== 'object') { |
| 271 | + throw new Error('Invalid BYAF manifest'); |
| 272 | + } |
| 273 | + |
| 274 | + return manifest; |
| 175 | 275 | } |
| 176 | 276 | |
| 177 | | - return imageBuffer; |
| 277 | + /** |
| 178 | | -} |
| 278 | + * Parses the BYAF data. |
| 279 | + * @return {Promise<{card: TavernCardV2, image: Buffer}>} Parsed character card and image buffer |
| 280 | + */ |
| 281 | + async parse() { |
| 282 | + const manifest = await this.getManifest(); |
| 283 | + const { character, characterPath } = await this.getCharacterFromManifest(manifest); |
| 284 | + const scenario = await this.getScenarioFromManifest(manifest); |
| 285 | + const image = await this.getCharacterImage(character, characterPath); |
| 286 | + const card = this.getCharacterCard(manifest, character, scenario); |
| 179 | 287 | |
| 180 | | -/** |
| 288 | + return { card, image }; |
| 181 | | - * Formats BYAF data as a character card. |
| 289 | + } |
| 182 | | - * @param {object} character |
| 183 | | - * @param {object} scenario |
| 184 | | - */ |
| 185 | | -export function formatByafAsCharacterCard(character, scenario) { |
| 186 | | - return { |
| 187 | | - spec: 'chara_card_v2', |
| 188 | | - spec_version: '2.0', |
| 189 | | - create_date: humanizedISO8601DateTime(), |
| 190 | | - data: { |
| 191 | | - name: sanitize(character?.name || character?.displayName || ''), |
| 192 | | - description: replaceByafMacros(character?.persona), |
| 193 | | - personality: '', |
| 194 | | - scenario: replaceByafMacros(scenario?.narrative), |
| 195 | | - first_mes: replaceByafMacros(scenario?.firstMessages?.[0]?.text), |
| 196 | | - mes_example: formatByafExampleMessages(scenario?.exampleMessages), |
| 197 | | - creator_notes: '', |
| 198 | | - system_prompt: replaceByafMacros(scenario?.formattingInstructions), |
| 199 | | - post_history_instructions: '', |
| 200 | | - alternate_greetings: formatByafAlternateGreetings(scenario?.firstMessages), |
| 201 | | - character_book: convertByafCharacterBook(character?.loreItems), |
| 202 | | - tags: [], |
| 203 | | - creator: '', |
| 204 | | - character_version: '', |
| 205 | | - extensions: {}, |
| 206 | | - }, |
| 207 | | - }; |
| 208 | 290 | } |
| 291 | + |
| 292 | +export default ByafParser; |