class TestTagManager(TestCase): wrong_path = 'wrong.mp3' not_mp3_file_path = 'file.txt' def setUp(self): self.tag_manager = TagManager() self.folder_manager = FolderManager() if self.folder_manager.exist_path(self.not_mp3_file_path): self.folder_manager.remove_file(self.not_mp3_file_path) def test_instantiate_tag_manager(self): assert TagManager() def test_retrieve_file_from_none_path(self): with self.assertRaises(FileNotFoundError): self.tag_manager.mp3_file(self.wrong_path) def test_retrieve_not_mp3_file(self): with open(self.not_mp3_file_path, 'w') as file: file.write(' ') with self.assertRaises(FileNotFoundError): self.tag_manager.mp3_file(self.not_mp3_file_path) # def test_retrieve_mp3_file(self): def test_retrieve_tags_from_mp3(self):
class TestFileManager(TestCase): def setUp(self): self.manager = FolderManager() self.destination_path = 'Awesome Mix Vol. 1' self.destination_path_when_full = 'Awesome Mix Vol. 2' if os.path.exists(self.destination_path): shutil.rmtree(self.destination_path, ignore_errors=True) if os.path.exists(self.destination_path_when_full): shutil.rmtree(self.destination_path_when_full, ignore_errors=True) self.source_path = '/files' self.source_within_directory_path = '/files/folder' if os.path.exists(self.source_path): shutil.rmtree(self.source_path, ignore_errors=True) def test_get_new_saving_directory(self): saving_directory = self.manager.get_current_saving_directory() assert saving_directory == self.destination_path def test_get_saving_directory_when_it_exists_and_not_full(self): os.mkdir(self.destination_path) saving_directory = self.manager.get_current_saving_directory() assert saving_directory == self.destination_path def test_get_saving_directory_when_it_exists_and_is_full(self): os.mkdir(self.destination_path) self.manager.FILES_IN_DIRECTORY = self.manager.MAX_FILES_IN_DIRECTORY saving_directory = self.manager.get_current_saving_directory() assert saving_directory == self.destination_path_when_full def test_retrieve_only_files_from_existing_directory(self): os.mkdir(self.source_path) os.mkdir(self.source_within_directory_path) completeName = os.path.join(self.source_path, "test.mp3") with open(completeName, "w") as file: file.write(' ') entries = self.manager.retrieve_directory_files(self.source_path) assert len(entries) == 1 def test_save_file_to_other_folder(self): source_file = os.DirEntry() source_file.name = '/test/test.mp3' assert open(completeName, "r")
def main(): print("python main function") folder_manager = FolderManager() tag_manager = TagManager() entries = folder_manager.retrieve_directory_files('./files') for entry in entries: mp3_file = tag_manager.mp3_file(entry.name)
def setUp(self): self.manager = FolderManager() self.destination_path = 'Awesome Mix Vol. 1' self.destination_path_when_full = 'Awesome Mix Vol. 2' if self.os_proxy.exist_path(self.destination_path): self.os_proxy.remove_directory(self.destination_path) if self.os_proxy.exist_path(self.destination_path_when_full): self.os_proxy.remove_directory(self.destination_path_when_full) if self.os_proxy.exist_path(self.source_path): self.os_proxy.remove_directory(self.source_path)
def __init__(self, url, settingValueDict): self.url = url print(settingValueDict) self.textSegmentation = TextSegmenation() self.textDetection = TextDetection(settingValueDict["ContourSize"]) self.textOcr = TextOcr(settingValueDict["OCR"]) self.textTranslator = TextTranslator(settingValueDict["Translator"], settingValueDict["Language"]) self.textDraw = TextDraw(settingValueDict["FontStyle"], settingValueDict["FontSize"]) self.folder = FolderManager() self.downloader = DownloaderManager() self.customTqdm = tqdm
def __init__(self, browser): self.downloadLock = threading.Lock() self.configPath = "setting.ini" self.config = configparser.ConfigParser() self.browser = browser self.credFileDetected = False self.credScopeDetected = False self.ehndDetected = False self.folder = FolderManager() self.folder.removeDir(["tmp", "listItem"]) self.folder.createDir(["tmp", "listItem"]) self.loadINI()
def setUp(self): self.manager = FolderManager() self.destination_path = 'Awesome Mix Vol. 1' self.destination_path_when_full = 'Awesome Mix Vol. 2' if os.path.exists(self.destination_path): shutil.rmtree(self.destination_path, ignore_errors=True) if os.path.exists(self.destination_path_when_full): shutil.rmtree(self.destination_path_when_full, ignore_errors=True) self.source_path = '/files' self.source_within_directory_path = '/files/folder' if os.path.exists(self.source_path): shutil.rmtree(self.source_path, ignore_errors=True)
def __init__(self, url,settingValueDict): self.url=url self.translatorType=settingValueDict["translator"] self.language=settingValueDict["language"] self.font=settingValueDict["fontstyle"] self.fontsize=settingValueDict["fontsize"] self.textSegmentation=TextSegmenation() self.textDetection=TextDetection() self.textOcr=TextOcr() self.textTranslator=TextTranslator(self.translatorType,self.language) self.textDraw=TextDraw(self.font,self.fontsize) self.folder=FolderManager() self.customTqdm=tqdm
def __init__(self, browser): self.downloadLock = threading.Lock() self.browser = browser self.textOcr = TextOcr("") self.detectDict = dict() self.detectDict["credFileDetected"] = False self.detectDict["credScopeDetected"] = False self.detectDict["ehndDetected"] = False self.detectDict["windowocr"] = False self.folder = FolderManager() self.folder.removeDir(["tmp", "listItem"]) self.folder.createDir(["tmp", "listItem"]) self.iniHandler = IniHandler() listItemFolder = "./listItem/" if os.path.exists(listItemFolder): shutil.rmtree(listItemFolder) self.runGoodByeDpi()
def setUp(self): self.tag_manager = TagManager() self.folder_manager = FolderManager() if self.folder_manager.exist_path(self.not_mp3_file_path): self.folder_manager.remove_file(self.not_mp3_file_path)
class TestFileManager(TestCase): os_proxy = OSProxy() source_path = '/files' source_within_directory_path = '/files/folder' def setUp(self): self.manager = FolderManager() self.destination_path = 'Awesome Mix Vol. 1' self.destination_path_when_full = 'Awesome Mix Vol. 2' if self.os_proxy.exist_path(self.destination_path): self.os_proxy.remove_directory(self.destination_path) if self.os_proxy.exist_path(self.destination_path_when_full): self.os_proxy.remove_directory(self.destination_path_when_full) if self.os_proxy.exist_path(self.source_path): self.os_proxy.remove_directory(self.source_path) def test_get_new_saving_directory(self): saving_directory = self.manager.get_current_saving_directory() assert saving_directory == self.destination_path def test_get_saving_directory_when_it_exists_and_not_full(self): self.os_proxy.create_directory(self.destination_path) saving_directory = self.manager.get_current_saving_directory() assert saving_directory == self.destination_path def test_get_saving_directory_when_it_exists_and_is_full(self): self.os_proxy.create_directory(self.destination_path) self.manager.FILES_IN_DIRECTORY = self.manager.MAX_FILES_IN_DIRECTORY saving_directory = self.manager.get_current_saving_directory() assert saving_directory == self.destination_path_when_full def test_retrieve_only_files_from_not_existing_directory(self): with self.assertRaises(FileNotFoundError): self.manager.retrieve_directory_files(self.source_path) def test_retrieve_only_files_from_existing_directory(self): self.os_proxy.create_directory(self.source_path) self.os_proxy.create_directory(self.source_within_directory_path) completeName = self.os_proxy.join_paths(self.source_path, "test.mp3") with open(completeName, "w") as file: file.write(' ') entries = self.manager.retrieve_directory_files(self.source_path) assert len(entries) == 1 def test_retrieve_only_mp3_files_from_existing_directory(self): self.os_proxy.create_directory(self.source_path) self.os_proxy.create_directory(self.source_within_directory_path) completeName = self.os_proxy.join_paths(self.source_path, "test.mp3") with open(completeName, "w") as file: file.write(' ') completeName2 = self.os_proxy.join_paths(self.source_path, "test.txt") with open(completeName2, "w") as file: file.write(' ') entries = self.manager.retrieve_directory_files(self.source_path) assert len(entries) == 1 def test_save_file_to_other_folder(self): pass # source_file = os.DirEntry() # source_file.name = '/test/test.mp3' # assert open(completeName, "r") def test_path_not_exist(self): assert not self.manager.exist_path(self.source_path) def test_path_exist(self): self.os_proxy.create_directory(self.source_path) assert self.manager.exist_path(self.source_path) def test_remove_not_existing_file(self): with self.assertRaises(FileNotFoundError): self.manager.remove_file(self.source_path) def test_remove_existing_file(self): with open(self.source_path, "w") as file: file.write(' ') self.manager.remove_file(self.source_path) assert not self.manager.exist_path(self.source_path)
class GuiUtil(): def __init__(self, browser): self.downloadLock = threading.Lock() self.browser = browser self.textOcr = TextOcr("") self.detectDict = dict() self.detectDict["credFileDetected"] = False self.detectDict["credScopeDetected"] = False self.detectDict["ehndDetected"] = False self.detectDict["windowocr"] = False self.folder = FolderManager() self.folder.removeDir(["tmp", "listItem"]) self.folder.createDir(["tmp", "listItem"]) self.iniHandler = IniHandler() listItemFolder = "./listItem/" if os.path.exists(listItemFolder): shutil.rmtree(listItemFolder) self.runGoodByeDpi() def runGoodByeDpi(self, ): def runGoodByeDpiThreadFunc(): admin.runAsAdmin(["lib_\\goodbyedpi\\goodbyedpi.exe "]) t = threading.Thread(target=runGoodByeDpiThreadFunc, args=(), daemon=True).start() def filterText(self, text): text = re.sub('[^0-9a-zA-Z]+', '', text) return text def showJSMessage(self, msg): self.browser.ExecuteFunction("showMessage", msg) ##ini setting------------------------------------------------------------- def createSettingBoxHtml(self, optionTitle, optionDict, selectedOption): optionItemHtml = "" for key in sorted(optionDict.keys()): selected = "" if key == selectedOption: selected = " selected" optionItemHtml += """ <option value='""" + optionDict[ key] + """'""" + selected + """>""" + key + """ </option> """ optionBarHtml = """ <div class="optionBoxContainer"> <h2 class='""" + optionTitle + """'>""" + optionTitle + """</h2> <div class="select_wrapper"><select name="" id="" class="form-control" onfocus='this.size=5; ' onblur='this.size=1;' onchange='this.size=1; this.blur();'> """ + optionItemHtml + """ </select> </div> </div> """ return optionBarHtml def createSettingBoxListHtml(self, ): boxListHtml = "" for key in sorted(self.iniHandler.optionList.keys()): item = self.iniHandler.optionList[key] if item["show"] == True: boxListHtml += self.createSettingBoxHtml( key, self.iniHandler.optionList[key]["optionItemDict"], self.iniHandler.currentSettingValDict[key]) return boxListHtml def initSetting(self, ): boxListHtml = self.createSettingBoxListHtml() self.browser.ExecuteFunction("createSettingBoxList", boxListHtml) if self.iniHandler.currentSettingValDict["detectiondone"] == "done": self.browser.ExecuteFunction("showPage", "main_page") for key in self.detectDict.keys(): self.detectDict[key] = True else: self.browser.ExecuteFunction("showPage", "start_page") ##start page------------------------------------------------------------- def openBrowser(self, url): webbrowser.open(url, new=2) def validateUrl(self, url): try: result = urlparse(url) return all([result.scheme, result.netloc]) except ValueError: return False def setClipboard(self, text): pyperclip.copy(text) def getClipboard(self, ): return pyperclip.paste() def checkClipboardChangedLoop(self, ): previouseClipboard = self.getClipboard() while True: time.sleep(1) if self.getClipboard() != previouseClipboard and self.getClipboard( ) != "": currentClipboard = self.getClipboard() previouseClipboard = currentClipboard self.processInputUrl(currentClipboard) def processInputUrl(self, url): if self.validateUrl(url) or os.path.isdir(url): if self.validateUrl(url): url = urllib.parse.urlparse(url) url = url.scheme + "://" + url.netloc + urllib.parse.quote( url.path) self.showJSMessage(url) self.startDownload(url) else: self.showJSMessage("not a valid url, use http format") def checkClipboardChanged(self, ): t = threading.Thread(target=self.checkClipboardChangedLoop, args=(), daemon=True).start() def get_download_path(self, ): """Returns the default downloads path for linux or windows""" if os.name == 'nt': import winreg sub_key = r'SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders' downloads_guid = '{374DE290-123F-4565-9164-39C4925E467B}' with winreg.OpenKey(winreg.HKEY_CURRENT_USER, sub_key) as key: location = winreg.QueryValueEx(key, downloads_guid)[0] return location else: return os.path.join(os.path.expanduser('~'), 'downloads') ##environment detection------------------------------------------------------------- def checkCredentialsDownloadedLoop(self, ): while (not os.path.exists( os.path.join(self.get_download_path(), 'credentials.json')) and not os.path.exists('credentials.json')): time.sleep(1.) if os.path.exists( os.path.join(self.get_download_path(), 'credentials.json')): shutil.copy( os.path.join(self.get_download_path(), 'credentials.json'), "./") self.showJSMessage("credentials.json detected") self.detectDict["credFileDetected"] = True self.checkDetectionAllDone() def checkCredScopeLoop(self, ): while (not os.path.exists("./token.pickle")): time.sleep(1.) self.showJSMessage("credential scope detected") self.detectDict["credScopeDetected"] = True self.checkDetectionAllDone() def checkEhndLoop(self, ): while (not os.path.exists( "C:\Program Files (x86)\ChangShinSoft\ezTrans XP\J2KEngineH.dll" )): time.sleep(1.) self.showJSMessage("eztrans ehnd detected") self.detectDict["ehndDetected"] = True self.checkDetectionAllDone() def checkWindowOcrLoop(self, ): while (not self.textOcr.checkWindowOcr()): time.sleep(1.) self.showJSMessage("window ocr detected") self.detectDict["windowocr"] = True self.checkDetectionAllDone() def checkInstall(self, slideNum): print(slideNum) if slideNum == 1: checkFunc = self.checkCredentialsDownloadedLoop elif slideNum == 2: checkFunc = self.checkCredScopeLoop elif slideNum == 3: checkFunc = self.checkEhndLoop elif slideNum == 4: checkFunc = self.checkWindowOcrLoop t = threading.Thread(target=checkFunc, args=(), daemon=True).start() def installWinOcr(self, ): admin.runAsAdmin([ "C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe ", """ $Capability = Get-WindowsCapability -Online | Where-Object { $_.Name -Like 'Language.OCR*ja-JP*' }; $Result = $Capability | Add-WindowsCapability -Online; if ($Result.RestartNeeded -eq $True) { Restart-Computer -Force }; """ ]) def checkDetectionAllDone(self, ): for key in self.detectDict.keys(): if self.detectDict[key] == False: return self.iniHandler.setINIValue("detectiondone", "done") #if all true check done def checkIsRunnableEvn(self, ): currentSetting = self.iniHandler.getCurrentSetting() if currentSetting["Translator"] == "eztrans": if self.detectDict["ehndDetected"] == False: self.showJSMessage( "ehnd setup is required for current setting") return False if currentSetting["OCR"] == "googleocr": if self.detectDict["credFileDetected"] == False or self.detectDict[ "credScopeDetected"] == False: self.showJSMessage( "googleocr setup is required for current setting") return False if currentSetting["OCR"] == "windowocr": if self.detectDict["windowocr"] == False: self.showJSMessage( "windowocr setup is required for current setting") return False return True #download------------------------------------------------------------- def startDownloadThreadFunc(self, url): itemId = self.filterText(url) itemId = datetime.now().strftime("%Y%m%d%H%M%S") infoFunc = self.createDownloadListItemHtml progressFunc = self.setItemProgressFunc self.createListItemLoading(itemId) self.downloadLock.acquire() mangaTrnaslator = MangaTranslatorGUI( url, self.iniHandler.getCurrentSetting(), itemId, infoFunc, progressFunc) result = mangaTrnaslator.processTranslation() self.downloadLock.release() if result == -1: self.browser.ExecuteFunction("removeListItem", itemId) self.showJSMessage("download failed. may be GoodbyeDPI not on") else: self.showJSMessage("downloaded to " + self.get_download_path()) def startDownload(self, url): if self.checkIsRunnableEvn(): t = threading.Thread(target=self.startDownloadThreadFunc, args=(url, ), daemon=True).start() def setItemProgressFunc(self, id, progress, time): self.browser.ExecuteFunction("setItemProgress", id, progress, time) def createListItemLoading(self, id): itemHtml = """ <li id=""" + id + """> <div class="loader_parent"> <div class="loader"></div> </div> <div class="progress-container"> <div class="progress_bar" ></div> </div> </li> """ self.browser.ExecuteFunction("addListItem", itemHtml) def createDownloadListItemHtml(self, id, title, itemImage, itemPages): itemHtml = """ <div class="li_contents"> <img class="li_img" src='""" + itemImage + """' id="thumb"/> <div class="li_contents_text"> <div class="li_title">""" + title + """</div> <div class="li_info_box"> <img src="icon/clock.png" class="li_info_icon"/> <div class="li_info_time">test</div> <img src="icon/photo.png" class="li_info_icon"/> <div class="li_info_pages">""" + itemPages + """p</div> </div> </div> </div> <div class="progress-container"><div class="progress_bar" ></div></div> """ self.browser.ExecuteFunction("changeListItem", id, itemHtml)
class MangaTranslator(): def __init__(self, url,settingValueDict): self.url=url self.translatorType=settingValueDict["translator"] self.language=settingValueDict["language"] self.font=settingValueDict["fontstyle"] self.fontsize=settingValueDict["fontsize"] self.textSegmentation=TextSegmenation() self.textDetection=TextDetection() self.textOcr=TextOcr() self.textTranslator=TextTranslator(self.translatorType,self.language) self.textDraw=TextDraw(self.font,self.fontsize) self.folder=FolderManager() self.customTqdm=tqdm def processTranslation(self,): ###folder init self.folder.removeDir([self.folder.downloadPath]) ####download downloader=DownloaderManager() downloadFileList,mangaName=downloader.downloadUrl(self.url) #downloadFileList,mangaName=downloader.getDownloadedFilePathList() if mangaName=="": print("download fail") return -1 oriFileList=self.folder.intitFolderEnv(downloadFileList,mangaName) self.sendInfo(mangaName,oriFileList[0],len(oriFileList)) print(mangaName) self.threadCounter=0 self.lock = threading.Lock() self.lock1 = threading.Lock() self.lock2 = threading.Lock() self.lock3 = threading.Lock() self.lock4 = threading.Lock() self.lock5 = threading.Lock() #forloop #for fileName in tqdm(oriFileList): # self.processTranslationTask(fileName) #thread start tList=[] for fileName in oriFileList: t = threading.Thread(target=self.processTranslationTask, args=(fileName,)) t.daemon = True t.start() tList+=[t] print("progess") #thread progress for i in self.customTqdm(range(len(oriFileList))): while self.threadCounter<=i: time.sleep(0.5) ###save_file self.folder.saveFileAndRemove(mangaName) return 1 def processTranslationTask(self,fileName): self.lock1.acquire() ###segmentation self.textSegmentation.segmentPage(fileName,self.folder.inpaintedFolder,self.folder.textOnlyFolder) self.lock1.release() self.lock2.acquire() ###text_detection textBoxList=self.textDetection.textDetect(fileName,self.folder.textOnlyFolder) self.lock2.release() self.lock3.acquire() ###text_ocr textList=self.textOcr.getTextFromImg(fileName,textBoxList,self.folder.textOnlyFolder) self.lock3.release() self.lock4.acquire() ###text_translation textList_trans=self.textTranslator.translate(textList) self.lock4.release() self.lock5.acquire() ###text_draw self.textDraw.drawTextToImage(fileName,textBoxList,textList_trans,self.folder.inpaintedFolder,self.folder.transalatedFolder) self.lock5.release() #count finish self.lock.acquire() self.threadCounter+=1 self.lock.release() def sendInfo(self,title,image,pages): pass
class GuiUtil(): def __init__(self, browser): self.downloadLock = threading.Lock() self.configPath = "setting.ini" self.config = configparser.ConfigParser() self.browser = browser self.credFileDetected = False self.credScopeDetected = False self.ehndDetected = False self.folder = FolderManager() self.folder.removeDir(["tmp", "listItem"]) self.folder.createDir(["tmp", "listItem"]) self.loadINI() def filterText(self, text): text = re.sub('[^0-9a-zA-Z]+', '', text) return text def showJSMessage(self, msg): self.browser.ExecuteFunction("showMessage", msg) ##ini setting------------------------------------------------------------- def saveINIwithDict(self, settingDict): self.config['setting'] = settingDict with open(self.configPath, 'w') as configfile: self.config.write(configfile) def saveINI(self, tranlsator, lang, font, fontSize, detection): self.config['setting'] = { 'translator': tranlsator, 'language': lang, 'fontstyle': font, 'fontsize': fontSize, "detectiondone": detection } with open(self.configPath, 'w') as configfile: self.config.write(configfile) def loadINI(self, ): self.config = configparser.ConfigParser() self.config.read(self.configPath) if "setting" not in self.config.sections(): self.saveINI("EZTrans XP", "korean", "NotoSans", "auto", "notDone") self.iniDict = dict(self.config["setting"]) def loadTranslateSettingValue(self, ): self.loadINI() settingValueDict = dict({}) settingValueDict["translator"] = self.getTranslaotrList()[ self.iniDict["translator"]] settingValueDict["language"] = self.getLanguageList()[ self.iniDict["language"]] settingValueDict["fontstyle"] = self.getFontStyleList()[ self.iniDict["fontstyle"]] settingValueDict["fontsize"] = self.iniDict["fontsize"] return settingValueDict def getTranslaotrList(self, ): translatorDict = dict({"EZTrans XP": "eztrans"}) #,"Google":"google" }) return translatorDict def getLanguageList(self, ): LANGUAGES = { 'afrikaans': 'af', 'albanian': 'sq', 'amharic': 'am', 'arabic': 'ar', 'armenian': 'hy', 'azerbaijani': 'az', 'basque': 'eu', 'belarusian': 'be', 'bengali': 'bn', 'bosnian': 'bs', 'bulgarian': 'bg', 'catalan': 'ca', 'cebuano': 'ceb', 'chichewa': 'ny', 'chinese (simplified)': 'zh-cn', 'chinese (traditional)': 'zh-tw', 'corsican': 'co', 'croatian': 'hr', 'czech': 'cs', 'danish': 'da', 'dutch': 'nl', 'english': 'en', 'esperanto': 'eo', 'estonian': 'et', 'filipino': 'tl', 'finnish': 'fi', 'french': 'fr', 'frisian': 'fy', 'galician': 'gl', 'georgian': 'ka', 'german': 'de', 'greek': 'el', 'gujarati': 'gu', 'haitian creole': 'ht', 'hausa': 'ha', 'hawaiian': 'haw', 'hebrew': 'iw', 'hindi': 'hi', 'hmong': 'hmn', 'hungarian': 'hu', 'icelandic': 'is', 'igbo': 'ig', 'indonesian': 'id', 'irish': 'ga', 'italian': 'it', 'japanese': 'ja', 'javanese': 'jw', 'kannada': 'kn', 'kazakh': 'kk', 'khmer': 'km', 'korean': 'ko', 'kurdish (kurmanji)': 'ku', 'kyrgyz': 'ky', 'lao': 'lo', 'latin': 'la', 'latvian': 'lv', 'lithuanian': 'lt', 'luxembourgish': 'lb', 'macedonian': 'mk', 'malagasy': 'mg', 'malay': 'ms', 'malayalam': 'ml', 'maltese': 'mt', 'maori': 'mi', 'marathi': 'mr', 'mongolian': 'mn', 'myanmar (burmese)': 'my', 'nepali': 'ne', 'norwegian': 'no', 'pashto': 'ps', 'persian': 'fa', 'polish': 'pl', 'portuguese': 'pt', 'punjabi': 'pa', 'romanian': 'ro', 'russian': 'ru', 'samoan': 'sm', 'scots gaelic': 'gd', 'serbian': 'sr', 'sesotho': 'st', 'shona': 'sn', 'sindhi': 'sd', 'sinhala': 'si', 'slovak': 'sk', 'slovenian': 'sl', 'somali': 'so', 'spanish': 'es', 'sundanese': 'su', 'swahili': 'sw', 'swedish': 'sv', 'tajik': 'tg', 'tamil': 'ta', 'telugu': 'te', 'thai': 'th', 'turkish': 'tr', 'ukrainian': 'uk', 'urdu': 'ur', 'uzbek': 'uz', 'vietnamese': 'vi', 'welsh': 'cy', 'xhosa': 'xh', 'yiddish': 'yi', 'yoruba': 'yo', 'zulu': 'zu' } return LANGUAGES def getFontSizeList(self, ): sizeDict = dict({}) for i in range(5, 100): sizeDict[str(i)] = str(i) sizeDict["auto"] = "auto" return sizeDict def getFontStyleList(self, ): from matplotlib import font_manager font_manager._rebuild() # 리스트의 원소(폰트파일의 경로)만큼 반복 fontDict = dict({}) for v in font_manager.findSystemFonts(fontpaths=None, fontext='ttf'): try: # 각 폰트파일의 경로를 사용하여 폰트 속성 객체 얻기 fprop = font_manager.FontProperties(fname=v) # 폰트 속성중 이름과 파일 경로를 딕셔러리로 구성하여 리스트에 추가. fontDict[fprop.get_name()] = fprop.get_file() except: continue fontDict = dict(sorted(fontDict.items())) #sort key newFontDict = dict({}) for key in fontDict.keys(): newFontDict["""<span style="font-family:""" + key + """;">""" + key + "</span>"] = fontDict[ key] #apply font style on display fontDict = newFontDict #<span style="font-family:Ami R;">Ami R</span> fontDict["NotoSans"] = "./font/NotoSansKR-Regular.otf" return newFontDict def createSettingBoxHtml(self, optionTitle, optionKey, optionDict, selectedOption): optionItemHtml = "" for key in optionDict.keys(): optionItemHtml += """ <div class="option"> <input type="radio" class="radio" id='""" + optionDict[ key] + """' "name="category" /> <label for='""" + optionDict[key] + """'>""" + key + """</label> </div> """ optionBarHtml = """ <div class="optionBoxContainer"> <h2 class='""" + optionKey + """'>""" + optionTitle + """</h2> <div class="select-box"> <div class="options-container"> """ + optionItemHtml + """ </div> <div class="selected"> """ + selectedOption + """ </div> </div> </div> """ return optionBarHtml def createSettingBoxListHtml(self, ): boxListHtml = "" boxListHtml += self.createSettingBoxHtml("Translator", "translator", self.getTranslaotrList(), self.iniDict["translator"]) boxListHtml += self.createSettingBoxHtml("Language", "language", self.getLanguageList(), self.iniDict["language"]) boxListHtml += self.createSettingBoxHtml("FontStyle", "fontstyle", self.getFontStyleList(), self.iniDict["fontstyle"]) boxListHtml += self.createSettingBoxHtml("FontSize", "fontsize", self.getFontSizeList(), self.iniDict["fontsize"]) return boxListHtml def initSetting(self, ): boxListHtml = self.createSettingBoxListHtml() self.browser.ExecuteFunction("createSettingBoxList", boxListHtml) if self.iniDict["detectiondone"] == "done": self.browser.ExecuteFunction("showPage", "main_page") else: self.browser.ExecuteFunction("showPage", "start_page") def setINIValue(self, name, value): self.iniDict[name] = value self.saveINIwithDict(self.iniDict) ##start page------------------------------------------------------------- def getGoogleCred(self, ): SCOPES = ['https://www.googleapis.com/auth/drive'] creds = None # The file token.pickle stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. if os.path.exists('token.pickle'): with open('token.pickle', 'rb') as token: creds = pickle.load(token) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( 'credentials.json', SCOPES) creds = flow.run_local_server(port=0) # Save the credentials for the next run with open('token.pickle', 'wb') as token: pickle.dump(creds, token) service = build('drive', 'v3', credentials=creds) return service def openBrowser(self, url): webbrowser.open(url, new=2) def validateUrl(self, url): try: result = urlparse(url) return all([result.scheme, result.netloc]) except ValueError: return False def getClipboard(self, ): try: win32clipboard.OpenClipboard() data = win32clipboard.GetClipboardData() win32clipboard.CloseClipboard() except: data = "" return data def checkClipboardChangedLoop(self, ): previouseClipboard = self.getClipboard() while True: time.sleep(1) if self.getClipboard() != previouseClipboard and self.getClipboard( ) != "": currentClipboard = self.getClipboard() previouseClipboard = currentClipboard self.processInputUrl(currentClipboard) def processInputUrl(self, url): if not self.validateUrl(url): self.showJSMessage("not a valid url, use http format") else: self.showJSMessage(url) self.startDownload(url) def checkClipboardChanged(self, ): t = threading.Thread(target=self.checkClipboardChangedLoop, args=()) t.daemon = True t.start() def get_download_path(self, ): """Returns the default downloads path for linux or windows""" if os.name == 'nt': import winreg sub_key = r'SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders' downloads_guid = '{374DE290-123F-4565-9164-39C4925E467B}' with winreg.OpenKey(winreg.HKEY_CURRENT_USER, sub_key) as key: location = winreg.QueryValueEx(key, downloads_guid)[0] return location else: return os.path.join(os.path.expanduser('~'), 'downloads') def checkCredentialsDownloadedLoop(self, ): if self.iniDict["detectiondone"] == "done": return while (not os.path.exists( os.path.join(self.get_download_path(), 'credentials.json')) and not os.path.exists('credentials.json')): time.sleep(1.) if os.path.exists( os.path.join(self.get_download_path(), 'credentials.json')): shutil.copy( os.path.join(self.get_download_path(), 'credentials.json'), "./") self.showJSMessage("credentials.json detected") self.credFileDetected = True self.checkDetectionAllDone() def checkCredentialsDownloaded(self, ): t = threading.Thread(target=self.checkCredentialsDownloadedLoop, args=()) t.daemon = True t.start() def checkCredScopeLoop(self, ): while (not os.path.exists("./token.pickle")): time.sleep(1.) self.showJSMessage("credential scope detected") self.credScopeDetected = True self.checkDetectionAllDone() def checkCredScope(self, ): t = threading.Thread(target=self.checkCredScopeLoop, args=()) t.daemon = True t.start() def checkEhndLoop(self, ): while (not os.path.exists( "C:\Program Files (x86)\ChangShinSoft\ezTrans XP\J2KEngineH.dll" )): time.sleep(1.) self.showJSMessage("eztrans ehnd detected") self.ehndDetected = True self.checkDetectionAllDone() def checkEhnd(self, ): t = threading.Thread(target=self.checkEhndLoop, args=()) t.daemon = True t.start() def checkDetectionAllDone(self, ): if self.credFileDetected and self.credScopeDetected and self.ehndDetected: self.setINIValue("detectiondone", "done") #download------------------------------------------------------------- def startDownloadThreadFunc(self, url): itemId = self.filterText(url) infoFunc = self.createDownloadListItemHtml progressFunc = self.setItemProgressFunc self.createListItemLoading(itemId) self.downloadLock.acquire() mangaTrnaslator = MangaTranslatorGUI(url, self.loadTranslateSettingValue(), itemId, infoFunc, progressFunc) result = mangaTrnaslator.processTranslation() self.downloadLock.release() if result == -1: self.browser.ExecuteFunction("removeListItem", itemId) self.showJSMessage("download failed. may be GoodbyeDPI not on") else: self.showJSMessage("downloaded to " + self.get_download_path()) def startDownload(self, url): t = threading.Thread(target=self.startDownloadThreadFunc, args=(url, )) t.daemon = True t.start() def setItemProgressFunc(self, id, progress, time): self.browser.ExecuteFunction("setItemProgress", id, progress, time) def createListItemLoading(self, id): itemHtml = """ <li id=""" + id + """> <div class="loader_parent"> <div class="loader"></div> </div> <div class="progress-container"> <div class="progress_bar" ></div> </div> </li> """ self.browser.ExecuteFunction("addListItem", itemHtml) def createDownloadListItemHtml(self, id, title, itemImage, itemPages): itemHtml = """ <div class="li_contents"> <img class="li_img" src='""" + itemImage + """' id="thumb"/> <div class="li_contents_text"> <div class="li_title">""" + title + """</div> <div class="li_info_box"> <img src="icon/clock.png" class="li_info_icon"/> <div class="li_info_time">test</div> <img src="icon/photo.png" class="li_info_icon"/> <div class="li_info_pages">""" + itemPages + """p</div> </div> </div> </div> <div class="progress-container"><div class="progress_bar" ></div></div> """ self.browser.ExecuteFunction("changeListItem", id, itemHtml)