|
| 1 | +import type { ILocalEmbeddingEngine } from "@readany/core/ai/local-embedding-service"; |
| 2 | +import Constants from "expo-constants"; |
| 3 | +import * as FileSystem from "expo-file-system"; |
| 4 | + |
| 5 | +export class RNEmbeddingEngine implements ILocalEmbeddingEngine { |
| 6 | + private generator: any = null; |
| 7 | + private transformers: any = null; |
| 8 | + |
| 9 | + private async ensureTransformers(): Promise<any> { |
| 10 | + if (this.transformers) return this.transformers; |
| 11 | + |
| 12 | + const isExpoGo = Constants.executionEnvironment === "storeClient" || Constants.appOwnership === "expo"; |
| 13 | + if (isExpoGo) { |
| 14 | + throw new Error("本地向量模型推理依赖 ONNX C++ 原生引擎库。Expo Go 沙盒均不提供。请编译自定义原生客户端体验本地大模型!"); |
| 15 | + } |
| 16 | + |
| 17 | + try { |
| 18 | + this.transformers = await import("@huggingface/transformers"); |
| 19 | + } catch (e) { |
| 20 | + console.warn("[RNEmbeddingEngine] Transformers/ONNX not available natively", e); |
| 21 | + throw e; |
| 22 | + } |
| 23 | + |
| 24 | + const { env } = this.transformers; |
| 25 | + env.allowLocalModels = false; |
| 26 | + |
| 27 | + // Disable WASM threads to prevent issues in strict environments |
| 28 | + if (env.backends?.onnx?.wasm) { |
| 29 | + env.backends.onnx.wasm.numThreads = 1; |
| 30 | + } |
| 31 | + |
| 32 | + // Intercept fetch to cache model files on disk |
| 33 | + const originalFetch = fetch; |
| 34 | + const cacheDir = `${(FileSystem as any).documentDirectory}models/`; |
| 35 | + |
| 36 | + await FileSystem.makeDirectoryAsync(cacheDir, { intermediates: true }).catch(() => {}); |
| 37 | + |
| 38 | + // @ts-ignore - transformers.js v3 allows overriding fetch on the env object |
| 39 | + env.fetch = async (url: RequestInfo | URL, init?: RequestInit) => { |
| 40 | + const urlStr = url.toString(); |
| 41 | + |
| 42 | + // Only cache huggingface model files |
| 43 | + if (!urlStr.includes("huggingface.co")) { |
| 44 | + return originalFetch(url, init); |
| 45 | + } |
| 46 | + |
| 47 | + const filename = urlStr.split("/").pop() || "unknown"; |
| 48 | + // Generate a unique cache key based on URL path to avoid collisions |
| 49 | + const urlPath = new URL(urlStr).pathname.replace(/[^a-zA-Z0-9]/g, "_"); |
| 50 | + const localUri = `${cacheDir}${urlPath}_${filename}`; |
| 51 | + |
| 52 | + try { |
| 53 | + const fileInfo = await FileSystem.getInfoAsync(localUri); |
| 54 | + if (fileInfo.exists) { |
| 55 | + console.log(`[RNEmbeddingEngine] Cache HIT for ${filename}`); |
| 56 | + // Read as binary string, then convert to ArrayBuffer |
| 57 | + const base64 = await FileSystem.readAsStringAsync(localUri, { encoding: "base64" }); |
| 58 | + const binaryStr = atob(base64); |
| 59 | + const len = binaryStr.length; |
| 60 | + const bytes = new Uint8Array(len); |
| 61 | + for (let i = 0; i < len; i++) { |
| 62 | + bytes[i] = binaryStr.charCodeAt(i); |
| 63 | + } |
| 64 | + |
| 65 | + return new Response(bytes.buffer, { |
| 66 | + status: 200, |
| 67 | + headers: new Headers({ "Content-Type": "application/octet-stream" }) |
| 68 | + }); |
| 69 | + } |
| 70 | + } catch (e) { |
| 71 | + console.warn(`[RNEmbeddingEngine] Cache read error for ${filename}:`, e); |
| 72 | + } |
| 73 | + |
| 74 | + console.log(`[RNEmbeddingEngine] Cache MISS for ${filename}. Downloading...`); |
| 75 | + const response = await originalFetch(url, init); |
| 76 | + |
| 77 | + if (response.ok) { |
| 78 | + try { |
| 79 | + // Clone the response so we can both save it and return it |
| 80 | + const resClone = response.clone(); |
| 81 | + const buffer = await resClone.arrayBuffer(); |
| 82 | + const bytes = new Uint8Array(buffer); |
| 83 | + |
| 84 | + // Convert to base64 for writing via Expo FileSystem |
| 85 | + // This is a bit expensive for large models but works reliably |
| 86 | + let binaryStr = ""; |
| 87 | + for (let i = 0; i < bytes.length; i++) { |
| 88 | + binaryStr += String.fromCharCode(bytes[i]); |
| 89 | + } |
| 90 | + const base64 = btoa(binaryStr); |
| 91 | + |
| 92 | + await FileSystem.writeAsStringAsync(localUri, base64, { encoding: "base64" }); |
| 93 | + console.log(`[RNEmbeddingEngine] Saved ${filename} to cache`); |
| 94 | + } catch (e) { |
| 95 | + console.warn(`[RNEmbeddingEngine] Failed to cache ${filename}:`, e); |
| 96 | + } |
| 97 | + } |
| 98 | + |
| 99 | + return response; |
| 100 | + }; |
| 101 | + |
| 102 | + return this.transformers; |
| 103 | + } |
| 104 | + |
| 105 | + async init(): Promise<void> { |
| 106 | + // No-op for Expo initialization to prevent crashing on standard App startup. |
| 107 | + // Transformers and its native modules will be lazily loaded in `load()`. |
| 108 | + } |
| 109 | + |
| 110 | + async load(modelId: string, hfModelId: string, onProgress?: (p: number) => void): Promise<void> { |
| 111 | + const transformers = await this.ensureTransformers().catch(() => null); |
| 112 | + if (!transformers) { |
| 113 | + console.warn("[RNEmbeddingEngine] Transformers engine not loaded. Cannot load model."); |
| 114 | + return; |
| 115 | + } |
| 116 | + try { |
| 117 | + console.log(`[RNEmbeddingEngine] Loading model ${hfModelId}...`); |
| 118 | + |
| 119 | + const { pipeline } = transformers; |
| 120 | + // Initialize pipeline |
| 121 | + this.generator = await pipeline("feature-extraction", hfModelId, { |
| 122 | + progress_callback: (info: any) => { |
| 123 | + if (info.status === "progress" && onProgress) { |
| 124 | + onProgress(info.progress); |
| 125 | + } |
| 126 | + }, |
| 127 | + dtype: "q8", |
| 128 | + }); |
| 129 | + |
| 130 | + console.log(`[RNEmbeddingEngine] Model ${hfModelId} ready!`); |
| 131 | + } catch (e) { |
| 132 | + console.error(`[RNEmbeddingEngine] Failed to load model:`, e); |
| 133 | + throw e; |
| 134 | + } |
| 135 | + } |
| 136 | + |
| 137 | + async generate( |
| 138 | + modelId: string, |
| 139 | + texts: string[], |
| 140 | + onItemProgress?: (done: number, total: number) => void, |
| 141 | + ): Promise<number[][]> { |
| 142 | + if (!this.generator) { |
| 143 | + throw new Error("RNEmbeddingEngine pipeline not loaded."); |
| 144 | + } |
| 145 | + |
| 146 | + const embeddings: number[][] = []; |
| 147 | + for (let i = 0; i < texts.length; i++) { |
| 148 | + const text = texts[i]; |
| 149 | + // Generate embedding for one text |
| 150 | + const output = await this.generator(text, { pooling: "mean", normalize: true }); |
| 151 | + |
| 152 | + // Extract Float32Array to standard JS Array |
| 153 | + embeddings.push(Array.from(output.data)); |
| 154 | + |
| 155 | + onItemProgress?.(i + 1, texts.length); |
| 156 | + } |
| 157 | + return embeddings; |
| 158 | + } |
| 159 | + |
| 160 | + async dispose(): Promise<void> { |
| 161 | + if (this.generator) { |
| 162 | + try { |
| 163 | + await this.generator.dispose(); |
| 164 | + } catch (e) { |
| 165 | + console.warn("[RNEmbeddingEngine] Error disposing pipeline:", e); |
| 166 | + } |
| 167 | + this.generator = null; |
| 168 | + } |
| 169 | + } |
| 170 | + |
| 171 | + async clearCache(hfModelId: string): Promise<void> { |
| 172 | + // Currently relying on React Native's fetch cache or custom polyfills. |
| 173 | + // If transformers.js uses Cache API, we might need a custom clear mechanism. |
| 174 | + this.generator = null; |
| 175 | + console.log(`[RNEmbeddingEngine] Cleared cache flag for ${hfModelId}`); |
| 176 | + } |
| 177 | +} |
0 commit comments