Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Multiple improvements, view comment #2

Merged
merged 11 commits into from Sep 5, 2021
Merged
5 changes: 4 additions & 1 deletion .gitignore
@@ -1,2 +1,5 @@
test/
*.pyc
*.pyc
build/
dist/
resource/img_cache/*.png
141 changes: 78 additions & 63 deletions ScreenTranslate.py
Expand Up @@ -4,13 +4,14 @@
import asyncio
from resource.LangCode import *
from tkinter import *
from tkinter import ttk
import tkinter.ttk as ttk
import resource.Capture as capture
import resource.JsonHandling as fJson
from resource.JsonHandling import JsonHandler
import subprocess
import pyperclip
from resource.Mbox import Mbox
import keyboard
import time
from sys import exit

# Add try except to intercept connection error
Expand All @@ -35,6 +36,8 @@
# Get dir path
dir_path = os.path.dirname(os.path.realpath(__file__))

fJson = JsonHandler()

# ----------------------------------------------------------------
# public func
def startfile(filename):
Expand Down Expand Up @@ -110,15 +113,7 @@ def offSetSettings(widthHeighOff, xyOffsetType, xyOff, custom = ""):
return offSetsGet

def getTheOffset(custom = ""):
tStatus, settings = fJson.readSetting()
if tStatus != True:
var1, var2 = fJson.setDefault()
if var1 : # If successfully set default
print("Default setting applied")
Mbox("Default setting applied", "Please change your tesseract location in setting if you didn't install tesseract on default C location", 1)
else: # If error
print("Error: " + var2)
Mbox("An Error Occured", var2, 2)
settings = fJson.readSetting()

offSetXY = settings["offSetXY"]
offSetWH = settings["offSetWH"]
Expand Down Expand Up @@ -198,7 +193,7 @@ def getTextAndTranslate(self, offSetXY=["auto", "auto"]):
print("Error Need to generate the capture window! Please generate the capture window first")
return
# Check for the lang from and langto only if it's on translation mode
if main_Menu.CBTranslateEngine.get() != "None":
if main_Menu.CBTranslateEngine.get() != "None":
# If selected langfrom and langto is the same
if(main_Menu.CBLangFrom.current()) == (main_Menu.CBLangTo.current()):
Mbox("Error: Language target is the same as source", "Please choose a different language", 2)
Expand All @@ -223,27 +218,7 @@ def getTextAndTranslate(self, offSetXY=["auto", "auto"]):
x, y, w, h = self.root.winfo_x(), self.root.winfo_y(), self.root.winfo_width(), self.root.winfo_height()

# Get settings
tStatus, settings = fJson.readSetting()
if tStatus == False: # If error its probably file not found, thats why we only handle the file not found error
if settings[0] == "Setting file is not found":
self.root.wm_withdraw() # Hide the capture window

# Show error
print("Error: " + settings[0])
print(settings[1])
Mbox("Error: " + settings[0], settings[1], 2)

# Set Default
var1, var2 = fJson.setDefault()
if var1 : # If successfully set default
print("Default setting applied")
Mbox("Default setting applied", "Please change your tesseract location in setting if you didn't install tesseract on default C location", 2)
else: # If error
print("Error: " + var2)
Mbox("An Error Occured", var2, 2)

self.root.wm_deiconify() # Show the capture window
return # Reject
settings = fJson.readSetting()

validTesseract = "tesseract" in settings['tesseract_loc'].lower()
# If tesseract is not found
Expand Down Expand Up @@ -581,6 +556,13 @@ def screenShotAndOpenLayout():
capture.captureAll()
startfile(dir_path + r"\resource\img_cache\Monitor(s) Captured View.png")

def setHotkey():
hotkey = keyboard.read_hotkey(suppress=False)
main_Menu.setting_UI.labelCurrentHotkey.config(text=str(hotkey))

def clearHotkey():
main_Menu.setting_UI.labelCurrentHotkey.config(text="")

def restoreDefault(self):
x = Mbox("Confirmation", "Are you sure you want to set the settings to default?\n\n**WARNING! CURRENTLY SAVED SETTING WILL BE OVERWRITTEN**", 3)
if x == False:
Expand All @@ -598,28 +580,8 @@ def restoreDefault(self):
Mbox("Success", "Successfully Restored Value to Default Settings", 0)

def reset(self):
tStatus, settings = fJson.readSetting()
if tStatus == False: # If error its probably file not found, thats why we only handle the file not found error
if settings[0] == "Setting file is not found":
self.root.wm_withdraw() # Hide setting
settings = fJson.readSetting()

# Show error
print("Error: " + settings[0])
print(settings[1])
Mbox("Error: " + settings[0], settings[1], 2)

settings = fJson.default_Setting

# Set Default
var1, var2 = fJson.setDefault()
if var1 : # If successfully set default
print("Default setting applied")
Mbox("Default setting applied", "Please change your tesseract location in setting if you didn't install tesseract on default C location", 1)
else: # If error
print("Error: " + var2)
Mbox("An Error Occured", var2, 2)

self.root.wm_deiconify() # Show setting
validTesseract = "tesseract" in settings['tesseract_loc'].lower()
# If tesseract is not found
if os.path.exists(settings['tesseract_loc']) == False or validTesseract == False:
Expand All @@ -641,11 +603,16 @@ def reset(self):
self.root.setvar(name="checkVarAutoCopy", value=False)
self.checkBTNAutoCopy.deselect()

# Show current hotkey
main_Menu.setting_UI.labelCurrentHotkey.config(text=settings['capture_Hotkey'])

# Store setting to localvar
offSetXY = settings["offSetXY"]
offSetWH = settings["offSetWH"]
xyOffSetType = settings["offSetXYType"]

self.spinValHotkeyDelay.set(settings["capture_HotkeyDelay"])

offSets = offSetSettings(offSetWH, xyOffSetType, offSetXY)
x = offSets[0]
y = offSets[1]
Expand Down Expand Up @@ -764,9 +731,20 @@ def saveSettings():
"tesseract_loc": main_Menu.setting_UI.textBoxTesseractPath.get("1.0", END).strip(),
"default_Engine": main_Menu.setting_UI.CBDefaultEngine.get(),
"default_FromOnOpen": main_Menu.setting_UI.CBDefaultFrom.get(),
"default_ToOnOpen": main_Menu.setting_UI.CBDefaultTo.get()
"default_ToOnOpen": main_Menu.setting_UI.CBDefaultTo.get(),
"capture_Hotkey": main_Menu.setting_UI.labelCurrentHotkey['text'],
"capture_HotkeyDelay": main_Menu.setting_UI.spinValHotkeyDelay.get()
}

# Bind hotkey
try:
keyboard.unhook_all_hotkeys()
except AttributeError:
# No hotkeys to unbind
pass
if main_Menu.setting_UI.labelCurrentHotkey['text'] != '':
keyboard.add_hotkey(main_Menu.setting_UI.labelCurrentHotkey['text'], gui.hotkeyCallback)

print("-" * 50)
print("Setting saved!")
print(settingToSave)
Expand Down Expand Up @@ -888,6 +866,11 @@ def CBTLChange_setting(self, event = ""):
fourthFrameContent = Frame(fourthFrame)
fourthFrameContent.pack(side=TOP, fill=X, expand=False)

fifthFrame = ttk.LabelFrame(root, text="• Hotkey Settings")
fifthFrame.pack(side=TOP, fill=X, expand=False, padx=5, pady=5)
fifthFrameContent = Frame(fifthFrame)
fifthFrameContent.pack(side=TOP, fill=X, expand=False)

bottomFrame = Frame(root)
bottomFrame.pack(side=BOTTOM, fill=BOTH, expand=False)

Expand Down Expand Up @@ -922,6 +905,8 @@ def CBTLChange_setting(self, event = ""):
spinValOffSetW = StringVar(root)
spinValOffSetH = StringVar(root)

spinValHotkeyDelay = IntVar(root)

validateDigits = (root.register(validateSpinBox), '%P')

spinnerOffSetX = Spinbox(secondFrameContent2, from_=-100000, to=100000, width=20, textvariable=spinValOffSetX)
Expand Down Expand Up @@ -949,13 +934,22 @@ def CBTLChange_setting(self, event = ""):
labelTesseractPath = Label(fourthFrameContent, text="Tesseract Path :")
textBoxTesseractPath = Text(fourthFrameContent, width=77, height=1, xscrollcommand=True)

# Fifth frame
labelHotkeyDelay = Label(fifthFrameContent, text="Time delay (ms) : ")
spinnerHotkeyDelay = Spinbox(fifthFrameContent, from_=0, to=100000, width=20, textvariable=spinValHotkeyDelay)
spinnerHotkeyDelay.configure(validate='key', validatecommand=validateDigits)
buttonSetHotkey = Button(fifthFrameContent, text="Click to set hotkey for capture", command=setHotkey)
buttonClearHotkey = Button(fifthFrameContent, text="Clear", command=clearHotkey)
labelHotkeyTip = Label(fifthFrameContent, text="Current hotkey : ")
labelCurrentHotkey = Label(fifthFrameContent, text="")

# Bottom Frame
btnSave = Button(bottomFrame, text="Save Settings", command=saveSettings)

# ----------------------------------------------------------------------
def __init__(self):
self.root.title("Setting")
self.root.geometry("727x420") # When you see it
self.root.geometry("727x500") # When you see it
self.root.wm_attributes('-topmost', False) # Default False
self.root.wm_withdraw()

Expand Down Expand Up @@ -1003,6 +997,14 @@ def __init__(self):
self.labelTesseractPath.pack(side=LEFT, padx=5, pady=5)
self.textBoxTesseractPath.pack(side=LEFT, padx=5, pady=5, fill=X, expand=True)

# 5
self.labelHotkeyDelay.pack(side=LEFT, padx=5, pady=5)
self.spinnerHotkeyDelay.pack(side=LEFT, padx=5, pady=5)
self.buttonSetHotkey.pack(side=LEFT, padx=5, pady=5)
self.buttonClearHotkey.pack(side=LEFT, padx=5, pady=5)
self.labelHotkeyTip.pack(side=LEFT, padx=5, pady=5)
self.labelCurrentHotkey.pack(side=LEFT, padx=5, pady=5)

# Bottom Frame
self.btnSave.pack(side=RIGHT, padx=4, pady=5)
btnReset = Button(self.bottomFrame, text="Reset To Currently Stored Setting", command=self.reset)
Expand Down Expand Up @@ -1315,6 +1317,19 @@ def cbTLChange(self, event = ""):
textBoxTop = Text(topFrame2, height = 5, width = 100, font=("Segoe UI", 10), yscrollcommand=True)
textBoxBottom = Text(bottomFrame2, height = 5, width = 100, font=("Segoe UI", 10), yscrollcommand=True)

hotkeyPressed = False

def hotkeyCallback(self):
self.hotkeyPressed = True

def hotkeyPoll(self):
if self.hotkeyPressed == True and self.capUiHidden == False:
settings = fJson.readSetting()
time.sleep(settings['capture_HotkeyDelay'] / 1000)
self.capture_UI.getTextAndTranslate()
self.hotkeyPressed = False
self.root.after(100, self.hotkeyPoll)

# ----------------------------------------------------------------------
def __init__(self):
# ----------------------------------------------
Expand All @@ -1325,7 +1340,7 @@ def __init__(self):
self.root.title("Screen Translate")
self.root.geometry("900x300")
self.root.wm_attributes('-topmost', False) # Default False
tStatus, settings = fJson.readSetting()
tStatus, settings = fJson.loadSetting()
if tStatus == False: # If error its probably file not found, thats why we only handle the file not found error
if settings[0] == "Setting file is not found":
# Show error
Expand Down Expand Up @@ -1426,11 +1441,11 @@ def always_on_top():
# Check setting on startup
self.setting_UI.reset() # Reset

# ----------------------------------------------------------------
# main function
def main():
main_Menu()
main_Menu.root.mainloop()
# Bind hotkey
if settings['capture_Hotkey'] != '':
keyboard.add_hotkey(settings['capture_Hotkey'], self.hotkeyCallback)
self.root.after(100, self.hotkeyPoll)

if __name__ == '__main__':
main()
gui = main_Menu()
gui.root.mainloop()
8 changes: 5 additions & 3 deletions ScreenTranslate.spec
Expand Up @@ -5,7 +5,7 @@ block_cipher = None


a = Analysis(['ScreenTranslate.py'],
pathex=['D:\\Coding\\Screen-Translate'],
pathex=['./'],
binaries=[],
datas=[],
hiddenimports=[],
Expand Down Expand Up @@ -33,11 +33,13 @@ exe = EXE(pyz,
disable_windowed_traceback=False,
target_arch=None,
codesign_identity=None,
entitlements_file=None )
entitlements_file=None)
coll = COLLECT(exe,
a.binaries,
a.zipfiles,
a.datas,
a.datas,
Tree('./user_manual', prefix='user_manual/'),
Tree('./resource', prefix='resource/'),
strip=False,
upx=True,
upx_exclude=[],
Expand Down
Binary file removed __pycache__/Capture.cpython-39.pyc
Binary file not shown.
Binary file removed __pycache__/Capture_UI.cpython-39.pyc
Binary file not shown.
Binary file removed __pycache__/Capture_screen.cpython-39.pyc
Binary file not shown.
Binary file removed __pycache__/Main.cpython-39.pyc
Binary file not shown.
Binary file removed __pycache__/Main_Menu.cpython-39.pyc
Binary file not shown.
Binary file removed __pycache__/Mbox.cpython-39.pyc
Binary file not shown.
Binary file removed __pycache__/ScreenTranslate.cpython-39.pyc
Binary file not shown.
20 changes: 0 additions & 20 deletions copy_after_compiling/@@Changelog.txt

This file was deleted.

25 changes: 0 additions & 25 deletions copy_after_compiling/@@Readme.txt

This file was deleted.

6 changes: 0 additions & 6 deletions copy_after_compiling/ReadBeforeCopy.txt

This file was deleted.

1 change: 0 additions & 1 deletion copy_after_compiling/resource/img_cache/readme.txt

This file was deleted.

3 changes: 0 additions & 3 deletions copy_after_compiling/resource/json/History.json

This file was deleted.

1 change: 0 additions & 1 deletion copy_after_compiling/resource/json/Readme.txt

This file was deleted.

17 changes: 0 additions & 17 deletions copy_after_compiling/resource/json/Setting.json

This file was deleted.

1 change: 0 additions & 1 deletion copy_after_compiling/resource/readme.txt

This file was deleted.

Binary file not shown.
Binary file removed copy_after_compiling/user_manual/2_1_installocr.png
Binary file not shown.
Binary file removed copy_after_compiling/user_manual/2_2_installocr.png
Binary file not shown.
Binary file removed copy_after_compiling/user_manual/2_3_installocr.png
Binary file not shown.
Binary file removed copy_after_compiling/user_manual/2_4_installocr.png
Binary file not shown.
Binary file not shown.
Binary file removed copy_after_compiling/user_manual/3_2_extract.png
Binary file not shown.
Binary file not shown.
Binary file removed copy_after_compiling/user_manual/4_1Checksetting.png
Binary file not shown.
Binary file removed copy_after_compiling/user_manual/4_2_settingui.png
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file removed copy_after_compiling/user_manual/Test Doc.docx
Binary file not shown.