You can edit the below JavaScript code to customize the image tool.
Apply Changes
async function processImage(originalImg, languagesToCheckStr = 'eng,rus,ara,heb,hin,jpn,kor,chi_sim,gre', confidenceThreshold = 50) {
/**
* Dynamically loads the Tesseract.js library from a CDN.
* Caches the library on the window object to avoid reloading.
* @returns {Promise<object>} A promise that resolves with the Tesseract object.
*/
const loadTesseract = () => {
return new Promise((resolve, reject) => {
const SCRIPT_URL = 'https://cdn.jsdelivr.net/npm/tesseract.js@5/dist/tesseract.min.js';
// Check if Tesseract is already loaded and ready
if (window.Tesseract && typeof window.Tesseract.createWorker === 'function') {
return resolve(window.Tesseract);
}
// Check if the script tag is already in the document
const existingScript = document.querySelector(`script[src="${SCRIPT_URL}"]`);
if (existingScript) {
// If it's still loading, wait for it to finish
existingScript.addEventListener('load', () => resolve(window.Tesseract));
existingScript.addEventListener('error', (e) => reject(new Error(`Tesseract.js script already existed but failed to load.`)));
return;
}
// Otherwise, create and append the script tag
const script = document.createElement('script');
script.src = SCRIPT_URL;
script.onload = () => resolve(window.Tesseract);
script.onerror = () => reject(new Error(`Failed to load Tesseract.js from ${SCRIPT_URL}`));
document.head.appendChild(script);
});
};
/**
* Creates a styled HTML element to display results or errors.
* @param {string} title - The title of the message (e.g., "Success", "Error").
* @param {string} message - The main content of the message.
* @param {string} color - The theme color for the title.
* @param {string} [details=''] - Optional extra details or footer text.
* @returns {HTMLDivElement} A styled div element.
*/
const createResultElement = (title, message, color, details = '') => {
const element = document.createElement('div');
element.style.fontFamily = 'Arial, sans-serif';
element.style.padding = '20px';
element.style.textAlign = 'center';
element.style.border = `1px solid #ccc`;
element.style.borderRadius = '8px';
element.style.maxWidth = '400px';
element.style.margin = 'auto';
element.style.backgroundColor = '#f9f9f9';
let html = `<h3 style="margin-top:0; color: ${color};">${title}</h3><p style="font-size: 1.1em;">${message}</p>`;
if (details) {
html += `<p style="font-size: 0.9em; color: #666; border-top: 1px solid #eee; padding-top: 10px; margin-top: 15px;">${details}</p>`;
}
element.innerHTML = html;
return element;
};
try {
const Tesseract = await loadTesseract();
// A mapping of Tesseract language codes to their primary alphabet/script.
const languageToAlphabetMap = {
eng: 'Latin', fra: 'Latin', deu: 'Latin', spa: 'Latin', por: 'Latin', ita: 'Latin',
rus: 'Cyrillic', ukr: 'Cyrillic', bel: 'Cyrillic',
ara: 'Arabic',
heb: 'Hebrew',
hin: 'Devanagari',
jpn: 'Japanese (Kanji/Kana)',
kor: 'Korean (Hangul)',
chi_sim: 'Chinese (Simplified)',
chi_tra: 'Chinese (Traditional)',
gre: 'Greek',
tha: 'Thai'
};
const languages = languagesToCheckStr.split(',').map(s => s.trim()).filter(s => s);
if (languages.length === 0) {
return createResultElement('Configuration Error', 'No languages specified to check.', '#d9534f');
}
const worker = await Tesseract.createWorker();
const results = [];
for (const lang of languages) {
try {
await worker.loadLanguage(lang);
await worker.initialize(lang);
const { data } = await worker.recognize(originalImg);
if (data.text && data.text.trim().length > 0 && data.confidence > 0) {
results.push({ lang: lang, confidence: data.confidence, text: data.text.trim() });
}
} catch (e) {
console.warn(`Could not process language '${lang}':`, e.message);
// Silently continue to the next language if one fails.
}
}
await worker.terminate();
if (results.length === 0) {
return createResultElement('Detection Failed', 'No recognizable text was found in the image.', '#777');
}
results.sort((a, b) => b.confidence - a.confidence);
const bestMatch = results[0];
if (bestMatch.confidence < confidenceThreshold) {
const message = `Could not identify the alphabet with sufficient confidence (Threshold: ${confidenceThreshold}%).`;
const details = `Best guess: <strong>${languageToAlphabetMap[bestMatch.lang] || bestMatch.lang}</strong> with ${bestMatch.confidence.toFixed(2)}% confidence.`;
return createResultElement('Low Confidence', message, '#f0ad4e', details);
}
const identifiedAlphabet = languageToAlphabetMap[bestMatch.lang] || bestMatch.lang;
const mainMessage = `<span style="font-size: 2em; font-weight: bold;">${identifiedAlphabet}</span>`;
const sampleText = bestMatch.text.substring(0, 70) + (bestMatch.text.length > 70 ? '...' : '');
const detailsMessage = `Detected as <strong>${bestMatch.lang.toUpperCase()}</strong> with ${bestMatch.confidence.toFixed(2)}% confidence.<br><br><em>Sample: "${sampleText}"</em>`;
return createResultElement('Alphabet Identified!', mainMessage, '#5cb85c', detailsMessage);
} catch (error) {
console.error("An error occurred during alphabet identification:", error);
return createResultElement('Error', 'An unexpected error occurred during processing.', '#d9534f', error.message);
}
}
Apply Changes