import tkinter as tk
from tkinter import messagebox
from pynput import keyboard
from PIL import ImageGrab, Image
import pytesseract
import numpy as np
import cv2
import threading
import sys
# Ensure pytesseract can find the tesseract executable
# If Tesseract is not in your PATH, uncomment the following line and set the path
# pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'
# Sudoku Solver using Backtracking
def solve_sudoku(board):
empty = find_empty(board)
if not empty:
return True # Solved
row, col = empty
for num in range(1, 10):
if is_valid(board, num, (row, col)):
board[row][col] = num
if solve_sudoku(board):
return True
board[row][col] = 0 # Reset on backtrack
return False
def is_valid(board, num, pos):
row, col = pos
# Check row
for i in range(9):
if board[row][i] == num and i != col:
return False
# Check column
for i in range(9):
if board[i][col] == num and i != row:
return False
# Check box
box_x = col // 3
box_y = row // 3
for i in range(box_y*3, box_y*3 + 3):
for j in range(box_x*3, box_x*3 + 3):
if board[i][j] == num and (i, j) != pos:
return False
return True
def find_empty(board):
for i in range(9):
for j in range(9):
if board[i][j] == 0:
return (i, j) # row, col
return None
# Function to pretty-print Sudoku in console
def print_board(board):
for i in range(9):
if i % 3 == 0 and i !=0:
print("-" * 21)
for j in range(9):
if j %3 ==0 and j !=0:
print("| ", end="")
if j ==8:
print(board[i][j])
else:
print(str(board[i][j]) + " ", end="")
# Function to start the process after rectangle selection
def process_screenshot(x1, y1, x2, y2):
# Capture the selected area
img = ImageGrab.grab(bbox=(x1, y1, x2, y2))
img = img.convert('L') # Convert to grayscale
# Preprocessing with OpenCV
img_np = np.array(img)
img_np = cv2.resize(img_np, (450, 450))
img_np = cv2.GaussianBlur(img_np, (5,5), 0)
_, img_np = cv2.threshold(img_np, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
# Recognize digits using pytesseract
# This is a simplistic approach and might not work perfectly
# For better results, more advanced image processing is needed
board = [[0 for _ in range(9)] for _ in range(9)]
cell_width = img_np.shape[1] // 9
cell_height = img_np.shape[0] // 9
for i in range(9):
for j in range(9):
# Define the cell boundaries
x_start = j * cell_width
y_start = i * cell_height
x_end = (j +1 ) * cell_width
y_end = (i +1 ) * cell_height
cell = img_np[y_start:y_end, x_start:x_end]
# Further thresholding
cell = cv2.threshold(cell, 128, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]
# Resize to improve OCR accuracy
cell = cv2.resize(cell, (100, 100))
# Add padding
cell = cv2.copyMakeBorder(cell, 10,10,10,10, cv2.BORDER_CONSTANT, value=0)
# Use pytesseract to do OCR on the cell
config = "--psm 10 --oem 3 -c tessedit_char_whitelist=123456789"
text = pytesseract.image_to_string(cell, config=config)
try:
num = int(text.strip())
board[i][j] = num
except:
board[i][j] = 0 # Assume empty if not recognized
# Now, solve the Sudoku
if solve_sudoku(board):
print("\nSolved Sudoku:")
print_board(board)
else:
print("No solution exists for the provided Sudoku.")
# GUI for selecting the rectangle
class RectangleSelector:
def __init__(self):
self.start_x = None
self.start_y = None
self.rect = None
self.root = tk.Tk()
self.root.attributes("-fullscreen", True)
self.root.attributes("-alpha", 0.3)
self.root.config(background='black')
self.root.bind("<Escape>", lambda e: self.root.destroy())
self.canvas = tk.Canvas(self.root, cursor="cross", bg='grey11')
self.canvas.pack(fill=tk.BOTH, expand=True)
self.canvas.bind("<ButtonPress-1>", self.on_button_press)
self.canvas.bind("<B1-Motion>", self.on_move_press)
self.canvas.bind("<ButtonRelease-1>", self.on_button_release)
self.root.mainloop()
def on_button_press(self, event):
self.start_x = self.canvas.canvasx(event.x)
self.start_y = self.canvas.canvasy(event.y)
# Create rectangle
self.rect = self.canvas.create_rectangle(self.start_x, self.start_y, self.start_x, self.start_y, outline='red', width=2)
def on_move_press(self, event):
cur_x, cur_y = (self.canvas.canvasx(event.x), self.canvas.canvasy(event.y))
self.canvas.coords(self.rect, self.start_x, self.start_y, cur_x, cur_y)
def on_button_release(self, event):
end_x, end_y = (self.canvas.canvasx(event.x), self.canvas.canvasy(event.y))
self.root.destroy()
# Start a new thread to process the screenshot
threading.Thread(target=process_screenshot, args=(self.start_x, self.start_y, end_x, end_y)).start()
# Function to listen for keyboard shortcut
def on_activate():
# Start the rectangle selector
RectangleSelector()
def for_canonical(f):
return lambda k: f(listener.canonical(k))
# Setting up the keyboard listener
def start_keyboard_listener():
with keyboard.GlobalHotKeys({
'<ctrl>+<alt>+t': on_activate}) as listener:
listener.join()
if __name__ == "__main__":
print("Press Ctrl+Alt+T to select a Sudoku area.")
# Run the keyboard listener in the main thread
start_keyboard_listener()