import "@johnlindquist/kit";
const captureScreenshot = async () => {
const tmpFile = kenvTmpPath(`screenshot-${Date.now()}.png`);
const scriptFile = kenvTmpPath('script.ps1');
if (isMac) {
await exec(`screencapture -i ${tmpFile}`);
} else if (isWin) {
const psScript = `Add-Type -AssemblyName System.Windows.Forms;
[System.Windows.Forms.SendKeys]::SendWait('%{PRTSC}');
Start-Sleep -m 500;
$clipboardData = Get-Clipboard -Format Image;
$clipboardData.Save('${tmpFile}', [System.Drawing.Imaging.ImageFormat]::Png);`;
await writeFile(scriptFile, psScript.replace(/\n/g, ''))
await exec(`powershell -File "${scriptFile}"`);
} else if (isLinux) {
try {
await exec('gnome-screenshot --version');
await exec(`gnome-screenshot -f ${tmpFile}`);
} catch (error) {
await exec(`import ${tmpFile}`);
}
}
return tmpFile;
};
const recognizeText = async (filePath, language) => {
const { createWorker } = await npm("tesseract.js");
const worker = await createWorker();
await worker.loadLanguage(language);
await worker.initialize(language);
const { data } = await worker.recognize(filePath);
await worker.terminate();
return data.text;
};
const languages = [
{ name: "Spanish", value: "spa" },
{ name: "French", value: "fra" },
{ name: "Portuguese", value: "por" },
{ name: "English", value: "eng" },
];
const selectedLanguage = flag.ctrl
? await arg("Select a language:", languages)
: "eng";
await hide();
const filePath = await captureScreenshot();
if (!await pathExists(filePath)) exit()
const text = await recognizeText(filePath, selectedLanguage);
if (text) {
await clipboard.writeText(text.trim());
await notify("Text recognized and copied to clipboard");
} else {
await notify("No text found in the screenshot");
}
await remove(filePath);