Here's a Node.js code that fulfills your requirements using Electron.js for handling GUI and global shortcuts, and Tesseract.js for OCR processing.
1. Initialize your project and install the necessary dependencies:
npm init -y
npm install electron@latest tesseract.js screenshot-desktop jimp
2. Create a main.js file with the following content:
const { app, BrowserWindow, globalShortcut, desktopCapturer, dialog, ipcMain } = require('electron');
const path = require('path');
let mainWindow;
let overlayWindow;
function createWindow() {
mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true,
},
});
mainWindow.loadFile('index.html');
}
app.whenReady().then(() => {
createWindow();
// Register global shortcut for Ctrl+Alt+T
globalShortcut.register('Control+Alt+T', () => {
console.log('Ctrl+Alt+T is pressed');
startSelectionTool();
});
});
app.on('will-quit', () => {
globalShortcut.unregisterAll();
});
// Function to start the selection overlay
function startSelectionTool() {
overlayWindow = new BrowserWindow({
transparent: true,
frame: false,
fullscreen: true,
alwaysOnTop: true,
skipTaskbar: true,
webPreferences: {
nodeIntegration: true,
},
});
overlayWindow.loadFile('overlay.html');
overlayWindow.setIgnoreMouseEvents(false);
}
// Handle selection data from overlay
ipcMain.on('selection-made', (event, selection) => {
console.log('Selection made:', selection);
overlayWindow.close();
// Capture the selected area
captureScreen(selection)
.then((imagePath) => {
console.log('Image saved at', imagePath);
processImage(imagePath);
})
.catch((err) => {
console.error(err);
});
});
// Function to capture the selected screen area
async function captureScreen(selection) {
const { x, y, width, height } = selection;
const imgBuffer = await require('screenshot-desktop')({ format: 'png' });
const Jimp = require('jimp');
const image = await Jimp.read(imgBuffer);
image.crop(x, y, width, height);
const imagePath = path.join(app.getPath('userData'), 'sudoku_selection.png');
await image.writeAsync(imagePath);
return imagePath;
}
// Function to process the captured image
function processImage(imagePath) {
const Tesseract = require('tesseract.js');
Tesseract.recognize(imagePath, 'eng', {
tessedit_char_whitelist: '0123456789',
})
.then(({ data: { text } }) => {
console.log('OCR Text:', text);
const grid = parseSudokuGrid(text);
if (!grid) {
dialog.showMessageBox({
type: 'error',
message: 'The selected area does not contain a valid Sudoku puzzle.',
});
} else {
const solution = solveSudoku(grid);
if (solution) {
console.log('Sudoku solution:');
console.log(formatGrid(solution));
} else {
console.log('No solution found for the Sudoku puzzle.');
}
}
})
.catch((err) => {
console.error(err);
});
}
// Function to parse OCR text into a Sudoku grid
function parseSudokuGrid(text) {
text = text.replace(/[^\d]/g, '');
if (text.length !== 81) {
return null;
}
const grid = [];
for (let i = 0; i < 81; i++) {
const num = parseInt(text[i]);
grid.push(isNaN(num) ? 0 : num);
}
const rows = [];
for (let i = 0; i < 9; i++) {
rows.push(grid.slice(i * 9, (i + 1) * 9));
}
return rows;
}
// Function to format and display the grid
function formatGrid(grid) {
return grid.map((row) => row.join(' ')).join('\n');
}
// Sudoku solver implementation
function solveSudoku(grid) {
function isSafe(grid, row, col, num) {
for (let x = 0; x < 9; x++) {
if (grid[row][x] === num || grid[x][col] === num) {
return false;
}
}
const startRow = row - (row % 3);
const startCol = col - (col % 3);
for (let i = 0; i < 3; i++)
for (let j = 0; j < 3; j++)
if (grid[i + startRow][j + startCol] === num) return false;
return true;
}
function solve(grid) {
for (let row = 0; row < 9; row++)
for (let col = 0; col < 9; col++)
if (grid[row][col] === 0) {
for (let num = 1; num <= 9; num++)
if (isSafe(grid, row, col, num)) {
grid[row][col] = num;
if (solve(grid)) return true;
grid[row][col] = 0;
}
return false;
}
return true;
}
const gridCopy = grid.map((row) => row.slice());
if (solve(gridCopy)) return gridCopy;
else return null;
}
3. Create an index.html file (the main window, can be left empty or used for displaying logs):
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Sudoku Solver</title>
</head>
<body>
<h1>Sudoku Solver</h1>
<p>Press Ctrl+Alt+T to capture a Sudoku puzzle.</p>
</body>
</html>
4. Create an overlay.html file for the selection overlay:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Selection Overlay</title>
<style>
html,
body,
canvas {
margin: 0;
padding: 0;
overflow: hidden;
cursor: crosshair;
}
#selectionCanvas {
position: absolute;
top: 0;
left: 0;
}
</style>
</head>
<body>
<canvas id="selectionCanvas"></canvas>
<script src="overlay.js"></script>
</body>
</html>
5. Create an overlay.js file to handle the selection logic:
const { ipcRenderer } = require('electron');
const canvas = document.getElementById('selectionCanvas');
const ctx = canvas.getContext('2d');
let selection = {
startX: 0,
startY: 0,
w: 0,
h: 0,
};
let isDrawing = false;
function resizeCanvas() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}
window.addEventListener('resize', resizeCanvas);
resizeCanvas();
canvas.addEventListener('mousedown', (e) => {
isDrawing = true;
selection.startX = e.clientX;
selection.startY = e.clientY;
selection.w = 0;
selection.h = 0;
});
canvas.addEventListener('mousemove', (e) => {
if (!isDrawing) return;
selection.w = e.clientX - selection.startX;
selection.h = e.clientY - selection.startY;
draw();
});
canvas.addEventListener('mouseup', () => {
isDrawing = false;
ipcRenderer.send('selection-made', getSelectionBounds(selection));
});
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = 'rgba(0, 0, 0, 0.3)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.clearRect(selection.startX, selection.startY, selection.w, selection.h);
ctx.strokeStyle = 'red';
ctx.lineWidth = 2;
ctx.strokeRect(
selection.startX + 0.5,
selection.startY + 0.5,
selection.w,
selection.h
);
}
function getSelectionBounds(selection) {
const x = selection.w >= 0 ? selection.startX : selection.startX + selection.w;
const y = selection.h >= 0 ? selection.startY : selection.startY + selection.h;
const width = Math.abs(selection.w);
const height = Math.abs(selection.h);
return { x, y, width, height };
}
6. Run your app with:
npm start
Usage:
- Launch the application.
- Press Ctrl+Alt+T to activate the selection tool.
- Click and drag to select the area containing the Sudoku puzzle.
- Release the mouse button to capture and process the image.
- The app will attempt to recognize the Sudoku grid, solve it, and output the solution in the console.
- If the selected area does not contain a valid Sudoku grid, an error message box will appear.
Notes:
- Make sure the Sudoku puzzle in the image is clear and the numbers are legible to improve OCR accuracy.
- The OCR might misread some numbers; ensure high image quality.
- The Sudoku solver uses a simple backtracking algorithm.
Dependencies Explanation:
- Electron: Used to create desktop applications with GUI elements and handle global shortcuts.
- Tesseract.js: A JavaScript OCR engine for recognizing text within images.
- screenshot-desktop: Allows capturing screenshots of the desktop.
- Jimp: An image processing library to crop the captured image to the selected area.
Security Considerations:
- The code uses
nodeIntegration: true for simplicity, which can be a security concern in production apps.
- In a production environment, consider using a context bridge or IPC for communication between the renderer and main processes and set
nodeIntegration: false.
Error Handling:
- The code includes basic error handling for OCR recognition and Sudoku validation.
- If OCR fails or the grid is invalid, an error message is displayed to the user.
Enhancements:
- Improve the OCR preprocessing steps (e.g., image binarization) to increase recognition accuracy.
- Implement more robust parsing of the OCR text to handle different formats or errors.
- Add a GUI display of the solution within the app instead of the console output.