Please bookmark this page to avoid losing your image tool!

Image AI Powered Language And Code Identifier Creator

(Free & Supports Bulk Upload)

Drag & drop your images here or

The result will appear here...
You can edit the below JavaScript code to customize the image tool.
/**
 * Analyzes an image to identify the programming or natural language of the text within it.
 * This function uses Tesseract.js for OCR, highlight.js for code detection,
 * and franc for natural language detection. It displays the progress and result
 * as an overlay on a canvas containing the original image.
 *
 * @param {HTMLImageElement} originalImg The original image object to be processed.
 * @returns {Promise<HTMLCanvasElement>} A promise that resolves with a canvas element
 *                                       displaying the original image and the identified language.
 */
async function processImage(originalImg) {
    // Cache for script loading promises to prevent re-loading and re-executing.
    if (!processImage.scriptPromises) {
        processImage.scriptPromises = {};
    }
    const scriptPromises = processImage.scriptPromises;

    /**
     * Dynamically loads a UMD script and resolves when its global variable is available.
     * Caches promises to avoid reloading the same script.
     * @param {string} url The URL of the script.
     * @param {string} globalVar The name of the global variable the script is expected to create.
     * @returns {Promise<void>} A promise that resolves when the script is loaded and ready.
     */
    const loadUmdScript = (url, globalVar) => {
        if (!scriptPromises[url]) {
            scriptPromises[url] = new Promise((resolve, reject) => {
                if (window[globalVar]) {
                    return resolve();
                }
                const script = document.createElement('script');
                script.src = url;
                script.onload = () => {
                    if (window[globalVar]) {
                        resolve();
                    } else {
                        reject(new Error(`Script ${url} loaded but global var '${globalVar}' not found.`));
                    }
                };
                script.onerror = () => {
                    delete scriptPromises[url]; // Allow retries on error
                    reject(new Error(`Failed to load script: ${url}`));
                };
                document.head.appendChild(script);
            });
        }
        return scriptPromises[url];
    };

    /**
     * Dynamically loads a Google Font stylesheet.
     * @param {string} fontFamily The name of the font family (e.g., 'Roboto').
     */
    const loadGoogleFont = (fontFamily) => {
        const fontId = `google-font-${fontFamily.replace(/\s/g, '-')}`;
        if (document.getElementById(fontId)) {
            return; // Font already loaded or being loaded
        }
        const link = document.createElement('link');
        link.id = fontId;
        link.rel = 'stylesheet';
        link.href = `https://fonts.googleapis.com/css2?family=${fontFamily.replace(/\s/g, '+')}&display=swap`;
        document.head.appendChild(link);
    };

    loadGoogleFont('Roboto');

    // Setup the output canvas
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');
    canvas.width = originalImg.naturalWidth;
    canvas.height = originalImg.naturalHeight;
    ctx.drawImage(originalImg, 0, 0);

    /**
     * Draws a text overlay at the bottom of the canvas.
     * @param {string} text The text to display.
     */
    const drawOverlay = (text) => {
        ctx.save();
        const padding = 10;
        const fontSize = Math.max(16, Math.min(canvas.width / 25, 30));
        ctx.font = `bold ${fontSize}px Roboto, Arial, sans-serif`;
        ctx.textBaseline = 'middle';
        ctx.textAlign = 'center';

        const rectHeight = fontSize + 2 * padding;
        const rectY = canvas.height - rectHeight;

        // Draw a semi-transparent background for the text
        ctx.fillStyle = 'rgba(0, 0, 0, 0.75)';
        ctx.fillRect(0, rectY, canvas.width, rectHeight);

        // Draw the text
        ctx.fillStyle = 'white';
        ctx.fillText(text, canvas.width / 2, rectY + rectHeight / 2);
        ctx.restore();
    };

    /**
     * Redraws the original image and updates the status overlay text.
     * @param {string} text The status text to display.
     */
    const updateStatus = (text) => {
        ctx.drawImage(originalImg, 0, 0, canvas.width, canvas.height);
        drawOverlay(text);
    };

    try {
        updateStatus('Initializing AI Engine...');

        // 1. Load Tesseract.js for Optical Character Recognition (OCR)
        await loadUmdScript('https://cdn.jsdelivr.net/npm/tesseract.js@5/dist/tesseract.min.js', 'Tesseract');

        // 2. Perform OCR, with progress updates displayed on the canvas
        const worker = await Tesseract.createWorker('eng', 1, {
            logger: m => {
                let statusText = m.status.charAt(0).toUpperCase() + m.status.slice(1).replace(/_/g, ' ');
                if (m.status === 'recognizing text') {
                    const progress = (m.progress * 100).toFixed(0);
                    statusText = `Recognizing Text... ${progress}%`;
                }
                updateStatus(statusText);
            },
        });
        const { data: { text } } = await worker.recognize(originalImg);
        await worker.terminate();

        // Ensure sufficient text was extracted for reliable identification
        if (!text || text.trim().length < 10) {
            updateStatus('Not enough text found to identify language.');
            return canvas;
        }

        updateStatus('Analyzing text...');
        let identifiedLanguage = 'Unknown';
        let isCode = false;

        // 3. Attempt to identify as a programming language using highlight.js
        try {
            await loadUmdScript('https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js', 'hljs');
            const hljsResult = window.hljs.highlightAuto(text);

            // Use relevance score and language type to determine if it's code
            if (hljsResult.relevance > 10 && hljsResult.language && hljsResult.language !== 'plaintext') {
                identifiedLanguage = hljsResult.language.charAt(0).toUpperCase() + hljsResult.language.slice(1);
                isCode = true;
            }
        } catch (e) {
            console.error('highlight.js identification failed:', e);
        }

        // 4. If not code, attempt to identify as a natural language using franc
        if (!isCode) {
            try {
                await loadUmdScript('https://unpkg.com/franc@6.2.0/dist/franc.umd.js', 'franc');
                await loadUmdScript('https://unpkg.com/langs@2.0.0/langs.min.js', 'langs');

                const langCode = window.franc(text); // Get ISO 639-3 code
                if (langCode && langCode !== 'und') {
                    const langInfo = window.langs.where('3', langCode);
                    identifiedLanguage = langInfo ? langInfo.name : langCode; // Fallback to code if name not found
                }
            } catch (e) {
                console.error('Natural language identification failed:', e);
            }
        }

        // 5. Display the final result
        if (identifiedLanguage !== 'Unknown') {
            updateStatus(`Identified: ${identifiedLanguage}`);
        } else {
            updateStatus('Could not identify the language.');
        }

    } catch (error) {
        console.error('An error occurred during image processing:', error);
        updateStatus('An unexpected error occurred.');
    }

    return canvas;
}

Free Image Tool Creator

Can't find the image tool you're looking for?
Create one based on your own needs now!

Description

The Image AI Powered Language and Code Identifier Creator is a tool that analyzes images containing text to identify the programming or natural language of the text present. It employs Optical Character Recognition (OCR) to extract text from images and uses advanced algorithms to determine whether the extracted text is code or a natural language. This tool is particularly useful for developers, educators, and researchers who may need to understand or categorize text within images such as screenshots of code, educational materials, or printed text. The results are overlaid on the original image, making it easy to see what language was detected.

Leave a Reply

Your email address will not be published. Required fields are marked *