@h-ai/ai 1.0.0-beta.34 → 1.0.0-beta.36
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.en.md +1 -0
- package/README.ja.md +1 -0
- package/README.md +1 -0
- package/dist/{ai-acp-types-cue1ZWUk.d.ts → ai-acp-types-DvA3nO5I.d.ts} +348 -92
- package/dist/{ai-audio-types-4R5yUAVl.d.ts → ai-audio-types-C4n15IHq.d.ts} +21 -21
- package/dist/ai-audio-wav-MnfOlGUF.d.ts +202 -0
- package/dist/{ai-file-types-BN7l67hR.d.ts → ai-file-types-BMfnQU4W.d.ts} +21 -6
- package/dist/ai-file-worker.d.ts +10 -2
- package/dist/ai-file-worker.js +139 -29
- package/dist/ai-file-worker.js.map +1 -1
- package/dist/browser.d.ts +36 -6
- package/dist/browser.js +20 -4
- package/dist/browser.js.map +1 -1
- package/dist/{chunk-C6T3ONVG.js → chunk-A3DZ6LJ5.js} +5 -2
- package/dist/chunk-A3DZ6LJ5.js.map +1 -0
- package/dist/{chunk-HZDINADT.js → chunk-CLCPQTW2.js} +20 -2
- package/dist/chunk-CLCPQTW2.js.map +1 -0
- package/dist/{chunk-UVBQCI7A.js → chunk-ENF7WU4Y.js} +115 -6
- package/dist/chunk-ENF7WU4Y.js.map +1 -0
- package/dist/{chunk-IVEOIRBO.js → chunk-XURRFCRC.js} +37 -31
- package/dist/chunk-XURRFCRC.js.map +1 -0
- package/dist/client/index.d.ts +14 -115
- package/dist/client/index.js +7 -2
- package/dist/client/index.js.map +1 -1
- package/dist/index.d.ts +9 -61
- package/dist/index.js +791 -463
- package/dist/index.js.map +1 -1
- package/package.json +24 -8
- package/dist/chunk-C6T3ONVG.js.map +0 -1
- package/dist/chunk-HZDINADT.js.map +0 -1
- package/dist/chunk-IVEOIRBO.js.map +0 -1
- package/dist/chunk-UVBQCI7A.js.map +0 -1
|
@@ -159,8 +159,8 @@ interface TranscriptionSegment {
|
|
|
159
159
|
*
|
|
160
160
|
* @example
|
|
161
161
|
* ```ts
|
|
162
|
-
* import { ai } from '@h-ai/ai'
|
|
163
|
-
*
|
|
162
|
+
* import { type AudioContent, type TranscriptionOptions, ai } from '@h-ai/ai'
|
|
163
|
+
*
|
|
164
164
|
* async function transcribe(audio: AudioContent) {
|
|
165
165
|
* const options: TranscriptionOptions = { language: 'zh', contextHints: ['hai-framework'], timestampGranularities: ['word'], strictCapabilities: true }
|
|
166
166
|
* const result = await ai.audio.transcribe({ ...options, audio })
|
|
@@ -194,8 +194,8 @@ interface TranscriptionOptions {
|
|
|
194
194
|
*
|
|
195
195
|
* @example
|
|
196
196
|
* ```ts
|
|
197
|
-
* import { ai } from '@h-ai/ai'
|
|
198
|
-
*
|
|
197
|
+
* import { type AudioContent, type TranscriptionRequest, ai } from '@h-ai/ai'
|
|
198
|
+
*
|
|
199
199
|
* async function transcribe(audio: AudioContent) {
|
|
200
200
|
* const request: TranscriptionRequest = { audio, language: 'zh' }
|
|
201
201
|
* const result = await ai.audio.transcribe(request)
|
|
@@ -213,8 +213,8 @@ interface TranscriptionRequest extends TranscriptionOptions {
|
|
|
213
213
|
*
|
|
214
214
|
* @example
|
|
215
215
|
* ```ts
|
|
216
|
-
* import { ai } from '@h-ai/ai'
|
|
217
|
-
*
|
|
216
|
+
* import { type AudioInputStream, type TranscriptionStreamRequest, ai } from '@h-ai/ai'
|
|
217
|
+
*
|
|
218
218
|
* async function transcribe(audio: AudioInputStream) {
|
|
219
219
|
* const request: TranscriptionStreamRequest = { audio, language: 'zh' }
|
|
220
220
|
* // 流式失败通过异步迭代抛出;调用边界应处理异常和取消。
|
|
@@ -314,8 +314,8 @@ interface AudioReference {
|
|
|
314
314
|
*
|
|
315
315
|
* @example
|
|
316
316
|
* ```ts
|
|
317
|
-
* import { ai } from '@h-ai/ai'
|
|
318
|
-
*
|
|
317
|
+
* import { type SynthesisOptions, ai } from '@h-ai/ai'
|
|
318
|
+
*
|
|
319
319
|
* async function speak() {
|
|
320
320
|
* const options: SynthesisOptions = { language: 'zh', format: 'mp3', speed: 1.1 }
|
|
321
321
|
* const result = await ai.audio.synthesize({ ...options, text: '欢迎使用' })
|
|
@@ -363,8 +363,8 @@ interface SynthesisOptions {
|
|
|
363
363
|
*
|
|
364
364
|
* @example
|
|
365
365
|
* ```ts
|
|
366
|
-
* import { ai } from '@h-ai/ai'
|
|
367
|
-
*
|
|
366
|
+
* import { type SynthesisRequest, ai } from '@h-ai/ai'
|
|
367
|
+
*
|
|
368
368
|
* async function speak() {
|
|
369
369
|
* const request: SynthesisRequest = { text: '欢迎使用', format: 'mp3' }
|
|
370
370
|
* const result = await ai.audio.synthesize(request)
|
|
@@ -406,8 +406,8 @@ interface SynthesisTextSegment {
|
|
|
406
406
|
*
|
|
407
407
|
* @example
|
|
408
408
|
* ```ts
|
|
409
|
-
* import { ai } from '@h-ai/ai'
|
|
410
|
-
*
|
|
409
|
+
* import { type SynthesisStreamRequest, ai } from '@h-ai/ai'
|
|
410
|
+
*
|
|
411
411
|
* const request: SynthesisStreamRequest = { text: { id: 'segment-1', text: '欢迎使用。' }, format: 'mp3' }
|
|
412
412
|
* for await (const event of ai.audio.synthesizeStream(request)) {
|
|
413
413
|
* if (event.type === 'segment_done') {
|
|
@@ -425,10 +425,10 @@ interface SynthesisStreamRequest extends SynthesisOptions {
|
|
|
425
425
|
*
|
|
426
426
|
* @example
|
|
427
427
|
* ```ts
|
|
428
|
-
* import {
|
|
429
|
-
*
|
|
428
|
+
* import { type SynthesisResult, ai } from '@h-ai/ai'
|
|
429
|
+
*
|
|
430
430
|
* function playable(result: SynthesisResult) {
|
|
431
|
-
* const serialized = serializePlayableAudio(result)
|
|
431
|
+
* const serialized = ai.serializePlayableAudio(result)
|
|
432
432
|
* if (!serialized.success) return serialized
|
|
433
433
|
* return serialized.data.mimeType
|
|
434
434
|
* }
|
|
@@ -489,8 +489,8 @@ type SynthesisEvent = {
|
|
|
489
489
|
*
|
|
490
490
|
* @example
|
|
491
491
|
* ```ts
|
|
492
|
-
* import { ai } from '@h-ai/ai'
|
|
493
|
-
*
|
|
492
|
+
* import { type AudioModelCapabilities, ai } from '@h-ai/ai'
|
|
493
|
+
*
|
|
494
494
|
* function supportsRealtime(capabilities: AudioModelCapabilities) {
|
|
495
495
|
* return Boolean(capabilities.transcribe?.realtimeAudioInput && capabilities.transcribe.speechBoundaryEvents)
|
|
496
496
|
* }
|
|
@@ -559,8 +559,8 @@ interface AudioModelCapabilities {
|
|
|
559
559
|
*
|
|
560
560
|
* @example
|
|
561
561
|
* ```ts
|
|
562
|
-
* import { ai } from '@h-ai/ai'
|
|
563
|
-
*
|
|
562
|
+
* import { type AudioCapabilitiesRequest, ai } from '@h-ai/ai'
|
|
563
|
+
*
|
|
564
564
|
* const request: AudioCapabilitiesRequest = { operation: 'synthesize' }
|
|
565
565
|
* const result = ai.audio.getCapabilities(request)
|
|
566
566
|
* if (result.success) {
|
|
@@ -582,12 +582,12 @@ interface AudioCapabilitiesRequest {
|
|
|
582
582
|
*
|
|
583
583
|
* @example
|
|
584
584
|
* ```ts
|
|
585
|
-
* import { ai
|
|
585
|
+
* import { ai } from '@h-ai/ai'
|
|
586
586
|
* async function speak() {
|
|
587
587
|
* // ai 已由应用初始化;非流式方法逐层检查 HaiResult。
|
|
588
588
|
* const result = await ai.audio.synthesize({ text: '欢迎使用', format: 'mp3' })
|
|
589
589
|
* if (!result.success) return result
|
|
590
|
-
* const playable = serializePlayableAudio(result.data)
|
|
590
|
+
* const playable = ai.serializePlayableAudio(result.data)
|
|
591
591
|
* if (!playable.success) return playable
|
|
592
592
|
* return playable.data
|
|
593
593
|
* }
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
import { m as TranscriptionRequest, n as TranscriptionResult, p as TranscriptionStreamRequest, T as TranscriptionEvent, h as SynthesisRequest, i as SynthesisResult, j as SynthesisStreamRequest, S as SynthesisEvent } from './ai-audio-types-C4n15IHq.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* @h-ai/ai/client — 浏览器语音客户端
|
|
5
|
+
*
|
|
6
|
+
* 通过统一 WebSocket 连接 `@h-ai/serv` 的语音入口,向浏览器暴露与 Node 端一致的
|
|
7
|
+
* `ai.audio.*` 业务 API。WebSocket 建立、消息编解码等传输细节在此内部完成,
|
|
8
|
+
* 调用方不接触任何厂商原生事件。
|
|
9
|
+
* @module client/ai-audio-client
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* getTicket 收到的当前 Audio 请求摘要
|
|
14
|
+
*
|
|
15
|
+
* 供应用签发与本次操作严格绑定的能力票据(如 `iam.ticket.issue({ grant })`),
|
|
16
|
+
* 使票据只能用于本次操作 / 模型 / 会话,降低票据被重放的风险。
|
|
17
|
+
*
|
|
18
|
+
* @example
|
|
19
|
+
* ```ts
|
|
20
|
+
* import type { AudioTicketRequest } from '@h-ai/ai/client'
|
|
21
|
+
* function grant(request: AudioTicketRequest) {
|
|
22
|
+
* return { operation: request.operation, model: request.model } // 经已登录 HTTP 接口签发并在服务端原子消费。
|
|
23
|
+
* }
|
|
24
|
+
* ```
|
|
25
|
+
*/
|
|
26
|
+
interface AudioTicketRequest {
|
|
27
|
+
/** 本次操作类型 */
|
|
28
|
+
operation: 'transcribe' | 'synthesize';
|
|
29
|
+
/** 本次使用的模型 ID(如有指定) */
|
|
30
|
+
model?: string;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* 浏览器语音客户端配置
|
|
34
|
+
*
|
|
35
|
+
* @example
|
|
36
|
+
* ```ts
|
|
37
|
+
* import { type AudioTicketRequest, ai } from '@h-ai/ai/client'
|
|
38
|
+
*
|
|
39
|
+
* function connect(issueTicket: (request: AudioTicketRequest) => Promise<string>) {
|
|
40
|
+
* return ai.createAudioClient({ url: 'wss://example.com/api/v1/ai/audio', getTicket: issueTicket })
|
|
41
|
+
* }
|
|
42
|
+
* ```
|
|
43
|
+
*/
|
|
44
|
+
interface AudioClientConfig {
|
|
45
|
+
/** 语音 WebSocket 完整 URL(如 `wss://host/api/v1/ai/audio`) */
|
|
46
|
+
url: string;
|
|
47
|
+
/**
|
|
48
|
+
* 获取短期、一次性的 Audio WebSocket ticket
|
|
49
|
+
*
|
|
50
|
+
* ticket 应由已登录 HTTP 请求签发,并在服务端首次校验时原子消费。
|
|
51
|
+
* 收到当前请求摘要(operation / model),可签发与本次操作严格绑定的票据。
|
|
52
|
+
*/
|
|
53
|
+
getTicket: (request: AudioTicketRequest) => string | Promise<string>;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* 浏览器语音操作接口
|
|
57
|
+
*
|
|
58
|
+
* 与 Node 端 `AudioOperations` 业务形态一致;出错时抛出异常(浏览器 Client 约定)。
|
|
59
|
+
*
|
|
60
|
+
* @example
|
|
61
|
+
* ```ts
|
|
62
|
+
* import type { AudioClientOperations } from '@h-ai/ai/client'
|
|
63
|
+
* async function speak(audio: AudioClientOperations) {
|
|
64
|
+
* // 浏览器 AudioClient 普通方法也显式抛错,由应用交互边界处理。
|
|
65
|
+
* const result = await audio.synthesize({ text: '你好', format: 'mp3' })
|
|
66
|
+
* return result.data
|
|
67
|
+
* }
|
|
68
|
+
* ```
|
|
69
|
+
*/
|
|
70
|
+
interface AudioClientOperations {
|
|
71
|
+
/** 将完整音频识别为完整文本 */
|
|
72
|
+
transcribe: (request: TranscriptionRequest) => Promise<TranscriptionResult>;
|
|
73
|
+
/** 持续输入音频或增量返回识别文本(含语音起止事件) */
|
|
74
|
+
transcribeStream: (request: TranscriptionStreamRequest) => AsyncIterable<TranscriptionEvent>;
|
|
75
|
+
/** 将完整文本合成为完整音频 */
|
|
76
|
+
synthesize: (request: SynthesisRequest) => Promise<SynthesisResult>;
|
|
77
|
+
/** 持续输入文本段并按段输出结构化音频事件 */
|
|
78
|
+
synthesizeStream: (request: SynthesisStreamRequest) => AsyncIterable<SynthesisEvent>;
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* 创建浏览器语音客户端
|
|
82
|
+
*
|
|
83
|
+
* @param config - 语音客户端配置
|
|
84
|
+
* @returns 浏览器语音操作接口
|
|
85
|
+
*
|
|
86
|
+
* @example
|
|
87
|
+
* ```ts
|
|
88
|
+
* import { type AudioTicketRequest, ai } from '@h-ai/ai/client'
|
|
89
|
+
*
|
|
90
|
+
* function connect(issueTicket: (request: AudioTicketRequest) => Promise<string>) {
|
|
91
|
+
* return ai.createAudioClient({ url: 'wss://example.com/api/v1/ai/audio', getTicket: issueTicket })
|
|
92
|
+
* }
|
|
93
|
+
* ```
|
|
94
|
+
*/
|
|
95
|
+
declare function createAudioClient(config: AudioClientConfig): AudioClientOperations;
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* 麦克风会话选项。应用通过回调决定何时转写和保存录音。
|
|
99
|
+
* @example
|
|
100
|
+
* ```ts
|
|
101
|
+
* import type { AudioRecorderOptions } from '@h-ai/ai/client'
|
|
102
|
+
* const options: AudioRecorderOptions = { maxDurationSeconds: 30, onStop: blob => void blob.size }
|
|
103
|
+
* ```
|
|
104
|
+
*/
|
|
105
|
+
interface AudioRecorderOptions {
|
|
106
|
+
/** 请求麦克风时使用的音轨约束,默认 true。 */
|
|
107
|
+
audio?: MediaTrackConstraints | true;
|
|
108
|
+
/** MediaRecorder 的编码选项。 */
|
|
109
|
+
encoding?: MediaRecorderOptions;
|
|
110
|
+
/** 分段间隔,毫秒,默认 250。 */
|
|
111
|
+
timesliceMs?: number;
|
|
112
|
+
/** 达到录音时长上限后停止并发布最后一段数据。 */
|
|
113
|
+
maxDurationSeconds?: number;
|
|
114
|
+
/** 超过编码字节上限时中止并调用 onError。 */
|
|
115
|
+
maxInputBytes?: number;
|
|
116
|
+
/** 正常停止后的完整录音。 */
|
|
117
|
+
onStop: (recording: Blob) => void;
|
|
118
|
+
/** 录音开始后发生的编码或容量错误。 */
|
|
119
|
+
onError?: (error: Error) => void;
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* 浏览器麦克风会话。
|
|
123
|
+
* @example
|
|
124
|
+
* ```ts
|
|
125
|
+
* import { ai } from '@h-ai/ai/client'
|
|
126
|
+
* const recorder = ai.createAudioRecorder({ onStop: blob => void blob.size })
|
|
127
|
+
* recorder.close()
|
|
128
|
+
* ```
|
|
129
|
+
*/
|
|
130
|
+
interface AudioRecorder {
|
|
131
|
+
/** 请求麦克风并开始录音,权限、设备和配置失败时 reject。 */
|
|
132
|
+
start: () => Promise<void>;
|
|
133
|
+
/** 正常停止,最终数据随后由 onStop 发布。 */
|
|
134
|
+
stop: () => void;
|
|
135
|
+
/** 返回已经收到的录音分段,不改变录音状态。 */
|
|
136
|
+
snapshot: () => Blob;
|
|
137
|
+
/** 放弃本次录音及未完成的麦克风申请,释放已有轨道。 */
|
|
138
|
+
close: () => void;
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* 创建独立的浏览器麦克风会话,故读取权限及编码状态不依赖 AI 服务。
|
|
142
|
+
* @param options - 录音约束、会话上限和结果回调
|
|
143
|
+
* @returns 可开始、快照、停止或释放的会话实例
|
|
144
|
+
* @throws 上限或分段间隔无效时抛出 RangeError
|
|
145
|
+
* @example
|
|
146
|
+
* ```ts
|
|
147
|
+
* import { ai } from '@h-ai/ai/client'
|
|
148
|
+
* async function record() {
|
|
149
|
+
* const recorder = ai.createAudioRecorder({ onStop: blob => void blob.size })
|
|
150
|
+
* await recorder.start()
|
|
151
|
+
* return recorder
|
|
152
|
+
* }
|
|
153
|
+
* ```
|
|
154
|
+
*/
|
|
155
|
+
declare function createAudioRecorder(options: AudioRecorderOptions): AudioRecorder;
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* 浏览器端 WAV 编码工具
|
|
159
|
+
*
|
|
160
|
+
* MediaRecorder 通常输出 webm/opus,而多数 ASR 服务(如 MiMo)仅接受 wav/mp3,
|
|
161
|
+
* 故录音快照先用 Web Audio API 解码,再重采样为单声道并编码为 16bit PCM WAV。
|
|
162
|
+
* 所有 API 均为浏览器专用(AudioContext / OfflineAudioContext),仅在客户端调用。
|
|
163
|
+
* @module audio/wav
|
|
164
|
+
*/
|
|
165
|
+
/**
|
|
166
|
+
* WAV 转换的目标格式和处理上限。
|
|
167
|
+
* @example
|
|
168
|
+
* ```ts
|
|
169
|
+
* import type { AudioWavOptions } from '@h-ai/ai/client'
|
|
170
|
+
* const options: AudioWavOptions = { maxInputBytes: 1024 * 1024, maxDurationSeconds: 30, overflow: 'truncate' }
|
|
171
|
+
* ```
|
|
172
|
+
*/
|
|
173
|
+
interface AudioWavOptions {
|
|
174
|
+
/** 输出采样率,单位 Hz,默认 16000。 */
|
|
175
|
+
sampleRate?: number;
|
|
176
|
+
/** 解码前允许的 Blob 最大字节数。 */
|
|
177
|
+
maxInputBytes?: number;
|
|
178
|
+
/** 输出 PCM 的最长秒数,在解码后、重采样前检查。 */
|
|
179
|
+
maxDurationSeconds?: number;
|
|
180
|
+
/** 超过最长秒数时默认拒绝,设为 truncate 时保留开头。 */
|
|
181
|
+
overflow?: 'reject' | 'truncate';
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* 将任意浏览器可解码的音频 Blob(如 MediaRecorder 的 webm)转换为单声道 16bit PCM WAV。
|
|
185
|
+
*
|
|
186
|
+
* @param blob - 录制得到的原始音频
|
|
187
|
+
* @param options - 目标采样率(兼容旧调用)或含转换上限的配置
|
|
188
|
+
* @throws 配置无效、输入超限、解码失败或超时长且未指定截断时抛错
|
|
189
|
+
* @returns `audio/wav` 类型的 Blob
|
|
190
|
+
* @example
|
|
191
|
+
* ```ts
|
|
192
|
+
* import { ai } from '@h-ai/ai/client'
|
|
193
|
+
* async function prepareRecording(recording: Blob) {
|
|
194
|
+
* const wav = await ai.blobToWav(recording)
|
|
195
|
+
* return new File([wav], 'recording.wav', { type: wav.type })
|
|
196
|
+
* }
|
|
197
|
+
* ```
|
|
198
|
+
*/
|
|
199
|
+
declare function blobToWav(blob: Blob, options?: number | AudioWavOptions): Promise<Blob>;
|
|
200
|
+
|
|
201
|
+
export { createAudioClient as a, blobToWav as b, createAudioRecorder as c };
|
|
202
|
+
export type { AudioClientConfig as A, AudioClientOperations as d, AudioRecorder as e, AudioRecorderOptions as f, AudioTicketRequest as g, AudioWavOptions as h };
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { HaiResult } from '@h-ai/core';
|
|
2
|
-
import { Buffer } from 'node:buffer';
|
|
3
2
|
|
|
4
3
|
/**
|
|
5
4
|
* @h-ai/ai — File 子功能类型
|
|
@@ -50,6 +49,18 @@ type OutputFormat = 'text' | 'markdown';
|
|
|
50
49
|
* ```
|
|
51
50
|
*/
|
|
52
51
|
interface FileParseOptions {
|
|
52
|
+
/** 默认模式允许现有 OCR 路径。local 仅在当前 Node 进程解析,且无需初始化 AI。 */
|
|
53
|
+
mode?: 'auto' | 'local';
|
|
54
|
+
/** 本地模式单文件字节上限,默认 4 MiB。 */
|
|
55
|
+
maxInputBytes?: number;
|
|
56
|
+
/** 本地模式输出 UTF-16 长度上限,默认 12000,超限返回标有省略号的摘录。 */
|
|
57
|
+
maxTextLength?: number;
|
|
58
|
+
/** 本地 DOCX 的 ZIP 条目上限,默认 512。 */
|
|
59
|
+
maxZipEntries?: number;
|
|
60
|
+
/** 本地 DOCX 的实际解压总字节上限,默认 24 MiB。 */
|
|
61
|
+
maxExpandedBytes?: number;
|
|
62
|
+
/** 本地解析超时毫秒数,默认 20000,超时会停止解析线程。 */
|
|
63
|
+
timeoutMs?: number;
|
|
53
64
|
/** 强制使用指定 MIME 类型(覆盖自动检测) */
|
|
54
65
|
mimeType?: string;
|
|
55
66
|
/** 强制使用 OCR(即使有原生解析器支持) */
|
|
@@ -63,7 +74,7 @@ interface FileParseOptions {
|
|
|
63
74
|
model?: string;
|
|
64
75
|
/** OCR 系统提示词(覆盖全局 `file.systemPrompt` 配置) */
|
|
65
76
|
systemPrompt?: string;
|
|
66
|
-
/** PDF
|
|
77
|
+
/** PDF 最大解析页数(本地模式默认 100,其他模式默认解析全部页)。 */
|
|
67
78
|
maxPages?: number;
|
|
68
79
|
/**
|
|
69
80
|
* 输出格式(默认 `'text'`)
|
|
@@ -84,14 +95,16 @@ interface FileParseRequest {
|
|
|
84
95
|
/**
|
|
85
96
|
* 文件内容
|
|
86
97
|
*
|
|
87
|
-
* - `Buffer` — 二进制文件(图片、PDF、DOCX 等)
|
|
98
|
+
* - `Buffer` 或 `Uint8Array` — 二进制文件(图片、PDF、DOCX 等)
|
|
88
99
|
* - `string` — 文本内容(直接传入文本格式文件)
|
|
89
100
|
*/
|
|
90
|
-
content:
|
|
101
|
+
content: Uint8Array | string;
|
|
91
102
|
/** 文件名(用于 MIME 类型自动检测,可选) */
|
|
92
103
|
filename?: string;
|
|
93
104
|
/** 解析选项 */
|
|
94
105
|
options?: FileParseOptions;
|
|
106
|
+
/** 本地模式取消信号,取消时停止解析线程。 */
|
|
107
|
+
signal?: AbortSignal;
|
|
95
108
|
}
|
|
96
109
|
/**
|
|
97
110
|
* 文件解析结果
|
|
@@ -117,12 +130,14 @@ interface FileParseResult {
|
|
|
117
130
|
filename?: string;
|
|
118
131
|
mimeType?: string;
|
|
119
132
|
charCount?: number;
|
|
133
|
+
/** 本地模式因页数或字符上限返回了摘录。 */
|
|
134
|
+
truncated?: boolean;
|
|
120
135
|
};
|
|
121
136
|
}
|
|
122
137
|
/**
|
|
123
138
|
* File 操作接口(通过 `ai.file` 访问)
|
|
124
139
|
*
|
|
125
|
-
*
|
|
140
|
+
* 可在初始化前调用 `parse({ options: { mode: 'local' } })`。默认模式需要 AI 初始化,OCR 需要 LLM 配置。
|
|
126
141
|
*
|
|
127
142
|
* 支持的格式:
|
|
128
143
|
* - 文本格式(txt、md、csv 等):直接解码
|
|
@@ -161,7 +176,7 @@ interface FileOperations {
|
|
|
161
176
|
* @param filename - 文件名(用于格式检测,可选)
|
|
162
177
|
* @returns 提取的文本内容
|
|
163
178
|
*/
|
|
164
|
-
parseText: (content:
|
|
179
|
+
parseText: (content: Uint8Array | string, filename?: string) => Promise<HaiResult<string>>;
|
|
165
180
|
}
|
|
166
181
|
|
|
167
182
|
export type { FileOperations as F, OutputFormat as O, FileParseMethod as a, FileParseOptions as b, FileParseRequest as c, FileParseResult as d };
|
package/dist/ai-file-worker.d.ts
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { Locale, HaiResult } from '@h-ai/core';
|
|
2
2
|
import { OutputFormat } from './browser.js';
|
|
3
|
-
import 'node:buffer';
|
|
4
3
|
|
|
5
4
|
/**
|
|
6
5
|
* 本地解析任务仅携带文件内容、格式和调用语言。
|
|
@@ -12,7 +11,15 @@ import 'node:buffer';
|
|
|
12
11
|
type FileParseJob = {
|
|
13
12
|
format: OutputFormat;
|
|
14
13
|
locale: Locale;
|
|
14
|
+
limits?: {
|
|
15
|
+
maxTextLength: number;
|
|
16
|
+
maxZipEntries: number;
|
|
17
|
+
maxExpandedBytes: number;
|
|
18
|
+
};
|
|
15
19
|
} & ({
|
|
20
|
+
type: 'text';
|
|
21
|
+
content: string | Uint8Array;
|
|
22
|
+
} | {
|
|
16
23
|
type: 'html';
|
|
17
24
|
content: string | Uint8Array;
|
|
18
25
|
} | {
|
|
@@ -27,12 +34,13 @@ type FileParseJob = {
|
|
|
27
34
|
* 本地解析成功后附带正文和 PDF 页数。
|
|
28
35
|
* @example 模块内部上下文
|
|
29
36
|
* ```ts
|
|
30
|
-
* const reply: FileParseReply = ok({ text: 'Report', pageCount: 1 })
|
|
37
|
+
* const reply: FileParseReply = core.ok({ text: 'Report', pageCount: 1 })
|
|
31
38
|
* ```
|
|
32
39
|
*/
|
|
33
40
|
type FileParseReply = HaiResult<{
|
|
34
41
|
text: string;
|
|
35
42
|
pageCount?: number;
|
|
43
|
+
truncated?: boolean;
|
|
36
44
|
}>;
|
|
37
45
|
|
|
38
46
|
export type { FileParseJob, FileParseReply };
|
package/dist/ai-file-worker.js
CHANGED
|
@@ -1,38 +1,112 @@
|
|
|
1
1
|
import { parseHtmlFile } from './chunk-OWR55FRO.js';
|
|
2
|
-
import { aiM } from './chunk-
|
|
3
|
-
import { HaiAIError } from './chunk-
|
|
2
|
+
import { aiM } from './chunk-CLCPQTW2.js';
|
|
3
|
+
import { HaiAIError } from './chunk-A3DZ6LJ5.js';
|
|
4
4
|
import { Buffer } from 'buffer';
|
|
5
5
|
import { parentPort } from 'worker_threads';
|
|
6
|
-
import { core
|
|
6
|
+
import { core } from '@h-ai/core';
|
|
7
|
+
import { fromBuffer } from 'yauzl';
|
|
8
|
+
import { fileURLToPath } from 'url';
|
|
7
9
|
|
|
8
|
-
async function
|
|
10
|
+
async function verifyDocxArchive(content, maxEntries, maxExpandedBytes) {
|
|
11
|
+
const buffer = Buffer.from(content.buffer, content.byteOffset, content.byteLength);
|
|
12
|
+
const archive = await new Promise((resolve, reject) => {
|
|
13
|
+
fromBuffer(buffer, { lazyEntries: true, validateEntrySizes: true, strictFileNames: true }, (error, zip) => {
|
|
14
|
+
if (error)
|
|
15
|
+
reject(error);
|
|
16
|
+
else
|
|
17
|
+
resolve(zip);
|
|
18
|
+
});
|
|
19
|
+
});
|
|
20
|
+
const names = /* @__PURE__ */ new Set();
|
|
21
|
+
let expanded = 0;
|
|
22
|
+
try {
|
|
23
|
+
if (archive.entryCount > maxEntries)
|
|
24
|
+
throw new Error("Too many Word archive entries");
|
|
25
|
+
await new Promise((resolve, reject) => {
|
|
26
|
+
archive.once("error", reject);
|
|
27
|
+
archive.once("end", resolve);
|
|
28
|
+
archive.on("entry", (entry) => {
|
|
29
|
+
expanded += entry.uncompressedSize;
|
|
30
|
+
if (expanded > maxExpandedBytes || names.has(entry.fileName)) {
|
|
31
|
+
reject(new Error("Invalid Word archive limits"));
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
names.add(entry.fileName);
|
|
35
|
+
if (entry.fileName.endsWith("/")) {
|
|
36
|
+
if (entry.uncompressedSize === 0)
|
|
37
|
+
archive.readEntry();
|
|
38
|
+
else
|
|
39
|
+
reject(new Error("Invalid Word archive directory"));
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
archive.openReadStream(entry, (error, stream) => {
|
|
43
|
+
if (error) {
|
|
44
|
+
reject(error);
|
|
45
|
+
return;
|
|
46
|
+
}
|
|
47
|
+
stream.once("error", reject);
|
|
48
|
+
stream.once("end", () => archive.readEntry());
|
|
49
|
+
stream.resume();
|
|
50
|
+
});
|
|
51
|
+
});
|
|
52
|
+
archive.readEntry();
|
|
53
|
+
});
|
|
54
|
+
if (!names.has("[Content_Types].xml") || !names.has("word/document.xml"))
|
|
55
|
+
throw new Error("Invalid Word archive structure");
|
|
56
|
+
} finally {
|
|
57
|
+
archive.close();
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
async function parsePdfContent(content, outputFormat = "text", maxPages, maxTextLength) {
|
|
9
61
|
try {
|
|
10
|
-
const
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
62
|
+
const { getDocument } = await import('pdfjs-dist/legacy/build/pdf.mjs');
|
|
63
|
+
const local = maxTextLength !== void 0;
|
|
64
|
+
const pdfjsRoot = local ? new URL("../../", import.meta.resolve("pdfjs-dist/legacy/build/pdf.mjs")) : void 0;
|
|
65
|
+
const loadingTask = getDocument({
|
|
66
|
+
data: content,
|
|
67
|
+
...pdfjsRoot && {
|
|
68
|
+
cMapUrl: fileURLToPath(new URL("cmaps/", pdfjsRoot)),
|
|
69
|
+
standardFontDataUrl: fileURLToPath(new URL("standard_fonts/", pdfjsRoot)),
|
|
70
|
+
enableXfa: false,
|
|
71
|
+
useSystemFonts: false,
|
|
72
|
+
useWorkerFetch: false,
|
|
73
|
+
useWasm: false,
|
|
74
|
+
stopAtErrors: true
|
|
75
|
+
}
|
|
76
|
+
});
|
|
15
77
|
try {
|
|
16
78
|
const pdf = await loadingTask.promise;
|
|
17
79
|
const totalPages = pdf.numPages;
|
|
18
80
|
const pagesToProcess = maxPages ? Math.min(maxPages, totalPages) : totalPages;
|
|
81
|
+
const separator = outputFormat === "markdown" ? "\n\n---\n\n" : "\n\n";
|
|
19
82
|
const textParts = [];
|
|
83
|
+
let textLength = 0;
|
|
20
84
|
for (let i = 1; i <= pagesToProcess; i++) {
|
|
21
85
|
const page = await pdf.getPage(i);
|
|
22
86
|
const textContent = await page.getTextContent();
|
|
23
|
-
const pageText = textContent.items.map((item) =>
|
|
87
|
+
const pageText = textContent.items.map((item) => {
|
|
88
|
+
if (!("str" in item))
|
|
89
|
+
return "";
|
|
90
|
+
return local && item.hasEOL ? `${item.str}
|
|
91
|
+
` : item.str;
|
|
92
|
+
}).join(" ");
|
|
24
93
|
textParts.push(pageText);
|
|
94
|
+
textLength += pageText.length + (i === 1 ? 0 : separator.length);
|
|
95
|
+
if (local)
|
|
96
|
+
page.cleanup();
|
|
97
|
+
if (maxTextLength !== void 0 && textLength > maxTextLength)
|
|
98
|
+
break;
|
|
25
99
|
}
|
|
26
|
-
|
|
27
|
-
return ok({
|
|
100
|
+
return core.ok({
|
|
28
101
|
text: textParts.join(separator),
|
|
29
|
-
pageCount: totalPages
|
|
102
|
+
pageCount: totalPages,
|
|
103
|
+
...local && (pagesToProcess < totalPages || textLength > maxTextLength) ? { truncated: true } : {}
|
|
30
104
|
});
|
|
31
105
|
} finally {
|
|
32
106
|
await loadingTask.destroy();
|
|
33
107
|
}
|
|
34
108
|
} catch (error) {
|
|
35
|
-
return err(HaiAIError.FILE_PARSE_FAILED, aiM("ai_fileParseFailed", {
|
|
109
|
+
return core.err(HaiAIError.FILE_PARSE_FAILED, aiM("ai_fileParseFailed", {
|
|
36
110
|
params: {
|
|
37
111
|
error: String(error)
|
|
38
112
|
}
|
|
@@ -41,22 +115,19 @@ async function parsePdfContent(content, outputFormat = "text", maxPages) {
|
|
|
41
115
|
}
|
|
42
116
|
async function parseDocxContent(content, outputFormat = "text") {
|
|
43
117
|
try {
|
|
44
|
-
const mammoth = await import(
|
|
45
|
-
// @ts-expect-error — mammoth is an optional peer dependency
|
|
46
|
-
'mammoth'
|
|
47
|
-
);
|
|
118
|
+
const { default: mammoth } = await import('mammoth');
|
|
48
119
|
if (outputFormat === "markdown") {
|
|
49
120
|
const result2 = await mammoth.convertToHtml({
|
|
50
121
|
buffer: Buffer.from(content.buffer, content.byteOffset, content.byteLength)
|
|
51
122
|
});
|
|
52
|
-
return ok(parseHtmlFile(result2.value, "markdown"));
|
|
123
|
+
return core.ok(parseHtmlFile(result2.value, "markdown"));
|
|
53
124
|
}
|
|
54
125
|
const result = await mammoth.extractRawText({
|
|
55
126
|
buffer: Buffer.from(content.buffer, content.byteOffset, content.byteLength)
|
|
56
127
|
});
|
|
57
|
-
return ok(result.value);
|
|
128
|
+
return core.ok(result.value);
|
|
58
129
|
} catch (error) {
|
|
59
|
-
return err(HaiAIError.FILE_PARSE_FAILED, aiM("ai_fileParseFailed", {
|
|
130
|
+
return core.err(HaiAIError.FILE_PARSE_FAILED, aiM("ai_fileParseFailed", {
|
|
60
131
|
params: {
|
|
61
132
|
error: String(error)
|
|
62
133
|
}
|
|
@@ -65,17 +136,56 @@ async function parseDocxContent(content, outputFormat = "text") {
|
|
|
65
136
|
}
|
|
66
137
|
|
|
67
138
|
// src/file/ai-file-worker.ts
|
|
68
|
-
async function
|
|
69
|
-
if (job.type === "html") {
|
|
70
|
-
const
|
|
71
|
-
|
|
72
|
-
|
|
139
|
+
async function extract(job) {
|
|
140
|
+
if (job.type === "text" || job.type === "html") {
|
|
141
|
+
const source = typeof job.content === "string" ? job.content : new TextDecoder("utf-8", {
|
|
142
|
+
fatal: Boolean(job.limits)
|
|
143
|
+
}).decode(job.content);
|
|
144
|
+
if (job.limits) {
|
|
145
|
+
for (const character of source) {
|
|
146
|
+
const code = character.charCodeAt(0);
|
|
147
|
+
if (code < 32 && code !== 9 && code !== 10 && code !== 13 || code === 127)
|
|
148
|
+
return core.err(HaiAIError.FILE_INVALID_CONTENT, aiM("ai_fileLocalInvalid"));
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
return core.ok({
|
|
152
|
+
text: job.type === "html" ? parseHtmlFile(source, job.format) : source.replace(/\r\n?/g, "\n")
|
|
73
153
|
});
|
|
74
154
|
}
|
|
75
|
-
if (job.type === "pdf")
|
|
76
|
-
|
|
155
|
+
if (job.type === "pdf") {
|
|
156
|
+
if (job.limits && Buffer.from(job.content.subarray(0, 5)).toString("ascii") !== "%PDF-")
|
|
157
|
+
return core.err(HaiAIError.FILE_INVALID_CONTENT, aiM("ai_fileLocalInvalid"));
|
|
158
|
+
return parsePdfContent(job.content, job.format, job.maxPages, job.limits?.maxTextLength);
|
|
159
|
+
}
|
|
160
|
+
if (job.limits)
|
|
161
|
+
await verifyDocxArchive(job.content, job.limits.maxZipEntries, job.limits.maxExpandedBytes);
|
|
77
162
|
const result = await parseDocxContent(job.content, job.format);
|
|
78
|
-
return result.success ? ok({ text: result.data }) : result;
|
|
163
|
+
return result.success ? core.ok({ text: result.data }) : result;
|
|
164
|
+
}
|
|
165
|
+
async function parse(job) {
|
|
166
|
+
if (!job.limits)
|
|
167
|
+
return extract(job);
|
|
168
|
+
try {
|
|
169
|
+
const result = await extract(job);
|
|
170
|
+
if (!result.success) {
|
|
171
|
+
return result.error.code === HaiAIError.FILE_INVALID_CONTENT.code ? result : core.err(HaiAIError.FILE_PARSE_FAILED, aiM("ai_fileLocalFailed"));
|
|
172
|
+
}
|
|
173
|
+
const text = result.data.text.trim();
|
|
174
|
+
if (!text)
|
|
175
|
+
return core.err(HaiAIError.FILE_INVALID_CONTENT, aiM("ai_fileLocalNoText"));
|
|
176
|
+
const limit = job.limits.maxTextLength;
|
|
177
|
+
if (!result.data.truncated && text.length <= limit)
|
|
178
|
+
return core.ok({ ...result.data, text });
|
|
179
|
+
const suffix = limit > 1 ? "\n\u2026" : "\u2026";
|
|
180
|
+
const excerpt = text.slice(0, limit - suffix.length).replace(new RegExp("\\p{Surrogate}$", "u"), "").trimEnd();
|
|
181
|
+
return core.ok({
|
|
182
|
+
...result.data,
|
|
183
|
+
text: excerpt ? `${excerpt}${suffix}` : "\u2026",
|
|
184
|
+
truncated: true
|
|
185
|
+
});
|
|
186
|
+
} catch {
|
|
187
|
+
return core.err(HaiAIError.FILE_INVALID_CONTENT, aiM("ai_fileLocalInvalid"));
|
|
188
|
+
}
|
|
79
189
|
}
|
|
80
190
|
parentPort?.on("message", async (job) => {
|
|
81
191
|
const result = await core.i18n.runWithLocale(job.locale, () => parse(job));
|