Skip to content

Commit

Permalink
Update main.js
Browse files Browse the repository at this point in the history
  • Loading branch information
Rockytkg authored Nov 14, 2024
1 parent d045cf9 commit ddda1d5
Showing 1 changed file with 87 additions and 42 deletions.
129 changes: 87 additions & 42 deletions main.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,13 @@ async function recognize(base64, lang, options) {
model = "gpt-4o",
apiKey,
requestPath,
customPrompt
customPrompt
} = config;

// 验证必要参数
// 验证输入参数
if (!base64) {
throw new Error('Base64 image data is required');
}
if (!apiKey) {
throw new Error('API Key is required');
}
Expand All @@ -29,30 +32,31 @@ async function recognize(base64, lang, options) {
'Authorization': `Bearer ${apiKey}`
};

// 加载图像并压缩
const compressedBase64 = await compressImage(base64);

const body = {
model,
messages: [
{
"role": "system",
"content": systemPrompt
},
{
"role": "user",
"content": [{
"type": "image_url",
"image_url": {
"url": `data:image/jpeg;base64,${compressedBase64}`,
"detail": "high"
}
}]
}
]
};

try {
// 加载图像并压缩
const compressedBase64 = await compressImage(base64);

const body = {
model,
max_tokens: 4096,
messages: [
{
"role": "system",
"content": systemPrompt
},
{
"role": "user",
"content": [{
"type": "image_url",
"image_url": {
"url": `data:image/jpeg;base64,${compressedBase64}`,
"detail": "high"
}
}]
}
]
};

const response = await fetch(url.toString(), {
method: 'POST',
headers: headers,
Expand All @@ -68,12 +72,28 @@ async function recognize(base64, lang, options) {
throw new Error(`API Request Failed: ${errorDetails}`);
}

// 安全地获取响应内容
const responseData = response.data;
if (!responseData || !responseData.choices || !responseData.choices[0]) {
throw new Error('Invalid API response structure');
}

// 返回识别的文本内容
return response.data.choices[0].message.content;
return responseData.choices[0].message.content || '';

} catch (error) {
// 捕获并详细记录错误
throw new Error(`OCR Recognition Error: ${error.message}`);
// 详细的错误日志
console.error('Full error details:', error);

// 区分不同类型的错误
if (error.message.includes('Failed to fetch')) {
throw new Error('Network error: Unable to connect to the API');
}
if (error.message.includes('API Request Failed')) {
throw error;
}
// 默认错误处理
throw new Error(`OCR Recognition Error: ${error.message ||'Unknown error occurred'}`);
}
}

Expand All @@ -94,26 +114,51 @@ async function parseErrorResponse(response) {
// 压缩图像的函数
async function compressImage(base64) {
return new Promise((resolve, reject) => {
// 安全检查
if (!base64) {
reject(new Error('No base64 image data provided'));
return;
}

const img = new Image();
img.src = `data:image/png;base64,${base64}`;

// 添加超时处理
const timeoutId = setTimeout(() => {
reject(new Error('Image loading timed out'));
}, 10000);

img.onload = () => {
const maxSize = 1400;
const ratio = maxSize / Math.max(img.width, img.height);
const newWidth = Math.floor(img.width * ratio);
const newHeight = Math.floor(img.height * ratio);

const canvas = document.createElement('canvas');
canvas.width = newWidth;
canvas.height = newHeight;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, newWidth, newHeight);
const compressedDataUrl = canvas.toDataURL('image/jpeg', 0.8);
resolve(compressedDataUrl.split(',')[1]); // 返回压缩后的 base64 数据
clearTimeout(timeoutId);

try {
const maxSize = 1400;
const ratio = maxSize / Math.max(img.width, img.height);
const newWidth = Math.floor(img.width * ratio);
const newHeight = Math.floor(img.height * ratio);

const canvas = document.createElement('canvas');
canvas.width = newWidth;
canvas.height = newHeight;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, newWidth, newHeight);
const compressedDataUrl = canvas.toDataURL('image/jpeg', 0.8);
resolve(compressedDataUrl.split(',')[1]); // 返回压缩后的 base64 数据
} catch (drawError) {
reject(new Error(`Image processing error: ${drawError.message}`));
}
};

img.onerror = (error) => {
reject(new Error("Image loading error: " + error));
clearTimeout(timeoutId);
reject(new Error(`Image loading error: ${error.message}`));
};

//尝试加载图像
try {
img.src = `data:image/png;base64,${base64}`;
} catch (srcError) {
clearTimeout(timeoutId);
reject(new Error(`Error setting image source: ${srcError.message}`));
}
});
}

0 comments on commit ddda1d5

Please sign in to comment.