mirror of
https://github.com/margrop/wrong-notebook.git
synced 2026-12-05 07:29:27 +08:00
merge: 按 data URL 声明解析图片 MIME 类型
This commit is contained in:
21
src/__tests__/unit/ai/data-url.test.ts
Normal file
21
src/__tests__/unit/ai/data-url.test.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { parseImagePayload } from '@/lib/ai/image-data-url';
|
||||
|
||||
describe('parseImagePayload 解析图片 data URL', () => {
|
||||
it('data URL 声明类型优先于传入的 mimeType', () => {
|
||||
expect(parseImagePayload('data:image/png;base64,iVBORw0KGgo=', 'image/jpeg'))
|
||||
.toEqual({ mimeType: 'image/png', data: 'iVBORw0KGgo=' });
|
||||
});
|
||||
|
||||
it('兼容含 + / - 的 MIME 子类型', () => {
|
||||
expect(parseImagePayload('data:image/svg+xml;base64,PHN2Zz4='))
|
||||
.toEqual({ mimeType: 'image/svg+xml', data: 'PHN2Zz4=' });
|
||||
expect(parseImagePayload('data:image/x-png;base64,AAAA'))
|
||||
.toEqual({ mimeType: 'image/x-png', data: 'AAAA' });
|
||||
});
|
||||
|
||||
it('纯 base64 使用传入的 mimeType,缺省回退 image/jpeg', () => {
|
||||
expect(parseImagePayload('QUJD', 'image/webp')).toEqual({ mimeType: 'image/webp', data: 'QUJD' });
|
||||
expect(parseImagePayload('QUJD')).toEqual({ mimeType: 'image/jpeg', data: 'QUJD' });
|
||||
});
|
||||
});
|
||||
@@ -437,3 +437,36 @@ describe('Gemini Provider 用量与请求 ID', () => {
|
||||
expect(observer.mock.calls[0][0]).toMatchObject({ requestId: 'gateway-2', model: 'gemini-2.0-flash' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('Gemini Provider 图片 data URL 类型解析', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
const reanswerReply = '<answer_text>x=1</answer_text><analysis>移项</analysis><knowledge_points>一元一次方程</knowledge_points>';
|
||||
|
||||
it.each([
|
||||
['data:image/png;base64,iVBORw0KGgo=', 'image/png', 'iVBORw0KGgo='],
|
||||
['data:image/webp;base64,UklGRg==', 'image/webp', 'UklGRg=='],
|
||||
['data:image/svg+xml;base64,PHN2Zz4=', 'image/svg+xml', 'PHN2Zz4='],
|
||||
['data:image/x-png;base64,AAAA', 'image/x-png', 'AAAA'],
|
||||
])('无显式 mimeType 时按 %s 的声明类型发送', async (dataUrl, mimeType, data) => {
|
||||
mockGenerateContent.mockResolvedValue({ text: reanswerReply });
|
||||
const provider = new GeminiProvider({ apiKey: 'test-key' });
|
||||
|
||||
await provider.reanswerQuestion('解方程 x+1=2', 'zh', '数学', dataUrl);
|
||||
|
||||
const contents = mockGenerateContent.mock.calls.at(-1)?.[0].contents;
|
||||
expect(contents[1].inlineData).toEqual({ mimeType, data });
|
||||
});
|
||||
|
||||
it('纯 base64 沿用显式 mimeType', async () => {
|
||||
mockGenerateContent.mockResolvedValue({ text: '<subject>数学</subject><question_text>题目</question_text><answer_text>2</answer_text><analysis>计算</analysis><knowledge_points>加法</knowledge_points><requires_image>false</requires_image>' });
|
||||
const provider = new GeminiProvider({ apiKey: 'test-key' });
|
||||
|
||||
await provider.analyzeImage('QUJD', 'image/webp', 'zh', 4, '数学');
|
||||
|
||||
const contents = mockGenerateContent.mock.calls.at(-1)?.[0].contents;
|
||||
expect(contents[1].inlineData).toEqual({ mimeType: 'image/webp', data: 'QUJD' });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -9,6 +9,7 @@ import { trimTrailingSlashes } from '../utils';
|
||||
import { withModelOutputLimit } from './truncation';
|
||||
import { isAIErrorCode, parseErrorCode } from './error-classification';
|
||||
import { normalizeThinkingLevel } from './thinking-level';
|
||||
import { parseImagePayload } from './image-data-url';
|
||||
import type { ThinkingLevel } from './thinking-level';
|
||||
|
||||
const logger = createLogger('ai:anthropic');
|
||||
@@ -22,8 +23,8 @@ const REQUEST_TIMEOUT_MS = 10 * 60 * 1000;
|
||||
type ImageMediaType = 'image/jpeg' | 'image/png' | 'image/gif' | 'image/webp';
|
||||
type UserContent = string | Anthropic.ContentBlockParam[];
|
||||
|
||||
function toImageMediaType(mimeType: string | undefined): ImageMediaType {
|
||||
const normalized = (mimeType || '').toLowerCase();
|
||||
function toImageMediaType(mimeType: string): ImageMediaType {
|
||||
const normalized = mimeType.toLowerCase();
|
||||
if (normalized === 'image/png' || normalized === 'image/gif' || normalized === 'image/webp') {
|
||||
return normalized;
|
||||
}
|
||||
@@ -31,14 +32,14 @@ function toImageMediaType(mimeType: string | undefined): ImageMediaType {
|
||||
}
|
||||
|
||||
function imageBlock(base64: string, mimeType?: string): Anthropic.ImageBlockParam {
|
||||
// 兼容 data URL(data:image/png;base64,xxx)和纯 base64
|
||||
const match = base64.match(/^data:([^;]+);base64,([\s\S]*)$/);
|
||||
// 兼容 data URL(data:image/png;base64,xxx)和纯 base64;声明类型优先于传入类型
|
||||
const payload = parseImagePayload(base64, mimeType);
|
||||
return {
|
||||
type: 'image',
|
||||
source: {
|
||||
type: 'base64',
|
||||
media_type: toImageMediaType(match ? match[1] : mimeType),
|
||||
data: match ? match[2] : base64,
|
||||
media_type: toImageMediaType(payload.mimeType),
|
||||
data: payload.data,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import { BaseAIProvider } from './base-provider';
|
||||
import { createLogger } from '../logger';
|
||||
import { AI_OUTPUT_TRUNCATED } from './truncation';
|
||||
import { geminiThinkingConfig, normalizeThinkingLevel } from './thinking-level';
|
||||
import { parseImagePayload } from './image-data-url';
|
||||
import type { ThinkingLevel } from './thinking-level';
|
||||
|
||||
const logger = createLogger('ai:gemini');
|
||||
@@ -113,15 +114,14 @@ export class GeminiProvider extends BaseAIProvider {
|
||||
if (images.length === 0) {
|
||||
return request.user;
|
||||
}
|
||||
// 兼容 data URL(data:image/xxx;base64,...)前缀:去掉前缀,声明类型沿用传入的 mimeType(缺省 image/jpeg)
|
||||
// 兼容 data URL(data:image/xxx;base64,...)前缀:按声明类型剥离前缀,
|
||||
// 未声明时沿用传入的 mimeType(缺省 image/jpeg);含 `+`/`-` 的子类型也能匹配
|
||||
const contents: Array<{ text: string } | { inlineData: { mimeType: string; data: string } }> = [
|
||||
{ text: request.user },
|
||||
...images.map((image) => ({
|
||||
inlineData: {
|
||||
data: image.base64.replace(/^data:image\/\w+;base64,/, ''),
|
||||
mimeType: image.mimeType || 'image/jpeg',
|
||||
},
|
||||
})),
|
||||
...images.map((image) => {
|
||||
const payload = parseImagePayload(image.base64, image.mimeType);
|
||||
return { inlineData: { mimeType: payload.mimeType, data: payload.data } };
|
||||
}),
|
||||
];
|
||||
// 原 Gemini 的 generateFigureSvg 不在图片后附加额外文字(extraUserText 是 Anthropic 的行为),这里按 task 忽略
|
||||
if (request.extraUserText && request.task !== 'figure') {
|
||||
|
||||
16
src/lib/ai/image-data-url.ts
Normal file
16
src/lib/ai/image-data-url.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
/** 图片 data URL 或纯 base64 载荷的解析结果 */
|
||||
export interface ImagePayload {
|
||||
mimeType: string;
|
||||
data: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析图片 data URL(data:image/png;base64,...)与纯 base64 载荷。
|
||||
* 类型优先级:data URL 声明 > 调用方传入的 mimeType > image/jpeg;
|
||||
* 正则兼容 `+`、`-`、`.` 等 MIME 子类型字符(如 image/svg+xml、image/x-png)。
|
||||
*/
|
||||
export function parseImagePayload(base64: string, fallbackMimeType?: string): ImagePayload {
|
||||
const match = base64.match(/^data:([^;]+);base64,([\s\S]*)$/);
|
||||
if (match) return { mimeType: match[1].toLowerCase(), data: match[2] };
|
||||
return { mimeType: (fallbackMimeType || 'image/jpeg').toLowerCase(), data: base64 };
|
||||
}
|
||||
Reference in New Issue
Block a user