diff --git a/libs/jieba-wasm/jieba_rs_wasm.js b/libs/jieba-wasm/jieba_rs_wasm.js deleted file mode 100644 index 7281ce6..0000000 --- a/libs/jieba-wasm/jieba_rs_wasm.js +++ /dev/null @@ -1,438 +0,0 @@ -let wasm; - -let cachedUint8ArrayMemory0 = null; - -function getUint8ArrayMemory0() { - if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) { - cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer); - } - return cachedUint8ArrayMemory0; -} - -let cachedTextDecoder = (typeof TextDecoder !== 'undefined' ? new TextDecoder('utf-8', { ignoreBOM: true, fatal: true }) : { decode: () => { throw Error('TextDecoder not available') } } ); - -if (typeof TextDecoder !== 'undefined') { cachedTextDecoder.decode(); }; - -const MAX_SAFARI_DECODE_BYTES = 2146435072; -let numBytesDecoded = 0; -function decodeText(ptr, len) { - numBytesDecoded += len; - if (numBytesDecoded >= MAX_SAFARI_DECODE_BYTES) { - cachedTextDecoder = (typeof TextDecoder !== 'undefined' ? new TextDecoder('utf-8', { ignoreBOM: true, fatal: true }) : { decode: () => { throw Error('TextDecoder not available') } } ); - cachedTextDecoder.decode(); - numBytesDecoded = len; - } - return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len)); -} - -function getStringFromWasm0(ptr, len) { - ptr = ptr >>> 0; - return decodeText(ptr, len); -} - -function debugString(val) { - // primitive types - const type = typeof val; - if (type == 'number' || type == 'boolean' || val == null) { - return `${val}`; - } - if (type == 'string') { - return `"${val}"`; - } - if (type == 'symbol') { - const description = val.description; - if (description == null) { - return 'Symbol'; - } else { - return `Symbol(${description})`; - } - } - if (type == 'function') { - const name = val.name; - if (typeof name == 'string' && name.length > 0) { - return `Function(${name})`; - } else { - return 'Function'; - } - } - // objects - if (Array.isArray(val)) { - const length = val.length; - let debug = '['; - if (length > 0) { - debug += debugString(val[0]); - } - for(let i = 1; i < length; i++) { - debug += ', ' + debugString(val[i]); - } - debug += ']'; - return debug; - } - // Test for built-in - const builtInMatches = /\[object ([^\]]+)\]/.exec(toString.call(val)); - let className; - if (builtInMatches && builtInMatches.length > 1) { - className = builtInMatches[1]; - } else { - // Failed to match the standard '[object ClassName]' - return toString.call(val); - } - if (className == 'Object') { - // we're a user defined class or Object - // JSON.stringify avoids problems with cycles, and is generally much - // easier than looping through ownProperties of `val`. - try { - return 'Object(' + JSON.stringify(val) + ')'; - } catch (_) { - return 'Object'; - } - } - // errors - if (val instanceof Error) { - return `${val.name}: ${val.message}\n${val.stack}`; - } - // TODO we could test for more things here, like `Set`s and `Map`s. - return className; -} - -let WASM_VECTOR_LEN = 0; - -const cachedTextEncoder = (typeof TextEncoder !== 'undefined' ? new TextEncoder('utf-8') : { encode: () => { throw Error('TextEncoder not available') } } ); - -const encodeString = (typeof cachedTextEncoder.encodeInto === 'function' - ? function (arg, view) { - return cachedTextEncoder.encodeInto(arg, view); -} - : function (arg, view) { - const buf = cachedTextEncoder.encode(arg); - view.set(buf); - return { - read: arg.length, - written: buf.length - }; -}); - -function passStringToWasm0(arg, malloc, realloc) { - - if (realloc === undefined) { - const buf = cachedTextEncoder.encode(arg); - const ptr = malloc(buf.length, 1) >>> 0; - getUint8ArrayMemory0().subarray(ptr, ptr + buf.length).set(buf); - WASM_VECTOR_LEN = buf.length; - return ptr; - } - - let len = arg.length; - let ptr = malloc(len, 1) >>> 0; - - const mem = getUint8ArrayMemory0(); - - let offset = 0; - - for (; offset < len; offset++) { - const code = arg.charCodeAt(offset); - if (code > 0x7F) break; - mem[ptr + offset] = code; - } - - if (offset !== len) { - if (offset !== 0) { - arg = arg.slice(offset); - } - ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0; - const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len); - const ret = encodeString(arg, view); - - offset += ret.written; - ptr = realloc(ptr, len, offset, 1) >>> 0; - } - - WASM_VECTOR_LEN = offset; - return ptr; -} - -let cachedDataViewMemory0 = null; - -function getDataViewMemory0() { - if (cachedDataViewMemory0 === null || cachedDataViewMemory0.buffer.detached === true || (cachedDataViewMemory0.buffer.detached === undefined && cachedDataViewMemory0.buffer !== wasm.memory.buffer)) { - cachedDataViewMemory0 = new DataView(wasm.memory.buffer); - } - return cachedDataViewMemory0; -} - -function isLikeNone(x) { - return x === undefined || x === null; -} - -function getArrayJsValueFromWasm0(ptr, len) { - ptr = ptr >>> 0; - const mem = getDataViewMemory0(); - const result = []; - for (let i = ptr; i < ptr + 4 * len; i += 4) { - result.push(wasm.__wbindgen_export_2.get(mem.getUint32(i, true))); - } - wasm.__externref_drop_slice(ptr, len); - return result; -} -/** - * @param {string} text - * @param {boolean | null} [hmm] - * @returns {string[]} - */ -export function cut(text, hmm) { - const ptr0 = passStringToWasm0(text, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - const ret = wasm.cut(ptr0, len0, isLikeNone(hmm) ? 0xFFFFFF : hmm ? 1 : 0); - var v2 = getArrayJsValueFromWasm0(ret[0], ret[1]).slice(); - wasm.__wbindgen_free(ret[0], ret[1] * 4, 4); - return v2; -} - -/** - * @param {string} text - * @returns {string[]} - */ -export function cut_all(text) { - const ptr0 = passStringToWasm0(text, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - const ret = wasm.cut_all(ptr0, len0); - var v2 = getArrayJsValueFromWasm0(ret[0], ret[1]).slice(); - wasm.__wbindgen_free(ret[0], ret[1] * 4, 4); - return v2; -} - -/** - * @param {string} text - * @param {boolean | null} [hmm] - * @returns {string[]} - */ -export function cut_for_search(text, hmm) { - const ptr0 = passStringToWasm0(text, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - const ret = wasm.cut_for_search(ptr0, len0, isLikeNone(hmm) ? 0xFFFFFF : hmm ? 1 : 0); - var v2 = getArrayJsValueFromWasm0(ret[0], ret[1]).slice(); - wasm.__wbindgen_free(ret[0], ret[1] * 4, 4); - return v2; -} - -function takeFromExternrefTable0(idx) { - const value = wasm.__wbindgen_export_2.get(idx); - wasm.__externref_table_dealloc(idx); - return value; -} -/** - * @param {string} text - * @param {string} mode - * @param {boolean | null} [hmm] - * @returns {Token[]} - */ -export function tokenize(text, mode, hmm) { - const ptr0 = passStringToWasm0(text, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - const ptr1 = passStringToWasm0(mode, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len1 = WASM_VECTOR_LEN; - const ret = wasm.tokenize(ptr0, len0, ptr1, len1, isLikeNone(hmm) ? 0xFFFFFF : hmm ? 1 : 0); - if (ret[3]) { - throw takeFromExternrefTable0(ret[2]); - } - var v3 = getArrayJsValueFromWasm0(ret[0], ret[1]).slice(); - wasm.__wbindgen_free(ret[0], ret[1] * 4, 4); - return v3; -} - -/** - * @param {string} word - * @param {number | null} [freq] - * @param {string | null} [tag] - * @returns {number} - */ -export function add_word(word, freq, tag) { - const ptr0 = passStringToWasm0(word, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - var ptr1 = isLikeNone(tag) ? 0 : passStringToWasm0(tag, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - var len1 = WASM_VECTOR_LEN; - const ret = wasm.add_word(ptr0, len0, isLikeNone(freq) ? 0x100000001 : (freq) >>> 0, ptr1, len1); - return ret >>> 0; -} - -/** - * @param {string} sentence - * @param {boolean | null} [hmm] - * @returns {Tag[]} - */ -export function tag(sentence, hmm) { - const ptr0 = passStringToWasm0(sentence, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - const ret = wasm.tag(ptr0, len0, isLikeNone(hmm) ? 0xFFFFFF : hmm ? 1 : 0); - var v2 = getArrayJsValueFromWasm0(ret[0], ret[1]).slice(); - wasm.__wbindgen_free(ret[0], ret[1] * 4, 4); - return v2; -} - -/** - * @param {string} dict - */ -export function with_dict(dict) { - const ptr0 = passStringToWasm0(dict, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - const ret = wasm.with_dict(ptr0, len0); - if (ret[1]) { - throw takeFromExternrefTable0(ret[0]); - } -} - -const EXPECTED_RESPONSE_TYPES = new Set(['basic', 'cors', 'default']); - -async function __wbg_load(module, imports) { - if (typeof Response === 'function' && module instanceof Response) { - if (typeof WebAssembly.instantiateStreaming === 'function') { - try { - return await WebAssembly.instantiateStreaming(module, imports); - - } catch (e) { - const validResponse = module.ok && EXPECTED_RESPONSE_TYPES.has(module.type); - - if (validResponse && module.headers.get('Content-Type') !== 'application/wasm') { - console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n", e); - - } else { - throw e; - } - } - } - - const bytes = await module.arrayBuffer(); - return await WebAssembly.instantiate(bytes, imports); - - } else { - const instance = await WebAssembly.instantiate(module, imports); - - if (instance instanceof WebAssembly.Instance) { - return { instance, module }; - - } else { - return instance; - } - } -} - -function __wbg_get_imports() { - const imports = {}; - imports.wbg = {}; - imports.wbg.__wbg_Error_0497d5bdba9362e5 = function(arg0, arg1) { - const ret = Error(getStringFromWasm0(arg0, arg1)); - return ret; - }; - imports.wbg.__wbg_new_07b483f72211fd66 = function() { - const ret = new Object(); - return ret; - }; - imports.wbg.__wbg_set_3f1d0b984ed272ed = function(arg0, arg1, arg2) { - arg0[arg1] = arg2; - }; - imports.wbg.__wbindgen_bigint_from_u64 = function(arg0) { - const ret = BigInt.asUintN(64, arg0); - return ret; - }; - imports.wbg.__wbindgen_debug_string = function(arg0, arg1) { - const ret = debugString(arg1); - const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len1 = WASM_VECTOR_LEN; - getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true); - getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true); - }; - imports.wbg.__wbindgen_init_externref_table = function() { - const table = wasm.__wbindgen_export_2; - const offset = table.grow(4); - table.set(0, undefined); - table.set(offset + 0, undefined); - table.set(offset + 1, null); - table.set(offset + 2, true); - table.set(offset + 3, false); - ; - }; - imports.wbg.__wbindgen_number_new = function(arg0) { - const ret = arg0; - return ret; - }; - imports.wbg.__wbindgen_string_new = function(arg0, arg1) { - const ret = getStringFromWasm0(arg0, arg1); - return ret; - }; - imports.wbg.__wbindgen_throw = function(arg0, arg1) { - throw new Error(getStringFromWasm0(arg0, arg1)); - }; - - return imports; -} - -function __wbg_init_memory(imports, memory) { - -} - -function __wbg_finalize_init(instance, module) { - wasm = instance.exports; - __wbg_init.__wbindgen_wasm_module = module; - cachedDataViewMemory0 = null; - cachedUint8ArrayMemory0 = null; - - - wasm.__wbindgen_start(); - return wasm; -} - -function initSync(module) { - if (wasm !== undefined) return wasm; - - - if (typeof module !== 'undefined') { - if (Object.getPrototypeOf(module) === Object.prototype) { - ({module} = module) - } else { - console.warn('using deprecated parameters for `initSync()`; pass a single object instead') - } - } - - const imports = __wbg_get_imports(); - - __wbg_init_memory(imports); - - if (!(module instanceof WebAssembly.Module)) { - module = new WebAssembly.Module(module); - } - - const instance = new WebAssembly.Instance(module, imports); - - return __wbg_finalize_init(instance, module); -} - -async function __wbg_init(module_or_path) { - if (wasm !== undefined) return wasm; - - - if (typeof module_or_path !== 'undefined') { - if (Object.getPrototypeOf(module_or_path) === Object.prototype) { - ({module_or_path} = module_or_path) - } else { - console.warn('using deprecated parameters for the initialization function; pass a single object instead') - } - } - - if (typeof module_or_path === 'undefined') { - module_or_path = new URL('jieba_rs_wasm_bg.wasm', import.meta.url); - } - const imports = __wbg_get_imports(); - - if (typeof module_or_path === 'string' || (typeof Request === 'function' && module_or_path instanceof Request) || (typeof URL === 'function' && module_or_path instanceof URL)) { - module_or_path = fetch(module_or_path); - } - - __wbg_init_memory(imports); - - const { instance, module } = await __wbg_load(await module_or_path, imports); - - return __wbg_finalize_init(instance, module); -} - -export { initSync }; -export default __wbg_init; diff --git a/libs/jieba-wasm/jieba_rs_wasm_bg.js b/libs/jieba-wasm/jieba_rs_wasm_bg.js deleted file mode 100644 index 790c302..0000000 --- a/libs/jieba-wasm/jieba_rs_wasm_bg.js +++ /dev/null @@ -1,372 +0,0 @@ -let wasm; -export function __wbg_set_wasm(val) { - wasm = val; -} - - -const heap = new Array(128).fill(undefined); - -heap.push(undefined, null, true, false); - -function getObject(idx) { return heap[idx]; } - -let heap_next = heap.length; - -function dropObject(idx) { - if (idx < 132) return; - heap[idx] = heap_next; - heap_next = idx; -} - -function takeObject(idx) { - const ret = getObject(idx); - dropObject(idx); - return ret; -} - -const lTextDecoder = typeof TextDecoder === 'undefined' ? (0, module.require)('util').TextDecoder : TextDecoder; - -let cachedTextDecoder = new lTextDecoder('utf-8', { ignoreBOM: true, fatal: true }); - -cachedTextDecoder.decode(); - -let cachedUint8ArrayMemory0 = null; - -function getUint8ArrayMemory0() { - if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) { - cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer); - } - return cachedUint8ArrayMemory0; -} - -function getStringFromWasm0(ptr, len) { - ptr = ptr >>> 0; - return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len)); -} - -function addHeapObject(obj) { - if (heap_next === heap.length) heap.push(heap.length + 1); - const idx = heap_next; - heap_next = heap[idx]; - - heap[idx] = obj; - return idx; -} - -function debugString(val) { - // primitive types - const type = typeof val; - if (type == 'number' || type == 'boolean' || val == null) { - return `${val}`; - } - if (type == 'string') { - return `"${val}"`; - } - if (type == 'symbol') { - const description = val.description; - if (description == null) { - return 'Symbol'; - } else { - return `Symbol(${description})`; - } - } - if (type == 'function') { - const name = val.name; - if (typeof name == 'string' && name.length > 0) { - return `Function(${name})`; - } else { - return 'Function'; - } - } - // objects - if (Array.isArray(val)) { - const length = val.length; - let debug = '['; - if (length > 0) { - debug += debugString(val[0]); - } - for(let i = 1; i < length; i++) { - debug += ', ' + debugString(val[i]); - } - debug += ']'; - return debug; - } - // Test for built-in - const builtInMatches = /\[object ([^\]]+)\]/.exec(toString.call(val)); - let className; - if (builtInMatches.length > 1) { - className = builtInMatches[1]; - } else { - // Failed to match the standard '[object ClassName]' - return toString.call(val); - } - if (className == 'Object') { - // we're a user defined class or Object - // JSON.stringify avoids problems with cycles, and is generally much - // easier than looping through ownProperties of `val`. - try { - return 'Object(' + JSON.stringify(val) + ')'; - } catch (_) { - return 'Object'; - } - } - // errors - if (val instanceof Error) { - return `${val.name}: ${val.message}\n${val.stack}`; - } - // TODO we could test for more things here, like `Set`s and `Map`s. - return className; -} - -let WASM_VECTOR_LEN = 0; - -const lTextEncoder = typeof TextEncoder === 'undefined' ? (0, module.require)('util').TextEncoder : TextEncoder; - -let cachedTextEncoder = new lTextEncoder('utf-8'); - -const encodeString = (typeof cachedTextEncoder.encodeInto === 'function' - ? function (arg, view) { - return cachedTextEncoder.encodeInto(arg, view); -} - : function (arg, view) { - const buf = cachedTextEncoder.encode(arg); - view.set(buf); - return { - read: arg.length, - written: buf.length - }; -}); - -function passStringToWasm0(arg, malloc, realloc) { - - if (realloc === undefined) { - const buf = cachedTextEncoder.encode(arg); - const ptr = malloc(buf.length, 1) >>> 0; - getUint8ArrayMemory0().subarray(ptr, ptr + buf.length).set(buf); - WASM_VECTOR_LEN = buf.length; - return ptr; - } - - let len = arg.length; - let ptr = malloc(len, 1) >>> 0; - - const mem = getUint8ArrayMemory0(); - - let offset = 0; - - for (; offset < len; offset++) { - const code = arg.charCodeAt(offset); - if (code > 0x7F) break; - mem[ptr + offset] = code; - } - - if (offset !== len) { - if (offset !== 0) { - arg = arg.slice(offset); - } - ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0; - const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len); - const ret = encodeString(arg, view); - - offset += ret.written; - ptr = realloc(ptr, len, offset, 1) >>> 0; - } - - WASM_VECTOR_LEN = offset; - return ptr; -} - -let cachedDataViewMemory0 = null; - -function getDataViewMemory0() { - if (cachedDataViewMemory0 === null || cachedDataViewMemory0.buffer.detached === true || (cachedDataViewMemory0.buffer.detached === undefined && cachedDataViewMemory0.buffer !== wasm.memory.buffer)) { - cachedDataViewMemory0 = new DataView(wasm.memory.buffer); - } - return cachedDataViewMemory0; -} - -function isLikeNone(x) { - return x === undefined || x === null; -} - -function getArrayJsValueFromWasm0(ptr, len) { - ptr = ptr >>> 0; - const mem = getDataViewMemory0(); - const result = []; - for (let i = ptr; i < ptr + 4 * len; i += 4) { - result.push(takeObject(mem.getUint32(i, true))); - } - return result; -} -/** - * @param {string} text - * @param {boolean | undefined} [hmm] - * @returns {any[]} - */ -export function cut(text, hmm) { - try { - const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); - const ptr0 = passStringToWasm0(text, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - wasm.cut(retptr, ptr0, len0, isLikeNone(hmm) ? 0xFFFFFF : hmm ? 1 : 0); - var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true); - var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true); - var v2 = getArrayJsValueFromWasm0(r0, r1).slice(); - wasm.__wbindgen_free(r0, r1 * 4, 4); - return v2; - } finally { - wasm.__wbindgen_add_to_stack_pointer(16); - } -} - -/** - * @param {string} text - * @returns {any[]} - */ -export function cut_all(text) { - try { - const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); - const ptr0 = passStringToWasm0(text, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - wasm.cut_all(retptr, ptr0, len0); - var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true); - var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true); - var v2 = getArrayJsValueFromWasm0(r0, r1).slice(); - wasm.__wbindgen_free(r0, r1 * 4, 4); - return v2; - } finally { - wasm.__wbindgen_add_to_stack_pointer(16); - } -} - -/** - * @param {string} text - * @param {boolean | undefined} [hmm] - * @returns {any[]} - */ -export function cut_for_search(text, hmm) { - try { - const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); - const ptr0 = passStringToWasm0(text, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - wasm.cut_for_search(retptr, ptr0, len0, isLikeNone(hmm) ? 0xFFFFFF : hmm ? 1 : 0); - var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true); - var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true); - var v2 = getArrayJsValueFromWasm0(r0, r1).slice(); - wasm.__wbindgen_free(r0, r1 * 4, 4); - return v2; - } finally { - wasm.__wbindgen_add_to_stack_pointer(16); - } -} - -/** - * @param {string} text - * @param {string} mode - * @param {boolean | undefined} [hmm] - * @returns {any[]} - */ -export function tokenize(text, mode, hmm) { - try { - const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); - const ptr0 = passStringToWasm0(text, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - const ptr1 = passStringToWasm0(mode, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len1 = WASM_VECTOR_LEN; - wasm.tokenize(retptr, ptr0, len0, ptr1, len1, isLikeNone(hmm) ? 0xFFFFFF : hmm ? 1 : 0); - var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true); - var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true); - var r2 = getDataViewMemory0().getInt32(retptr + 4 * 2, true); - var r3 = getDataViewMemory0().getInt32(retptr + 4 * 3, true); - if (r3) { - throw takeObject(r2); - } - var v3 = getArrayJsValueFromWasm0(r0, r1).slice(); - wasm.__wbindgen_free(r0, r1 * 4, 4); - return v3; - } finally { - wasm.__wbindgen_add_to_stack_pointer(16); - } -} - -/** - * @param {string} word - * @param {number | undefined} [freq] - * @param {string | undefined} [tag] - * @returns {number} - */ -export function add_word(word, freq, tag) { - const ptr0 = passStringToWasm0(word, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - var ptr1 = isLikeNone(tag) ? 0 : passStringToWasm0(tag, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - var len1 = WASM_VECTOR_LEN; - const ret = wasm.add_word(ptr0, len0, !isLikeNone(freq), isLikeNone(freq) ? 0 : freq, ptr1, len1); - return ret >>> 0; -} - -/** - * @param {string} sentence - * @param {boolean | undefined} [hmm] - * @returns {any[]} - */ -export function tag(sentence, hmm) { - try { - const retptr = wasm.__wbindgen_add_to_stack_pointer(-16); - const ptr0 = passStringToWasm0(sentence, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len0 = WASM_VECTOR_LEN; - wasm.tag(retptr, ptr0, len0, isLikeNone(hmm) ? 0xFFFFFF : hmm ? 1 : 0); - var r0 = getDataViewMemory0().getInt32(retptr + 4 * 0, true); - var r1 = getDataViewMemory0().getInt32(retptr + 4 * 1, true); - var v2 = getArrayJsValueFromWasm0(r0, r1).slice(); - wasm.__wbindgen_free(r0, r1 * 4, 4); - return v2; - } finally { - wasm.__wbindgen_add_to_stack_pointer(16); - } -} - -export function __wbindgen_object_drop_ref(arg0) { - takeObject(arg0); -}; - -export function __wbindgen_string_new(arg0, arg1) { - const ret = getStringFromWasm0(arg0, arg1); - return addHeapObject(ret); -}; - -export function __wbindgen_object_clone_ref(arg0) { - const ret = getObject(arg0); - return addHeapObject(ret); -}; - -export function __wbg_new_1e7c00339420672b() { - const ret = new Object(); - return addHeapObject(ret); -}; - -export function __wbindgen_number_new(arg0) { - const ret = arg0; - return addHeapObject(ret); -}; - -export function __wbg_set_1754fb90457a8cce(arg0, arg1, arg2) { - getObject(arg0)[takeObject(arg1)] = takeObject(arg2); -}; - -export function __wbg_new_b44ab9ef6060dd36(arg0, arg1) { - const ret = new Error(getStringFromWasm0(arg0, arg1)); - return addHeapObject(ret); -}; - -export function __wbindgen_debug_string(arg0, arg1) { - const ret = debugString(getObject(arg1)); - const ptr1 = passStringToWasm0(ret, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc); - const len1 = WASM_VECTOR_LEN; - getDataViewMemory0().setInt32(arg0 + 4 * 1, len1, true); - getDataViewMemory0().setInt32(arg0 + 4 * 0, ptr1, true); -}; - -export function __wbindgen_throw(arg0, arg1) { - throw new Error(getStringFromWasm0(arg0, arg1)); -}; - diff --git a/libs/jieba-wasm/jieba_rs_wasm_bg.wasm b/libs/jieba-wasm/jieba_rs_wasm_bg.wasm deleted file mode 100644 index 92df1dc..0000000 Binary files a/libs/jieba-wasm/jieba_rs_wasm_bg.wasm and /dev/null differ diff --git a/libs/jieba-wasm/jieba_rs_wasm_bg.wasm.d.ts b/libs/jieba-wasm/jieba_rs_wasm_bg.wasm.d.ts deleted file mode 100644 index ab7e1cd..0000000 --- a/libs/jieba-wasm/jieba_rs_wasm_bg.wasm.d.ts +++ /dev/null @@ -1,25 +0,0 @@ -/* tslint:disable */ -/* eslint-disable */ -export const memory: WebAssembly.Memory; -export const cut: (a: number, b: number, c: number) => [number, number]; -export const cut_all: (a: number, b: number) => [number, number]; -export const cut_for_search: (a: number, b: number, c: number) => [number, number]; -export const tokenize: (a: number, b: number, c: number, d: number, e: number) => [number, number, number, number]; -export const add_word: (a: number, b: number, c: number, d: number, e: number) => number; -export const tag: (a: number, b: number, c: number) => [number, number]; -export const with_dict: (a: number, b: number) => [number, number]; -export const rust_zstd_wasm_shim_qsort: (a: number, b: number, c: number, d: number) => void; -export const rust_zstd_wasm_shim_malloc: (a: number) => number; -export const rust_zstd_wasm_shim_memcmp: (a: number, b: number, c: number) => number; -export const rust_zstd_wasm_shim_calloc: (a: number, b: number) => number; -export const rust_zstd_wasm_shim_free: (a: number) => void; -export const rust_zstd_wasm_shim_memcpy: (a: number, b: number, c: number) => number; -export const rust_zstd_wasm_shim_memmove: (a: number, b: number, c: number) => number; -export const rust_zstd_wasm_shim_memset: (a: number, b: number, c: number) => number; -export const __wbindgen_malloc: (a: number, b: number) => number; -export const __wbindgen_realloc: (a: number, b: number, c: number, d: number) => number; -export const __wbindgen_export_2: WebAssembly.Table; -export const __externref_drop_slice: (a: number, b: number) => void; -export const __wbindgen_free: (a: number, b: number, c: number) => void; -export const __externref_table_dealloc: (a: number) => void; -export const __wbindgen_start: () => void; diff --git a/modules/story-summary/data/config.js b/modules/story-summary/data/config.js index dbb1ebe..77d6832 100644 --- a/modules/story-summary/data/config.js +++ b/modules/story-summary/data/config.js @@ -1,5 +1,6 @@ -// Story Summary - Config -// Plugin settings, panel config, and vector config. +// ═══════════════════════════════════════════════════════════════════════════ +// Story Summary - Config (v2 简化版) +// ═══════════════════════════════════════════════════════════════════════════ import { extension_settings } from "../../../../../../extensions.js"; import { EXT_ID } from "../../../core/constants.js"; @@ -37,6 +38,7 @@ export function getSummaryPanelConfig() { }, vector: null, }; + try { const raw = localStorage.getItem('summary_panel_config'); if (!raw) return defaults; @@ -66,15 +68,29 @@ export function saveSummaryPanelConfig(config) { } } +// ═══════════════════════════════════════════════════════════════════════════ +// 向量配置(简化版 - 只需要 key) +// ═══════════════════════════════════════════════════════════════════════════ + export function getVectorConfig() { try { const raw = localStorage.getItem('summary_panel_config'); if (!raw) return null; const parsed = JSON.parse(raw); const cfg = parsed.vector || null; + if (cfg && !cfg.textFilterRules) { cfg.textFilterRules = [...DEFAULT_FILTER_RULES]; } + + // 简化:统一使用硅基 + if (cfg) { + cfg.engine = 'online'; + cfg.online = cfg.online || {}; + cfg.online.provider = 'siliconflow'; + cfg.online.model = 'BAAI/bge-m3'; + } + return cfg; } catch { return null; @@ -90,7 +106,19 @@ export function saveVectorConfig(vectorCfg) { try { const raw = localStorage.getItem('summary_panel_config') || '{}'; const parsed = JSON.parse(raw); - parsed.vector = vectorCfg; + + // 简化配置 + parsed.vector = { + enabled: vectorCfg?.enabled || false, + engine: 'online', + online: { + provider: 'siliconflow', + key: vectorCfg?.online?.key || '', + model: 'BAAI/bge-m3', + }, + textFilterRules: vectorCfg?.textFilterRules || DEFAULT_FILTER_RULES, + }; + localStorage.setItem('summary_panel_config', JSON.stringify(parsed)); CommonSettingStorage.set(SUMMARY_CONFIG_KEY, parsed); } catch (e) { diff --git a/modules/story-summary/data/store.js b/modules/story-summary/data/store.js index 6c93b3b..0429d49 100644 --- a/modules/story-summary/data/store.js +++ b/modules/story-summary/data/store.js @@ -6,7 +6,6 @@ import { chat_metadata } from "../../../../../../../script.js"; import { EXT_ID } from "../../../core/constants.js"; import { xbLog } from "../../../core/debug-core.js"; import { clearEventVectors, deleteEventVectorsByIds } from "../vector/storage/chunk-store.js"; -import { clearEventTextIndex } from '../vector/retrieval/text-search.js'; const MODULE_ID = 'summaryStore'; const FACTS_LIMIT_PER_SUBJECT = 10; @@ -422,7 +421,6 @@ export async function clearSummaryData(chatId) { await clearEventVectors(chatId); } - clearEventTextIndex(); xbLog.info(MODULE_ID, '总结数据已清空'); } diff --git a/modules/story-summary/story-summary-ui.js b/modules/story-summary/story-summary-ui.js index 14c898e..aa5aafa 100644 --- a/modules/story-summary/story-summary-ui.js +++ b/modules/story-summary/story-summary-ui.js @@ -1,4 +1,4 @@ -// story-summary-ui.js +// story-summary-ui.js // iframe 内 UI 逻辑 (function () { @@ -73,33 +73,6 @@ '陌生': 'trend-stranger', '投缘': 'trend-click', '亲密': 'trend-close', '交融': 'trend-merge' }; - const LOCAL_MODELS_INFO = { - 'bge-small-zh': { desc: '手机/低配适用' }, - 'bge-base-zh': { desc: 'PC 推荐,效果更好' }, - 'e5-small': { desc: '非中文用户' } - }; - - const ONLINE_PROVIDERS_INFO = { - siliconflow: { - url: 'https://api.siliconflow.cn', - models: ['BAAI/bge-m3', 'BAAI/bge-large-zh-v1.5', 'BAAI/bge-small-zh-v1.5'], - hint: '💡 硅基流动 注册即送额度,推荐 BAAI/bge-m3', - canFetch: false, urlEditable: false - }, - cohere: { - url: 'https://api.cohere.ai', - models: ['embed-multilingual-v3.0', 'embed-english-v3.0'], - hint: '💡 Cohere 提供免费试用额度', - canFetch: false, urlEditable: false - }, - openai: { - url: '', - models: [], - hint: '💡 可用 Hugging Face Space 免费自建
', - canFetch: true, urlEditable: true - } - }; - const DEFAULT_FILTER_RULES = [ { start: '', end: '' }, { start: '', end: '' }, @@ -119,6 +92,7 @@ let summaryData = { keywords: [], events: [], characters: { main: [], relationships: [] }, arcs: [], facts: [] }; let localGenerating = false; let vectorGenerating = false; + let anchorGenerating = false; let relationChart = null; let relationChartFullscreen = null; let currentEditSection = null; @@ -172,7 +146,7 @@ const settingsOpen = $('settings-modal')?.classList.contains('active'); if (settingsOpen) config.vector = getVectorConfig(); if (!config.vector) { - config.vector = { enabled: false, engine: 'online', local: { modelId: 'bge-small-zh' }, online: { provider: 'siliconflow', url: '', key: '', model: '' } }; + config.vector = { enabled: false, engine: 'online', online: { provider: 'siliconflow', key: '', model: 'BAAI/bge-m3' } }; } localStorage.setItem('summary_panel_config', JSON.stringify(config)); postMsg('SAVE_PANEL_CONFIG', { config }); @@ -186,38 +160,16 @@ // ═══════════════════════════════════════════════════════════════════════════ function getVectorConfig() { - const safeVal = (id, fallback) => { - const el = $(id); - if (!el) return fallback; - return el.type === 'checkbox' ? el.checked : (el.value?.trim() || fallback); - }; - const safeRadio = (name, fallback) => { - const el = document.querySelector(`input[name="${name}"]:checked`); - return el?.value || fallback; - }; - const modelSelect = $('vector-model-select'); - const modelCache = []; - if (modelSelect) { - for (const opt of modelSelect.options) { - if (opt.value) modelCache.push(opt.value); - } - } - const result = { - enabled: safeVal('vector-enabled', false), - engine: safeRadio('vector-engine', 'online'), - local: { modelId: safeVal('local-model-select', 'bge-small-zh') }, + return { + enabled: $('vector-enabled')?.checked || false, + engine: 'online', online: { - provider: safeVal('online-provider', 'siliconflow'), - url: safeVal('vector-api-url', ''), - key: safeVal('vector-api-key', ''), - model: safeVal('vector-model-select', ''), - modelCache - } + provider: 'siliconflow', + key: $('vector-api-key')?.value?.trim() || '', + model: 'BAAI/bge-m3', + }, + textFilterRules: collectFilterRules(), }; - - // 收集过滤规则 - result.textFilterRules = collectFilterRules(); - return result; } function loadVectorConfig(cfg) { @@ -225,70 +177,14 @@ $('vector-enabled').checked = !!cfg.enabled; $('vector-config-area').classList.toggle('hidden', !cfg.enabled); - const engine = cfg.engine || 'online'; - const engineRadio = document.querySelector(`input[name="vector-engine"][value="${engine}"]`); - if (engineRadio) engineRadio.checked = true; - - $('local-engine-area').classList.toggle('hidden', engine !== 'local'); - $('online-engine-area').classList.toggle('hidden', engine !== 'online'); - - if (cfg.local?.modelId) { - $('local-model-select').value = cfg.local.modelId; - updateLocalModelDesc(cfg.local.modelId); - } - if (cfg.online) { - const provider = cfg.online.provider || 'siliconflow'; - $('online-provider').value = provider; - updateOnlineProviderUI(provider); - if (cfg.online.url) $('vector-api-url').value = cfg.online.url; - if (cfg.online.key) $('vector-api-key').value = cfg.online.key; - if (cfg.online.modelCache?.length) { - setSelectOptions($('vector-model-select'), cfg.online.modelCache); - } - if (cfg.online.model) $('vector-model-select').value = cfg.online.model; + if (cfg.online?.key) { + $('vector-api-key').value = cfg.online.key; } - // 加载过滤规则 renderFilterRules(cfg?.textFilterRules || DEFAULT_FILTER_RULES); } - function updateLocalModelDesc(modelId) { - const info = LOCAL_MODELS_INFO[modelId]; - $('local-model-desc').textContent = info?.desc || ''; - } - - function updateOnlineProviderUI(provider) { - const info = ONLINE_PROVIDERS_INFO[provider]; - if (!info) return; - - const urlInput = $('vector-api-url'); - const urlRow = $('online-url-row'); - if (info.urlEditable) { - urlInput.value = urlInput.value || ''; - urlInput.disabled = false; - urlRow.style.display = ''; - } else { - urlInput.value = info.url; - urlInput.disabled = true; - urlRow.style.display = 'none'; - } - - const modelSelect = $('vector-model-select'); - const fetchBtn = $('btn-fetch-models'); - if (info.canFetch) { - fetchBtn.style.display = ''; - setHtml(modelSelect, ''); - } else { - fetchBtn.style.display = 'none'; - setSelectOptions(modelSelect, info.models); - } - - setHtml($('provider-hint'), info.hint); - const guideBtn = $('btn-hf-guide'); - if (guideBtn) guideBtn.onclick = e => { e.preventDefault(); openHfGuide(); }; - } - - // ═══════════════════════════════════════════════════════════════════════════ + // ═══════════════════════════════════════════════════════════════════════════ // Filter Rules UI // ═══════════════════════════════════════════════════════════════════════════ @@ -352,31 +248,6 @@ list.appendChild(div); } - function updateLocalModelStatus(status, message) { - const dot = $('local-model-status').querySelector('.status-dot'); - const text = $('local-model-status').querySelector('.status-text'); - dot.className = 'status-dot ' + status; - text.textContent = message; - - const btnDownload = $('btn-download-model'); - const btnCancel = $('btn-cancel-download'); - const btnDelete = $('btn-delete-model'); - const progress = $('local-model-progress'); - - btnDownload.style.display = (status === 'not_downloaded' || status === 'cached' || status === 'error') ? '' : 'none'; - btnCancel.style.display = (status === 'downloading') ? '' : 'none'; - btnDelete.style.display = (status === 'ready' || status === 'cached') ? '' : 'none'; - progress.classList.toggle('hidden', status !== 'downloading'); - - btnDownload.textContent = status === 'cached' ? '加载模型' : status === 'error' ? '重试下载' : '下载模型'; - } - - function updateLocalModelProgress(percent) { - const progress = $('local-model-progress'); - progress.classList.remove('hidden'); - progress.querySelector('.progress-inner').style.width = percent + '%'; - progress.querySelector('.progress-text').textContent = percent + '%'; - } function updateOnlineStatus(status, message) { const dot = $('online-api-status').querySelector('.status-dot'); @@ -385,116 +256,129 @@ text.textContent = message; } - function updateOnlineModels(models) { - const select = $('vector-model-select'); - const current = select.value; - setSelectOptions(select, models); - if (current && models.includes(current)) select.value = current; - if (!config.vector) config.vector = { enabled: false, engine: 'online', local: {}, online: {} }; - if (!config.vector.online) config.vector.online = {}; - config.vector.online.modelCache = [...models]; - } - function updateVectorStats(stats) { + $('vector-atom-count').textContent = stats.stateAtoms || 0; + $('vector-chunk-count').textContent = stats.chunkCount || 0; $('vector-event-count').textContent = stats.eventVectors || 0; - if ($('vector-event-total')) $('vector-event-total').textContent = stats.eventCount || 0; - if ($('vector-chunk-count')) $('vector-chunk-count').textContent = stats.chunkCount || 0; - if ($('vector-chunk-floors')) $('vector-chunk-floors').textContent = stats.builtFloors || 0; - if ($('vector-chunk-total')) $('vector-chunk-total').textContent = stats.totalFloors || 0; - if ($('vector-message-count')) $('vector-message-count').textContent = stats.totalMessages || 0; - } - - function updateVectorGenProgress(phase, current, total) { - const progressId = phase === 'L1' ? 'vector-gen-progress-l1' : 'vector-gen-progress-l2'; - const progress = $(progressId); - const btnGen = $('btn-gen-vectors'); - const btnCancel = $('btn-cancel-vectors'); - const btnClear = $('btn-clear-vectors'); - - if (current < 0) { - progress.classList.add('hidden'); - const l1Hidden = $('vector-gen-progress-l1').classList.contains('hidden'); - const l2Hidden = $('vector-gen-progress-l2').classList.contains('hidden'); - if (l1Hidden && l2Hidden) { - btnGen.classList.remove('hidden'); - btnCancel.classList.add('hidden'); - btnClear.classList.remove('hidden'); - vectorGenerating = false; - } - return; - } - - vectorGenerating = true; - progress.classList.remove('hidden'); - btnGen.classList.add('hidden'); - btnCancel.classList.remove('hidden'); - btnClear.classList.add('hidden'); - - const percent = total > 0 ? Math.round(current / total * 100) : 0; - progress.querySelector('.progress-inner').style.width = percent + '%'; - progress.querySelector('.progress-text').textContent = `${current}/${total}`; } function showVectorMismatchWarning(show) { $('vector-mismatch-warning').classList.toggle('hidden', !show); } - function initVectorUI() { + // ═══════════════════════════════════════════════════════════════════════════ + // 记忆锚点(L0)UI + // ═══════════════════════════════════════════════════════════════════════════ + + function updateAnchorStats(stats) { + const extracted = stats.extracted || 0; + const total = stats.total || 0; + const pending = stats.pending || 0; + const empty = stats.empty || 0; + const fail = stats.fail || 0; + + $('anchor-extracted').textContent = extracted; + $('anchor-total').textContent = total; + $('anchor-pending').textContent = pending; + + const extra = document.getElementById('anchor-extra'); + if (extra) extra.textContent = `空 ${empty} · 失败 ${fail}`; + + const pendingWrap = $('anchor-pending-wrap'); + if (pendingWrap) { + pendingWrap.classList.toggle('hidden', pending === 0); + } + + const emptyWarning = $('vector-empty-l0-warning'); + if (emptyWarning) { + emptyWarning.classList.toggle('hidden', extracted > 0); + } + } + + function updateAnchorProgress(current, total, message) { + const progress = $('anchor-progress'); + const btnGen = $('btn-anchor-generate'); + const btnClear = $('btn-anchor-clear'); + const btnCancel = $('btn-anchor-cancel'); + + if (current < 0) { + progress.classList.add('hidden'); + btnGen.classList.remove('hidden'); + btnClear.classList.remove('hidden'); + btnCancel.classList.add('hidden'); + anchorGenerating = false; + } else { + anchorGenerating = true; + progress.classList.remove('hidden'); + btnGen.classList.add('hidden'); + btnClear.classList.add('hidden'); + btnCancel.classList.remove('hidden'); + + const percent = total > 0 ? Math.round(current / total * 100) : 0; + progress.querySelector('.progress-inner').style.width = percent + '%'; + progress.querySelector('.progress-text').textContent = message || `${current}/${total}`; + } + } + + function initAnchorUI() { + $('btn-anchor-generate').onclick = () => { + if (anchorGenerating) return; + postMsg('ANCHOR_GENERATE'); + }; + + $('btn-anchor-clear').onclick = () => { + if (confirm('清空所有记忆锚点?(L0 向量也会一并清除)')) { + postMsg('ANCHOR_CLEAR'); + } + }; + + $('btn-anchor-cancel').onclick = () => { + postMsg('ANCHOR_CANCEL'); + }; + } + +function initVectorUI() { $('vector-enabled').onchange = e => { $('vector-config-area').classList.toggle('hidden', !e.target.checked); }; - document.querySelectorAll('input[name="vector-engine"]').forEach(radio => { - radio.onchange = e => { - const isLocal = e.target.value === 'local'; - $('local-engine-area').classList.toggle('hidden', !isLocal); - $('online-engine-area').classList.toggle('hidden', isLocal); - }; - }); - $('local-model-select').onchange = e => { - updateLocalModelDesc(e.target.value); - postMsg('VECTOR_CHECK_LOCAL_MODEL', { modelId: e.target.value }); - }; - $('online-provider').onchange = e => updateOnlineProviderUI(e.target.value); - $('btn-download-model').onclick = () => postMsg('VECTOR_DOWNLOAD_MODEL', { modelId: $('local-model-select').value }); - $('btn-cancel-download').onclick = () => postMsg('VECTOR_CANCEL_DOWNLOAD'); - $('btn-delete-model').onclick = () => { - if (confirm('确定删除本地模型缓存?')) postMsg('VECTOR_DELETE_MODEL', { modelId: $('local-model-select').value }); - }; - $('btn-fetch-models').onclick = () => { - postMsg('VECTOR_FETCH_MODELS', { config: { url: $('vector-api-url').value.trim(), key: $('vector-api-key').value.trim() } }); - }; + $('btn-test-vector-api').onclick = () => { postMsg('VECTOR_TEST_ONLINE', { - provider: $('online-provider').value, - config: { url: $('vector-api-url').value.trim(), key: $('vector-api-key').value.trim(), model: $('vector-model-select').value.trim() } + provider: 'siliconflow', + config: { + key: $('vector-api-key').value.trim(), + model: 'BAAI/bge-m3', + } }); }; - // 过滤规则:添加按钮 $('btn-add-filter-rule').onclick = addFilterRule; $('btn-gen-vectors').onclick = () => { if (vectorGenerating) return; postMsg('VECTOR_GENERATE', { config: getVectorConfig() }); }; + $('btn-clear-vectors').onclick = () => { - if (confirm('确定清除当前聊天的向量数据?')) postMsg('VECTOR_CLEAR'); + if (confirm('?????????')) postMsg('VECTOR_CLEAR'); }; + $('btn-cancel-vectors').onclick = () => postMsg('VECTOR_CANCEL_GENERATE'); - // 导入导出 $('btn-export-vectors').onclick = () => { $('btn-export-vectors').disabled = true; - $('vector-io-status').textContent = '导出中...'; + $('vector-io-status').textContent = '???...'; postMsg('VECTOR_EXPORT'); }; $('btn-import-vectors').onclick = () => { - // 让 parent 处理文件选择,避免 iframe 传大文件 $('btn-import-vectors').disabled = true; - $('vector-io-status').textContent = '导入中...'; + $('vector-io-status').textContent = '???...'; postMsg('VECTOR_IMPORT_PICK'); }; + + initAnchorUI(); + postMsg('REQUEST_ANCHOR_STATS'); } // ═══════════════════════════════════════════════════════════════════════════ // Settings Modal @@ -1039,172 +923,48 @@ postMsg('FULLSCREEN_CLOSED'); } - function openHfGuide() { - $('hf-guide-modal').classList.add('active'); - renderHfGuideContent(); - postMsg('FULLSCREEN_OPENED'); - } + function renderArcsEditor(arcs) { + const list = arcs?.length ? arcs : [{ name: '', trajectory: '', progress: 0, moments: [] }]; + const es = $('editor-struct'); - function closeHfGuide() { - $('hf-guide-modal').classList.remove('active'); - postMsg('FULLSCREEN_CLOSED'); - } - - function renderHfGuideContent() { - const body = $('hf-guide-body'); - if (!body || body.innerHTML.trim()) return; - - setHtml(body, ` -
-
-
免费自建 Embedding 服务,10 分钟搞定
-
- 🆓 完全免费 - ⚡ 速度不快 - 🔐 数据私有 -
-
-
-
1创建 Space
-
-

访问 huggingface.co/new-space,登录后创建:

-
    -
  • Space name: 随便取(如 my-embedding
  • -
  • SDK: 选 Docker
  • -
  • Hardware: 选 CPU basic (Free)
  • -
-
-
-
-
2上传 3 个文件
-
-

在 Space 的 Files 页面,依次创建以下文件:

-
-
📄requirements.txt
-
fastapi
-uvicorn
-sentence-transformers
-torch
-
-
-
🐍app.py主程序
-
import os
-os.environ["OMP_NUM_THREADS"] = "1"
-os.environ["MKL_NUM_THREADS"] = "1"
-os.environ["TOKENIZERS_PARALLELISM"] = "false"
-
-import torch
-torch.set_num_threads(1)
-
-import threading
-from functools import lru_cache
-from typing import List, Optional
-from fastapi import FastAPI, HTTPException, Header
-from fastapi.middleware.cors import CORSMiddleware
-from pydantic import BaseModel
-from sentence_transformers import SentenceTransformer
-
-ACCESS_KEY = os.environ.get("ACCESS_KEY", "")
-MODEL_ID = "BAAI/bge-m3"
-
-app = FastAPI()
-app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"])
-
-@lru_cache(maxsize=1)
-def get_model():
-    return SentenceTransformer(MODEL_ID, trust_remote_code=True)
-
-class EmbedRequest(BaseModel):
-    input: List[str]
-    model: Optional[str] = "bge-m3"
-
-@app.post("/v1/embeddings")
-async def embed(req: EmbedRequest, authorization: Optional[str] = Header(None)):
-    if ACCESS_KEY and (authorization or "").replace("Bearer ", "").strip() != ACCESS_KEY:
-        raise HTTPException(401, "Unauthorized")
-    embeddings = get_model().encode(req.input, normalize_embeddings=True)
-    return {"data": [{"embedding": e.tolist(), "index": i} for i, e in enumerate(embeddings)]}
-
-@app.get("/v1/models")
-async def models():
-    return {"data": [{"id": "bge-m3"}]}
-
-@app.get("/health")
-async def health():
-    return {"status": "ok"}
-
-@app.on_event("startup")
-async def startup():
-    threading.Thread(target=get_model, daemon=True).start()
-
-
-
🐳Dockerfile
-
FROM python:3.10-slim
-WORKDIR /app
-COPY requirements.txt .
-RUN pip install --no-cache-dir -r requirements.txt
-COPY app.py ./
-RUN python -c "from sentence_transformers import SentenceTransformer; SentenceTransformer('BAAI/bge-m3', trust_remote_code=True)"
-EXPOSE 7860
-CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860", "--workers", "2"]
+ setHtml(es, ` +
+ ${list.map((a, i) => ` +
+
+
+
+
+
+
角色弧光 ${i + 1}
-
-
-
3等待构建
-
-

上传完成后自动开始构建,约需 10 分钟(下载模型)。

-

成功后状态变为 Running

-
-
-
-
4在插件中配置
-
-
-
服务渠道OpenAI 兼容
-
API URLhttps://用户名-空间名.hf.space
-
API Key随便填
-
模型点"拉取" → 选 bge-m3
-
-
-
-
-
💡 小提示
-
    -
  • URL 格式:https://用户名-空间名.hf.space(减号连接,非斜杠)
  • -
  • 免费 Space 一段时间无请求会休眠,首次唤醒需等 20-30 秒
  • -
  • 如需保持常驻,可用 cron-job.org 每 5 分钟 ping /health
  • -
  • 如需密码,在 Space Settings 设置 ACCESS_KEY 环境变量
  • -
-
+ `).join('')}
+
`); - // Add copy button handlers - body.querySelectorAll('.copy-btn').forEach(btn => { - btn.onclick = async () => { - const code = btn.previousElementSibling?.textContent || ''; - try { - await navigator.clipboard.writeText(code); - btn.textContent = '已复制'; - setTimeout(() => btn.textContent = '复制', 1200); - } catch { - const ta = document.createElement('textarea'); - ta.value = code; - document.body.appendChild(ta); - ta.select(); - document.execCommand('copy'); - ta.remove(); - btn.textContent = '已复制'; - setTimeout(() => btn.textContent = '复制', 1200); - } - }; - }); - } + es.querySelectorAll('.arc-item').forEach(addDeleteHandler); - // ═══════════════════════════════════════════════════════════════════════════ - // Recall Log - // ═══════════════════════════════════════════════════════════════════════════ + $('arc-add').onclick = () => { + const listEl = $('arc-list'); + const idx = listEl.querySelectorAll('.arc-item').length; + const div = document.createElement('div'); + div.className = 'struct-item arc-item'; + div.dataset.index = idx; + setHtml(div, ` +
+
+
+ +
+
+
角色弧光 ${idx + 1}
+ `); + addDeleteHandler(div); + listEl.appendChild(div); + }; + } function setRecallLog(text) { lastRecallLogText = text || ''; @@ -1357,50 +1117,7 @@ CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860", "--workers", " }; } - function renderArcsEditor(arcs) { - const list = arcs?.length ? arcs : [{ name: '', trajectory: '', progress: 0, moments: [] }]; - const es = $('editor-struct'); - - setHtml(es, ` -
- ${list.map((a, i) => ` -
-
-
-
- -
-
-
角色弧光 ${i + 1}
-
- `).join('')} -
-
- `); - - es.querySelectorAll('.arc-item').forEach(addDeleteHandler); - - $('arc-add').onclick = () => { - const listEl = $('arc-list'); - const idx = listEl.querySelectorAll('.arc-item').length; - const div = document.createElement('div'); - div.className = 'struct-item arc-item'; - div.dataset.index = idx; - setHtml(div, ` -
-
-
- -
-
-
角色弧光 ${idx + 1}
- `); - addDeleteHandler(div); - listEl.appendChild(div); - }; - } - - function openEditor(section) { + function openEditor(section) { currentEditSection = section; const meta = SECTION_META[section]; const es = $('editor-struct'); @@ -1615,31 +1332,50 @@ CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860", "--workers", " if (d.config) loadVectorConfig(d.config); break; - case 'VECTOR_LOCAL_MODEL_STATUS': - updateLocalModelStatus(d.status, d.message); - break; - - case 'VECTOR_LOCAL_MODEL_PROGRESS': - updateLocalModelProgress(d.percent); - break; - case 'VECTOR_ONLINE_STATUS': updateOnlineStatus(d.status, d.message); break; - case 'VECTOR_ONLINE_MODELS': - updateOnlineModels(d.models || []); - break; - case 'VECTOR_STATS': updateVectorStats(d.stats); if (d.mismatch !== undefined) showVectorMismatchWarning(d.mismatch); break; - case 'VECTOR_GEN_PROGRESS': - updateVectorGenProgress(d.phase, d.current, d.total); + case 'ANCHOR_STATS': + updateAnchorStats(d.stats || {}); break; + case 'ANCHOR_GEN_PROGRESS': + updateAnchorProgress(d.current, d.total, d.message); + break; + + case 'VECTOR_GEN_PROGRESS': { + const progress = $('vector-gen-progress'); + const btnGen = $('btn-gen-vectors'); + const btnCancel = $('btn-cancel-vectors'); + const btnClear = $('btn-clear-vectors'); + + if (d.current < 0) { + progress.classList.add('hidden'); + btnGen.classList.remove('hidden'); + btnCancel.classList.add('hidden'); + btnClear.classList.remove('hidden'); + vectorGenerating = false; + } else { + vectorGenerating = true; + progress.classList.remove('hidden'); + btnGen.classList.add('hidden'); + btnCancel.classList.remove('hidden'); + btnClear.classList.add('hidden'); + + const percent = d.total > 0 ? Math.round(d.current / d.total * 100) : 0; + progress.querySelector('.progress-inner').style.width = percent + '%'; + const displayText = d.message || `${d.phase || ''}: ${d.current}/${d.total}`; + progress.querySelector('.progress-text').textContent = displayText; + } + break; + } + case 'VECTOR_EXPORT_RESULT': $('btn-export-vectors').disabled = false; if (d.success) { @@ -1772,8 +1508,6 @@ CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860", "--workers", " $('rel-fs-close').onclick = closeRelationsFullscreen; // HF guide - $('hf-guide-backdrop').onclick = closeHfGuide; - $('hf-guide-close').onclick = closeHfGuide; // Character selector $('char-sel-trigger').onclick = e => { diff --git a/modules/story-summary/story-summary.css b/modules/story-summary/story-summary.css index 6fe71c0..a2f5c07 100644 --- a/modules/story-summary/story-summary.css +++ b/modules/story-summary/story-summary.css @@ -2750,3 +2750,126 @@ h1 span { font-size: .8125rem; line-height: 1.8; } + +/* ═══════════════════════════════════════════════════════════════════════════ + 记忆锚点区域(L0) + ═══════════════════════════════════════════════════════════════════════════ */ + +.anchor-section { + margin-top: 20px; + padding: 16px; + background: linear-gradient(135deg, rgba(255, 193, 7, 0.05), rgba(255, 152, 0, 0.05)); + border: 1px solid rgba(255, 193, 7, 0.3); + border-radius: 8px; +} + +.anchor-header { + margin-bottom: 12px; +} + +.anchor-title { + display: flex; + align-items: center; + gap: 6px; + font-size: 0.875rem; + font-weight: 600; + color: var(--txt); + margin-bottom: 4px; +} + +.anchor-icon { + font-size: 1rem; +} + +.anchor-hint { + font-size: 0.75rem; + color: var(--txt3); +} + +.anchor-stats { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px; + font-size: 0.8125rem; + color: var(--txt2); + margin-bottom: 12px; + padding: 8px 12px; + background: var(--bg2); + border-radius: 6px; +} + +.anchor-stat-item { + display: flex; + align-items: center; + gap: 4px; +} + +.anchor-stat-label { + color: var(--txt3); +} + +.anchor-stat-value strong { + color: var(--hl); + font-weight: 600; +} + +.anchor-stat-sep { + color: var(--txt3); +} + +.anchor-stat-pending { + color: #f59e0b; + font-size: 0.75rem; +} + +.anchor-stat-pending strong { + font-weight: 600; +} + +.anchor-progress { + margin-bottom: 12px; +} + +.anchor-actions { + display: flex; + gap: 8px; +} + +.anchor-actions .btn { + flex: 1; + min-width: 0; +} + +.vector-empty-warning { + font-size: 0.75rem; + color: #f59e0b; + margin-top: 6px; +} + +@media (max-width: 768px) { + .anchor-section { + padding: 12px; + } + + .anchor-stats { + flex-direction: column; + align-items: flex-start; + gap: 4px; + } + + .anchor-stat-sep { + display: none; + } +} + +@media (max-width: 480px) { + .anchor-title { + font-size: 0.8125rem; + } + + .anchor-stats { + font-size: 0.75rem; + padding: 6px 10px; + } +} diff --git a/modules/story-summary/story-summary.html b/modules/story-summary/story-summary.html index e0f7e2b..4de2c26 100644 --- a/modules/story-summary/story-summary.html +++ b/modules/story-summary/story-summary.html @@ -83,7 +83,7 @@
-
世界状态
+
世界状态
@@ -116,6 +116,7 @@
选择角色
+
暂无角色
@@ -346,6 +347,8 @@
智能记忆(向量检索)
+ +
+