id
int64
0
458k
file_name
stringlengths
4
119
file_path
stringlengths
14
227
content
stringlengths
24
9.96M
size
int64
24
9.96M
language
stringclasses
1 value
extension
stringclasses
14 values
total_lines
int64
1
219k
avg_line_length
float64
2.52
4.63M
max_line_length
int64
5
9.91M
alphanum_fraction
float64
0
1
repo_name
stringlengths
7
101
repo_stars
int64
100
139k
repo_forks
int64
0
26.4k
repo_open_issues
int64
0
2.27k
repo_license
stringclasses
12 values
repo_extraction_date
stringclasses
433 values
6,700
g_kobo_dictfile_test.py
ilius_pyglossary/tests/g_kobo_dictfile_test.py
import unittest import mistune # noqa: F401, to ensure it's installed from glossary_v2_test import TestGlossaryBase class TestGlossaryDictfile(TestGlossaryBase): def __init__(self, *args, **kwargs): TestGlossaryBase.__init__(self, *args, **kwargs) self.dataFileCRC32.update( { "022-en-en.df": "edff6de1", "022-en-en.df.txt": "93a2450f", "022-en-en.df.txt.df": "8e952e56", "res/01cf5b41.gif": "01cf5b41", "res/1f3c1a36.gif": "1f3c1a36", "res/3af9fd5d.gif": "3af9fd5d", "res/6684158d.gif": "6684158d", }, ) def convert_df_txt(self, fname, fname2, resFiles, **convertArgs): resFilesPath = { resFileName: self.newTempFilePath(f"{fname}-2.txt_res/{resFileName}") for resFileName in resFiles } self.convert( f"{fname}.df", f"{fname}-2.txt", compareText=f"{fname2}.txt", **convertArgs, ) for resFileName in resFiles: fpath1 = self.downloadFile(f"res/{resFileName}") fpath2 = resFilesPath[resFileName] self.compareBinaryFiles(fpath1, fpath2) def convert_txt_df(self, fname, fname2, **convertArgs): self.convert( f"{fname}.txt", f"{fname}-2.df", compareText=f"{fname2}.df", **convertArgs, ) def test_convert_df_txt_1(self): self.convert_df_txt( "022-en-en", "022-en-en.df", resFiles=[ "01cf5b41.gif", "1f3c1a36.gif", "3af9fd5d.gif", "6684158d.gif", ], ) def test_convert_txt_df_1(self): self.convert_txt_df( "022-en-en.df", "022-en-en.df.txt", ) if __name__ == "__main__": unittest.main()
1,534
Python
.py
57
23.22807
72
0.666894
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,701
g_dsl_test.py
ilius_pyglossary/tests/g_dsl_test.py
import sys import tempfile import unittest from os.path import abspath, dirname, join rootDir = dirname(dirname(abspath(__file__))) sys.path.insert(0, rootDir) from glossary_v2_test import TestGlossaryBase from pyglossary.glossary_v2 import ConvertArgs, Glossary class TestGlossaryDSL(TestGlossaryBase): def __init__(self, *args, **kwargs): TestGlossaryBase.__init__(self, *args, **kwargs) self.dataFileCRC32.update( { "dsl/100-RussianAmericanEnglish-ru-en.dsl": "c24491e0", "dsl/100-RussianAmericanEnglish-ru-en-v3.txt": "43b6d58e", "dsl/001-empty-lines-br.dsl": "6f2fca1a", "dsl/001-empty-lines-br.txt": "74e578ff", "dsl/002-m-tag_multiline-paragraph.dsl": "334079e3", "dsl/002-m-tag_multiline-paragraph-v2.txt": "d5001afd", "dsl/003-ref-target-c.dsl": "9c1396c4", "dsl/003-ref-target-c.txt": "ab41cedf", "dsl/006-include/included.dsl": "10ef1018", "dsl/006-include/main.dsl": "8325d538", "dsl/006-include/main.txt": "d7ed9f2b", }, ) def convert_string_dsl_txt( self, dsl: str, txtExpected: str, removeInfo: bool = True, **convertArgs, ): prefix = join(self.tempDir, "") dsl_fname = tempfile.mktemp(suffix=".dsl", prefix=prefix) txt_fname = tempfile.mktemp(suffix=".txt", prefix=prefix) with open(dsl_fname, "w", encoding="utf-8") as _file: _file.write(dsl) glos = self.glos = Glossary() # glos.config = config res = glos.convert( ConvertArgs( inputFilename=dsl_fname, outputFilename=txt_fname, **convertArgs, ), ) self.assertEqual(txt_fname, res) with open(txt_fname, encoding="utf-8") as _file: txtActual = _file.read() if removeInfo: txtActual = "\n".join( [ line for line in txtActual.split("\n") if line and not line.startswith("#") ], ) self.assertEqual(txtExpected, txtActual) def convert_dsl_txt(self, fname, fname2, **convertArgs): self.convert( f"dsl/{fname}.dsl", f"{fname}-2.txt", compareText=f"dsl/{fname2}.txt", **convertArgs, ) def test_include(self): dirName = "dsl/006-include" fname = "main" files = ["included.dsl", "main.dsl"] inputDirPath = self.downloadDir(dirName, files) inputFilePath = join(inputDirPath, f"{fname}.dsl") outputFilePath = self.newTempFilePath(f"{fname}-2.txt") expectedOutputFilePath = self.downloadFile(join(dirName, f"{fname}.txt")) self.glos = Glossary() result = self.glos.convert( ConvertArgs( inputFilename=inputFilePath, outputFilename=outputFilePath, ) ) self.assertIsNotNone(result) self.assertEqual(result, outputFilePath) self.compareTextFiles( outputFilePath, expectedOutputFilePath, ) def test_russianAmericanEnglish(self): self.convert_dsl_txt( "100-RussianAmericanEnglish-ru-en", "100-RussianAmericanEnglish-ru-en-v3", ) def test_empty_lines_br(self): self.convert_dsl_txt( "001-empty-lines-br", "001-empty-lines-br", ) def test_m_tag_multiline_paragraph(self): self.convert_dsl_txt( "002-m-tag_multiline-paragraph", "002-m-tag_multiline-paragraph-v2", ) def test_ref_target_c(self): self.convert_dsl_txt( "003-ref-target-c", "003-ref-target-c", ) def test_headword_formatting_bashkir_basque(self): # from Bashkir -> Basque dict (001-headword-with-formatting.dsl) dsl = ( "{[c slategray]}{to }{[/c]}tell " "{[c slategray]}smb{[/c]} how to do " "{[c slategray]}smth{[/c]}\n [m1][trn]" "рассказать кому-либо, как что-либо делать[/trn][/m]" ) txt = ( "tell smb how to do smth\t" '<b><font color="slategray">to </font>tell ' '<font color="slategray">smb</font> how to do ' '<font color="slategray">smth</font></b><br/>' '<p style="padding-left:1em;margin:0">' "рассказать кому-либо, как что-либо делать</p>" ) self.convert_string_dsl_txt(dsl, txt) def test_headword_formatting_english(self): dsl = ( "{[c slategray]}{to }{[/c]}tell" " {[c violet]}smb{[/c]} {[u]}how{[/u]}" " to do {[c violet]}smth{[/c]} {[sub]subscript[/sub]}\n" " [m1]1. main meaning[/m]\n" " [m2]a. first submeaning[/m]\n" " [m2]b. second submeaning[/m]\n" ) txt = ( "tell smb how to do smth\t" '<b><font color="slategray">to </font>tell' ' <font color="violet">smb</font> <u>how</u>' ' to do <font color="violet">smth</font> <sub>subscript</sub></b><br/>' '<p style="padding-left:1em;margin:0">1. main meaning</p>' '<p style="padding-left:2em;margin:0">a. first submeaning</p>' '<p style="padding-left:2em;margin:0">b. second submeaning</p>' ) self.convert_string_dsl_txt(dsl, txt) def test_p_unclosed(self): dsl = "headword\n" " [m1][p]test\n" txt = ( "headword\t" '<p style="padding-left:1em;margin:0"><i class="p"><font color="green">test\\n</font></i>' ) self.convert_string_dsl_txt(dsl, txt) def test_headword_paran(self): self.convert_string_dsl_txt( "headword with (parenthesis)\n test", "headword with parenthesis|headword with\ttest", ) def test_headword_paran_2(self): self.convert_string_dsl_txt( "(headword with) parenthesis\n test", "headword with parenthesis|parenthesis\ttest", ) def test_headword_paran_escaped(self): self.convert_string_dsl_txt( "headword \\(with escaped parenthesis\\)\n test", "headword (with escaped parenthesis)\ttest", ) def test_headword_paran_escaped_2(self): self.convert_string_dsl_txt( "headword (with escaped right \\) parenthesis)\n test", "headword with escaped right \\\\) parenthesis|headword\ttest", ) def test_headword_curly(self): txt = ( "headword with curly brackets\t" "<b>headword with <b>curly brackets</b></b><br/>test" ) self.convert_string_dsl_txt( "headword with {[b]}curly brackets{[/b]}\n test", txt, ) def test_headword_curly_escaped(self): self.convert_string_dsl_txt( "headword with escaped \\{\\}curly brackets\\{\n test", "headword with escaped {}curly brackets{\ttest", ) def test_double_brackets_1(self): self.convert_string_dsl_txt( "test\n hello [[world]]", "test\thello [world]", ) def test_double_brackets_2(self): self.convert_string_dsl_txt( "test\n hello [[", "test\thello [", ) def test_double_brackets_3(self): self.convert_string_dsl_txt( "test\n hello ]]", "test\thello ]", ) def test_ref_double_ltgt(self): self.convert_string_dsl_txt( "test\n hello <<world>>", 'test\thello <a href="bword://world">world</a>', ) def test_ref_double_ltgt_escaped(self): self.convert_string_dsl_txt( "test\n hello \\<<world\\>>", "test\thello &lt;&lt;world&gt;&gt;", ) if __name__ == "__main__": unittest.main()
6,743
Python
.py
211
28.118483
93
0.672422
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,702
glossary_v2_test.py
ilius_pyglossary/tests/glossary_v2_test.py
import hashlib import json import logging import os import random import sys import tempfile import tracemalloc import unittest import zipfile from collections.abc import Callable from os.path import abspath, dirname, isdir, isfile, join, realpath from urllib.request import urlopen rootDir = dirname(dirname(abspath(__file__))) sys.path.insert(0, rootDir) from pyglossary.core import cacheDir, log, tmpDir from pyglossary.glossary_v2 import ConvertArgs, Glossary from pyglossary.os_utils import rmtree from pyglossary.text_utils import crc32hex __all__ = ["TestGlossaryBase", "appTmpDir", "testCacheDir"] tracemalloc.start() Glossary.init() repo = os.getenv( "PYGLOSSARY_TEST_REPO", "ilius/pyglossary-test/main", ) dataURL = f"https://raw.githubusercontent.com/{repo}/{{filename}}" testCacheDir = realpath(join(cacheDir, "test")) appTmpDir = join(cacheDir, "tmp") os.makedirs(testCacheDir, exist_ok=True) os.chdir(testCacheDir) os.makedirs(join(tmpDir, "pyglossary"), exist_ok=True) class TestGlossaryBase(unittest.TestCase): def __init__(self, *args, **kwargs): unittest.TestCase.__init__(self, *args, **kwargs) self.maxDiff = None self.dataFileCRC32 = { "004-bar.txt": "6775e590", "004-bar-sort.txt": "fe861123", "006-empty.txt": "07ff224b", "006-empty-filtered.txt": "2b3c1c0f", "100-en-de-v4.txt": "d420a669", "100-en-fa.txt": "f5c53133", "100-ja-en.txt": "93542e89", "100-en-de-v4-remove_font_b.txt": "a3144e2f", "100-en-de-v4.sd/100-en-de.dict": "5a97476f", "100-en-de-v4.sd/100-en-de.idx": "a99f29d2", "100-en-de-v4.sd/100-en-de.ifo": "6529871f", "100-en-de-v4.info": "f2cfb284", "100-en-fa.info": "9bddb7bb", "100-en-fa-v2.info": "7c0f646b", "100-ja-en.info": "8cf5403c", "300-rand-en-fa.txt": "586617c8", "res/stardict.png": "7e1447fa", "res/test.json": "41f8cf31", } def addDirCRC32(self, dirPath: str, files: "dict[str, str]") -> None: for fpath, _hash in files.items(): self.dataFileCRC32[f"{dirPath}/{fpath}"] = _hash # The setUp() and tearDown() methods allow you to define instructions that # will be executed before and after each test method. def setUp(self): self.glos = None self.tempDir = tempfile.mkdtemp(dir=join(tmpDir, "pyglossary")) def tearDown(self): if self.glos is not None: self.glos.cleanup() self.glos.clear() if os.getenv("NO_CLEANUP"): return for direc in ( self.tempDir, appTmpDir, ): if isdir(direc): rmtree(direc) def fixDownloadFilename(self, filename): return filename.replace("/", "__").replace("\\", "__") def downloadFile(self, filename): unixFilename = filename.replace("\\", "/") _crc32 = self.dataFileCRC32[unixFilename] fpath = join(testCacheDir, self.fixDownloadFilename(filename)) if isfile(fpath): with open(fpath, mode="rb") as _file: data = _file.read() if crc32hex(data) != _crc32: raise RuntimeError(f"CRC32 check failed for existing file: {fpath!r}") return fpath try: with urlopen(dataURL.format(filename=unixFilename)) as res: data = res.read() except Exception as e: print(f"{filename=}") raise e from None actual_crc32 = crc32hex(data) if actual_crc32 != _crc32: raise RuntimeError( "CRC32 check failed for downloaded file: " f"{filename!r}: {actual_crc32}", ) with open(fpath, mode="wb") as _file: _file.write(data) return fpath def downloadDir(self, dirName: str, files: list[str]) -> str: dirPath = join(testCacheDir, self.fixDownloadFilename(dirName)) for fileRelPath in files: newFilePath = join(dirPath, fileRelPath) if isfile(newFilePath): # TODO: check crc-32 continue filePath = self.downloadFile(join(dirName, fileRelPath)) os.makedirs(dirname(newFilePath), exist_ok=True) os.rename(filePath, newFilePath) return dirPath def newTempFilePath(self, filename): fpath = join(self.tempDir, filename) if isfile(fpath): os.remove(fpath) return fpath def showGlossaryDiff(self, fpath1, fpath2) -> None: from pyglossary.ui.tools.diff_glossary import diffGlossary diffGlossary(fpath1, fpath2) def compareTextFiles(self, fpath1, fpath2, showDiff=False): self.assertTrue(isfile(fpath1), f"{fpath1 = }") self.assertTrue(isfile(fpath2), f"{fpath2 = }") with open(fpath1, encoding="utf-8") as file1: text1 = file1.read().rstrip("\n") with open(fpath2, encoding="utf-8") as file2: text2 = file2.read().rstrip("\n") try: self.assertEqual( len(text1), len(text2), msg=f"{fpath1!r} differs from {fpath2!r} in file size", ) self.assertEqual( text1, text2, msg=f"{fpath1!r} differs from {fpath2!r}", ) except AssertionError as e: if showDiff: self.showGlossaryDiff(fpath1, fpath2) raise e from None def compareBinaryFiles(self, fpath1, fpath2): self.assertTrue(isfile(fpath1), f"File {fpath1!r} does not exist") self.assertTrue(isfile(fpath2), f"File {fpath2!r} does not exist") with open(fpath1, mode="rb") as file1: data1 = file1.read() with open(fpath2, mode="rb") as file2: data2 = file2.read() self.assertEqual(len(data1), len(data2), msg=f"{fpath1!r}") self.assertTrue( data1 == data2, msg=f"{fpath1!r} differs from {fpath2!r}", ) def compareZipFiles( self, fpath1, fpath2, dataReplaceFuncs: "dict[str, Callable]", ): zf1 = zipfile.ZipFile(fpath1) zf2 = zipfile.ZipFile(fpath2) pathList1 = zf1.namelist() pathList2 = zf2.namelist() if not self.assertEqual(pathList1, pathList2): return for zfpath in pathList1: data1 = zf1.read(zfpath) data2 = zf2.read(zfpath) func = dataReplaceFuncs.get(zfpath) if func is not None: data1 = func(data1) data2 = func(data2) self.assertEqual(len(data1), len(data2), msg=f"{zfpath=}") self.assertTrue( data1 == data2, msg=f"{zfpath=}", ) def checkZipFileSha1sum( self, fpath, sha1sumDict: "dict[str, str]", dataReplaceFuncs: "dict[str, Callable] | None" = None, ): if dataReplaceFuncs is None: dataReplaceFuncs = {} zf = zipfile.ZipFile(fpath) # pathList = zf.namelist() for zfpath, expectedSha1 in sha1sumDict.items(): data = zf.read(zfpath) func = dataReplaceFuncs.get(zfpath) if func is not None: data = func(data) actualSha1 = hashlib.sha1(data).hexdigest() self.assertEqual(actualSha1, expectedSha1, msg=f"file: {zfpath}") def convert( # noqa: PLR0913 self, fname, # input file with extension fname2, # output file with extension testId="tmp", # noqa: ARG002 compareText="", compareBinary="", sha1sum=None, md5sum=None, config=None, showDiff=False, **convertKWArgs, ): inputFilename = self.downloadFile(fname) outputFilename = self.newTempFilePath(fname2) glos = self.glos = Glossary() if config is not None: glos.config = config res = glos.convert( ConvertArgs( inputFilename=inputFilename, outputFilename=outputFilename, **convertKWArgs, ), ) self.assertEqual(outputFilename, res) if compareText: self.compareTextFiles( outputFilename, self.downloadFile(compareText), showDiff=showDiff, ) return if compareBinary: self.compareBinaryFiles(outputFilename, self.downloadFile(compareBinary)) return msg = f"{outputFilename=}" if sha1sum: with open(outputFilename, mode="rb") as _file: actualSha1 = hashlib.sha1(_file.read()).hexdigest() self.assertEqual(sha1sum, actualSha1, msg) return if md5sum: with open(outputFilename, mode="rb") as _file: actualMd5 = hashlib.md5(_file.read()).hexdigest() self.assertEqual(md5sum, actualMd5, msg) return def convert_sqlite_both(self, *args, **kwargs): for sqlite in (None, True, False): self.convert(*args, sqlite=sqlite, **kwargs) class TestGlossary(TestGlossaryBase): def __init__(self, *args, **kwargs): TestGlossaryBase.__init__(self, *args, **kwargs) self.dataFileCRC32.update( { "100-en-fa-sort.txt": "d7a82dc8", "100-en-fa-sort-headword.txt": "4067a29f", "100-en-fa-sort-ebook.txt": "aa620d07", "100-en-fa-sort-ebook3.txt": "5a20f140", "100-en-fa-lower.txt": "62178940", "100-en-fa-remove_html_all-v3.txt": "d611c978", "100-en-fa-rtl.txt": "25ede1e8", "300-rand-en-fa-sort-headword-w1256.txt": "06d83bac", "300-rand-en-fa-sort-headword.txt": "df0f8020", "300-rand-en-fa-sort-w1256.txt": "9594aab3", "sort-locale/092-en-fa-alphabet-sample.txt": "b4856532", "sort-locale/092-en-fa-alphabet-sample-sorted-default.txt": "e7b70589", "sort-locale/092-en-fa-alphabet-sample-sorted-en.txt": "3d2bdf73", "sort-locale/092-en-fa-alphabet-sample-sorted-fa.txt": "245419db", "sort-locale/092-en-fa-alphabet-sample-sorted-latin-fa.txt": "261c03c0", }, ) def setUp(self): TestGlossaryBase.setUp(self) self.prevLogLevel = log.level log.setLevel(logging.ERROR) def tearDown(self): TestGlossaryBase.tearDown(self) log.setLevel(self.prevLogLevel) def test__str__1(self): glos = self.glos = Glossary() self.assertEqual(str(glos), "Glossary{filename: '', name: None}") def test__str__2(self): glos = self.glos = Glossary() glos._filename = "test.txt" self.assertEqual(str(glos), "Glossary{filename: 'test.txt', name: None}") def test__str__3(self): glos = self.glos = Glossary() glos.setInfo("title", "Test Title") self.assertEqual( str(glos), "Glossary{filename: '', name: 'Test Title'}", ) def test__str__4(self): glos = self.glos = Glossary() glos._filename = "test.txt" glos.setInfo("title", "Test Title") self.assertEqual( str(glos), "Glossary{filename: 'test.txt', name: 'Test Title'}", ) def test_info_1(self): glos = self.glos = Glossary() glos.setInfo("test", "ABC") self.assertEqual(glos.getInfo("test"), "ABC") def test_info_2(self): glos = self.glos = Glossary() glos.setInfo("bookname", "Test Glossary") self.assertEqual(glos.getInfo("title"), "Test Glossary") def test_info_3(self): glos = self.glos = Glossary() glos.setInfo("bookname", "Test Glossary") glos.setInfo("title", "Test 2") self.assertEqual(glos.getInfo("name"), "Test 2") self.assertEqual(glos.getInfo("bookname"), "Test 2") self.assertEqual(glos.getInfo("title"), "Test 2") def test_info_4(self): glos = self.glos = Glossary() glos.setInfo("test", 123) self.assertEqual(glos.getInfo("test"), "123") def test_info_del_1(self): glos = self.glos = Glossary() glos.setInfo("test", "abc") self.assertEqual(glos.getInfo("test"), "abc") glos.setInfo("test", None) self.assertEqual(glos.getInfo("test"), "") def test_info_del_2(self): glos = self.glos = Glossary() glos.setInfo("test", None) self.assertEqual(glos.getInfo("test"), "") def test_setInfo_err1(self): glos = self.glos = Glossary() try: glos.setInfo(1, "a") except TypeError as e: self.assertEqual(str(e), "invalid key=1, must be str") else: self.fail("must raise a TypeError") def test_getInfo_err1(self): glos = self.glos = Glossary() try: glos.getInfo(1) except TypeError as e: self.assertEqual(str(e), "invalid key=1, must be str") else: self.fail("must raise a TypeError") def test_getExtraInfos_1(self): glos = self.glos = Glossary() glos.setInfo("a", "test 1") glos.setInfo("b", "test 2") glos.setInfo("c", "test 3") glos.setInfo("d", "test 4") glos.setInfo("name", "my name") self.assertEqual( glos.getExtraInfos(["b", "c", "title"]), {"a": "test 1", "d": "test 4"}, ) def test_infoKeys_1(self): glos = self.glos = Glossary() glos.setInfo("a", "test 1") glos.setInfo("b", "test 2") glos.setInfo("name", "test name") glos.setInfo("title", "test title") self.assertEqual( glos.infoKeys(), ["a", "b", "name"], ) def test_config_attr_get(self): glos = self.glos = Glossary() try: glos.config # noqa: B018 except NotImplementedError: pass else: self.fail("must raise NotImplementedError") def test_config_attr_set(self): glos = self.glos = Glossary() glos.config = {"lower": True} self.assertEqual(glos.getConfig("lower", False), True) def test_directRead_txt_1(self): inputFilename = self.downloadFile("100-en-fa.txt") glos = self.glos = Glossary() res = glos.directRead(filename=inputFilename) self.assertTrue(res) self.assertEqual(glos.sourceLangName, "English") self.assertEqual(glos.targetLangName, "Persian") self.assertIn("Sample: ", glos.getInfo("name")) entryCount = sum(1 for _ in glos) self.assertEqual(entryCount, 100) def test_init_infoDict(self): glos = self.glos = Glossary(info={"a": "b"}) self.assertEqual(list(glos.iterInfo()), [("a", "b")]) def test_init_infoOrderedDict(self): from collections import OrderedDict glos = self.glos = Glossary( info=OrderedDict( [ ("y", "z"), ("a", "b"), ("1", "2"), ], ), ) self.assertEqual(list(glos.iterInfo()), [("y", "z"), ("a", "b"), ("1", "2")]) def test_lang_1(self): glos = self.glos = Glossary() self.assertEqual(glos.sourceLangName, "") self.assertEqual(glos.targetLangName, "") glos.sourceLangName = "ru" glos.targetLangName = "de" self.assertEqual(glos.sourceLangName, "Russian") self.assertEqual(glos.targetLangName, "German") def test_lang_get_source(self): glos = self.glos = Glossary() glos.setInfo("sourcelang", "farsi") self.assertEqual(glos.sourceLangName, "Persian") def test_lang_get_target(self): glos = self.glos = Glossary() glos.setInfo("targetlang", "malay") self.assertEqual(glos.targetLangName, "Malay") def test_lang_set_source(self): glos = self.glos = Glossary() glos.sourceLangName = "en" self.assertEqual(glos.sourceLangName, "English") def test_lang_set_source_empty(self): glos = self.glos = Glossary() glos.sourceLangName = "" self.assertEqual(glos.sourceLangName, "") def test_lang_set_target(self): glos = self.glos = Glossary() glos.targetLangName = "fa" self.assertEqual(glos.targetLangName, "Persian") def test_lang_set_target_empty(self): glos = self.glos = Glossary() glos.targetLangName = "" self.assertEqual(glos.targetLangName, "") def test_lang_getObj_source(self): glos = self.glos = Glossary() glos.setInfo("sourcelang", "farsi") self.assertEqual(glos.sourceLang.name, "Persian") def test_lang_getObj_target(self): glos = self.glos = Glossary() glos.setInfo("targetlang", "malay") self.assertEqual(glos.targetLang.name, "Malay") def test_lang_detect_1(self): glos = self.glos = Glossary() glos.setInfo("name", "en-fa") glos.detectLangsFromName() self.assertEqual( (glos.sourceLangName, glos.targetLangName), ("English", "Persian"), ) def test_lang_detect_2(self): glos = self.glos = Glossary() glos.setInfo("name", "test-en-fa") glos.detectLangsFromName() self.assertEqual( (glos.sourceLangName, glos.targetLangName), ("English", "Persian"), ) def test_lang_detect_3(self): glos = self.glos = Glossary() glos.setInfo("name", "eng to per") glos.detectLangsFromName() self.assertEqual( (glos.sourceLangName, glos.targetLangName), ("English", "Persian"), ) def test_lang_detect_4(self): glos = self.glos = Glossary() glos.setInfo("name", "Test english to farsi") glos.detectLangsFromName() self.assertEqual( (glos.sourceLangName, glos.targetLangName), ("English", "Persian"), ) def test_lang_detect_5(self): glos = self.glos = Glossary() glos.setInfo("name", "freedict-eng-deu.index") glos.detectLangsFromName() self.assertEqual( (glos.sourceLangName, glos.targetLangName), ("English", "German"), ) def convert_txt_txt( self, fname, # input txt file without extension fname2, # expected output txt file without extension testId="tmp", config=None, **convertArgs, ): self.convert( f"{fname}.txt", f"{fname2}-{testId}.txt", compareText=f"{fname2}.txt", testId=testId, config=config, **convertArgs, ) def convert_to_txtZip( self, fname, # input file with extension fname2, # expected output file without extensions testId="tmp", config=None, **convertKWArgs, ): inputFilename = self.downloadFile(fname) outputTxtName = f"{fname2}-{testId}.txt" outputFilename = self.newTempFilePath(f"{outputTxtName}.zip") expectedFilename = self.downloadFile(f"{fname2}.txt") glos = self.glos = Glossary() if config is not None: glos.config = config res = glos.convert( ConvertArgs( inputFilename=inputFilename, outputFilename=outputFilename, **convertKWArgs, ), ) self.assertEqual(outputFilename, res) zf = zipfile.ZipFile(outputFilename) self.assertTrue( outputTxtName in zf.namelist(), msg=f"{outputTxtName} not in {zf.namelist()}", ) with open(expectedFilename, encoding="utf-8") as expectedFile: expectedText = expectedFile.read() actualText = zf.read(outputTxtName).decode("utf-8") self.assertEqual(len(actualText), len(expectedText)) self.assertEqual(actualText, expectedText) def test_txt_txtZip_1(self): self.convert_to_txtZip( "100-en-fa.txt", "100-en-fa", testId="txt_txtZip_1", infoOverride={"input_file_size": None}, ) def test_sort_1(self): self.convert_txt_txt( "100-en-fa", "100-en-fa-sort", testId="sort_1", sort=True, ) def test_sort_2(self): self.convert_txt_txt( "100-en-fa", "100-en-fa-sort", testId="sort_2", sort=True, sortKeyName="headword_lower", ) def test_sort_3(self): self.convert_txt_txt( "100-en-fa", "100-en-fa-sort-headword", testId="sort_3", sort=True, sortKeyName="headword", ) def test_sort_4(self): self.convert_txt_txt( "300-rand-en-fa", "300-rand-en-fa-sort-headword", testId="sort_4", sort=True, sortKeyName="headword", ) def test_sort_5(self): self.convert_txt_txt( "300-rand-en-fa", "300-rand-en-fa-sort-headword-w1256", testId="sort_5", sort=True, sortKeyName="headword", sortEncoding="windows-1256", ) def test_sort_6(self): self.convert_txt_txt( "300-rand-en-fa", "300-rand-en-fa-sort-w1256", testId="sort_6", sort=True, sortKeyName="headword_lower", sortEncoding="windows-1256", ) def test_sort_7(self): self.convert_txt_txt( "100-en-fa", "100-en-fa-sort-ebook", testId="sort_7", sort=True, sortKeyName="ebook", ) def test_sort_8(self): self.convert_txt_txt( "100-en-fa", "100-en-fa-sort-ebook3", testId="sort_8", sort=True, sortKeyName="ebook_length3", ) def test_lower_1(self): self.convert_txt_txt( "100-en-fa", "100-en-fa-lower", testId="lower_1", config={"lower": True}, ) def test_rtl_1(self): self.convert_txt_txt( "100-en-fa", "100-en-fa-rtl", testId="rtl_1", config={"rtl": True}, ) def test_remove_html_all_1(self): self.convert_txt_txt( "100-en-fa", "100-en-fa-remove_html_all-v3", testId="remove_html_all_1", config={"remove_html_all": True}, ) def test_remove_html_1(self): self.convert_txt_txt( "100-en-de-v4", "100-en-de-v4-remove_font_b", testId="remove_html_1", config={"remove_html": "font,b"}, ) def test_save_info_json(self): fname = "100-en-fa" testId = "save_info_json" infoPath = self.newTempFilePath(f"{fname}-{testId}.info") self.convert_txt_txt( fname, fname, testId=testId, config={"save_info_json": True}, infoOverride={"input_file_size": None}, ) with open(infoPath, encoding="utf8") as _file: infoDict = json.load(_file) with open(self.downloadFile(f"{fname}-v2.info"), encoding="utf8") as _file: infoDictExpected = json.load(_file) for key, value in infoDictExpected.items(): self.assertIn(key, infoDict) self.assertEqual(value, infoDict.get(key)) def test_convert_sqlite_direct_error(self): glos = self.glos = Glossary() try: glos.convert( ConvertArgs( inputFilename="foo.txt", outputFilename="bar.txt", direct=True, sqlite=True, ), ) except ValueError as e: self.assertEqual(str(e), "Conflictng arguments: direct=True, sqlite=True") else: self.fail("must raise a ValueError") def test_txt_txt_bar(self): for direct in (None, False, True): self.convert_txt_txt( "004-bar", "004-bar", testId="bar", direct=direct, infoOverride={ "name": None, "input_file_size": None, }, ) def test_txt_txt_bar_sort(self): for sqlite in (None, False, True): self.convert_txt_txt( "004-bar", "004-bar-sort", testId="bar_sort", sort=True, sqlite=sqlite, ) def test_txt_txt_empty_filtered(self): for direct in (None, False, True): self.convert_txt_txt( "006-empty", "006-empty-filtered", testId="empty_filtered", direct=direct, ) def test_txt_txt_empty_filtered_sqlite(self): for sqlite in (None, False, True): self.convert_txt_txt( "006-empty", "006-empty-filtered", testId="empty_filtered_sqlite", sqlite=sqlite, ) def test_dataEntry_save(self): glos = self.glos = Glossary() tmpFname = "test_dataEntry_save" entry = glos.newDataEntry(tmpFname, b"test") saveFpath = entry.save(self.tempDir) self.assertTrue( isfile(saveFpath), msg=f"saved file does not exist: {saveFpath}", ) def test_dataEntry_getFileName(self): glos = self.glos = Glossary() tmpFname = "test_dataEntry_getFileName" entry = glos.newDataEntry(tmpFname, b"test") self.assertEqual(entry.getFileName(), tmpFname) def test_cleanup_noFile(self): glos = self.glos = Glossary() glos.cleanup() def test_cleanup_cleanup(self): glos = self.glos = Glossary() tmpFname = "test_cleanup_cleanup" entry = glos.newDataEntry(tmpFname, b"test") tmpFpath = entry._tmpPath self.assertTrue(bool(tmpFpath), msg="entry tmpPath is empty") self.assertTrue( isfile(tmpFpath), msg=f"tmp file does not exist: {tmpFpath}", ) glos.cleanup() self.assertTrue( not isfile(tmpFpath), msg=f"tmp file still exists: {tmpFpath}", ) def test_cleanup_noCleanup(self): glos = self.glos = Glossary() tmpFname = "test_cleanup_noCleanup" entry = glos.newDataEntry(tmpFname, b"test") tmpFpath = entry._tmpPath self.assertTrue(bool(tmpFpath), msg="entry tmpPath is empty") self.assertTrue(isfile(tmpFpath), msg=f"tmp file does not exist: {tmpFpath}") glos.config = {"cleanup": False} glos.cleanup() self.assertTrue(isfile(tmpFpath), msg=f"tmp file does not exist: {tmpFpath}") def test_rawEntryCompress(self): glos = self.glos = Glossary() glos.setRawEntryCompress(True) self.assertTrue(glos.rawEntryCompress) glos.setRawEntryCompress(False) self.assertFalse(glos.rawEntryCompress) def addWordsList(self, glos, words, newDefiFunc=str, defiFormat=""): wordsList = [] for index, line in enumerate(words): words = line.rstrip().split("|") wordsList.append(words) glos.addEntry( glos.newEntry( words, newDefiFunc(index), defiFormat=defiFormat, ), ) return wordsList def addWords(self, glos, wordsStr, **kwargs): return self.addWordsList(glos, wordsStr.split("\n"), **kwargs) tenWordsStr = """comedic tubenose organosol adipocere gid next friend bitter apple caca|ca-ca darkling beetle japonica""" tenWordsStr2 = """comedic Tubenose organosol Adipocere gid Next friend bitter apple Caca|ca-ca darkling beetle Japonica""" tenWordsStrFa = ( "بیمارانه\nگالوانومتر\nنقاهت\nرشک" "مندی\nناکاستنی\nشگفتآفرینی\nچندپاری\nنامبارکی\nآماسش\nانگیزنده" ) def test_addEntries_1(self): glos = self.glos = Glossary() wordsList = self.addWords( glos, self.tenWordsStr, newDefiFunc=lambda _i: str(random.randint(0, 10000)), ) self.assertEqual(wordsList, [entry.l_word for entry in glos]) def test_addEntries_2(self): # entry filters don't apply to loaded entries (added with addEntry) glos = self.glos = Glossary() glos.addEntry(glos.newEntry(["a"], "test 1")) glos.addEntry(glos.newEntry([""], "test 2")) glos.addEntry(glos.newEntry(["b"], "test 3")) glos.addEntry(glos.newEntry([], "test 4")) glos.updateEntryFilters() self.assertEqual( [["a"], [""], ["b"], []], [entry.l_word for entry in glos], ) def test_addEntries_3(self): glos = self.glos = Glossary() glos.addEntry(glos.newEntry(["a"], "test 1")) glos.addEntry(glos.newEntry(["b"], "test 3")) glos.addEntry( glos.newDataEntry( "file.bin", b"hello\x00world", ), ) glos.updateEntryFilters() wordListList = [] dataEntries = [] for entry in glos: wordListList.append(entry.l_word) if entry.isData(): dataEntries.append(entry) self.assertEqual( wordListList, [["a"], ["b"], ["file.bin"]], ) self.assertEqual(len(dataEntries), 1) self.assertEqual(dataEntries[0].getFileName(), "file.bin") self.assertEqual(dataEntries[0].data, b"hello\x00world") def test_read_filename(self): glos = self.glos = Glossary() glos.directRead(self.downloadFile("004-bar.txt")) self.assertEqual(glos.filename, join(testCacheDir, "004-bar")) def test_wordTitleStr_em1(self): glos = self.glos = Glossary() self.assertEqual(glos.wordTitleStr(""), "") def test_wordTitleStr_em2(self): glos = self.glos = Glossary() glos._defiHasWordTitle = True self.assertEqual(glos.wordTitleStr("test1"), "") def test_wordTitleStr_b1(self): glos = self.glos = Glossary() self.assertEqual(glos.wordTitleStr("test1"), "<b>test1</b><br>") def test_wordTitleStr_b2(self): glos = self.glos = Glossary() self.assertEqual( glos.wordTitleStr("test1", _class="headword"), '<b class="headword">test1</b><br>', ) def test_wordTitleStr_cjk1(self): glos = self.glos = Glossary() self.assertEqual( glos.wordTitleStr("test1", sample="くりかえし"), "<big>test1</big><br>", ) def test_wordTitleStr_cjk2(self): glos = self.glos = Glossary() self.assertEqual( glos.wordTitleStr("くりかえし"), "<big>くりかえし</big><br>", ) def test_convert_sortLocale_default_1(self): name = "092-en-fa-alphabet-sample" self.convert_sqlite_both( f"sort-locale/{name}.txt", f"{name}-sorted-default.txt", compareText=f"sort-locale/{name}-sorted-default.txt", testId="sorted-default", sort=True, sortKeyName="headword_lower", ) def test_convert_sortLocale_en_1(self): name = "092-en-fa-alphabet-sample" self.convert_sqlite_both( f"sort-locale/{name}.txt", f"{name}-sorted-en.txt", compareText=f"sort-locale/{name}-sorted-en.txt", testId="sorted-en", sort=True, sortKeyName="headword_lower:en_US.UTF-8", ) def test_convert_sortLocale_fa_1(self): name = "092-en-fa-alphabet-sample" self.convert_sqlite_both( f"sort-locale/{name}.txt", f"{name}-sorted-fa.txt", compareText=f"sort-locale/{name}-sorted-fa.txt", testId="sorted-fa", sort=True, sortKeyName="headword_lower:fa_IR.UTF-8", ) def test_convert_sortLocale_fa_2(self): name = "092-en-fa-alphabet-sample" self.convert_sqlite_both( f"sort-locale/{name}.txt", f"{name}-sorted-latin-fa.txt", compareText=f"sort-locale/{name}-sorted-latin-fa.txt", testId="sorted-latin-fa", sort=True, sortKeyName="headword_lower:fa-u-kr-latn-arab", ) if __name__ == "__main__": unittest.main()
27,259
Python
.py
905
26.601105
79
0.696841
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,703
g_babylon_bgl_test.py
ilius_pyglossary/tests/g_babylon_bgl_test.py
import unittest from os.path import join from glossary_v2_test import TestGlossaryBase class TestGlossaryBGL(TestGlossaryBase): def __init__(self, *args, **kwargs): TestGlossaryBase.__init__(self, *args, **kwargs) self.dataFileCRC32.update( { "Flavours_of_Malaysia.bgl": "46ef154b", "Flavours_of_Malaysia.txt_res/icon1.ico": "76a3b4c3", "Currency_In_Each_Country.bgl": "309f1b3f", "Solar_Physics_Glossary.bgl": "cc8f5ca1", "Farsi_Aviation_Dictionary.bgl": "efa7bee4", }, ) def convert_bgl_txt( self, fname, sha1sum=None, md5sum=None, resFiles=None, **convertArgs, ): if resFiles is None: resFiles = {} resFilesPath = { resName: self.newTempFilePath(join(f"{fname}-2.txt_res", resName)) for resName in resFiles } self.convert( f"{fname}.bgl", f"{fname}-2.txt", sha1sum=sha1sum, md5sum=md5sum, **convertArgs, ) for resName in resFiles: resPathActual = resFilesPath[resName] resPathExpected = self.downloadFile(f"{fname}.txt_res/{resName}") self.compareBinaryFiles(resPathActual, resPathExpected) def test_convert_bgl_txt_1(self): self.convert_bgl_txt( "Flavours_of_Malaysia", sha1sum="2b1fae135df2aaaeac23fb1dde497a4b6a22fd95", resFiles=["icon1.ico"], ) def test_convert_bgl_txt_2(self): self.convert_bgl_txt( "Currency_In_Each_Country", sha1sum="731147c72092d813dfe1ab35d420477478832443", ) def test_convert_bgl_txt_3(self): self.convert_bgl_txt( "Solar_Physics_Glossary", sha1sum="f30b392c748c4c5bfa52bf7f9945c574617ff74a", ) def test_convert_bgl_txt_4(self): self.convert_bgl_txt( "Farsi_Aviation_Dictionary", sha1sum="34729e2542085c6026090e9e3f49d10291393113", readOptions={ "process_html_in_key": True, }, ) if __name__ == "__main__": unittest.main()
1,817
Python
.py
66
24.060606
69
0.722094
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,704
py-to-stardict.py
ilius_pyglossary/doc/lib-examples/py-to-stardict.py
from pyglossary.glossary import Glossary Glossary.init() glos = Glossary() defiFormat = "m" # "m" for plain text, "h" for HTML mydict = { "a": "test1", "b": "test2", "c": "test3", "d": "test4", "e": "test5", "f": "test6", } for word, defi in mydict.items(): glos.addEntryObj(glos.newEntry(word, defi, defiFormat=defiFormat)) glos.setInfo("title", "My Test StarDict") glos.setInfo("author", "John Doe") glos.write("test.ifo", format="Stardict")
457
Python
.py
18
23.666667
67
0.685912
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,705
any_to_txt.py
ilius_pyglossary/doc/lib-examples/any_to_txt.py
#!/usr/bin/env python3 import sys from pyglossary import Glossary # Glossary.init() must be called only once, so make sure you put it # in the right place Glossary.init() glos = Glossary() glos.convert( inputFilename=sys.argv[1], outputFilename=f"{sys.argv[1]}.txt", # although it can detect format for *.txt, you can still pass outputFormat outputFormat="Tabfile", # you can pass readOptions or writeOptions as a dict # writeOptions={"encoding": "utf-8"}, )
469
Python
.py
15
29.6
75
0.762222
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,706
oxford.py
ilius_pyglossary/doc/lib-examples/oxford.py
from pyglossary import Glossary def takePhonetic_oxford_gb(glos): phonGlos = Glossary() # phonetic glossary phonGlos.setInfo("name", glos.getInfo("name") + "_phonetic") for entry in glos: word = entry.s_word defi = entry.defi if not defi.startswith("/"): continue # Now set the phonetic to the `ph` variable. ph = "" for s in ( "/ adj", "/ v", "/ n", "/ adv", "/adj", "/v", "/n", "/adv", "/ n", "/ the", ): i = defi.find(s, 2, 85) if i == -1: continue ph = defi[: i + 1] break ph = ( ph.replace(";", "\t") .replace(",", "\t") .replace(" ", "\t") .replace(" ", "\t") .replace(" ", "\t") .replace("//", "/") .replace("\t/\t", "\t") .replace("<i>US</i>\t", "\tUS: ") .replace("<i>US</i>", "\tUS: ") .replace("\t\t\t", "\t") .replace("\t\t", "\t") ) # .replace("/", "") # .replace("\\n ", "\\n") # .replace("\\n ", "\\n") if ph: phonGlos.addEntryObj(phonGlos.newEntry(word, ph)) return phonGlos
1,020
Python
.py
47
18.212766
61
0.504634
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,707
sort_keys.py
ilius_pyglossary/pyglossary/sort_keys.py
# -*- coding: utf-8 -*- # # Copyright © 2022 Saeed Rasooli <saeed.gnu@gmail.com> (ilius) # This file is part of PyGlossary project, https://github.com/ilius/pyglossary # # This program is a free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program. Or on Debian systems, from /usr/share/common-licenses/GPL # If not, see <http://www.gnu.org/licenses/gpl.txt>. from __future__ import annotations from dataclasses import dataclass from typing import TYPE_CHECKING, Any, NamedTuple if TYPE_CHECKING: from collections.abc import Callable from .icu_types import T_Collator, T_Locale from .sort_keys_type import SortKeyType, SQLiteSortKeyType __all__ = [ "LocaleNamedSortKey", "NamedSortKey", "defaultSortKeyName", "lookupSortKey", "namedSortKeyList", ] defaultSortKeyName = "headword_lower" class NamedSortKey(NamedTuple): name: str desc: str normal: SortKeyType sqlite: SQLiteSortKeyType @dataclass(slots=True) # not frozen because of mod class LocaleNamedSortKey: name: str desc: str mod: Any = None @property def module(self): # noqa: ANN201 if self.mod is not None: return self.mod mod = __import__( f"pyglossary.sort_modules.{self.name}", fromlist=self.name, ) self.mod = mod return mod @property def normal(self) -> SortKeyType: return self.module.normal @property def sqlite(self) -> SQLiteSortKeyType: return self.module.sqlite @property def locale(self) -> SortKeyType | None: return getattr(self.module, "locale", None) @property def sqlite_locale(self) -> Callable[..., SQLiteSortKeyType] | None: return getattr(self.module, "sqlite_locale", None) namedSortKeyList = [ LocaleNamedSortKey( name="headword", desc="Headword", ), LocaleNamedSortKey( name="headword_lower", desc="Lowercase Headword", ), LocaleNamedSortKey( name="headword_bytes_lower", desc="ASCII-Lowercase Headword", ), LocaleNamedSortKey( name="stardict", desc="StarDict", ), LocaleNamedSortKey( name="ebook", desc="E-Book (prefix length: 2)", ), LocaleNamedSortKey( name="ebook_length3", desc="E-Book (prefix length: 3)", ), LocaleNamedSortKey( name="dicformids", desc="DictionaryForMIDs", ), LocaleNamedSortKey( name="random", desc="Random", ), ] _sortKeyByName = {item.name: item for item in namedSortKeyList} def lookupSortKey(sortKeyId: str) -> NamedSortKey | None: localeName: "str | None" = None parts = sortKeyId.split(":") if len(parts) == 1: (sortKeyName,) = parts elif len(parts) == 2: sortKeyName, localeName = parts else: raise ValueError(f"invalid {sortKeyId = }") if not sortKeyName: sortKeyName = defaultSortKeyName localeSK = _sortKeyByName.get(sortKeyName) if localeSK is None: return None if not localeName: return NamedSortKey( name=localeSK.name, desc=localeSK.desc, normal=localeSK.normal, sqlite=localeSK.sqlite, ) from icu import Collator, Locale # type: ignore localeObj: "T_Locale" = Locale(localeName) localeNameFull = localeObj.getName() collator: "T_Collator" = Collator.createInstance(localeObj) return NamedSortKey( name=f"{localeSK.name}:{localeNameFull}", desc=f"{localeSK.desc}:{localeNameFull}", normal=localeSK.locale(collator) if localeSK.locale else None, sqlite=localeSK.sqlite_locale(collator) if localeSK.sqlite_locale else None, ) # https://en.wikipedia.org/wiki/UTF-8#Comparison_with_other_encodings # Sorting order: The chosen values of the leading bytes means that a list # of UTF-8 strings can be sorted in code point order by sorting the # corresponding byte sequences.
4,065
Python
.py
135
27.8
78
0.759867
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,708
core_test.py
ilius_pyglossary/pyglossary/core_test.py
from __future__ import annotations import logging __all__ = [ "MockLogHandler", "getMockLogger", ] class MockLogHandler(logging.Handler): def __init__(self) -> None: logging.Handler.__init__(self) self.clear() def clear(self) -> None: self.recordsByLevel: dict[int, list[logging.LogRecord]] = {} def emit(self, record: logging.LogRecord) -> None: level = record.levelno if level in self.recordsByLevel: self.recordsByLevel[level].append(record) else: self.recordsByLevel[level] = [record] def popLog(self, level: int, msg: str, partial=False) -> logging.LogRecord | None: if level not in self.recordsByLevel: return None records = self.recordsByLevel[level] for index, record in list(enumerate(records)): rec_msg = record.getMessage() if msg == rec_msg or (msg in rec_msg and partial): return records.pop(index) return None def printRemainingLogs(self, level, method: str = "") -> int: if level not in self.recordsByLevel: return 0 count = 0 for record in self.recordsByLevel[level]: count += 1 msg = self.format(record) print(f"{method}: {msg!r}") return count def printRemainingErrors(self, method: str = "") -> int: count = self.printRemainingLogs(logging.CRITICAL, method) count += self.printRemainingLogs(logging.ERROR, method) return count def printRemainingwWarnings(self, method: str = "") -> int: return self.printRemainingLogs(logging.WARNING, method) mockLog = None def getMockLogger(): global mockLog if mockLog is not None: return mockLog log = logging.getLogger("pyglossary") for handler in log.handlers: log.removeHandler(handler) mockLog = MockLogHandler() mockLog.setLevel(logging.WARNING) log.addHandler(mockLog) return mockLog
1,752
Python
.py
54
29.481481
83
0.741071
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,709
lxml_types.py
ilius_pyglossary/pyglossary/lxml_types.py
# -*- coding: utf-8 -*- # # Copyright © 2023 Saeed Rasooli <saeed.gnu@gmail.com> (ilius) # # based on https://github.com/abelcheung/types-lxml # under Apache License, Version 2.0, January 2004 # http://www.apache.org/licenses/ from __future__ import annotations import typing from collections.abc import Mapping # noqa: TCH003 from contextlib import ( AbstractAsyncContextManager as AsyncContextManager, ) from contextlib import ( AbstractContextManager as ContextManager, ) from typing import ( AnyStr, Literal, TypeAlias, ) from lxml.etree import QName, _Element # noqa: PLC2701 __all__ = ["Element", "T_htmlfile"] _TextArg: TypeAlias = "str | bytes | QName" _TagName: TypeAlias = _TextArg _OutputMethodArg = Literal[ "html", "text", "xml", "HTML", "TEXT", "XML", ] # Element type can not be a protocol or interface or even TypeAlias # it's stupid! Element = _Element class IncrementalFileWriter(typing.Protocol): def write_declaration( self, version: AnyStr | None = ..., standalone: bool | None = ..., doctype: AnyStr | None = ..., ) -> None: ... def write_doctype( self, doctype: AnyStr | None, ) -> None: ... def write( self, *args: AnyStr | Element, with_tail: bool = ..., pretty_print: bool = ..., method: _OutputMethodArg | None = ..., ) -> None: ... def flush(self) -> None: ... def method( self, method: _OutputMethodArg | None, ) -> ContextManager[None]: raise NotImplementedError def element( self, tag: _TagName, attrib: Mapping[str, AnyStr] | None = ..., nsmap: dict[str | None, AnyStr] | None = ..., method: _OutputMethodArg | None = ..., **_extra: AnyStr, ) -> ContextManager[None]: raise NotImplementedError class AsyncIncrementalFileWriter(typing.Protocol): async def write_declaration( self, version: AnyStr | None = ..., standalone: bool | None = ..., doctype: AnyStr | None = ..., ) -> None: ... async def write_doctype( self, doctype: AnyStr | None, ) -> None: ... async def write( self, *args: AnyStr | Element | None, with_tail: bool = ..., pretty_print: bool = ..., method: _OutputMethodArg | None = ..., ) -> None: ... async def flush(self) -> None: ... def method( self, method: _OutputMethodArg | None, ) -> AsyncContextManager[None]: raise NotImplementedError def element( self, tag: _TagName, attrib: Mapping[str, AnyStr] | None = ..., nsmap: dict[str | None, AnyStr] | None = ..., method: _OutputMethodArg | None = ..., **_extra: AnyStr, ) -> AsyncContextManager[None]: raise NotImplementedError class T_htmlfile( # type: ignore # noqa: PGH003 IncrementalFileWriter, ContextManager[IncrementalFileWriter], # AsyncIncrementalFileWriter, # AsyncContextManager[AsyncIncrementalFileWriter], ): pass # typing.AsyncContextManager # is generic version of contextlib.AbstractAsyncContextManager
2,872
Python
.py
111
23.531532
67
0.698244
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,710
icu_types.py
ilius_pyglossary/pyglossary/icu_types.py
from __future__ import annotations import typing from collections.abc import Callable from typing import AnyStr __all__ = ["T_Collator", "T_Locale"] class T_Locale(typing.Protocol): def __init__(self, _id: str) -> None: pass def getName(self) -> str: pass class T_Collator(typing.Protocol): PRIMARY: int = 0 SECONDARY: int = 1 TERTIARY: int = 2 QUATERNARY: int = 3 IDENTICAL: int = 15 # mypy: error: Self argument missing for a non-static method # (or an invalid type for self) [misc] @classmethod def createInstance(cls: "T_Locale | None" = None) -> T_Collator: # type: ignore pass @property def getSortKey(self) -> Callable[[AnyStr], bytes]: pass def setStrength(self, strength: int) -> None: pass def setAttribute(self, attr: int, value: int) -> None: pass class T_UCollAttribute(typing.Protocol): ALTERNATE_HANDLING: int = 1 CASE_FIRST: int = 2 CASE_LEVEL: int = 3 DECOMPOSITION_MODE: int = 4 FRENCH_COLLATION: int = 0 HIRAGANA_QUATERNARY_MODE: int = 6 NORMALIZATION_MODE: int = 4 NUMERIC_COLLATION: int = 7 STRENGTH: int = 5 class T_UCollAttributeValue(typing.Protocol): DEFAULT: int = -1 DEFAULT_STRENGTH: int = 2 IDENTICAL: int = 15 LOWER_FIRST: int = 24 NON_IGNORABLE: int = 21 OFF: int = 16 ON: int = 17 PRIMARY: int = 0 QUATERNARY: int = 3 SECONDARY: int = 1 SHIFTED: int = 20 TERTIARY: int = 2 UPPER_FIRST: int = 25
1,393
Python
.py
52
24.557692
81
0.717195
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,711
entry_filters.py
ilius_pyglossary/pyglossary/entry_filters.py
# -*- coding: utf-8 -*- from __future__ import annotations import logging import re import typing from typing import TYPE_CHECKING from . import core from .text_utils import ( fixUtf8, ) if TYPE_CHECKING: from .glossary_types import Callable, EntryType, GlossaryExtendedType, GlossaryType __all__ = [ "EntryFilterType", "PreventDuplicateWords", "RemoveHtmlTagsAll", "ShowMaxMemoryUsage", "ShowProgressBar", "StripFullHtml", "entryFiltersRules", ] log = logging.getLogger("pyglossary") class EntryFilterType(typing.Protocol): name: str = "" desc: str = "" falseComment: str = "" def __init__(self, glos: GlossaryType) -> None: raise NotImplementedError def prepare(self) -> None: raise NotImplementedError def run(self, entry: EntryType) -> EntryType | None: raise NotImplementedError class EntryFilter: name: str = "" desc: str = "" falseComment: str = "" def __init__(self, glos: GlossaryType) -> None: self.glos = glos def prepare(self) -> None: """Run this after glossary info is set and ready.""" def run(self, entry: EntryType) -> EntryType | None: # noqa: PLR6301 """ Return an Entry object, or None to skip. may return the same `entry`, or modify and return it, or return a new Entry object. """ return entry class TrimWhitespaces(EntryFilter): name = "trim_whitespaces" desc = "Remove leading/trailing whitespaces from word(s) and definition" def run(self, entry: EntryType) -> EntryType | None: # noqa: PLR6301 entry.strip() entry.replace("\r", "") return entry class NonEmptyWordFilter(EntryFilter): name = "non_empty_word" desc = "Skip entries with empty word" def run(self, entry: EntryType) -> EntryType | None: # noqa: PLR6301 if not entry.s_word: return None return entry class NonEmptyDefiFilter(EntryFilter): name = "non_empty_defi" desc = "Skip entries with empty definition" def run(self, entry: EntryType) -> EntryType | None: # noqa: PLR6301 if not entry.defi: return None return entry class RemoveEmptyAndDuplicateAltWords(EntryFilter): name = "remove_empty_dup_alt_words" desc = "Remove empty and duplicate alternate words" def run(self, entry: EntryType) -> EntryType | None: # noqa: PLR6301 entry.removeEmptyAndDuplicateAltWords() if not entry.l_word: return None return entry class FixUnicode(EntryFilter): name = "utf8_check" desc = "Fix Unicode in word(s) and definition" falseComment = "Do not fix Unicode in word(s) and definition" def run(self, entry: EntryType) -> EntryType | None: # noqa: PLR6301 entry.editFuncWord(fixUtf8) entry.editFuncDefi(fixUtf8) return entry class LowerWord(EntryFilter): name = "lower" desc = "Lowercase word(s)" falseComment = "Do not lowercase words before writing" def __init__(self, glos: GlossaryType) -> None: EntryFilter.__init__(self, glos) self._re_word_ref = re.compile("href=[\"'](bword://[^\"']+)[\"']") def lowerWordRefs(self, defi: str) -> str: return self._re_word_ref.sub( lambda m: m.group(0).lower(), defi, ) def run(self, entry: EntryType) -> EntryType | None: entry.editFuncWord(str.lower) entry.editFuncDefi(self.lowerWordRefs) return entry class RTLDefi(EntryFilter): name = "rtl" desc = "Make definition right-to-left" def run(self, entry: EntryType) -> EntryType | None: # noqa: PLR6301 entry.editFuncDefi(lambda defi: f'<div dir="rtl">{defi}</div>') return entry class RemoveHtmlTagsAll(EntryFilter): name = "remove_html_all" desc = "Remove all HTML tags (not their contents) from definition" def __init__( self, glos: GlossaryType, # noqa: ARG002 ) -> None: self._p_pattern = re.compile( "<p( [^<>]*?)?>(.*?)</p>", re.DOTALL, ) self._div_pattern = re.compile( "<div( [^<>]*?)?>(.*?)</div>", re.DOTALL, ) self._br_pattern = re.compile( "<br[ /]*>", re.IGNORECASE, ) def run(self, entry: EntryType) -> EntryType | None: from bs4 import BeautifulSoup def fixStr(st: str) -> str: st = self._p_pattern.sub("\\2\n", st) # if there is </p> left without opening, replace with <br> st = st.replace("</p>", "\n") st = self._div_pattern.sub("\\2\n", st) # if there is </div> left without opening, replace with <br> st = st.replace("</div>", "\n") st = self._br_pattern.sub("\n", st) st = BeautifulSoup(st, "lxml").text st = st.strip() return st # noqa: RET504 entry.editFuncDefi(fixStr) return entry class RemoveHtmlTags(EntryFilter): name = "remove_html" desc = "Remove given comma-separated HTML tags (not their contents) from definition" def __init__(self, glos: GlossaryType, tagsStr: str) -> None: tags = tagsStr.split(",") self.glos = glos self.tags = tags tagsRE = "|".join(self.tags) self.pattern = re.compile(f"</?({tagsRE})( [^>]*)?>") def run(self, entry: EntryType) -> EntryType | None: def fixStr(st: str) -> str: return self.pattern.sub("", st) entry.editFuncDefi(fixStr) return entry class StripFullHtml(EntryFilter): name = "strip_full_html" desc = "Replace a full HTML document with it's body" def __init__( self, glos: GlossaryType, # noqa: ARG002 errorHandler: "Callable[[EntryType, str], None] | None", ) -> None: self._errorHandler = errorHandler def run(self, entry: EntryType) -> EntryType | None: err = entry.stripFullHtml() if err and self._errorHandler: self._errorHandler(entry, err) return entry # FIXME: It's is not safe to lowercases everything between < and > # including class name, element ids/names, scripts, <a href="bword://..."> # etc. How can we fix that? class NormalizeHtml(EntryFilter): name = "normalize_html" desc = "Normalize HTML tags in definition (WIP)" _tags = ( "a", "font", "i", "b", "u", "p", "sup", "div", "span", "table", "tr", "th", "td", "ul", "ol", "li", "img", "br", "hr", ) def __init__( self, glos: GlossaryType, # noqa: ARG002 ) -> None: log.info("Normalizing HTML tags") self._pattern = re.compile( "(" + "|".join(rf"</?{tag}[^<>]*?>" for tag in self._tags) + ")", re.DOTALL | re.IGNORECASE, ) @staticmethod def _subLower(m: "re.Match") -> str: return m.group(0).lower() def _fixDefi(self, st: str) -> str: return self._pattern.sub(self._subLower, st) def run(self, entry: EntryType) -> EntryType | None: entry.editFuncDefi(self._fixDefi) return entry class SkipDataEntry(EntryFilter): name = "skip_resources" desc = "Skip resources / data files" def run(self, entry: EntryType) -> EntryType | None: # noqa: PLR6301 if entry.isData(): return None return entry class LanguageCleanup(EntryFilter): name = "lang" desc = "Language-specific cleanup/fixes" def __init__(self, glos: GlossaryType) -> None: EntryFilter.__init__(self, glos) self._run_func: "Callable[[EntryType], EntryType | None] | None" = None def prepare(self) -> None: langCodes = { lang.code for lang in (self.glos.sourceLang, self.glos.targetLang) if lang is not None } if "fa" in langCodes: self._run_func = self.run_fa log.info("Using Persian filter") def run_fa(self, entry: EntryType) -> EntryType | None: # noqa: PLR6301 from .persian_utils import faEditStr entry.editFuncWord(faEditStr) entry.editFuncDefi(faEditStr) # RLM = "\xe2\x80\x8f" # defi = "\n".join(RLM+line for line in defi.split("\n")) # for GoldenDict ^^ FIXME return entry def run(self, entry: EntryType) -> EntryType | None: if self._run_func: return self._run_func(entry) return entry class TextListSymbolCleanup(EntryFilter): """ Symbols like ♦ (diamond) ● (black circle) or * (star) are used in some plaintext or even html glossaries to represent items of a list (like <li> in proper html). This EntryFilter cleans up spaces/newlines issues around them. """ name = "text_list_symbol_cleanup" desc = "Text List Symbol Cleanup" winNewlinePattern = re.compile("[\r\n]+") spacesNewlinePattern = re.compile(" *\n *") blocksNewlinePattern = re.compile("♦\n+♦") def cleanDefi(self, st: str) -> str: st = st.replace("♦ ", "♦ ") st = self.winNewlinePattern.sub("\n", st) st = self.spacesNewlinePattern.sub("\n", st) st = self.blocksNewlinePattern.sub("♦", st) st = st.removesuffix("<p") st = st.strip() st = st.removesuffix(",") return st # noqa: RET504 def run(self, entry: EntryType) -> EntryType | None: entry.editFuncDefi(self.cleanDefi) return entry class PreventDuplicateWords(EntryFilter): name = "prevent_duplicate_words" desc = "Prevent duplicate words" def __init__(self, glos: GlossaryType) -> None: EntryFilter.__init__(self, glos) self._wordSet: set[str] = set() def run(self, entry: EntryType) -> EntryType | None: if entry.isData(): return entry wordSet = self._wordSet word = entry.s_word if word not in wordSet: wordSet.add(word) return entry n = 2 while f"{word} ({n})" in wordSet: n += 1 word = f"{word} ({n})" wordSet.add(word) entry._word = word # type: ignore # use entry.editFuncWord? return entry class SkipEntriesWithDuplicateHeadword(EntryFilter): name = "skip_duplicate_headword" desc = "Skip entries with a duplicate headword" def __init__(self, glos: GlossaryType) -> None: EntryFilter.__init__(self, glos) self._wset: set[str] = set() def run(self, entry: EntryType) -> EntryType | None: word = entry.l_word[0] if word in self._wset: return None self._wset.add(word) return entry class TrimArabicDiacritics(EntryFilter): name = "trim_arabic_diacritics" desc = "Trim Arabic diacritics from headword" def __init__(self, glos: GlossaryType) -> None: EntryFilter.__init__(self, glos) self._pat = re.compile("[\u064b-\u065f]") def run(self, entry: EntryType) -> EntryType | None: words = list(entry.l_word) hw = words[0] hw_t = self._pat.sub("", hw) hw_t = hw_t.replace("\u0622", "\u0627").replace("\u0623", "\u0627") if hw_t == hw or not hw_t: return entry entry._word = [hw_t, *words] # type: ignore return entry class UnescapeWordLinks(EntryFilter): name = "unescape_word_links" desc = "Unescape Word Links" def __init__(self, glos: GlossaryType) -> None: from pyglossary.html_utils import unescape_unicode EntryFilter.__init__(self, glos) self._pat = re.compile( r'href="bword://[^<>"]*&#?\w+;[^<>"]*"', re.IGNORECASE, ) self._unescape = unescape_unicode def _sub(self, m: "re.Match") -> str: return self._unescape(m.group(0)) def run(self, entry: EntryType) -> EntryType | None: if entry.isData(): return entry entry._defi = self._pat.sub(self._sub, entry.defi) # type: ignore return entry class ShowProgressBar(EntryFilter): name = "progressbar" desc = "Progress Bar" def __init__(self, glos: GlossaryExtendedType) -> None: EntryFilter.__init__(self, glos) self.glos: GlossaryExtendedType = glos self._wordCount = -1 self._wordCountThreshold = 0 self._lastPos = 0 self._index = 0 def run(self, entry: EntryType) -> EntryType | None: index = self._index self._index = index + 1 if entry is not None and (bp := entry.byteProgress()): if bp[0] > self._lastPos + 100_000: self.glos.progress(bp[0], bp[1], unit="bytes") self._lastPos = bp[0] return entry if self._wordCount == -1: self._wordCount = len(self.glos) self._wordCountThreshold = max( 1, min( 500, self._wordCount // 200, ), ) if self._wordCount > 1 and index % self._wordCountThreshold == 0: self.glos.progress(index, self._wordCount) return entry class ShowMaxMemoryUsage(EntryFilter): name = "max_memory_usage" desc = "Show Max Memory Usage" MAX_WORD_LEN = 30 def __init__(self, glos: GlossaryType) -> None: import os import psutil EntryFilter.__init__(self, glos) self._process = psutil.Process(os.getpid()) self._max_mem_usage = 0 def run(self, entry: EntryType) -> EntryType | None: usage = self._process.memory_info().rss // 1024 if usage > self._max_mem_usage: self._max_mem_usage = usage word = entry.s_word if len(word) > self.MAX_WORD_LEN: word = word[: self.MAX_WORD_LEN - 3] + "..." core.trace(log, f"MaxMemUsage: {usage:,}, {word=}") return entry entryFiltersRules = [ (None, True, TrimWhitespaces), (None, True, NonEmptyWordFilter), ("skip_resources", False, SkipDataEntry), ("utf8_check", False, FixUnicode), ("lower", False, LowerWord), ("skip_duplicate_headword", False, SkipEntriesWithDuplicateHeadword), ("trim_arabic_diacritics", False, TrimArabicDiacritics), ("rtl", False, RTLDefi), ("remove_html_all", False, RemoveHtmlTagsAll), ("remove_html", "", RemoveHtmlTags), ("normalize_html", False, NormalizeHtml), ("unescape_word_links", False, UnescapeWordLinks), (None, True, LanguageCleanup), # ------------------------------------- # TODO # ("text_list_symbol_cleanup", False, TextListSymbolCleanup), # ------------------------------------- (None, True, NonEmptyWordFilter), (None, True, NonEmptyDefiFilter), (None, True, RemoveEmptyAndDuplicateAltWords), # ------------------------------------- # filters that are enabled by plugins using glossary methods: (None, False, PreventDuplicateWords), (None, False, StripFullHtml), # ------------------------------------- # filters are added conditionally (other than with config or glossary methods): (None, False, ShowProgressBar), (None, False, ShowMaxMemoryUsage), ]
13,420
Python
.py
417
29.230216
85
0.684206
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,712
gregorian.py
ilius_pyglossary/pyglossary/gregorian.py
# -*- coding: utf-8 -*- # # Copyright © 2008-2019 Saeed Rasooli <saeed.gnu@gmail.com> # Copyright © 2007 Mehdi Bayazee <Bayazee@Gmail.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program. If not, see <http://www.gnu.org/licenses/gpl.txt>. # Also available in /usr/share/common-licenses/GPL on Debian systems # or /usr/share/licenses/common/GPL3/license.txt on ArchLinux # Gregorian calendar: # http://en.wikipedia.org/wiki/Gregorian_calendar from __future__ import annotations from datetime import datetime __all__ = ["isLeap", "jd_to", "to_jd"] name = "gregorian" desc = "Gregorian" epoch = 1721426 options = () def save() -> None: pass def isLeap(y: int) -> bool: return y % 4 == 0 and not (y % 100 == 0 and y % 400 != 0) def to_jd(year: int, month: int, day: int) -> int: if 0 < year < 10000: # > 1.5x faster # noqa: PLR2004 return datetime(year, month, day).toordinal() + 1721425 if month <= 2: # noqa: PLR2004 tm = 0 elif isLeap(year): tm = -1 else: tm = -2 return ( epoch - 1 + 365 * (year - 1) + (year - 1) // 4 + -((year - 1) // 100) + (year - 1) // 400 + (367 * month - 362) // 12 + tm + day ) def jd_to(jd: int) -> tuple[int, int, int]: ordinal = jd - 1721425 if 0 < ordinal < 3652060: # > 4x faster # noqa: PLR2004 # datetime(9999, 12, 31).toordinal() == 3652059 dt = datetime.fromordinal(ordinal) return (dt.year, dt.month, dt.day) # wjd = floor(jd - 0.5) + 0.5 qc, dqc = divmod(jd - epoch, 146097) # qc ~~ quadricent cent, dcent = divmod(dqc, 36524) quad, dquad = divmod(dcent, 1461) yindex = dquad // 365 # divmod(dquad, 365)[0] year = ( qc * 400 + cent * 100 + quad * 4 + yindex + (cent != 4 and yindex != 4) # noqa: PLR2004 ) yearday = jd - to_jd(year, 1, 1) if jd < to_jd(year, 3, 1): leapadj = 0 elif isLeap(year): leapadj = 1 else: leapadj = 2 month = ((yearday + leapadj) * 12 + 373) // 367 day = jd - to_jd(year, month, 1) + 1 return year, month, day
2,513
Python
.py
79
29.632911
73
0.669432
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,713
glossary_progress.py
ilius_pyglossary/pyglossary/glossary_progress.py
from __future__ import annotations from typing import TYPE_CHECKING from .core import log if TYPE_CHECKING: from .ui_type import UIType __all__ = ["GlossaryProgress"] class GlossaryProgress: def __init__( self, ui: UIType | None = None, # noqa: F821 ) -> None: self._ui = ui self._progressbar = True def clear(self) -> None: self._progressbar = True @property def progressbar(self) -> bool: return self._ui is not None and self._progressbar @progressbar.setter def progressbar(self, enabled: bool) -> None: self._progressbar = enabled def progressInit( self, *args, # noqa: ANN003 ) -> None: if self._ui and self._progressbar: self._ui.progressInit(*args) def progress(self, pos: int, total: int, unit: str = "entries") -> None: if total == 0: log.warning(f"{pos=}, {total=}") return if self._ui is None: return self._ui.progress( min(pos + 1, total) / total, f"{pos:,} / {total:,} {unit}", ) def progressEnd(self) -> None: if self._ui and self._progressbar: self._ui.progressEnd()
1,059
Python
.py
40
23.6
73
0.679245
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,714
io_utils.py
ilius_pyglossary/pyglossary/io_utils.py
from __future__ import annotations import io from typing import TYPE_CHECKING if TYPE_CHECKING: from collections.abc import Iterator __all__ = ["nullBinaryIO", "nullTextIO"] class _NullBinaryIO(io.BufferedIOBase): # noqa: PLR0904 def __enter__(self, *args): raise NotImplementedError def __exit__(self, *args): raise NotImplementedError def close(self) -> None: pass def fileno(self) -> int: raise NotImplementedError def flush(self) -> None: raise NotImplementedError def isatty(self) -> bool: raise NotImplementedError def readable(self) -> bool: raise NotImplementedError def seek(self, pos: int, whence: int = 0) -> int: raise NotImplementedError def seekable(self) -> bool: raise NotImplementedError def tell(self) -> int: raise NotImplementedError def truncate(self, pos: "int | None" = None) -> int: raise NotImplementedError def writable(self) -> bool: raise NotImplementedError def detach(self) -> io.RawIOBase: raise NotImplementedError def read(self, n: "int | None" = None) -> bytes: raise NotImplementedError def read1(self, n: "int | None" = None) -> bytes: raise NotImplementedError def readinto(self, buffer) -> int: raise NotImplementedError def readinto1(self, buffer) -> int: raise NotImplementedError # data: "bytearray|memoryview|array[Any]|io.mmap|io._CData|io.PickleBuffer" def write(self, data: bytes) -> int: # type: ignore raise NotImplementedError def __iter__(self) -> Iterator[bytes]: raise NotImplementedError def __next__(self) -> bytes: raise NotImplementedError def readline(self, size: "int | None" = -1) -> bytes: raise NotImplementedError def readlines(self, hint: int = -1) -> list[bytes]: raise NotImplementedError def writelines(self, lines: list[bytes]) -> None: # type: ignore raise NotImplementedError class _NullTextIO(io.TextIOBase): # noqa: PLR0904 def __enter__(self, *args): raise NotImplementedError def __exit__(self, *args): raise NotImplementedError def close(self) -> None: pass def fileno(self) -> int: raise NotImplementedError def flush(self) -> None: raise NotImplementedError def isatty(self) -> bool: raise NotImplementedError def readable(self) -> bool: raise NotImplementedError def seek(self, pos: int, whence: int = 0) -> int: raise NotImplementedError def seekable(self) -> bool: raise NotImplementedError def tell(self) -> int: raise NotImplementedError def truncate(self, pos: "int | None" = None) -> int: raise NotImplementedError def writable(self) -> bool: raise NotImplementedError def detach(self) -> io.IOBase: # type: ignore raise NotImplementedError def read(self, n: "int | None" = None) -> str: raise NotImplementedError def read1(self, n: "int | None" = None) -> str: raise NotImplementedError def readinto(self, buffer) -> io.BufferedIOBase: raise NotImplementedError def readinto1(self, buffer) -> io.BufferedIOBase: raise NotImplementedError # data: "bytearray|memoryview|array[Any]|io.mmap|io._CData|io.PickleBuffer" def write(self, data: bytes) -> int: # type: ignore raise NotImplementedError def __iter__(self) -> Iterator[str]: # type: ignore raise NotImplementedError def __next__(self) -> str: # type: ignore raise NotImplementedError def readline(self, size: "int | None" = -1) -> str: # type: ignore raise NotImplementedError def readlines(self, hint: int = -1) -> list[str]: # type: ignore raise NotImplementedError def writelines(self, lines: list[str]) -> None: # type: ignore raise NotImplementedError nullBinaryIO = _NullBinaryIO() nullTextIO = _NullTextIO()
3,657
Python
.py
104
32.298077
76
0.738571
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,715
reverse.py
ilius_pyglossary/pyglossary/reverse.py
from __future__ import annotations import logging import re from operator import itemgetter from typing import TYPE_CHECKING, Iterable, Iterator if TYPE_CHECKING: from .glossary_types import EntryType, GlossaryExtendedType __all__ = ["reverseGlossary"] log = logging.getLogger("pyglossary") def reverseGlossary( glos: GlossaryExtendedType, savePath: str = "", words: "list[str] | None" = None, includeDefs: bool = False, reportStep: int = 300, saveStep: int = 1000, # set this to zero to disable auto saving **kwargs, ) -> Iterator[int]: """ This is a generator Usage: for wordIndex in glos.reverse(...): pass Inside the `for` loop, you can pause by waiting (for input or a flag) or stop by breaking Potential keyword arguments: words = None ## None, or list reportStep = 300 saveStep = 1000 savePath = "" matchWord = True sepChars = ".,،" maxNum = 100 minRel = 0.0 minWordLen = 3 includeDefs = False showRel = "None" allowed values: None, "Percent", "Percent At First" """ if not savePath: savePath = glos.getInfo("name") + ".txt" if saveStep < 2: raise ValueError("saveStep must be more than 1") entries: list[EntryType] = list(glos) log.info(f"loaded {len(entries)} entries into memory") if words: words = list(words) else: words = takeOutputWords(glos, entries) wordCount = len(words) log.info( f"Reversing to file {savePath!r}" f", number of words: {wordCount}", ) glos.progressInit("Reversing") wcThreshold = wordCount // 200 + 1 with open(savePath, "w", encoding="utf-8") as saveFile: for wordI in range(wordCount): word = words[wordI] if wordI % wcThreshold == 0: glos.progress(wordI, wordCount) if wordI % saveStep == 0 and wordI > 0: saveFile.flush() result = searchWordInDef( entries, word, includeDefs=includeDefs, **kwargs, ) if result: try: if includeDefs: defi = "\\n\\n".join(result) else: defi = ", ".join(result) + "." except Exception: log.exception("") log.debug(f"{result = }") return saveFile.write(f"{word}\t{defi}\n") yield wordI glos.progressEnd() yield wordCount def takeOutputWords( glos: GlossaryExtendedType, entryIter: Iterable[EntryType], minWordLen: int = 3, ) -> list[str]: # fr"[\w]{{{minWordLen},}}" wordPattern = re.compile(r"[\w]{%d,}" % minWordLen, re.UNICODE) words = set() progressbar, glos.progressbar = glos.progressbar, False for entry in entryIter: words.update(wordPattern.findall( entry.defi, )) glos.progressbar = progressbar return sorted(words) def searchWordInDef( entryIter: Iterable[EntryType], st: str, matchWord: bool = True, sepChars: str = ".,،", maxNum: int = 100, minRel: float = 0.0, minWordLen: int = 3, includeDefs: bool = False, showRel: str = "Percent", # "Percent" | "Percent At First" | "" ) -> list[str]: # searches word "st" in definitions of the glossary splitPattern = re.compile( "|".join(re.escape(x) for x in sepChars), re.UNICODE, ) wordPattern = re.compile(r"[\w]{%d,}" % minWordLen, re.UNICODE) outRel: "list[tuple[str, float] | tuple[str, float, str]]" = [] for entry in entryIter: words = entry.l_word defi = entry.defi if st not in defi: continue for word in words: rel = 0.0 # relation value of word (0 <= rel <= 1) for part in splitPattern.split(defi): if not part: continue if matchWord: partWords = wordPattern.findall( part, ) if not partWords: continue rel = max( rel, partWords.count(st) / len(partWords), ) else: rel = max( rel, part.count(st) * len(st) / len(part), ) if rel <= minRel: continue if includeDefs: outRel.append((word, rel, defi)) else: outRel.append((word, rel)) outRel.sort( key=itemgetter(1), reverse=True, ) n = len(outRel) if n > maxNum > 0: outRel = outRel[:maxNum] n = maxNum num = 0 out = [] if includeDefs: for j in range(n): numP = num w, num, m = outRel[j] # type: ignore m = m.replace("\n", "\\n").replace("\t", "\\t") onePer = int(1.0 / num) if onePer == 1.0: out.append(f"{w}\\n{m}") elif showRel == "Percent": out.append(f"{w}(%{100*num})\\n{m}") elif showRel == "Percent At First": if num == numP: out.append(f"{w}\\n{m}") else: out.append(f"{w}(%{100*num})\\n{m}") else: out.append(f"{w}\\n{m}") return out for j in range(n): numP = num w, num = outRel[j] # type: ignore onePer = int(1.0 / num) if onePer == 1.0: out.append(w) elif showRel == "Percent": out.append(f"{w}(%{100*num})") elif showRel == "Percent At First": if num == numP: out.append(w) else: out.append(f"{w}(%{100*num})") else: out.append(w) return out
4,804
Python
.py
191
21.727749
70
0.652221
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,716
text_writer.py
ilius_pyglossary/pyglossary/text_writer.py
from __future__ import annotations import logging import os from os.path import ( isdir, ) from typing import TYPE_CHECKING, cast if TYPE_CHECKING: import io from collections.abc import Callable, Generator from .glossary_types import EntryType, GlossaryType from .compression import compressionOpen as c_open from .io_utils import nullTextIO __all__ = ["TextGlossaryWriter", "writeTxt"] log = logging.getLogger("pyglossary") file_size_check_every = 100 class TextGlossaryWriter: _encoding: str = "utf-8" _newline: str = "\n" _wordListEncodeFunc: "Callable[[list[str]], str] | None" = None _wordEscapeFunc: "Callable[[str], str] | None" = None _defiEscapeFunc: "Callable[[str], str] | None" = None _ext: str = ".txt" _head: str = "" _tail: str = "" _resources: bool = True _file_size_approx: int = 0 _word_title: bool = False def __init__( self, glos: GlossaryType, entryFmt: str = "", # contain {word} and {defi} writeInfo: bool = True, outInfoKeysAliasDict: "dict[str, str] | None" = None, ) -> None: self._glos = glos self._filename = "" self._file: "io.TextIOBase" = nullTextIO self._resDir = "" if not entryFmt: raise ValueError("entryFmt argument is missing") self._entryFmt = entryFmt self._writeInfo = writeInfo if not outInfoKeysAliasDict: outInfoKeysAliasDict = {} self._outInfoKeysAliasDict = outInfoKeysAliasDict # TODO: replace outInfoKeysAliasDict arg with a func? # TODO: use @property setters def setAttrs( # noqa: PLR0913 self, encoding: "str | None" = None, newline: "str | None" = None, wordListEncodeFunc: "Callable | None" = None, wordEscapeFunc: "Callable | None" = None, defiEscapeFunc: "Callable | None" = None, ext: "str | None" = None, head: "str | None" = None, tail: "str | None" = None, resources: "bool | None" = None, word_title: "bool | None" = None, file_size_approx: "int | None" = None, ) -> None: if encoding is not None: self._encoding = encoding if newline is not None: self._newline = newline if wordListEncodeFunc is not None: self._wordListEncodeFunc = wordListEncodeFunc if wordEscapeFunc is not None: self._wordEscapeFunc = wordEscapeFunc if defiEscapeFunc is not None: self._defiEscapeFunc = defiEscapeFunc if ext is not None: self._ext = ext if head is not None: self._head = head if tail is not None: self._tail = tail if resources is not None: self._resources = resources if word_title is not None: self._word_title = word_title if file_size_approx is not None: self._file_size_approx = file_size_approx def open(self, filename: str) -> None: if self._file_size_approx > 0: self._glos.setInfo("file_count", "-1") self._open(filename) self._filename = filename self._resDir = f"{filename}_res" if not isdir(self._resDir): os.mkdir(self._resDir) def _doWriteInfo(self, _file: "io.TextIOBase") -> None: entryFmt = self._entryFmt outInfoKeysAliasDict = self._outInfoKeysAliasDict wordEscapeFunc = self._wordEscapeFunc defiEscapeFunc = self._defiEscapeFunc for key, value in self._glos.iterInfo(): # both key and value are supposed to be non-empty string if not (key and value): log.warning(f"skipping info {key=}, {value=}") continue key = outInfoKeysAliasDict.get(key, key) # noqa: PLW2901 if not key: continue word = f"##{key}" if wordEscapeFunc is not None: word = wordEscapeFunc(word) if not word: continue if defiEscapeFunc is not None: value = defiEscapeFunc(value) # noqa: PLW2901 if not value: continue _file.write( entryFmt.format( word=word, defi=value, ), ) def _open(self, filename: str) -> io.TextIOBase: if not filename: filename = self._glos.filename + self._ext _file = self._file = cast( "io.TextIOBase", c_open( filename, mode="wt", encoding=self._encoding, newline=self._newline, ), ) _file.write(self._head) if self._writeInfo: self._doWriteInfo(_file) _file.flush() return _file def write(self) -> Generator[None, EntryType, None]: glos = self._glos _file = self._file entryFmt = self._entryFmt wordListEncodeFunc = self._wordListEncodeFunc wordEscapeFunc = self._wordEscapeFunc defiEscapeFunc = self._defiEscapeFunc resources = self._resources word_title = self._word_title file_size_approx = self._file_size_approx entryCount = 0 fileIndex = 0 while True: entry = yield if entry is None: break if entry.isData(): if resources: entry.save(self._resDir) continue word = entry.s_word defi = entry.defi # if glos.alts: # FIXME if word_title: defi = glos.wordTitleStr(entry.l_word[0]) + defi if wordListEncodeFunc is not None: word = wordListEncodeFunc(entry.l_word) elif wordEscapeFunc is not None: word = wordEscapeFunc(word) if defiEscapeFunc is not None: defi = defiEscapeFunc(defi) _file.write(entryFmt.format(word=word, defi=defi)) if file_size_approx > 0: entryCount += 1 if ( entryCount % file_size_check_every == 0 and _file.tell() >= file_size_approx ): fileIndex += 1 _file = self._open(f"{self._filename}.{fileIndex}") def finish(self) -> None: if self._tail: self._file.write(self._tail) self._file.close() if not os.listdir(self._resDir): os.rmdir(self._resDir) def writeTxt( # noqa: PLR0913 glos: GlossaryType, entryFmt: str = "", # contain {word} and {defi} filename: str = "", writeInfo: bool = True, wordEscapeFunc: "Callable | None" = None, defiEscapeFunc: "Callable | None" = None, ext: str = ".txt", head: str = "", tail: str = "", outInfoKeysAliasDict: "dict[str, str] | None" = None, encoding: str = "utf-8", newline: str = "\n", resources: bool = True, word_title: bool = False, ) -> Generator[None, EntryType, None]: writer = TextGlossaryWriter( glos, entryFmt=entryFmt, writeInfo=writeInfo, outInfoKeysAliasDict=outInfoKeysAliasDict, ) writer.setAttrs( encoding=encoding, newline=newline, wordEscapeFunc=wordEscapeFunc, defiEscapeFunc=defiEscapeFunc, ext=ext, head=head, tail=tail, resources=resources, word_title=word_title, ) writer.open(filename) yield from writer.write() writer.finish()
6,295
Python
.py
219
25.415525
64
0.697551
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,717
glossary_v2.py
ilius_pyglossary/pyglossary/glossary_v2.py
# -*- coding: utf-8 -*- # glossary.py # # Copyright © 2008-2022 Saeed Rasooli <saeed.gnu@gmail.com> (ilius) # This file is part of PyGlossary project, https://github.com/ilius/pyglossary # # This program is a free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program. Or on Debian systems, from /usr/share/common-licenses/GPL # If not, see <http://www.gnu.org/licenses/gpl.txt>. from __future__ import annotations import os import os.path from collections import OrderedDict as odict from contextlib import suppress from dataclasses import dataclass from os.path import ( isdir, isfile, join, relpath, ) from pickle import dumps as pickle_dumps from pickle import loads as pickle_loads from time import perf_counter as now from typing import ( TYPE_CHECKING, cast, ) from uuid import uuid1 from zlib import compress as zlib_compress from zlib import decompress as zlib_decompress from . import core from .core import ( cacheDir, log, ) from .entry import DataEntry, Entry from .entry_filters import ( EntryFilterType, PreventDuplicateWords, RemoveHtmlTagsAll, ShowMaxMemoryUsage, ShowProgressBar, StripFullHtml, entryFiltersRules, ) from .entry_list import EntryList from .flags import ( ALWAYS, DEFAULT_YES, NEVER, ) from .glossary_info import GlossaryInfo from .glossary_progress import GlossaryProgress from .glossary_types import ( EntryListType, EntryType, GlossaryExtendedType, GlossaryType, RawEntryType, ) from .glossary_utils import Error, ReadError, WriteError, splitFilenameExt from .info import c_name from .os_utils import rmtree, showMemoryUsage from .plugin_manager import PluginManager from .sort_keys import defaultSortKeyName, lookupSortKey if TYPE_CHECKING: from collections.abc import Callable, Iterator from typing import ( Any, ) from .entry_base import MultiStr from .plugin_prop import PluginProp from .sort_keys import NamedSortKey from .ui_type import UIType __all__ = [ "ConvertArgs", "Error", "Glossary", "GlossaryCommon", "ReadError", "WriteError", ] # SortKeyType = Callable[ # [[list[str]], # Any, # ] @dataclass(slots=True, frozen=True) class ConvertArgs: inputFilename: str inputFormat: str = "" direct: "bool | None" = None outputFilename: str = "" outputFormat: str = "" sort: "bool | None" = None sortKeyName: "str | None" = None sortEncoding: "str | None" = None readOptions: "dict[str, Any] | None" = None writeOptions: "dict[str, Any] | None" = None sqlite: "bool | None" = None infoOverride: "dict[str, str] | None" = None class GlossaryCommon(GlossaryInfo, GlossaryProgress, PluginManager): # noqa: PLR0904 """ The signature of 'convert' method is different in glossary_v2.py See help(Glossary.convert). addEntryObj is renamed to addEntry in glossary_v2.py These methods do not exist in glossary_v2.py (but still exist in glossary.py) - read(): you can use directRead() then iterate over glossary - sortWords(): you have to sort entries yourself (when adding or after directRead) - updateIter(): no longer needed, and does't do anything in glossary.py """ def _closeReaders(self) -> None: for reader in self._readers: try: reader.close() except Exception: # noqa: PERF203 log.exception("") def clear(self) -> None: GlossaryProgress.clear(self) self._info = odict() self._data.clear() readers = getattr(self, "_readers", []) for reader in readers: try: reader.close() except Exception: # noqa: PERF203 log.exception("") self._readers: list[Any] = [] self._defiHasWordTitle = False self._iter: Iterator[EntryType] | None = None self._entryFilters: list[EntryFilterType] = [] self._entryFiltersExtra: list[EntryFilterType] = [] self._entryFiltersName: set[str] = set() self._sort = False self._filename = "" self._defaultDefiFormat = "m" self._tmpDataDir = "" self._entryFiltersAreSet = False def __init__( self, info: "dict[str, str] | None" = None, ui: "UIType | None" = None, # noqa: F821 ) -> None: """ info: OrderedDict or dict instance, or None no need to copy OrderedDict instance before passing here we will not reference to it. """ GlossaryInfo.__init__(self) GlossaryProgress.__init__(self, ui=ui) self._config: "dict[str, Any]" = {} self._data: EntryListType = EntryList( entryToRaw=self._entryToRaw, entryFromRaw=self._entryFromRaw, ) self._sqlite = False self._rawEntryCompress = False self._cleanupPathList: set[str] = set() self._readOptions: dict[str, Any] | None = None self.clear() if info: if not isinstance(info, dict | odict): raise TypeError( "Glossary: `info` has invalid type" ", dict or OrderedDict expected", ) for key, value in info.items(): self.setInfo(key, value) def cleanup(self) -> None: self._closeReaders() if not self._cleanupPathList: return if not self._config.get("cleanup", True): log.info("Not cleaning up files:") log.info("\n".join(self._cleanupPathList)) return self._data.close() for cleanupPath in self._cleanupPathList: if isfile(cleanupPath): log.debug(f"Removing file {cleanupPath}") try: os.remove(cleanupPath) except Exception: log.exception(f"error removing {cleanupPath}") elif isdir(cleanupPath): log.debug(f"Removing directory {cleanupPath}") rmtree(cleanupPath) else: log.error(f"no such file or directory: {cleanupPath}") self._cleanupPathList = set() def _dataEntryToRaw(self, entry: DataEntry) -> RawEntryType: b_fpath = b"" if self.tmpDataDir: b_fpath = entry.save(self.tmpDataDir).encode("utf-8") tpl = ( [entry.getFileName()], b_fpath, "b", ) if self._rawEntryCompress: return zlib_compress(pickle_dumps(tpl), level=9) return tpl def _entryToRaw(self, entry: EntryType) -> RawEntryType: """ Return a tuple (word, defi) or (word, defi, defiFormat) where both word and defi might be string or list of strings. """ if entry.isData(): return self._dataEntryToRaw(cast("DataEntry", entry)) tpl: "tuple[list[str], bytes, str] | tuple[list[str], bytes]" defiFormat = entry.defiFormat if defiFormat and defiFormat != self._defaultDefiFormat: tpl = (entry.l_word, entry.b_defi, defiFormat) else: tpl = (entry.l_word, entry.b_defi) if self.rawEntryCompress: return zlib_compress(pickle_dumps(tpl), level=9) return tpl def _entryFromRaw(self, rawEntryArg: RawEntryType) -> EntryType: if isinstance(rawEntryArg, bytes): rawEntry = pickle_loads(zlib_decompress(rawEntryArg)) else: rawEntry = rawEntryArg word = rawEntry[0] defi = rawEntry[1].decode("utf-8") if len(rawEntry) > 2: # noqa: PLR2004 defiFormat = rawEntry[2] if defiFormat == "b": fname = word if isinstance(fname, list): fname = fname[0] # NESTED 4 return DataEntry(fname, tmpPath=defi) else: defiFormat = self._defaultDefiFormat return Entry(word, defi, defiFormat=defiFormat) @property def rawEntryCompress(self) -> bool: return self._rawEntryCompress def setRawEntryCompress(self, enable: bool) -> None: self._rawEntryCompress = enable self._data.rawEntryCompress = enable def updateEntryFilters(self) -> None: entryFilters = [] config = self._config glosArg = cast(GlossaryExtendedType, self) for configParam, default, filterClass in entryFiltersRules: args = [] value = default if configParam is None else config.get(configParam, default) if not value: continue if not isinstance(default, bool): args = [value] entryFilters.append(filterClass(glosArg, *tuple(args))) if self.progressbar: entryFilters.append(ShowProgressBar(glosArg)) if log.level <= core.TRACE: try: import psutil # noqa: F401 except ModuleNotFoundError: pass else: entryFilters.append(ShowMaxMemoryUsage(glosArg)) self._entryFilters = entryFilters self._entryFiltersName = {entryFilter.name for entryFilter in entryFilters} self._entryFiltersAreSet = True def prepareEntryFilters(self) -> None: """ Call .prepare() method on all _entryFilters run this after glossary info is set and ready for most entry filters, it won't do anything. """ for entryFilter in self._entryFilters: entryFilter.prepare() def _addExtraEntryFilter(self, cls: "type[EntryFilterType]") -> None: if cls.name in self._entryFiltersName: return self._entryFilters.append(cls(cast(GlossaryType, self))) self._entryFiltersExtra.append(cls(cast(GlossaryType, self))) self._entryFiltersName.add(cls.name) def removeHtmlTagsAll(self) -> None: """ Remove all HTML tags from definition. This should only be called from a plugin's Writer.__init__ method. Does not apply on entries added with glos.addEntry """ self._addExtraEntryFilter(RemoveHtmlTagsAll) def stripFullHtml( self, errorHandler: "Callable[[EntryType, str], None] | None" = None, ) -> None: """ Add entry filter "strip_full_html" to replace a full HTML document with it's body in entry definition. """ name = StripFullHtml.name if name in self._entryFiltersName: return self._entryFilters.append( StripFullHtml( cast(GlossaryType, self), errorHandler=errorHandler, ), ) self._entryFiltersName.add(name) def preventDuplicateWords(self) -> None: """ Add entry filter to prevent duplicate `entry.s_word`. This should only be called from a plugin's Writer.__init__ method. Does not apply on entries added with glos.addEntry Note: there may be still duplicate headwords or alternate words but we only care about making the whole `entry.s_word` (aka entry key) unique """ self._addExtraEntryFilter(PreventDuplicateWords) # def mergeEntriesWithSameHeadwordHTML(self): # """ # Merge consequtive entries that have the same word list. # Currently this convert all non-html entries to html. # Should be only called in writer.open. # """ # from pyglossary.entry_merge import mergeHtmlEntriesWithSameHeadword # self._iter = mergeHtmlEntriesWithSameHeadword(self._iter) def mergeEntriesWithSameHeadwordPlaintext(self): """ Merge consequtive entries that have the same word list. Currently this assume all entries are plaintext Should be only called in writer.open. """ from pyglossary.entry_merge import mergePlaintextEntriesWithSameHeadword self._iter = mergePlaintextEntriesWithSameHeadword(self._iter) def __str__(self) -> str: return ( "Glossary{" f"filename: {self._filename!r}" f", name: {self._info.get('name')!r}" "}" ) def _loadedEntryGen(self) -> Iterator[EntryType]: if not self.progressbar: yield from self._data return filters = self._entryFiltersExtra if self.progressbar: filters.append(ShowProgressBar(cast(GlossaryExtendedType, self))) self.progressInit("Writing") for _entry in self._data: entry = _entry for f in filters: entry = f.run(entry) yield entry self.progressEnd() def _readersEntryGen(self) -> Iterator[EntryType]: for reader in self._readers: self.progressInit("Converting") try: yield from self._applyEntryFiltersGen(reader) finally: reader.close() self.progressEnd() # This iterator/generator does not give None entries. # And Entry is not falsable, so bool(entry) is always True. # Since ProgressBar is already handled with an EntryFilter, there is # no point of returning None entries anymore. def _applyEntryFiltersGen( self, gen: Iterator[EntryType], ) -> Iterator[EntryType]: entry: "EntryType | None" for entry in gen: if entry is None: continue for entryFilter in self._entryFilters: entry = entryFilter.run(entry) # noqa: PLW2901 if entry is None: break else: yield entry def __iter__(self) -> Iterator[EntryType]: if self._iter is not None: return self._iter if not self._readers: return self._loadedEntryGen() log.error("Glossary: iterator is not set in direct mode") return iter([]) # TODO: switch to @property defaultDefiFormat def setDefaultDefiFormat(self, defiFormat: str) -> None: """ DefiFormat must be empty or one of these: "m": plain text "h": html "x": xdxf. """ self._defaultDefiFormat = defiFormat def getDefaultDefiFormat(self) -> str: return self._defaultDefiFormat def collectDefiFormat( self, maxCount: int, ) -> dict[str, float] | None: """ Collect definition format. Example return value: [("h", 0.91), ("m", 0.09)]. """ from collections import Counter readers = self._readers if readers: log.error("collectDefiFormat: not supported in direct mode") return None counter: "dict[str, int]" = Counter() count = 0 for entry in self: if entry.isData(): continue entry.detectDefiFormat() counter[entry.defiFormat] += 1 count += 1 if count >= maxCount: break result = { defiFormat: itemCount / count for defiFormat, itemCount in counter.items() } for defiFormat in ("h", "m", "x"): if defiFormat not in result: result[defiFormat] = 0 self._iter = self._loadedEntryGen() return result def __len__(self) -> int: return len(self._data) + sum(len(reader) for reader in self._readers) @property def config(self) -> dict[str, Any]: raise NotImplementedError @config.setter def config(self, config: "dict[str, Any]") -> None: if self._config: log.error("glos.config is set more than once") return self._config = config if "optimize_memory" in config: self.setRawEntryCompress(config["optimize_memory"]) @property def alts(self) -> bool: return self._config.get("enable_alts", True) @property def filename(self) -> str: return self._filename @property def tmpDataDir(self) -> str: if not self._tmpDataDir: self._setTmpDataDir(self._filename) return self._tmpDataDir @property def readOptions(self) -> dict | None: return self._readOptions def wordTitleStr( self, word: str, sample: str = "", _class: str = "", ) -> str: """ Return title tag for words. Notes ----- - `word` needs to be escaped before passing - `word` can contain html code (multiple words, colors, etc) - if input format (reader) indicates that words are already included in definition (as title), this method will return empty string - depending on glossary's `sourceLang` or writing system of `word`, (or sample if given) either '<b>' or '<big>' will be used. """ if self._defiHasWordTitle: return "" if not word: return "" if not sample: sample = word tag = self.titleTag(sample) if _class: return f'<{tag} class="{_class}">{word}</{tag}><br>' return f"<{tag}>{word}</{tag}><br>" def getConfig(self, name: str, default: "str | None") -> str | None: return self._config.get(name, default) def addEntry(self, entry: EntryType) -> None: self._data.append(entry) def newEntry( self, word: MultiStr, defi: str, defiFormat: str = "", byteProgress: "tuple[int, int] | None" = None, ) -> Entry: """ Create and return a new entry object. defiFormat must be empty or one of these: "m": plain text "h": html "x": xdxf """ if not defiFormat: defiFormat = self._defaultDefiFormat return Entry( word, defi, defiFormat=defiFormat, byteProgress=byteProgress, ) def newDataEntry(self, fname: str, data: bytes) -> EntryType: if self._readers: return DataEntry(fname, data) if self._tmpDataDir: return DataEntry( fname, data, tmpPath=join(self._tmpDataDir, fname.replace("/", "_")), ) tmpDir = join(cacheDir, "tmp") os.makedirs(tmpDir, mode=0o700, exist_ok=True) self._cleanupPathList.add(tmpDir) return DataEntry( fname, data, tmpPath=join(tmpDir, uuid1().hex), ) # ________________________________________________________________________# # def _hasWriteAccessToDir(self, dirPath: str) -> None: # if isdir(dirPath): # return os.access(dirPath, os.W_OK) # return os.access(os.path.dirname(dirPath), os.W_OK) def _createReader( self, format: str, options: "dict[str, Any]", ) -> Any: readerClass = self.plugins[format].readerClass if readerClass is None: raise ReadError("_createReader: readerClass is None") reader = readerClass(self) for name, value in options.items(): setattr(reader, f"_{name}", value) return reader def _setTmpDataDir(self, filename: str) -> None: # good thing about cacheDir is that we don't have to clean it up after # conversion is finished. # specially since dataEntry.save(...) will move the file from cacheDir # to the new directory (associated with output glossary path) # And we don't have to check for write access to cacheDir because it's # inside user's home dir. But input glossary might be in a directory # that we don't have write access to. # still maybe add a config key to decide if we should always use cacheDir # if self._hasWriteAccessToDir(f"{filename}_res", os.W_OK): # self._tmpDataDir = f"{filename}_res" # else: if not filename: filename = uuid1().hex self._tmpDataDir = join(cacheDir, os.path.basename(filename) + "_res") log.debug(f"tmpDataDir = {self._tmpDataDir}") os.makedirs(self._tmpDataDir, mode=0o700, exist_ok=True) self._cleanupPathList.add(self._tmpDataDir) def _validateReadoptions( self, format: str, options: "dict[str, Any]", ) -> None: validOptionKeys = set(self.formatsReadOptions[format]) for key in list(options): if key not in validOptionKeys: log.error( f"Invalid read option {key!r} given for {format} format", ) del options[key] def _openReader(self, reader: Any, filename: str): # reader.open returns "Iterator[tuple[int, int]] | None" progressbar: bool = self.progressbar try: openResult = reader.open(filename) if openResult is not None: self.progressInit("Reading metadata") lastPos = -100_000 for pos, total in openResult: if progressbar and pos - lastPos > 100_000: # noqa: PLR2004 self.progress(pos, total, unit="bytes") lastPos = pos self.progressEnd() except (FileNotFoundError, LookupError) as e: raise ReadError(str(e)) from e hasTitleStr = self._info.get("definition_has_headwords", "") if hasTitleStr: if hasTitleStr.lower() == "true": self._defiHasWordTitle = True else: log.error(f"bad info value: definition_has_headwords={hasTitleStr!r}") def directRead( self, filename: str, format: str = "", **options, ) -> bool: self._setTmpDataDir(filename) return self._read( filename=filename, format=format, direct=True, **options, ) def _read( self, filename: str, format: str = "", direct: bool = False, **options, ) -> bool: filename = os.path.abspath(filename) ### inputArgs = self.detectInputFormat(filename, format=format) if inputArgs is None: return False origFilename = filename filename, format, compression = inputArgs if compression: from .compression import uncompress uncompress(origFilename, filename, compression) self._validateReadoptions(format, options) filenameNoExt, ext = os.path.splitext(filename) if ext.lower() not in self.plugins[format].extensions: filenameNoExt = filename self._filename = filenameNoExt if not self._info.get(c_name): self._info[c_name] = os.path.split(filename)[1] if not self._entryFiltersAreSet: self.updateEntryFilters() reader = self._createReader(format, options) self._openReader(reader, filename) self._readOptions = options self.prepareEntryFilters() if not direct: self.loadReader(reader) self._iter = self._loadedEntryGen() return True self._readers.append(reader) self._iter = self._readersEntryGen() return True def loadReader(self, reader: Any) -> None: """ Iterate over `reader` object and loads the whole data into self._data must call `reader.open(filename)` before calling this function. """ showMemoryUsage() self.progressInit("Reading") try: for entry in self._applyEntryFiltersGen(reader): self.addEntry(entry) finally: reader.close() self.progressEnd() core.trace(log, f"Loaded {len(self._data)} entries") showMemoryUsage() def _createWriter( self, format: str, options: "dict[str, Any]", ) -> Any: validOptions = self.formatsWriteOptions.get(format) if validOptions is None: raise WriteError(f"No write support for {format!r} format") validOptionKeys = list(validOptions) for key in list(options): if key not in validOptionKeys: log.error( f"Invalid write option {key!r} given for {format} format", ) del options[key] writerClass = self.plugins[format].writerClass if writerClass is None: raise WriteError("_createWriter: writerClass is None") writer = writerClass(self) for name, value in options.items(): setattr(writer, f"_{name}", value) return writer def write( self, filename: str, format: str, **kwargs, ) -> str: """ Write to a given glossary file, with given format (optional). Return absolute path of output file, or None if failed. Parameters ---------- filename (str): file name or path to write. format (str): format name sort (bool): True (enable sorting), False (disable sorting), None (auto, get from UI) sortKeyName (str or None): key function name for sorting sortEncoding (str or None): encoding for sorting, default utf-8 You can pass write-options (of given format) as keyword arguments """ if type(filename) is not str: raise TypeError("filename must be str") if format is not None and type(format) is not str: raise TypeError("format must be str") return self._write( filename=filename, format=format, **kwargs, ) def _writeEntries( self, writerList: list[Any], filename: str, ) -> None: writer = writerList[0] genList = [] gen = writer.write() if gen is None: log.error(f"{format} write function is not a generator") else: genList.append(gen) if self._config.get("save_info_json", False): from pyglossary.info_writer import InfoWriter infoWriter = InfoWriter(cast(GlossaryType, self)) filenameNoExt, _, _, _ = splitFilenameExt(filename) infoWriter.open(f"{filenameNoExt}.info") genList.append(infoWriter.write()) writerList.append(infoWriter) for gen in genList: gen.send(None) for entry in self: for gen in genList: gen.send(entry) # suppress() on the whole for-loop does not work for gen in genList: with suppress(StopIteration): gen.send(None) @staticmethod def _openWriter( writer: Any, filename: str, ): try: writer.open(filename) except (FileNotFoundError, LookupError) as e: raise WriteError(str(e)) from e def _write( self, filename: str, format: str, sort: bool = False, **options, ) -> str: filename = os.path.abspath(filename) if format not in self.plugins or not self.plugins[format].canWrite: raise WriteError(f"No Writer class found for plugin {format}") if self._readers and sort: log.warning( "Full sort enabled, falling back to indirect mode", ) for reader in self._readers: self.loadReader(reader) self._readers = [] log.info(f"Writing to {format} file {filename!r}") writer = self._createWriter(format, options) self._sort = sort if sort: t0 = now() self._data.sort() log.info(f"Sorting took {now() - t0:.1f} seconds") if self._readers: self._iter = self._readersEntryGen() else: self._iter = self._loadedEntryGen() self._openWriter(writer, filename) showMemoryUsage() writerList = [writer] try: self._writeEntries(writerList, filename) except (FileNotFoundError, LookupError) as e: raise WriteError(str(e)) from e finally: showMemoryUsage() log.debug("Running writer.finish()") for writer in writerList: writer.finish() self.clear() showMemoryUsage() return filename def _compressOutput(self, filename: str, compression: str) -> str: from .compression import compress return compress( cast(GlossaryType, self), filename, compression, ) def _switchToSQLite( self, inputFilename: str, ) -> None: from .sq_entry_list import SqEntryList sq_fpath = join(cacheDir, f"{os.path.basename(inputFilename)}.db") if isfile(sq_fpath): log.info(f"Removing and re-creating {sq_fpath!r}") os.remove(sq_fpath) self._data = SqEntryList( entryToRaw=self._entryToRaw, entryFromRaw=self._entryFromRaw, filename=sq_fpath, create=True, persist=True, ) self._cleanupPathList.add(sq_fpath) if not self.alts: log.warning( "SQLite mode only works with enable_alts=True, force-enabling it.", ) self._config["enable_alts"] = True self._sqlite = True @staticmethod def _checkSortFlag( plugin: PluginProp, sort: "bool | None", ) -> bool: sortOnWrite = plugin.sortOnWrite if sortOnWrite == ALWAYS: if sort is False: log.warning( f"Writing {plugin.name} requires sorting" ", ignoring user sort=False option", ) return True if sortOnWrite == NEVER: if sort: log.warning( "Plugin prevents sorting before write" ", ignoring user sort=True option", ) return False if sortOnWrite == DEFAULT_YES: return sort or sort is None # if sortOnWrite == DEFAULT_NO: return bool(sort) def _resolveSortParams( self, args: ConvertArgs, plugin: PluginProp, ) -> tuple[bool, bool]: """ sortKeyName: see doc/sort-key.md. returns (sort, direct) """ if args.direct and args.sqlite: raise ValueError( f"Conflictng arguments: direct={args.direct}, sqlite={args.sqlite}", ) sort = self._checkSortFlag(plugin, args.sort) if not sort: if args.direct is None: return True, False return args.direct, False # from this point we can assume sort == True and direct == False sqlite = args.sqlite if sqlite is None: sqlite = self._config.get("auto_sqlite", True) if sqlite: log.info( "Automatically switching to SQLite mode" f" for writing {plugin.name}", ) sortKeyTuple = self._checkSortKey( plugin, args.sortKeyName, args.sortEncoding, ) namedSortKey, sortEncoding = sortKeyTuple if sqlite: self._switchToSQLite( inputFilename=args.inputFilename, ) self._data.setSortKey( namedSortKey=namedSortKey, sortEncoding=sortEncoding, writeOptions=args.writeOptions or {}, ) return False, True @staticmethod def _checkSortKey( plugin: PluginProp, sortKeyName: "str | None", sortEncoding: "str | None", ) -> tuple[NamedSortKey, str]: """ Check sortKeyName, sortEncoding and (output) plugin's params returns (namedSortKey, sortEncoding). """ writerSortKeyName = plugin.sortKeyName writerSortEncoding = getattr(plugin, "sortEncoding", None) if plugin.sortOnWrite == ALWAYS: if not writerSortKeyName: raise Error("No sortKeyName was found in plugin") if sortKeyName and sortKeyName != writerSortKeyName: log.warning( f"Ignoring user-defined sort order {sortKeyName!r}" f", and using sortKey function from {plugin.name} plugin", ) sortKeyName = writerSortKeyName if writerSortEncoding: sortEncoding = writerSortEncoding elif not sortKeyName: sortKeyName = writerSortKeyName or defaultSortKeyName namedSortKey = lookupSortKey(sortKeyName) if namedSortKey is None: raise Error(f"invalid {sortKeyName = }") log.info(f"Using sortKeyName = {namedSortKey.name!r}") if not sortEncoding: sortEncoding = "utf-8" return namedSortKey, sortEncoding @staticmethod def _convertValidateStrings(args: ConvertArgs) -> None: if type(args.inputFilename) is not str: raise TypeError("inputFilename must be str") if type(args.outputFilename) is not str: raise TypeError("outputFilename must be str") if args.inputFormat is not None and type(args.inputFormat) is not str: raise TypeError("inputFormat must be str") if args.outputFormat is not None and type(args.outputFormat) is not str: raise TypeError("outputFormat must be str") def _convertPrepare( self, args: ConvertArgs, outputFilename: str = "", outputFormat: str = "", ) -> bool | None: if isdir(outputFilename) and os.listdir(outputFilename): raise Error( f"Directory already exists and not empty: {relpath(outputFilename)}", ) outputPlugin = self.plugins[outputFormat] sortParams = self._resolveSortParams( args=args, plugin=outputPlugin, ) direct, sort = sortParams showMemoryUsage() self._setTmpDataDir(args.inputFilename) readOptions = args.readOptions or {} self._read( args.inputFilename, format=args.inputFormat, direct=direct, **readOptions, ) self.detectLangsFromName() return sort def convertV2(self, args: ConvertArgs) -> str: """ Return absolute path of output file, or None if failed. sortKeyName: name of sort key/algorithm defaults to `defaultSortKeyName` in sort_keys.py see doc/sort-key.md or sort_keys.py for other possible values This can also include sort locale after a colon sign, for example: sortKeyName=":fa_IR.UTF-8" sortKeyName="headword:fa_IR.UTF-8" sortEncoding: encoding/charset for sorting, default to utf-8 """ self._convertValidateStrings(args) if args.outputFilename == args.inputFilename: raise Error("Input and output files are the same") tm0 = now() outputArgs = self.detectOutputFormat( filename=args.outputFilename, format=args.outputFormat, inputFilename=args.inputFilename, ) if not outputArgs: raise Error(f"Writing file {relpath(args.outputFilename)!r} failed.") outputFilename, outputFormat, compression = outputArgs sort = self._convertPrepare( args=args, outputFilename=outputFilename, outputFormat=outputFormat, ) if sort is None: return None if args.infoOverride: for key, value in args.infoOverride.items(): self.setInfo(key, value) if compression and not self.plugins[outputFormat].singleFile: os.makedirs(outputFilename, mode=0o700, exist_ok=True) writeOptions = args.writeOptions or {} finalOutputFile = self._write( outputFilename, outputFormat, sort=sort, **writeOptions, ) if compression: finalOutputFile = self._compressOutput(finalOutputFile, compression) log.info(f"Writing file {finalOutputFile!r} done.") log.info(f"Running time of convert: {now() - tm0:.1f} seconds") showMemoryUsage() self.cleanup() return finalOutputFile # ________________________________________________________________________# class Glossary(GlossaryCommon): """ init method is inherited from PluginManager arguments: usePluginsJson: bool = True skipDisabledPlugins: bool = True. init() must be called only once, so make sure you put it in the right place. Probably in the top of your program's main function or module. """ GLOSSARY_API_VERSION = "2.0" def convert(self, args: ConvertArgs) -> str | None: return self.convertV2(args)
31,491
Python
.py
1,034
27.111219
85
0.721308
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,718
entry.py
ilius_pyglossary/pyglossary/entry.py
# -*- coding: utf-8 -*- from __future__ import annotations import logging import os import re import shutil from os.path import ( dirname, getsize, join, ) from pickle import loads as pickle_loads from typing import TYPE_CHECKING from zlib import decompress as zlib_decompress from .entry_base import BaseEntry, MultiStr from .iter_utils import unique_everseen from .text_utils import joinByBar if TYPE_CHECKING: from collections.abc import Callable from typing import ( Any, ) from .glossary_types import RawEntryType __all__ = ["DataEntry", "Entry"] log = logging.getLogger("pyglossary") # aka Resource class DataEntry(BaseEntry): # noqa: PLR0904 __slots__ = [ "_byteProgress", "_data", "_fname", "_tmpPath", ] @classmethod def isData(cls) -> bool: return True def __init__( self, fname: str, data: bytes = b"", tmpPath: "str | None" = None, byteProgress: "tuple[int, int] | None" = None, ) -> None: if data and tmpPath: os.makedirs(dirname(tmpPath), mode=0o755, exist_ok=True) with open(tmpPath, "wb") as toFile: toFile.write(data) data = b"" self._fname = fname self._data = data # bytes instance self._tmpPath = tmpPath self._byteProgress = byteProgress # tuple[int, int] | None def getFileName(self) -> str: return self._fname @property def data(self) -> bytes: if self._tmpPath: with open(self._tmpPath, "rb") as _file: return _file.read() else: return self._data def size(self) -> int: if self._tmpPath: return getsize(self._tmpPath) return len(self._data) def save(self, directory: str) -> str: fname = self._fname fpath = join(directory, fname) fdir = dirname(fpath) try: os.makedirs(fdir, mode=0o755, exist_ok=True) if self._tmpPath: shutil.move(self._tmpPath, fpath) self._tmpPath = fpath else: with open(fpath, "wb") as toFile: toFile.write(self._data) # NESTED 4 except FileNotFoundError as e: log.error(f"error in DataEntry.save: {e}") except Exception: log.exception(f"error while saving {fpath}") return "" return fpath @property def s_word(self) -> str: return self._fname @property def l_word(self) -> list[str]: return [self._fname] @property def defi(self) -> str: return f"File: {self._fname}" def byteProgress(self) -> tuple[int, int] | None: return self._byteProgress @property def defiFormat(self) -> str: return "b" @defiFormat.setter def defiFormat(self, defiFormat: str) -> None: pass def detectDefiFormat(self) -> None: pass def addAlt(self, alt: str) -> None: pass def editFuncWord(self, func: "Callable[[str], str]") -> None: pass def editFuncDefi(self, func: "Callable[[str], str]") -> None: pass def strip(self) -> None: pass def replaceInWord(self, source: str, target: str) -> None: pass def replaceInDefi(self, source: str, target: str) -> None: pass def replace(self, source: str, target: str) -> None: pass def removeEmptyAndDuplicateAltWords(self) -> None: pass def stripFullHtml(self) -> str | None: pass class Entry(BaseEntry): xdxfPattern = re.compile("^<k>[^<>]*</k>", re.DOTALL | re.IGNORECASE) htmlPattern = re.compile( ".*(?:" + "|".join( [ r"<font[ >]", r"<br\s*/?\s*>", r"<i[ >]", r"<b[ >]", r"<p[ >]", r"<hr\s*/?\s*>", r"<a ", # or r"<a [^<>]*href=" r"<div[ >]", r"<span[ >]", r"<img[ >]", r"<table[ >]", r"<sup[ >]", r"<u[ >]", r"<ul[ >]", r"<ol[ >]", r"<li[ >]", r"<h[1-6][ >]", r"<audio[ >]", ], ) + "|&[a-z]{2,8};|&#x?[0-9]{2,5};)", re.DOTALL | re.IGNORECASE, ) __slots__ = [ "_byteProgress", "_defi", "_defiFormat", "_word", ] @classmethod def isData(cls) -> bool: return False @staticmethod def getRawEntrySortKey( key: "Callable[[bytes], Any]", rawEntryCompress: bool, ) -> Callable[[RawEntryType], Any]: # FIXME: this type for `key` is only for rawEntryCompress=False # for rawEntryCompress=True, it is Callable[[bytes], Any] # here `x` is raw entity, meaning a tuple of form (word, defi) or # (word, defi, defiFormat) # so x[0] is word(s) in bytes, that can be a str (one word), # or a list or tuple (one word with or more alternatives) if rawEntryCompress: return lambda x: key(pickle_loads(zlib_decompress(x))[0]) # type: ignore # x is rawEntry, so x[0] is list of words (entry.l_word) return lambda x: key(x[0]) # type: ignore def __init__( self, word: MultiStr, defi: str, defiFormat: str = "m", byteProgress: "tuple[int, int] | None" = None, ) -> None: """ Create a new Entry. word: string or a list of strings (including alternate words) defi: string or a list of strings (including alternate definitions) defiFormat (optional): definition format: "m": plain text "h": html "x": xdxf. """ # memory optimization: if isinstance(word, list | tuple): if len(word) == 1: word = word[0] elif not isinstance(word, str): raise TypeError(f"invalid word type {type(word)}") if isinstance(defi, list): if len(defi) == 1: defi = defi[0] elif not isinstance(defi, str): raise TypeError(f"invalid defi type {type(defi)}") if defiFormat not in {"m", "h", "x"}: raise ValueError(f"invalid defiFormat {defiFormat!r}") self._word = word self._defi = defi self._defiFormat = defiFormat self._byteProgress = byteProgress # tuple[int, int] | None def __repr__(self) -> str: return ( f"Entry({self._word!r}, {self._defi!r}, " f"defiFormat={self._defiFormat!r})" ) @property def s_word(self) -> str: """Returns string of word, and all the alternate words separated by "|".""" if isinstance(self._word, str): return self._word return joinByBar(self._word) @property def l_word(self) -> list[str]: """Returns list of the word and all the alternate words.""" if isinstance(self._word, str): return [self._word] return self._word @property def defi(self) -> str: """Returns string of definition.""" return self._defi @property def defiFormat(self) -> str: """ Returns definition format. Values: "m": plain text "h": html "x": xdxf. """ # TODO: type: Literal["m", "h", "x"] return self._defiFormat @defiFormat.setter def defiFormat(self, defiFormat: str) -> None: """ Set definition format. defiFormat: "m": plain text "h": html "x": xdxf. """ self._defiFormat = defiFormat def detectDefiFormat(self) -> None: if self._defiFormat != "m": return if Entry.xdxfPattern.match(self.defi): self._defiFormat = "x" return if Entry.htmlPattern.match(self.defi): self._defiFormat = "h" return def byteProgress(self) -> tuple[int, int] | None: return self._byteProgress def addAlt(self, alt: str) -> None: l_word = self.l_word l_word.append(alt) self._word = l_word def editFuncWord(self, func: "Callable[[str], str]") -> None: """ Run function `func` on all the words. `func` must accept only one string as argument and return the modified string. """ if isinstance(self._word, str): self._word = func(self._word) return self._word = [func(st) for st in self._word] def editFuncDefi(self, func: "Callable[[str], str]") -> None: """ Run function `func` on all the definitions. `func` must accept only one string as argument and return the modified string. """ self._defi = func(self._defi) @classmethod def _stripTrailingBR(cls, s: str) -> str: while s.endswith(("<BR>", "<br>")): s = s[:-4] return s def strip(self) -> None: """Strip whitespaces from all words and definitions.""" self.editFuncWord(str.strip) self.editFuncDefi(str.strip) self.editFuncDefi(self._stripTrailingBR) def replaceInWord(self, source: str, target: str) -> None: """Replace string `source` with `target` in all words.""" if isinstance(self._word, str): self._word = self._word.replace(source, target) return self._word = [st.replace(source, target) for st in self._word] def replaceInDefi(self, source: str, target: str) -> None: """Replace string `source` with `target` in all definitions.""" self._defi = self._defi.replace(source, target) def replace(self, source: str, target: str) -> None: """Replace string `source` with `target` in all words and definitions.""" self.replaceInWord(source, target) self.replaceInDefi(source, target) def removeEmptyAndDuplicateAltWords(self) -> None: l_word = self.l_word if len(l_word) == 1: return l_word = [word for word in l_word if word] l_word = list(unique_everseen(l_word)) self._word = l_word def stripFullHtml(self) -> str | None: """Remove <html><head><body> tags and returns error.""" defi = self._defi if not defi.startswith("<"): return None if defi.startswith("<!DOCTYPE html>"): defi = defi[len("<!DOCTYPE html>") :].strip() if not defi.startswith("<html"): return "Has <!DOCTYPE html> but no <html>" elif not defi.startswith("<html>"): return None i = defi.find("<body") if i == -1: return "<body not found" defi = defi[i + 5 :] i = defi.find(">") if i == -1: return "'>' after <body not found" defi = defi[i + 1 :] i = defi.find("</body") if i == -1: return "</body close not found" defi = defi[:i] self._defi = defi return None
9,323
Python
.py
335
24.659701
77
0.660838
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,719
ui_type.py
ilius_pyglossary/pyglossary/ui_type.py
__all__ = ["UIType"] class UIType: def progressInit(self, title: str) -> None: raise NotImplementedError def progress(self, ratio: float, text: str = "") -> None: raise NotImplementedError def progressEnd(self) -> None: raise NotImplementedError
259
Python
.py
8
29.75
58
0.732794
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,720
plugin_manager.py
ilius_pyglossary/pyglossary/plugin_manager.py
# -*- coding: utf-8 -*- # # Copyright © 2008-2022 Saeed Rasooli <saeed.gnu@gmail.com> (ilius) # This file is part of PyGlossary project, https://github.com/ilius/pyglossary # # This program is a free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program. Or on Debian systems, from /usr/share/common-licenses/GPL # If not, see <http://www.gnu.org/licenses/gpl.txt>. from __future__ import annotations import logging import os import sys from os.path import isdir, join from typing import Any, NamedTuple from . import core from .core import ( cacheDir, dataDir, pluginsDir, userPluginsDir, ) from .glossary_utils import ( Error, splitFilenameExt, ) from .plugin_prop import PluginProp __all__ = ["PluginManager"] log = logging.getLogger("pyglossary") class DetectedFormat(NamedTuple): filename: str formatName: str compression: str class PluginManager: plugins: "dict[str, PluginProp]" = {} pluginByExt: "dict[str, PluginProp]" = {} loadedModules: set[str] = set() formatsReadOptions: "dict[str, dict[str, Any]]" = {} formatsWriteOptions: "dict[str, dict[str, Any]]" = {} # for example formatsReadOptions[format][optName] gives you the default value readFormats: list[str] = [] writeFormats: list[str] = [] @classmethod def loadPluginsFromJson(cls: type[PluginManager], jsonPath: str) -> None: import json with open(jsonPath, encoding="utf-8") as _file: data = json.load(_file) for attrs in data: moduleName = attrs["module"] cls._loadPluginByDict( attrs=attrs, modulePath=join(pluginsDir, moduleName), ) cls.loadedModules.add(moduleName) @classmethod def loadPlugins( cls: type[PluginManager], directory: str, skipDisabled: bool = True, ) -> None: """ Load plugins from directory on startup. Skip importing plugin modules that are already loaded. """ import pkgutil # log.debug(f"Loading plugins from directory: {directory!r}") if not isdir(directory): log.critical(f"Invalid plugin directory: {directory!r}") return moduleNames = [ moduleName for _, moduleName, _ in pkgutil.iter_modules([directory]) if moduleName not in cls.loadedModules and moduleName != "formats_common" ] moduleNames.sort() sys.path.append(directory) for moduleName in moduleNames: cls._loadPlugin(moduleName, skipDisabled=skipDisabled) sys.path.pop() @classmethod def _loadPluginByDict( cls: type[PluginManager], attrs: "dict[str, Any]", modulePath: str, ) -> None: format = attrs["name"] extensions = attrs["extensions"] prop = PluginProp.fromDict( attrs=attrs, modulePath=modulePath, ) if prop is None: return cls.plugins[format] = prop cls.loadedModules.add(attrs["module"]) if not prop.enable: return for ext in extensions: if ext.lower() != ext: log.error(f"non-lowercase extension={ext!r} in {prop.name} plugin") cls.pluginByExt[ext.lstrip(".")] = prop cls.pluginByExt[ext] = prop if attrs["canRead"]: cls.formatsReadOptions[format] = attrs["readOptions"] cls.readFormats.append(format) if attrs["canWrite"]: cls.formatsWriteOptions[format] = attrs["writeOptions"] cls.writeFormats.append(format) if log.level <= core.TRACE: prop.module # noqa: B018, to make sure importing works @classmethod def _loadPlugin( cls: type[PluginManager], moduleName: str, skipDisabled: bool = True, ) -> None: log.debug(f"importing {moduleName} in loadPlugin") try: module = __import__(moduleName) except ModuleNotFoundError as e: log.warning(f"Module {e.name!r} not found, skipping plugin {moduleName!r}") return except Exception: log.exception(f"Error while importing plugin {moduleName}") return enable = getattr(module, "enable", False) if skipDisabled and not enable: # log.debug(f"Plugin disabled or not a module: {moduleName}") return name = module.format prop = PluginProp.fromModule(module) cls.plugins[name] = prop cls.loadedModules.add(moduleName) if not enable: return for ext in prop.extensions: if ext.lower() != ext: log.error(f"non-lowercase extension={ext!r} in {moduleName} plugin") cls.pluginByExt[ext.lstrip(".")] = prop cls.pluginByExt[ext] = prop if prop.canRead: options = prop.getReadOptions() cls.formatsReadOptions[name] = options cls.readFormats.append(name) if prop.canWrite: options = prop.getWriteOptions() cls.formatsWriteOptions[name] = options cls.writeFormats.append(name) @classmethod def _findPlugin( cls: type[PluginManager], query: str, ) -> PluginProp | None: """Find plugin by name or extension.""" plugin = cls.plugins.get(query) if plugin: return plugin plugin = cls.pluginByExt.get(query) if plugin: return plugin return None @classmethod def detectInputFormat( cls: type[PluginManager], filename: str, format: str = "", quiet: bool = False, # noqa: ARG003 ) -> DetectedFormat: filenameOrig = filename _, filename, ext, compression = splitFilenameExt(filename) plugin = None if format: plugin = cls.plugins.get(format) if plugin is None: raise Error(f"Invalid format {format!r}") else: plugin = cls.pluginByExt.get(ext) if not plugin: plugin = cls._findPlugin(filename) if not plugin: raise Error("Unable to detect input format!") if not plugin.canRead: raise Error(f"plugin {plugin.name} does not support reading") if compression in plugin.readCompressions: compression = "" filename = filenameOrig return DetectedFormat(filename, plugin.name, compression) @classmethod def _outputPluginByFormat( cls: type[PluginManager], format: str, ) -> tuple[PluginProp | None, str]: if not format: return None, "" plugin = cls.plugins.get(format, None) if not plugin: return None, f"Invalid format {format}" if not plugin.canWrite: return None, f"plugin {plugin.name} does not support writing" return plugin, "" # TODO: breaking change: # return "tuple[DetectedFormat | None, str]" # where the str is error # and remove `quiet` argument, and local `error` function # also: # C901 `detectOutputFormat` is too complex (16 > 13) # PLR0912 Too many branches (14 > 12) @classmethod def detectOutputFormat( # noqa: PLR0912, PLR0913, C901 cls: type[PluginManager], filename: str = "", format: str = "", inputFilename: str = "", quiet: bool = False, # noqa: ARG003, TODO: remove addExt: bool = False, ) -> DetectedFormat: from os.path import splitext # Ugh, mymy # https://github.com/python/mypy/issues/6549 # > Mypy assumes that the return value of methods that return None should not # > be used. This helps guard against mistakes where you accidentally use the # > return value of such a method (e.g., saying new_list = old_list.sort()). # > I don't think there's a bug here. # Sorry, but that's not the job of a type checker at all! plugin, err = cls._outputPluginByFormat(format) if err: raise Error(err) if not filename: # FIXME: not covered in tests if not inputFilename: raise Error(f"Invalid filename {filename!r}") # type: ignore if not plugin: raise Error( "No filename nor format is given for output file", ) # type: ignore filename = splitext(inputFilename)[0] + plugin.ext return DetectedFormat(filename, plugin.name, "") filenameOrig = filename filenameNoExt, filename, ext, compression = splitFilenameExt(filename) if not plugin: plugin = cls.pluginByExt.get(ext) if not plugin: plugin = cls._findPlugin(filename) if not plugin: raise Error("Unable to detect output format!") # type: ignore if not plugin.canWrite: raise Error( f"plugin {plugin.name} does not support writing", ) # type: ignore if compression in getattr(plugin.writerClass, "compressions", []): compression = "" filename = filenameOrig if addExt: if not filenameNoExt: if inputFilename: ext = plugin.ext filename = splitext(inputFilename)[0] + ext else: log.error("inputFilename is empty") if not ext and plugin.ext: filename += plugin.ext return DetectedFormat(filename, plugin.name, compression) @classmethod def init( cls: type[PluginManager], usePluginsJson: bool = True, skipDisabledPlugins: bool = True, ) -> None: """ Initialize the glossary class (not an insatnce). Must be called only once, so make sure you put it in the right place. Probably in the top of your program's main function or module. """ cls.readFormats = [] cls.writeFormats = [] pluginsJsonPath = join(dataDir, "plugins-meta", "index.json") # even if usePluginsJson, we should still call loadPlugins to load # possible new plugins that are not in json file if usePluginsJson: cls.loadPluginsFromJson(pluginsJsonPath) cls.loadPlugins(pluginsDir, skipDisabled=skipDisabledPlugins) if isdir(userPluginsDir): cls.loadPlugins(userPluginsDir) os.makedirs(cacheDir, mode=0o700, exist_ok=True)
9,476
Python
.py
293
29.156997
79
0.730849
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,721
glossary.py
ilius_pyglossary/pyglossary/glossary.py
# -*- coding: utf-8 -*- # glossary.py # # Copyright © 2008-2022 Saeed Rasooli <saeed.gnu@gmail.com> (ilius) # This file is part of PyGlossary project, https://github.com/ilius/pyglossary # # This program is a free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program. Or on Debian systems, from /usr/share/common-licenses/GPL # If not, see <http://www.gnu.org/licenses/gpl.txt>. from __future__ import annotations from os.path import relpath from time import perf_counter as now from typing import TYPE_CHECKING from .core import log from .glossary_v2 import ConvertArgs, Error, GlossaryCommon, ReadError, WriteError from .sort_keys import lookupSortKey if TYPE_CHECKING: from typing import Any from .glossary_types import EntryType __all__ = ["Glossary"] class Glossary(GlossaryCommon): GLOSSARY_API_VERSION = "1.0" def titleElement( # noqa: ANN201 self, hf, # noqa: ANN001, type: ignore sample: str = "", ): # type: ignore return hf.element(self.titleTag(sample)) def read( self, filename: str, format: str = "", direct: bool = False, progressbar: bool = True, **kwargs, # noqa: ANN003 ) -> bool: """ Read from a given glossary file. Parameters ---------- filename (str): name/path of input file format (str): name of input format, or "" to detect from file extension direct (bool): enable direct mode progressbar (bool): enable progressbar. read-options can be passed as additional keyword arguments """ if type(filename) is not str: raise TypeError("filename must be str") if format is not None and type(format) is not str: raise TypeError("format must be str") # don't allow direct=False when there are readers # (read is called before with direct=True) if self._readers and not direct: raise ValueError( f"there are already {len(self._readers)} readers" ", you can not read with direct=False mode", ) self._setTmpDataDir(filename) self._progressbar = progressbar return self._read( filename=filename, format=format, direct=direct, **kwargs, ) def addEntryObj(self, entry: EntryType) -> None: self._data.append(entry) @staticmethod def updateIter() -> None: log.warning("calling glos.updateIter() is no longer needed.") def sortWords( self, sortKeyName: str = "headword_lower", sortEncoding: str = "utf-8", writeOptions: "dict[str, Any] | None" = None, ) -> None: """sortKeyName: see doc/sort-key.md.""" if self._readers: raise NotImplementedError( "can not use sortWords in direct mode", ) if self._sqlite: raise NotImplementedError( "can not use sortWords in SQLite mode", ) namedSortKey = lookupSortKey(sortKeyName) if namedSortKey is None: log.critical(f"invalid {sortKeyName = }") return if not sortEncoding: sortEncoding = "utf-8" if writeOptions is None: writeOptions = {} t0 = now() self._data.setSortKey( namedSortKey=namedSortKey, sortEncoding=sortEncoding, writeOptions=writeOptions, ) self._data.sort() log.info(f"Sorting took {now() - t0:.1f} seconds") self._sort = True self._iter = self._loadedEntryGen() @classmethod def detectInputFormat(cls, *args, **kwargs): try: return GlossaryCommon.detectInputFormat(*args, **kwargs) except Error as e: log.critical(str(e)) return None @classmethod def detectOutputFormat(cls, *args, **kwargs): try: return GlossaryCommon.detectOutputFormat(*args, **kwargs) except Error as e: log.critical(str(e)) return None def convert( # noqa: PLR0913 self, inputFilename: str, inputFormat: str = "", direct: "bool | None" = None, progressbar: bool = True, outputFilename: str = "", outputFormat: str = "", sort: "bool | None" = None, sortKeyName: "str | None" = None, sortEncoding: "str | None" = None, readOptions: "dict[str, Any] | None" = None, writeOptions: "dict[str, Any] | None" = None, sqlite: "bool | None" = None, infoOverride: "dict[str, str] | None" = None, ) -> str | None: self.progressbar = progressbar try: return GlossaryCommon.convertV2( self, ConvertArgs( inputFilename=inputFilename, inputFormat=inputFormat, direct=direct, outputFilename=outputFilename, outputFormat=outputFormat, sort=sort, sortKeyName=sortKeyName, sortEncoding=sortEncoding, readOptions=readOptions, writeOptions=writeOptions, sqlite=sqlite, infoOverride=infoOverride, ), ) except ReadError as e: log.critical(str(e)) log.critical(f"Reading file {relpath(inputFilename)!r} failed.") except WriteError as e: log.critical(str(e)) log.critical(f"Writing file {relpath(outputFilename)!r} failed.") except Error as e: log.critical(str(e)) self.cleanup() return None
5,286
Python
.py
173
27.33526
82
0.719961
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,722
flags.py
ilius_pyglossary/pyglossary/flags.py
from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import TypeAlias __all__ = [ "ALWAYS", "DEFAULT_NO", "DEFAULT_YES", "NEVER", "StrWithDesc", "YesNoAlwaysNever", "flagsByName", ] flagsByName = {} class StrWithDesc(str): desc: str __slots__ = ["desc"] def __new__(cls: type, name: str, desc: str) -> StrWithDesc: s: StrWithDesc = str.__new__(cls, name) s.desc = desc flagsByName[name] = s return s ALWAYS = StrWithDesc("always", "Always") DEFAULT_YES = StrWithDesc("default_yes", "Yes (by default)") DEFAULT_NO = StrWithDesc("default_no", "No (by default)") NEVER = StrWithDesc("never", "Never") # to satisfy mypy: YesNoAlwaysNever: TypeAlias = StrWithDesc
733
Python
.py
28
24.142857
61
0.709353
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,723
sq_entry_list.py
ilius_pyglossary/pyglossary/sq_entry_list.py
# -*- coding: utf-8 -*- # # Copyright © 2008-2022 Saeed Rasooli <saeed.gnu@gmail.com> (ilius) # This file is part of PyGlossary project, https://github.com/ilius/pyglossary # # This program is a free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program. Or on Debian systems, from /usr/share/common-licenses/GPL # If not, see <http://www.gnu.org/licenses/gpl.txt>. from __future__ import annotations import logging import os from os.path import isfile from pickle import dumps, loads from typing import TYPE_CHECKING from .glossary_utils import Error if TYPE_CHECKING: from collections.abc import Callable, Iterable, Iterator from typing import Any from .glossary_types import EntryType, RawEntryType from .sort_keys import NamedSortKey # from typing import Self # typing.Self is new in Python 3.11. __all__ = ["SqEntryList"] log = logging.getLogger("pyglossary") PICKLE_PROTOCOL = 4 # Pickle protocol 4 performed better than protocol 5 on Python 3.9.2 # Slightly lower running time, lower memory usage, and same .db file size # Pickle protocol 5 added in Python 3.8 PEP 574 # Pickle protocol 4 added in Python 3.4 PEP 3154 # Pickle Protocol 3 added in Python 3.0 # https://docs.python.org/3/library/pickle.html class SqEntryList: def __init__( # noqa: PLR0913 self, entryToRaw: "Callable[[EntryType], RawEntryType]", entryFromRaw: "Callable[[RawEntryType], EntryType]", filename: str, create: bool = True, persist: bool = False, ) -> None: """ sqliteSortKey[i] == (name, type, valueFunc). persist: do not delete the file when variable is deleted """ import sqlite3 self._entryToRaw = entryToRaw self._entryFromRaw = entryFromRaw self._filename = filename self._persist = persist self._con: "sqlite3.Connection | None" = sqlite3.connect(filename) self._cur: "sqlite3.Cursor | None" = self._con.cursor() if not filename: raise ValueError(f"invalid {filename=}") self._orderBy = "rowid" self._sorted = False self._reverse = False self._len = 0 self._create = create self._sqliteSortKey = None self._columnNames = "" @property def rawEntryCompress(self) -> bool: return False @rawEntryCompress.setter def rawEntryCompress(self, enable: bool) -> None: # just to comply with EntryListType pass def setSortKey( self, namedSortKey: NamedSortKey, sortEncoding: "str | None", writeOptions: "dict[str, Any]", ) -> None: """sqliteSortKey[i] == (name, type, valueFunc).""" if self._con is None: raise RuntimeError("self._con is None") if self._sqliteSortKey is not None: raise RuntimeError("Called setSortKey twice") if namedSortKey.sqlite is None: raise NotImplementedError( f"sort key {namedSortKey.name!r} is not supported", ) kwargs = writeOptions.copy() if sortEncoding: kwargs["sortEncoding"] = sortEncoding sqliteSortKey = namedSortKey.sqlite(**kwargs) self._sqliteSortKey = sqliteSortKey self._columnNames = ",".join(col[0] for col in sqliteSortKey) if not self._create: self._parseExistingIndex() return colDefs = ",".join( [f"{col[0]} {col[1]}" for col in sqliteSortKey] + ["pickle BLOB"], ) self._con.execute( f"CREATE TABLE data ({colDefs})", ) def __len__(self) -> int: return self._len def append(self, entry: EntryType) -> None: self._cur.execute( f"insert into data({self._columnNames}, pickle)" f" values (?{', ?' * len(self._sqliteSortKey)})", [col[2](entry.l_word) for col in self._sqliteSortKey] + [dumps(self._entryToRaw(entry), protocol=PICKLE_PROTOCOL)], ) self._len += 1 def __iadd__(self, other: Iterable): # -> Self for item in other: self.append(item) return self def sort(self, reverse: bool = False) -> None: if self._sorted: raise NotImplementedError("can not sort more than once") if self._sqliteSortKey is None: raise RuntimeError("self._sqliteSortKey is None") self._reverse = reverse self._sorted = True sortColumnNames = self._columnNames self._orderBy = sortColumnNames if reverse: self._orderBy = ",".join(f"{col[0]} DESC" for col in self._sqliteSortKey) self._con.commit() self._con.execute( f"CREATE INDEX sortkey ON data({sortColumnNames});", ) self._con.commit() def _parseExistingIndex(self) -> bool: if self._cur is None: return False self._cur.execute("select sql FROM sqlite_master WHERE name='sortkey'") row = self._cur.fetchone() if row is None: return False sql = row[0] # sql == "CREATE INDEX sortkey ON data(wordlower,word)" i = sql.find("(") if i < 0: log.error(f"error parsing index {sql=}") return False j = sql.find(")", i) if j < 0: log.error(f"error parsing index {sql=}") return False columnNames = sql[i + 1 : j] self._sorted = True self._orderBy = columnNames return True def deleteAll(self) -> None: if self._con is None: return self._con.execute("DELETE FROM data;") self._con.commit() self._len = 0 def clear(self) -> None: self.close() def close(self) -> None: if self._con is None or self._cur is None: return self._con.commit() self._cur.close() self._con.close() self._con = None self._cur = None def __del__(self) -> None: try: self.close() if not self._persist and isfile(self._filename): os.remove(self._filename) except AttributeError as e: log.error(str(e)) def __iter__(self) -> Iterator[EntryType]: if self._cur is None: raise Error("SQLite cursor is closed") query = f"SELECT pickle FROM data ORDER BY {self._orderBy}" self._cur.execute(query) entryFromRaw = self._entryFromRaw for row in self._cur: yield entryFromRaw(loads(row[0]))
6,156
Python
.py
189
29.687831
78
0.715708
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,724
json_utils.py
ilius_pyglossary/pyglossary/json_utils.py
from __future__ import annotations import json from collections import OrderedDict from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import AnyStr, TypeAlias __all__ = ["dataToPrettyJson", "jsonToData", "jsonToOrderedData"] JsonEncodable: TypeAlias = "dict | list" # OrderedDict is also subclass of Dict, issubclass(OrderedDict, Dict) is True def dataToPrettyJson( data: JsonEncodable, ensure_ascii: bool = False, sort_keys: bool = False, ) -> str: return json.dumps( data, sort_keys=sort_keys, indent="\t", ensure_ascii=ensure_ascii, ) def jsonToData(st: AnyStr) -> JsonEncodable: return json.loads(st) def jsonToOrderedData(text: str) -> OrderedDict: return json.JSONDecoder( object_pairs_hook=OrderedDict, ).decode(text)
766
Python
.py
26
27.346154
77
0.775342
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,725
iter_utils.py
ilius_pyglossary/pyglossary/iter_utils.py
# Copyright (c) 2019 Saeed Rasooli # Copyright (c) 2012 Erik Rose # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: from collections.abc import Iterable, Iterator from typing import Any __all__ = ["unique_everseen"] # from https://github.com/erikrose/more-itertools def unique_everseen(iterable: Iterable) -> Iterator: """List unique elements, preserving order. Remember all elements ever seen.""" from itertools import filterfalse # unique_everseen('AAAABBBCCDAABBB') --> A B C D seen: set[Any] = set() seen_add = seen.add for element in filterfalse(seen.__contains__, iterable): seen_add(element) yield element
1,718
Python
.py
33
50.515152
79
0.784991
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,726
persian_utils.py
ilius_pyglossary/pyglossary/persian_utils.py
# -*- coding: utf-8 -*- from __future__ import annotations from .text_utils import replacePostSpaceChar __all__ = ["faEditStr"] def faEditStr(st: str) -> str: return replacePostSpaceChar( st.replace("ي", "ی").replace("ك", "ک").replace("ۂ", "هٔ").replace("ہ", "ه"), "،", )
293
Python
.py
9
29.222222
78
0.639405
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,727
html_utils.py
ilius_pyglossary/pyglossary/html_utils.py
# -*- coding: utf-8 -*- from __future__ import annotations import logging import re __all__ = ["name2codepoint", "unescape_unicode"] log = logging.getLogger("pyglossary") re_entity = re.compile( r"&#?\w+;", ) special_chars = { "<", ">", "&", '"', "'", "\xa0", # "&#160;" or "&nbsp;" } # these are not included in html.entities.name2codepoint name2codepoint_extra = { "itilde": 0x0129, # ĩ "utilde": 0x0169, # ũ "uring": 0x016F, # ů "ycirc": 0x0177, # ŷ "wring": 0x1E98, # ẘ "yring": 0x1E99, # ẙ "etilde": 0x1EBD, # ẽ "ygrave": 0x1EF3, # ỳ "ytilde": 0x1EF9, # ỹ "ldash": 0x2013, # – "frac13": 0x2153, # ⅓ "xfrac13": 0x2153, # ⅓ "frac23": 0x2154, # ⅔ } # Use build_name2codepoint_dict function to update this dictionary name2codepoint = { "Aacute": 0x00C1, # Á "aacute": 0x00E1, # á "Acirc": 0x00C2, #  "acirc": 0x00E2, # â "acute": 0x00B4, # ´ "AElig": 0x00C6, # Æ "aelig": 0x00E6, # æ "Agrave": 0x00C0, # À "agrave": 0x00E0, # à "alefsym": 0x2135, # ℵ "Alpha": 0x0391, # Α "alpha": 0x03B1, # α "amp": 0x0026, # & "and": 0x2227, # ∧ "ang": 0x2220, # ∠ "Aring": 0x00C5, # Å "aring": 0x00E5, # å "asymp": 0x2248, # ≈ "Atilde": 0x00C3, # à "atilde": 0x00E3, # ã "Auml": 0x00C4, # Ä "auml": 0x00E4, # ä "bdquo": 0x201E, # „ "Beta": 0x0392, # Β "beta": 0x03B2, # β "brvbar": 0x00A6, # ¦ "bull": 0x2022, # • "cap": 0x2229, # ∩ "Ccedil": 0x00C7, # Ç "ccedil": 0x00E7, # ç "cedil": 0x00B8, # ¸ "cent": 0x00A2, # ¢ "Chi": 0x03A7, # Χ "chi": 0x03C7, # χ "circ": 0x02C6, # ˆ "clubs": 0x2663, # ♣ "cong": 0x2245, # ≅ "copy": 0x00A9, # © "crarr": 0x21B5, # ↵ "cup": 0x222A, # ∪ "curren": 0x00A4, # ¤ "Dagger": 0x2021, # ‡ "dagger": 0x2020, # † "dArr": 0x21D3, # ⇓ "darr": 0x2193, # ↓ "deg": 0x00B0, # ° "Delta": 0x0394, # Δ "delta": 0x03B4, # δ "diams": 0x2666, # ♦ "divide": 0x00F7, # ÷ "Eacute": 0x00C9, # É "eacute": 0x00E9, # é "Ecirc": 0x00CA, # Ê "ecirc": 0x00EA, # ê "Egrave": 0x00C8, # È "egrave": 0x00E8, # è "empty": 0x2205, # ∅ "emsp": 0x2003, "ensp": 0x2002, "Epsilon": 0x0395, # Ε "epsilon": 0x03B5, # ε "equiv": 0x2261, # ≡ "Eta": 0x0397, # Η "eta": 0x03B7, # η "ETH": 0x00D0, # Ð "eth": 0x00F0, # ð "etilde": 0x1EBD, # ẽ "Euml": 0x00CB, # Ë "euml": 0x00EB, # ë "euro": 0x20AC, # € "exist": 0x2203, # ∃ "fnof": 0x0192, # ƒ "forall": 0x2200, # ∀ "frac12": 0x00BD, # ½ "frac13": 0x2153, # ⅓ "frac14": 0x00BC, # ¼ "frac23": 0x2154, # ⅔ "frac34": 0x00BE, # ¾ "frasl": 0x2044, # ⁄ "Gamma": 0x0393, # Γ "gamma": 0x03B3, # γ "ge": 0x2265, # ≥ "gt": 0x003E, # > "hArr": 0x21D4, # ⇔ "harr": 0x2194, # ↔ "hearts": 0x2665, # ♥ "hellip": 0x2026, # … "Iacute": 0x00CD, # Í "iacute": 0x00ED, # í "Icirc": 0x00CE, # Î "icirc": 0x00EE, # î "iexcl": 0x00A1, # ¡ "Igrave": 0x00CC, # Ì "igrave": 0x00EC, # ì "image": 0x2111, # ℑ "infin": 0x221E, # ∞ "int": 0x222B, # ∫ "Iota": 0x0399, # Ι "iota": 0x03B9, # ι "iquest": 0x00BF, # ¿ "isin": 0x2208, # ∈ "itilde": 0x0129, # ĩ "Iuml": 0x00CF, # Ï "iuml": 0x00EF, # ï "Kappa": 0x039A, # Κ "kappa": 0x03BA, # κ "Lambda": 0x039B, # Λ "lambda": 0x03BB, # λ "lang": 0x2329, # 〈 "laquo": 0x00AB, # « "lArr": 0x21D0, # ⇐ "larr": 0x2190, # ← "lceil": 0x2308, # ⌈ "ldash": 0x2013, # – "ldquo": 0x201C, # “ "le": 0x2264, # ≤ "lfloor": 0x230A, # ⌊ "lowast": 0x2217, # ∗ "loz": 0x25CA, # ◊ "lrm": 0x200E, # ‎ "lsaquo": 0x2039, # ‹ "lsquo": 0x2018, # ‘ "lt": 0x003C, # < "macr": 0x00AF, # ¯ "mdash": 0x2014, # — "micro": 0x00B5, # µ "middot": 0x00B7, # · "minus": 0x2212, # − "Mu": 0x039C, # Μ "mu": 0x03BC, # μ "nabla": 0x2207, # ∇ "nbsp": 0x00A0, # space "ndash": 0x2013, # – "ne": 0x2260, # ≠ "ni": 0x220B, # ∋ "not": 0x00AC, # ¬ "notin": 0x2209, # ∉ "nsub": 0x2284, # ⊄ "Ntilde": 0x00D1, # Ñ "ntilde": 0x00F1, # ñ "Nu": 0x039D, # Ν "nu": 0x03BD, # ν "Oacute": 0x00D3, # Ó "oacute": 0x00F3, # ó "Ocirc": 0x00D4, # Ô "ocirc": 0x00F4, # ô "OElig": 0x0152, # Œ "oelig": 0x0153, # œ "Ograve": 0x00D2, # Ò "ograve": 0x00F2, # ò "oline": 0x203E, # ‾ "Omega": 0x03A9, # Ω "omega": 0x03C9, # ω "Omicron": 0x039F, # Ο "omicron": 0x03BF, # ο "oplus": 0x2295, # ⊕ "or": 0x2228, # ∨ "ordf": 0x00AA, # ª "ordm": 0x00BA, # º "Oslash": 0x00D8, # Ø "oslash": 0x00F8, # ø "Otilde": 0x00D5, # Õ "otilde": 0x00F5, # õ "otimes": 0x2297, # ⊗ "Ouml": 0x00D6, # Ö "ouml": 0x00F6, # ö "para": 0x00B6, # ¶ "part": 0x2202, # ∂ "permil": 0x2030, # ‰ "perp": 0x22A5, # ⊥ "Phi": 0x03A6, # Φ "phi": 0x03C6, # φ "Pi": 0x03A0, # Π "pi": 0x03C0, # π "piv": 0x03D6, # ϖ "plusmn": 0x00B1, # ± "pound": 0x00A3, # £ "Prime": 0x2033, # ″ "prime": 0x2032, # ′ "prod": 0x220F, # ∏ "prop": 0x221D, # ∝ "Psi": 0x03A8, # Ψ "psi": 0x03C8, # ψ "quot": 0x0022, # " "radic": 0x221A, # √ "rang": 0x232A, # 〉 "raquo": 0x00BB, # » "rArr": 0x21D2, # ⇒ "rarr": 0x2192, # → "rceil": 0x2309, # ⌉ "rdquo": 0x201D, # ” "real": 0x211C, # ℜ "reg": 0x00AE, # ® "rfloor": 0x230B, # ⌋ "Rho": 0x03A1, # Ρ "rho": 0x03C1, # ρ "rlm": 0x200F, # U+200F "rsaquo": 0x203A, # › "rsquo": 0x2019, # ’ "sbquo": 0x201A, # ‚ "Scaron": 0x0160, # Š "scaron": 0x0161, # š "sdot": 0x22C5, # ⋅ "sect": 0x00A7, # § "shy": 0x00AD, # ­ "Sigma": 0x03A3, # Σ "sigma": 0x03C3, # σ "sigmaf": 0x03C2, # ς "sim": 0x223C, # ∼ "spades": 0x2660, # ♠ "sub": 0x2282, # ⊂ "sube": 0x2286, # ⊆ "sum": 0x2211, # ∑ "sup": 0x2283, # ⊃ "sup1": 0x00B9, # ¹ "sup2": 0x00B2, # ² "sup3": 0x00B3, # ³ "supe": 0x2287, # ⊇ "szlig": 0x00DF, # ß "Tau": 0x03A4, # Τ "tau": 0x03C4, # τ "there4": 0x2234, # ∴ "Theta": 0x0398, # Θ "theta": 0x03B8, # θ "thetasym": 0x03D1, # ϑ "thinsp": 0x2009, "THORN": 0x00DE, # Þ "thorn": 0x00FE, # þ "tilde": 0x02DC, # ˜ "times": 0x00D7, # × "trade": 0x2122, # ™ "Uacute": 0x00DA, # Ú "uacute": 0x00FA, # ú "uArr": 0x21D1, # ⇑ "uarr": 0x2191, # ↑ "Ucirc": 0x00DB, # Û "ucirc": 0x00FB, # û "Ugrave": 0x00D9, # Ù "ugrave": 0x00F9, # ù "uml": 0x00A8, # ¨ "upsih": 0x03D2, # ϒ "Upsilon": 0x03A5, # Υ "upsilon": 0x03C5, # υ "uring": 0x016F, # ů "utilde": 0x0169, # ũ "Uuml": 0x00DC, # Ü "uuml": 0x00FC, # ü "weierp": 0x2118, # ℘ "wring": 0x1E98, # ẘ "xfrac13": 0x2153, # ⅓ "Xi": 0x039E, # Ξ "xi": 0x03BE, # ξ "Yacute": 0x00DD, # Ý "yacute": 0x00FD, # ý "ycirc": 0x0177, # ŷ "yen": 0x00A5, # ¥ "ygrave": 0x1EF3, # ỳ "yring": 0x1E99, # ẙ "ytilde": 0x1EF9, # ỹ "Yuml": 0x0178, # Ÿ "yuml": 0x00FF, # ÿ "Zeta": 0x0396, # Ζ "zeta": 0x03B6, # ζ "zwj": 0x200D, # ‍ "zwnj": 0x200C, # ‌ } def build_name2codepoint_dict() -> None: """ Build name -> codepoint dictionary copy and paste the output to the name2codepoint dictionary name2str - name to utf-8 string dictionary. """ import html.entities name2str = {} for k, v in name2codepoint_extra.items(): name2str[k] = chr(v) for k, v in html.entities.name2codepoint.items(): name2str[k] = chr(v) for key in sorted(name2str, key=lambda s: (s.lower(), s)): value = name2str[key] if len(value) > 1: raise ValueError(f"{value = }") print(f'\t"{key}": 0x{ord(value):0>4x}, # {value}') # noqa: T201 def _sub_unescape_unicode(m: "re.Match") -> str: text = m.group(0) if text[:2] == "&#": # character reference code = int(text[3:-1], 16) if text.startswith("&#x") else int(text[2:-1]) try: char = chr(code) except ValueError: return text if char not in special_chars: return char return text # named entity name = text[1:-1] if name in name2codepoint: char = chr(name2codepoint[name]) if char not in special_chars: return char return text def unescape_unicode(text: str) -> str: """ Unscape unicode entities, but not "&lt;", "&gt;" and "&amp;" leave these 3 special entities alone, since unescaping them creates invalid html we also ignore quotations: "&quot;" and "&#x27;". """ return re_entity.sub(_sub_unescape_unicode, text) if __name__ == "__main__": build_name2codepoint_dict()
8,575
Python
.py
347
21.559078
75
0.558805
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,728
info_writer.py
ilius_pyglossary/pyglossary/info_writer.py
from __future__ import annotations from collections.abc import Generator from os.path import splitext from typing import TYPE_CHECKING from pyglossary.core import log from pyglossary.io_utils import nullTextIO if TYPE_CHECKING: import io from pyglossary.glossary_types import ( EntryType, GlossaryType, ) class InfoWriter: def __init__(self, glos: GlossaryType) -> None: self._glos = glos self._filename = "" self._file: "io.TextIOBase" = nullTextIO def open(self, filename: str) -> None: self._filename = filename self._file = open(filename, mode="w", encoding="utf-8") def finish(self) -> None: self._filename = "" self._file.close() self._file = nullTextIO def write(self) -> Generator[None, EntryType, None]: # noqa: PLR0912, C901 import re from collections import Counter, OrderedDict from pyglossary.json_utils import dataToPrettyJson from pyglossary.langs.writing_system import getWritingSystemFromText glos = self._glos re_possible_html = re.compile( r"<[a-z1-6]+[ />]", re.IGNORECASE, ) re_style = re.compile( r"<([a-z1-6]+)[^<>]* style=", re.IGNORECASE | re.DOTALL, ) wordCount = 0 bwordCount = 0 nonLowercaseWordCount = 0 styleByTagCounter: "dict[str, int]" = Counter() defiFormatCounter: "dict[str, int]" = Counter() firstTagCounter: "dict[str, int]" = Counter() allTagsCounter: "dict[str, int]" = Counter() sourceScriptCounter: "dict[str, int]" = Counter() dataEntryExtCounter: "dict[str, int]" = Counter() while True: entry = yield if entry is None: break defi = entry.defi wordCount += 1 bwordCount += defi.count("bword://") for word in entry.l_word: if word.lower() != word: nonLowercaseWordCount += 1 for m in re_style.finditer(defi): tag = m.group(1) styleByTagCounter[tag] += 1 entry.detectDefiFormat() defiFormat = entry.defiFormat defiFormatCounter[defiFormat] += 1 if defiFormat == "m": if re_possible_html.match(defi): log.warning(f"undetected html defi: {defi}") elif defiFormat == "h": match = re_possible_html.search(defi) if match is not None: firstTagCounter[match.group().strip("< />").lower()] += 1 for tag in re_possible_html.findall(defi): allTagsCounter[tag.strip("< />").lower()] += 1 elif defiFormat == "b": _filenameNoExt, ext = splitext(entry.s_word) ext = ext.lstrip(".") dataEntryExtCounter[ext] += 1 ws = getWritingSystemFromText(entry.s_word) if ws: wsName = ws.name else: log.debug(f"No script detected for word: {entry.s_word}") wsName = "None" sourceScriptCounter[wsName] += 1 data_entry_count = defiFormatCounter["b"] del defiFormatCounter["b"] info = OrderedDict() for key, value in glos.iterInfo(): info[key] = value info["word_count"] = wordCount info["bword_count"] = bwordCount info["non_lowercase_word_count"] = nonLowercaseWordCount info["data_entry_count"] = data_entry_count info["data_entry_extension_count"] = ", ".join( f"{ext}={count}" for ext, count in dataEntryExtCounter.most_common() ) info["defi_format"] = ", ".join( f"{defiFormat}={count}" for defiFormat, count in sorted(defiFormatCounter.items()) ) info["defi_tag"] = ", ".join( f"{defiFormat}={count}" for defiFormat, count in allTagsCounter.most_common() ) info["defi_first_tag"] = ", ".join( f"{defiFormat}={count}" for defiFormat, count in firstTagCounter.most_common() ) info["style"] = ", ".join( f"{defiFormat}={count}" for defiFormat, count in styleByTagCounter.most_common() ) info["source_script"] = ", ".join( f"{defiFormat}={count}" for defiFormat, count in sourceScriptCounter.most_common() ) info["read_options"] = glos.readOptions self._file.write(dataToPrettyJson(info) + "\n")
3,821
Python
.py
117
29.017094
76
0.688943
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,729
text_reader.py
ilius_pyglossary/pyglossary/text_reader.py
from __future__ import annotations import io import logging import os import typing from os.path import isdir, isfile, join, splitext from typing import TYPE_CHECKING, cast if TYPE_CHECKING: from collections.abc import Generator, Iterator from pyglossary.entry_base import MultiStr from pyglossary.glossary_types import EntryType, GlossaryType from pyglossary.compression import ( compressionOpen, stdCompressions, ) from pyglossary.entry import DataEntry from pyglossary.io_utils import nullTextIO __all__ = ["TextFilePosWrapper", "TextGlossaryReader", "nextBlockResultType"] log = logging.getLogger("pyglossary") nextBlockResultType: "typing.TypeAlias" = ( "tuple[str | list[str], str, list[tuple[str, str]] | None] | None" ) # ( # word: str | list[str], # defi: str, # images: list[tuple[str, str]] | None # ) class TextFilePosWrapper(io.TextIOBase): def __init__(self, fileobj: "io.TextIOBase", encoding: str) -> None: self.fileobj = fileobj self._encoding = encoding self.pos = 0 def __iter__(self) -> Iterator[str]: # type: ignore return self def close(self) -> None: self.fileobj.close() def __next__(self) -> str: # type: ignore line = self.fileobj.__next__() self.pos += len(line.encode(self._encoding)) return line def tell(self) -> int: return self.pos class TextGlossaryReader: _encoding: str = "utf-8" compressions = stdCompressions def __init__(self, glos: GlossaryType, hasInfo: bool = True) -> None: self._glos = glos self._filename = "" self._file: "io.TextIOBase" = nullTextIO self._hasInfo = hasInfo self._pendingEntries: list[EntryType] = [] self._wordCount = 0 self._fileSize = 0 self._pos = -1 self._fileCount = 1 self._fileIndex = -1 self._bufferLine = "" self._resDir = "" self._resFileNames: list[str] = [] def _setResDir(self, resDir: str) -> bool: if isdir(resDir): self._resDir = resDir self._resFileNames = os.listdir(self._resDir) return True return False def detectResDir(self, filename: str) -> bool: if self._setResDir(f"{filename}_res"): return True filenameNoExt, ext = splitext(filename) ext = ext.lstrip(".") if ext not in self.compressions: return False return self._setResDir(f"{filenameNoExt}_res") def readline(self) -> str: if self._bufferLine: line = self._bufferLine self._bufferLine = "" return line try: return next(self._file) except StopIteration: return "" def _openGen(self, filename: str) -> Iterator[tuple[int, int]]: self._fileIndex += 1 log.info(f"Reading file: {filename}") cfile = cast( "io.TextIOBase", compressionOpen( filename, mode="rt", encoding=self._encoding, ), ) if not self._wordCount: if cfile.seekable(): cfile.seek(0, 2) self._fileSize = cfile.tell() cfile.seek(0) log.debug(f"File size of {filename}: {self._fileSize}") self._glos.setInfo("input_file_size", f"{self._fileSize}") else: log.warning("TextGlossaryReader: file is not seekable") self._file = TextFilePosWrapper(cfile, self._encoding) if self._hasInfo: yield from self.loadInfo() self.detectResDir(filename) def _open(self, filename: str) -> None: for _ in self._openGen(filename): pass def open(self, filename: str) -> Iterator[tuple[int, int]] | None: self._filename = filename self._open(filename) return None def openGen(self, filename: str) -> Iterator[tuple[int, int]]: """ Like open() but return a generator / iterator to track the progress example for reader.open: yield from TextGlossaryReader.openGen(self, filename). """ self._filename = filename yield from self._openGen(filename) def openNextFile(self) -> bool: self.close() nextFilename = f"{self._filename}.{self._fileIndex + 1}" if isfile(nextFilename): self._open(nextFilename) return True for ext in self.compressions: if isfile(f"{nextFilename}.{ext}"): self._open(f"{nextFilename}.{ext}") return True if self._fileCount != -1: log.warning(f"next file not found: {nextFilename}") return False def close(self) -> None: try: self._file.close() except Exception: log.exception(f"error while closing file {self._filename!r}") self._file = nullTextIO def newEntry(self, word: MultiStr, defi: str) -> EntryType: byteProgress: "tuple[int, int] | None" = None if self._fileSize and self._file is not None: byteProgress = (self._file.tell(), self._fileSize) return self._glos.newEntry( word, defi, byteProgress=byteProgress, ) def setInfo(self, key: str, value: str) -> None: self._glos.setInfo(key, value) def _loadNextInfo(self) -> bool: """Returns True when reached the end.""" block = self.nextBlock() if not block: return False key, value, _ = block origKey = key if isinstance(key, list): key = key[0] if not self.isInfoWords(key): self._pendingEntries.append(self.newEntry(origKey, value)) return True if not value: return False key = self.fixInfoWord(key) if not key: return False self.setInfo(key, value) return False def loadInfo(self) -> Generator[tuple[int, int], None, None]: self._pendingEntries = [] try: while True: if self._loadNextInfo(): break yield (self._file.tell(), self._fileSize) except StopIteration: pass if self._fileIndex == 0: fileCountStr = self._glos.getInfo("file_count") if fileCountStr: self._fileCount = int(fileCountStr) self._glos.setInfo("file_count", "") @staticmethod def _genDataEntries( resList: list[tuple[str, str]], resPathSet: set[str], ) -> Iterator[DataEntry]: for relPath, fullPath in resList: if relPath in resPathSet: continue resPathSet.add(relPath) yield DataEntry( fname=relPath, tmpPath=fullPath, ) def __iter__(self) -> Iterator[EntryType | None]: resPathSet: set[str] = set() while True: self._pos += 1 if self._pendingEntries: yield self._pendingEntries.pop(0) continue ### try: block = self.nextBlock() except StopIteration: if self._fileCount == -1 or ( self._fileIndex < self._fileCount - 1 and self.openNextFile() ): continue self._wordCount = self._pos break if not block: yield None continue word, defi, resList = block if resList: yield from self._genDataEntries(resList, resPathSet) yield self.newEntry(word, defi) resDir = self._resDir for fname in self._resFileNames: fpath = join(resDir, fname) if not isfile(fpath): log.error(f"No such file: {fpath}") continue with open(fpath, "rb") as _file: yield self._glos.newDataEntry( fname, _file.read(), ) def __len__(self) -> int: return self._wordCount @classmethod def isInfoWord(cls, word: str) -> bool: raise NotImplementedError def isInfoWords(self, arg: "str | list[str]") -> bool: if isinstance(arg, str): return self.isInfoWord(arg) if isinstance(arg, list): return self.isInfoWord(arg[0]) raise TypeError(f"bad argument {arg}") @classmethod def fixInfoWord(cls, word: str) -> str: raise NotImplementedError def nextBlock(self) -> nextBlockResultType: raise NotImplementedError
7,186
Python
.py
248
25.596774
77
0.700609
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,730
glossary_info.py
ilius_pyglossary/pyglossary/glossary_info.py
# -*- coding: utf-8 -*- # # Copyright © 2008-2022 Saeed Rasooli <saeed.gnu@gmail.com> (ilius) # This file is part of PyGlossary project, https://github.com/ilius/pyglossary # # This program is a free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program. Or on Debian systems, from /usr/share/common-licenses/GPL # If not, see <http://www.gnu.org/licenses/gpl.txt>. from __future__ import annotations import logging from collections import OrderedDict as odict from typing import TYPE_CHECKING if TYPE_CHECKING: from collections.abc import Iterator from .info import ( c_author, c_name, c_publisher, c_sourceLang, c_targetLang, infoKeysAliasDict, ) from .langs import Lang, langDict from .text_utils import ( fixUtf8, ) __all__ = ["GlossaryInfo"] log = logging.getLogger("pyglossary") class GlossaryInfo: def __init__(self) -> None: self._info: "dict[str, str]" = odict() def infoKeys(self) -> list[str]: return list(self._info) # def formatInfoKeys(self, format: str):# FIXME def iterInfo(self) -> Iterator[tuple[str, str]]: return iter(self._info.items()) def getInfo(self, key: str) -> str: if not isinstance(key, str): raise TypeError(f"invalid {key=}, must be str") return self._info.get( infoKeysAliasDict.get(key.lower(), key), "", ) def setInfo(self, key: str, value: "str | None") -> None: if value is None: try: del self._info[key] except KeyError: pass return if not isinstance(key, str): raise TypeError(f"invalid {key=}, must be str") key = fixUtf8(key) value = fixUtf8(str(value)) key = infoKeysAliasDict.get(key.lower(), key) self._info[key] = value def getExtraInfos(self, excludeKeys: list[str]) -> odict: """ excludeKeys: a list of (basic) info keys to be excluded returns an OrderedDict including the rest of info keys, with associated values. """ excludeKeySet = set() for key in excludeKeys: excludeKeySet.add(key) key2 = infoKeysAliasDict.get(key.lower()) if key2: excludeKeySet.add(key2) extra = odict() for key, value in self._info.items(): if key in excludeKeySet: continue extra[key] = value return extra @property def author(self) -> str: for key in (c_author, c_publisher): value = self._info.get(key, "") if value: return value return "" @staticmethod def _getLangByStr(st: str) -> Lang | None: lang = langDict[st] if lang: return lang log.error(f"unknown language {st!r}") return None def _getLangByInfoKey(self, key: str) -> Lang | None: st = self._info.get(key, "") if not st: return None return self._getLangByStr(st) @property def sourceLang(self) -> Lang | None: return self._getLangByInfoKey(c_sourceLang) @sourceLang.setter def sourceLang(self, lang: Lang) -> None: if not isinstance(lang, Lang): raise TypeError(f"invalid {lang=}, must be a Lang object") self._info[c_sourceLang] = lang.name @property def targetLang(self) -> Lang | None: return self._getLangByInfoKey(c_targetLang) @targetLang.setter def targetLang(self, lang: Lang) -> None: if not isinstance(lang, Lang): raise TypeError(f"invalid {lang=}, must be a Lang object") self._info[c_targetLang] = lang.name @property def sourceLangName(self) -> str: lang = self.sourceLang if lang is None: return "" return lang.name @sourceLangName.setter def sourceLangName(self, langName: str) -> None: if not langName: self._info[c_sourceLang] = "" return lang = self._getLangByStr(langName) if lang is None: return self._info[c_sourceLang] = lang.name @property def targetLangName(self) -> str: lang = self.targetLang if lang is None: return "" return lang.name @targetLangName.setter def targetLangName(self, langName: str) -> None: if not langName: self._info[c_targetLang] = "" return lang = self._getLangByStr(langName) if lang is None: return self._info[c_targetLang] = lang.name def titleTag(self, sample: str) -> str: from .langs.writing_system import getWritingSystemFromText ws = getWritingSystemFromText(sample) if ws and ws.name != "Latin": return ws.titleTag sourceLang = self.sourceLang if sourceLang: return sourceLang.titleTag return "b" def detectLangsFromName(self) -> None: """Extract sourceLang and targetLang from glossary name/title.""" import re name = self._info.get(c_name) if not name: return if self._info.get(c_sourceLang): return langNames = [] def checkPart(part: str) -> None: for match in re.findall(r"\w\w\w*", part): # print(f"{match = }") lang = langDict[match] if lang is None: continue langNames.append(lang.name) for part in re.split("-| to ", name): # print(f"{part = }") checkPart(part) if len(langNames) >= 2: # noqa: PLR2004 break if len(langNames) < 2: # noqa: PLR2004 return if len(langNames) > 2: # noqa: PLR2004 log.info(f"detectLangsFromName: {langNames = }") log.info( f"Detected sourceLang={langNames[0]!r}, " f"targetLang={langNames[1]!r} " f"from glossary name {name!r}", ) self.sourceLangName = langNames[0] self.targetLangName = langNames[1]
5,666
Python
.py
190
26.805263
78
0.713261
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,731
plugin_prop.py
ilius_pyglossary/pyglossary/plugin_prop.py
# -*- coding: utf-8 -*- # # Copyright © 2022 Saeed Rasooli <saeed.gnu@gmail.com> (ilius) # This file is part of PyGlossary project, https://github.com/ilius/pyglossary # # This program is a free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program. Or on Debian systems, from /usr/share/common-licenses/GPL # If not, see <http://www.gnu.org/licenses/gpl.txt>. from __future__ import annotations import logging from collections import OrderedDict as odict from typing import TYPE_CHECKING if TYPE_CHECKING: import pathlib from typing import Any from .flags import StrWithDesc from . import core from .flags import ( DEFAULT_NO, YesNoAlwaysNever, flagsByName, ) from .option import Option, optionFromDict __all__ = ["PluginProp"] log = logging.getLogger("pyglossary") def optionsPropFromDict( optionsPropDict: "dict[str, Any]", ) -> dict[str, Option]: props = {} for name, propDict in optionsPropDict.items(): try: prop = optionFromDict(propDict) except Exception: log.exception(f"{name=}, {propDict=}\n") continue props[name] = prop return props def sortOnWriteFromStr(sortOnWriteStr: "str | None") -> StrWithDesc: if sortOnWriteStr is None: return DEFAULT_NO return flagsByName[sortOnWriteStr] class PluginCheckError(Exception): pass class PluginProp: # noqa: PLR0904 __slots__ = [ "_Reader", "_ReaderLoaded", "_Writer", "_WriterLoaded", "_canRead", "_canWrite", "_description", "_enable", "_extensionCreate", "_extensions", "_lname", "_mod", "_moduleName", "_modulePath", "_name", "_optionsProp", "_readCompressions", "_readDepends", "_readOptions", "_singleFile", "_sortKeyName", "_sortOnWrite", "_writeDepends", "_writeOptions", ] def __init__(self) -> None: self._mod: Any self._Reader: Any self._ReaderLoaded: bool self._Writer: Any self._WriterLoaded: bool self._moduleName: str self._modulePath: str self._enable: bool self._lname: str self._name: str self._description: str self._extensions: list[str] self._extensionCreate: str self._singleFile: bool self._optionsProp: "dict[str, Option]" self._sortOnWrite: YesNoAlwaysNever self._sortKeyName: "str | None" self._canRead: bool self._canWrite: bool self._readOptions: "dict[str, Any]" self._writeOptions: "dict[str, Any]" self._readCompressions: list[str] self._readDepends: "dict[str, str]" self._writeDepends: "dict[str, str]" @classmethod def fromDict( cls: type, attrs: "dict[str, Any]", modulePath: str, ) -> None: self = cls() self._mod = None self._Reader = None self._ReaderLoaded = False self._Writer = None self._WriterLoaded = False self._moduleName = attrs["module"] self._modulePath = modulePath self._enable = attrs.get("enable", True) self._lname = attrs["lname"] self._name = attrs["name"] self._description = attrs["description"] self._extensions = attrs["extensions"] self._extensionCreate = attrs.get("extensionCreate", "") self._singleFile = attrs["singleFile"] self._optionsProp = optionsPropFromDict(attrs["optionsProp"]) self._sortOnWrite = sortOnWriteFromStr(attrs.get("sortOnWrite")) self._sortKeyName = attrs.get("sortKeyName") self._canRead = attrs["canRead"] self._canWrite = attrs["canWrite"] self._readOptions = attrs.get("readOptions", {}) self._writeOptions = attrs.get("writeOptions", {}) self._readCompressions = attrs.get("readCompressions", []) self._readDepends = attrs.get("readDepends", {}) self._writeDepends = attrs.get("writeDepends", {}) return self @classmethod def fromModule(cls: type, mod: Any) -> PluginProp: self = cls() self._mod = mod self._Reader = None self._ReaderLoaded = False self._Writer = None self._WriterLoaded = False self._moduleName = mod.__name__ self._modulePath = mod.__file__ if self._modulePath.endswith("__init__.py"): self._modulePath = self._modulePath[: -len("/__init__.py")] elif self._modulePath.endswith(".py"): self._modulePath = self._modulePath[:-3] self._enable = getattr(mod, "enable", True) self._lname = mod.lname self._name = mod.format self._description = mod.description self._extensions = list(mod.extensions) self._extensionCreate = getattr(mod, "extensionCreate", "") self._singleFile = getattr(mod, "singleFile", False) self._optionsProp = getattr(mod, "optionsProp", {}) self._sortOnWrite = getattr(mod, "sortOnWrite", DEFAULT_NO) self._sortKeyName = getattr(mod, "sortKeyName", None) self._canRead = hasattr(mod, "Reader") self._canWrite = hasattr(mod, "Writer") self._readOptions = None self._writeOptions = None self._readCompressions = None self._readDepends = None self._writeDepends = None if core.isDebug(): self.checkModule(mod) return self @property def enable(self) -> bool: return self._enable @property def module(self) -> Any: if self._mod is not None: return self._mod moduleName = self._moduleName log.debug(f"importing {moduleName} in DictPluginProp") try: _mod = __import__( f"pyglossary.plugins.{moduleName}", fromlist=moduleName, ) except ModuleNotFoundError as e: log.warning( f"Module {e.name!r} not found in {self._modulePath}" f", skipping plugin {moduleName!r}", ) return None except Exception: log.exception(f"Error while importing plugin {moduleName}") return None # self._mod = _mod if core.isDebug(): self.checkModule(_mod) return _mod @property def lname(self) -> str: return self._lname @property def name(self) -> str: return self._name @property def description(self) -> str: return self._description @property def extensions(self) -> list[str]: return self._extensions @property def ext(self) -> str: extensions = self.extensions if extensions: return extensions[0] return "" @property def extensionCreate(self) -> str: return self._extensionCreate @property def singleFile(self) -> bool: return self._singleFile @property def optionsProp(self) -> dict[str, Option]: return self._optionsProp @property def sortOnWrite(self) -> YesNoAlwaysNever: return self._sortOnWrite @property def sortKeyName(self) -> str | None: return self._sortKeyName @property def path(self) -> pathlib.Path: from pathlib import Path return Path(self._modulePath) @property def readerClass(self) -> Any | None: if self._ReaderLoaded: return self._Reader cls = getattr(self.module, "Reader", None) self._Reader = cls self._ReaderLoaded = True if cls is not None and core.isDebug(): self.checkReaderClass() return cls @property def writerClass(self) -> Any | None: if self._WriterLoaded: return self._Writer cls = getattr(self.module, "Writer", None) self._Writer = cls self._WriterLoaded = True if cls is not None and core.isDebug(): self.checkWriterClass() return cls @property def canRead(self) -> bool: return self._canRead @property def canWrite(self) -> bool: return self._canWrite @staticmethod def _getOptionAttrNamesFromClass(rwclass: type) -> list[str]: nameList = [] for cls in (*rwclass.__bases__, rwclass): for _name in cls.__dict__: if not _name.startswith("_") or _name.startswith("__"): # and _name not in ("_open",) continue nameList.append(_name) # rwclass.__dict__ does not include attributes of parent/base class # and dir(rwclass) is sorted by attribute name alphabetically # using rwclass.__bases__ solves the problem return nameList def _getOptionsFromClass(self, rwclass: type) -> dict[str, Any]: optionsProp = self.optionsProp options = odict() if rwclass is None: return options for attrName in self._getOptionAttrNamesFromClass(rwclass): name = attrName[1:] default = getattr(rwclass, attrName) if name not in optionsProp: if not callable(default): log.warning(f"format={self.name}, {attrName=}, {type(default)=}") continue prop = optionsProp[name] if prop.disabled: core.trace( log, f"skipping disabled option {name} in {self.name} plugin", ) continue if not prop.validate(default): log.warning( "invalid default value for option: " f"{name} = {default!r} in plugin {self.name}", ) options[name] = default return options def getReadOptions(self) -> dict[str, Any]: if self._readOptions is None: self._readOptions = self._getOptionsFromClass(self.readerClass) return self._readOptions def getWriteOptions(self) -> dict[str, Any]: if self._writeOptions is None: self._writeOptions = self._getOptionsFromClass(self.writerClass) return self._writeOptions @property def readCompressions(self) -> list[str]: if self._readCompressions is None: self._readCompressions = getattr(self.readerClass, "compressions", []) return self._readCompressions @property def readDepends(self) -> dict[str, str]: if self._readDepends is None: self._readDepends = getattr(self.readerClass, "depends", {}) return self._readDepends @property def writeDepends(self) -> dict[str, str]: if self._writeDepends is None: self._writeDepends = getattr(self.writerClass, "depends", {}) return self._writeDepends def checkModule(self, module) -> None: name = self.name if hasattr(module, "write"): log.error( f"plugin {name!r} has write function, must migrate to Writer class", ) extensions = module.extensions if not isinstance(extensions, tuple): msg = f"{name} plugin: extensions must be tuple" if isinstance(extensions, list): extensions = tuple(extensions) log.error(msg) else: raise TypeError(msg) if not isinstance(self.readDepends, dict): log.error( f"invalid depends={self.readDepends} in {self.name!r}.Reader class", ) if not isinstance(self.writeDepends, dict): log.error( f"invalid depends={self.writeDepends}" f" in {self.name!r}.Reader class", ) for name, opt in self.optionsProp.items(): if name.lower() != name: suggestName = "".join( "_" + x.lower() if x.isupper() else x for x in name ) log.debug( f"{self.name}: please rename option {name} to {suggestName}", ) if not opt.comment: log.debug( f"{self.name}: please add comment for option {name}", ) valid__all__ = [ "enable", "lname", "format", "description", "extensions", "extensionCreate", "singleFile", "kind", "wiki", "website", "optionsProp", "Reader", "Writer", ] # only run this on CI to do extra validation def checkModuleMore(self, module) -> None: name = self.name if not hasattr(module, "__all__"): raise PluginCheckError(f"Please add __all__ to plugin {name!r}") _all = module.__all__ for attr in _all: if not hasattr(module, attr): raise PluginCheckError( f"Undefined name {attr!r} in __all__ in plugin {name!r}" f": {module.__file__}", ) if attr not in self.valid__all__: raise PluginCheckError( f"Unnecessary name {attr!r} in __all__ in plugin {name!r}" f": {module.__file__}", ) def checkReaderClass(self) -> bool: cls = self._Reader for attr in ( "__init__", "open", "close", "__len__", "__iter__", ): if not hasattr(cls, attr): log.error( f"Invalid Reader class in {self.name!r} plugin" f", no {attr!r} method", ) self._Reader = None return False return True def checkWriterClass(self) -> bool: cls = self._Writer for attr in ( "__init__", "open", "write", "finish", ): if not hasattr(cls, attr): log.error( f"Invalid Writer class in {self.name!r} plugin" f", no {attr!r} method", ) self._Writer = None return False return True # def _getReadExtraOptions(self) -> list[str]: # noqa: F811 # cls = self.readerClass # if cls is None: # return [] # return self.__class__.getExtraOptionsFromFunc(cls.open, self.name) # def _getWriteExtraOptions(self) -> list[str]: # noqa: F811 # cls = self.writerClass # if cls is None: # return [] # return self.__class__.getExtraOptionsFromFunc(cls.write, self.name) # @classmethod # def getExtraOptionsFromFunc( # cls: type, # func: Callable, # format: str, # ) -> list[str]: # import inspect # extraOptNames = [] # for name, param in inspect.signature(func).parameters.items(): # if name == "self": # continue # if str(param.default) != "<class 'inspect._empty'>": # extraOptNames.append(name) # continue # if name not in {"filename", "dirname"}: # extraOptNames.append(name) # if extraOptNames: # log.warning(f"{format}: {extraOptNames = }") # return extraOptNames
13,166
Python
.py
452
25.926991
78
0.698624
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,732
image_utils.py
ilius_pyglossary/pyglossary/image_utils.py
from __future__ import annotations import base64 import logging import re from os.path import join from pyglossary.text_utils import crc32hex __all__ = ["extractInlineHtmlImages"] log = logging.getLogger("pyglossary") re_inline_image = re.compile('src="(data:image/[^<>"]*)"') def extractInlineHtmlImages( defi: str, outDir: str, fnamePrefix: str = "", ) -> tuple[str, list[tuple[str, str]]]: imageDataDict: "dict[str, bytes]" = {} def subFunc(m: "re.Match[str]") -> str: src = m.group(1)[len("data:image/") :] i = src.find(";") if i < 0: log.error(f"no semicolon, bad inline img src: {src[:60]}...") return "" imgFormat, src = src[:i], src[i + 1 :] if not src.startswith("base64,"): log.error(f"no 'base64,', bad inline img src: {src[:60]}...") return "" imgDataB64 = src[len("base64,") :] imgData = base64.b64decode(imgDataB64) imgFname = f"{fnamePrefix}{crc32hex(imgData)}.{imgFormat}" imageDataDict[imgFname] = imgData return f'src="./{imgFname}"' defi = re_inline_image.sub(subFunc, defi) images: list[tuple[str, str]] = [] for imgFname, imgData in imageDataDict.items(): imgPath = join(outDir, imgFname) with open(imgPath, mode="wb") as _file: _file.write(imgData) del imgData images.append((imgFname, imgPath)) return defi, images
1,301
Python
.py
39
30.74359
64
0.685052
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,733
sdsqlite.py
ilius_pyglossary/pyglossary/sdsqlite.py
# -*- coding: utf-8 -*- from __future__ import annotations from os.path import isfile from typing import TYPE_CHECKING from .core import log from .glossary_utils import Error if TYPE_CHECKING: import sqlite3 from collections.abc import Generator, Iterator from .glossary_types import EntryType, GlossaryType from .text_utils import ( joinByBar, splitByBar, ) class Writer: def __init__(self, glos: GlossaryType) -> None: self._glos = glos self._clear() def _clear(self) -> None: self._filename = "" self._con: "sqlite3.Connection | None" self._cur: "sqlite3.Cursor | None" def open(self, filename: str) -> None: import sqlite3 if isfile(filename): raise OSError(f"file {filename!r} already exists") self._filename = filename self._con = sqlite3.connect(filename) self._cur = self._con.cursor() self._con.execute( "CREATE TABLE dict (" "word TEXT," "wordlower TEXT," "alts TEXT," "defi TEXT," "defiFormat CHAR(1)," "bindata BLOB)", ) self._con.execute( "CREATE INDEX dict_sortkey ON dict(wordlower, word);", ) def write(self) -> Generator[None, EntryType, None]: con = self._con cur = self._cur if not (con and cur): log.error(f"write: {con=}, {cur=}") return count = 0 while True: entry = yield if entry is None: break word = entry.l_word[0] alts = joinByBar(entry.l_word[1:]) defi = entry.defi defiFormat = entry.defiFormat bindata = None if entry.isData(): bindata = entry.data cur.execute( "insert into dict(" "word, wordlower, alts, " "defi, defiFormat, bindata)" " values (?, ?, ?, ?, ?, ?)", ( word, word.lower(), alts, defi, defiFormat, bindata, ), ) count += 1 if count % 1000 == 0: con.commit() con.commit() def finish(self) -> None: if self._cur: self._cur.close() if self._con: self._con.close() self._clear() class Reader: def __init__(self, glos: GlossaryType) -> None: self._glos = glos self._clear() def _clear(self) -> None: self._filename = "" self._con: "sqlite3.Connection | None" self._cur: "sqlite3.Cursor | None" def open(self, filename: str) -> None: from sqlite3 import connect self._filename = filename self._con = connect(filename) self._cur = self._con.cursor() # self._glos.setDefaultDefiFormat("m") def __len__(self) -> int: if self._cur is None: return 0 self._cur.execute("select count(*) from dict") return self._cur.fetchone()[0] def __iter__(self) -> Iterator[EntryType]: if self._cur is None: raise Error("SQLite cursor is closed") self._cur.execute( "select word, alts, defi, defiFormat from dict order by wordlower, word", ) for row in self._cur: words = [row[0]] + splitByBar(row[1]) defi = row[2] defiFormat = row[3] yield self._glos.newEntry(words, defi, defiFormat=defiFormat) def close(self) -> None: if self._cur: self._cur.close() if self._con: self._con.close() self._clear()
3,012
Python
.py
119
21.865546
76
0.660515
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,734
entry_merge.py
ilius_pyglossary/pyglossary/entry_merge.py
from __future__ import annotations from collections.abc import Iterator from typing import TYPE_CHECKING from pyglossary.entry import Entry from pyglossary.xdxf.transform import XdxfTransformer if TYPE_CHECKING: from pyglossary.glossary_types import EntryType _xdxfTr: XdxfTransformer | None = None def xdxf_transform(text: str) -> str: global _xdxfTr if _xdxfTr is None: # if self._xsl: # self._xdxfTr = XslXdxfTransformer(encoding="utf-8") # return _xdxfTr = XdxfTransformer(encoding="utf-8") return _xdxfTr.transformByInnerString(text) # type: ignore def getHtmlDefi(entry: EntryType): if entry.defiFormat == "m": return f"<pre>{entry.defi}</pre>" if entry.defiFormat == "x": return xdxf_transform(entry.defi) # now assume it's html defi = entry.defi if len(entry.l_word) > 1: defi = "".join(f"<b>{word}</b><br/>" for word in entry.l_word) + defi return defi def mergeHtmlEntriesWithSameHeadword( entryIter: Iterator[EntryType], ) -> Iterator[EntryType]: try: last: EntryType = next(entryIter) except StopIteration: return last.detectDefiFormat() for entry in entryIter: if entry.isData(): if last is not None: yield last last = None continue entry.detectDefiFormat() if last is None: last = entry continue if entry.l_word[0] != last.l_word[0]: yield last last = entry continue defi = getHtmlDefi(last) + "\n<hr>\n" + getHtmlDefi(entry) last = Entry( entry.l_word[0], defi, defiFormat="h", ) if last is not None: yield last def mergePlaintextEntriesWithSameHeadword( entryIter: Iterator[EntryType], ) -> Iterator[EntryType]: try: last: EntryType = next(entryIter) except StopIteration: return for entry in entryIter: if entry.isData(): if last is not None: yield last last = None continue if last is None: last = entry continue if entry.l_word[0] != last.l_word[0]: yield last last = entry continue defi = ( last.defi + "\n\n" + "-" * 40 + "\n" + ", ".join(entry.l_word) + "\n" + entry.defi ) last = Entry( entry.l_word[0], defi, defiFormat="m", ) if last is not None: yield last
2,180
Python
.py
92
20.586957
71
0.704259
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,735
apple_utils.py
ilius_pyglossary/pyglossary/apple_utils.py
# list of css params that are defined in Apple's WebKit and used in # Apple dictionary files (binary and source formats) # but to make the css work in other dictionaries, we have to substitute them # default / system font of Mac OS X is Helvetica Neue / Neue Helvetica # https://en.wikipedia.org/wiki/Helvetica # list of fonts that are shipped with Mac OS X # https://en.wikipedia.org/wiki/List_of_typefaces_included_with_macOS # but we actually prefer to set font that are free and more widely available # in all operating systems # also see: # https://github.com/servo/servo/blob/master/components/style/properties/counted_unknown_properties.py from __future__ import annotations import re from .core import log __all__ = ["substituteAppleCSS"] # remove these keys along with their value cssKeyRemove = { b"-webkit-text-combine", # ^ value: horizontal b"-apple-color-filter", # ^ value: apple-invert-lightness() b"-webkit-overflow-scrolling", # ^ controls whether or not touch devices use momentum-based scrolling # https://developer.mozilla.org/en-US/docs/Web/CSS/-webkit-overflow-scrolling # values: touch, auto } cssKeyRemovePattern = re.compile( rb"[ \t]*(" + b"|".join(cssKeyRemove) + rb")\s*:[^;}]*;\s*", ) cssMapping: dict[str, str] = { # I didn't actually find these font values: "-apple-system-body": '"Helvetica Neue"', "-apple-system": '"Helvetica Neue"', "-webkit-link": "rgb(0, 0, 238)", # value, color of <a> links "-webkit-control": "normal normal normal normal 13px/normal system-ui", "-webkit-mini-control": "normal normal normal normal 9px/normal system-ui", "-webkit-small-control": "normal normal normal normal 11px/normal system-ui", "-webkit-isolate": "isolate", # value for "unicode-bidi" "-webkit-isolate-override": "isolate-override", # value for "unicode-bidi" "-webkit-border-bottom-left-radius": "border-bottom-left-radius", # key "-webkit-border-bottom-right-radius": "border-bottom-right-radius", # key "-webkit-border-radius": "border-radius", # key "-webkit-border-top-left-radius": "border-top-left-radius", # key "-webkit-border-top-right-radius": "border-top-right-radius", # key "-webkit-hyphens": "hyphens", # key "-webkit-writing-mode": "writing-mode", # key "-webkit-column-width": "column-width", # key "-webkit-column-rule-color": "column-rule-color", # key "-webkit-column-rule-style": "column-rule-style", # key "-webkit-column-rule-width": "column-rule-width", # key "-webkit-ruby-position": "ruby-position", # key # not so sure about this: "-webkit-padding-start": "padding-inline-start", # key "-apple-system-alternate-selected-text": "rgb(255, 255, 255)", "-apple-system-blue": "rgb(0, 122, 255)", "-apple-system-brown": "rgb(162, 132, 94)", "-apple-system-container-border": "rgba(0, 0, 0, 0.247)", "-apple-system-control-accent": "rgb(0, 122, 255)", "-apple-system-control-background": "rgb(255, 255, 255)", "-apple-system-even-alternating-content-background": "rgb(255, 255, 255)", "-apple-system-find-highlight-background": "rgb(255, 255, 0)", "-apple-system-gray": "rgb(142, 142, 147)", "-apple-system-green": "rgb(40, 205, 65)", "-apple-system-grid": "rgb(230, 230, 230)", "-apple-system-header-text": "rgba(0, 0, 0, 0.847)", "-apple-system-label": "rgba(0, 0, 0, 0.847)", "-apple-system-odd-alternating-content-background": "rgb(244, 245, 245)", "-apple-system-orange": "rgb(255, 149, 0)", "-apple-system-pink": "rgb(255, 45, 85)", "-apple-system-placeholder-text": "rgba(0, 0, 0, 0.247)", "-apple-system-purple": "rgb(175, 82, 222)", "-apple-system-quaternary-label": "rgba(0, 0, 0, 0.098)", "-apple-system-red": "rgb(255, 59, 48)", "-apple-system-secondary-label": "rgba(0, 0, 0, 0.498)", "-apple-system-selected-content-background": "rgb(0, 99, 225)", "-apple-system-selected-text": "rgb(0, 0, 0)", "-apple-system-selected-text-background": "rgba(128, 188, 254, 0.6)", "-apple-system-separator": "rgba(0, 0, 0, 0.098)", "-apple-system-tertiary-label": "rgba(0, 0, 0, 0.26)", "-apple-system-text-background": "rgb(255, 255, 255)", "-apple-system-unemphasized-selected-content-background": "rgb(220, 220, 220)", "-apple-system-unemphasized-selected-text": "rgb(0, 0, 0)", "-apple-system-unemphasized-selected-text-background": "rgb(220, 220, 220)", "-apple-system-yellow": "rgb(255, 204, 0)", "-apple-wireless-playback-target-active": "rgb(0, 122, 255)", } cssParamPattern = re.compile( rb"(-(apple|webkit)-[a-z\-]+)", ) def _subCSS(m: re.Match) -> bytes: b_key = m.group(0) value = cssMapping.get(b_key.decode("ascii")) if value is None: log.warning(f"unrecognized CSS param: {b_key.decode('ascii')!r}") return b_key return value.encode("ascii") def substituteAppleCSS(css: bytes) -> bytes: css = cssKeyRemovePattern.sub(b"", css) return cssParamPattern.sub(_subCSS, css)
4,836
Python
.py
99
46.939394
102
0.699068
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,736
__init__.py
ilius_pyglossary/pyglossary/__init__.py
from .core import VERSION from .glossary import Glossary __version__ = VERSION __all__ = [ "Glossary", "__version__", ]
124
Python
.py
7
16.142857
30
0.686957
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,737
sort_keys_types.py
ilius_pyglossary/pyglossary/sort_keys_types.py
from __future__ import annotations from collections.abc import Callable from typing import Any, TypeAlias SortKeyType: TypeAlias = Callable[ [list[str]], Any, ] SQLiteSortKeyType: TypeAlias = list[tuple[str, str, SortKeyType]] __all__ = [ "SQLiteSortKeyType", "SortKeyType", ]
285
Python
.py
12
22.083333
65
0.773234
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,738
glossary_utils.py
ilius_pyglossary/pyglossary/glossary_utils.py
# -*- coding: utf-8 -*- # glossary_utils.py # # Copyright © 2008-2022 Saeed Rasooli <saeed.gnu@gmail.com> (ilius) # This file is part of PyGlossary project, https://github.com/ilius/pyglossary # # This program is a free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program. Or on Debian systems, from /usr/share/common-licenses/GPL # If not, see <http://www.gnu.org/licenses/gpl.txt>. from __future__ import annotations import logging from os.path import ( splitext, ) from .compression import ( stdCompressions, ) __all__ = ["Error", "ReadError", "WriteError", "splitFilenameExt"] log = logging.getLogger("pyglossary") MAX_EXT_LEN = 4 # FIXME class Error(Exception): pass class ReadError(Error): pass class WriteError(Error): pass def splitFilenameExt( filename: str = "", ) -> tuple[str, str, str, str]: """Return (filenameNoExt, filename, ext, compression).""" compression = "" filenameNoExt, ext = splitext(filename) ext = ext.lower() if not ext and len(filenameNoExt) <= MAX_EXT_LEN: filenameNoExt, ext = "", filenameNoExt if not ext: return filename, filename, "", "" if ext[1:] in {*stdCompressions, "zip", "dz"}: compression = ext[1:] filename = filenameNoExt filenameNoExt, ext = splitext(filename) ext = ext.lower() return filenameNoExt, filename, ext, compression
1,817
Python
.py
53
32.45283
78
0.748568
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,739
entry_list.py
ilius_pyglossary/pyglossary/entry_list.py
# -*- coding: utf-8 -*- # entry_list.py # # Copyright © 2020-2023 Saeed Rasooli <saeed.gnu@gmail.com> (ilius) # This file is part of PyGlossary project, https://github.com/ilius/pyglossary # # This program is a free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program. Or on Debian systems, from /usr/share/common-licenses/GPL # If not, see <http://www.gnu.org/licenses/gpl.txt>. from __future__ import annotations import logging from typing import TYPE_CHECKING if TYPE_CHECKING: from collections.abc import Callable, Iterator from typing import Any from .glossary_types import EntryType, RawEntryType from .sort_keys import NamedSortKey from .entry import Entry __all__ = ["EntryList"] log = logging.getLogger("pyglossary") class EntryList: def __init__( self, entryToRaw: "Callable[[EntryType], RawEntryType]", entryFromRaw: "Callable[[RawEntryType], EntryType]", ) -> None: self._l: list[RawEntryType] = [] self._entryToRaw = entryToRaw self._entryFromRaw = entryFromRaw self._sortKey: "Callable[[RawEntryType], Any] | None" = None self._rawEntryCompress = False @property def rawEntryCompress(self) -> bool: return self._rawEntryCompress @rawEntryCompress.setter def rawEntryCompress(self, enable: bool) -> None: self._rawEntryCompress = enable def append(self, entry: EntryType) -> None: self._l.append(self._entryToRaw(entry)) def clear(self) -> None: self._l.clear() def __len__(self) -> int: return len(self._l) def __iter__(self) -> Iterator[EntryType]: entryFromRaw = self._entryFromRaw for rawEntry in self._l: yield entryFromRaw(rawEntry) def setSortKey( self, namedSortKey: NamedSortKey, sortEncoding: "str | None", writeOptions: "dict[str, Any]", ) -> None: if namedSortKey.normal is None: raise NotImplementedError( f"sort key {namedSortKey.name!r} is not supported", ) kwargs = writeOptions.copy() if sortEncoding: kwargs["sortEncoding"] = sortEncoding sortKey = namedSortKey.normal(**kwargs) self._sortKey = Entry.getRawEntrySortKey( key=sortKey, rawEntryCompress=self._rawEntryCompress, ) def sort(self) -> None: if self._sortKey is None: raise ValueError("EntryList.sort: sortKey is not set") self._l.sort(key=self._sortKey) def close(self) -> None: pass
2,789
Python
.py
81
32
78
0.749535
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,740
xml_utils.py
ilius_pyglossary/pyglossary/xml_utils.py
# from xml.sax.saxutils import escape as xml_escape # from xml.sax.saxutils import unescape as xml_unescape from __future__ import annotations __all__ = ["xml_escape"] def xml_escape(data: str, quotation: bool = True) -> str: """Escape &, <, and > in a string of data.""" # must do ampersand first data = data.replace("&", "&amp;") data = data.replace(">", "&gt;") data = data.replace("<", "&lt;") if quotation: data = data.replace('"', "&quot;").replace("'", "&apos;") return data # noqa: RET504
511
Python
.py
13
37.307692
59
0.649798
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,741
core.py
ilius_pyglossary/pyglossary/core.py
from __future__ import annotations import inspect import logging import os import platform import sys import traceback from os.path import ( abspath, dirname, exists, isdir, isfile, join, ) from typing import TYPE_CHECKING, cast if TYPE_CHECKING: from collections.abc import Callable from types import TracebackType from typing import ( Any, TypeAlias, ) ExcInfoType: TypeAlias = ( "tuple[type[BaseException], BaseException, TracebackType]" " | tuple[None, None, None]" ) def exc_note(e: Exception, note: str) -> Exception: try: e.add_note(note) except AttributeError: e.msg += "\n" + note return e __all__ = [ "TRACE", "VERSION", "StdLogHandler", "appResDir", "cacheDir", "checkCreateConfDir", "confDir", "confJsonFile", "dataDir", "format_exception", "getDataDir", "homeDir", "homePage", "isDebug", "log", "noColor", "pip", "pluginsDir", "rootConfJsonFile", "rootDir", "sysName", "tmpDir", "trace", "uiDir", "userPluginsDir", ] VERSION = "4.7.1" homePage = "https://github.com/ilius/pyglossary" TRACE = 5 logging.addLevelName(TRACE, "TRACE") noColor = False def trace(log: logging.Logger, msg: str) -> None: func = getattr(log, "trace", None) if func is None: log.error(f"Logger {log} has no 'trace' method") return func(msg) class _Formatter(logging.Formatter): def __init__(self, *args, **kwargs) -> None: # noqa: ANN101 logging.Formatter.__init__(self, *args, **kwargs) self.fill: Callable[[str], str] | None = None def formatMessage( self, record: logging.LogRecord, ) -> str: msg = logging.Formatter.formatMessage(self, record) if self.fill is not None: msg = self.fill(msg) return msg # noqa: RET504 class _MyLogger(logging.Logger): levelsByVerbosity = ( logging.CRITICAL, logging.ERROR, logging.WARNING, logging.INFO, logging.DEBUG, TRACE, logging.NOTSET, ) levelNamesCap = ( "Critical", "Error", "Warning", "Info", "Debug", "Trace", "All", # "Not-Set", ) def __init__(self, *args) -> None: # noqa: ANN101 logging.Logger.__init__(self, *args) self._verbosity = 3 self._timeEnable = False def setVerbosity(self, verbosity: int) -> None: self.setLevel(self.levelsByVerbosity[verbosity]) self._verbosity = verbosity def getVerbosity(self) -> int: return self._verbosity def trace(self, msg: str) -> None: self.log(TRACE, msg) def pretty(self, data: Any, header: str = "") -> None: from pprint import pformat self.debug(header + pformat(data)) def newFormatter(self) -> _Formatter: timeEnable = self._timeEnable if timeEnable: fmt = "%(asctime)s [%(levelname)s] %(message)s" else: fmt = "[%(levelname)s] %(message)s" return _Formatter(fmt) def setTimeEnable(self, timeEnable: bool) -> None: self._timeEnable = timeEnable formatter = self.newFormatter() for handler in self.handlers: handler.setFormatter(formatter) def addHandler(self, hdlr: logging.Handler) -> None: # if want to add separate format (new config keys and flags) for ui_gtk # and ui_tk, you need to remove this function and run handler.setFormatter # in ui_gtk and ui_tk logging.Logger.addHandler(self, hdlr) hdlr.setFormatter(self.newFormatter()) def _formatVarDict( dct: dict[str, Any], indent: int = 4, max_width: int = 80, ) -> str: lines = [] pre = " " * indent for key, value in dct.items(): line = pre + key + " = " + repr(value) if len(line) > max_width: line = line[: max_width - 3] + "..." try: value_len = len(value) except TypeError: pass else: line += f"\n{pre}len({key}) = {value_len}" lines.append(line) return "\n".join(lines) def format_exception( exc_info: ExcInfoType | None = None, add_locals: bool = False, add_globals: bool = False, ) -> str: if exc_info is None: exc_info = sys.exc_info() _type, value, tback = exc_info text = "".join(traceback.format_exception(_type, value, tback)) if tback is None: return text if add_locals or add_globals: try: frame = inspect.getinnerframes(tback, context=0)[-1][0] except IndexError: pass else: if add_locals: text += f"Traceback locals:\n{_formatVarDict(frame.f_locals)}\n" if add_globals: text += f"Traceback globals:\n{_formatVarDict(frame.f_globals)}\n" return text class StdLogHandler(logging.Handler): colorsConfig = { "CRITICAL": ("color.cmd.critical", 196), "ERROR": ("color.cmd.error", 1), "WARNING": ("color.cmd.warning", 208), } # 1: dark red (like 31m), 196: real red, 9: light red # 15: white, 229: light yellow (#ffffaf), 226: real yellow (#ffff00) def __init__(self, noColor: bool = False) -> None: logging.Handler.__init__(self) self.set_name("std") self.noColor = noColor self.config: "dict[str, Any]" = {} @property def endFormat(self) -> str: if self.noColor: return "" return "\x1b[0;0;0m" def emit(self, record: logging.LogRecord) -> None: msg = "" if record.getMessage(): msg = self.format(record) ### if record.exc_info: _type, value, tback = record.exc_info if _type and tback and value: # to fix mypy error tback_text = format_exception( exc_info=(_type, value, tback), add_locals=(log.level <= logging.DEBUG), add_globals=False, ) if not msg: msg = "unhandled exception:" msg += "\n" msg += tback_text ### levelname = record.levelname fp = sys.stderr if levelname in {"CRITICAL", "ERROR"} else sys.stdout if not self.noColor and levelname in self.colorsConfig: key, default = self.colorsConfig[levelname] colorCode = self.config.get(key, default) startColor = f"\x1b[38;5;{colorCode}m" msg = startColor + msg + self.endFormat ### if fp is None: print(f"fp=None, levelname={record.levelname}") # noqa: T201 print(msg) # noqa: T201 return fp.write(msg + "\n") fp.flush() def checkCreateConfDir() -> None: if not isdir(confDir): if exists(confDir): # file, or anything other than directory os.rename(confDir, confDir + ".bak") # we do not import old config os.mkdir(confDir) if not exists(userPluginsDir): try: os.mkdir(userPluginsDir) except Exception as e: log.warning(f"failed to create user plugins directory: {e}") if not isfile(confJsonFile): with ( open(rootConfJsonFile, encoding="utf-8") as srcF, open(confJsonFile, "w", encoding="utf-8") as usrF, ): usrF.write(srcF.read()) def _in_virtualenv() -> bool: if hasattr(sys, "real_prefix"): return True return hasattr(sys, "base_prefix") and sys.base_prefix != sys.prefix def getDataDir() -> str: if _in_virtualenv(): pass # TODO # print(f"prefix={sys.prefix}, base_prefix={sys.base_prefix}") # return join( # dirname(dirname(dirname(rootDir))), # os.getenv("VIRTUAL_ENV"), "share", "pyglossary", # ) if not rootDir.endswith(("dist-packages", "site-packages")): return rootDir parent3 = dirname(dirname(dirname(rootDir))) if os.sep == "/": return join(parent3, "share", "pyglossary") _dir = join( parent3, f"Python{sys.version_info.major}{sys.version_info.minor}", "share", "pyglossary", ) if isdir(_dir): return _dir _dir = join(parent3, "Python3", "share", "pyglossary") if isdir(_dir): return _dir _dir = join(parent3, "Python", "share", "pyglossary") if isdir(_dir): return _dir _dir = join(sys.prefix, "share", "pyglossary") if isdir(_dir): return _dir if CONDA_PREFIX := os.getenv("CONDA_PREFIX"): _dir = join(CONDA_PREFIX, "share", "pyglossary") if isdir(_dir): return _dir raise OSError("failed to detect dataDir") # __________________________________________________________________________ # logging.setLoggerClass(_MyLogger) log = cast(_MyLogger, logging.getLogger("pyglossary")) def isDebug() -> bool: return log.getVerbosity() >= 4 # noqa: PLR2004 if os.sep == "\\": def _windows_show_exception( _type: type[BaseException], exc: BaseException, tback: "TracebackType | None", ) -> None: if not (_type and exc and tback): return import ctypes msg = format_exception( exc_info=(_type, exc, tback), add_locals=(log.level <= logging.DEBUG), add_globals=False, ) log.critical(msg) ctypes.windll.user32.MessageBoxW(0, msg, "PyGlossary Error", 0) # type: ignore sys.excepthook = _windows_show_exception else: def _unix_show_exception( _type: type[BaseException], exc: BaseException, tback: "TracebackType | None", ) -> None: if not (_type and exc and tback): return log.critical( format_exception( exc_info=(_type, exc, tback), add_locals=(log.level <= logging.DEBUG), add_globals=False, ), ) sys.excepthook = _unix_show_exception sysName = platform.system().lower() # platform.system() is in ["Linux", "Windows", "Darwin", "FreeBSD"] # sysName is in ["linux", "windows", "darwin', "freebsd"] # can set env var WARNINGS to: # "error", "ignore", "always", "default", "module", "once" if WARNINGS := os.getenv("WARNINGS"): if WARNINGS in {"default", "error", "ignore", "always", "module", "once"}: import warnings warnings.filterwarnings(WARNINGS) # type: ignore # noqa: PGH003 else: log.error(f"invalid env var {WARNINGS = }") if getattr(sys, "frozen", False): # PyInstaller frozen executable log.info(f"sys.frozen = {getattr(sys, 'frozen', False)}") rootDir = dirname(sys.executable) uiDir = join(rootDir, "pyglossary", "ui") else: _srcDir = dirname(abspath(__file__)) uiDir = join(_srcDir, "ui") rootDir = dirname(_srcDir) dataDir = getDataDir() appResDir = join(dataDir, "res") if os.sep == "/": # Operating system is Unix-Like homeDir = os.getenv("HOME", "/") tmpDir = os.getenv("TMPDIR", "/tmp") # noqa: S108 if sysName == "darwin": # MacOS X _libDir = join(homeDir, "Library") confDir = join(_libDir, "Preferences", "PyGlossary") # or maybe: join(_libDir, "PyGlossary") # os.environ["OSTYPE"] == "darwin10.0" # os.environ["MACHTYPE"] == "x86_64-apple-darwin10.0" # platform.dist() == ("", "", "") # platform.release() == "10.3.0" cacheDir = join(_libDir, "Caches", "PyGlossary") pip = "pip3" else: # GNU/Linux, Termux, FreeBSD, etc # should switch to "$XDG_CONFIG_HOME/pyglossary" in version 5.0.0 # which generally means ~/.config/pyglossary confDir = join(homeDir, ".pyglossary") cacheDir = join(homeDir, ".cache", "pyglossary") pip = "pip3" if "/com.termux/" in homeDir else "sudo pip3" elif os.sep == "\\": # Operating system is Windows # FIXME: default values _HOMEDRIVE = os.getenv("HOMEDRIVE", "") _HOMEPATH = os.getenv("HOMEPATH", "") homeDir = join(_HOMEDRIVE, _HOMEPATH) tmpDir = os.getenv("TEMP", "") _appData = os.getenv("APPDATA", "") confDir = join(_appData, "PyGlossary") _localAppData = os.getenv("LOCALAPPDATA") if not _localAppData: # Windows Vista or older _localAppData = abspath(join(_appData, "..", "Local")) cacheDir = join(_localAppData, "PyGlossary", "Cache") pip = "pip3" else: raise RuntimeError( f"Unknown path separator(os.sep=={os.sep!r}), unknown operating system!", ) pluginsDir = join(rootDir, "pyglossary", "plugins") confJsonFile = join(confDir, "config.json") rootConfJsonFile = join(dataDir, "config.json") userPluginsDir = join(confDir, "plugins")
11,207
Python
.py
381
26.64042
81
0.681091
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,742
ebook_base.py
ilius_pyglossary/pyglossary/ebook_base.py
# -*- coding: utf-8 -*- # The MIT License (MIT) # Copyright © 2012-2016 Alberto Pettarin (alberto@albertopettarin.it) # Copyright © 2016-2019 Saeed Rasooli <saeed.gnu@gmail.com> # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. from __future__ import annotations import logging import os import shutil import tempfile import zipfile from datetime import datetime from os.path import join from typing import TYPE_CHECKING, cast from pyglossary.os_utils import indir, rmtree if TYPE_CHECKING: import io from collections.abc import Generator from typing import Any from pyglossary.glossary_types import EntryType, GlossaryType __all__ = ["EbookWriter"] log = logging.getLogger("pyglossary") class GroupState: def __init__(self, writer: EbookWriter) -> None: self.writer = writer self.last_prefix = "" self.group_index = -1 self.reset() def reset(self) -> None: self.first_word = "" self.last_word = "" self.group_contents: list[str] = [] def is_new(self, prefix: str) -> bool: return bool(self.last_prefix) and prefix != self.last_prefix def add(self, entry: EntryType, prefix: str) -> None: word = entry.s_word defi = entry.defi if not self.first_word: self.first_word = word self.last_word = word self.last_prefix = prefix self.group_contents.append(self.writer.format_group_content(word, defi)) class EbookWriter: """ A class representing a generic ebook containing a dictionary. It can be used to output a MOBI or an EPUB 2 container. The ebook must have an OPF, and one or more group XHTML files. Optionally, it can have a cover image, an NCX TOC, an index XHTML file. The actual file templates are provided by the caller. """ _keep: bool = False _group_by_prefix_length: int = 2 _include_index_page: bool = False _compress: bool = True _css: str = "" # path to css file, or "" _cover_path: str = "" # path to cover file, or "" CSS_CONTENTS = b"" GROUP_XHTML_TEMPLATE = "" GROUP_XHTML_INDEX_LINK = "" GROUP_XHTML_WORD_DEFINITION_TEMPLATE = "" GROUP_XHTML_WORD_DEFINITION_JOINER = "\n" MIMETYPE_CONTENTS = "" CONTAINER_XML_CONTENTS = "" GROUP_START_INDEX = 2 COVER_TEMPLATE = "{cover}" INDEX_XHTML_TEMPLATE = """<?xml version="1.0" encoding="utf-8" standalone="no"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>{title}</title> <link rel="stylesheet" type="text/css" href="style.css" /> </head> <body class="indexPage"> <h1 class="indexTitle">{indexTitle}</h1> <p class="indexGroupss"> {links} </p> </body> </html>""" INDEX_XHTML_LINK_TEMPLATE = ( ' <span class="indexGroup"><a href="{ref}">{label}</a></span>' ) INDEX_XHTML_LINK_JOINER = " &#8226;\n" OPF_MANIFEST_ITEM_TEMPLATE = ( ' <item href="{ref}" id="{id}" media-type="{mediaType}" />' ) OPF_SPINE_ITEMREF_TEMPLATE = ' <itemref idref="{id}" />' OPF_TEMPLATE = "" def __init__( self, glos: GlossaryType, escape_strings: bool = False, # ignore_synonyms=False, # flatten_synonyms=False, ) -> None: self._glos = glos self._filename = "" self._escape_strings = escape_strings # self._ignore_synonyms = ignore_synonyms # self._flatten_synonyms = flatten_synonyms # Penelope's extra options: # "bookeen_collation_function": None, # bookeen format # "bookeen_install_file": False, # bookeen format # "group_by_prefix_merge_across_first": False, # "group_by_prefix_merge_min_size": 0, self._tmpDir = tempfile.mkdtemp() self.cover = "" self.files: list[dict[str, Any]] = [] self.manifest_files: list[dict[str, str]] = [] self._group_labels: list[str] = [] def finish(self) -> None: self._filename = "" def myOpen(self, fname: str, mode: str) -> io.IOBase: return cast( "io.IOBase", open( join(self._tmpDir, fname), mode=mode, ), ) def add_file( self, relative_path: str, contents: bytes, mode: "int | None" = None, ) -> None: if mode is None: mode = zipfile.ZIP_DEFLATED file_path = os.path.join(self._tmpDir, relative_path) with self.myOpen(file_path, "wb") as file_obj: file_obj.write(contents) self.files.append( { "path": relative_path, "mode": mode, }, ) def write_cover(self, cover_path: str) -> None: if not cover_path: return basename = os.path.basename(cover_path) with self.myOpen(cover_path, "rb") as cover_obj: cover = cover_obj.read() b = basename.lower() mimetype = "image/jpeg" if b.endswith(".png"): mimetype = "image/png" elif b.endswith(".gif"): mimetype = "image/gif" self.add_file_manifest("OEBPS/" + basename, basename, cover, mimetype) self.cover = basename def write_css(self, custom_css_path_absolute: str) -> None: css = self.CSS_CONTENTS if custom_css_path_absolute: try: with self.myOpen(custom_css_path_absolute, "rb") as css_obj: css = css_obj.read() # NESTED 4 except Exception: log.exception("") if not css: return self.add_file_manifest("OEBPS/style.css", "style.css", css, "text/css") def add_file_manifest( self, relative_path: str, _id: str, contents: bytes, mimetype: str, ) -> None: self.add_file(relative_path, contents) self.manifest_files.append( { "path": relative_path, "id": _id, "mimetype": mimetype, }, ) def get_group_xhtml_file_name_from_index(self, index: int) -> str: if index < self.GROUP_START_INDEX: # or index >= groupCount + self.GROUP_START_INDEX: # number of groups are not known, FIXME # so we can191 not say if the current group is the last or not return "#groupPage" return f"g{index:06d}.xhtml" def get_prefix(self, word: str) -> str: raise NotImplementedError def sortKey(self, words: list[str]) -> Any: raise NotImplementedError def _add_group( self, group_labels: list[str], state: GroupState, ) -> None: if not state.last_prefix: return state.group_index += 1 index = state.group_index + self.GROUP_START_INDEX group_label = state.last_prefix if group_label != "SPECIAL": group_label = state.first_word + "&#8211;" + state.last_word log.debug(f"add_group: {state.group_index}, {state.last_prefix!r}") group_labels.append(group_label) previous_link = self.get_group_xhtml_file_name_from_index(index - 1) next_link = self.get_group_xhtml_file_name_from_index(index + 1) group_xhtml_path = self.get_group_xhtml_file_name_from_index(index) contents = self.GROUP_XHTML_TEMPLATE.format( title=group_label, group_title=group_label, previous_link=previous_link, index_link=( self.GROUP_XHTML_INDEX_LINK if self._include_index_page else "" ), next_link=next_link, group_contents=self.GROUP_XHTML_WORD_DEFINITION_JOINER.join( state.group_contents, ), ).encode("utf-8") self.add_file_manifest( "OEBPS/" + group_xhtml_path, group_xhtml_path, contents, "application/xhtml+xml", ) def write_data_entry(self, entry: EntryType) -> None: if entry.getFileName() == "style.css": self.add_file_manifest( "OEBPS/style.css", "style.css", entry.data, "text/css", ) def write_groups(self) -> Generator[None, EntryType, None]: # TODO: rtl=False option # TODO: handle alternates better (now shows word1|word2... in title) group_labels: list[str] = [] state = GroupState(self) while True: entry = yield if entry is None: break if entry.isData(): self.write_data_entry(entry) continue prefix = self.get_prefix(entry.s_word) if state.is_new(prefix): self._add_group(group_labels, state) state.reset() state.add(entry, prefix) self._add_group(group_labels, state) self._group_labels = group_labels def format_group_content( self, word: str, defi: str, variants: list[str] | None = None, # noqa: ARG002 ) -> str: return self.GROUP_XHTML_WORD_DEFINITION_TEMPLATE.format( headword=self.escape_if_needed(word), definition=self.escape_if_needed(defi), ) def escape_if_needed(self, string: str) -> str: if not self._escape_strings: return string return ( string.replace("&", "&amp;") .replace('"', "&quot;") .replace("'", "&apos;") .replace(">", "&gt;") .replace("<", "&lt;") ) def write_index(self, group_labels: list[str]) -> None: """group_labels: a list of labels.""" links = [] for label_i, label in enumerate(group_labels): ref = self.get_group_xhtml_file_name_from_index( self.GROUP_START_INDEX + label_i, ) links.append( self.INDEX_XHTML_LINK_TEMPLATE.format( ref=ref, label=label, ), ) links_str = self.INDEX_XHTML_LINK_JOINER.join(links) title = self._glos.getInfo("name") contents = self.INDEX_XHTML_TEMPLATE.format( title=title, indexTitle=title, links=links_str, ).encode("utf-8") self.add_file_manifest( "OEBPS/index.xhtml", "index.xhtml", contents, "application/xhtml+xml", ) def get_opf_contents( # noqa: F811 self, manifest_contents: str, spine_contents: str, ) -> bytes: cover = "" if self.cover: cover = self.COVER_TEMPLATE.format(cover=self.cover) creationDate = datetime.now().strftime("%Y-%m-%d") return self.OPF_TEMPLATE.format( identifier=self._glos.getInfo("uuid"), sourceLang=self._glos.sourceLangName, targetLang=self._glos.targetLangName, title=self._glos.getInfo("name"), creator=self._glos.author, copyright=self._glos.getInfo("copyright"), creationDate=creationDate, cover=cover, manifest=manifest_contents, spine=spine_contents, ).encode("utf-8") def write_opf(self) -> None: manifest_lines = [] spine_lines = [] for mi in self.manifest_files: manifest_lines.append( self.OPF_MANIFEST_ITEM_TEMPLATE.format( ref=mi["id"], id=mi["id"], mediaType=mi["mimetype"], ), ) if mi["mimetype"] == "application/xhtml+xml": spine_lines.append( self.OPF_SPINE_ITEMREF_TEMPLATE.format( id=mi["id"], # NESTED 4 ), ) manifest_contents = "\n".join(manifest_lines) spine_contents = "\n".join(spine_lines) opf_contents = self.get_opf_contents( manifest_contents, spine_contents, ) self.add_file("OEBPS/content.opf", opf_contents) def write_ncx(self, group_labels: list[str]) -> None: """ write_ncx. only for epub. """ def open(self, filename: str) -> None: self._filename = filename def _doZip(self) -> None: with zipfile.ZipFile( self._filename, mode="w", compression=zipfile.ZIP_DEFLATED, ) as zipFp: for fileDict in self.files: zipFp.write( fileDict["path"], compress_type=fileDict["mode"], ) if not self._keep: rmtree(self._tmpDir) def write(self) -> Generator[None, EntryType, None]: filename = self._filename # self._group_by_prefix_length # self._include_index_page css = self._css cover_path = self._cover_path with indir(self._tmpDir): if cover_path: cover_path = os.path.abspath(cover_path) if css: css = os.path.abspath(css) os.makedirs("META-INF") os.makedirs("OEBPS") if self.MIMETYPE_CONTENTS: self.add_file( "mimetype", self.MIMETYPE_CONTENTS.encode("utf-8"), mode=zipfile.ZIP_STORED, ) if self.CONTAINER_XML_CONTENTS: self.add_file( "META-INF/container.xml", self.CONTAINER_XML_CONTENTS.encode("utf-8"), ) try: self.write_cover(cover_path) except Exception: log.exception("") self.write_css(css) yield from self.write_groups() group_labels = self._group_labels if self._include_index_page: self.write_index(group_labels) self.write_ncx(group_labels) self.write_opf() if self._compress: self._doZip() return if self._keep: shutil.copytree(self._tmpDir, filename) return if os.sep == "\\": shutil.copytree(self._tmpDir, filename) self._glos._cleanupPathList.add(self._tmpDir) # noqa: SLF001, type: ignore return shutil.move(self._tmpDir, filename)
12,997
Python
.py
423
27.309693
79
0.693762
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,743
text_utils.py
ilius_pyglossary/pyglossary/text_utils.py
# -*- coding: utf-8 -*- # text_utils.py # # Copyright © 2008-2022 Saeed Rasooli <saeed.gnu@gmail.com> (ilius) # # This program is a free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # You can get a copy of GNU General Public License along this program # But you can always get it from http://www.gnu.org/licenses/gpl.txt # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. from __future__ import annotations import binascii import logging import re import struct import sys from typing import AnyStr __all__ = [ "crc32hex", "escapeNTB", "excMessage", "fixUtf8", "joinByBar", "replacePostSpaceChar", "splitByBar", "splitByBarUnescapeNTB", "toStr", "uint32FromBytes", "uint32ToBytes", "uint64FromBytes", "uint64ToBytes", "uintFromBytes", "unescapeBar", "unescapeNTB", "urlToPath", ] log = logging.getLogger("pyglossary") endFormat = "\x1b[0;0;0m" # len=8 def toStr(s: AnyStr) -> str: if isinstance(s, bytes): return str(s, "utf-8") return str(s) def fixUtf8(st: AnyStr) -> str: if isinstance(st, str): st = bytes(st, "utf-8") return st.replace(b"\x00", b"").decode("utf-8", "replace") pattern_n_us = re.compile(r"((?<!\\)(?:\\\\)*)\\n") pattern_t_us = re.compile(r"((?<!\\)(?:\\\\)*)\\t") pattern_bar_us = re.compile(r"((?<!\\)(?:\\\\)*)\\\|") pattern_bar_sp = re.compile(r"(?:(?<!\\)(?:\\\\)*)\|") def escapeNTB(st: str, bar: bool = False) -> str: """Scapes Newline, Tab, Baskslash, and vertical Bar (if bar=True).""" st = st.replace("\\", "\\\\") st = st.replace("\t", r"\t") st = st.replace("\r", "") st = st.replace("\n", r"\n") if bar: st = st.replace("|", r"\|") return st # noqa: RET504 def unescapeNTB(st: str, bar: bool = False) -> str: """Unscapes Newline, Tab, Baskslash, and vertical Bar (if bar=True).""" st = pattern_n_us.sub("\\1\n", st) st = pattern_t_us.sub("\\1\t", st) if bar: st = pattern_bar_us.sub(r"\1|", st) st = st.replace("\\\\", "\\") # probably faster than re.sub return st # noqa: RET504 def splitByBarUnescapeNTB(st: str) -> list[str]: r""" Split by "|" (and not "\\|") then unescapes Newline (\\n), Tab (\\t), Baskslash (\\) and Bar (\\|) in each part returns a list. """ return [unescapeNTB(part, bar=True) for part in pattern_bar_sp.split(st)] def escapeBar(st: str) -> str: r"""Scapes vertical bar (\|).""" return st.replace("\\", "\\\\").replace("|", r"\|") def unescapeBar(st: str) -> str: r"""Unscapes vertical bar (\|).""" # str.replace is probably faster than re.sub return pattern_bar_us.sub(r"\1|", st).replace("\\\\", "\\") def splitByBar(st: str) -> list[str]: r""" Split by "|" (and not "\\|") then unescapes Baskslash (\\) and Bar (\\|) in each part. """ return [unescapeBar(part) for part in pattern_bar_sp.split(st)] def joinByBar(parts: list[str]) -> str: return "|".join(escapeBar(part) for part in parts) # return a message string describing the current exception def excMessage() -> str: i = sys.exc_info() if not i[0]: return "" return f"{i[0].__name__}: {i[1]}" # ___________________________________________ # def uint32ToBytes(n: int) -> bytes: return struct.pack(">I", n) def uint64ToBytes(n: int) -> bytes: return struct.pack(">Q", n) def uint32FromBytes(bs: bytes) -> int: return struct.unpack(">I", bs)[0] def uint64FromBytes(bs: bytes) -> int: return struct.unpack(">Q", bs)[0] def uintFromBytes(bs: bytes) -> int: n = 0 for c in bs: n = (n << 8) + c return n def crc32hex(bs: bytes) -> str: return struct.pack(">I", binascii.crc32(bs) & 0xFFFFFFFF).hex() # ___________________________________________ # def urlToPath(url: str) -> str: from urllib.parse import unquote if not url.startswith("file://"): return unquote(url) path = url[7:] if path[-2:] == "\r\n": path = path[:-2] elif path[-1] == "\r": path = path[:-1] # here convert html unicode symbols to utf-8 string: return unquote(path) def replacePostSpaceChar(st: str, ch: str) -> str: return ( st.replace(f" {ch}", ch) .replace(ch, f"{ch} ") .replace(f"{ch} ", f"{ch} ") .removesuffix(" ") )
4,416
Python
.py
137
30.182482
74
0.642722
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,744
glossary_types.py
ilius_pyglossary/pyglossary/glossary_types.py
from __future__ import annotations import typing from collections.abc import ( Callable, Iterator, # noqa: TCH003 ) # -*- coding: utf-8 -*- from typing import ( TYPE_CHECKING, Any, ) if TYPE_CHECKING: from collections import OrderedDict from typing import TypeAlias from .langs import Lang from .sort_keys import NamedSortKey __all__ = [ "Callable", "EntryListType", "EntryType", "GlossaryExtendedType", "GlossaryType", "RawEntryType", ] MultiStr: TypeAlias = "str | list[str]" # 3 different types in order: # - compressed # - uncompressed, without defiFormat # - uncompressed, with defiFormat RawEntryType: TypeAlias = "bytes |tuple[list[str], bytes] |tuple[list[str], bytes, str]" class EntryType(typing.Protocol): # noqa: PLR0904 def __init__(self) -> None: ... def isData(self) -> bool: ... def getFileName(self) -> str: ... @property def data(self) -> bytes: ... def size(self) -> int: ... def save(self, directory: str) -> str: ... @property def s_word(self) -> str: ... @property def l_word(self) -> list[str]: ... @property def defi(self) -> str: ... @property def b_word(self) -> bytes: ... @property def b_defi(self) -> bytes: ... @property def defiFormat(self) -> str: # TODO: type: Literal["m", "h", "x", "b"] ... @defiFormat.setter def defiFormat(self, defiFormat: str) -> None: # TODO: type: Literal["m", "h", "x", "b"] ... def detectDefiFormat(self) -> None: ... def addAlt(self, alt: str) -> None: ... def editFuncWord(self, func: "Callable[[str], str]") -> None: ... def editFuncDefi(self, func: "Callable[[str], str]") -> None: ... def strip(self) -> None: ... def replaceInWord(self, source: str, target: str) -> None: ... def replaceInDefi(self, source: str, target: str) -> None: ... def replace(self, source: str, target: str) -> None: ... def byteProgress(self) -> tuple[int, int] | None: ... def removeEmptyAndDuplicateAltWords(self) -> None: ... def stripFullHtml(self) -> str | None: ... class EntryListType(typing.Protocol): def __init__( self, entryToRaw: "Callable[[EntryType], RawEntryType]", entryFromRaw: "Callable[[RawEntryType], EntryType]", ) -> None: ... @property def rawEntryCompress(self) -> bool: ... @rawEntryCompress.setter def rawEntryCompress(self, enable: bool) -> None: ... def append(self, entry: EntryType) -> None: ... def clear(self) -> None: ... def __len__(self) -> int: ... def __iter__(self) -> Iterator[EntryType]: ... def setSortKey( self, namedSortKey: NamedSortKey, sortEncoding: "str | None", writeOptions: "dict[str, Any]", ) -> None: ... def sort(self) -> None: ... def close(self) -> None: ... class GlossaryType(typing.Protocol): # noqa: PLR0904 """ an abstract type class for Glossary class in plugins. it only contains methods and properties that might be used in plugins. """ def __iter__(self) -> Iterator[EntryType]: ... def __len__(self) -> int: ... def setDefaultDefiFormat(self, defiFormat: str) -> None: ... def getDefaultDefiFormat(self) -> str: ... def collectDefiFormat( self, maxCount: int, ) -> dict[str, float] | None: ... def iterInfo(self) -> Iterator[tuple[str, str]]: ... def getInfo(self, key: str) -> str: ... def setInfo(self, key: str, value: str) -> None: ... def getExtraInfos(self, excludeKeys: list[str]) -> OrderedDict: ... @property def author(self) -> str: ... @property def alts(self) -> bool: ... @property def filename(self) -> str: ... @property def tmpDataDir(self) -> str: ... @property def readOptions(self) -> dict | None: ... @property def sourceLang(self) -> Lang | None: ... @property def targetLang(self) -> Lang | None: ... @property def sourceLangName(self) -> str: ... @sourceLangName.setter def sourceLangName(self, langName: str) -> None: ... @property def targetLangName(self) -> str: ... @targetLangName.setter def targetLangName(self, langName: str) -> None: ... def titleTag(self, sample: str) -> str: ... def wordTitleStr( self, word: str, sample: str = "", _class: str = "", ) -> str: ... def getConfig(self, name: str, default: "str | None") -> str | None: ... def addEntry(self, entry: EntryType) -> None: ... def newEntry( self, word: MultiStr, defi: str, defiFormat: str = "", byteProgress: "tuple[int, int] | None" = None, ) -> EntryType: ... def newDataEntry(self, fname: str, data: bytes) -> EntryType: ... @property def rawEntryCompress(self) -> bool: ... def stripFullHtml( self, errorHandler: "Callable[[EntryType, str], None] | None" = None, ) -> None: ... def preventDuplicateWords(self) -> None: ... def removeHtmlTagsAll(self) -> None: ... class GlossaryExtendedType(GlossaryType, typing.Protocol): def progressInit( self, *args, ) -> None: ... def progress(self, pos: int, total: int, unit: str = "entries") -> None: ... def progressEnd(self) -> None: ... @property def progressbar(self) -> bool: ... @progressbar.setter def progressbar(self, enabled: bool) -> None: ...
5,057
Python
.py
164
28.29878
88
0.66348
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,745
option.py
ilius_pyglossary/pyglossary/option.py
# -*- coding: utf-8 -*- from __future__ import annotations import logging import re from typing import Any __all__ = [ "BoolOption", "DictOption", "EncodingOption", "FileSizeOption", "FloatOption", "HtmlColorOption", "IntOption", "ListOption", "NewlineOption", "Option", "StrOption", "optionFromDict", ] log = logging.getLogger("pyglossary") def optionFromDict(data: "dict[str, Any]") -> Option: className = data.pop("class") optClass: type if className == "Option": data["typ"] = data.pop("type") optClass = Option else: data.pop("type") optClass = Option.classes[className] return optClass(**data) class Option: classes: "dict[str, type]" = {} @classmethod def register(cls: type[Option], optClass: type) -> type: cls.classes[optClass.__name__] = optClass return optClass def __init__( # noqa: PLR0913 self, typ: str, customValue: bool = False, values: list[Any] | None = None, allowNone: bool = False, comment: str = "", multiline: bool = False, disabled: bool = False, hasFlag: bool = False, customFlag: str = "", falseComment: str = "", ) -> None: if values is None: # otherwise there would not be any valid value customValue = True self.typ = typ self.values = values self.allowNone = allowNone self.customValue = customValue self.comment = comment self.multiline = multiline self.disabled = disabled self.hasFlag = hasFlag self.customFlag = customFlag self.falseComment = falseComment @property def typeDesc(self) -> str: return self.typ @property def longComment(self) -> str: comment = self.typeDesc if self.comment: if comment: comment += ", " comment += self.comment return comment def toDict(self) -> dict[str, Any]: data = { "class": self.__class__.__name__, "type": self.typ, "customValue": self.customValue, } if self.values: data["values"] = self.values if self.comment: data["comment"] = self.comment if self.disabled: data["disabled"] = True if self.hasFlag: data["hasFlag"] = True data["customFlag"] = self.customFlag if self.falseComment: data["falseComment"] = self.falseComment return data @classmethod def evaluate(cls, raw: str) -> tuple[Any, bool]: """Return (value, isValid).""" if raw == "None": return None, True return raw, True def validate(self, value: Any) -> bool: if not self.customValue: if not self.values: log.error( f"invalid option: customValue={self.customValue!r}" f", values={self.values!r}", ) return False return value in self.values if value is None: return self.allowNone valueType = type(value).__name__ return self.typ == valueType def validateRaw(self, raw: str) -> bool: """Return isValid.""" value, isValid = self.evaluate(raw) if not isValid: return False return self.validate(value) def groupValues(self) -> dict[str, Any] | None: # noqa: PLR6301 return None @Option.register class BoolOption(Option): def __init__( self, allowNone: bool = False, **kwargs, # noqa: ANN003 ) -> None: values: list[bool | None] = [False, True] if allowNone: values.append(None) Option.__init__( self, typ="bool", customValue=False, values=values, allowNone=allowNone, **kwargs, # noqa: ANN003 ) def toDict(self) -> dict[str, Any]: data = Option.toDict(self) del data["customValue"] del data["values"] return data @classmethod def evaluate( cls, raw: "str | bool", ) -> tuple[bool | None, bool]: if raw is None: return None, True if isinstance(raw, bool): return raw, True if isinstance(raw, str): raw = raw.lower() if raw == "none": return None, True if raw in {"yes", "true", "1"}: return True, True if raw in {"no", "false", "0"}: return False, True return None, False # not valid @Option.register class StrOption(Option): def __init__( self, **kwargs, # noqa: ANN003 ) -> None: Option.__init__( self, typ="str", **kwargs, ) def validate(self, value: Any) -> bool: if not self.customValue: if not self.values: log.error( f"invalid option: customValue={self.customValue!r}" f", values={self.values!r}", ) return False return value in self.values return type(value).__name__ == "str" def groupValues(self) -> dict[str, Any] | None: # noqa: PLR6301 return None @Option.register class IntOption(Option): def __init__( self, **kwargs, # noqa: ANN003 ) -> None: Option.__init__( self, typ="int", **kwargs, ) @classmethod def evaluate(cls, raw: "str | int") -> tuple[int | None, bool]: """Return (value, isValid).""" try: value = int(raw) except ValueError: return None, False return value, True @Option.register class FileSizeOption(IntOption): factors = { "KiB": 1024, "kib": 1024, "Ki": 1024, "ki": 1024, # ------------ "MiB": 1048576, "mib": 1048576, "Mi": 1048576, "mi": 1048576, # ------------ "GiB": 1073741824, "gib": 1073741824, "Gi": 1073741824, "gi": 1073741824, # ------------ "kB": 1000, "kb": 1000, "KB": 1000, "k": 1000, "K": 1000, # ------------ "MB": 1000000, "mb": 1000000, "mB": 1000000, "M": 1000000, "m": 1000000, # ------------ "GB": 1000000000, "gb": 1000000000, "gB": 1000000000, "G": 1000000000, "g": 1000000000, } validPattern = "^([0-9.]+)([kKmMgG]i?[bB]?)$" @property def typeDesc(self) -> str: return "" @classmethod def evaluate(cls, raw: "str | int") -> tuple[int | None, bool]: if not raw: return 0, True factor = 1 if isinstance(raw, str): m = re.match(cls.validPattern, raw) if m is not None: raw, unit = m.groups() factorTmp = cls.factors.get(unit) if factorTmp is None: return None, False factor = factorTmp try: value = float(raw) except ValueError: return None, False if value < 0: return None, False return int(value * factor), True @Option.register class FloatOption(Option): def __init__( self, **kwargs, # noqa: ANN003 ) -> None: Option.__init__( self, typ="float", **kwargs, ) @classmethod def evaluate( cls, raw: "str | float | int", ) -> tuple[float | None, bool]: """Return (value, isValid).""" try: value = float(raw) except ValueError: return None, False return value, True @Option.register class DictOption(Option): def __init__( self, **kwargs, # noqa: ANN003 ) -> None: Option.__init__( self, typ="dict", customValue=True, allowNone=True, multiline=True, **kwargs, ) def toDict(self) -> dict[str, Any]: data = Option.toDict(self) del data["customValue"] return data @classmethod def evaluate( cls, raw: "str | dict", ) -> tuple[dict | None, bool]: import ast if isinstance(raw, dict): return raw, True if raw == "": # noqa: PLC1901 return None, True # valid try: value = ast.literal_eval(raw) except SyntaxError: return None, False # not valid if type(value).__name__ != "dict": return None, False # not valid return value, True # valid @Option.register class ListOption(Option): def __init__(self, **kwargs) -> None: Option.__init__( self, typ="list", customValue=True, allowNone=True, multiline=True, **kwargs, # noqa: ANN003 ) def toDict(self) -> dict[str, Any]: data = Option.toDict(self) del data["customValue"] return data @classmethod def evaluate(cls, raw: str) -> tuple[list | None, bool]: import ast if raw == "": # noqa: PLC1901 return None, True # valid try: value = ast.literal_eval(raw) except SyntaxError: return None, False # not valid if type(value).__name__ != "list": return None, False # not valid return value, True # valid @Option.register class EncodingOption(Option): re_category = re.compile("^[a-z]+") def __init__( self, customValue: bool = True, values: "list[str] | None" = None, comment: "str | None" = None, **kwargs, # noqa: ANN003 ) -> None: if values is None: values = [ "utf-8", "utf-16", "windows-1250", "windows-1251", "windows-1252", "windows-1253", "windows-1254", "windows-1255", "windows-1256", "windows-1257", "windows-1258", "mac_cyrillic", "mac_greek", "mac_iceland", "mac_latin2", "mac_roman", "mac_turkish", "cyrillic", "arabic", "greek", "hebrew", "latin2", "latin3", "latin4", "latin5", "latin6", ] if comment is None: comment = "Encoding/charset" Option.__init__( self, typ="str", customValue=customValue, values=values, comment=comment, **kwargs, # noqa: ANN003 ) def toDict(self) -> dict[str, Any]: data = Option.toDict(self) del data["values"] return data def groupValues(self) -> dict[str, Any] | None: from collections import OrderedDict groups: "dict[str, list[str]]" = OrderedDict() others: list[str] = [] for value in self.values or []: cats = self.re_category.findall(value) if not cats: others.append(value) continue cat = cats[0] if len(cat) == len(value): others.append(value) continue if cat not in groups: groups[cat] = [] groups[cat].append(value) if others: groups["other"] = others return groups @Option.register class NewlineOption(Option): def __init__( self, customValue: bool = True, values: "list[str] | None" = None, comment: "str | None" = None, **kwargs, # noqa: ANN003 ) -> None: if values is None: values = [ "\r\n", "\n", "\r", ] if comment is None: comment = "Newline string" Option.__init__( self, typ="str", customValue=customValue, values=values, multiline=True, comment=comment, **kwargs, # noqa: ANN003 ) @Option.register class UnicodeErrorsOption(Option): def __init__( self, comment: "str | None" = None, ) -> None: if comment is None: comment = "Unicode Errors, values: `strict`, `ignore`, `replace`" Option.__init__( self, typ="str", customValue=False, values=["strict", "ignore", "replace"], multiline=False, comment=comment, ) def toDict(self) -> dict[str, Any]: return { "class": "UnicodeErrorsOption", "type": "str", "comment": self.comment, } @Option.register class HtmlColorOption(Option): def toDict(self) -> dict[str, Any]: data = Option.toDict(self) del data["customValue"] return data def __init__(self, **kwargs) -> None: Option.__init__( self, typ="str", customValue=True, **kwargs, # noqa: ANN003 ) # TODO: use a specific type?
10,630
Python
.py
479
18.903967
68
0.644704
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,746
os_utils.py
ilius_pyglossary/pyglossary/os_utils.py
from __future__ import annotations import logging import os import shutil import sys import types from collections.abc import Callable from pathlib import Path from pyglossary import core __all__ = ["indir", "rmtree", "runDictzip", "showMemoryUsage"] log = logging.getLogger("pyglossary") class indir: """ mkdir + chdir shortcut to use with `with` statement. >>> print(os.getcwd()) # -> "~/projects" >>> with indir('my_directory', create=True): >>> print(os.getcwd()) # -> "~/projects/my_directory" >>> # do some work inside new 'my_directory'... >>> print(os.getcwd()) # -> "~/projects" >>> # automatically return to previous directory. """ def __init__( self, directory: str, create: bool = False, clear: bool = False, ) -> None: self.old_pwd: "str | None" = None self.dir = directory self.create = create self.clear = clear def __enter__(self) -> None: self.old_pwd = os.getcwd() if os.path.exists(self.dir): if self.clear: shutil.rmtree(self.dir) os.makedirs(self.dir) elif self.create: os.makedirs(self.dir) os.chdir(self.dir) def __exit__( self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: types.TracebackType | None, ) -> None: if self.old_pwd: os.chdir(self.old_pwd) self.old_pwd = None def _idzip(filename: "str | Path") -> bool: try: import idzip except ModuleNotFoundError: return False filename = Path(filename) destination = filename.parent / (filename.name + ".dz") try: with open(filename, "rb") as inp_file, open(destination, "wb") as out_file: inputInfo = os.fstat(inp_file.fileno()) log.debug("compressing %s to %s with idzip", filename, destination) idzip.compressor.compress( inp_file, inputInfo.st_size, out_file, filename.name, int(inputInfo.st_mtime), ) filename.unlink() except OSError as error: log.error(str(error)) return True def _dictzip(filename: str | Path) -> bool: import subprocess dictzipCmd = shutil.which("dictzip") if not dictzipCmd: return False log.debug(f"dictzip command: {dictzipCmd!r}") try: subprocess.run( [dictzipCmd, filename], check=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, ) except subprocess.CalledProcessError as proc_err: err_msg = proc_err.output.decode("utf-8").replace("\n", ";") retcode = proc_err.returncode log.error(f"dictzip exit {retcode}: {err_msg}") return True def runDictzip(filename: str | Path, method: str = "") -> None: """Compress file into dictzip format.""" res = None if method in {"", "idzip"}: res = _idzip(filename) if not res and method in {"", "dictzip"}: res = _dictzip(filename) if not res: log.warning( "Dictzip compression requires idzip module or dictzip utility," f" run `{core.pip} install python-idzip` to install or make sure" " dictzip is in your $PATH", ) def _rmtreeError( _func: Callable, _direc: str, exc_info: "tuple[type, Exception, types.TracebackType] | None", ) -> None: if exc_info is None: return _, exc_val, _ = exc_info log.error(exc_val) def _rmtree(direc: str) -> None: # in Python 3.12, onexc is added and onerror is deprecated # https://github.com/python/cpython/blob/main/Lib/shutil.py if sys.version_info < (3, 12): shutil.rmtree(direc, onerror=_rmtreeError) return shutil.rmtree(direc, onexc=_rmtreeError) def rmtree(direc: str) -> None: from os.path import isdir try: for _ in range(2): if not isdir(direc): break _rmtree(direc) except Exception: log.exception(f"error removing directory: {direc}") def showMemoryUsage() -> None: if log.level > core.TRACE: return try: import psutil except ModuleNotFoundError: return usage = psutil.Process(os.getpid()).memory_info().rss // 1024 core.trace(log, f"Memory Usage: {usage:,} kB")
3,836
Python
.py
136
25.441176
77
0.699701
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,747
info.py
ilius_pyglossary/pyglossary/info.py
__all__ = [ "c_author", "c_name", "c_publisher", "c_sourceLang", "c_targetLang", "infoKeysAliasDict", ] c_name = "name" c_sourceLang = "sourceLang" c_targetLang = "targetLang" c_copyright = "copyright" c_author = "author" c_publisher = "publisher" infoKeysAliasDict = { "title": c_name, "bookname": c_name, "dbname": c_name, ## "sourcelang": c_sourceLang, "inputlang": c_sourceLang, "origlang": c_sourceLang, ## "targetlang": c_targetLang, "outputlang": c_targetLang, "destlang": c_targetLang, ## "license": c_copyright, ## # do not map "publisher" to "author" ## # are there alternatives to "creationTime" # and "lastUpdated"? }
656
Python
.py
34
17.529412
43
0.690323
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,748
slob.py
ilius_pyglossary/pyglossary/slob.py
# slob.py # Copyright (C) 2020-2023 Saeed Rasooli # Copyright (C) 2019 Igor Tkach <itkach@gmail.com> # as part of https://github.com/itkach/slob # # This program is a free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program. Or on Debian systems, from /usr/share/common-licenses/GPL # If not, see <http://www.gnu.org/licenses/gpl.txt>. from __future__ import annotations import encodings import io import operator import os import pickle import sys import tempfile import typing import warnings from abc import abstractmethod from bisect import bisect_left from builtins import open as fopen from collections.abc import Callable, Iterator, Mapping, Sequence from datetime import datetime, timezone from functools import cache, lru_cache from io import BufferedIOBase, IOBase from os.path import isdir from struct import calcsize, pack, unpack from threading import RLock from types import MappingProxyType, TracebackType from typing import ( TYPE_CHECKING, Any, Generic, NamedTuple, TypeVar, cast, ) from uuid import UUID, uuid4 import icu # type: ignore from icu import Collator, Locale, UCollAttribute, UCollAttributeValue if TYPE_CHECKING: from .icu_types import T_Collator __all__ = [ "MAX_TEXT_LEN", "MAX_TINY_TEXT_LEN", "MIME_HTML", "MIME_TEXT", "MultiFileReader", "UnknownEncoding", "Writer", "encodings", "fopen", "open", "read_byte_string", "read_header", "sortkey", ] DEFAULT_COMPRESSION = "lzma2" UTF8 = "utf-8" MAGIC = b"!-1SLOB\x1f" class Compression(NamedTuple): compress: Callable[..., bytes] # first arg: bytes decompress: Callable[[bytes], bytes] class Ref(NamedTuple): key: str bin_index: int item_index: int fragment: str class Header(NamedTuple): magic: bytes uuid: UUID encoding: str compression: str tags: MappingProxyType[str, str] content_types: Sequence[str] blob_count: int store_offset: int refs_offset: int size: int U_CHAR = ">B" U_CHAR_SIZE = calcsize(U_CHAR) U_SHORT = ">H" U_SHORT_SIZE = calcsize(U_SHORT) U_INT = ">I" U_INT_SIZE = calcsize(U_INT) U_LONG_LONG = ">Q" U_LONG_LONG_SIZE = calcsize(U_LONG_LONG) def calcmax(len_size_spec: str) -> int: return 2 ** (calcsize(len_size_spec) * 8) - 1 MAX_TEXT_LEN = calcmax(U_SHORT) MAX_TINY_TEXT_LEN = calcmax(U_CHAR) MAX_LARGE_BYTE_STRING_LEN = calcmax(U_INT) MAX_BIN_ITEM_COUNT = calcmax(U_SHORT) PRIMARY: int = Collator.PRIMARY SECONDARY: int = Collator.SECONDARY TERTIARY: int = Collator.TERTIARY QUATERNARY: int = Collator.QUATERNARY IDENTICAL: int = Collator.IDENTICAL class CompressionModule(typing.Protocol): # gzip.compress(data, compresslevel=9, *, mtime=None) # bz2.compress(data, compresslevel=9) # zlib.compress(data, /, level=-1, wbits=15) # lzma.compress(data, format=1, check=-1, preset=None, filters=None) @staticmethod def compress(data: bytes, compresslevel: int = 9) -> bytes: raise NotImplementedError # gzip.decompress(data) # bz2.decompress(data) # zlib.decompress(data, /, wbits=15, bufsize=16384) # lzma.decompress(data, format=0, memlimit=None, filters=None) @staticmethod def decompress( data: bytes, **kwargs: "Mapping[str, Any]", ) -> bytes: raise NotImplementedError def init_compressions() -> dict[str, Compression]: def ident(x: bytes) -> bytes: return x compressions: "dict[str, Compression]" = { "": Compression(ident, ident), } for name in ("bz2", "zlib"): m: CompressionModule try: m = cast(CompressionModule, __import__(name)) except ImportError: warnings.showwarning( message=f"{name} is not available", category=ImportWarning, filename=__file__, lineno=0, ) continue def compress_new(x: bytes, m: CompressionModule = m) -> bytes: return m.compress(x, 9) compressions[name] = Compression(compress_new, m.decompress) try: import lzma except ImportError: warnings.warn("lzma is not available", stacklevel=1) else: filters = [{"id": lzma.FILTER_LZMA2}] compressions["lzma2"] = Compression( lambda s: lzma.compress( s, format=lzma.FORMAT_RAW, filters=filters, ), lambda s: lzma.decompress( s, format=lzma.FORMAT_RAW, filters=filters, ), ) return compressions COMPRESSIONS = init_compressions() del init_compressions MIME_TEXT = "text/plain" MIME_HTML = "text/html" class FileFormatException(Exception): pass class UnknownFileFormat(FileFormatException): pass class UnknownCompression(FileFormatException): pass class UnknownEncoding(FileFormatException): pass class IncorrectFileSize(FileFormatException): pass @cache def sortkey( strength: int, maxlength: "int | None" = None, ) -> Callable: # pass empty locale to use root locale # if you pass no arg, it will use system locale c: "T_Collator" = Collator.createInstance(Locale("")) c.setStrength(strength) c.setAttribute( UCollAttribute.ALTERNATE_HANDLING, UCollAttributeValue.SHIFTED, ) if maxlength is None: return c.getSortKey return lambda x: c.getSortKey(x)[:maxlength] class MultiFileReader(BufferedIOBase): def __init__( self, *args: str, ) -> None: filenames: list[str] = list(args) files = [] ranges = [] offset = 0 for name in filenames: size = os.stat(name).st_size ranges.append(range(offset, offset + size)) files.append(fopen(name, "rb")) offset += size self.size = offset self._ranges = ranges self._files = files self._fcount = len(self._files) self._offset = -1 self.seek(0) def __enter__(self) -> MultiFileReader: return self def __exit__( self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None, ) -> None: self.close() def close(self) -> None: for f in self._files: f.close() self._files.clear() self._ranges.clear() @property def closed(self) -> bool: return len(self._ranges) == 0 def isatty(self) -> bool: # noqa: PLR6301 return False def readable(self) -> bool: # noqa: PLR6301 return True def seek( self, offset: int, whence: int = io.SEEK_SET, ) -> int: if whence == io.SEEK_SET: self._offset = offset elif whence == io.SEEK_CUR: self._offset += offset elif whence == io.SEEK_END: self._offset = self.size + offset else: raise ValueError(f"Invalid value for parameter whence: {whence!r}") return self._offset def seekable(self) -> bool: # noqa: PLR6301 return True def tell(self) -> int: return self._offset def writable(self) -> bool: # noqa: PLR6301 return False def read(self, n: "int | None" = -1) -> bytes: file_index = -1 actual_offset = 0 for i, r in enumerate(self._ranges): if self._offset in r: file_index = i actual_offset = self._offset - r.start break result = b"" to_read = self.size if n == -1 or n is None else n while -1 < file_index < self._fcount: f = self._files[file_index] f.seek(actual_offset) read = f.read(to_read) read_count = len(read) self._offset += read_count result += read to_read -= read_count if to_read > 0: file_index += 1 actual_offset = 0 else: break return result class KeydItemDict: def __init__( self, blobs: "Sequence[Blob | Ref]", strength: int, maxlength: "int | None" = None, ) -> None: self.blobs = blobs self.sortkey = sortkey(strength, maxlength=maxlength) def __len__(self) -> int: return len(self.blobs) # https://docs.python.org/3/library/bisect.html # key= parameter to bisect_left is added in Python 3.10 def __getitem__(self, key: str) -> Iterator[Blob | Ref]: blobs = self.blobs key_as_sk = self.sortkey(key) i = bisect_left( blobs, key_as_sk, key=lambda blob: self.sortkey(blob.key), ) if i == len(blobs): return while i < len(blobs): if self.sortkey(blobs[i].key) == key_as_sk: yield blobs[i] else: break i += 1 def __contains__(self, key: str) -> bool: try: next(self[key]) except StopIteration: return False return True class Blob: def __init__( # noqa: PLR0913 self, content_id: int, key: str, fragment: str, read_content_type_func: "Callable[[], str]", read_func: Callable, ) -> None: # print(f"read_func is {type(read_func)}") # read_func is <class 'functools._lru_cache_wrapper'> self._content_id = content_id self._key = key self._fragment = fragment self._read_content_type = read_content_type_func self._read = read_func @property def identity(self) -> int: return self._content_id @property def key(self) -> str: return self._key @property def fragment(self) -> str: return self._fragment @property def content_type(self) -> str: return self._read_content_type() @property def content(self) -> bytes: return self._read() def __str__(self) -> str: return self.key def __repr__(self) -> str: return f"<{self.__class__.__module__}.{self.__class__.__name__} {self.key}>" def read_byte_string(f: IOBase, len_spec: str) -> bytes: length = unpack(len_spec, f.read(calcsize(len_spec)))[0] return f.read(length) class StructReader: def __init__( self, _file: IOBase, encoding: "str | None" = None, ) -> None: self._file = _file self.encoding = encoding def read_int(self) -> int: s = self.read(U_INT_SIZE) return unpack(U_INT, s)[0] def read_long(self) -> int: b = self.read(U_LONG_LONG_SIZE) return unpack(U_LONG_LONG, b)[0] def read_byte(self) -> int: s = self.read(U_CHAR_SIZE) return unpack(U_CHAR, s)[0] def read_short(self) -> int: return unpack(U_SHORT, self._file.read(U_SHORT_SIZE))[0] def _read_text(self, len_spec: str) -> str: if self.encoding is None: raise ValueError("self.encoding is None") max_len = 2 ** (8 * calcsize(len_spec)) - 1 byte_string = read_byte_string(self._file, len_spec) if len(byte_string) == max_len: terminator = byte_string.find(0) if terminator > -1: byte_string = byte_string[:terminator] return byte_string.decode(self.encoding) def read_tiny_text(self) -> str: return self._read_text(U_CHAR) def read_text(self) -> str: return self._read_text(U_SHORT) def read(self, n: int) -> bytes: return self._file.read(n) def write(self, data: bytes) -> int: return self._file.write(data) def seek(self, pos: int) -> None: self._file.seek(pos) def tell(self) -> int: return self._file.tell() def close(self) -> None: self._file.close() def flush(self) -> None: self._file.flush() class StructWriter: def __init__( self, _file: "io.BufferedWriter", encoding: "str | None" = None, ) -> None: self._file = _file self.encoding = encoding def write_int(self, value: int) -> None: self._file.write(pack(U_INT, value)) def write_long(self, value: int) -> None: self._file.write(pack(U_LONG_LONG, value)) def write_byte(self, value: int) -> None: self._file.write(pack(U_CHAR, value)) def write_short(self, value: int) -> None: self._file.write(pack(U_SHORT, value)) def _write_text( self, text: str, len_size_spec: str, encoding: "str | None" = None, pad_to_length: "int | None" = None, ) -> None: if encoding is None: encoding = self.encoding if encoding is None: raise ValueError("encoding is None") text_bytes = text.encode(encoding) length = len(text_bytes) max_length = calcmax(len_size_spec) if length > max_length: raise ValueError(f"Text is too long for size spec {len_size_spec}") self._file.write( pack( len_size_spec, pad_to_length or length, ), ) self._file.write(text_bytes) if pad_to_length: for _ in range(pad_to_length - length): self._file.write(pack(U_CHAR, 0)) def write_tiny_text( self, text: str, encoding: "str | None" = None, editable: bool = False, ) -> None: pad_to_length = 255 if editable else None self._write_text( text, U_CHAR, encoding=encoding, pad_to_length=pad_to_length, ) def write_text( self, text: str, encoding: "str | None" = None, ) -> None: self._write_text(text, U_SHORT, encoding=encoding) def close(self) -> None: self._file.close() def flush(self) -> None: self._file.flush() @property def name(self) -> str: return self._file.name def tell(self) -> int: return self._file.tell() def write(self, data: bytes) -> int: return self._file.write(data) def read_header(_file: MultiFileReader) -> Header: _file.seek(0) magic = _file.read(len(MAGIC)) if magic != MAGIC: raise UnknownFileFormat(f"magic {magic!r} != {MAGIC!r}") uuid = UUID(bytes=_file.read(16)) encoding = read_byte_string(_file, U_CHAR).decode(UTF8) if encodings.search_function(encoding) is None: raise UnknownEncoding(encoding) reader = StructReader(_file, encoding) compression = reader.read_tiny_text() if compression not in COMPRESSIONS: raise UnknownCompression(compression) def read_tags() -> dict[str, str]: count = reader.read_byte() return {reader.read_tiny_text(): reader.read_tiny_text() for _ in range(count)} tags = read_tags() def read_content_types() -> Sequence[str]: content_types: list[str] = [] count = reader.read_byte() for _ in range(count): content_type = reader.read_text() content_types.append(content_type) return tuple(content_types) content_types = read_content_types() blob_count = reader.read_int() store_offset = reader.read_long() size = reader.read_long() refs_offset = reader.tell() return Header( magic=magic, uuid=uuid, encoding=encoding, compression=compression, tags=MappingProxyType(tags), content_types=content_types, blob_count=blob_count, store_offset=store_offset, refs_offset=refs_offset, size=size, ) def meld_ints(a: int, b: int) -> int: return (a << 16) | b def unmeld_ints(c: int) -> tuple[int, int]: bstr = bin(c).lstrip("0b").zfill(48) a, b = bstr[-48:-16], bstr[-16:] return int(a, 2), int(b, 2) class Slob: def __init__( self, *filenames: str, ) -> None: self._f = MultiFileReader(*filenames) try: self._header = read_header(self._f) if self._f.size != self._header.size: raise IncorrectFileSize( f"File size should be {self._header.size}, " f"{self._f.size} bytes found", ) except FileFormatException: self._f.close() raise self._refs = RefList( self._f, self._header.encoding, offset=self._header.refs_offset, ) self._g = MultiFileReader(*filenames) self._store = Store( self._g, self._header.store_offset, COMPRESSIONS[self._header.compression].decompress, self._header.content_types, ) def __enter__(self) -> Slob: return self def __exit__( self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None, ) -> None: self.close() @property def identity(self) -> str: return self._header.uuid.hex @property def content_types(self) -> Sequence[str]: return self._header.content_types @property def tags(self) -> MappingProxyType[str, str]: return self._header.tags @property def blob_count(self) -> int: return self._header.blob_count @property def compression(self) -> str: return self._header.compression @property def encoding(self) -> str: return self._header.encoding def __len__(self) -> int: return len(self._refs) def __getitem__(self, i: int) -> Any: # this is called by bisect_left return self.getBlobByIndex(i) def __iter__(self) -> Iterator[Blob]: for i in range(len(self._refs)): yield self.getBlobByIndex(i) def count(self) -> int: # just to comply with Sequence and make type checker happy raise NotImplementedError def index(self, x: Blob) -> int: # just to comply with Sequence and make type checker happy raise NotImplementedError def getBlobByIndex(self, i: int) -> Blob: ref = self._refs[i] def read_func() -> bytes: return self._store.get(ref.bin_index, ref.item_index)[1] read_func = lru_cache(maxsize=None)(read_func) def read_content_type_func() -> str: return self._store.content_type(ref.bin_index, ref.item_index) content_id = meld_ints(ref.bin_index, ref.item_index) return Blob( content_id=content_id, key=ref.key, fragment=ref.fragment, read_content_type_func=read_content_type_func, read_func=read_func, ) def get(self, blob_id: int) -> tuple[str, bytes]: """Returns (content_type: str, content: bytes).""" bin_index, bin_item_index = unmeld_ints(blob_id) return self._store.get(bin_index, bin_item_index) @cache def as_dict( self: Slob, strength: int = TERTIARY, maxlength: "int | None" = None, ) -> KeydItemDict: return KeydItemDict( cast(Sequence, self), strength=strength, maxlength=maxlength, ) def close(self) -> None: self._f.close() self._g.close() def open(*filenames: str) -> Slob: return Slob(*filenames) class BinMemWriter: def __init__(self) -> None: self.content_type_ids: list[int] = [] self.item_dir: list[bytes] = [] self.items: list[bytes] = [] self.current_offset = 0 def add(self, content_type_id: int, blob_bytes: bytes) -> None: self.content_type_ids.append(content_type_id) self.item_dir.append(pack(U_INT, self.current_offset)) length_and_bytes = pack(U_INT, len(blob_bytes)) + blob_bytes self.items.append(length_and_bytes) self.current_offset += len(length_and_bytes) def __len__(self) -> int: return len(self.item_dir) def finalize( self, fout: BufferedIOBase, compress: "Callable[[bytes], bytes]", ) -> None: count = len(self) fout.write(pack(U_INT, count)) for content_type_id in self.content_type_ids: fout.write(pack(U_CHAR, content_type_id)) content = b"".join(self.item_dir + self.items) compressed = compress(content) fout.write(pack(U_INT, len(compressed))) fout.write(compressed) self.content_type_ids.clear() self.item_dir.clear() self.items.clear() ItemT = TypeVar("ItemT") class ItemList(Generic[ItemT]): def __init__( self, reader: StructReader, offset: int, count_or_spec: "str | int", pos_spec: str, ) -> None: self.lock = RLock() self.reader = reader reader.seek(offset) count: int if isinstance(count_or_spec, str): count_spec = count_or_spec count = unpack(count_spec, reader.read(calcsize(count_spec)))[0] elif isinstance(count_or_spec, int): count = count_or_spec else: raise TypeError(f"invalid {count_or_spec = }") self._count: int = count self.pos_offset = reader.tell() self.pos_spec = pos_spec self.pos_size = calcsize(pos_spec) self.data_offset = self.pos_offset + self.pos_size * count def __len__(self) -> int: return self._count def pos(self, i: int) -> int: with self.lock: self.reader.seek(self.pos_offset + self.pos_size * i) return unpack(self.pos_spec, self.reader.read(self.pos_size))[0] def read(self, pos: int) -> ItemT: with self.lock: self.reader.seek(self.data_offset + pos) return self._read_item() @abstractmethod def _read_item(self) -> ItemT: pass def __getitem__(self, i: int) -> ItemT: if i >= len(self) or i < 0: raise IndexError("index out of range") return self.read(self.pos(i)) class RefList(ItemList[Ref]): def __init__( self, f: IOBase, encoding: str, offset: int = 0, count: "int | None" = None, ) -> None: super().__init__( reader=StructReader(f, encoding), offset=offset, count_or_spec=U_INT if count is None else count, pos_spec=U_LONG_LONG, ) @lru_cache(maxsize=512) def __getitem__( self, i: int, ) -> Ref: if i >= len(self) or i < 0: raise IndexError("index out of range") return cast(Ref, self.read(self.pos(i))) def _read_item(self) -> Ref: key = self.reader.read_text() bin_index = self.reader.read_int() item_index = self.reader.read_short() fragment = self.reader.read_tiny_text() return Ref( key=key, bin_index=bin_index, item_index=item_index, fragment=fragment, ) @cache def as_dict( self: RefList, strength: int = TERTIARY, maxlength: "int | None" = None, ) -> KeydItemDict: return KeydItemDict( cast(Sequence, self), strength=strength, maxlength=maxlength, ) class Bin(ItemList[bytes]): def __init__( self, count: int, bin_bytes: bytes, ) -> None: super().__init__( reader=StructReader(io.BytesIO(bin_bytes)), offset=0, count_or_spec=count, pos_spec=U_INT, ) def _read_item(self) -> bytes: content_len = self.reader.read_int() return self.reader.read(content_len) class StoreItem(NamedTuple): content_type_ids: list[int] compressed_content: bytes class Store(ItemList[StoreItem]): def __init__( self, _file: IOBase, offset: int, decompress: "Callable[[bytes], bytes]", content_types: Sequence[str], ) -> None: super().__init__( reader=StructReader(_file), offset=offset, count_or_spec=U_INT, pos_spec=U_LONG_LONG, ) self.decompress = decompress self.content_types = content_types @lru_cache(maxsize=32) def __getitem__( self, i: int, ) -> StoreItem: if i >= len(self) or i < 0: raise IndexError("index out of range") return cast(StoreItem, self.read(self.pos(i))) def _read_item(self) -> StoreItem: bin_item_count = self.reader.read_int() packed_content_type_ids = self.reader.read(bin_item_count * U_CHAR_SIZE) content_type_ids = [] for i in range(bin_item_count): content_type_id = unpack(U_CHAR, packed_content_type_ids[i : i + 1])[0] content_type_ids.append(content_type_id) content_length = self.reader.read_int() content = self.reader.read(content_length) return StoreItem( content_type_ids=content_type_ids, compressed_content=content, ) def _content_type( self, bin_index: int, item_index: int, ) -> tuple[str, StoreItem]: store_item = self[bin_index] content_type_id = store_item.content_type_ids[item_index] content_type = self.content_types[content_type_id] return content_type, store_item def content_type( self, bin_index: int, item_index: int, ) -> str: return self._content_type(bin_index, item_index)[0] @lru_cache(maxsize=16) def _decompress(self, bin_index: int) -> bytes: store_item = self[bin_index] return self.decompress(store_item.compressed_content) def get( self, bin_index: int, item_index: int, ) -> tuple[str, bytes]: content_type, store_item = self._content_type(bin_index, item_index) content = self._decompress(bin_index) count = len(store_item.content_type_ids) store_bin = Bin(count, content) content = store_bin[item_index] return (content_type, content) class WriterEvent(NamedTuple): name: str data: Any class Writer: def __init__( # noqa: PLR0913 self, filename: str, workdir: "str | None" = None, encoding: str = UTF8, compression: "str | None" = DEFAULT_COMPRESSION, min_bin_size: int = 512 * 1024, max_redirects: int = 5, observer: "Callable[[WriterEvent], None] | None" = None, version_info: bool = True, ) -> None: self.filename = filename self.observer = observer if os.path.exists(self.filename): raise SystemExit(f"File {self.filename!r} already exists") # make sure we can write with fopen(self.filename, "wb"): pass self.encoding = encoding if encodings.search_function(self.encoding) is None: raise UnknownEncoding(self.encoding) self.workdir = workdir self.tmpdir = tmpdir = tempfile.TemporaryDirectory( prefix=f"{os.path.basename(filename)}-", dir=workdir, ) self.f_ref_positions = self._wbfopen("ref-positions") self.f_store_positions = self._wbfopen("store-positions") self.f_refs = self._wbfopen("refs") self.f_store = self._wbfopen("store") self.max_redirects = max_redirects if max_redirects: self.aliases_path = os.path.join(tmpdir.name, "aliases") self.f_aliases = Writer( self.aliases_path, workdir=tmpdir.name, max_redirects=0, compression=None, version_info=False, ) if compression is None: compression = "" if compression not in COMPRESSIONS: raise UnknownCompression(compression) self.compress = COMPRESSIONS[compression].compress self.compression = compression self.content_types: "dict[str, int]" = {} self.min_bin_size = min_bin_size self.current_bin: "BinMemWriter | None" = None created_at = ( os.getenv("SLOB_TIMESTAMP") or datetime.now(timezone.utc).isoformat() ) self.blob_count = 0 self.ref_count = 0 self.bin_count = 0 self._tags = { "created.at": created_at, } if version_info: self._tags.update( { "version.python": sys.version.replace("\n", " "), "version.pyicu": icu.VERSION, "version.icu": icu.ICU_VERSION, }, ) self.tags = MappingProxyType(self._tags) def _wbfopen(self, name: str) -> StructWriter: return StructWriter( fopen(os.path.join(self.tmpdir.name, name), "wb"), encoding=self.encoding, ) def tag(self, name: str, value: str = "") -> None: if len(name.encode(self.encoding)) > MAX_TINY_TEXT_LEN: self._fire_event("tag_name_too_long", (name, value)) return if len(value.encode(self.encoding)) > MAX_TINY_TEXT_LEN: self._fire_event("tag_value_too_long", (name, value)) value = "" self._tags[name] = value @staticmethod def key_is_too_long(actual_key, fragment) -> bool: return len(actual_key) > MAX_TEXT_LEN or len(fragment) > MAX_TINY_TEXT_LEN @staticmethod def _split_key( key: str | tuple[str, str], ) -> tuple[str, str]: if isinstance(key, str): actual_key = key fragment = "" else: actual_key, fragment = key return actual_key, fragment def add( self, blob: bytes, *keys: str, content_type: str = "", ) -> None: if len(blob) > MAX_LARGE_BYTE_STRING_LEN: self._fire_event("content_too_long", blob) return if len(content_type) > MAX_TEXT_LEN: self._fire_event("content_type_too_long", content_type) return actual_keys = [] for key in keys: actual_key, fragment = self._split_key(key) if self.key_is_too_long(actual_key, fragment): self._fire_event("key_too_long", key) else: actual_keys.append((actual_key, fragment)) if not actual_keys: return current_bin = self.current_bin if current_bin is None: current_bin = self.current_bin = BinMemWriter() self.bin_count += 1 if content_type not in self.content_types: self.content_types[content_type] = len(self.content_types) current_bin.add(self.content_types[content_type], blob) self.blob_count += 1 bin_item_index = len(current_bin) - 1 bin_index = self.bin_count - 1 for actual_key, fragment in actual_keys: self._write_ref(actual_key, bin_index, bin_item_index, fragment) if ( current_bin.current_offset > self.min_bin_size or len(current_bin) == MAX_BIN_ITEM_COUNT ): self._write_current_bin() def add_alias(self, key: str, target_key: str) -> None: if not self.max_redirects: raise NotImplementedError if self.key_is_too_long(*self._split_key(key)): self._fire_event("alias_too_long", key) return if self.key_is_too_long(*self._split_key(target_key)): self._fire_event("alias_target_too_long", target_key) return self.f_aliases.add(pickle.dumps(target_key), key) def _fire_event( self, name: str, data: Any = None, ) -> None: if self.observer: self.observer(WriterEvent(name, data)) def _write_current_bin(self) -> None: current_bin = self.current_bin if current_bin is None: return self.f_store_positions.write_long(self.f_store.tell()) current_bin.finalize( self.f_store._file, self.compress, ) self.current_bin = None def _write_ref( self, key: str, bin_index: int, item_index: int, fragment: str = "", ) -> None: self.f_ref_positions.write_long(self.f_refs.tell()) self.f_refs.write_text(key) self.f_refs.write_int(bin_index) self.f_refs.write_short(item_index) self.f_refs.write_tiny_text(fragment) self.ref_count += 1 def _sort(self) -> None: self._fire_event("begin_sort") f_ref_positions_sorted = self._wbfopen("ref-positions-sorted") self.f_refs.flush() self.f_ref_positions.close() with MultiFileReader(self.f_ref_positions.name, self.f_refs.name) as f: ref_list = RefList(f, self.encoding, count=self.ref_count) sortkey_func = sortkey(IDENTICAL) for i in sorted( range(len(ref_list)), key=lambda j: sortkey_func(ref_list[j].key), ): ref_pos = ref_list.pos(i) f_ref_positions_sorted.write_long(ref_pos) f_ref_positions_sorted.close() os.remove(self.f_ref_positions.name) os.rename(f_ref_positions_sorted.name, self.f_ref_positions.name) self.f_ref_positions = StructWriter( fopen(self.f_ref_positions.name, "ab"), encoding=self.encoding, ) self._fire_event("end_sort") def _resolve_aliases(self) -> None: # noqa: PLR0912 self._fire_event("begin_resolve_aliases") self.f_aliases.finalize() def read_key_frag(item: Blob, default_fragment: str) -> tuple[str, str]: key_frag = pickle.loads(item.content) if isinstance(key_frag, str): return key_frag, default_fragment to_key, fragment = key_frag return to_key, fragment with MultiFileReader( self.f_ref_positions.name, self.f_refs.name, ) as f_ref_list: ref_list = RefList(f_ref_list, self.encoding, count=self.ref_count) ref_dict = ref_list.as_dict() with Slob(self.aliases_path) as aliasesSlob: aliases = aliasesSlob.as_dict() path = os.path.join(self.tmpdir.name, "resolved-aliases") alias_writer = Writer( path, workdir=self.tmpdir.name, max_redirects=0, compression=None, version_info=False, ) for item in aliasesSlob: from_key = item.key keys = set() keys.add(from_key) to_key, fragment = read_key_frag(item, item.fragment) count = 0 while count <= self.max_redirects: # is target key itself a redirect? try: alias_item: Blob = next(aliases[to_key]) except StopIteration: break orig_to_key = to_key to_key, fragment = read_key_frag( alias_item, fragment, ) count += 1 keys.add(orig_to_key) if count > self.max_redirects: self._fire_event("too_many_redirects", from_key) target_ref: Ref try: target_ref = cast(Ref, next(ref_dict[to_key])) except StopIteration: self._fire_event("alias_target_not_found", to_key) else: for key in keys: ref = Ref( key=key, bin_index=target_ref.bin_index, item_index=target_ref.item_index, # last fragment in the chain wins fragment=target_ref.fragment or fragment, ) alias_writer.add(pickle.dumps(ref), key) alias_writer.finalize() with Slob(path) as resolved_aliases_reader: previous = None targets = set() for item in resolved_aliases_reader: ref = pickle.loads(item.content) if previous is not None and ref.key != previous.key: for bin_index, item_index, fragment in sorted(targets): self._write_ref(previous.key, bin_index, item_index, fragment) targets.clear() targets.add((ref.bin_index, ref.item_index, ref.fragment)) previous = ref for bin_index, item_index, fragment in sorted(targets): self._write_ref(previous.key, bin_index, item_index, fragment) self._sort() self._fire_event("end_resolve_aliases") def finalize(self) -> None: self._fire_event("begin_finalize") if self.current_bin is not None: self._write_current_bin() self._sort() if self.max_redirects: self._resolve_aliases() files = ( self.f_ref_positions, self.f_refs, self.f_store_positions, self.f_store, ) for f in files: f.close() buf_size = 10 * 1024 * 1024 def write_tags(tags: "MappingProxyType[str, Any]", f: StructWriter) -> None: f.write(pack(U_CHAR, len(tags))) for key, value in tags.items(): f.write_tiny_text(key) f.write_tiny_text(value, editable=True) with fopen(self.filename, mode="wb") as output_file: out = StructWriter(output_file, self.encoding) out.write(MAGIC) out.write(uuid4().bytes) out.write_tiny_text(self.encoding, encoding=UTF8) out.write_tiny_text(self.compression) write_tags(self.tags, out) def write_content_types( content_types: "dict[str, int]", f: StructWriter, ) -> None: count = len(content_types) f.write(pack(U_CHAR, count)) types = sorted(content_types.items(), key=operator.itemgetter(1)) for content_type, _ in types: f.write_text(content_type) write_content_types(self.content_types, out) out.write_int(self.blob_count) store_offset = ( out.tell() + U_LONG_LONG_SIZE # this value + U_LONG_LONG_SIZE # file size value + U_INT_SIZE # ref count value + os.stat(self.f_ref_positions.name).st_size + os.stat(self.f_refs.name).st_size ) out.write_long(store_offset) out.flush() file_size = ( out.tell() # bytes written so far + U_LONG_LONG_SIZE # file size value + 2 * U_INT_SIZE # ref count and bin count ) file_size += sum(os.stat(f.name).st_size for f in files) out.write_long(file_size) def mv(src: StructWriter, out: StructWriter) -> None: fname = src.name self._fire_event("begin_move", fname) with fopen(fname, mode="rb") as f: while True: data = f.read(buf_size) if len(data) == 0: break out.write(data) out.flush() os.remove(fname) self._fire_event("end_move", fname) out.write_int(self.ref_count) mv(self.f_ref_positions, out) mv(self.f_refs, out) out.write_int(self.bin_count) mv(self.f_store_positions, out) mv(self.f_store, out) self.f_ref_positions = None # type: ignore # noqa: PGH003 self.f_refs = None # type: ignore # noqa: PGH003 self.f_store_positions = None # type: ignore # noqa: PGH003 self.f_store = None # type: ignore # noqa: PGH003 self.tmpdir.cleanup() self._fire_event("end_finalize") def size_header(self) -> int: size = 0 size += len(MAGIC) size += 16 # uuid bytes size += U_CHAR_SIZE + len(self.encoding.encode(UTF8)) size += U_CHAR_SIZE + len(self.compression.encode(self.encoding)) size += U_CHAR_SIZE # tag length size += U_CHAR_SIZE # content types count # tags and content types themselves counted elsewhere size += U_INT_SIZE # blob count size += U_LONG_LONG_SIZE # store offset size += U_LONG_LONG_SIZE # file size size += U_INT_SIZE # ref count size += U_INT_SIZE # bin count return size def size_tags(self) -> int: size = 0 for key in self.tags: size += U_CHAR_SIZE + len(key.encode(self.encoding)) size += 255 return size def size_content_types(self) -> int: size = 0 for content_type in self.content_types: size += U_CHAR_SIZE + len(content_type.encode(self.encoding)) return size def size_data(self) -> int: files = ( self.f_ref_positions, self.f_refs, self.f_store_positions, self.f_store, ) return sum(os.stat(f.name).st_size for f in files) def __enter__(self) -> Slob: return cast("Slob", self) def close(self) -> None: for _file in ( self.f_ref_positions, self.f_refs, self.f_store_positions, self.f_store, ): if _file is None: continue self._fire_event("WARNING: closing without finalize()") try: _file.close() except Exception: pass if self.tmpdir and isdir(self.tmpdir.name): self.tmpdir.cleanup() self.tmpdir = None # type: ignore # noqa: PGH003 def __exit__( self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None, ) -> None: """ It used to call self.finalize() here that was bad! __exit__ is not meant for doing so much as finalize() is doing! so make sure to call writer.finalize() after you are done!. """ self.close()
36,090
Python
.py
1,243
25.740145
81
0.69177
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,749
compression.py
ilius_pyglossary/pyglossary/compression.py
# -*- coding: utf-8 -*- from __future__ import annotations import logging import os from os.path import join from typing import TYPE_CHECKING if TYPE_CHECKING: import io from collections.abc import Callable from .glossary_types import GlossaryType stdCompressions = ("gz", "bz2", "lzma") log = logging.getLogger("pyglossary") __all__ = [ "compress", "compressionOpen", "compressionOpenFunc", "stdCompressions", "uncompress", "zipFileOrDir", ] def compressionOpenFunc(c: str) -> Callable | None: if not c: return open if c == "gz": import gzip return gzip.open if c == "bz2": import bz2 return bz2.open if c == "lzma": import lzma return lzma.open if c == "dz": import gzip return gzip.open return None def compressionOpen( filename: str, dz: bool = False, **kwargs, # noqa: ANN003 ) -> io.IOBase: from os.path import splitext filenameNoExt, ext = splitext(filename) ext = ext.lower().lstrip(".") try: int(ext) except ValueError: pass else: _, ext = splitext(filenameNoExt) ext = ext.lower().lstrip(".") if ext in stdCompressions or (dz and ext == "dz"): openFunc = compressionOpenFunc(ext) if not openFunc: raise RuntimeError(f"no compression found for {ext=}") _file = openFunc(filename, **kwargs) _file.compression = ext return _file return open(filename, **kwargs) # noqa: SIM115 def zipFileOrDir(filename: str) -> None: import shutil import zipfile from os.path import ( isdir, isfile, split, ) from .os_utils import indir def _zipFileAdd(zf: zipfile.ZipFile, filename: str) -> None: if isfile(filename): zf.write(filename) return if not isdir(filename): raise OSError(f"Not a file or directory: {filename}") for subFname in os.listdir(filename): _zipFileAdd(zf, join(filename, subFname)) with zipfile.ZipFile(f"{filename}.zip", mode="w") as zf: if isdir(filename): dirn, name = split(filename) with indir(filename): for subFname in os.listdir(filename): _zipFileAdd(zf, subFname) shutil.rmtree(filename) return dirn, name = split(filename) files = [name] if isdir(f"{filename}_res"): files.append(f"{name}_res") with indir(dirn): for fname in files: _zipFileAdd(zf, fname) def compress(_glos: GlossaryType, filename: str, compression: str) -> str: """ Filename is the existing file path. supported compressions: "gz", "bz2", "lzma", "zip". """ import shutil from os.path import isfile log.info(f"Compressing {filename!r} with {compression!r}") compFilename = f"{filename}.{compression}" if compression in stdCompressions: openFunc = compressionOpenFunc(compression) if not openFunc: raise RuntimeError(f"invalid {compression=}") with openFunc(compFilename, mode="wb") as dest: with open(filename, mode="rb") as source: shutil.copyfileobj(source, dest) return compFilename if compression == "zip": try: os.remove(compFilename) except OSError: pass try: zipFileOrDir(filename) except Exception as e: log.error( f'{e}\nFailed to compress file "{filename}"', ) else: raise ValueError(f"unexpected {compression=}") if isfile(compFilename): return compFilename return filename def uncompress(srcFilename: str, dstFilename: str, compression: str) -> None: """ Filename is the existing file path. supported compressions: "gz", "bz2", "lzma". """ import shutil log.info(f"Uncompressing {srcFilename!r} to {dstFilename!r}") if compression in stdCompressions: openFunc = compressionOpenFunc(compression) if not openFunc: raise RuntimeError(f"invalid {compression=}") with openFunc(srcFilename, mode="rb") as source: with open(dstFilename, mode="wb") as dest: shutil.copyfileobj(source, dest) return # TODO: if compression == "zip": raise ValueError(f"unsupported compression {compression!r}")
3,854
Python
.py
141
24.453901
77
0.726456
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,750
file_utils.py
ilius_pyglossary/pyglossary/file_utils.py
from __future__ import annotations import sys from itertools import ( repeat, takewhile, ) __all__ = ["fileCountLines"] def fileCountLines(filename: str, newline: bytes = b"\n") -> int: with open(filename, "rb") as _file: bufgen = takewhile( lambda x: x, # predicate (_file.read(1024 * 1024) for _ in repeat(None)), # iterable ) return sum(buf.count(newline) for buf in bufgen if buf) if __name__ == "__main__": for filename in sys.argv[1:]: print(fileCountLines(filename), filename) # noqa: T201
524
Python
.py
17
28.411765
65
0.686627
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,751
entry_base.py
ilius_pyglossary/pyglossary/entry_base.py
# -*- coding: utf-8 -*- from __future__ import annotations import typing # from typing import TYPE_CHECKING __all__ = ["BaseEntry", "MultiStr"] MultiStr: typing.TypeAlias = "str | list[str]" class BaseEntry: __slots__: list[str] = [ "_word", ] def __init__(self) -> None: self._word: str | list[str] @property def s_word(self) -> str: raise NotImplementedError @property def defi(self) -> str: raise NotImplementedError @property def b_word(self) -> bytes: """Returns bytes of word and all the alternate words separated by b"|".""" return self.s_word.encode("utf-8") @property def b_defi(self) -> bytes: """Returns definition in bytes.""" return self.defi.encode("utf-8")
711
Python
.py
26
24.846154
76
0.686478
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,752
writing_system.py
ilius_pyglossary/pyglossary/langs/writing_system.py
from __future__ import annotations import unicodedata from typing import Literal, NamedTuple __all__ = [ "WritingSystem", "getAllWritingSystemsFromText", "getWritingSystemFromText", # 'unicodeNextWord', "writingSystemByLowercaseName", "writingSystemByName", "writingSystemByUnicode", "writingSystemList", ] class WritingSystem(NamedTuple): name: str iso: list[tuple[int, str]] | list[tuple[int, str, str]] = [] unicode: list = [] titleTag: str = "b" direction: Literal["ltr", "rtl", "ttb"] = "ltr" comma: str = ", " pop: int | float = 0 # population in millions # digits and FULLWIDTH DIGITs are considered neutral/ignored, not Latin # scripts are separated into multiple groups based on their popularity # (usage in multiple live languages, and number of native speakers) writingSystemList = [ WritingSystem( name="Latin", iso=[(215, "Latn")], unicode=[ "LATIN", ], titleTag="b", comma=", ", pop=4900, ), WritingSystem( name="Arabic", iso=[(160, "Arab")], unicode=["ARABIC"], titleTag="b", direction="rtl", comma="، ", pop=670, ), WritingSystem( name="Cyrillic", iso=[(220, "Cyrl")], unicode=["CYRILLIC"], titleTag="b", comma=", ", pop=250, ), WritingSystem( name="CJK", iso=[ (285, "Bopo", "BOPOMOFO"), (286, "Hang", "HANGUL"), (410, "Hira", "HIRAGANA"), (411, "Kana", "KATAKANA"), (412, "Hrkt", "KATAKANA OR HIRAGANA"), (460, "Yiii", "Yi"), (499, "Nshu", "NUSHU"), (500, "Hani", "HAN"), # aka Hanzi, Kanji, Hanja (501, "Hans", "SIMPLIFIED HAN"), (502, "Hant", "TRADITIONAL HAN"), ], unicode=[ "CJK", "HIRAGANA", "KATAKANA", "IDEOGRAPHIC", # Ideographic Description Characters "DITTO", # Ditto mark "HANGUL", # Korean alphabet "HALFWIDTH KATAKANA", "HALFWIDTH HANGUL", "YI", # https://en.wikipedia.org/wiki/Yi_script "FULLWIDTH LATIN", "BOPOMOFO", "NUSHU", ], titleTag="big", comma="�", pop=1540, # Chinese=1340, Kana=120, Hangul=78.7 ), WritingSystem( name="Devanagari", iso=[(315, "Deva")], unicode=["DEVANAGARI"], titleTag="big", comma=", ", pop=610, ), # _____________________________________________________ WritingSystem( name="Armenian", iso=[(230, "Armn")], unicode=["ARMENIAN"], titleTag="big", comma=", ", pop=12, ), WritingSystem( name="Bengali-Assamese", iso=[(325, "Beng")], unicode=["BENGALI"], titleTag="big", comma=", ", pop=270, ), WritingSystem( name="Burmese", iso=[(350, "Mymr")], unicode=["MYANMAR"], titleTag="big", comma=", ", # almost not used except in English phrases pop=39, ), WritingSystem( name="Ge'ez", iso=[(430, "Ethi")], unicode=["ETHIOPIC"], titleTag="big", comma=", ", pop=21, ), WritingSystem( name="Greek", iso=[(200, "Grek")], unicode=["GREEK"], titleTag="b", comma=", ", pop=11, ), WritingSystem( name="Gujarati", iso=[(320, "Gujr")], unicode=["GUJARATI"], titleTag="big", comma=", ", pop=48, ), WritingSystem( name="Gurmukhi", iso=[(310, "Guru")], unicode=["GURMUKHI"], titleTag="big", comma=", ", pop=22, ), WritingSystem( name="Hebrew", iso=[(125, "Hebr")], unicode=["HEBREW"], titleTag="big", direction="rtl", comma=", ", pop=14, ), WritingSystem( name="Kannada", iso=[(345, "Knda")], unicode=["KANNADA"], titleTag="big", comma=", ", pop=45, ), WritingSystem( name="Khmer", iso=[(355, "Khmr")], unicode=["KHMER"], titleTag="big", comma=", ", pop=11.4, ), WritingSystem( name="Lao", iso=[(356, "Laoo")], unicode=["LAO"], titleTag="big", comma=", ", pop=22, ), WritingSystem( name="Malayalam", iso=[(347, "Mlym")], unicode=["MALAYALAM"], titleTag="big", comma=", ", pop=38, ), WritingSystem( name="Odia", iso=[(327, "Orya")], unicode=["ORIYA"], titleTag="big", comma=", ", pop=21, ), WritingSystem( name="Sinhala", iso=[(348, "Sinh")], unicode=["SINHALA"], titleTag="big", comma=", ", pop=14.4, ), WritingSystem( name="Sundanese", iso=[(362, "Sund")], unicode=["SUNDANESE"], titleTag="big", comma=", ", pop=38, ), WritingSystem( name="Brahmi", iso=[ (300, "Brah", "Brahmi"), ], unicode=["BRAHMI"], titleTag="big", comma=", ", ), WritingSystem( name="Tamil", iso=[ (346, "Taml", "Tamil"), ], unicode=["TAMIL"], titleTag="big", # Parent scripts: Brahmi, Tamil-Brahmi, Pallava comma=", ", pop=70, ), WritingSystem( name="Telugu", iso=[(340, "Telu")], unicode=["TELUGU"], titleTag="big", comma=", ", pop=74, ), WritingSystem( name="Thai", iso=[(352, "Thai")], unicode=["THAI"], titleTag="big", comma=", ", pop=38, ), # _____________________________________________________ WritingSystem( name="Syriac", iso=[(135, "Syrc")], unicode=["SYRIAC"], titleTag="b", direction="rtl", comma="، ", pop=8, # Syriac=0.4, Lontara=7.6 # Lontara is a separate script according to Wikipedia # but not according to Unicode ), WritingSystem( name="Tibetan", iso=[(330, "Tibt")], unicode=["TIBETAN"], titleTag="big", comma=", ", # almost not used expect in numbers! pop=5, ), WritingSystem( name="Georgian", iso=[(240, "Geor")], unicode=["GEORGIAN"], titleTag="big", comma=", ", pop=4.5, ), WritingSystem( name="Mongolian", iso=[(145, "Mong")], unicode=["MONGOLIAN"], titleTag="big", direction="ltr", # historically ttb? comma=", ", pop=2, ), WritingSystem( name="Thaana", iso=[(170, "Thaa")], unicode=["THAANA"], titleTag="big", direction="rtl", comma="، ", pop=0.35, ), # _____________________________________________________ WritingSystem( name="Javanese", iso=[(361, "Java")], unicode=["JAVANESE"], titleTag="big", # Since around 1945 Javanese script has largely been # supplanted by Latin script to write Javanese. ), WritingSystem( # aka CANADIAN ABORIGINAL or UCAS name="Canadian syllabic", iso=[(440, "Cans")], unicode=["CANADIAN SYLLABICS"], titleTag="big", comma=", ", ), WritingSystem( name="Takri", iso=[(321, "Takr")], unicode=["TAKRI"], titleTag="b", # comma="", FIXME ), # _____________________________________________________ WritingSystem( name="SignWriting", iso=[(95, "Sgnw")], unicode=["SIGNWRITING"], titleTag="big", direction="ttb", comma="�", ), # _____________________________________________________ WritingSystem( name="Adlam", iso=[(166, "Adlm")], unicode=["ADLAM"], titleTag="big", direction="rtl", ), WritingSystem( name="Avestan", iso=[(134, "Avst")], unicode=["AVESTAN"], titleTag="b", direction="rtl", ), WritingSystem( name="Glagolitic", iso=[(225, "Glag")], unicode=["GLAGOLITIC"], # Unicode 4.1 titleTag="b", ), WritingSystem( name="Khojki", iso=[(322, "Khoj")], unicode=["KHOJKI"], titleTag="big", ), WritingSystem( name="Khudabadi", # aka: Khudawadi, "Sindhi" iso=[(318, "Sind")], unicode=["KHUDAWADI"], titleTag="big", ), WritingSystem( name="N'Ko", iso=[(165, "Nkoo")], unicode=["NKO"], titleTag="big", ), # _____________________________________________________ # WritingSystem( # name="Baybayin", # iso=[(370, "Tglg")], # unicode=["TAGALOG"], # added in Unicode 3.2 # ), # WritingSystem( # name="Rejang", # iso=[(363, "Rjng")], # unicode=["REJANG"], # ), # WritingSystem( # name="Mandombe", # unicode=[], # ), # WritingSystem( # name="Mwangwego", # unicode=[], # ), ] for _ws in writingSystemList: if not _ws.name: raise ValueError(f"empty name in {_ws}") writingSystemByUnicode = {uni: ws for ws in writingSystemList for uni in ws.unicode} writingSystemByName = {ws.name: ws for ws in writingSystemList} writingSystemByLowercaseName = {ws.name.lower(): ws for ws in writingSystemList} unicodeNextWord = { "HALFWIDTH", "FULLWIDTH", "CANADIAN", } def _getWritingSystemFromChar(char: str) -> WritingSystem | None: try: unicodeWords = unicodedata.name(char).split(" ") except ValueError: # if c not in string.whitespace: # print(f"{c=}, {e}") return None alias = unicodeWords[0] ws = writingSystemByUnicode.get(alias) if ws: return ws if alias in unicodeNextWord: return writingSystemByUnicode.get(" ".join(unicodeWords[:2])) return None def _getWritingSystemFromText( st: str, start: int, end: int, ) -> WritingSystem | None: for char in st[start:end]: ws = _getWritingSystemFromChar(char) if ws: return ws return None def getWritingSystemFromText( st: str, beginning: bool = False, ) -> WritingSystem | None: st = st.strip() if not st: return None # some special first words in unicodedata.name(c): # "RIGHT", "ASTERISK", "MODIFIER" k = 0 if beginning else (len(st) + 1) // 2 - 1 ws = _getWritingSystemFromText(st, k, len(st)) if ws: return ws return _getWritingSystemFromText(st, 0, k) def getAllWritingSystemsFromText( st: str, ) -> set[str]: st = st.strip() if not st: return set() wsSet = set() for char in st: ws = _getWritingSystemFromChar(char) if ws: wsSet.add(ws.name) return wsSet
9,133
Python
.py
449
17.670379
84
0.613715
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,753
__init__.py
ilius_pyglossary/pyglossary/langs/__init__.py
from __future__ import annotations import json import logging from os.path import join from pyglossary.core import rootDir log = logging.getLogger("pyglossary") class Lang: def __init__( self, codes: list[str], names: list[str], titleTag: str = "b", rtl: int = 0, ) -> None: self._codes = codes self._names = names self._titleTag = titleTag self._rtl = rtl def __repr__(self) -> str: return ( "Lang(" f"codes={self._codes!r}, " f"names={self._names!r}, " f"titleTag={self._titleTag!r}" ")" ) def __str__(self) -> str: return f"Lang({self._codes + self._names})" @property def codes(self) -> list[str]: return self._codes @property def names(self) -> list[str]: return self._names @property def name(self) -> str: return self._names[0] @property def code(self) -> str: return self._codes[0] @property def titleTag(self) -> str: return self._titleTag @property def rtl(self) -> int: return self._rtl class LangDict(dict): def _addLang(self, lang: Lang) -> None: for key in lang.codes: if key in self: log.error(f"duplicate language code: {key}") self[key] = lang for name in lang.names: if name in self: log.error(f"duplicate language name: {name}") self[name.lower()] = lang def load(self) -> None: from time import perf_counter as now if len(self) > 0: return t0 = now() filename = join(rootDir, "pyglossary", "langs", "langs.json") with open(filename, encoding="utf-8") as _file: data = json.load(_file) for row in data: self._addLang( Lang( codes=row["codes"], names=[row["name"]] + row["alt_names"], titleTag=row["title_tag"], rtl=row.get("rtl", 0), ), ) log.debug( f"LangDict: loaded, {len(self)} keys, " f"took {(now() - t0) * 1000:.1f} ms", ) def __getitem__(self, key: str) -> Lang | None: self.load() return self.get(key.lower(), None) langDict = LangDict()
1,956
Python
.py
81
20.802469
63
0.642934
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,754
xsl_transform.py
ilius_pyglossary/pyglossary/xdxf/xsl_transform.py
from __future__ import annotations import logging from os.path import join from typing import TYPE_CHECKING if TYPE_CHECKING: from lxml.etree import _XSLTResultTree from pyglossary.lxml_types import Element from pyglossary import core from pyglossary.core import rootDir log = logging.getLogger("pyglossary") __all__ = [ "XslXdxfTransformer", ] class XslXdxfTransformer: _gram_color: str = "green" _example_padding: int = 10 def __init__(self, encoding: str = "utf-8") -> None: try: from lxml import etree as ET except ModuleNotFoundError as e: e.msg += f", run `{core.pip} install lxml` to install" raise e with open( join(rootDir, "pyglossary", "xdxf", "xdxf.xsl"), encoding="utf-8", ) as f: xslt_txt = f.read() xslt = ET.XML(xslt_txt) self._transform = ET.XSLT(xslt) self._encoding = encoding @staticmethod def tostring(elem: "_XSLTResultTree | Element") -> str: from lxml import etree as ET return ( ET.tostring( elem, method="html", pretty_print=True, ) .decode("utf-8") .strip() ) def transform(self, article: Element) -> str: result_tree = self._transform(article) text = self.tostring(result_tree) text = text.replace("<br/> ", "<br/>") return text # noqa: RET504 def transformByInnerString(self, articleInnerStr: str) -> str: from lxml import etree as ET return self.transform( ET.fromstring(f"<ar>{articleInnerStr}</ar>"), )
1,442
Python
.py
52
24.692308
63
0.707939
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,755
transform.py
ilius_pyglossary/pyglossary/xdxf/transform.py
from __future__ import annotations import logging from io import BytesIO from typing import TYPE_CHECKING, cast if TYPE_CHECKING: from pyglossary.lxml_types import Element, T_htmlfile log = logging.getLogger("pyglossary") __all__ = [ "XdxfTransformer", ] class XdxfTransformer: _gram_color: str = "green" _example_padding: int = 10 def __init__(self, encoding: str = "utf-8") -> None: self._encoding = encoding self._childTagWriteMapping = { "br": self._write_br, "i": self._write_basic_format, "b": self._write_basic_format, "sub": self._write_basic_format, "sup": self._write_basic_format, "tt": self._write_basic_format, "big": self._write_basic_format, "small": self._write_basic_format, "blockquote": self._write_blockquote, "tr": self._write_tr, "k": self._write_k, "sr": self._write_sr, "ex": self._write_example, "mrkd": self._write_mrkd, "kref": self._write_kref, "iref": self._write_iref, "pos": self._write_pos, "abr": self._write_abr, "dtrn": self._write_dtrn, "co": self._write_co, "c": self._write_c, "rref": self._write_rref, "def": self._write_def, "deftext": self._write_deftext, "span": self._write_span, "abbr_def": self._write_abbr_def, "gr": self._write_gr, "ex_orig": self._write_ex_orig, "categ": self._write_categ, "opt": self._write_opt, "img": self._write_img, "abbr": self._write_abbr, "etm": self._write_etm, } @staticmethod def tostring(elem: Element) -> str: from lxml import etree as ET return ( ET.tostring( elem, method="html", pretty_print=True, ) .decode("utf-8") .strip() ) @staticmethod def hasPrevText(prev: "None | str | Element") -> bool: if isinstance(prev, str): return True if prev is None: return False if prev.tag == "k": return False if prev.tag in { "dtrn", "def", "span", "co", "i", "b", "sub", "sup", "tt", "big", "small", }: return True if prev.text: # noqa: SIM103 return True # print(prev) return False def writeString( # noqa: PLR0913 self, hf: "T_htmlfile", child: str, parent: Element, prev: "None | str | Element", stringSep: "str | None" = None, ) -> None: from lxml import etree as ET def addSep() -> None: if stringSep is None: hf.write(ET.Element("br")) else: hf.write(stringSep) hasPrev = self.hasPrevText(prev) trail = False if parent.tag in {"ar", "font"}: if child.startswith("\n"): child = child.lstrip("\n") if hasPrev: hf.write(ET.Element("br")) elif child.endswith("\n"): child = child.rstrip("\n") trail = True if not hasPrev: child = child.lstrip() elif child.startswith("\n"): child = child.lstrip() if hasPrev: addSep() child = child.rstrip() lines = [line for line in child.split("\n") if line] for index, line in enumerate(lines): if index > 0: # and line[0] not in ".,;)" addSep() hf.write(line) if trail: addSep() def _write_example(self, hf: "T_htmlfile", elem: Element) -> None: prev = None stringSep = " " with hf.element( "div", attrib={ "class": "example", "style": f"padding: {self._example_padding}px 0px;", }, ): for child in elem.xpath("child::node()"): if isinstance(child, str): # if not child.strip(): # continue self.writeString(hf, child, elem, prev, stringSep=stringSep) continue if child.tag == "iref": with hf.element("div"): self._write_iref(hf, child) # NESTED 5 continue if child.tag in {"ex_orig", "ex_tran"}: with hf.element("div"): self.writeChildrenOf(hf, child, stringSep=stringSep) # NESTED 5 continue # log.warning(f"unknown tag {child.tag} inside <ex>") self.writeChild(hf, child, elem, prev, stringSep=stringSep) prev = child def _write_iref(self, hf: "T_htmlfile", child: Element) -> None: iref_url = child.attrib.get("href", "") if iref_url.endswith((".mp3", ".wav", ".aac", ".ogg")): # with hf.element("audio", src=iref_url): with hf.element( "a", attrib={ "class": "iref", "href": iref_url, }, ): hf.write("🔊") return with hf.element( "a", attrib={ "class": "iref", "href": child.attrib.get("href", child.text or ""), }, ): self.writeChildrenOf(hf, child, stringSep=" ") def _write_blockquote(self, hf: "T_htmlfile", child: Element) -> None: with hf.element("div", attrib={"class": "m"}): self.writeChildrenOf(hf, child) def _write_tr(self, hf: "T_htmlfile", child: Element) -> None: from lxml import etree as ET hf.write("[") self.writeChildrenOf(hf, child) hf.write("]") hf.write(ET.Element("br")) def _write_k(self, hf: "T_htmlfile", child: Element) -> None: with hf.element("div", attrib={"class": child.tag}): # with hf.element(glos.titleTag(child.text)): # ^ no glos object here! with hf.element("b"): self.writeChildrenOf(hf, child) def _write_mrkd(self, hf: "T_htmlfile", child: Element) -> None: # noqa: PLR6301 if not child.text: return with hf.element("span", attrib={"class": child.tag}): with hf.element("b"): hf.write(child.text) def _write_kref(self, hf: "T_htmlfile", child: Element) -> None: if not child.text: log.warning(f"kref with no text: {self.tostring(child)}") return with hf.element( "a", attrib={ "class": "kref", "href": f"bword://{child.attrib.get('k', child.text)}", }, ): hf.write(child.text) def _write_sr(self, hf: "T_htmlfile", child: Element) -> None: with hf.element("div", attrib={"class": child.tag}): self.writeChildrenOf(hf, child) def _write_pos(self, hf: "T_htmlfile", child: Element) -> None: with hf.element("span", attrib={"class": child.tag}): with hf.element("font", color="green"): with hf.element("i"): self.writeChildrenOf(hf, child) # NESTED 5 def _write_abr(self, hf: "T_htmlfile", child: Element) -> None: with hf.element("span", attrib={"class": child.tag}): with hf.element("font", color="green"): with hf.element("i"): self.writeChildrenOf(hf, child) # NESTED 5 def _write_dtrn(self, hf: "T_htmlfile", child: Element) -> None: self.writeChildrenOf(hf, child, sep=" ") def _write_co(self, hf: "T_htmlfile", child: Element) -> None: self.writeChildrenOf(hf, child, sep=" ") def _write_basic_format(self, hf: "T_htmlfile", child: Element) -> None: with hf.element(child.tag): self.writeChildrenOf(hf, child) # if child.text is not None: # hf.write(child.text.strip("\n")) def _write_br(self, hf: "T_htmlfile", child: Element) -> None: from lxml import etree as ET hf.write(ET.Element("br")) self.writeChildrenOf(hf, child) def _write_c(self, hf: "T_htmlfile", child: Element) -> None: color = child.attrib.get("c", "green") with hf.element("font", color=color): self.writeChildrenOf(hf, child) def _write_rref(self, _hf: "T_htmlfile", child: Element) -> None: if not child.text: log.warning(f"rref with no text: {self.tostring(child)}") return def _write_def(self, hf: "T_htmlfile", child: Element) -> None: # TODO: create a list (ol / ul) unless it has one item only # like FreeDict reader with hf.element("div"): self.writeChildrenOf(hf, child) def _write_deftext(self, hf: "T_htmlfile", child: Element) -> None: self.writeChildrenOf(hf, child, stringSep=" ", sep=" ") def _write_span(self, hf: "T_htmlfile", child: Element) -> None: with hf.element("span"): self.writeChildrenOf(hf, child) def _write_abbr_def(self, hf: "T_htmlfile", child: Element) -> None: # _type = child.attrib.get("type", "") # {"": "", "grm": "grammatical", "stl": "stylistical", # "knl": "area/field of knowledge", "aux": "subsidiary" # "oth": "others"}[_type] self.writeChildrenOf(hf, child) def _write_gr(self, hf: "T_htmlfile", child: Element) -> None: from lxml import etree as ET with hf.element("font", color=self._gram_color): hf.write(child.text or "") hf.write(ET.Element("br")) def _write_ex_orig(self, hf: "T_htmlfile", child: Element) -> None: with hf.element("i"): self.writeChildrenOf(hf, child) # def _write_ex_transl(self, hf: "T_htmlfile", child: Element) -> None: def _write_categ(self, hf: "T_htmlfile", child: Element) -> None: with hf.element("span", style="background-color: green;"): self.writeChildrenOf(hf, child, stringSep=" ") def _write_opt(self, hf: "T_htmlfile", child: Element) -> None: # noqa: PLR6301 if child.text: hf.write(" (") hf.write(child.text) hf.write(")") def _write_img(self, hf: "T_htmlfile", child: Element) -> None: # noqa: PLR6301 with hf.element("img", attrib=dict(child.attrib)): pass def _write_abbr(self, hf: "T_htmlfile", child: Element) -> None: # noqa: PLR6301 # FIXME: may need an space or newline before it with hf.element("i"): hf.write(f"{child.text}") def _write_etm(self, hf: "T_htmlfile", child: Element) -> None: # noqa: PLR6301 # Etymology (history and origin) # TODO: formatting? hf.write(f"{child.text}") def writeChildElem( # noqa: PLR0913 self, hf: "T_htmlfile", child: Element, parent: Element, # noqa: ARG002 prev: "None | str | Element", stringSep: "str | None" = None, # noqa: ARG002 ) -> None: func = self._childTagWriteMapping.get(child.tag, None) if func is not None: func(hf, child) return if child.tag == "ex_transl" and prev is not None: if isinstance(prev, str): pass elif prev.tag == "ex_orig": if child.text != prev.text: with hf.element("i"): self.writeChildrenOf(hf, child) return log.warning(f"unknown tag {child.tag}") self.writeChildrenOf(hf, child) def writeChild( # noqa: PLR0913 self, hf: "T_htmlfile", child: "str | Element", parent: Element, prev: "None | str | Element", stringSep: "str | None" = None, ) -> None: if isinstance(child, str): if not child.strip(): return self.writeString(hf, child, parent, prev, stringSep=stringSep) return self.writeChildElem( hf=hf, child=child, parent=parent, prev=prev, stringSep=stringSep, ) def shouldAddSep( # noqa: PLR6301 self, child: "str | Element", prev: "str | Element", ) -> bool: if isinstance(child, str): return not (len(child) > 0 and child[0] in ".,;)") if child.tag in {"sub", "sup"}: return False if isinstance(prev, str): pass elif prev.tag in {"sub", "sup"}: return False return True def writeChildrenOf( self, hf: "T_htmlfile", elem: Element, sep: "str | None" = None, stringSep: "str | None" = None, ) -> None: prev = None for child in elem.xpath("child::node()"): if sep and prev is not None and self.shouldAddSep(child, prev): hf.write(sep) self.writeChild(hf, child, elem, prev, stringSep=stringSep) prev = child def transform(self, article: Element) -> str: from lxml import etree as ET # encoding = self._encoding f = BytesIO() with ET.htmlfile(f, encoding="utf-8") as hf: with hf.element("div", attrib={"class": "article"}): self.writeChildrenOf(cast("T_htmlfile", hf), article) text = f.getvalue().decode("utf-8") text = text.replace("<br>", "<br/>") # for compatibility return text # noqa: RET504 def transformByInnerString(self, articleInnerStr: str) -> str: from lxml import etree as ET return self.transform( ET.fromstring(f"<ar>{articleInnerStr}</ar>"), )
11,476
Python
.py
370
27.332432
82
0.646537
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,756
css_js_transform.py
ilius_pyglossary/pyglossary/xdxf/css_js_transform.py
from __future__ import annotations import logging import sys from io import BytesIO from typing import TYPE_CHECKING, cast if TYPE_CHECKING: from pyglossary.lxml_types import Element, T_htmlfile log = logging.getLogger("pyglossary") __all__ = [ "XdxfTransformer", ] class XdxfTransformer: def __init__(self, encoding: str = "utf-8") -> None: self._encoding = encoding self.logging_enabled = False self._childTagWriteMapping = { "br": self._write_br, "u": self._write_basic_format, "i": self._write_basic_format, "b": self._write_basic_format, "sub": self._write_basic_format, "sup": self._write_basic_format, "tt": self._write_basic_format, "big": self._write_basic_format, "small": self._write_basic_format, "blockquote": self._write_blockquote, "tr": self._write_tr, "k": self._write_k, "sr": self._write_sr, "ex": self._write_example, "mrkd": self._write_mrkd, "kref": self._write_kref, "iref": self._write_iref, "pos": self._write_pos, "abr": self._write_abr, "abbr": self._write_abbr, "dtrn": self._write_dtrn, "co": self._write_co, "c": self._write_c, "rref": self._write_rref, "def": self._write_def, "deftext": self._write_deftext, "span": self._write_span, "gr": self._write_gr, "ex_orig": self._write_ex_orig, "categ": self._write_categ, "opt": self._write_opt, "img": self._write_img, "etm": self._write_etm, } @staticmethod def tostring(elem: Element) -> str: from lxml import etree as ET return ( ET.tostring( elem, method="html", pretty_print=True, ) .decode("utf-8") .strip() ) @staticmethod def hasPrevText(prev: "None | str | Element") -> bool: if isinstance(prev, str): return True if prev is None: return False if prev.tag == "k": return False if prev.tag in { "dtrn", "def", "span", "co", "i", "b", "sub", "sup", "tt", "big", "small", }: return True if prev.text: # noqa: SIM103 return True # print(prev) return False def writeString( # noqa: PLR0913 self, hf: "T_htmlfile", child: str, parent: Element, prev: "None | str | Element", stringSep: "str | None" = None, ) -> None: from lxml import etree as ET def addSep() -> None: if stringSep is None: hf.write(ET.Element("br")) else: hf.write(stringSep) hasPrev = self.hasPrevText(prev) trail = False if parent.tag in {"ar", "font"}: if child.startswith("\n"): child = child.lstrip("\n") if hasPrev: hf.write(ET.Element("br")) elif child.endswith("\n"): child = child.rstrip("\n") trail = True if not hasPrev: child = child.lstrip() elif child.startswith("\n"): # child = child.lstrip() if hasPrev: addSep() lines = [line for line in child.split("\n") if line] for index, line in enumerate(lines): if index > 0: # and line[0] not in ".,;)" addSep() hf.write(line) if trail: addSep() def _write_example(self, hf: "T_htmlfile", elem: Element) -> None: prev = None stringSep = " " with hf.element( # noqa: PLR1702 "div", attrib={"class": elem.tag}, ): for child in elem.xpath("child::node()"): if isinstance(child, str): # if not child.strip(): # continue self.writeString(hf, child, elem, prev, stringSep=stringSep) continue if child.tag == "iref": with hf.element("div"): self._write_iref(hf, child) # NESTED 5 continue if child.tag == "ex_orig": with hf.element("span", attrib={"class": child.tag}): self.writeChildrenOf(hf, child, stringSep=stringSep) continue if child.tag == "ex_tran": ex_trans = elem.xpath("./ex_tran") if ex_trans.index(child) == 0: # when several translations, make HTML unordered list of them if len(ex_trans) > 1: with hf.element("ul", attrib={}): for ex_tran in ex_trans: with hf.element("li", attrib={}): self._write_ex_transl(hf, ex_tran) else: self._write_ex_transl(hf, child) continue # log.warning(f"unknown tag {child.tag} inside <ex>") self.writeChild(hf, child, elem, prev, stringSep=stringSep) prev = child def _write_ex_orig(self, hf: "T_htmlfile", child: Element) -> None: # TODO NOT REACHABLE sys.exit("NOT REACHABLE") with hf.element("i"): self.writeChildrenOf(hf, child) def _write_ex_transl(self, hf: "T_htmlfile", child: Element) -> None: with hf.element("span", attrib={"class": child.tag}): self.writeChildrenOf(hf, child) def _write_iref(self, hf: "T_htmlfile", child: Element) -> None: iref_url = child.attrib.get("href", "") if iref_url.endswith((".mp3", ".wav", ".aac", ".ogg")): # with hf.element("audio", src=iref_url): with hf.element( "a", attrib={ "class": "iref", "href": iref_url, }, ): hf.write("🔊") return with hf.element( "a", attrib={ "class": "iref", "href": child.attrib.get("href", child.text or ""), }, ): self.writeChildrenOf(hf, child, stringSep=" ") def _write_blockquote(self, hf: "T_htmlfile", child: Element) -> None: with hf.element("div", attrib={"class": "m"}): self.writeChildrenOf(hf, child) def _write_tr(self, hf: "T_htmlfile", child: Element) -> None: from lxml import etree as ET hf.write("[") self.writeChildrenOf(hf, child) hf.write("]") hf.write(ET.Element("br")) def _write_k(self, hf: "T_htmlfile", child: Element) -> None: self.logging_enabled = child.text == "iść" index = child.getparent().index(child) if index == 0: with hf.element("div", attrib={"class": child.tag}): # with hf.element(glos.titleTag(child.text)): # ^ no glos object here! self.writeChildrenOf(hf, child) # TODO Lenny: show other forms in a collapsible list # else: # with (hf.element("span", attrib={"class": child.tag})): # hf.write(str(index)) # self.writeChildrenOf(hf, child) def _write_mrkd(self, hf: "T_htmlfile", child: Element) -> None: # noqa: PLR6301 if not child.text: return with hf.element("span", attrib={"class": child.tag}): hf.write(child.text) def _write_kref(self, hf: "T_htmlfile", child: Element) -> None: if not child.text: log.warning(f"kref with no text: {self.tostring(child)}") return with hf.element( "a", attrib={ "class": "kref", "href": f"bword://{child.attrib.get('k', child.text)}", }, ): hf.write(child.text) def _write_sr(self, hf: "T_htmlfile", child: Element) -> None: with hf.element("div", attrib={"class": child.tag}): self.writeChildrenOf(hf, child) def _write_pos(self, hf: "T_htmlfile", child: Element) -> None: with hf.element("span", attrib={"class": child.tag}): self.writeChildrenOf(hf, child) def _write_abr(self, hf: "T_htmlfile", child: Element) -> None: with hf.element("span", attrib={"class": "abbr"}): self.writeChildrenOf(hf, child) def _write_abbr(self, hf: "T_htmlfile", child: Element) -> None: # noqa: PLR6301 with hf.element("span", attrib={"class": child.tag}): self.writeChildrenOf(hf, child) def _write_dtrn(self, hf: "T_htmlfile", child: Element) -> None: self.writeChildrenOf(hf, child, sep=" ") def _write_co(self, hf: "T_htmlfile", child: Element) -> None: with hf.element("span", attrib={"class": child.tag}): hf.write("(") self.writeChildrenOf(hf, child, sep=" ") hf.write(")") def _write_basic_format(self, hf: "T_htmlfile", child: Element) -> None: with hf.element(child.tag): self.writeChildrenOf(hf, child) # if child.text is not None: # hf.write(child.text.strip("\n")) def _write_br(self, hf: "T_htmlfile", child: Element) -> None: from lxml import etree as ET hf.write(ET.Element("br")) self.writeChildrenOf(hf, child) def _write_c(self, hf: "T_htmlfile", child: Element) -> None: color = child.attrib.get("c", "green") with hf.element("font", color=color): self.writeChildrenOf(hf, child) def _write_rref(self, _hf: "T_htmlfile", child: Element) -> None: if not child.text: log.warning(f"rref with no text: {self.tostring(child)}") return def _write_def(self, hf: "T_htmlfile", elem: Element) -> None: has_nested_def = False has_deftext = False for child in elem.iterchildren(): if child.tag == "def": has_nested_def = True if child.tag == "deftext": has_deftext = True if elem.getparent().tag == "ar": # this is a root <def> if has_nested_def: with hf.element("ol"): self.writeChildrenOf(hf, elem) else: with hf.element("div"): self.writeChildrenOf(hf, elem) elif has_deftext: with hf.element("li"): self.writeChildrenOf(hf, elem) elif has_nested_def: with hf.element("li"): with hf.element("ol"): self.writeChildrenOf(hf, elem) else: with hf.element("li"): self.writeChildrenOf(hf, elem) def _write_deftext(self, hf: "T_htmlfile", child: Element) -> None: with hf.element("span", attrib={"class": child.tag}): self.writeChildrenOf(hf, child, stringSep=" ", sep=" ") def _write_span(self, hf: "T_htmlfile", child: Element) -> None: with hf.element("span"): self.writeChildrenOf(hf, child) def _write_gr(self, hf: "T_htmlfile", child: Element) -> None: with hf.element("div", attrib={"class": child.tag}): self.writeChildrenOf(hf, child) def _write_categ(self, hf: "T_htmlfile", child: Element) -> None: with hf.element("span", style="background-color: green;"): self.writeChildrenOf(hf, child, stringSep=" ") def _write_opt(self, hf: "T_htmlfile", child: Element) -> None: # noqa: PLR6301 if child.text: hf.write(" (") hf.write(child.text) hf.write(")") def _write_img(self, hf: "T_htmlfile", child: Element) -> None: # noqa: PLR6301 with hf.element("img", attrib=dict(child.attrib)): pass def _write_etm(self, hf: "T_htmlfile", child: Element) -> None: # noqa: PLR6301 # Etymology (history and origin) # TODO: formatting? hf.write(f"{child.text}") def writeChildElem( # noqa: PLR0913 self, hf: "T_htmlfile", child: Element, parent: Element, # noqa: ARG002 prev: "None | str | Element", stringSep: "str | None" = None, # noqa: ARG002 ) -> None: func = self._childTagWriteMapping.get(child.tag, None) if func is not None: func(hf, child) return if child.tag == "ex_transl" and prev is not None: if isinstance(prev, str): pass elif prev.tag == "ex_orig": if child.text != prev.text: with hf.element("i"): self.writeChildrenOf(hf, child) return log.warning(f"unknown tag {child.tag}") self.writeChildrenOf(hf, child) def writeChild( # noqa: PLR0913 self, hf: "T_htmlfile", child: "str | Element", parent: Element, prev: "None | str | Element", stringSep: "str | None" = None, ) -> None: if isinstance(child, str): self.writeString(hf, child, parent, prev, stringSep=stringSep) else: self.writeChildElem( hf=hf, child=child, parent=parent, prev=prev, stringSep=stringSep, ) def shouldAddSep( # noqa: PLR6301 self, child: "str | Element", prev: "str | Element", ) -> bool: if isinstance(child, str): return not (len(child) > 0 and child[0] in ".,;)") if child.tag in {"sub", "sup"}: return False if isinstance(prev, str): pass elif prev.tag in {"sub", "sup"}: return False return True def writeChildrenOf( self, hf: "T_htmlfile", elem: Element, sep: "str | None" = None, stringSep: "str | None" = None, ) -> None: prev = None for child in elem.xpath("child::node()"): if sep and prev is not None and self.shouldAddSep(child, prev): hf.write(sep) self.writeChild(hf, child, elem, prev, stringSep=stringSep) prev = child @staticmethod def stringify_children(elem: Element) -> str: from itertools import chain from lxml.etree import tostring children = [ chunk for chunk in chain( (elem.text,), chain( *( (tostring(child, with_tail=False), child.tail) for child in elem.getchildren() ) ), (elem.tail,), ) if chunk ] normalized_children = "" for chunk in children: if isinstance(chunk, str): normalized_children += chunk if isinstance(chunk, bytes): normalized_children += chunk.decode(encoding="utf-8") return normalized_children def transform(self, article: Element) -> str: from lxml import etree as ET # encoding = self._encoding f = BytesIO() with ET.htmlfile(f, encoding="utf-8") as hf: with hf.element("div", attrib={"class": "article"}): self.writeChildrenOf(cast("T_htmlfile", hf), article) text = f.getvalue().decode("utf-8") text = text.replace("<br>", "<br/>") # for compatibility return text # noqa: RET504 def transformByInnerString(self, articleInnerStr: str) -> str: from lxml import etree as ET return self.transform( ET.fromstring(f"<ar>{articleInnerStr}</ar>"), )
12,912
Python
.py
422
26.739336
82
0.647783
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,757
ui_qt.py
ilius_pyglossary/pyglossary/ui/ui_qt.py
# -*- coding: utf-8 -*- # mypy: ignore-errors # ui_qk.py # # Copyright © 2010-2019 Saeed Rasooli <saeed.gnu@gmail.com> (ilius) # # This program is a free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # You can get a copy of GNU General Public License along this program # But you can always get it from http://www.gnu.org/licenses/gpl.txt # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. from __future__ import annotations from os.path import join from PyQt4 import QtGui as qt from pyglossary.glossary_v2 import * from .base import * noneItem = 'Not Selected' class UI(qt.QWidget, UIBase): def __init__(self) -> None: qt.QWidget.__init__(self) UIBase.__init__(self) self.setWindowTitle('PyGlossary (Qt)') self.setWindowIcon(qt.QIcon(join(uiDir, 'pyglossary.png'))) ###################### self.running = False self.glos = Glossary(ui=self) self.glos.config = self.config self.pathI = '' self.pathO = '' self.fcd_dir = join(homeDir, 'Desktop') ###################### vbox = qt.QVBoxLayout() self.setLayout(vbox)
1,411
Python
.py
40
33.375
72
0.719208
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,758
ui_cmd_interactive.py
ilius_pyglossary/pyglossary/ui/ui_cmd_interactive.py
# -*- coding: utf-8 -*- # mypy: ignore-errors # ui_cmd_interactive.py # # Copyright © 2008-2022 Saeed Rasooli <saeed.gnu@gmail.com> (ilius) # This file is part of PyGlossary project, https://github.com/ilius/pyglossary # # This program is a free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program. Or on Debian systems, from /usr/share/common-licenses/GPL # If not, see <http://www.gnu.org/licenses/gpl.txt>. from __future__ import annotations """ To use this user interface: sudo pip3 install prompt_toolkit. """ # GitHub repo for prompt_toolkit # https://github.com/prompt-toolkit/python-prompt-toolkit # The code for Python's cmd.Cmd was very ugly and hard to understand last I # checked. But we don't use cmd module here, and nor does prompt_toolkit. # Completion func for Python's readline, silently (and stupidly) hides any # exception, and only shows the print if it's in the first line of function. # very awkward! # We also don't use readline module, and nor does prompt_toolkit. # Looks like prompt_toolkit works directly with sys.stdin, sys.stdout # and sys.stderr. # prompt_toolkit also supports ncurses-like dialogs with buttons and widgets, # but I prefer this kind of UI with auto-completion and history import argparse import json import logging import os import shlex from collections import OrderedDict from os.path import ( abspath, dirname, isabs, isdir, join, relpath, ) from typing import TYPE_CHECKING if TYPE_CHECKING: from collections.abc import Iterable from typing import Literal from pyglossary.option import Option from pyglossary.plugin_prop import PluginProp import prompt_toolkit from prompt_toolkit import ANSI from prompt_toolkit import prompt as promptLow from prompt_toolkit.auto_suggest import AutoSuggestFromHistory from prompt_toolkit.completion import ( Completion, PathCompleter, WordCompleter, ) from prompt_toolkit.history import FileHistory from prompt_toolkit.key_binding import KeyBindings from prompt_toolkit.keys import Keys from prompt_toolkit.shortcuts import PromptSession, confirm from pyglossary import core from pyglossary.core import confDir from pyglossary.glossary_v2 import Error, Glossary from pyglossary.sort_keys import lookupSortKey, namedSortKeyList from pyglossary.ui import ui_cmd __all__ = ["UI"] endFormat = "\x1b[0;0;0m" class MiniCheckBoxPrompt: def __init__( self, message: str = "", fmt: str = "{message}: {check}", value: bool = False, ) -> None: self.message = message self.fmt = fmt self.value = value def formatMessage(self): msg = self.fmt.format( check="[x]" if self.value else "[ ]", message=self.message, ) # msg = ANSI(msg) # NOT SUPPORTED return msg # noqa: RET504 def __pt_formatted_text__(self): # noqa: PLW3201 return [("", self.formatMessage())] def checkbox_prompt( message: str, default: bool, ) -> PromptSession[bool]: """Create a `PromptSession` object for the 'confirm' function.""" bindings = KeyBindings() check = MiniCheckBoxPrompt(message=message, value=default) @bindings.add(" ") def space(_event: "prompt_toolkit.E") -> None: check.value = not check.value # cursor_pos = check.formatMessage().find("[") + 1 # cur_cursor_pos = session.default_buffer.cursor_position # print(f"{cur_cursor_pos=}, {cursor_pos=}") # session.default_buffer.cursor_position = cursor_pos @bindings.add(Keys.Any) def _(_event: "prompt_toolkit.E") -> None: """Disallow inserting other text.""" complete_message = check session: PromptSession[bool] = PromptSession( complete_message, key_bindings=bindings, ) session.prompt() return check.value log = logging.getLogger("pyglossary") indent = "\t" cmdiConfDir = join(confDir, "cmdi") histDir = join(cmdiConfDir, "history") for direc in (cmdiConfDir, histDir): os.makedirs(direc, mode=0o700, exist_ok=True) if __name__ == "__main__": Glossary.init() pluginByDesc = {plugin.description: plugin for plugin in Glossary.plugins.values()} readFormatDescList = [ Glossary.plugins[_format].description for _format in Glossary.readFormats ] writeFormatDescList = [ Glossary.plugins[_format].description for _format in Glossary.writeFormats ] convertOptionsFlags = { "direct": ("indirect", "direct"), "sqlite": ("", "sqlite"), "progressbar": ("no-progress-bar", ""), "sort": ("no-sort", "sort"), } infoOverrideFlags = { "sourceLang": "source-lang", "targetLang": "target-lang", "name": "name", } def dataToPrettyJson(data, ensure_ascii=False, sort_keys=False): return json.dumps( data, sort_keys=sort_keys, indent=2, ensure_ascii=ensure_ascii, ) def prompt( message: str, multiline: bool = False, **kwargs, ): if kwargs.get("default", "") is None: kwargs["default"] = "" text = promptLow(message=message, **kwargs) if multiline and text == "!m": print("Entering Multi-line mode, press Alt+ENTER to end") text = promptLow( message="", multiline=True, **kwargs, ) return text # noqa: RET504 back = "back" class MyPathCompleter(PathCompleter): def __init__( self, reading: bool, # noqa: ARG002 fs_action_names=None, **kwargs, ) -> None: PathCompleter.__init__( self, file_filter=self.file_filter, **kwargs, ) if fs_action_names is None: fs_action_names = [] self.fs_action_names = fs_action_names @staticmethod def file_filter(_filename: str) -> bool: # filename is full/absolute file path return True # def get_completions_exception(document, complete_event, e): # log.error(f"Exception in get_completions: {e}") def get_completions( self, document: "prompt_toolkit.Document", complete_event: "prompt_toolkit.CompleteEvent", ) -> Iterable[Completion]: text = document.text_before_cursor for action in self.fs_action_names: if action.startswith(text): yield Completion( text=action, start_position=-len(text), display=action, ) yield from PathCompleter.get_completions( self, document=document, complete_event=complete_event, ) class AbsolutePathHistory(FileHistory): def load_history_strings(self) -> Iterable[str]: # pwd = os.getcwd() pathList = FileHistory.load_history_strings(self) return [relpath(p) for p in pathList] def store_string(self, string: str) -> None: FileHistory.store_string(self, abspath(string)) class UI(ui_cmd.UI): def __init__( self, progressbar: bool = True, ) -> None: self._inputFilename = "" self._outputFilename = "" self._inputFormat = "" self._outputFormat = "" self.config = None self._readOptions = None self._writeOptions = None self._convertOptions = None ui_cmd.UI.__init__( self, progressbar=progressbar, ) self.ls_parser = argparse.ArgumentParser(add_help=False) self.ls_parser.add_argument( "-l", "--long", action="store_true", dest="long", help="use a long listing format", ) self.ls_parser.add_argument( "--help", action="store_true", dest="help", help="display help", ) self.ls_usage = ( "Usage: !ls [--help] [-l] [FILE/DIRECTORY]...\n\n" "optional arguments:\n" " --help show this help message and exit\n" " -l, --long use a long listing format\n" ) self._fsActions = OrderedDict( [ ("!pwd", (self.fs_pwd, "")), ("!ls", (self.fs_ls, self.ls_usage)), ("!..", (self.fs_cd_parent, "")), ("!cd", (self.fs_cd, "")), ], ) self._finalActions = OrderedDict( [ ("formats", self.askFormats), ("read-options", self.askReadOptions), ("write-options", self.askWriteOptions), ("reset-read-options", self.resetReadOptions), ("reset-write-options", self.resetWriteOptions), ("config", self.askConfig), ("indirect", self.setIndirect), ("sqlite", self.setSQLite), ("no-progressbar", self.setNoProgressbar), ("sort", self.setSort), ("sort-key", self.setSortKey), ("show-options", self.showOptions), ("back", None), ], ) @staticmethod def fs_pwd(args: list[str]): if args: print(f"extra arguments: {args}") print(os.getcwd()) @staticmethod def get_ls_l( arg: str, st: "os.stat_result | None" = None, parentDir: str = "", sizeWidth: int = 0, ) -> str: import grp import pwd import stat import time argPath = arg if parentDir: argPath = join(parentDir, arg) if st is None: st = os.lstat(argPath) # os.lstat does not follow sym links, like "ls" command details = [ stat.filemode(st.st_mode), pwd.getpwuid(st.st_uid).pw_name, grp.getgrgid(st.st_gid).gr_name, str(st.st_size).rjust(sizeWidth), time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(st.st_mtime)), arg, ] if stat.S_ISLNK(st.st_mode): details.append(f"-> {os.readlink(argPath)}") return " ".join(details) def fs_ls(self, args: list[str]): opts, args = self.ls_parser.parse_known_args(args=args) if opts.help: print(self.ls_usage) return if not args: args = [os.getcwd()] showTitle = len(args) > 1 # Note: isdir and isfile funcs follow sym links, so no worry about links for argI, arg in enumerate(args): if argI > 0: print() if not isdir(arg): print(self.get_ls_l(arg)) continue if showTitle: print(f"> List of directory {arg!r}:") if not opts.long: for _path in os.listdir(arg): if isdir(_path): _path += "/" print(f"{_path}") continue contents = os.listdir(arg) statList = [os.lstat(join(arg, _path)) for _path in contents] maxFileSize = max(st.st_size for st in statList) sizeWidth = len(str(maxFileSize)) for pathI, path_ in enumerate(contents): print( self.get_ls_l( path_, parentDir=arg, st=statList[pathI], sizeWidth=sizeWidth, ), ) @staticmethod def fs_cd_parent(args: list[str]): if args: log.error("This command does not take arguments") return newDir = dirname(os.getcwd()) os.chdir(newDir) print(f"Changed current directory to: {newDir}") @staticmethod def fs_cd(args: list[str]): if len(args) != 1: log.error("This command takes exactly one argument") return newDir = args[0] if not isabs(newDir): newDir = abspath(newDir) os.chdir(newDir) print(f"Changed current directory to: {newDir}") def formatPromptMsg(self, level, msg, colon=":"): _indent = self.promptIndentStr * level if core.noColor: return f"{_indent} {msg}{colon} ", False if self.promptIndentColor >= 0: _indent = f"\x1b[38;5;{self.promptIndentColor}m{_indent}{endFormat}" if self.promptMsgColor >= 0: msg = f"\x1b[38;5;{self.promptMsgColor}m{msg}{endFormat}" return f"{_indent} {msg}{colon} ", True def prompt(self, level, msg, colon=":", **kwargs): msg, colored = self.formatPromptMsg(level, msg, colon) if colored: msg = ANSI(msg) return prompt(msg, **kwargs) def checkbox_prompt(self, level, msg, colon=":", **kwargs): # FIXME: colors are not working, they are being escaped msg = f"{self.promptIndentStr * level} {msg}{colon} " # msg, colored = self.formatPromptMsg(level, msg, colon) return checkbox_prompt(msg, **kwargs) def askFile( self, kind: str, histName: str, varName: str, reading: bool, ): from shlex import split as shlex_split history = AbsolutePathHistory(join(histDir, histName)) auto_suggest = AutoSuggestFromHistory() # Note: isdir and isfile funcs follow sym links, so no worry about links completer = MyPathCompleter( reading=reading, fs_action_names=list(self._fsActions), ) default = getattr(self, varName) while True: filename = self.prompt( 1, kind, history=history, auto_suggest=auto_suggest, completer=completer, default=default, ) if not filename: continue try: parts = shlex_split(filename) except ValueError: # file name can have single/double quote setattr(self, varName, filename) return filename if parts[0] in self._fsActions: actionFunc, usage = self._fsActions[parts[0]] try: actionFunc(parts[1:]) except Exception: log.exception("") if usage: print("\n" + usage) continue setattr(self, varName, filename) return filename raise ValueError(f"{kind} is not given") def askInputFile(self): return self.askFile( "Input file", "filename-input", "_inputFilename", True, ) def askOutputFile(self): return self.askFile( "Output file", "filename-output", "_outputFilename", False, ) @staticmethod def pluginByNameOrDesc(value: str) -> PluginProp | None: plugin = pluginByDesc.get(value) if plugin: return plugin plugin = Glossary.plugins.get(value) if plugin: return plugin log.error(f"internal error: invalid format name/desc {value!r}") return None def askInputFormat(self) -> str: history = FileHistory(join(histDir, "format-input")) auto_suggest = AutoSuggestFromHistory() completer = WordCompleter( readFormatDescList + Glossary.readFormats, ignore_case=True, match_middle=True, sentence=True, ) while True: value = self.prompt( 1, "Input format", history=history, auto_suggest=auto_suggest, completer=completer, default=self._inputFormat, ) if not value: continue plugin = self.pluginByNameOrDesc(value) if plugin: return plugin.name raise ValueError("input format is not given") def askOutputFormat(self) -> str: history = FileHistory(join(histDir, "format-output")) auto_suggest = AutoSuggestFromHistory() completer = WordCompleter( writeFormatDescList + Glossary.writeFormats, ignore_case=True, match_middle=True, sentence=True, ) while True: value = self.prompt( 1, "Output format", history=history, auto_suggest=auto_suggest, completer=completer, default=self._outputFormat, ) if not value: continue plugin = self.pluginByNameOrDesc(value) if plugin: return plugin.name raise ValueError("output format is not given") def finish(self): pass # TODO: how to handle \r and \n in NewlineOption.values? @staticmethod def getOptionValueSuggestValues(option: Option): if option.values: return [str(x) for x in option.values] if option.typ == "bool": return ["True", "False"] return None def getOptionValueCompleter(self, option: Option): values = self.getOptionValueSuggestValues(option) if values: return WordCompleter( values, ignore_case=True, match_middle=True, sentence=True, ) return None # PLR0912 Too many branches (15 > 12) def askReadOptions(self): # noqa: PLR0912 options = Glossary.formatsReadOptions.get(self._inputFormat) if options is None: log.error(f"internal error: invalid format {self._inputFormat!r}") return optionsProp = Glossary.plugins[self._inputFormat].optionsProp history = FileHistory(join(histDir, f"read-options-{self._inputFormat}")) auto_suggest = AutoSuggestFromHistory() completer = WordCompleter( list(options), ignore_case=True, match_middle=True, sentence=True, ) while True: try: optName = self.prompt( 2, "ReadOption: Name (ENTER if done)", history=history, auto_suggest=auto_suggest, completer=completer, ) except (KeyboardInterrupt, EOFError): return if not optName: return option = optionsProp[optName] valueCompleter = self.getOptionValueCompleter(option) default = self._readOptions.get(optName) if default is None: default = options[optName] print(f"Comment: {option.longComment}") while True: if option.typ == "bool": try: valueNew = self.checkbox_prompt( 3, f"ReadOption: {optName}", default=default, ) except (KeyboardInterrupt, EOFError): break print(f"Set read-option: {optName} = {valueNew!r}") self._readOptions[optName] = valueNew break try: value = self.prompt( 3, f"ReadOption: {optName}", colon=" =", history=FileHistory(join(histDir, f"option-value-{optName}")), auto_suggest=AutoSuggestFromHistory(), default=str(default), completer=valueCompleter, ) except (KeyboardInterrupt, EOFError): break if value == "": # noqa: PLC1901 if optName in self._readOptions: print(f"Unset read-option {optName!r}") del self._readOptions[optName] # FIXME: set empty value? break valueNew, ok = option.evaluate(value) if not ok or not option.validate(valueNew): log.error( f"Invalid read option value {optName}={value!r}" f" for format {self._inputFormat}", ) continue print(f"Set read-option: {optName} = {valueNew!r}") self._readOptions[optName] = valueNew break # PLR0912 Too many branches (15 > 12) def askWriteOptions(self): # noqa: PLR0912 options = Glossary.formatsWriteOptions.get(self._outputFormat) if options is None: log.error(f"internal error: invalid format {self._outputFormat!r}") return optionsProp = Glossary.plugins[self._outputFormat].optionsProp history = FileHistory(join(histDir, f"write-options-{self._outputFormat}")) auto_suggest = AutoSuggestFromHistory() completer = WordCompleter( list(options), ignore_case=True, match_middle=True, sentence=True, ) while True: try: optName = self.prompt( 2, "WriteOption: Name (ENTER if done)", history=history, auto_suggest=auto_suggest, completer=completer, ) except (KeyboardInterrupt, EOFError): return if not optName: return option = optionsProp[optName] print(f"Comment: {option.longComment}") valueCompleter = self.getOptionValueCompleter(option) default = self._writeOptions.get(optName) if default is None: default = options[optName] while True: if option.typ == "bool": try: valueNew = self.checkbox_prompt( 3, f"WriteOption: {optName}", default=default, ) except (KeyboardInterrupt, EOFError): break print(f"Set write-option: {optName} = {valueNew!r}") self._writeOptions[optName] = valueNew break try: value = self.prompt( 3, f"WriteOption: {optName}", colon=" =", history=FileHistory(join(histDir, f"option-value-{optName}")), auto_suggest=AutoSuggestFromHistory(), default=str(default), completer=valueCompleter, ) except (KeyboardInterrupt, EOFError): break if value == "": # noqa: PLC1901 if optName in self._writeOptions: print(f"Unset write-option {optName!r}") del self._writeOptions[optName] # FIXME: set empty value? break valueNew, ok = option.evaluate(value) if not ok or not option.validate(valueNew): log.error( f"Invalid write option value {optName}={value!r}" f" for format {self._outputFormat}", ) continue print(f"Set write-option: {optName} = {valueNew!r}") self._writeOptions[optName] = valueNew break def resetReadOptions(self): self._readOptions = {} def resetWriteOptions(self): self._writeOptions = {} def askConfigValue(self, configKey, option): default = self.config.get(configKey, "") if option.typ == "bool": return str( self.checkbox_prompt( 3, f"Config: {configKey}", default=bool(default), ), ) return self.prompt( 3, f"Config: {configKey}", colon=" =", history=FileHistory(join(histDir, f"config-value-{configKey}")), auto_suggest=AutoSuggestFromHistory(), default=str(default), completer=self.getOptionValueCompleter(option), ) def askConfig(self): configKeys = sorted(self.configDefDict) history = FileHistory(join(histDir, "config-key")) auto_suggest = AutoSuggestFromHistory() completer = WordCompleter( configKeys, ignore_case=True, match_middle=True, sentence=True, ) while True: try: configKey = self.prompt( 2, "Config: Key (ENTER if done)", history=history, auto_suggest=auto_suggest, completer=completer, ) except (KeyboardInterrupt, EOFError): return if not configKey: return option = self.configDefDict[configKey] while True: try: value = self.askConfigValue(configKey, option) except (KeyboardInterrupt, EOFError): break if value == "": # noqa: PLC1901 if configKey in self.config: print(f"Unset config {configKey!r}") del self.config[configKey] # FIXME: set empty value? break valueNew, ok = option.evaluate(value) if not ok or not option.validate(valueNew): log.error( f"Invalid config value {configKey}={value!r}", ) continue print(f"Set config: {configKey} = {valueNew!r}") self.config[configKey] = valueNew self.config[configKey] = valueNew break def showOptions(self): print(f"readOptions = {self._readOptions}") print(f"writeOptions = {self._writeOptions}") print(f"convertOptions = {self._convertOptions}") print(f"config = {self.config}") print() def setIndirect(self): self._convertOptions["direct"] = False self._convertOptions["sqlite"] = None print("Switched to indirect mode") def setSQLite(self): self._convertOptions["direct"] = None self._convertOptions["sqlite"] = True print("Switched to SQLite mode") def setNoProgressbar(self): self._convertOptions["progressbar"] = False print("Disabled progress bar") def setSort(self): try: value = self.checkbox_prompt( 2, "Enable Sort", default=self._convertOptions.get("sort", False), ) except (KeyboardInterrupt, EOFError): return self._convertOptions["sort"] = value def setSortKey(self): completer = WordCompleter( [_sk.name for _sk in namedSortKeyList], ignore_case=False, match_middle=True, sentence=True, ) default = self._convertOptions.get("sortKeyName", "") sortKeyName = self.prompt( 2, "SortKey", history=FileHistory(join(histDir, "sort-key")), auto_suggest=AutoSuggestFromHistory(), default=default, completer=completer, ) if not sortKeyName: if "sortKeyName" in self._convertOptions: del self._convertOptions["sortKeyName"] return if not lookupSortKey(sortKeyName): log.error(f"invalid {sortKeyName = }") return self._convertOptions["sortKeyName"] = sortKeyName if not self._convertOptions.get("sort"): self.setSort() def askFinalAction(self) -> str | None: history = FileHistory(join(histDir, "action")) auto_suggest = AutoSuggestFromHistory() completer = WordCompleter( list(self._finalActions), ignore_case=False, match_middle=True, sentence=True, ) while True: action = self.prompt( 1, "Select action (ENTER to convert)", history=history, auto_suggest=auto_suggest, completer=completer, ) if not action: return None if action not in self._finalActions: log.error(f"invalid action: {action}") continue return action def askFinalOptions(self) -> bool | Literal["back"]: while True: try: action = self.askFinalAction() except (KeyboardInterrupt, EOFError): return False except Exception: log.exception("") return False if action == back: return back if action is None: return True # convert actionFunc = self._finalActions[action] if actionFunc is None: return True # convert actionFunc() return True # convert def getRunKeywordArgs(self) -> dict: return { "inputFilename": self._inputFilename, "outputFilename": self._outputFilename, "inputFormat": self._inputFormat, "outputFormat": self._outputFormat, "config": self.config, "readOptions": self._readOptions, "writeOptions": self._writeOptions, "convertOptions": self._convertOptions, "glossarySetAttrs": self._glossarySetAttrs, } def checkInputFormat(self, forceAsk: bool = False): if not forceAsk: try: inputArgs = Glossary.detectInputFormat(self._inputFilename) except Error: pass else: inputFormat = inputArgs.formatName self._inputFormat = inputFormat return self._inputFormat = self.askInputFormat() def checkOutputFormat(self, forceAsk: bool = False): if not forceAsk: try: outputArgs = Glossary.detectOutputFormat( filename=self._outputFilename, inputFilename=self._inputFilename, ) except Error: pass else: self._outputFormat = outputArgs.formatName return self._outputFormat = self.askOutputFormat() def askFormats(self): self.checkInputFormat(forceAsk=True) self.checkOutputFormat(forceAsk=True) def askInputOutputAgain(self): self.askInputFile() self.checkInputFormat(forceAsk=True) self.askOutputFile() self.checkOutputFormat(forceAsk=True) def printNonInteractiveCommand(self): # noqa: PLR0912 cmd = [ ui_cmd.COMMAND, self._inputFilename, self._outputFilename, f"--read-format={self._inputFormat}", f"--write-format={self._outputFormat}", ] if self._readOptions: optionsJson = json.dumps(self._readOptions, ensure_ascii=True) cmd += ["--json-read-options", optionsJson] if self._writeOptions: optionsJson = json.dumps(self._writeOptions, ensure_ascii=True) cmd += ["--json-write-options", optionsJson] if self.config: for key, value in self.config.items(): if value is None: continue if value == self.savedConfig.get(key): continue option = self.configDefDict.get(key) if option is None: log.error(f"config key {key} was not found") if not option.hasFlag: log.error(f"config key {key} has no command line flag") flag = option.customFlag if not flag: flag = key.replace("_", "-") if option.typ == "bool": if not value: flag = f"no-{flag}" cmd.append(f"--{flag}") else: cmd.append(f"--{flag}={value}") if self._convertOptions: if "infoOverride" in self._convertOptions: infoOverride = self._convertOptions.pop("infoOverride") for key, value in infoOverride.items(): flag = infoOverrideFlags.get(key) if not flag: log.error(f"unknown key {key} in infoOverride") continue cmd.append(f"--{flag}={value}") if "sortKeyName" in self._convertOptions: value = self._convertOptions.pop("sortKeyName") cmd.append(f"--sort-key={value}") for key, value in self._convertOptions.items(): if value is None: continue if key not in convertOptionsFlags: log.error(f"unknown key {key} in convertOptions") continue ftup = convertOptionsFlags[key] if ftup is None: continue if isinstance(value, bool): flag = ftup[int(value)] if flag: cmd.append(f"--{flag}") else: flag = ftup[0] cmd.append(f"--{flag}={value}") print() print( "If you want to repeat this conversion later, you can use this command:", ) # shlex.join is added in Python 3.8 print(shlex.join(cmd)) def setConfigAttrs(self): config = self.config self.promptIndentStr = config.get("cmdi.prompt.indent.str", ">") self.promptIndentColor = config.get("cmdi.prompt.indent.color", 2) self.promptMsgColor = config.get("cmdi.prompt.msg.color", -1) self.msgColor = config.get("cmdi.msg.color", -1) # PLR0912 Too many branches (19 > 12) def main(self, again=False): # noqa: PLR0912 if again or not self._inputFilename: try: self.askInputFile() except (KeyboardInterrupt, EOFError): return None if again or not self._inputFormat: try: self.checkInputFormat() except (KeyboardInterrupt, EOFError): return None if again or not self._outputFilename: try: self.askOutputFile() except (KeyboardInterrupt, EOFError): return None if again or not self._outputFormat: try: self.checkOutputFormat() except (KeyboardInterrupt, EOFError): return None while True: status = self.askFinalOptions() if status == back: self.askInputOutputAgain() continue if not status: return None try: succeed = ui_cmd.UI.run(self, **self.getRunKeywordArgs()) except Exception: log.exception("") else: self.printNonInteractiveCommand() if succeed: return succeed print("Press Control + C to exit") def run( # noqa: PLR0913 self, inputFilename: str = "", outputFilename: str = "", inputFormat: str = "", outputFormat: str = "", reverse: bool = False, config: "dict | None" = None, readOptions: "dict | None" = None, writeOptions: "dict | None" = None, convertOptions: "dict | None" = None, glossarySetAttrs: "dict | None" = None, ): if reverse: raise NotImplementedError("Reverse is not implemented in this UI") if config is None: config = {} if readOptions is None: readOptions = {} if writeOptions is None: writeOptions = {} if convertOptions is None: convertOptions = {} if glossarySetAttrs is None: glossarySetAttrs = {} self._inputFilename = inputFilename self._outputFilename = outputFilename self._inputFormat = inputFormat self._outputFormat = outputFormat self._readOptions = readOptions self._writeOptions = writeOptions self._convertOptions = convertOptions self._glossarySetAttrs = glossarySetAttrs self.loadConfig() self.savedConfig = dict(self.config) self.config = config del inputFilename, outputFilename, inputFormat, outputFormat del config, readOptions, writeOptions, convertOptions self.setConfigAttrs() self.main() try: while ( self.prompt( level=1, msg="Press enter to exit, 'a' to convert again", default="", ) == "a" ): self.main(again=True) except KeyboardInterrupt: pass if self.config != self.savedConfig and confirm("Save Config?"): self.saveConfig()
30,166
Python
.py
1,043
25.079578
83
0.701383
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,759
argparse_utils.py
ilius_pyglossary/pyglossary/ui/argparse_utils.py
from __future__ import annotations import argparse class StoreConstAction(argparse.Action): def __init__( self, option_strings: list[str], same_dest: str = "", const_value: "bool | None" = None, nargs: int = 0, **kwargs, ) -> None: if isinstance(option_strings, str): option_strings = [option_strings] argparse.Action.__init__( self, option_strings=option_strings, nargs=nargs, **kwargs, ) self.same_dest = same_dest self.const_value = const_value def __call__( # noqa: PLR0913 self, parser: "argparse.ArgumentParser | None" = None, namespace: "argparse.Namespace | None" = None, values: list | None = None, # noqa: ARG002 option_strings: list[str] | None = None, # noqa: ARG002 required: bool = False, # noqa: ARG002 dest: str | None = None, ) -> StoreConstAction: if not parser: return self dest = self.dest if getattr(namespace, dest) is not None: flag = self.option_strings[0] if getattr(namespace, dest) == self.const_value: parser.error(f"multiple {flag} options") else: parser.error(f"conflicting options: {self.same_dest} and {flag}") setattr(namespace, dest, self.const_value) return self
1,191
Python
.py
41
25.878049
69
0.686736
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,760
pbar_tqdm.py
ilius_pyglossary/pyglossary/ui/pbar_tqdm.py
# mypy: ignore-errors from __future__ import annotations from tqdm import tqdm __all__ = ["createProgressBar"] def createProgressBar(title: str): return MyTqdm( total=1.0, desc=title, ) class MyTqdm(tqdm): @property def format_dict(self): d = super().format_dict # return dict( # n=self.n, total=self.total, # elapsed=self._time() - self.start_t # if hasattr(self, 'start_t') else 0, # ncols=ncols, nrows=nrows, # prefix=self.desc, ascii=self.ascii, unit=self.unit, # unit_scale=self.unit_scale, # rate=1 / self.avg_time if self.avg_time else None, # bar_format=self.bar_format, postfix=self.postfix, # unit_divisor=self.unit_divisor, initial=self.initial, # colour=self.colour, # ) d["bar_format"] = ( "{desc}: %{percentage:04.1f} |" "{bar}|[{elapsed}<{remaining}" ", {rate_fmt}{postfix}]" ) # Possible vars: # l_bar, bar, r_bar, n, n_fmt, total, total_fmt, # percentage, elapsed, elapsed_s, ncols, nrows, desc, unit, # rate, rate_fmt, rate_noinv, rate_noinv_fmt, # rate_inv, rate_inv_fmt, postfix, unit_divisor, # remaining, remaining_s. return d def update(self, ratio: float) -> None: tqdm.update(self, ratio - self.n) def finish(self) -> None: self.close() @property def term_width(self) -> int: return self.ncols
1,315
Python
.py
44
27.045455
62
0.672482
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,761
option_ui.py
ilius_pyglossary/pyglossary/ui/option_ui.py
from __future__ import annotations import argparse import json from typing import TYPE_CHECKING, Any from pyglossary.ui.argparse_utils import StoreConstAction if TYPE_CHECKING: from pyglossary.option import Option def registerConfigOption( parser: "argparse.ArgumentParser", key: str, option: Option, ) -> None: if not option.hasFlag: return flag = option.customFlag if not flag: flag = key.replace("_", "-") if option.typ != "bool": parser.add_argument( f"--{flag}", dest=key, default=None, help=option.comment, ) return if not option.comment: print(f"registerConfigOption: option has no comment: {option}") return if not option.falseComment: parser.add_argument( f"--{flag}", dest=key, action="store_true", default=None, help=option.comment, ) return parser.add_argument( dest=key, action=StoreConstAction( f"--{flag}", same_dest=f"--no-{flag}", const_value=True, dest=key, default=None, help=option.comment, ), ) parser.add_argument( dest=key, action=StoreConstAction( f"--no-{flag}", same_dest=f"--{flag}", const_value=False, dest=key, default=None, help=option.falseComment, ), ) def evaluateReadOptions( options: dict[str, Any], inputFilename: str, inputFormat: str | None, ) -> tuple[dict[str, Any] | None, str | None]: from pyglossary.glossary_v2 import Glossary inputArgs = Glossary.detectInputFormat( inputFilename, format=inputFormat, ) if not inputArgs: return None, f"Could not detect format for input file {inputFilename}" inputFormat = inputArgs.formatName optionsProp = Glossary.plugins[inputFormat].optionsProp for optName, optValue in options.items(): if optName not in Glossary.formatsReadOptions[inputFormat]: return None, f"Invalid option name {optName} for format {inputFormat}" prop = optionsProp[optName] optValueNew, ok = prop.evaluate(optValue) if not ok or not prop.validate(optValueNew): return ( None, f"Invalid option value {optName}={optValue!r} for format {inputFormat}", ) options[optName] = optValueNew return options, None def evaluateWriteOptions( options: dict[str, Any], inputFilename: str, outputFilename: str, outputFormat: str | None, ) -> tuple[dict[str, Any] | None, str | None]: from pyglossary.glossary_v2 import Glossary outputArgs = Glossary.detectOutputFormat( filename=outputFilename, format=outputFormat, inputFilename=inputFilename, ) if outputArgs is None: return None, "failed to detect output format" outputFormat = outputArgs.formatName optionsProp = Glossary.plugins[outputFormat].optionsProp for optName, optValue in options.items(): if optName not in Glossary.formatsWriteOptions[outputFormat]: return None, f"Invalid option name {optName} for format {outputFormat}" prop = optionsProp[optName] optValueNew, ok = prop.evaluate(optValue) if not ok or not prop.validate(optValueNew): return ( None, f"Invalid option value {optName}={optValue!r} " f"for format {outputFormat}", ) options[optName] = optValueNew return options, None def parseReadWriteOptions( args: "argparse.Namespace", ) -> tuple[tuple[dict[str, Any], dict[str, Any]] | None, str | None]: from pyglossary.ui.ui_cmd import parseFormatOptionsStr readOptions = parseFormatOptionsStr(args.readOptions) if readOptions is None: return None, "" if args.jsonReadOptions: newReadOptions = json.loads(args.jsonReadOptions) if not isinstance(newReadOptions, dict): return None, ( "invalid value for --json-read-options, " f"must be an object/dict, not {type(newReadOptions)}" ) readOptions.update(newReadOptions) writeOptions = parseFormatOptionsStr(args.writeOptions) if writeOptions is None: return None, "" if args.jsonWriteOptions: newWriteOptions = json.loads(args.jsonWriteOptions) if not isinstance(newWriteOptions, dict): return None, ( "invalid value for --json-write-options, " f"must be an object/dict, not {type(newWriteOptions)}" ) writeOptions.update(newWriteOptions) return (readOptions, writeOptions), None
4,114
Python
.py
141
26.198582
76
0.751455
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,762
ui_gtk4.py
ilius_pyglossary/pyglossary/ui/ui_gtk4.py
# -*- coding: utf-8 -*- # mypy: ignore-errors # ui_gtk.py # # Copyright © 2008-2022 Saeed Rasooli <saeed.gnu@gmail.com> (ilius) # # This program is a free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # You can get a copy of GNU General Public License along this program # But you can always get it from http://www.gnu.org/licenses/gpl.txt # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. from __future__ import annotations import logging import sys import traceback from collections import OrderedDict from os.path import abspath, isfile from typing import TYPE_CHECKING, Any import gi from pyglossary import core from pyglossary.glossary_v2 import ConvertArgs, Error, Glossary from pyglossary.sort_keys import defaultSortKeyName, namedSortKeyList from pyglossary.text_utils import urlToPath from .base import ( UIBase, aboutText, authors, licenseText, logo, ) from .dependency import checkDepends from .version import getVersion gi.require_version("Gtk", "4.0") from .gtk4_utils import gdk, gio, gtk # noqa: E402 from .gtk4_utils.about import AboutWidget # noqa: E402 from .gtk4_utils.utils import ( # noqa: E402 HBox, VBox, dialog_add_button, gtk_event_iteration_loop, gtk_window_iteration_loop, imageFromFile, pack, rgba_parse, set_tooltip, showInfo, ) if TYPE_CHECKING: from pyglossary.plugin_prop import PluginProp # from gi.repository import GdkPixbuf log = logging.getLogger("pyglossary") # gtk.Window.set_default_icon_from_file(logo) # removed in Gtk 4.0 _ = str # later replace with translator function pluginByDesc = {plugin.description: plugin for plugin in Glossary.plugins.values()} readDesc = [ plugin.description for plugin in Glossary.plugins.values() if plugin.canRead ] writeDesc = [ plugin.description for plugin in Glossary.plugins.values() if plugin.canWrite ] def getWorkAreaSize(_w): display = gdk.Display.get_default() # monitor = display.get_monitor_at_surface(w.get_surface()) # if monitor is None: monitor = display.get_primary_monitor() rect = monitor.get_workarea() return rect.width, rect.height def buffer_get_text(b): return b.get_text( b.get_start_iter(), b.get_end_iter(), True, ) # GTK 4 has removed the GtkContainer::border-width property # (together with the rest of GtkContainer). # Use other means to influence the spacing of your containers, # such as the CSS margin and padding properties on child widgets, # or the CSS border-spacing property on containers. class FormatDialog(gtk.Dialog): def __init__( self, descList: list[str], parent=None, **kwargs, ) -> None: gtk.Dialog.__init__(self, transient_for=parent, **kwargs) self.set_default_size(400, 400) self.vbox = self.get_content_area() ## self.descList = descList self.items = descList self.activeDesc = "" ## self.connect("response", lambda _w, _e: self.hide()) dialog_add_button( self, "gtk-cancel", "_Cancel", gtk.ResponseType.CANCEL, ) dialog_add_button( self, "gtk-ok", "_OK", gtk.ResponseType.OK, ) ### treev = gtk.TreeView() treeModel = gtk.ListStore(str) treev.set_headers_visible(False) treev.set_model(treeModel) treev.connect("row-activated", self.rowActivated) # treev.connect("response", self.onResponse) ### self.treev = treev ############# cell = gtk.CellRendererText(editable=False) col = gtk.TreeViewColumn( title="Descriptin", cell_renderer=cell, text=0, ) col.set_property("expand", True) col.set_resizable(True) treev.append_column(col) self.descCol = col ############ hbox = HBox(spacing=15) hbox.get_style_context().add_class("margin_05") pack(hbox, gtk.Label(label="Search:")) entry = self.entry = gtk.Entry() pack(hbox, entry, 1, 1) pack(self.vbox, hbox) ### entry.connect("changed", self.onEntryChange) ############ self.swin = swin = gtk.ScrolledWindow() swin.set_child(treev) swin.set_policy(gtk.PolicyType.NEVER, gtk.PolicyType.AUTOMATIC) pack(self.vbox, swin, 1, 1) self.vbox.show() ## treev.set_can_focus(True) # no need, just to be safe # treev.set_can_default(True) treev.set_receives_default(True) # print("can_focus:", treev.get_can_focus()) # print("can_default:", treev.get_can_default()) # print("receives_default:", treev.get_receives_default()) #### self.updateTree() self.connect("realize", self.onRealize) def onRealize(self, _widget=None): if self.activeDesc: self.treev.grab_focus() else: self.entry.grab_focus() def onEntryChange(self, entry): text = entry.get_text().strip() if not text: self.items = self.descList self.updateTree() return text = text.lower() descList = self.descList items1 = [] items2 = [] for desc in descList: if desc.lower().startswith(text): items1.append(desc) elif text in desc.lower(): items2.append(desc) self.items = items1 + items2 self.updateTree() def setCursor(self, desc: str): model = self.treev.get_model() _iter = model.iter_children(None) while _iter is not None: if model.get_value(_iter, 0) == desc: path = model.get_path(_iter) self.treev.set_cursor(path, self.descCol, False) self.treev.scroll_to_cell(path) return _iter = model.iter_next(_iter) def updateTree(self): model = self.treev.get_model() model.clear() for desc in self.items: model.append([desc]) if self.activeDesc: self.setCursor(self.activeDesc) def getActive(self) -> PluginProp | None: _iter = self.treev.get_selection().get_selected()[1] if _iter is None: return None model = self.treev.get_model() desc = model.get_value(_iter, 0) return pluginByDesc[desc] def setActive(self, plugin): if plugin is None: self.activeDesc = "" return desc = plugin.description self.activeDesc = desc self.setCursor(desc) def rowActivated(self, treev, path, _col): model = treev.get_model() _iter = model.get_iter(path) desc = model.get_value(_iter, 0) self.activeDesc = desc self.response(gtk.ResponseType.OK) # def onResponse class FormatButton(gtk.Button): noneLabel = "[Select Format]" dialogTitle = "Select Format" def __init__(self, descList: list[str], parent=None) -> None: gtk.Button.__init__(self) self.set_label(self.noneLabel) ### self.descList = descList self._parent = parent self.activePlugin = None ### self.connect("clicked", self.onClick) def onChanged(self, obj=None): pass def onDialogResponse(self, dialog, response_id): print(f"onDialogResponse: {dialog}, {response_id}") if response_id != gtk.ResponseType.OK: return plugin = dialog.getActive() self.activePlugin = plugin if plugin: self.set_label(plugin.description) else: self.set_label(self.noneLabel) self.onChanged() def onClick(self, _button=None): dialog = FormatDialog( descList=self.descList, parent=self._parent, title=self.dialogTitle, ) dialog.setActive(self.activePlugin) dialog.connect("response", self.onDialogResponse) dialog.present() def getActive(self): if self.activePlugin is None: return "" return self.activePlugin.name def setActive(self, _format): plugin = Glossary.plugins[_format] self.activePlugin = plugin self.set_label(plugin.description) self.onChanged() class FormatOptionsDialog(gtk.Dialog): commentLen = 60 def __init__( self, app, formatName: str, options: list[str], optionsValues: "dict[str, Any]", **kwargs, ) -> None: self.app = app gtk.Dialog.__init__(self, **kwargs) self.vbox = self.get_content_area() ## optionsProp = Glossary.plugins[formatName].optionsProp self.optionsProp = optionsProp self.formatName = formatName self.actionIds = set() ## self.connect("response", lambda _w, _e: self.hide()) dialog_add_button( self, "gtk-cancel", "_Cancel", gtk.ResponseType.CANCEL, ) dialog_add_button( self, "gtk-ok", "_OK", gtk.ResponseType.OK, ) ### treev = gtk.TreeView() treeModel = gtk.ListStore( bool, # enable str, # name str, # comment str, # value ) treev.set_headers_clickable(True) treev.set_model(treeModel) treev.connect("row-activated", self.rowActivated) gesture = gtk.GestureClick.new() gesture.connect("pressed", self.treeviewButtonPress) treev.add_controller(gesture) ### self.treev = treev ############# cell = gtk.CellRendererToggle() # cell.set_property("activatable", True) cell.connect("toggled", self.enableToggled) col = gtk.TreeViewColumn(title="Enable", cell_renderer=cell) col.add_attribute(cell, "active", 0) # cell.set_active(False) col.set_property("expand", False) col.set_resizable(True) treev.append_column(col) ### col = gtk.TreeViewColumn( title="Name", cell_renderer=gtk.CellRendererText(), text=1, ) col.set_property("expand", False) col.set_resizable(True) treev.append_column(col) ### cell = gtk.CellRendererText(editable=True) self.valueCell = cell self.valueCol = 3 cell.connect("edited", self.valueEdited) col = gtk.TreeViewColumn( title="Value", cell_renderer=cell, text=self.valueCol, ) col.set_property("expand", True) col.set_resizable(True) col.set_min_width(200) treev.append_column(col) ### col = gtk.TreeViewColumn( title="Comment", cell_renderer=gtk.CellRendererText(), text=2, ) col.set_property("expand", False) col.set_resizable(False) treev.append_column(col) ############# for name in options: prop = optionsProp[name] comment = prop.longComment if len(comment) > self.commentLen: comment = comment[: self.commentLen] + "..." if prop.typ != "bool" and not prop.values: comment += " (double-click to edit)" treeModel.append( [ name in optionsValues, # enable name, # name comment, # comment str(optionsValues.get(name, "")), # value ], ) ############ pack(self.vbox, treev, 1, 1) self.vbox.show() def enableToggled(self, cell, path): # enable is column 0 model = self.treev.get_model() active = not cell.get_active() itr = model.get_iter(path) model.set_value(itr, 0, active) def valueEdited(self, _cell, path, rawValue): # value is column 3 model = self.treev.get_model() itr = model.get_iter(path) optName = model.get_value(itr, 1) prop = self.optionsProp[optName] if not prop.customValue: return enable = True if rawValue == "" and prop.typ != "str": # noqa: PLC1901 enable = False elif not prop.validateRaw(rawValue): log.error(f"invalid {prop.typ} value: {optName} = {rawValue!r}") return model.set_value(itr, self.valueCol, rawValue) model.set_value(itr, 0, enable) def rowActivated(self, _treev, path, _col): # forceMenu=True because we can not enter edit mode # if double-clicked on a cell other than Value return self.valueCellClicked(path, forceMenu=True) def treeviewButtonPress(self, _gesture, _n_press, x, y): # if gevent.button != 1: # return False pos_t = self.treev.get_path_at_pos(int(x), int(y)) if not pos_t: return False # pos_t == path, col, xRel, yRel path = pos_t[0] col = pos_t[1] # cell = col.get_cells()[0] if col.get_title() == "Value": return self.valueCellClicked(path) return False def valueItemActivate(self, item: "gio.MenuItem", itr: gtk.TreeIter): # value is column 3 value = item.get_label() model = self.treev.get_model() model.set_value(itr, self.valueCol, value) model.set_value(itr, 0, True) # enable it def valueCustomOpenDialog(self, itr: gtk.TreeIter, optName: str): model = self.treev.get_model() prop = self.optionsProp[optName] currentValue = model.get_value(itr, self.valueCol) optDesc = optName if prop.comment: optDesc += f" ({prop.comment})" label = gtk.Label(label=f"Value for {optDesc}") dialog = gtk.Dialog(transient_for=self, title="Option Value") dialog.connect("response", lambda _w, _e: dialog.hide()) dialog_add_button( dialog, "gtk-cancel", "_Cancel", gtk.ResponseType.CANCEL, ) dialog_add_button( dialog, "gtk-ok", "_OK", gtk.ResponseType.OK, ) pack(dialog.vbox, label) entry = gtk.Entry() entry.set_text(currentValue) entry.connect("activate", lambda _w: dialog.response(gtk.ResponseType.OK)) pack(dialog.vbox, entry) dialog.vbox.show() dialog.connect("response", self.valueCustomDialogResponse, entry) dialog.present() def valueCustomDialogResponse(self, _dialog, response_id, entry): if response_id != gtk.ResponseType.OK: return model = self.treev.get_model() value = entry.get_text() print(model, value) # FIXME # model.set_value(itr, self.valueCol, value) # model.set_value(itr, 0, True) # enable it def valueItemCustomActivate( self, _item: "gtk.MenuItem", itr: gtk.TreeIter, ): model = self.treev.get_model() optName = model.get_value(itr, 1) self.valueCustomOpenDialog(itr, optName) def addAction(self, path, name, callback, *args) -> str: actionId = self.formatName + "_" + str(path[0]) + "_" + name if actionId not in self.actionIds: action = gio.SimpleAction(name=actionId) action.connect("activate", callback, *args) self.app.add_action(action) return "app." + actionId def valueCellClicked(self, path, forceMenu=False) -> bool: """ Returns True if event is handled, False if not handled (need to enter edit mode). """ model = self.treev.get_model() itr = model.get_iter(path) optName = model.get_value(itr, 1) prop = self.optionsProp[optName] if prop.typ == "bool": rawValue = model.get_value(itr, self.valueCol) if rawValue == "": # noqa: PLC1901 value = False else: value, isValid = prop.evaluate(rawValue) if not isValid: log.error(f"invalid {optName} = {rawValue!r}") value = False model.set_value(itr, self.valueCol, str(not value)) model.set_value(itr, 0, True) # enable it return True propValues = prop.values if not propValues: if forceMenu: propValues = [] else: return False menu = gtk.PopoverMenu() menu.set_parent(self) menuM = menu.get_menu_model() # gio.MenuModel if prop.customValue: item = gio.MenuItem() item.set_label("[Custom Value]") item.set_detailed_action( self.addAction( path, "__custom__", self.valueItemCustomActivate, itr, ), ) menuM.append_item(item) groupedValues = None if len(propValues) > 10: groupedValues = prop.groupValues() if groupedValues: for groupName, values in groupedValues.items(): item = gio.MenuItem() item.set_label(groupName) if values is None: item.set_detailed_action( self.addAction( path, groupName, self.valueItemActivat, itr, ), ) else: subMenu = gio.Menu() for subValue in values: subItem = gio.MenuItem() subItem.set_label(str(subValue)) item.set_detailed_action( self.addAction( path, groupName, self.valueItemActivate, itr, ), ) subMenu.append_item(subItem) item.set_submenu(subMenu) item.show() menu.append_item(item) else: for value in propValues: item = gio.MenuItem() item.set_label(value) item.connect("activate", self.valueItemActivate, itr) item.show() menu.append_item(item) # etime = gtk.get_current_event_time() menu.popup() return True def getOptionsValues(self): model = self.treev.get_model() optionsValues = {} for row in model: if not row[0]: # not enable continue optName = row[1] rawValue = row[3] prop = self.optionsProp[optName] value, isValid = prop.evaluate(rawValue) if not isValid: log.error(f"invalid option value {optName} = {rawValue}") continue optionsValues[optName] = value return optionsValues class FormatBox(FormatButton): def __init__(self, app, descList: list[str], parent=None) -> None: self.app = app FormatButton.__init__(self, descList, parent=parent) self.optionsValues = {} self.optionsButton = gtk.Button(label="Options") # TODO: self.optionsButton.set_icon_name # self.optionsButton.set_image(gtk.Image.new_from_icon_name( # "gtk-preferences", # gtk.IconSize.BUTTON, # )) self.optionsButton.connect("clicked", self.optionsButtonClicked) self.dependsButton = gtk.Button(label="Install dependencies") self.dependsButton.pkgNames = [] self.dependsButton.connect("clicked", self.dependsButtonClicked) def setOptionsValues(self, optionsValues: "dict[str, Any]"): self.optionsValues = optionsValues def kind(self): """Return 'r' or 'w'.""" raise NotImplementedError def getActiveOptions(self): raise NotImplementedError def optionsButtonClicked(self, _button): formatName = self.getActive() options = self.getActiveOptions() dialog = FormatOptionsDialog( self.app, formatName, options, self.optionsValues, transient_for=self._parent, ) dialog.set_title("Options for " + formatName) dialog.connect("response", self.optionsDialogResponse) dialog.present() def optionsDialogResponse(self, dialog, response_id): if response_id == gtk.ResponseType.OK: self.optionsValues = dialog.getOptionsValues() dialog.destroy() def dependsButtonClicked(self, button): formatName = self.getActive() pkgNames = button.pkgNames if not pkgNames: print("All dependencies are stattisfied for " + formatName) return pkgNamesStr = " ".join(pkgNames) msg = f"Run the following command:\n{core.pip} install {pkgNamesStr}" showInfo( msg, title="Dependencies for " + formatName, selectable=True, parent=self._parent, ) self.onChanged(self) def onChanged(self, _obj=None): name = self.getActive() if not name: self.optionsButton.set_visible(False) return self.optionsValues.clear() options = self.getActiveOptions() self.optionsButton.set_visible(bool(options)) kind = self.kind() plugin = Glossary.plugins[name] if kind == "r": depends = plugin.readDepends elif kind == "w": depends = plugin.writeDepends else: raise RuntimeError(f"invalid {kind=}") uninstalled = checkDepends(depends) self.dependsButton.pkgNames = uninstalled self.dependsButton.set_visible(bool(uninstalled)) class InputFormatBox(FormatBox): dialogTitle = "Select Input Format" def __init__(self, app, **kwargs) -> None: FormatBox.__init__(self, app, readDesc, **kwargs) def kind(self): """Return 'r' or 'w'.""" return "r" def getActiveOptions(self): formatName = self.getActive() if not formatName: return None return list(Glossary.formatsReadOptions[formatName]) class OutputFormatBox(FormatBox): dialogTitle = "Select Output Format" def __init__(self, app, **kwargs) -> None: FormatBox.__init__(self, app, writeDesc, **kwargs) def kind(self): """Return 'r' or 'w'.""" return "w" def getActiveOptions(self): return list(Glossary.formatsWriteOptions[self.getActive()]) class GtkTextviewLogHandler(logging.Handler): def __init__(self, mainWin, treeview_dict) -> None: logging.Handler.__init__(self) self.mainWin = mainWin self.buffers = {} for levelNameCap in log.levelNamesCap[:-1]: levelName = levelNameCap.upper() textview = treeview_dict[levelName] buff = textview.get_buffer() tag = gtk.TextTag.new(levelName) buff.get_tag_table().add(tag) self.buffers[levelName] = buff def getTag(self, levelname): return self.buffers[levelname].get_tag_table().lookup(levelname) def setColor(self, levelname: str, rgba: gdk.RGBA) -> None: self.getTag(levelname).set_property("foreground-rgba", rgba) # foreground-gdk is deprecated since Gtk 3.4 def emit(self, record): msg = "" if record.getMessage(): msg = self.format(record) # msg = msg.replace("\x00", "") if record.exc_info: _type, value, tback = record.exc_info tback_text = "".join( traceback.format_exception(_type, value, tback), ) if msg: msg += "\n" msg += tback_text buff = self.buffers[record.levelname] buff.insert_with_tags_by_name( buff.get_end_iter(), msg + "\n", record.levelname, ) if record.levelno == logging.CRITICAL: self.mainWin.status(record.getMessage()) class GtkSingleTextviewLogHandler(GtkTextviewLogHandler): def __init__(self, ui, textview) -> None: GtkTextviewLogHandler.__init__( self, ui, { "CRITICAL": textview, "ERROR": textview, "WARNING": textview, "INFO": textview, "DEBUG": textview, "TRACE": textview, }, ) class BrowseButton(gtk.Button): def __init__( self, setFilePathFunc, label="Browse", actionSave=False, title="Select File", ) -> None: gtk.Button.__init__(self) self.set_label(label) # TODO: self.set_icon_name # self.set_image(gtk.Image.new_from_icon_name( # "document-save" if actionSave else "document-open", # gtk.IconSize.BUTTON, # )) self.actionSave = actionSave self.setFilePathFunc = setFilePathFunc self.title = title self.connect("clicked", self.onClick) def onResponse(self, fcd, response_id): if response_id == gtk.ResponseType.OK: gfile = fcd.get_file() if gfile is not None: self.setFilePathFunc(gfile.get_path()) fcd.destroy() def onClick(self, _widget): fcd = gtk.FileChooserNative( transient_for=self.get_root(), action=gtk.FileChooserAction.SAVE if self.actionSave else gtk.FileChooserAction.OPEN, title=self.title, ) fcd.connect("response", self.onResponse) # fcd.connect( # "file-activated", # FIXME: Gtk 4.0 # lambda w: fcd.response(gtk.ResponseType.OK) # ) fcd.present() sortKeyNameByDesc = {_sk.desc: _sk.name for _sk in namedSortKeyList} sortKeyNames = [_sk.name for _sk in namedSortKeyList] # Gtk.CheckButton is not a subclass of Gtk.Button! LOL class SortOptionsBox(gtk.Box): def __init__(self, mainWin) -> None: gtk.Box.__init__(self, orientation=gtk.Orientation.VERTICAL) self.mainWin = mainWin ### self.set_spacing(5) ### hbox = HBox(spacing=5) sortCheck = gtk.CheckButton(label="Sort entries by") sortKeyCombo = gtk.ComboBoxText() for _sk in namedSortKeyList: sortKeyCombo.append_text(_sk.desc) sortKeyCombo.set_active(sortKeyNames.index(defaultSortKeyName)) sortKeyCombo.set_sensitive(False) # sortKeyCombo.connect("changed", self.sortKeyComboChanged) self.sortCheck = sortCheck self.sortKeyCombo = sortKeyCombo sortCheck.connect("toggled", self.onSortCheckToggled) pack(hbox, sortCheck) pack(hbox, sortKeyCombo) pack(self, hbox) ### hbox = self.encodingHBox = HBox(spacing=5) encodingRadio = self.encodingRadio = gtk.CheckButton(label="Sort Encoding") encodingEntry = self.encodingEntry = gtk.Entry() encodingEntry.set_text("utf-8") encodingEntry.set_width_chars(15) pack(hbox, gtk.Label(label=" ")) pack(hbox, encodingRadio) pack(hbox, encodingEntry) pack(self, hbox) encodingRadio.set_active(True) ### sortRadioSizeGroup = gtk.SizeGroup(mode=gtk.SizeGroupMode.HORIZONTAL) sortRadioSizeGroup.add_widget(encodingRadio) ### self.show() def onSortCheckToggled(self, *_args): sort = self.sortCheck.get_active() self.sortKeyCombo.set_sensitive(sort) self.encodingHBox.set_sensitive(sort) def updateWidgets(self): convertOptions = self.mainWin.convertOptions sort = convertOptions.get("sort") self.sortCheck.set_active(sort) self.sortKeyCombo.set_sensitive(sort) self.encodingHBox.set_sensitive(sort) sortKeyName = convertOptions.get("sortKeyName") if sortKeyName: self.sortKeyCombo.set_active(sortKeyNames.index(sortKeyName)) sortEncoding = convertOptions.get("sortEncoding", "utf-8") self.encodingEntry.set_text(sortEncoding) def applyChanges(self): convertOptions = self.mainWin.convertOptions sort = self.sortCheck.get_active() if not sort: for param in ("sort", "sortKeyName", "sortEncoding"): if param in convertOptions: del convertOptions[param] return sortKeyDesc = self.sortKeyCombo.get_active_text() convertOptions["sort"] = sort convertOptions["sortKeyName"] = sortKeyNameByDesc[sortKeyDesc] if self.encodingRadio.get_active(): convertOptions["sortEncoding"] = self.encodingEntry.get_text() class GeneralOptionsDialog(gtk.Dialog): def onCloseRequest(self, _widget): self.hide() return True def onResponse(self, _widget, _event): self.applyChanges() self.hide() return True def __init__(self, mainWin, **kwargs) -> None: gtk.Dialog.__init__( self, transient_for=mainWin, **kwargs, ) self.set_title("General Options") self.mainWin = mainWin ## self.vbox = self.get_content_area() self.vbox.set_spacing(5) ## self.set_default_size(600, 500) self.connect("close-request", self.onCloseRequest) ## self.connect("response", self.onResponse) dialog_add_button( self, "gtk-ok", "_OK", gtk.ResponseType.OK, ) ## hpad = 10 ## self.sortOptionsBox = SortOptionsBox(mainWin) pack(self.vbox, self.sortOptionsBox) ## hbox = HBox(spacing=hpad) self.sqliteCheck = gtk.CheckButton(label="SQLite mode") pack(hbox, self.sqliteCheck) pack(self.vbox, hbox) ## self.configParams = OrderedDict( [ ("save_info_json", False), ("lower", False), ("skip_resources", False), ("rtl", False), ("enable_alts", True), ("cleanup", True), ("remove_html_all", True), ], ) self.configCheckButtons = {} configDefDict = UIBase.configDefDict for param in self.configParams: hbox = HBox(spacing=hpad) comment = configDefDict[param].comment checkButton = gtk.CheckButton( label=comment.split("\n")[0], ) self.configCheckButtons[param] = checkButton pack(hbox, checkButton) pack(self.vbox, hbox) ## self.updateWidgets() self.vbox.show() def getSQLite(self) -> bool: convertOptions = self.mainWin.convertOptions sqlite = convertOptions.get("sqlite") if sqlite is not None: return sqlite return self.mainWin.config.get("auto_sqlite", True) def updateWidgets(self): config = self.mainWin.config self.sortOptionsBox.updateWidgets() self.sqliteCheck.set_active(self.getSQLite()) for param, check in self.configCheckButtons.items(): default = self.configParams[param] check.set_active(config.get(param, default)) def applyChanges(self): # print("applyChanges") self.sortOptionsBox.applyChanges() convertOptions = self.mainWin.convertOptions config = self.mainWin.config convertOptions["sqlite"] = self.sqliteCheck.get_active() for param, check in self.configCheckButtons.items(): config[param] = check.get_active() class GeneralOptionsButton(gtk.Button): def __init__(self, mainWin) -> None: gtk.Button.__init__(self, label="General Options") self.mainWin = mainWin self.connect("clicked", self.onClick) self.dialog = None def onClick(self, _widget): if self.dialog is None: self.dialog = GeneralOptionsDialog(self.mainWin) self.dialog.present() class MainWindow(gtk.Window): # @property # def config(self): # return self.ui.config css = """ textview.console text { background-color: rgb(0, 0, 0); } check { min-width: 1.25em; min-height: 1.25em; } .margin_03 { margin-top: 0.5em; margin-right: 0.5em; margin-bottom: 0.5em; margin-left: 0.5em; } .margin_05 { margin-top: 0.5em; margin-right: 0.5em; margin-bottom: 0.5em; margin-left: 0.5em; } .margin_10 { margin-top: 1em; margin-right: 1em; margin-bottom: 1em; margin-left: 1em; } """ def status(self, msg): # try: # _id = self.statusMsgDict[msg] # except KeyError: # _id = self.statusMsgDict[msg] = self.statusNewId # self.statusNewId += 1 _id = self.statusBar.get_context_id(msg) self.statusBar.push(_id, msg) def __init__( self, ui=None, progressbar: bool = True, **kwargs, ) -> None: self.ui = ui ##### gtk.Window.__init__(self, **kwargs) self.set_title("PyGlossary (Gtk3)") self.progressbarEnable = progressbar ##### self.vbox = VBox() self.set_child(self.vbox) ##### # FIXME screenW, screenH = getWorkAreaSize(self) winSize = min(800, screenW - 50, screenH - 50) self.set_default_size(winSize, winSize) ##### # gesture = gtk.GestureClick.new() # gesture.connect("pressed", self.onButtonPress) # self.add_controller(gesture) ### ckey = gtk.EventControllerKey() ckey.connect("key-pressed", self.onKeyPress) self.add_controller(ckey) #### self.connect("close-request", self.onCloseRequest) #### self.pages = [] # self.statusNewId = 0 # self.statusMsgDict = {}## message -> id ##### self.convertOptions = {} ##### self.styleProvider = gtk.CssProvider() gtk.StyleContext.add_provider_for_display( gdk.Display.get_default(), self.styleProvider, gtk.STYLE_PROVIDER_PRIORITY_APPLICATION, ) # gtk.StyleContext.add_provider_for_screen( # gdk.Screen.get_default(), # self.styleProvider, # gtk.STYLE_PROVIDER_PRIORITY_APPLICATION, # ) self.styleProvider.load_from_data(self.css, len(self.css.encode("utf-8"))) ##### self.assert_quit = False self.path = "" # ____________________ Tab 1 - Convert ____________________ # labelSizeGroup = gtk.SizeGroup(mode=gtk.SizeGroupMode.HORIZONTAL) buttonSizeGroup = gtk.SizeGroup(mode=gtk.SizeGroupMode.HORIZONTAL) #### vbox = VBox(spacing=5) vbox.label = _("Convert") vbox.icon = "" # "*.png" self.pages.append(vbox) ###### hbox = HBox(spacing=3) hbox.label = gtk.Label(label=_("Input File:")) pack(hbox, hbox.label) labelSizeGroup.add_widget(hbox.label) hbox.label.set_property("xalign", 0) self.convertInputEntry = gtk.Entry() pack(hbox, self.convertInputEntry, 1, 1) button = BrowseButton( self.convertInputEntry.set_text, label="Browse", actionSave=False, title="Select Input File", ) pack(hbox, button) buttonSizeGroup.add_widget(button) pack(vbox, hbox) ## self.convertInputEntry.connect( "changed", self.convertInputEntryChanged, ) ### hbox = HBox(spacing=3) hbox.label = gtk.Label(label=_("Input Format:")) pack(hbox, hbox.label) labelSizeGroup.add_widget(hbox.label) hbox.label.set_property("xalign", 0) self.convertInputFormatCombo = InputFormatBox(self.ui, parent=self) buttonSizeGroup.add_widget(self.convertInputFormatCombo.optionsButton) pack(hbox, self.convertInputFormatCombo) pack(hbox, gtk.Label(), 1, 1) pack(hbox, self.convertInputFormatCombo.dependsButton) pack(hbox, self.convertInputFormatCombo.optionsButton) pack(vbox, hbox) ##### hbox = HBox() hbox.get_style_context().add_class("margin_03") pack(vbox, hbox) ##### hbox = HBox(spacing=3) hbox.label = gtk.Label(label=_("Output File:")) pack(hbox, hbox.label) labelSizeGroup.add_widget(hbox.label) hbox.label.set_property("xalign", 0) self.convertOutputEntry = gtk.Entry() pack(hbox, self.convertOutputEntry, 1, 1) button = BrowseButton( self.convertOutputEntry.set_text, label="Browse", actionSave=True, title="Select Output File", ) pack(hbox, button) buttonSizeGroup.add_widget(button) pack(vbox, hbox) ## self.convertOutputEntry.connect( "changed", self.convertOutputEntryChanged, ) ### hbox = HBox(spacing=3) hbox.label = gtk.Label(label=_("Output Format:")) pack(hbox, hbox.label) labelSizeGroup.add_widget(hbox.label) hbox.label.set_property("xalign", 0) self.convertOutputFormatCombo = OutputFormatBox(self.ui, parent=self) buttonSizeGroup.add_widget(self.convertOutputFormatCombo.optionsButton) pack(hbox, self.convertOutputFormatCombo) pack(hbox, gtk.Label(), 1, 1) pack(hbox, self.convertOutputFormatCombo.dependsButton) pack(hbox, self.convertOutputFormatCombo.optionsButton) pack(vbox, hbox) ##### hbox = HBox(spacing=10) hbox.get_style_context().add_class("margin_03") label = gtk.Label(label="") pack(hbox, label, expand=True) ## button = GeneralOptionsButton(self) button.set_size_request(300, 40) pack(hbox, button) ## self.convertButton = gtk.Button() self.convertButton.set_label("Convert") self.convertButton.connect("clicked", self.convertClicked) self.convertButton.set_size_request(300, 40) pack(hbox, self.convertButton) ## pack(vbox, hbox) # FIXME: padding=15 ##### self.convertConsoleTextview = textview = gtk.TextView() swin = gtk.ScrolledWindow() swin.set_policy(gtk.PolicyType.AUTOMATIC, gtk.PolicyType.AUTOMATIC) swin.set_child(textview) pack(vbox, swin, expand=True) # ____________________ Tab 2 - Reverse ____________________ # self.reverseStatus = "" #### labelSizeGroup = gtk.SizeGroup(mode=gtk.SizeGroupMode.HORIZONTAL) #### vbox = VBox() vbox.label = _("Reverse") vbox.icon = "" # "*.png" # self.pages.append(vbox) ###### hbox = HBox(spacing=3) hbox.label = gtk.Label(label=_("Input Format:")) pack(hbox, hbox.label) labelSizeGroup.add_widget(hbox.label) hbox.label.set_property("xalign", 0) self.reverseInputFormatCombo = InputFormatBox(self.ui) pack(hbox, self.reverseInputFormatCombo) pack(vbox, hbox) ### hbox = HBox(spacing=3) hbox.label = gtk.Label(label=_("Input File:")) pack(hbox, hbox.label) labelSizeGroup.add_widget(hbox.label) hbox.label.set_property("xalign", 0) self.reverseInputEntry = gtk.Entry() pack(hbox, self.reverseInputEntry, 1, 1) button = BrowseButton( self.reverseInputEntry.set_text, label="Browse", actionSave=False, title="Select Input File", ) pack(hbox, button) pack(vbox, hbox) ## self.reverseInputEntry.connect( "changed", self.reverseInputEntryChanged, ) ##### hbox = HBox() hbox.get_style_context().add_class("margin_03") pack(vbox, hbox) ##### hbox = HBox(spacing=3) hbox.label = gtk.Label(label=_("Output Tabfile:")) pack(hbox, hbox.label) labelSizeGroup.add_widget(hbox.label) hbox.label.set_property("xalign", 0) self.reverseOutputEntry = gtk.Entry() pack(hbox, self.reverseOutputEntry, 1, 1) button = BrowseButton( self.reverseOutputEntry.set_text, label="Browse", actionSave=True, title="Select Output File", ) pack(hbox, button) pack(vbox, hbox) ## self.reverseOutputEntry.connect( "changed", self.reverseOutputEntryChanged, ) ##### hbox = HBox(spacing=5) label = gtk.Label(label="") pack(hbox, label, expand=True) ### self.reverseStartButton = gtk.Button() self.reverseStartButton.set_label(_("Start")) self.reverseStartButton.connect("clicked", self.reverseStartClicked) pack(hbox, self.reverseStartButton, expand=True) ### self.reversePauseButton = gtk.Button() self.reversePauseButton.set_label(_("Pause")) self.reversePauseButton.set_sensitive(False) self.reversePauseButton.connect("clicked", self.reversePauseClicked) pack(hbox, self.reversePauseButton, expand=True) ### self.reverseResumeButton = gtk.Button() self.reverseResumeButton.set_label(_("Resume")) self.reverseResumeButton.set_sensitive(False) self.reverseResumeButton.connect("clicked", self.reverseResumeClicked) pack(hbox, self.reverseResumeButton, expand=True) ### self.reverseStopButton = gtk.Button() self.reverseStopButton.set_label(_("Stop")) self.reverseStopButton.set_sensitive(False) self.reverseStopButton.connect("clicked", self.reverseStopClicked) pack(hbox, self.reverseStopButton, expand=True) ### pack(vbox, hbox) # FIXME: padding=5 ###### about = AboutWidget( logo=logo, header=f"PyGlossary\nVersion {getVersion()}", # about=summary, about=f'{aboutText}\n<a href="{core.homePage}">{core.homePage}</a>', authors="\n".join(authors), license_text=licenseText, ) about.label = _("About") about.icon = "" # "*.png" self.pages.append(about) ##### # ____________________________________________________________ # notebook = gtk.Notebook() self.notebook = notebook ######### for vbox in self.pages: label = gtk.Label(label=vbox.label) label.set_use_underline(True) vb = VBox(spacing=3) if vbox.icon: vbox.image = imageFromFile(vbox.icon) pack(vb, vbox.image) pack(vb, label) vb.show() notebook.append_page(vbox, vb) try: notebook.set_tab_reorderable(vbox, True) except AttributeError: pass ####################### pack(self.vbox, notebook, 1, 1) # for i in ui.pagesOrder: # try: # j = pagesOrder[i] # except IndexError: # continue # notebook.reorder_child(self.pages[i], j) # ____________________________________________________________ # ########## textview.get_style_context().add_class("console") handler = GtkSingleTextviewLogHandler(self, textview) log.addHandler(handler) ### handler.setColor("CRITICAL", rgba_parse("red")) handler.setColor("ERROR", rgba_parse("red")) handler.setColor("WARNING", rgba_parse("yellow")) handler.setColor("INFO", rgba_parse("white")) handler.setColor("DEBUG", rgba_parse("white")) handler.setColor("TRACE", rgba_parse("white")) ### textview.get_buffer().set_text("Output & Error Console:\n") textview.set_editable(False) # ____________________________________________________________ # self.progressTitle = "" self.progressBar = pbar = gtk.ProgressBar() pbar.set_fraction(0) # pbar.set_text(_("Progress Bar")) # pbar.get_style_context() # pbar.set_property("height-request", 20) pack(self.vbox, pbar) ############ hbox = HBox(spacing=5) clearButton = gtk.Button( # always_show_image=True, label=_("Clear"), # icon_name="clear", ) clearButton.show() # image = gtk.Image() # image.set_icon_name(...) # clearButton.add(image) clearButton.connect("clicked", self.consoleClearButtonClicked) set_tooltip(clearButton, "Clear Console") pack(hbox, clearButton) #### # hbox.sepLabel1 = gtk.Label(label="") # pack(hbox, hbox.sepLabel1, 1, 1) ###### hbox.verbosityLabel = gtk.Label(label=_("Verbosity:")) pack(hbox, hbox.verbosityLabel) ## self.verbosityCombo = combo = gtk.ComboBoxText() for level, levelName in enumerate(log.levelNamesCap): combo.append_text(f"{level} - {_(levelName)}") combo.set_active(log.getVerbosity()) combo.connect("changed", self.verbosityComboChanged) pack(hbox, combo) #### # hbox.sepLabel2 = gtk.Label(label="") # pack(hbox, hbox.sepLabel2, 1, 1) #### self.statusBar = gtk.Statusbar() pack(hbox, self.statusBar, 1, 1) #### # ResizeButton does not work in Gtk 4.0 # hbox.resizeButton = ResizeButton(self) # pack(hbox, hbox.resizeButton) ###### pack(self.vbox, hbox) # ____________________________________________________________ # self.vbox.show() notebook.set_current_page(0) # Convert tab self.convertInputFormatCombo.dependsButton.hide() self.convertOutputFormatCombo.dependsButton.hide() self.convertInputFormatCombo.optionsButton.hide() self.convertOutputFormatCombo.optionsButton.hide() ######## self.status("Select input file") def run( # noqa: PLR0913 self, inputFilename: str = "", outputFilename: str = "", inputFormat: str = "", outputFormat: str = "", reverse: bool = False, config: "dict | None" = None, readOptions: "dict | None" = None, writeOptions: "dict | None" = None, convertOptions: "dict | None" = None, glossarySetAttrs: "dict | None" = None, ): if glossarySetAttrs is None: glossarySetAttrs = {} self.config = config if inputFilename: self.convertInputEntry.set_text(abspath(inputFilename)) if outputFilename: self.convertOutputEntry.set_text(abspath(outputFilename)) if inputFormat: self.convertInputFormatCombo.setActive(inputFormat) if outputFormat: self.convertOutputFormatCombo.setActive(outputFormat) if reverse: log.error("Gtk interface does not support Reverse feature") if readOptions: self.convertInputFormatCombo.setOptionsValues(readOptions) if writeOptions: self.convertOutputFormatCombo.setOptionsValues(writeOptions) self.convertOptions = convertOptions if convertOptions: log.debug(f"Using {convertOptions=}") self._glossarySetAttrs = glossarySetAttrs self.present() def exitApp(self): self.destroy() sys.exit(0) def onCloseRequest(self, _widget): self.exitApp() def onKeyPress( self, _ckey: "gtk.EventControllerKey", keyval: int, _keycode: int, _state: "gdk.ModifierType", ): if keyval == gdk.KEY_Escape: self.exitApp() def onButtonPress(self, gesture, _n_press, _x, _y): print(f"MainWindow.onButtonPress: {gesture}") def consoleClearButtonClicked(self, _widget=None): self.convertConsoleTextview.get_buffer().set_text("") def verbosityComboChanged(self, _widget=None): verbosity = self.verbosityCombo.get_active() # or int(self.verbosityCombo.get_active_text()) log.setVerbosity(verbosity) def convertClicked(self, _widget=None): inPath = self.convertInputEntry.get_text() if not inPath: log.critical("Input file path is empty!") return None inFormat = self.convertInputFormatCombo.getActive() outPath = self.convertOutputEntry.get_text() if not outPath: log.critical("Output file path is empty!") return None outFormat = self.convertOutputFormatCombo.getActive() gtk_event_iteration_loop() self.convertButton.set_sensitive(False) self.progressTitle = "Converting" readOptions = self.convertInputFormatCombo.optionsValues writeOptions = self.convertOutputFormatCombo.optionsValues glos = Glossary(ui=self.ui) glos.config = self.config glos.progressbar = self.progressbarEnable for attr, value in self._glossarySetAttrs.items(): setattr(glos, attr, value) log.debug(f"readOptions: {readOptions}") log.debug(f"writeOptions: {writeOptions}") log.debug(f"convertOptions: {self.convertOptions}") log.debug(f"config: {self.config}") try: finalOutputFile = glos.convert( ConvertArgs( inPath, inputFormat=inFormat, outputFilename=outPath, outputFormat=outFormat, readOptions=readOptions, writeOptions=writeOptions, **self.convertOptions, ), ) if finalOutputFile: self.status("Convert finished") return bool(finalOutputFile) except Error as e: log.critical(str(e)) glos.cleanup() return False finally: self.convertButton.set_sensitive(True) self.assert_quit = False self.progressTitle = "" return True def convertInputEntryChanged(self, _widget=None): inPath = self.convertInputEntry.get_text() inFormat = self.convertInputFormatCombo.getActive() if inPath.startswith("file://"): inPath = urlToPath(inPath) self.convertInputEntry.set_text(inPath) if self.config["ui_autoSetFormat"] and not inFormat: try: inputArgs = Glossary.detectInputFormat(inPath) except Error: pass else: self.convertInputFormatCombo.setActive(inputArgs.formatName) if not isfile(inPath): return self.status("Select output file") def convertOutputEntryChanged(self, _widget=None): outPath = self.convertOutputEntry.get_text() outFormat = self.convertOutputFormatCombo.getActive() if not outPath: return if outPath.startswith("file://"): outPath = urlToPath(outPath) self.convertOutputEntry.set_text(outPath) if self.config["ui_autoSetFormat"] and not outFormat: try: outputArgs = Glossary.detectOutputFormat( filename=outPath, inputFilename=self.convertInputEntry.get_text(), ) except Error: pass else: outFormat = outputArgs.formatName self.convertOutputFormatCombo.setActive(outFormat) if outFormat: self.status('Press "Convert"') else: self.status("Select output format") def reverseLoad(self): pass def reverseStartLoop(self): pass def reverseStart(self): if not self.reverseLoad(): return ### self.reverseStatus = "doing" self.reverseStartLoop() ### self.reverseStartButton.set_sensitive(False) self.reversePauseButton.set_sensitive(True) self.reverseResumeButton.set_sensitive(False) self.reverseStopButton.set_sensitive(True) def reverseStartClicked(self, _widget=None): self.waitingDo(self.reverseStart) def reversePause(self): self.reverseStatus = "pause" ### self.reverseStartButton.set_sensitive(False) self.reversePauseButton.set_sensitive(False) self.reverseResumeButton.set_sensitive(True) self.reverseStopButton.set_sensitive(True) def reversePauseClicked(self, _widget=None): self.waitingDo(self.reversePause) def reverseResume(self): self.reverseStatus = "doing" ### self.reverseStartButton.set_sensitive(False) self.reversePauseButton.set_sensitive(True) self.reverseResumeButton.set_sensitive(False) self.reverseStopButton.set_sensitive(True) def reverseResumeClicked(self, _widget=None): self.waitingDo(self.reverseResume) def reverseStop(self): self.reverseStatus = "stop" ### self.reverseStartButton.set_sensitive(True) self.reversePauseButton.set_sensitive(False) self.reverseResumeButton.set_sensitive(False) self.reverseStopButton.set_sensitive(False) def reverseStopClicked(self, _widget=None): self.waitingDo(self.reverseStop) def reverseInputEntryChanged(self, _widget=None): inPath = self.reverseInputEntry.get_text() if inPath.startswith("file://"): inPath = urlToPath(inPath) self.reverseInputEntry.set_text(inPath) if ( self.config["ui_autoSetFormat"] and not self.reverseInputFormatCombo.getActive() ): try: inputArgs = Glossary.detectInputFormat(inPath) except Error: pass else: self.reverseInputFormatCombo.setActive(inputArgs.formatName) def reverseOutputEntryChanged(self, widget=None): pass def progressInit(self, title): self.progressTitle = title def progress(self, ratio, text=None): if not text: text = "%" + str(int(ratio * 100)) text += " - " + self.progressTitle self.progressBar.set_fraction(ratio) # self.progressBar.set_text(text) # not working self.status(text) gtk_event_iteration_loop() class Application(gtk.Application): def __init__(self) -> None: gtk.Application.__init__( self, application_id="apps.starcal", flags=gio.ApplicationFlags.FLAGS_NONE, ) self.win = None def do_activate(self): win = self.props.active_window if not win: win = self.win self.add_window(win) win.set_application(self) win.present() class UI(UIBase): def __init__( self, progressbar: bool = True, ) -> None: UIBase.__init__(self) self.app = Application() self.win = MainWindow( ui=self, progressbar=progressbar, ) self.app.win = self.win def run(self, **kwargs): self.win.run(**kwargs) self.app.run(None) gtk_window_iteration_loop()
46,799
Python
.py
1,564
26.641944
83
0.714029
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,763
ui_gtk.py
ilius_pyglossary/pyglossary/ui/ui_gtk.py
# -*- coding: utf-8 -*- # mypy: ignore-errors # ui_gtk.py # # Copyright © 2008-2022 Saeed Rasooli <saeed.gnu@gmail.com> (ilius) # # This program is a free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # You can get a copy of GNU General Public License along this program # But you can always get it from http://www.gnu.org/licenses/gpl.txt # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. from __future__ import annotations import logging import sys import traceback from collections import OrderedDict from os.path import abspath, isfile from typing import TYPE_CHECKING, Any import gi from pyglossary import core from pyglossary.glossary_v2 import ConvertArgs, Error, Glossary from pyglossary.sort_keys import defaultSortKeyName, namedSortKeyList from pyglossary.text_utils import urlToPath from .base import ( UIBase, aboutText, authors, licenseText, logo, ) from .dependency import checkDepends from .version import getVersion gi.require_version("Gtk", "3.0") from .gtk3_utils import gdk, gtk # noqa: E402 from .gtk3_utils.about import AboutWidget # noqa: E402 from .gtk3_utils.dialog import MyDialog # noqa: E402 from .gtk3_utils.resize_button import ResizeButton # noqa: E402 from .gtk3_utils.utils import ( # noqa: E402 HBox, VBox, dialog_add_button, imageFromFile, pack, rgba_parse, set_tooltip, showInfo, ) if TYPE_CHECKING: from pyglossary.plugin_prop import PluginProp # from gi.repository import GdkPixbuf log = logging.getLogger("pyglossary") gtk.Window.set_default_icon_from_file(logo) _ = str # later replace with translator function pluginByDesc = {plugin.description: plugin for plugin in Glossary.plugins.values()} readDesc = [ plugin.description for plugin in Glossary.plugins.values() if plugin.canRead ] writeDesc = [ plugin.description for plugin in Glossary.plugins.values() if plugin.canWrite ] def getMonitor(): display = gdk.Display.get_default() monitor = display.get_monitor_at_point(1, 1) if monitor is not None: log.debug("getMonitor: using get_monitor_at_point") return monitor monitor = display.get_primary_monitor() if monitor is not None: log.debug("getMonitor: using get_primary_monitor") return monitor monitor = display.get_monitor_at_window(gdk.get_default_root_window()) if monitor is not None: log.debug("getMonitor: using get_monitor_at_window") return monitor return None def getWorkAreaSize() -> tuple[int, int] | None: monitor = getMonitor() if monitor is None: return None rect = monitor.get_workarea() return rect.width, rect.height def buffer_get_text(b): return b.get_text( b.get_start_iter(), b.get_end_iter(), True, ) class FormatDialog(gtk.Dialog): def __init__( self, descList: list[str], parent=None, **kwargs, ) -> None: gtk.Dialog.__init__(self, parent=parent, **kwargs) self.descList = descList self.items = descList self.activeDesc = "" ## self.connect("response", lambda _w, _e: self.hide()) dialog_add_button( self, "gtk-cancel", "_Cancel", gtk.ResponseType.CANCEL, ) dialog_add_button( self, "gtk-ok", "_OK", gtk.ResponseType.OK, ) ### treev = gtk.TreeView() treeModel = gtk.ListStore(str) treev.set_headers_visible(False) treev.set_model(treeModel) treev.connect("row-activated", self.rowActivated) # treev.connect("response", self.onResponse) ### self.treev = treev ############# cell = gtk.CellRendererText(editable=False) col = gtk.TreeViewColumn( title="Descriptin", cell_renderer=cell, text=0, ) col.set_property("expand", True) col.set_resizable(True) treev.append_column(col) self.descCol = col ############ hbox = HBox(spacing=15) hbox.set_border_width(10) pack(hbox, gtk.Label("Search:")) entry = self.entry = gtk.Entry() pack(hbox, entry, 1, 1) pack(self.vbox, hbox) ### entry.connect("changed", self.onEntryChange) ############ self.swin = swin = gtk.ScrolledWindow() swin.add(treev) swin.set_policy(gtk.PolicyType.NEVER, gtk.PolicyType.AUTOMATIC) pack(self.vbox, swin, 1, 1) self.vbox.show_all() ## treev.set_can_focus(True) # no need, just to be safe treev.set_can_default(True) treev.set_receives_default(True) # print("can_focus:", treev.get_can_focus()) # print("can_default:", treev.get_can_default()) # print("receives_default:", treev.get_receives_default()) #### self.updateTree() self.resize(400, 400) self.connect("realize", self.onRealize) def onRealize(self, _widget=None): if self.activeDesc: self.treev.grab_focus() else: self.entry.grab_focus() def onEntryChange(self, entry): text = entry.get_text().strip() if not text: self.items = self.descList self.updateTree() return text = text.lower() descList = self.descList items1 = [] items2 = [] for desc in descList: if desc.lower().startswith(text): items1.append(desc) elif text in desc.lower(): items2.append(desc) self.items = items1 + items2 self.updateTree() def setCursor(self, desc: str): model = self.treev.get_model() _iter = model.iter_children(None) while _iter is not None: if model.get_value(_iter, 0) == desc: path = model.get_path(_iter) self.treev.set_cursor(path, self.descCol, False) self.treev.scroll_to_cell(path) return _iter = model.iter_next(_iter) def updateTree(self): model = self.treev.get_model() model.clear() for desc in self.items: model.append([desc]) if self.activeDesc: self.setCursor(self.activeDesc) def getActive(self) -> PluginProp | None: _iter = self.treev.get_selection().get_selected()[1] if _iter is None: return None model = self.treev.get_model() desc = model.get_value(_iter, 0) return pluginByDesc[desc] def setActive(self, plugin): if plugin is None: self.activeDesc = "" return desc = plugin.description self.activeDesc = desc self.setCursor(desc) def rowActivated(self, treev, path, _col): model = treev.get_model() _iter = model.get_iter(path) desc = model.get_value(_iter, 0) self.activeDesc = desc self.response(gtk.ResponseType.OK) # def onResponse class FormatButton(gtk.Button): noneLabel = "[Select Format]" dialogTitle = "Select Format" def __init__(self, descList: list[str], parent=None) -> None: gtk.Button.__init__(self) self.set_label(self.noneLabel) ### self.descList = descList self._parent = parent self.activePlugin = None ### self.connect("clicked", self.onClick) def onChanged(self, obj=None): pass def onClick(self, _button=None): dialog = FormatDialog( descList=self.descList, parent=self._parent, title=self.dialogTitle, ) dialog.setActive(self.activePlugin) if dialog.run() != gtk.ResponseType.OK: return plugin = dialog.getActive() self.activePlugin = plugin if plugin: self.set_label(plugin.description) else: self.set_label(self.noneLabel) self.onChanged() def getActive(self): if self.activePlugin is None: return "" return self.activePlugin.name def setActive(self, _format): plugin = Glossary.plugins[_format] self.activePlugin = plugin self.set_label(plugin.description) self.onChanged() class FormatOptionsDialog(gtk.Dialog): commentLen = 60 def __init__( self, formatName: str, options: list[str], optionsValues: "dict[str, Any]", parent=None, ) -> None: gtk.Dialog.__init__(self, parent=parent) optionsProp = Glossary.plugins[formatName].optionsProp self.optionsProp = optionsProp ## self.connect("response", lambda _w, _e: self.hide()) dialog_add_button( self, "gtk-cancel", "_Cancel", gtk.ResponseType.CANCEL, ) dialog_add_button( self, "gtk-ok", "_OK", gtk.ResponseType.OK, ) ### treev = gtk.TreeView() treeModel = gtk.ListStore( bool, # enable str, # name str, # comment str, # value ) treev.set_headers_clickable(True) treev.set_model(treeModel) treev.connect("row-activated", self.rowActivated) treev.connect("button-press-event", self.treeviewButtonPress) ### self.treev = treev ############# cell = gtk.CellRendererToggle() # cell.set_property("activatable", True) cell.connect("toggled", self.enableToggled) col = gtk.TreeViewColumn(title="Enable", cell_renderer=cell) col.add_attribute(cell, "active", 0) # cell.set_active(False) col.set_property("expand", False) col.set_resizable(True) treev.append_column(col) ### col = gtk.TreeViewColumn( title="Name", cell_renderer=gtk.CellRendererText(), text=1, ) col.set_property("expand", False) col.set_resizable(True) treev.append_column(col) ### cell = gtk.CellRendererText(editable=True) self.valueCell = cell self.valueCol = 3 cell.connect("edited", self.valueEdited) col = gtk.TreeViewColumn( title="Value", cell_renderer=cell, text=self.valueCol, ) col.set_property("expand", True) col.set_resizable(True) col.set_min_width(200) treev.append_column(col) ### col = gtk.TreeViewColumn( title="Comment", cell_renderer=gtk.CellRendererText(), text=2, ) col.set_property("expand", False) col.set_resizable(False) treev.append_column(col) ############# for name in options: prop = optionsProp[name] comment = prop.longComment if len(comment) > self.commentLen: comment = comment[: self.commentLen] + "..." if prop.typ != "bool" and not prop.values: comment += " (double-click to edit)" treeModel.append( [ name in optionsValues, # enable name, # name comment, # comment str(optionsValues.get(name, "")), # value ], ) ############ pack(self.vbox, treev, 1, 1) self.vbox.show_all() def enableToggled(self, cell, path): # enable is column 0 model = self.treev.get_model() active = not cell.get_active() itr = model.get_iter(path) model.set_value(itr, 0, active) def valueEdited(self, _cell, path, rawValue): # value is column 3 model = self.treev.get_model() itr = model.get_iter(path) optName = model.get_value(itr, 1) prop = self.optionsProp[optName] if not prop.customValue: return enable = True if rawValue == "" and prop.typ != "str": # noqa: PLC1901 enable = False elif not prop.validateRaw(rawValue): log.error(f"invalid {prop.typ} value: {optName} = {rawValue!r}") return model.set_value(itr, self.valueCol, rawValue) model.set_value(itr, 0, enable) def rowActivated(self, _treev, path, _col): # forceMenu=True because we can not enter edit mode # if double-clicked on a cell other than Value return self.valueCellClicked(path, forceMenu=True) def treeviewButtonPress(self, treev, gevent): if gevent.button != 1: return False pos_t = treev.get_path_at_pos(int(gevent.x), int(gevent.y)) if not pos_t: return False # pos_t == path, col, xRel, yRel path = pos_t[0] col = pos_t[1] # cell = col.get_cells()[0] if col.get_title() == "Value": return self.valueCellClicked(path) return False def valueItemActivate(self, item: gtk.MenuItem, itr: gtk.TreeIter): # value is column 3 value = item.get_label() model = self.treev.get_model() model.set_value(itr, self.valueCol, value) model.set_value(itr, 0, True) # enable it def valueCustomOpenDialog(self, itr: gtk.TreeIter, optName: str): model = self.treev.get_model() prop = self.optionsProp[optName] currentValue = model.get_value(itr, self.valueCol) optDesc = optName if prop.comment: optDesc += f" ({prop.comment})" label = gtk.Label(label=f"Value for {optDesc}") dialog = gtk.Dialog(parent=self, title="Option Value") dialog.connect("response", lambda _w, _e: dialog.hide()) dialog_add_button( dialog, "gtk-cancel", "_Cancel", gtk.ResponseType.CANCEL, ) dialog_add_button( dialog, "gtk-ok", "_OK", gtk.ResponseType.OK, ) pack(dialog.vbox, label, 0, 0) entry = gtk.Entry() entry.set_text(currentValue) entry.connect("activate", lambda _w: dialog.response(gtk.ResponseType.OK)) pack(dialog.vbox, entry, 0, 0) dialog.vbox.show_all() if dialog.run() != gtk.ResponseType.OK: return value = entry.get_text() model.set_value(itr, self.valueCol, value) model.set_value(itr, 0, True) # enable it def valueItemCustomActivate( self, _item: gtk.MenuItem, itr: gtk.TreeIter, ): model = self.treev.get_model() optName = model.get_value(itr, 1) self.valueCustomOpenDialog(itr, optName) def valueCellClicked(self, path, forceMenu=False) -> bool: """ Returns True if event is handled, False if not handled (need to enter edit mode). """ model = self.treev.get_model() itr = model.get_iter(path) optName = model.get_value(itr, 1) prop = self.optionsProp[optName] if prop.typ == "bool": rawValue = model.get_value(itr, self.valueCol) if rawValue == "": # noqa: PLC1901 value = False else: value, isValid = prop.evaluate(rawValue) if not isValid: log.error(f"invalid {optName} = {rawValue!r}") value = False model.set_value(itr, self.valueCol, str(not value)) model.set_value(itr, 0, True) # enable it return True propValues = prop.values if not propValues: if forceMenu: propValues = [] else: return False menu = gtk.Menu() if prop.customValue: item = gtk.MenuItem("[Custom Value]") item.connect("activate", self.valueItemCustomActivate, itr) item.show() menu.append(item) groupedValues = None if len(propValues) > 10: groupedValues = prop.groupValues() if groupedValues: for groupName, values in groupedValues.items(): item = gtk.MenuItem() item.set_label(groupName) if values is None: item.connect("activate", self.valueItemActivate, itr) else: subMenu = gtk.Menu() for subValue in values: subItem = gtk.MenuItem(label=str(subValue)) subItem.connect("activate", self.valueItemActivate, itr) subItem.show() subMenu.append(subItem) item.set_submenu(subMenu) item.show() menu.append(item) else: for value in propValues: item = gtk.MenuItem(value) item.connect("activate", self.valueItemActivate, itr) item.show() menu.append(item) etime = gtk.get_current_event_time() menu.popup(None, None, None, None, 3, etime) return True def getOptionsValues(self): model = self.treev.get_model() optionsValues = {} for row in model: if not row[0]: # not enable continue optName = row[1] rawValue = row[3] prop = self.optionsProp[optName] value, isValid = prop.evaluate(rawValue) if not isValid: log.error(f"invalid option value {optName} = {rawValue}") continue optionsValues[optName] = value return optionsValues class FormatBox(FormatButton): def __init__(self, descList: list[str], parent=None) -> None: FormatButton.__init__(self, descList, parent=parent) self.optionsValues = {} self.optionsButton = gtk.Button(label="Options") self.optionsButton.set_image( gtk.Image.new_from_icon_name( "gtk-preferences", gtk.IconSize.BUTTON, ), ) self.optionsButton.connect("clicked", self.optionsButtonClicked) self.dependsButton = gtk.Button(label="Install dependencies") self.dependsButton.pkgNames = [] self.dependsButton.connect("clicked", self.dependsButtonClicked) def setOptionsValues(self, optionsValues: "dict[str, Any]"): self.optionsValues = optionsValues def kind(self): """Return 'r' or 'w'.""" raise NotImplementedError def getActiveOptions(self): raise NotImplementedError def optionsButtonClicked(self, _button): formatName = self.getActive() options = self.getActiveOptions() dialog = FormatOptionsDialog( formatName, options, self.optionsValues, parent=self._parent, ) dialog.set_title("Options for " + formatName) if dialog.run() != gtk.ResponseType.OK: dialog.destroy() return self.optionsValues = dialog.getOptionsValues() dialog.destroy() def dependsButtonClicked(self, button): formatName = self.getActive() pkgNames = button.pkgNames if not pkgNames: print("All dependencies are stattisfied for " + formatName) return pkgNamesStr = " ".join(pkgNames) msg = f"Run the following command:\n{core.pip} install {pkgNamesStr}" showInfo( msg, title="Dependencies for " + formatName, selectable=True, parent=self._parent, ) self.onChanged(self) def onChanged(self, _obj=None): name = self.getActive() if not name: self.optionsButton.set_visible(False) return self.optionsValues.clear() options = self.getActiveOptions() self.optionsButton.set_visible(bool(options)) kind = self.kind() plugin = Glossary.plugins[name] if kind == "r": depends = plugin.readDepends elif kind == "w": depends = plugin.writeDepends else: raise RuntimeError(f"invalid {kind=}") uninstalled = checkDepends(depends) self.dependsButton.pkgNames = uninstalled self.dependsButton.set_visible(bool(uninstalled)) class InputFormatBox(FormatBox): dialogTitle = "Select Input Format" def __init__(self, **kwargs) -> None: FormatBox.__init__(self, readDesc, **kwargs) def kind(self): """Return 'r' or 'w'.""" return "r" def getActiveOptions(self): formatName = self.getActive() if not formatName: return None return list(Glossary.formatsReadOptions[formatName]) class OutputFormatBox(FormatBox): dialogTitle = "Select Output Format" def __init__(self, **kwargs) -> None: FormatBox.__init__(self, writeDesc, **kwargs) def kind(self): """Return 'r' or 'w'.""" return "w" def getActiveOptions(self): return list(Glossary.formatsWriteOptions[self.getActive()]) class GtkTextviewLogHandler(logging.Handler): def __init__(self, ui, treeview_dict) -> None: logging.Handler.__init__(self) self.ui = ui self.buffers = {} for levelNameCap in log.levelNamesCap[:-1]: levelName = levelNameCap.upper() textview = treeview_dict[levelName] buff = textview.get_buffer() tag = gtk.TextTag.new(levelName) buff.get_tag_table().add(tag) self.buffers[levelName] = buff def getTag(self, levelname): return self.buffers[levelname].get_tag_table().lookup(levelname) def setColor(self, levelname: str, rgba: gdk.RGBA) -> None: self.getTag(levelname).set_property("foreground-rgba", rgba) # foreground-gdk is deprecated since Gtk 3.4 def emit(self, record): msg = "" if record.getMessage(): msg = self.format(record) # msg = msg.replace("\x00", "") if record.exc_info: _type, value, tback = record.exc_info tback_text = "".join( traceback.format_exception(_type, value, tback), ) if msg: msg += "\n" msg += tback_text buff = self.buffers[record.levelname] buff.insert_with_tags_by_name( buff.get_end_iter(), msg + "\n", record.levelname, ) if record.levelno == logging.CRITICAL: self.ui.status(record.getMessage()) class GtkSingleTextviewLogHandler(GtkTextviewLogHandler): def __init__(self, ui, textview) -> None: GtkTextviewLogHandler.__init__( self, ui, { "CRITICAL": textview, "ERROR": textview, "WARNING": textview, "INFO": textview, "DEBUG": textview, "TRACE": textview, }, ) class BrowseButton(gtk.Button): def __init__( self, setFilePathFunc, label="Browse", actionSave=False, title="Select File", ) -> None: gtk.Button.__init__(self) self.set_label(label) self.set_image( gtk.Image.new_from_icon_name( "document-save" if actionSave else "document-open", gtk.IconSize.BUTTON, ), ) self.actionSave = actionSave self.setFilePathFunc = setFilePathFunc self.title = title self.connect("clicked", self.onClick) def onClick(self, _widget): fcd = gtk.FileChooserNative( transient_for=( self.get_root() if hasattr(self, "get_root") else self.get_toplevel() ), action=gtk.FileChooserAction.SAVE if self.actionSave else gtk.FileChooserAction.OPEN, title=self.title, ) fcd.connect("response", lambda _w, _e: fcd.hide()) fcd.connect( "file-activated", lambda _w: fcd.response(gtk.ResponseType.ACCEPT), ) if fcd.run() == gtk.ResponseType.ACCEPT: self.setFilePathFunc(fcd.get_filename()) fcd.destroy() sortKeyNameByDesc = {_sk.desc: _sk.name for _sk in namedSortKeyList} sortKeyNames = [_sk.name for _sk in namedSortKeyList] class SortOptionsBox(gtk.Box): def __init__(self, ui) -> None: gtk.Box.__init__(self, orientation=gtk.Orientation.VERTICAL) self.ui = ui ### hbox = gtk.HBox() sortCheck = gtk.CheckButton("Sort entries by") sortKeyCombo = gtk.ComboBoxText() for _sk in namedSortKeyList: sortKeyCombo.append_text(_sk.desc) sortKeyCombo.set_active(sortKeyNames.index(defaultSortKeyName)) sortKeyCombo.set_border_width(0) sortKeyCombo.set_sensitive(False) # sortKeyCombo.connect("changed", self.sortKeyComboChanged) self.sortCheck = sortCheck self.sortKeyCombo = sortKeyCombo sortCheck.connect("clicked", self.onSortCheckClicked) pack(hbox, sortCheck, 0, 0, padding=5) pack(hbox, sortKeyCombo, 0, 0, padding=5) pack(self, hbox, 0, 0, padding=5) ### hbox = self.encodingHBox = gtk.HBox() encodingCheck = self.encodingCheck = gtk.CheckButton(label="Sort Encoding") encodingEntry = self.encodingEntry = gtk.Entry() encodingEntry.set_text("utf-8") encodingEntry.set_width_chars(15) pack(hbox, gtk.Label(label=" ")) pack(hbox, encodingCheck, 0, 0) pack(hbox, encodingEntry, 0, 0, padding=5) pack(self, hbox, 0, 0, padding=5) ### # RadioButton in Gtk3 is very unstable, # I could not make set_group work at all! # encodingRadio.get_group() == [encodingRadio] # localeRadio.set_group(encodingRadio) says: # TypeError: Must be sequence, not RadioButton # localeRadio.set_group([encodingRadio]) causes a crash!! # but localeRadio.join_group(encodingRadio) works, # so does group= argument to RadioButton() # Note: RadioButton does not exist in Gtk 4.0, # you have to use CheckButton with its new set_group() method hbox = self.localeHBox = gtk.HBox() localeEntry = self.localeEntry = gtk.Entry() localeEntry.set_width_chars(15) pack(hbox, gtk.Label(label=" ")) pack(hbox, gtk.Label(label="Sort Locale"), 0, 0) pack(hbox, localeEntry, 0, 0, padding=5) pack(self, hbox, 0, 0, padding=5) ### self.show_all() def onSortCheckClicked(self, check): sort = check.get_active() self.sortKeyCombo.set_sensitive(sort) self.encodingHBox.set_sensitive(sort) self.localeHBox.set_sensitive(sort) def updateWidgets(self): convertOptions = self.ui.convertOptions sort = convertOptions.get("sort") self.sortCheck.set_active(sort) self.sortKeyCombo.set_sensitive(sort) self.encodingHBox.set_sensitive(sort) self.localeHBox.set_sensitive(sort) sortKeyName = convertOptions.get("sortKeyName") sortKeyName, _, localeName = sortKeyName.partition(":") if sortKeyName: self.sortKeyCombo.set_active(sortKeyNames.index(sortKeyName)) self.localeEntry.set_text(localeName) if "sortEncoding" in convertOptions: self.encodingCheck.set_active(True) self.encodingEntry.set_text(convertOptions["sortEncoding"]) def applyChanges(self): convertOptions = self.ui.convertOptions sort = self.sortCheck.get_active() if not sort: for param in ("sort", "sortKeyName", "sortEncoding"): if param in convertOptions: del convertOptions[param] return sortKeyDesc = self.sortKeyCombo.get_active_text() sortKeyName = sortKeyNameByDesc[sortKeyDesc] sortLocale = self.localeEntry.get_text() if sortLocale: sortKeyName = f"{sortKeyName}:{sortLocale}" convertOptions["sort"] = True convertOptions["sortKeyName"] = sortKeyName if self.encodingCheck.get_active(): convertOptions["sortEncoding"] = self.encodingEntry.get_text() class GeneralOptionsDialog(gtk.Dialog): def onDeleteEvent(self, _widget, _event): self.hide() return True def onResponse(self, _widget, _event): self.applyChanges() self.hide() return True def __init__(self, ui, **kwargs) -> None: gtk.Dialog.__init__( self, transient_for=ui, **kwargs, ) self.set_title("General Options") self.ui = ui ## self.resize(600, 500) self.connect("delete-event", self.onDeleteEvent) ## self.connect("response", self.onResponse) dialog_add_button( self, "gtk-ok", "_OK", gtk.ResponseType.OK, ) ## hpad = 10 vpad = 5 ## self.sortOptionsBox = SortOptionsBox(ui) pack(self.vbox, self.sortOptionsBox, 0, 0, padding=vpad) ## hbox = gtk.HBox() self.sqliteCheck = gtk.CheckButton(label="SQLite mode") pack(hbox, self.sqliteCheck, 0, 0, padding=hpad) pack(self.vbox, hbox, 0, 0, padding=vpad) ## self.configParams = OrderedDict( [ ("save_info_json", False), ("lower", False), ("skip_resources", False), ("rtl", False), ("enable_alts", True), ("cleanup", True), ("remove_html_all", True), ], ) self.configCheckButtons = {} configDefDict = UIBase.configDefDict for param in self.configParams: hbox = gtk.HBox() comment = configDefDict[param].comment comment = comment.split("\n")[0] checkButton = gtk.CheckButton( label=comment, ) self.configCheckButtons[param] = checkButton pack(hbox, checkButton, 0, 0, padding=hpad) pack(self.vbox, hbox, 0, 0, padding=vpad) ## self.updateWidgets() self.vbox.show_all() def getSQLite(self) -> bool: convertOptions = self.ui.convertOptions sqlite = convertOptions.get("sqlite") if sqlite is not None: return sqlite return self.ui.config.get("auto_sqlite", True) def updateWidgets(self): config = self.ui.config self.sortOptionsBox.updateWidgets() self.sqliteCheck.set_active(self.getSQLite()) for param, check in self.configCheckButtons.items(): default = self.configParams[param] check.set_active(config.get(param, default)) def applyChanges(self): # print("applyChanges") self.sortOptionsBox.applyChanges() convertOptions = self.ui.convertOptions config = self.ui.config convertOptions["sqlite"] = self.sqliteCheck.get_active() for param, check in self.configCheckButtons.items(): config[param] = check.get_active() class GeneralOptionsButton(gtk.Button): def __init__(self, ui) -> None: gtk.Button.__init__(self, label="General Options") self.ui = ui self.connect("clicked", self.onClick) self.dialog = None def onClick(self, _widget): if self.dialog is None: self.dialog = GeneralOptionsDialog(self.ui) self.dialog.present() class UI(gtk.Dialog, MyDialog, UIBase): def status(self, msg): # try: # _id = self.statusMsgDict[msg] # except KeyError: # _id = self.statusMsgDict[msg] = self.statusNewId # self.statusNewId += 1 _id = self.statusBar.get_context_id(msg) self.statusBar.push(_id, msg) def __init__( self, progressbar: bool = True, ) -> None: gtk.Dialog.__init__(self) UIBase.__init__(self) self.set_title("PyGlossary (Gtk3)") ### self.progressbarEnable = progressbar ##### screenSize = getWorkAreaSize() if screenSize: winSize = min(800, screenSize[0] - 50, screenSize[1] - 50) self.resize(winSize, winSize) # print(f"{screenSize = }") ##### self.connect("delete-event", self.onDeleteEvent) self.pages = [] # self.statusNewId = 0 # self.statusMsgDict = {}## message -> id ##### self.convertOptions = {} ##### self.styleProvider = gtk.CssProvider() gtk.StyleContext.add_provider_for_screen( gdk.Screen.get_default(), self.styleProvider, gtk.STYLE_PROVIDER_PRIORITY_APPLICATION, ) css = "check {min-width: 1.25em; min-height: 1.25em;}\n" self.styleProvider.load_from_data(css.encode("utf-8")) ##### self.assert_quit = False self.path = "" # ____________________ Tab 1 - Convert ____________________ # labelSizeGroup = gtk.SizeGroup(mode=gtk.SizeGroupMode.HORIZONTAL) buttonSizeGroup = gtk.SizeGroup(mode=gtk.SizeGroupMode.HORIZONTAL) #### vbox = VBox() vbox.label = _("Convert") vbox.icon = "" # "*.png" self.pages.append(vbox) ###### hbox = HBox(spacing=3) hbox.label = gtk.Label(label=_("Input File:")) pack(hbox, hbox.label) labelSizeGroup.add_widget(hbox.label) hbox.label.set_property("xalign", 0) self.convertInputEntry = gtk.Entry() pack(hbox, self.convertInputEntry, 1, 1) button = BrowseButton( self.convertInputEntry.set_text, label="Browse", actionSave=False, title="Select Input File", ) pack(hbox, button) buttonSizeGroup.add_widget(button) pack(vbox, hbox) ## self.convertInputEntry.connect( "changed", self.convertInputEntryChanged, ) ### hbox = HBox(spacing=3) hbox.label = gtk.Label(label=_("Input Format:")) pack(hbox, hbox.label) labelSizeGroup.add_widget(hbox.label) hbox.label.set_property("xalign", 0) self.convertInputFormatCombo = InputFormatBox(parent=self) buttonSizeGroup.add_widget(self.convertInputFormatCombo.optionsButton) pack(hbox, self.convertInputFormatCombo) pack(hbox, gtk.Label(), 1, 1) pack(hbox, self.convertInputFormatCombo.dependsButton) pack(hbox, self.convertInputFormatCombo.optionsButton) pack(vbox, hbox) ##### vbox.sep1 = gtk.Label(label="") vbox.sep1.show() pack(vbox, vbox.sep1) ##### hbox = HBox(spacing=3) hbox.label = gtk.Label(label=_("Output File:")) pack(hbox, hbox.label) labelSizeGroup.add_widget(hbox.label) hbox.label.set_property("xalign", 0) self.convertOutputEntry = gtk.Entry() pack(hbox, self.convertOutputEntry, 1, 1) button = BrowseButton( self.convertOutputEntry.set_text, label="Browse", actionSave=True, title="Select Output File", ) pack(hbox, button) buttonSizeGroup.add_widget(button) pack(vbox, hbox) ## self.convertOutputEntry.connect( "changed", self.convertOutputEntryChanged, ) ### hbox = HBox(spacing=3) hbox.label = gtk.Label(label=_("Output Format:")) pack(hbox, hbox.label) labelSizeGroup.add_widget(hbox.label) hbox.label.set_property("xalign", 0) self.convertOutputFormatCombo = OutputFormatBox(parent=self) buttonSizeGroup.add_widget(self.convertOutputFormatCombo.optionsButton) pack(hbox, self.convertOutputFormatCombo) pack(hbox, gtk.Label(), 1, 1) pack(hbox, self.convertOutputFormatCombo.dependsButton) pack(hbox, self.convertOutputFormatCombo.optionsButton) pack(vbox, hbox) ##### hbox = HBox(spacing=10) label = gtk.Label(label="") pack(hbox, label, 1, 1, 5) ## button = GeneralOptionsButton(self) button.set_size_request(300, 40) pack(hbox, button, 0, 0, 0) ## self.convertButton = gtk.Button() self.convertButton.set_label("Convert") self.convertButton.connect("clicked", self.convertClicked) self.convertButton.set_size_request(300, 40) pack(hbox, self.convertButton, 0, 0, 10) ## pack(vbox, hbox, 0, 0, 15) ##### self.convertConsoleTextview = textview = gtk.TextView() swin = gtk.ScrolledWindow() swin.set_policy(gtk.PolicyType.AUTOMATIC, gtk.PolicyType.AUTOMATIC) swin.set_border_width(0) swin.add(textview) pack(vbox, swin, 1, 1) # ____________________ Tab 2 - Reverse ____________________ # self.reverseStatus = "" #### labelSizeGroup = gtk.SizeGroup(mode=gtk.SizeGroupMode.HORIZONTAL) #### vbox = VBox() vbox.label = _("Reverse") vbox.icon = "" # "*.png" # self.pages.append(vbox) ###### hbox = HBox(spacing=3) hbox.label = gtk.Label(label=_("Input Format:")) pack(hbox, hbox.label) labelSizeGroup.add_widget(hbox.label) hbox.label.set_property("xalign", 0) self.reverseInputFormatCombo = InputFormatBox() pack(hbox, self.reverseInputFormatCombo) pack(vbox, hbox) ### hbox = HBox(spacing=3) hbox.label = gtk.Label(label=_("Input File:")) pack(hbox, hbox.label) labelSizeGroup.add_widget(hbox.label) hbox.label.set_property("xalign", 0) self.reverseInputEntry = gtk.Entry() pack(hbox, self.reverseInputEntry, 1, 1) button = BrowseButton( self.reverseInputEntry.set_text, label="Browse", actionSave=False, title="Select Input File", ) pack(hbox, button) pack(vbox, hbox) ## self.reverseInputEntry.connect( "changed", self.reverseInputEntryChanged, ) ##### vbox.sep1 = gtk.Label(label="") vbox.sep1.show() pack(vbox, vbox.sep1) ##### hbox = HBox(spacing=3) hbox.label = gtk.Label(label=_("Output Tabfile:")) pack(hbox, hbox.label) labelSizeGroup.add_widget(hbox.label) hbox.label.set_property("xalign", 0) self.reverseOutputEntry = gtk.Entry() pack(hbox, self.reverseOutputEntry, 1, 1) button = BrowseButton( self.reverseOutputEntry.set_text, label="Browse", actionSave=True, title="Select Output File", ) pack(hbox, button) pack(vbox, hbox) ## self.reverseOutputEntry.connect( "changed", self.reverseOutputEntryChanged, ) ##### hbox = HBox(spacing=3) label = gtk.Label(label="") pack(hbox, label, 1, 1, 5) ### self.reverseStartButton = gtk.Button() self.reverseStartButton.set_label(_("Start")) self.reverseStartButton.connect("clicked", self.reverseStartClicked) pack(hbox, self.reverseStartButton, 1, 1, 2) ### self.reversePauseButton = gtk.Button() self.reversePauseButton.set_label(_("Pause")) self.reversePauseButton.set_sensitive(False) self.reversePauseButton.connect("clicked", self.reversePauseClicked) pack(hbox, self.reversePauseButton, 1, 1, 2) ### self.reverseResumeButton = gtk.Button() self.reverseResumeButton.set_label(_("Resume")) self.reverseResumeButton.set_sensitive(False) self.reverseResumeButton.connect("clicked", self.reverseResumeClicked) pack(hbox, self.reverseResumeButton, 1, 1, 2) ### self.reverseStopButton = gtk.Button() self.reverseStopButton.set_label(_("Stop")) self.reverseStopButton.set_sensitive(False) self.reverseStopButton.connect("clicked", self.reverseStopClicked) pack(hbox, self.reverseStopButton, 1, 1, 2) ### pack(vbox, hbox, 0, 0, 5) ###### about = AboutWidget( logo=logo, header=f"PyGlossary\nVersion {getVersion()}", # about=summary, about=f'{aboutText}\n<a href="{core.homePage}">{core.homePage}</a>', authors="\n".join(authors), license_text=licenseText, ) about.label = _("About") about.icon = "" # "*.png" self.pages.append(about) ##### # ____________________________________________________________ # notebook = gtk.Notebook() self.notebook = notebook ######### for vbox in self.pages: label = gtk.Label(label=vbox.label) label.set_use_underline(True) vb = VBox(spacing=3) if vbox.icon: vbox.image = imageFromFile(vbox.icon) pack(vb, vbox.image) pack(vb, label) vb.show_all() notebook.append_page(vbox, vb) try: notebook.set_tab_reorderable(vbox, True) except AttributeError: pass ####################### pack(self.vbox, notebook, 1, 1) # for i in ui.pagesOrder: # try: # j = pagesOrder[i] # except IndexError: # continue # notebook.reorder_child(self.pages[i], j) # ____________________________________________________________ # handler = GtkSingleTextviewLogHandler(self, textview) log.addHandler(handler) ### textview.override_background_color( gtk.StateFlags.NORMAL, gdk.RGBA(0, 0, 0, 1), ) ### handler.setColor("CRITICAL", rgba_parse("red")) handler.setColor("ERROR", rgba_parse("red")) handler.setColor("WARNING", rgba_parse("yellow")) handler.setColor("INFO", rgba_parse("white")) handler.setColor("DEBUG", rgba_parse("white")) handler.setColor("TRACE", rgba_parse("white")) ### textview.get_buffer().set_text("Output & Error Console:\n") textview.set_editable(False) # ____________________________________________________________ # self.progressTitle = "" self.progressBar = pbar = gtk.ProgressBar() pbar.set_fraction(0) # pbar.set_text(_("Progress Bar")) # pbar.get_style_context() # pbar.set_property("height-request", 20) pack(self.vbox, pbar, 0, 0) ############ hbox = HBox(spacing=5) clearButton = gtk.Button( use_stock=gtk.STOCK_CLEAR, always_show_image=True, label=_("Clear"), ) clearButton.show_all() # image = gtk.Image() # image.set_from_stock(gtk.STOCK_CLEAR, gtk.IconSize.MENU) # clearButton.add(image) clearButton.set_border_width(0) clearButton.connect("clicked", self.consoleClearButtonClicked) set_tooltip(clearButton, "Clear Console") pack(hbox, clearButton, 0, 0) #### # hbox.sepLabel1 = gtk.Label(label="") # pack(hbox, hbox.sepLabel1, 1, 1) ###### hbox.verbosityLabel = gtk.Label(label=_("Verbosity:")) pack(hbox, hbox.verbosityLabel, 0, 0) ## self.verbosityCombo = combo = gtk.ComboBoxText() for level, levelName in enumerate(log.levelNamesCap): combo.append_text(f"{level} - {_(levelName)}") combo.set_active(log.getVerbosity()) combo.set_border_width(0) combo.connect("changed", self.verbosityComboChanged) pack(hbox, combo, 0, 0) #### # hbox.sepLabel2 = gtk.Label(label="") # pack(hbox, hbox.sepLabel2, 1, 1) #### self.statusBar = gtk.Statusbar() pack(hbox, self.statusBar, 1, 1) #### hbox.resizeButton = ResizeButton(self) pack(hbox, hbox.resizeButton, 0, 0) ###### pack(self.vbox, hbox, 0, 0) # ____________________________________________________________ # self.vbox.show_all() notebook.set_current_page(0) # Convert tab self.convertInputFormatCombo.dependsButton.hide() self.convertOutputFormatCombo.dependsButton.hide() self.convertInputFormatCombo.optionsButton.hide() self.convertOutputFormatCombo.optionsButton.hide() ######## self.status("Select input file") def run( # noqa: PLR0913 self, inputFilename: str = "", outputFilename: str = "", inputFormat: str = "", outputFormat: str = "", reverse: bool = False, config: "dict | None" = None, readOptions: "dict | None" = None, writeOptions: "dict | None" = None, convertOptions: "dict | None" = None, glossarySetAttrs: "dict | None" = None, ): if glossarySetAttrs is None: glossarySetAttrs = {} self.config = config if inputFilename: self.convertInputEntry.set_text(abspath(inputFilename)) if outputFilename: self.convertOutputEntry.set_text(abspath(outputFilename)) if inputFormat: self.convertInputFormatCombo.setActive(inputFormat) if outputFormat: self.convertOutputFormatCombo.setActive(outputFormat) if reverse: log.error("Gtk interface does not support Reverse feature") if readOptions: self.convertInputFormatCombo.setOptionsValues(readOptions) if writeOptions: self.convertOutputFormatCombo.setOptionsValues(writeOptions) self.convertOptions = convertOptions if convertOptions: log.debug(f"Using {convertOptions=}") self._glossarySetAttrs = glossarySetAttrs self.convertInputEntry.grab_focus() gtk.Dialog.present(self) gtk.main() def onDeleteEvent(self, _widget, _event): self.destroy() # gtk.main_quit() # if called while converting, main_quit does not exit program, # it keeps printing warnings, # and makes you close the terminal or force kill the process sys.exit(0) def consoleClearButtonClicked(self, _widget=None): self.convertConsoleTextview.get_buffer().set_text("") def verbosityComboChanged(self, _widget=None): verbosity = self.verbosityCombo.get_active() # or int(self.verbosityCombo.get_active_text()) log.setVerbosity(verbosity) def convertClicked(self, _widget=None): inPath = self.convertInputEntry.get_text() if not inPath: log.critical("Input file path is empty!") return None inFormat = self.convertInputFormatCombo.getActive() outPath = self.convertOutputEntry.get_text() if not outPath: log.critical("Output file path is empty!") return None outFormat = self.convertOutputFormatCombo.getActive() while gtk.events_pending(): gtk.main_iteration_do(False) self.convertButton.set_sensitive(False) self.progressTitle = "Converting" readOptions = self.convertInputFormatCombo.optionsValues writeOptions = self.convertOutputFormatCombo.optionsValues glos = Glossary(ui=self) glos.config = self.config glos.progressbar = self.progressbarEnable for attr, value in self._glossarySetAttrs.items(): setattr(glos, attr, value) log.debug(f"readOptions: {readOptions}") log.debug(f"writeOptions: {writeOptions}") log.debug(f"convertOptions: {self.convertOptions}") log.debug(f"config: {self.config}") try: finalOutputFile = glos.convert( ConvertArgs( inPath, inputFormat=inFormat, outputFilename=outPath, outputFormat=outFormat, readOptions=readOptions, writeOptions=writeOptions, **self.convertOptions, ), ) if finalOutputFile: self.status("Convert finished") return bool(finalOutputFile) except Error as e: log.critical(str(e)) glos.cleanup() return False finally: self.convertButton.set_sensitive(True) self.assert_quit = False self.progressTitle = "" return True def convertInputEntryChanged(self, _widget=None): inPath = self.convertInputEntry.get_text() inFormat = self.convertInputFormatCombo.getActive() if inPath.startswith("file://"): inPath = urlToPath(inPath) self.convertInputEntry.set_text(inPath) if self.config["ui_autoSetFormat"] and not inFormat: try: inputArgs = Glossary.detectInputFormat(inPath) except Error: pass else: self.convertInputFormatCombo.setActive(inputArgs.formatName) if not isfile(inPath): return self.status("Select output file") def convertOutputEntryChanged(self, _widget=None): outPath = self.convertOutputEntry.get_text() outFormat = self.convertOutputFormatCombo.getActive() if not outPath: return if outPath.startswith("file://"): outPath = urlToPath(outPath) self.convertOutputEntry.set_text(outPath) if self.config["ui_autoSetFormat"] and not outFormat: try: outputArgs = Glossary.detectOutputFormat( filename=outPath, inputFilename=self.convertInputEntry.get_text(), ) except Error: pass else: outFormat = outputArgs.formatName self.convertOutputFormatCombo.setActive(outFormat) if outFormat: self.status('Press "Convert"') else: self.status("Select output format") def reverseLoad(self): pass def reverseStartLoop(self): pass def reverseStart(self): if not self.reverseLoad(): return ### self.reverseStatus = "doing" self.reverseStartLoop() ### self.reverseStartButton.set_sensitive(False) self.reversePauseButton.set_sensitive(True) self.reverseResumeButton.set_sensitive(False) self.reverseStopButton.set_sensitive(True) def reverseStartClicked(self, _widget=None): self.waitingDo(self.reverseStart) def reversePause(self): self.reverseStatus = "pause" ### self.reverseStartButton.set_sensitive(False) self.reversePauseButton.set_sensitive(False) self.reverseResumeButton.set_sensitive(True) self.reverseStopButton.set_sensitive(True) def reversePauseClicked(self, _widget=None): self.waitingDo(self.reversePause) def reverseResume(self): self.reverseStatus = "doing" ### self.reverseStartButton.set_sensitive(False) self.reversePauseButton.set_sensitive(True) self.reverseResumeButton.set_sensitive(False) self.reverseStopButton.set_sensitive(True) def reverseResumeClicked(self, _widget=None): self.waitingDo(self.reverseResume) def reverseStop(self): self.reverseStatus = "stop" ### self.reverseStartButton.set_sensitive(True) self.reversePauseButton.set_sensitive(False) self.reverseResumeButton.set_sensitive(False) self.reverseStopButton.set_sensitive(False) def reverseStopClicked(self, _widget=None): self.waitingDo(self.reverseStop) def reverseInputEntryChanged(self, _widget=None): inPath = self.reverseInputEntry.get_text() if inPath.startswith("file://"): inPath = urlToPath(inPath) self.reverseInputEntry.set_text(inPath) if ( self.config["ui_autoSetFormat"] and not self.reverseInputFormatCombo.getActive() ): try: inputArgs = Glossary.detectInputFormat(inPath) except Error: pass else: inFormat = inputArgs[1] self.reverseInputFormatCombo.setActive(inFormat) def reverseOutputEntryChanged(self, widget=None): pass def progressInit(self, title): self.progressTitle = title def progress(self, ratio, text=None): if not text: text = "%" + str(int(ratio * 100)) text += " - " + self.progressTitle self.progressBar.set_fraction(ratio) # self.progressBar.set_text(text) # not working self.status(text) while gtk.events_pending(): gtk.main_iteration_do(False)
44,781
Python
.py
1,461
27.370979
83
0.714597
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,764
runner.py
ilius_pyglossary/pyglossary/ui/runner.py
from __future__ import annotations import argparse import logging import os import sys from typing import TYPE_CHECKING from pyglossary import core from pyglossary.glossary_v2 import Error from pyglossary.ui.base import UIBase if TYPE_CHECKING: from collections.abc import Callable ui_list = ["gtk", "tk"] if os.sep == "\\": ui_list = ["tk", "gtk"] log = None def canRunGUI() -> bool: if core.sysName == "linux": return bool(os.getenv("DISPLAY")) if core.sysName == "darwin": try: import tkinter # noqa: F401 except ModuleNotFoundError: return False return True def shouldUseCMD(args: "argparse.Namespace") -> bool: if not canRunGUI(): return True if args.interactive: return True return bool(args.inputFilename and args.outputFilename) def base_ui_run( # noqa: PLR0913 inputFilename: str = "", outputFilename: str = "", inputFormat: str = "", outputFormat: str = "", reverse: bool = False, config: "dict | None" = None, readOptions: "dict | None" = None, writeOptions: "dict | None" = None, convertOptions: "dict | None" = None, glossarySetAttrs: "dict | None" = None, ) -> bool: from pyglossary.glossary_v2 import ConvertArgs, Glossary if reverse: log.error("--reverse does not work with --ui=none") return False ui = UIBase() ui.loadConfig(**config) glos = Glossary(ui=ui) glos.config = ui.config if glossarySetAttrs: for attr, value in glossarySetAttrs.items(): setattr(glos, attr, value) try: glos.convert( ConvertArgs( inputFilename=inputFilename, outputFilename=outputFilename, inputFormat=inputFormat, outputFormat=outputFormat, readOptions=readOptions, writeOptions=writeOptions, **convertOptions, ), ) except Error as e: log.critical(str(e)) glos.cleanup() return False return True def getRunner( args: "argparse.Namespace", ui_type: str, logArg: logging.Logger, ) -> Callable | None: global log log = logArg if ui_type == "none": return base_ui_run if ui_type == "auto" and shouldUseCMD(args): ui_type = "cmd" uiArgs = { "progressbar": args.progressbar is not False, } if ui_type == "cmd": if args.interactive: from pyglossary.ui.ui_cmd_interactive import UI elif args.inputFilename and args.outputFilename: from pyglossary.ui.ui_cmd import UI elif not args.no_interactive: from pyglossary.ui.ui_cmd_interactive import UI else: log.error("no input file given, try --help") return None return UI(**uiArgs).run if ui_type == "auto": for ui_type2 in ui_list: try: ui_module = __import__( f"pyglossary.ui.ui_{ui_type2}", fromlist=f"ui_{ui_type2}", ) except ImportError as e: # noqa: PERF203 log.error(str(e)) else: return ui_module.UI(**uiArgs).run log.error( "no user interface module found! " f'try "{sys.argv[0]} -h" to see command line usage', ) return None ui_module = __import__( f"pyglossary.ui.ui_{ui_type}", fromlist=f"ui_{ui_type}", ) return ui_module.UI(**uiArgs).run
3,007
Python
.py
116
23.043103
57
0.713389
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,765
ui_cmd.py
ilius_pyglossary/pyglossary/ui/ui_cmd.py
# -*- coding: utf-8 -*- # mypy: ignore-errors # ui_cmd.py # # Copyright © 2008-2021 Saeed Rasooli <saeed.gnu@gmail.com> (ilius) # This file is part of PyGlossary project, https://github.com/ilius/pyglossary # # This program is a free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program. Or on Debian systems, from /usr/share/common-licenses/GPL # If not, see <http://www.gnu.org/licenses/gpl.txt>. from __future__ import annotations import os import sys from collections.abc import Mapping from os.path import join from typing import TYPE_CHECKING, Any from pyglossary.core import dataDir, log from pyglossary.glossary_v2 import ConvertArgs, Error, Glossary from .base import UIBase, fread from .wcwidth import wcswidth if TYPE_CHECKING: import logging __all__ = ["COMMAND", "UI", "parseFormatOptionsStr", "printHelp"] def wc_ljust(text: str, length: int, padding: str = " ") -> str: return text + padding * max(0, (length - wcswidth(text))) if os.sep == "\\": # Operating system is Windows startBold = "" startUnderline = "" endFormat = "" else: startBold = "\x1b[1m" # Start Bold # len=4 startUnderline = "\x1b[4m" # Start Underline # len=4 endFormat = "\x1b[0;0;0m" # End Format # len=8 # redOnGray = "\x1b[0;1;31;47m" COMMAND = "pyglossary" def getColWidth(subject: str, strings: list[str]) -> int: return max(len(x) for x in [subject] + strings) def getFormatsTable(names: list[str], header: str) -> str: descriptions = [Glossary.plugins[name].description for name in names] extensions = [" ".join(Glossary.plugins[name].extensions) for name in names] nameWidth = getColWidth("Name", names) descriptionWidth = getColWidth("Description", descriptions) extensionsWidth = getColWidth("Extensions", extensions) lines = [ "\n", startBold + header + endFormat, " | ".join( [ "Name".center(nameWidth), "Description".center(descriptionWidth), "Extensions".center(extensionsWidth), ], ), "-+-".join( [ "-" * nameWidth, "-" * descriptionWidth, "-" * extensionsWidth, ], ), ] for index, name in enumerate(names): lines.append( " | ".join( [ name.ljust(nameWidth), descriptions[index].ljust(descriptionWidth), extensions[index].ljust(extensionsWidth), ], ), ) return "\n".join(lines) def printHelp() -> None: import string text = fread(join(dataDir, "help")) text = ( text.replace("<b>", startBold) .replace("<u>", startUnderline) .replace("</b>", endFormat) .replace("</u>", endFormat) ) text = string.Template(text).substitute( CMD=COMMAND, ) text += getFormatsTable(Glossary.readFormats, "Supported input formats:") text += getFormatsTable(Glossary.writeFormats, "Supported output formats:") print(text) def parseFormatOptionsStr(st: str) -> dict[str, Any] | None: """Prints error and returns None if failed to parse one option.""" st = st.strip() if not st: return {} opt = {} parts = st.split(";") for part in parts: if not part: continue eq = part.find("=") if eq < 1: log.critical(f"bad option syntax: {part!r}") return None key = part[:eq].strip() if not key: log.critical(f"bad option syntax: {part!r}") return None value = part[eq + 1 :].strip() opt[key] = value return opt class NullObj: def __getattr__(self, attr: str) -> NullObj: return self def __setattr__(self, attr: str, value: Any) -> None: pass def __setitem__(self, key: str, value: Any) -> None: pass def __call__( self, *args: tuple[Any], **kwargs: Mapping[Any], ) -> None: pass class UI(UIBase): def __init__( self, progressbar: bool = True, ) -> None: UIBase.__init__(self) # log.debug(self.config) self.pbar = NullObj() self._toPause = False self._resetLogFormatter = None self._progressbar = progressbar def onSigInt( self, *_args: tuple[Any], ) -> None: log.info("") if self._toPause: log.info("Operation Canceled") sys.exit(0) else: self._toPause = True log.info("Please wait...") def setText(self, text: str) -> None: self.pbar.widgets[0] = text def fixLogger(self) -> None: for h in log.handlers: if h.name == "std": self.fixLogHandler(h) return def fillMessage(self, msg: str) -> str: term_width = self.pbar.term_width if term_width is None: # FIXME: why? return msg return "\r" + wc_ljust(msg, term_width) def fixLogHandler(self, h: "logging.Handler") -> None: def reset() -> None: h.formatter.fill = None self._resetLogFormatter = reset h.formatter.fill = self.fillMessage def progressInit(self, title: str) -> None: try: from .pbar_tqdm import createProgressBar except ModuleNotFoundError: from .pbar_legacy import createProgressBar self.pbar = createProgressBar(title) self.fixLogger() def progress( self, ratio: float, text: str = "", # noqa: ARG002 ) -> None: self.pbar.update(ratio) def progressEnd(self) -> None: self.pbar.finish() if self._resetLogFormatter: self._resetLogFormatter() def reverseLoop( self, *_args: tuple[Any], **kwargs: Mapping[Any], ) -> None: from pyglossary.reverse import reverseGlossary reverseKwArgs = {} for key in ( "words", "matchWord", "showRel", "includeDefs", "reportStep", "saveStep", "maxNum", "minRel", "minWordLen", ): try: reverseKwArgs[key] = self.config["reverse_" + key] except KeyError: pass reverseKwArgs.update(kwargs) if not self._toPause: log.info("Reversing glossary... (Press Ctrl+C to pause/stop)") for _ in reverseGlossary(self.glos, **reverseKwArgs): if self._toPause: log.info( "Reverse is paused. Press Enter to continue, and Ctrl+C to exit", ) input() self._toPause = False # PLR0912 Too many branches (19 > 12) def run( # noqa: PLR0912, PLR0913 self, inputFilename: str = "", outputFilename: str = "", inputFormat: str = "", outputFormat: str = "", reverse: bool = False, config: "dict | None" = None, readOptions: "dict | None" = None, writeOptions: "dict | None" = None, convertOptions: "dict | None" = None, glossarySetAttrs: "dict | None" = None, ) -> bool: if config is None: config = {} if readOptions is None: readOptions = {} if writeOptions is None: writeOptions = {} if convertOptions is None: convertOptions = {} if glossarySetAttrs is None: glossarySetAttrs = {} self.config = config if inputFormat: # noqa: SIM102 # inputFormat = inputFormat.capitalize() if inputFormat not in Glossary.readFormats: log.error(f"invalid read format {inputFormat}") if outputFormat: # noqa: SIM102 # outputFormat = outputFormat.capitalize() if outputFormat not in Glossary.writeFormats: log.error(f"invalid write format {outputFormat}") log.error(f"try: {COMMAND} --help") return False if not outputFilename: if reverse: pass elif outputFormat: try: ext = Glossary.plugins[outputFormat].extensions[0] except (KeyError, IndexError): log.error(f"invalid write format {outputFormat}") log.error(f"try: {COMMAND} --help") return False outputFilename = os.path.splitext(inputFilename)[0] + ext else: log.error("neither output file nor output format is given") log.error(f"try: {COMMAND} --help") return False glos = self.glos = Glossary(ui=self) glos.config = self.config glos.progressbar = self._progressbar for attr, value in glossarySetAttrs.items(): setattr(glos, attr, value) if reverse: import signal signal.signal(signal.SIGINT, self.onSigInt) # good place? FIXME readOptions["direct"] = True if not glos.read( inputFilename, format=inputFormat, **readOptions, ): log.error("reading input file was failed!") return False self.setText("Reversing: ") self.pbar.update_step = 0.1 self.reverseLoop(savePath=outputFilename) return True try: finalOutputFile = self.glos.convert( ConvertArgs( inputFilename, inputFormat=inputFormat, outputFilename=outputFilename, outputFormat=outputFormat, readOptions=readOptions, writeOptions=writeOptions, **convertOptions, ), ) except Error as e: log.critical(str(e)) glos.cleanup() return False return bool(finalOutputFile)
8,794
Python
.py
307
25.368078
78
0.695827
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,766
ui_tk.py
ilius_pyglossary/pyglossary/ui/ui_tk.py
# -*- coding: utf-8 -*- # mypy: ignore-errors # ui_tk.py # # Copyright © 2009-2021 Saeed Rasooli <saeed.gnu@gmail.com> (ilius) # # This program is a free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # You can get a copy of GNU General Public License along this program # But you can always get it from http://www.gnu.org/licenses/gpl.txt # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. from __future__ import annotations import logging import os import tkinter as tk import traceback from collections.abc import Callable from os.path import abspath, isfile, join, splitext from tkinter import filedialog, tix, ttk from tkinter import font as tkFont from typing import Any, Literal from pyglossary import core from pyglossary.core import confDir, homeDir from pyglossary.glossary_v2 import ConvertArgs, Error, Glossary from pyglossary.text_utils import urlToPath from .base import ( UIBase, aboutText, authors, licenseText, logo, ) from .version import getVersion log = logging.getLogger("pyglossary") pluginByDesc = {plugin.description: plugin for plugin in Glossary.plugins.values()} readDesc = [ plugin.description for plugin in Glossary.plugins.values() if plugin.canRead ] writeDesc = [ plugin.description for plugin in Glossary.plugins.values() if plugin.canWrite ] def set_window_icon(window): window.iconphoto( True, tk.PhotoImage(file=logo), ) def decodeGeometry(gs): """ Example for gs: "253x252+30+684" returns (x, y, w, h). """ p = gs.split("+") w, h = p[0].split("x") return (int(p[1]), int(p[2]), int(w), int(h)) def encodeGeometry(x, y, w, h): return f"{w}x{h}+{x}+{y}" def encodeLocation(x, y): return f"+{x}+{y}" def centerWindow(win): """ Centers a tkinter window :param win: the root or Toplevel window to center. """ win.update_idletasks() width = win.winfo_width() frm_width = win.winfo_rootx() - win.winfo_x() win_width = width + 2 * frm_width height = win.winfo_height() titlebar_height = win.winfo_rooty() - win.winfo_y() win_height = height + titlebar_height + frm_width x = win.winfo_screenwidth() // 2 - win_width // 2 y = win.winfo_screenheight() // 2 - win_height // 2 win.geometry(encodeGeometry(x, y, width, height)) win.deiconify() def newButton(*args, **kwargs): button = tk.Button(*args, **kwargs) def onEnter(_event): button.invoke() button.bind("<Return>", onEnter) button.bind("<KP_Enter>", onEnter) return button def newTTKButton(*args, **kwargs): button = ttk.Button(*args, **kwargs) def onEnter(_event): button.invoke() button.bind("<Return>", onEnter) button.bind("<KP_Enter>", onEnter) return button def newLabelWithImage(parent, file=""): image = tk.PhotoImage(file=file) label = tk.Label(parent, image=image) label.image = image # keep a reference! return label def newReadOnlyText( parent, text="", borderwidth=10, font=None, ): height = len(text.strip().split("\n")) widget = tk.Text( parent, height=height, borderwidth=borderwidth, font=font, ) widget.insert(1.0, text) widget.pack() # widget.bind("<Key>", lambda e: break) widget.configure(state="disabled") # if tkinter is 8.5 or above you'll want the selection background # to appear like it does when the widget is activated # comment this out for older versions of Tkinter widget.configure( inactiveselectbackground=widget.cget("selectbackground"), bg=parent.cget("bg"), relief="flat", ) return widget class TkTextLogHandler(logging.Handler): def __init__(self, tktext) -> None: logging.Handler.__init__(self) ##### tktext.tag_config("CRITICAL", foreground="#ff0000") tktext.tag_config("ERROR", foreground="#ff0000") tktext.tag_config("WARNING", foreground="#ffff00") tktext.tag_config("INFO", foreground="#00ff00") tktext.tag_config("DEBUG", foreground="#ffffff") tktext.tag_config("TRACE", foreground="#ffffff") ### self.tktext = tktext def emit(self, record): msg = "" if record.getMessage(): msg = self.format(record) ### if record.exc_info: _type, value, tback = record.exc_info tback_text = "".join( traceback.format_exception(_type, value, tback), ) if msg: msg += "\n" msg += tback_text ### self.tktext.insert( "end", msg + "\n", record.levelname, ) # Monkey-patch Tkinter # http://stackoverflow.com/questions/5191830/python-exception-logging def CallWrapper__call__(self, *args): """Apply first function SUBST to arguments, than FUNC.""" if self.subst: args = self.subst(*args) try: return self.func(*args) except Exception: log.exception("Exception in Tkinter callback:") tk.CallWrapper.__call__ = CallWrapper__call__ class ProgressBar(tix.Frame): """ Comes from John Grayson's book "Python and Tkinter programming" Edited by Saeed Rasooli. """ def __init__( # noqa: PLR0913 self, rootWin=None, orientation="horizontal", min_=0, max_=100, width=100, height=18, appearance="sunken", fillColor="blue", background="gray", labelColor="yellow", labelFont="Verdana", labelFormat="%d%%", value=0, bd=2, ) -> None: # preserve various values self.rootWin = rootWin self.orientation = orientation self.min = min_ self.max = max_ self.width = width self.height = height self.fillColor = fillColor self.labelFont = labelFont self.labelColor = labelColor self.background = background self.labelFormat = labelFormat self.value = value tix.Frame.__init__(self, rootWin, relief=appearance, bd=bd) self.canvas = tix.Canvas( self, height=height, width=width, bd=0, highlightthickness=0, background=background, ) self.scale = self.canvas.create_rectangle( 0, 0, width, height, fill=fillColor, ) self.label = self.canvas.create_text( width / 2, height / 2, text="", anchor="c", fill=labelColor, font=self.labelFont, ) self.update() self.bind("<Configure>", self.update) self.canvas.pack(side="top", fill="x", expand="no") def updateProgress(self, value, _max=None, text=""): if _max: self.max = _max self.value = value self.update(None, text) def update(self, event=None, labelText=""): # noqa: ARG002 # Trim the values to be between min and max value = self.value value = min(value, self.max) value = max(value, self.min) # Adjust the rectangle width = int(self.winfo_width()) # width = self.width ratio = float(value) / self.max if self.orientation == "horizontal": self.canvas.coords( self.scale, 0, 0, width * ratio, self.height, ) else: self.canvas.coords( self.scale, 0, self.height * (1 - ratio), width, self.height, ) # Now update the colors self.canvas.itemconfig(self.scale, fill=self.fillColor) self.canvas.itemconfig(self.label, fill=self.labelColor) # And update the label if not labelText: labelText = self.labelFormat % int(ratio * 100) self.canvas.itemconfig(self.label, text=labelText) # FIXME: resizing window causes problem in progressbar # self.canvas.move(self.label, width/2, self.height/2) # self.canvas.scale(self.label, 0, 0, float(width)/self.width, 1) self.canvas.update_idletasks() class FormatDialog(tix.Toplevel): def __init__( # noqa: PLR0913 self, descList: list[str], title: str, onOk: Callable, button: FormatButton, activeDesc: str = "", ) -> None: tix.Toplevel.__init__(self) # bg="#0f0" does not work self.descList = descList self.items = self.descList self.onOk = onOk self.activeDesc = activeDesc self.lastSearch = None self.resizable(width=True, height=True) if title: self.title(title) set_window_icon(self) self.bind("<Escape>", lambda _e: self.destroy()) px, py, pw, ph = decodeGeometry(button.winfo_toplevel().geometry()) width = 400 height = 400 self.geometry( encodeGeometry( px + pw // 2 - width // 2, py + ph // 2 - height // 2, width, height, ), ) entryBox = tk.Frame(master=self) label = tk.Label(master=entryBox, text="Search: ") label.pack(side="left") entry = self.entry = tk.Entry(master=entryBox) entry.pack(fill="x", expand=True, side="left") entryBox.pack(fill="x", padx=5, pady=5) entry.bind("<KeyRelease>", self.onEntryKeyRelease) entry.focus() treevBox = tk.Frame(master=self) treev = self.treev = ttk.Treeview( master=treevBox, columns=["Description"], show="", ) treev.bind("<Double-1>", self.onTreeDoubleClick) treev.pack( side="left", fill="both", expand=True, ) vsb = tk.Scrollbar( master=treevBox, orient="vertical", command=treev.yview, ) vsb.pack(side="right", fill="y") treevBox.pack( fill="both", expand=True, padx=5, pady=5, ) treev.configure(yscrollcommand=vsb.set) self.updateTree() buttonBox = tix.Frame(master=self) cancelButton = newButton( buttonBox, text="Cancel", command=self.cancelClicked, ) cancelButton.pack(side="right") okButton = newButton( buttonBox, text=" OK ", command=self.okClicked, # bg="#ff0000", # activebackground="#ff5050", ) okButton.pack(side="right") buttonBox.pack(fill="x") self.bind("<Return>", self.onReturnPress) self.bind("<KP_Enter>", self.onReturnPress) self.bind("<Down>", self.onDownPress) self.bind("<Up>", self.onUpPress) # self.bind("<KeyPress>", self.onKeyPress) def setActiveRow(self, desc): self.treev.selection_set(desc) self.treev.see(desc) def updateTree(self): treev = self.treev current = treev.get_children() if current: treev.delete(*current) for desc in self.items: treev.insert("", "end", values=[desc], iid=desc) # iid should be rowId if self.activeDesc in self.items: self.setActiveRow(self.activeDesc) def onEntryKeyRelease(self, _event): text = self.entry.get().strip() if text == self.lastSearch: return if not text: self.items = self.descList self.updateTree() self.lastSearch = text return text = text.lower() descList = self.descList items1 = [] items2 = [] for desc in descList: if desc.lower().startswith(text): items1.append(desc) elif text in desc.lower(): items2.append(desc) self.items = items1 + items2 self.updateTree() self.lastSearch = text def onTreeDoubleClick(self, _event): self.okClicked() def cancelClicked(self): self.destroy() def onReturnPress(self, _event): self.okClicked() def onDownPress(self, _event): treev = self.treev selection = treev.selection() if selection: nextDesc = treev.next(selection[0]) if nextDesc: self.setActiveRow(nextDesc) elif self.items: self.setActiveRow(self.items[0]) treev.focus() def onUpPress(self, _event): treev = self.treev treev.focus() selection = treev.selection() if not selection: if self.items: self.setActiveRow(self.items[0]) return nextDesc = treev.prev(selection[0]) if nextDesc: self.setActiveRow(nextDesc) def onKeyPress(self, event): print(f"FormatDialog: onKeyPress: {event}") def okClicked(self): treev = self.treev selectedList = treev.selection() desc = selectedList[0] if selectedList else "" self.onOk(desc) self.destroy() class FormatButton(tk.Button): noneLabel = "[Select Format]" def __init__( self, descList: list[str], dialogTitle: str, onChange: Callable, master=None, ) -> None: self.var = tk.StringVar() self.var.set(self.noneLabel) tk.Button.__init__( self, master=master, textvariable=self.var, command=self.onClick, ) self.descList = descList self.dialogTitle = dialogTitle self._onChange = onChange self.activeDesc = "" self.bind("<Return>", self.onEnter) self.bind("<KP_Enter>", self.onEnter) def onEnter(self, _event=None): self.invoke() def onChange(self, desc): self.setValue(desc) self._onChange(desc) def get(self): return self.activeDesc def setValue(self, desc): if desc: self.var.set(desc) else: self.var.set(self.noneLabel) self.activeDesc = desc def onClick(self): dialog = FormatDialog( descList=self.descList, title=self.dialogTitle, onOk=self.onChange, button=self, activeDesc=self.activeDesc, ) dialog.focus() class FormatOptionsDialog(tix.Toplevel): commentLen = 60 kindFormatsOptions = { "Read": Glossary.formatsReadOptions, "Write": Glossary.formatsWriteOptions, } def __init__( self, format, kind, values, master=None, # noqa: ARG002 ) -> None: tix.Toplevel.__init__(self) # bg="#0f0" does not work self.resizable(width=True, height=True) self.title(kind + " Options") set_window_icon(self) self.bind("<Escape>", lambda _e: self.destroy()) self.menu = None self.format = format self.kind = kind self.values = values self.options = list(self.kindFormatsOptions[kind][format]) self.optionsProp = Glossary.plugins[format].optionsProp self.createOptionsList() buttonBox = tix.Frame(self) okButton = newButton( buttonBox, text=" OK ", command=self.okClicked, # bg="#ff0000", # activebackground="#ff5050", ) okButton.pack(side="right") buttonBox.pack(fill="x") def createOptionsList(self): values = self.values self.valueCol = "#3" cols = [ "Enable", # bool "Name", # str "Value", # str "Comment", # str ] treev = self.treev = ttk.Treeview( master=self, columns=cols, show="headings", ) for col in cols: treev.heading( col, text=col, # command=lambda c=col: sortby(treev, c, 0), ) # adjust the column's width to the header string treev.column( col, width=tkFont.Font().measure(col.title()), ) ### treev.bind( "<Button-1>", # "<<TreeviewSelect>>", # event.x and event.y are zero self.treeClicked, ) treev.pack(fill="x", expand=True) ### for optName in self.options: prop = self.optionsProp[optName] comment = prop.longComment if len(comment) > self.commentLen: comment = comment[: self.commentLen] + "..." row = [ int(optName in values), optName, str(values.get(optName, "")), comment, ] treev.insert("", "end", values=row, iid=optName) # iid should be rowId # adjust column's width if necessary to fit each value for col_i, valueTmp in enumerate(row): value = str(valueTmp) if col_i == 3: value = value.zfill(20) # to reserve window width, because it's hard to resize it later col_w = tkFont.Font().measure(value) if treev.column(cols[col_i], width=None) < col_w: treev.column(cols[col_i], width=col_w) def valueMenuItemCustomSelected( self, treev, format: str, optName: str, menu=None, ): if menu: menu.destroy() self.menu = None value = treev.set(optName, self.valueCol) dialog = tix.Toplevel(master=treev) # bg="#0f0" does not work dialog.resizable(width=True, height=True) dialog.title(optName) set_window_icon(dialog) dialog.bind("<Escape>", lambda _e: dialog.destroy()) px, py, pw, ph = decodeGeometry(treev.winfo_toplevel().geometry()) width = 300 height = 100 dialog.geometry( encodeGeometry( px + pw // 2 - width // 2, py + ph // 2 - height // 2, width, height, ), ) frame = tix.Frame(master=dialog) label = tk.Label(master=frame, text="Value for " + optName) label.pack() entry = tk.Entry(master=frame) entry.insert(0, value) entry.pack(fill="x") prop = Glossary.plugins[format].optionsProp[optName] def customOkClicked(_event=None): rawValue = entry.get() if not prop.validateRaw(rawValue): log.error(f"invalid {prop.typ} value: {optName} = {rawValue!r}") return treev.set(optName, self.valueCol, rawValue) treev.set(optName, "#1", "1") # enable it col_w = tkFont.Font().measure(rawValue) if treev.column("Value", width=None) < col_w: treev.column("Value", width=col_w) dialog.destroy() entry.bind("<Return>", customOkClicked) label = tk.Label(master=frame) label.pack(fill="x") customOkbutton = newButton( frame, text=" OK ", command=customOkClicked, # bg="#ff0000", # activebackground="#ff5050", ) customOkbutton.pack(side="right") ### frame.pack(fill="x") dialog.focus() def valueMenuItemSelected(self, optName, menu, value): treev = self.treev treev.set(optName, self.valueCol, value) treev.set(optName, "#1", "1") # enable it col_w = tkFont.Font().measure(value) if treev.column("Value", width=None) < col_w: treev.column("Value", width=col_w) menu.destroy() self.menu = None def valueCellClicked(self, event, optName): if not optName: return treev = self.treev prop = self.optionsProp[optName] propValues = prop.values if not propValues: if prop.customValue: self.valueMenuItemCustomSelected(treev, self.format, optName, None) else: log.error( f"invalid option {optName}, values={propValues}" f", customValue={prop.customValue}", ) return if prop.typ == "bool": rawValue = treev.set(optName, self.valueCol) if rawValue == "": # noqa: PLC1901 value = False else: value, isValid = prop.evaluate(rawValue) if not isValid: log.error(f"invalid {optName} = {rawValue!r}") value = False treev.set(optName, self.valueCol, str(not value)) treev.set(optName, "#1", "1") # enable it return menu = tk.Menu( master=treev, title=optName, tearoff=False, ) self.menu = menu # to destroy it later if prop.customValue: menu.add_command( label="[Custom Value]", command=lambda: self.valueMenuItemCustomSelected( treev, self.format, optName, menu, ), ) groupedValues = None if len(propValues) > 10: groupedValues = prop.groupValues() maxItemW = 0 def valueMenuItemSelectedCommand(value): def callback(): self.valueMenuItemSelected(optName, menu, value) return callback if groupedValues: for groupName, subValues in groupedValues.items(): if subValues is None: menu.add_command( label=str(value), command=valueMenuItemSelectedCommand(value), ) maxItemW = max(maxItemW, tkFont.Font().measure(str(value))) else: subMenu = tk.Menu(tearoff=False) for subValue in subValues: subMenu.add_command( label=str(subValue), command=valueMenuItemSelectedCommand(subValue), ) menu.add_cascade(label=groupName, menu=subMenu) maxItemW = max(maxItemW, tkFont.Font().measure(groupName)) else: for valueTmp in propValues: value = str(valueTmp) menu.add_command( label=value, command=valueMenuItemSelectedCommand(value), ) def close(): menu.destroy() self.menu = None menu.add_command( label="[Close]", command=close, ) try: menu.tk_popup( event.x_root, event.y_root, ) # do not pass the third argument (entry), so that the menu # appears where the pointer is on its top-left corner finally: # make sure to release the grab (Tk 8.0a1 only) menu.grab_release() def treeClicked(self, event): treev = self.treev if self.menu: self.menu.destroy() self.menu = None return optName = treev.identify_row(event.y) # optName is rowId if not optName: return col = treev.identify_column(event.x) # "#1" to self.valueCol if col == "#1": value = treev.set(optName, col) treev.set(optName, col, 1 - int(value)) return if col == self.valueCol: self.valueCellClicked(event, optName) def okClicked(self): treev = self.treev for optName in self.options: enable = bool(int(treev.set(optName, "#1"))) if not enable: if optName in self.values: del self.values[optName] continue rawValue = treev.set(optName, self.valueCol) prop = self.optionsProp[optName] value, isValid = prop.evaluate(rawValue) if not isValid: log.error(f"invalid option value {optName} = {rawValue}") continue self.values[optName] = value self.destroy() class FormatOptionsButton(tk.Button): def __init__( self, kind: "Literal['Read', 'Write']", values: dict, formatInput: FormatButton, master=None, ) -> None: tk.Button.__init__( self, master=master, text="Options", command=self.buttonClicked, # bg="#f0f000", # activebackground="#f6f622", borderwidth=3, ) self.kind = kind self.values = values self.formatInput = formatInput def setOptionsValues(self, values): self.values = values def buttonClicked(self): formatD = self.formatInput.get() if not formatD: return format = pluginByDesc[formatD].name dialog = FormatOptionsDialog(format, self.kind, self.values, master=self) # x, y, w, h = decodeGeometry(dialog.geometry()) w, h = 380, 250 # w and h are rough estimated width and height of `dialog` px, py, pw, ph = decodeGeometry(self.winfo_toplevel().geometry()) # move dialog without changing the size dialog.geometry( encodeLocation( px + pw // 2 - w // 2, py + ph // 2 - h // 2, ), ) dialog.focus() class UI(tix.Frame, UIBase): fcd_dir_save_path = join(confDir, "ui-tk-fcd-dir") def __init__( self, progressbar: bool = True, ) -> None: rootWin = self.rootWin = tix.Tk() # a hack that hides the window until we move it to the center of screen if os.sep == "\\": # Windows rootWin.attributes("-alpha", 0.0) else: # Linux rootWin.withdraw() tix.Frame.__init__(self, rootWin) UIBase.__init__(self) rootWin.title("PyGlossary (Tkinter)") rootWin.resizable(True, False) # self.progressbarEnable = progressbar ######## set_window_icon(rootWin) rootWin.bind("<Escape>", lambda _e: rootWin.quit()) ######### # Linux: ('clam', 'alt', 'default', 'classic') # Windows: ('winnative', 'clam', 'alt', 'default', 'classic', 'vista', # 'xpnative') # style = ttk.Style() # style.theme_use("default") # there is no tk.Style() ######## self.pack(fill="x") # rootWin.bind("<Configure>", self.resized) ####################### defaultFont = tkFont.nametofont("TkDefaultFont") if core.sysName in {"linux", "freebsd"}: defaultFont.configure(size=int(defaultFont.cget("size") * 1.4)) #### self.biggerFont = defaultFont.copy() self.biggerFont.configure(size=int(defaultFont.cget("size") * 1.8)) ###################### self.glos = Glossary(ui=self) self.glos.config = self.config self.glos.progressbar = progressbar self._convertOptions = {} self.pathI = "" self.pathO = "" fcd_dir = join(homeDir, "Desktop") if isfile(self.fcd_dir_save_path): try: with open(self.fcd_dir_save_path, encoding="utf-8") as fp: fcd_dir = fp.read().strip("\n") except Exception: log.exception("") self.fcd_dir = fcd_dir ###################### notebook = tix.NoteBook(self) notebook.add("tabConvert", label="Convert", underline=0) # notebook.add("tabReverse", label="Reverse", underline=0) notebook.add("tabAbout", label="About", underline=0) convertFrame = tix.Frame(notebook.tabConvert) aboutFrame = tix.Frame(notebook.tabAbout) ################### row = 0 label = tk.Label(convertFrame, text="Input File: ") label.grid( row=row, column=0, sticky=tk.W, padx=5, ) ## entry = tix.Entry(convertFrame) entry.grid( row=row, column=1, columnspan=2, sticky=tk.W + tk.E, padx=0, ) entry.bind_all("<KeyPress>", self.anyEntryChanged) self.entryInputConvert = entry ## button = newButton( convertFrame, text="Browse", command=self.browseInputConvert, # bg="#f0f000", # activebackground="#f6f622", borderwidth=3, ) button.grid( row=row, column=3, sticky=tk.W + tk.E, padx=5, ) ###################### row += 1 label = tk.Label(convertFrame, text="Input Format: ") label.grid( row=row, column=0, sticky=tk.W, padx=5, ) ## self.formatButtonInputConvert = FormatButton( master=convertFrame, descList=readDesc, dialogTitle="Select Input Format", onChange=self.inputFormatChanged, ) self.formatButtonInputConvert.grid( row=row, column=1, columnspan=2, sticky=tk.W, padx=0, ) ## self.readOptions: "dict[str, Any]" = {} self.writeOptions: "dict[str, Any]" = {} ## self.readOptionsButton = FormatOptionsButton( "Read", self.readOptions, self.formatButtonInputConvert, master=convertFrame, ) self.inputFormatRow = row ###################### row += 1 label = tk.Label(convertFrame) label.grid( row=row, column=0, sticky=tk.W, ) ###################### row += 1 label = tk.Label(convertFrame, text="Output Format: ") label.grid( row=row, column=0, sticky=tk.W, padx=5, ) ## self.formatButtonOutputConvert = FormatButton( master=convertFrame, descList=writeDesc, dialogTitle="Select Output Format", onChange=self.outputFormatChanged, ) self.formatButtonOutputConvert.grid( row=row, column=1, columnspan=2, sticky=tk.W, padx=0, ) ## self.writeOptionsButton = FormatOptionsButton( "Write", self.writeOptions, self.formatButtonOutputConvert, master=convertFrame, ) self.outputFormatRow = row ################### row += 1 label = tk.Label(convertFrame, text="Output File: ") label.grid( row=row, column=0, sticky=tk.W, padx=5, ) ## entry = tix.Entry(convertFrame) entry.grid( row=row, column=1, columnspan=2, sticky=tk.W + tk.E, padx=0, ) entry.bind_all("<KeyPress>", self.anyEntryChanged) self.entryOutputConvert = entry ## button = newButton( convertFrame, text="Browse", command=self.browseOutputConvert, # bg="#f0f000", # activebackground="#f6f622", borderwidth=3, ) button.grid( row=row, column=3, sticky=tk.W + tk.E, padx=5, ) ################### row += 1 button = newButton( convertFrame, text="Convert", command=self.convert, # background="#00e000", # activebackground="#22f022", borderwidth=7, font=self.biggerFont, padx=5, pady=5, ) button.grid( row=row, column=2, columnspan=3, sticky=tk.W + tk.E + tk.S, padx=5, pady=5, ) # print(f"row number for Convert button: {row}") ###### convertFrame.pack(fill="x") # convertFrame.grid(sticky=tk.W + tk.E + tk.N + tk.S) ################# row += 1 console = tix.Text( convertFrame, height=15, background="#000", foreground="#fff", ) console.bind("<Key>", self.consoleKeyPress) # self.consoleH = 15 # sbar = Tix.Scrollbar( # convertFrame, # orien=Tix.VERTICAL, # command=console.yview # ) # sbar.grid (row=row, column=1) # console["yscrollcommand"] = sbar.set console.grid( row=row, column=0, columnspan=4, sticky=tk.W + tk.E, padx=5, pady=0, ) log.addHandler( TkTextLogHandler(console), ) console.insert("end", "Console:\n") #### self.console = console ################## aboutFrame2 = tix.Frame(aboutFrame) ## label = newLabelWithImage(aboutFrame2, file=logo) label.pack(side="left") ## ## label = tk.Label(aboutFrame2, text=f"PyGlossary\nVersion {getVersion()}") label.pack(side="left") ## aboutFrame2.pack(side="top", fill="x") ## style = ttk.Style(self) style.configure("TNotebook", tabposition="wn") # ws => to the left (west) and to the bottom (south) # wn => to the left (west) and at top aboutNotebook = ttk.Notebook(aboutFrame, style="TNotebook") # aboutNotebook = tix.Notebook(aboutFrame) aboutFrame3 = tk.Frame(aboutNotebook) authorsFrame = tk.Frame(aboutNotebook) licenseFrame = tk.Frame(aboutNotebook) # tabImg = tk.PhotoImage(file=join(dataDir, "res", "dialog-information-22.png")) # tabImg = tk.PhotoImage(file=join(dataDir, "res", "author-22.png")) aboutNotebook.add( aboutFrame3, text="\n About \n", # image=tabImg, # not working # compound=tk.TOP, # padding=50, # not working ) aboutNotebook.add( authorsFrame, text="\nAuthors\n", ) aboutNotebook.add( licenseFrame, text="\nLicense\n", ) label = newReadOnlyText( aboutFrame3, text=f"{aboutText}\nHome page: {core.homePage}", font=("DejaVu Sans", 11, ""), ) label.pack(fill="x") authorsText = "\n".join(authors) authorsText = authorsText.replace("\t", " ") label = newReadOnlyText( authorsFrame, text=authorsText, font=("DejaVu Sans", 11, ""), ) label.pack(fill="x") label = newReadOnlyText( licenseFrame, text=licenseText, font=("DejaVu Sans", 11, ""), ) label.pack(fill="x") aboutNotebook.pack(fill="x") aboutFrame.pack(fill="x") ###################### tk.Grid.columnconfigure(convertFrame, 0, weight=1) tk.Grid.columnconfigure(convertFrame, 1, weight=30) tk.Grid.columnconfigure(convertFrame, 2, weight=20) tk.Grid.columnconfigure(convertFrame, 3, weight=1) tk.Grid.rowconfigure(convertFrame, 0, weight=50) tk.Grid.rowconfigure(convertFrame, 1, weight=50) tk.Grid.rowconfigure(convertFrame, 2, weight=1) tk.Grid.rowconfigure(convertFrame, 3, weight=50) tk.Grid.rowconfigure(convertFrame, 4, weight=50) tk.Grid.rowconfigure(convertFrame, 5, weight=1) tk.Grid.rowconfigure(convertFrame, 6, weight=50) # _________________________________________________________________ # notebook.pack(fill="both", expand=True) # _________________________________________________________________ # statusBarframe = tk.Frame(self, borderwidth=3) clearB = newButton( statusBarframe, text="Clear", command=self.console_clear, # bg="black", # fg="#ffff00", # activebackground="#333333", # activeforeground="#ffff00", borderwidth=3, height=2, ) clearB.pack(side="left") #### label = tk.Label(statusBarframe, text="Verbosity") label.pack(side="left") ## comboVar = tk.StringVar() combo = tk.OptionMenu( statusBarframe, comboVar, log.getVerbosity(), # default 0, 1, 2, 3, 4, 5, ) comboVar.trace("w", self.verbosityChanged) combo.pack(side="left") self.verbosityCombo = comboVar comboVar.set(log.getVerbosity()) ##### pbar = ProgressBar(statusBarframe, width=700, height=28) pbar.pack(side="left", fill="x", expand=True) self.pbar = pbar statusBarframe.pack(fill="x") self.progressTitle = "" # _________________________________________________________________ # centerWindow(rootWin) # show the window if os.sep == "\\": # Windows rootWin.attributes("-alpha", 1.0) else: # Linux rootWin.deiconify() def textSelectAll(self, tktext): tktext.tag_add(tk.SEL, "1.0", tk.END) tktext.mark_set(tk.INSERT, "1.0") tktext.see(tk.INSERT) def consoleKeyPress(self, e): # print(e.state, e.keysym) if e.state > 0: if e.keysym == "c": return None if e.keysym == "a": self.textSelectAll(self.console) return "break" if e.keysym == "Escape": return None return "break" def verbosityChanged(self, _index, _value, _op): log.setVerbosity( int(self.verbosityCombo.get()), ) # def resized(self, event): # self.rootWin.winfo_height() - self.winfo_height() # log.debug(dh, self.consoleH) # if dh > 20: # self.consoleH += 1 # self.console["height"] = self.consoleH # self.console["width"] = int(self.console["width"]) + 1 # self.console.grid() # for x in dir(self): # if "info" in x: # log.debug(x) def inputFormatChanged(self, *_args): formatDesc = self.formatButtonInputConvert.get() if not formatDesc: return self.readOptions.clear() # reset the options, DO NOT re-assign format = pluginByDesc[formatDesc].name if Glossary.formatsReadOptions[format]: self.readOptionsButton.grid( row=self.inputFormatRow, column=3, sticky=tk.W + tk.E, padx=5, pady=0, ) else: self.readOptionsButton.grid_forget() def outputFormatChanged(self, *_args): formatDesc = self.formatButtonOutputConvert.get() if not formatDesc: return format = pluginByDesc[formatDesc].name plugin = Glossary.plugins.get(format) if not plugin: log.error(f"plugin {format} not found") return self.writeOptions.clear() # reset the options, DO NOT re-assign if Glossary.formatsWriteOptions[format]: self.writeOptionsButton.grid( row=self.outputFormatRow, column=3, sticky=tk.W + tk.E, padx=5, pady=0, ) else: self.writeOptionsButton.grid_forget() pathI = self.entryInputConvert.get() if ( pathI and not self.entryOutputConvert.get() and self.formatButtonInputConvert.get() and plugin.extensionCreate ): pathNoExt, _ext = splitext(pathI) self.entryOutputConvert.insert( 0, pathNoExt + plugin.extensionCreate, ) def anyEntryChanged(self, _event=None): self.inputEntryChanged() self.outputEntryChanged() def inputEntryChanged(self, _event=None): # char = event.keysym pathI = self.entryInputConvert.get() if self.pathI == pathI: return if pathI.startswith("file://"): pathI = urlToPath(pathI) self.entryInputConvert.delete(0, "end") self.entryInputConvert.insert(0, pathI) if self.config["ui_autoSetFormat"]: formatDesc = self.formatButtonInputConvert.get() if not formatDesc: try: inputArgs = Glossary.detectInputFormat(pathI) except Error: pass else: plugin = Glossary.plugins.get(inputArgs.formatName) if plugin: self.formatButtonInputConvert.setValue(plugin.description) self.inputFormatChanged() self.pathI = pathI def outputEntryChanged(self, _event=None): pathO = self.entryOutputConvert.get() if self.pathO == pathO: return if pathO.startswith("file://"): pathO = urlToPath(pathO) self.entryOutputConvert.delete(0, "end") self.entryOutputConvert.insert(0, pathO) if self.config["ui_autoSetFormat"]: formatDesc = self.formatButtonOutputConvert.get() if not formatDesc: try: outputArgs = Glossary.detectOutputFormat( filename=pathO, inputFilename=self.entryInputConvert.get(), ) except Error: pass else: self.formatButtonOutputConvert.setValue( Glossary.plugins[outputArgs.formatName].description, ) self.outputFormatChanged() self.pathO = pathO def save_fcd_dir(self): if not self.fcd_dir: return with open(self.fcd_dir_save_path, mode="w", encoding="utf-8") as fp: fp.write(self.fcd_dir) def browseInputConvert(self): path = filedialog.askopenfilename(initialdir=self.fcd_dir) if path: self.entryInputConvert.delete(0, "end") self.entryInputConvert.insert(0, path) self.inputEntryChanged() self.fcd_dir = os.path.dirname(path) self.save_fcd_dir() def browseOutputConvert(self): path = filedialog.asksaveasfilename() if path: self.entryOutputConvert.delete(0, "end") self.entryOutputConvert.insert(0, path) self.outputEntryChanged() self.fcd_dir = os.path.dirname(path) self.save_fcd_dir() def convert(self): inPath = self.entryInputConvert.get() if not inPath: log.critical("Input file path is empty!") return None inFormatDesc = self.formatButtonInputConvert.get() # if not inFormatDesc: # log.critical("Input format is empty!");return inFormat = pluginByDesc[inFormatDesc].name if inFormatDesc else "" outPath = self.entryOutputConvert.get() if not outPath: log.critical("Output file path is empty!") return None outFormatDesc = self.formatButtonOutputConvert.get() if not outFormatDesc: log.critical("Output format is empty!") return None outFormat = pluginByDesc[outFormatDesc].name for attr, value in self._glossarySetAttrs.items(): setattr(self.glos, attr, value) finalOutputFile = self.glos.convert( ConvertArgs( inPath, inputFormat=inFormat, outputFilename=outPath, outputFormat=outFormat, readOptions=self.readOptions, writeOptions=self.writeOptions, **self._convertOptions, ), ) # if finalOutputFile: # self.status("Convert finished") # else: # self.status("Convert failed") return bool(finalOutputFile) def run( # noqa: PLR0913 self, inputFilename: str = "", outputFilename: str = "", inputFormat: str = "", outputFormat: str = "", reverse: bool = False, config: "dict | None" = None, readOptions: "dict | None" = None, writeOptions: "dict | None" = None, convertOptions: "dict | None" = None, glossarySetAttrs: "dict | None" = None, ): if glossarySetAttrs is None: glossarySetAttrs = {} self.config = config if inputFilename: self.entryInputConvert.insert(0, abspath(inputFilename)) self.inputEntryChanged() if outputFilename: self.entryOutputConvert.insert(0, abspath(outputFilename)) self.outputEntryChanged() if inputFormat: self.formatButtonInputConvert.setValue( Glossary.plugins[inputFormat].description, ) self.inputFormatChanged() if outputFormat: self.formatButtonOutputConvert.setValue( Glossary.plugins[outputFormat].description, ) self.outputFormatChanged() if reverse: log.error("Tkinter interface does not support Reverse feature") # must be before setting self.readOptions and self.writeOptions self.anyEntryChanged() if readOptions: self.readOptionsButton.setOptionsValues(readOptions) self.readOptions = readOptions if writeOptions: self.writeOptionsButton.setOptionsValues(writeOptions) self.writeOptions = writeOptions self._convertOptions = convertOptions if convertOptions: log.info(f"Using {convertOptions=}") self._glossarySetAttrs = glossarySetAttrs # inputFilename and readOptions are for DB Editor # which is not implemented self.mainloop() def progressInit(self, title): self.progressTitle = title def progress(self, ratio, text=""): if not text: text = "%" + str(int(ratio * 100)) text += " - " + self.progressTitle self.pbar.updateProgress(ratio * 100, None, text) # self.pbar.value = ratio * 100 # self.pbar.update() self.rootWin.update() def console_clear(self, _event=None): self.console.delete("1.0", "end") self.console.insert("end", "Console:\n") # def reverseBrowseInput(self): # pass # def reverseBrowseOutput(self): # pass # def reverseLoad(self): # pass if __name__ == "__main__": import sys _path = sys.argv[1] if len(sys.argv) > 1 else "" _ui = UI(_path) _ui.run()
38,546
Python
.py
1,430
23.516783
83
0.688268
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,767
base.py
ilius_pyglossary/pyglossary/ui/base.py
# -*- coding: utf-8 -*- # mypy: ignore-errors # # Copyright © 2012-2022 Saeed Rasooli <saeed.gnu@gmail.com> (ilius) # This file is part of PyGlossary project, https://github.com/ilius/pyglossary # # This program is a free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program. Or on Debian systems, from /usr/share/common-licenses/GPL # If not, see <http://www.gnu.org/licenses/gpl.txt>. from __future__ import annotations import logging from collections import OrderedDict from os.path import isfile, join from pyglossary.core import ( appResDir, confJsonFile, dataDir, rootConfJsonFile, ) from pyglossary.entry_filters import entryFiltersRules from pyglossary.option import ( BoolOption, FloatOption, IntOption, Option, StrOption, ) __all__ = ["UIBase", "aboutText", "authors", "fread", "licenseText", "logo"] def fread(path: str) -> str: with open(path, encoding="utf-8") as fp: return fp.read() log = logging.getLogger("pyglossary") logo = join(appResDir, "pyglossary.png") aboutText = fread(join(dataDir, "about")) licenseText = fread(join(dataDir, "_license-dialog")) authors = fread(join(dataDir, "AUTHORS")).split("\n") summary = ( "A tool for converting dictionary files aka glossaries with" " various formats for different dictionary applications" ) _entryFilterConfigDict = { configParam: (filterClass, default) for configParam, default, filterClass in entryFiltersRules if configParam } def getEntryFilterConfigPair(name: str) -> tuple[str, Option]: filterClass, default = _entryFilterConfigDict[name] if isinstance(default, bool): optClass = BoolOption elif isinstance(default, str): optClass = StrOption else: raise TypeError(f"{default = }") return name, optClass( hasFlag=True, comment=filterClass.desc, falseComment=filterClass.falseComment, ) class UIBase: configDefDict = OrderedDict( [ ( "log_time", BoolOption( hasFlag=True, comment="Show date and time in logs", falseComment="Do not show date and time in logs", ), ), ( "cleanup", BoolOption( hasFlag=True, comment="Cleanup cache or temporary files after conversion", falseComment=( "Do not cleanup cache or temporary files after conversion", ), ), ), ( "auto_sqlite", BoolOption( hasFlag=False, comment=( "Auto-enable --sqlite to limit RAM usage when direct\n" "mode is not possible. Can override with --no-sqlite" ), ), ), ( "optimize_memory", BoolOption( hasFlag=True, comment=("Optimize memory usage (over speed) in --indirect mode"), ), ), ( "enable_alts", BoolOption( hasFlag=True, customFlag="alts", comment="Enable alternates", falseComment="Disable alternates", ), ), # FIXME: replace with "resources" # comment="Use resources (images, audio, etc)" ( "skip_resources", BoolOption( hasFlag=True, comment="Skip resources (images, audio, css, etc)", ), ), ( "save_info_json", BoolOption( hasFlag=True, customFlag="info", comment="Save .info file alongside output file(s)", ), ), getEntryFilterConfigPair("lower"), getEntryFilterConfigPair("utf8_check"), getEntryFilterConfigPair("rtl"), getEntryFilterConfigPair("remove_html"), getEntryFilterConfigPair("remove_html_all"), getEntryFilterConfigPair("normalize_html"), getEntryFilterConfigPair("skip_duplicate_headword"), getEntryFilterConfigPair("trim_arabic_diacritics"), getEntryFilterConfigPair("unescape_word_links"), ( "color.enable.cmd.unix", BoolOption( hasFlag=False, comment="Enable colors in Linux/Unix command line", ), ), ( "color.enable.cmd.windows", BoolOption( hasFlag=False, comment="Enable colors in Windows command line", ), ), ( "color.cmd.critical", IntOption( hasFlag=False, comment="Color code for critical errors in command line", ), ), ( "color.cmd.error", IntOption( hasFlag=False, comment="Color code for errors in command line", ), ), ( "color.cmd.warning", IntOption( hasFlag=False, comment="Color code for warnings in command line", ), ), # interactive command line interface ("cmdi.prompt.indent.str", StrOption(hasFlag=False)), ("cmdi.prompt.indent.color", IntOption(hasFlag=False)), ("cmdi.prompt.msg.color", IntOption(hasFlag=False)), ("cmdi.msg.color", IntOption(hasFlag=False)), ("ui_autoSetFormat", BoolOption(hasFlag=False)), ("reverse_matchWord", BoolOption(hasFlag=False)), ("reverse_showRel", StrOption(hasFlag=False)), ("reverse_saveStep", IntOption(hasFlag=False)), ("reverse_minRel", FloatOption(hasFlag=False)), ("reverse_maxNum", IntOption(hasFlag=False)), ("reverse_includeDefs", BoolOption(hasFlag=False)), ], ) conflictingParams = [ ("sqlite", "direct"), ("remove_html", "remove_html_all"), ] def __init__(self, **_kwargs) -> None: self.config = {} def progressInit(self, title: str) -> None: pass def progress(self, ratio: float, text: str = "") -> None: pass def progressEnd(self) -> None: self.progress(1.0) def loadConfig( self, user: bool = True, **options, ) -> None: from pyglossary.json_utils import jsonToData data = jsonToData(fread(rootConfJsonFile)) if user and isfile(confJsonFile): try: userData = jsonToData(fread(confJsonFile)) except Exception: log.exception( f"error while loading user config file {confJsonFile!r}", ) else: data.update(userData) for key in self.configDefDict: try: self.config[key] = data.pop(key) except KeyError: # noqa: PERF203 pass for key in data: log.warning( f"unknown config key {key!r}, you may edit {confJsonFile}" " file and remove this key", ) for key, value in options.items(): if key in self.configDefDict: self.config[key] = value log.setTimeEnable(self.config["log_time"]) log.debug(f"loaded config: {self.config}") def saveConfig(self) -> None: from pyglossary.json_utils import dataToPrettyJson config = OrderedDict() for key, option in self.configDefDict.items(): if key not in self.config: log.warning(f"saveConfig: missing key {key!r}") continue value = self.config[key] if not option.validate(value): log.error(f"saveConfig: invalid {key}={value!r}") continue config[key] = value jsonStr = dataToPrettyJson(config) with open(confJsonFile, mode="w", encoding="utf-8") as _file: _file.write(jsonStr) log.info(f"saved {confJsonFile!r}")
7,142
Python
.py
249
24.963855
78
0.703175
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,768
dependency.py
ilius_pyglossary/pyglossary/ui/dependency.py
# -*- coding: utf-8 -*- # dependency.py # # Copyright © 2019-2019 Saeed Rasooli <saeed.gnu@gmail.com> (ilius) # This file is part of PyGlossary project, https://github.com/ilius/pyglossary # # This program is a free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program. Or on Debian systems, from /usr/share/common-licenses/GPL # If not, see <http://www.gnu.org/licenses/gpl.txt>. # reqs = subprocess.check_output([sys.executable, '-m', 'pip', 'freeze']) # ^ this takes about 3 seconds # installed_packages = set(r.decode().split('==')[0] for r in reqs.split()) from __future__ import annotations __all__ = ["checkDepends"] def checkDepends(depends: dict[str, str]) -> list[str]: """Return the list of non-installed dependencies.""" if not depends: return [] not_installed = [] for moduleName, pkgName in depends.items(): try: __import__(moduleName) except ModuleNotFoundError: # noqa: PERF203 not_installed.append(pkgName) return not_installed
1,465
Python
.py
35
40.228571
78
0.745263
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,769
pbar_legacy.py
ilius_pyglossary/pyglossary/ui/pbar_legacy.py
# mypy: ignore-errors from . import progressbar as pb __all__ = ["createProgressBar"] def createProgressBar(title: str): rot = pb.RotatingMarker() pbar = pb.ProgressBar( maxval=1.0, # update_step=0.5, removed ) pbar.widgets = [ title + " ", pb.AnimatedMarker(), " ", pb.Bar(marker="â–ˆ"), pb.Percentage(), " ", pb.ETA(), ] pbar.start(num_intervals=1000) rot.pbar = pbar return pbar
412
Python
.py
21
17.190476
34
0.671835
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,770
version.py
ilius_pyglossary/pyglossary/ui/version.py
from __future__ import annotations import sys from os.path import isdir, join from pyglossary import core __all__ = ["getVersion"] def getGitVersion(gitDir: str) -> str: import subprocess try: outputB, _err = subprocess.Popen( [ "git", "--git-dir", gitDir, "describe", "--always", ], stdout=subprocess.PIPE, ).communicate() except Exception as e: sys.stderr.write(str(e) + "\n") return "" # if _err is None: return outputB.decode("utf-8").strip() def getVersion() -> str: from pyglossary.core import rootDir gitDir = join(rootDir, ".git") if isdir(gitDir): version = getGitVersion(gitDir) if version: return version return core.VERSION
698
Python
.py
31
19.516129
39
0.694529
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,771
main.py
ilius_pyglossary/pyglossary/ui/main.py
# -*- coding: utf-8 -*- # mypy: ignore-errors # ui/main.py # # Copyright © 2008-2022 Saeed Rasooli <saeed.gnu@gmail.com> (ilius) # This file is part of PyGlossary project, https://github.com/ilius/pyglossary # # This program is a free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program. Or on Debian systems, from /usr/share/common-licenses/GPL # If not, see <http://www.gnu.org/licenses/gpl.txt>. from __future__ import annotations import argparse import logging import sys from dataclasses import dataclass from typing import Any from pyglossary import core # essential from pyglossary.langs import langDict from pyglossary.ui.argparse_main import configFromArgs, defineFlags, validateFlags from pyglossary.ui.base import UIBase __all__ = ["main"] # TODO: move to docs: # examples for read and write options: # --read-options testOption=stringValue # --read-options enableFoo=True # --read-options fooList=[1,2,3] # --read-options 'fooList=[1, 2, 3]' # --read-options 'testOption=stringValue; enableFoo=True; fooList=[1, 2, 3]' # --read-options 'testOption=stringValue;enableFoo=True;fooList=[1,2,3]' # if a desired value contains ";", you can use --json-read-options # or --json-write-options flags instead, with json object as value, # quoted for command line. for example: # '--json-write-options={"delimiter": ";"}' # the first thing to do is to set up logger. # other modules also using logger "root", so it is essential to set it up prior # to importing anything else; with exception to pyglossary.core which sets up # logger class, and so should be done before actually initializing logger. # verbosity level may be given on command line, so we have to parse arguments # before setting up logger. # once more: # - import system modules like os, sys, argparse etc and pyglossary.core # - parse args # - set up logger # - import submodules # - other code # no-progress-bar only for command line UI # TODO: load ui-dependent available options from ui modules # (for example ui_cmd.available_options) # the only problem is that it has to "import gtk" before it get the # "ui_gtk.available_options" # TODO # -v (verbose or version?) # -r (reverse or read-options) log = None def validateLangStr(st: str) -> str | None: lang = langDict[st] if lang: return lang.name lang = langDict[st.lower()] if lang: return lang.name log.error(f"unknown language {st!r}") return None convertOptionsKeys = ( "direct", "sort", "sortKeyName", "sortEncoding", "sqlite", ) infoOverrideSpec = ( ("sourceLang", validateLangStr), ("targetLang", validateLangStr), ("name", str), ) @dataclass(slots=True, frozen=True) class MainPrepareResult: args: "argparse.Namespace" uiType: str inputFilename: str outputFilename: str inputFormat: str | None outputFormat: str | None reverse: bool config: dict readOptions: dict[str, Any] writeOptions: dict[str, Any] convertOptions: dict[str, Any] # TODO: # PLR0911 Too many return statements (7 > 6) # PLR0915 Too many statements (56 > 50) def mainPrepare() -> tuple[bool, MainPrepareResult | None]: global log uiBase = UIBase() uiBase.loadConfig() config = uiBase.config parser = argparse.ArgumentParser( prog=sys.argv[0], add_help=False, # allow_abbrev=False, ) defineFlags(parser, config) # _______________________________ args = parser.parse_args() # parser.conflict_handler == "error" if args.version: from pyglossary.ui.version import getVersion print(f"PyGlossary {getVersion()}") return True, None log = logging.getLogger("pyglossary") if args.ui_type == "none": args.noColor = True core.noColor = args.noColor logHandler = core.StdLogHandler( noColor=args.noColor, ) log.setVerbosity(args.verbosity) log.addHandler(logHandler) # with the logger set up, we can import other pyglossary modules, so they # can do some logging in right way. if not validateFlags(args, log): return False, None if args.sqlite: # args.direct is None by default which means automatic args.direct = False core.checkCreateConfDir() if sys.getdefaultencoding() != "utf-8": log.warning(f"System encoding is not utf-8, it's {sys.getdefaultencoding()!r}") ############################## from pyglossary.glossary_v2 import Glossary from pyglossary.ui.ui_cmd import printHelp Glossary.init() if core.isDebug(): log.debug(f"en -> {langDict['en']!r}") ############################## # log.info(f"PyGlossary {core.VERSION}") if args.help: printHelp() return True, None from pyglossary.ui.option_ui import ( evaluateReadOptions, evaluateWriteOptions, parseReadWriteOptions, ) # only used in ui_cmd for now rwOpts, err = parseReadWriteOptions(args) if err: log.error(err) if rwOpts is None: return False, None readOptions, writeOptions = rwOpts config.update(configFromArgs(args, log)) logHandler.config = config convertOptions = {} for key in convertOptionsKeys: value = getattr(args, key, None) if value is not None: convertOptions[key] = value infoOverride = {} for key, validate in infoOverrideSpec: value = getattr(args, key, None) if value is None: continue value = validate(value) if value is None: continue infoOverride[key] = value if infoOverride: convertOptions["infoOverride"] = infoOverride if args.inputFilename and readOptions: readOptions, err = evaluateReadOptions( readOptions, args.inputFilename, args.inputFormat, ) if err: log.error(err) if readOptions is None: return False, None if args.outputFilename and writeOptions: writeOptions, err = evaluateWriteOptions( writeOptions, args.inputFilename, args.outputFilename, args.outputFormat, ) if err: log.error(err) if writeOptions is None: return False, None if convertOptions: log.debug(f"{convertOptions = }") return True, MainPrepareResult( args=args, uiType=args.ui_type, inputFilename=args.inputFilename, outputFilename=args.outputFilename, inputFormat=args.inputFormat, outputFormat=args.outputFormat, reverse=args.reverse, config=config, readOptions=readOptions, writeOptions=writeOptions, convertOptions=convertOptions, ) def main() -> None: # noqa: PLR0912 ok, res = mainPrepare() if res is None: sys.exit(0 if ok else 1) # import pprint;pprint.pprint(res) from pyglossary.ui.runner import getRunner run = getRunner(res.args, res.uiType, log) if run is None: sys.exit(1) try: ok = run( inputFilename=res.inputFilename, outputFilename=res.outputFilename, inputFormat=res.inputFormat, outputFormat=res.outputFormat, reverse=res.reverse, config=res.config, readOptions=res.readOptions, writeOptions=res.writeOptions, convertOptions=res.convertOptions, glossarySetAttrs=None, ) except KeyboardInterrupt: log.error("Cancelled") ok = False sys.exit(0 if ok else 1)
7,355
Python
.py
241
28.174274
82
0.749965
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,772
argparse_main.py
ilius_pyglossary/pyglossary/ui/argparse_main.py
from __future__ import annotations import argparse import logging import os from typing import Any from pyglossary.ui.base import UIBase from pyglossary.ui.option_ui import registerConfigOption def defineFlags(parser: argparse.ArgumentParser, config: dict[str, Any]): defaultHasColor = config.get( "color.enable.cmd.windows" if os.sep == "\\" else "color.enable.cmd.unix", True, ) parser.add_argument( "-v", "--verbosity", action="store", dest="verbosity", type=int, choices=(0, 1, 2, 3, 4, 5), required=False, default=int(os.getenv("VERBOSITY", "3")), ) parser.add_argument( "--version", action="store_true", ) parser.add_argument( "-h", "--help", dest="help", action="store_true", ) parser.add_argument( "-u", "--ui", dest="ui_type", default="auto", choices=( "cmd", "gtk", "gtk4", "tk", # "qt", "auto", "none", ), ) parser.add_argument( "--cmd", dest="ui_type", action="store_const", const="cmd", default=None, help="use command-line user interface", ) parser.add_argument( "--gtk", dest="ui_type", action="store_const", const="gtk", default=None, help="use Gtk-based user interface", ) parser.add_argument( "--gtk4", dest="ui_type", action="store_const", const="gtk4", default=None, help="use Gtk4-based user interface", ) parser.add_argument( "--tk", dest="ui_type", action="store_const", const="tk", default=None, help="use Tkinter-based user interface", ) parser.add_argument( "--interactive", "--inter", dest="interactive", action="store_true", default=None, help="switch to interactive command line interface", ) parser.add_argument( "--no-interactive", "--no-inter", dest="no_interactive", action="store_true", default=None, help=( "do not automatically switch to interactive command line" " interface, for scripts" ), ) parser.add_argument( "-r", "--read-options", dest="readOptions", default="", ) parser.add_argument( "-w", "--write-options", dest="writeOptions", default="", ) parser.add_argument( "--json-read-options", dest="jsonReadOptions", default=None, ) parser.add_argument( "--json-write-options", dest="jsonWriteOptions", default=None, ) parser.add_argument( "--read-format", dest="inputFormat", ) parser.add_argument( "--write-format", dest="outputFormat", action="store", ) parser.add_argument( "--direct", dest="direct", action="store_true", default=None, help="if possible, convert directly without loading into memory", ) parser.add_argument( "--indirect", dest="direct", action="store_false", default=None, help=( "disable `direct` mode, load full data into memory before writing" ", this is default" ), ) parser.add_argument( "--sqlite", dest="sqlite", action="store_true", default=None, help=( "use SQLite as middle storage instead of RAM in direct mode," "for very large glossaries" ), ) parser.add_argument( "--no-sqlite", dest="sqlite", action="store_false", default=None, help="do not use SQLite mode", ) parser.add_argument( "--no-progress-bar", dest="progressbar", action="store_false", default=None, ) parser.add_argument( "--no-color", dest="noColor", action="store_true", default=not defaultHasColor, ) parser.add_argument( "--sort", dest="sort", action="store_true", default=None, ) parser.add_argument( "--no-sort", dest="sort", action="store_false", default=None, ) parser.add_argument( "--sort-key", action="store", dest="sortKeyName", default=None, help="name of sort key", ) parser.add_argument( "--sort-encoding", action="store", dest="sortEncoding", default=None, help="encoding of sort (default utf-8)", ) # _______________________________ parser.add_argument( "--source-lang", action="store", dest="sourceLang", default=None, help="source/query language", ) parser.add_argument( "--target-lang", action="store", dest="targetLang", default=None, help="target/definition language", ) parser.add_argument( "--name", action="store", dest="name", default=None, help="glossary name/title", ) # _______________________________ parser.add_argument( "--reverse", dest="reverse", action="store_true", ) parser.add_argument( "inputFilename", action="store", default="", nargs="?", ) parser.add_argument( "outputFilename", action="store", default="", nargs="?", ) # _______________________________ for key, option in UIBase.configDefDict.items(): registerConfigOption(parser, key, option) def validateFlags(args: "argparse.Namespace", log: logging.Logger) -> bool: from pyglossary.sort_keys import lookupSortKey, namedSortKeyList for param1, param2 in UIBase.conflictingParams: if getattr(args, param1) and getattr(args, param2): log.critical( "Conflicting flags: " f"--{param1.replace('_', '-')} and " f"--{param2.replace('_', '-')}", ) return False if not args.sort: if args.sortKeyName: log.critical("Passed --sort-key without --sort") return False if args.sortEncoding: log.critical("Passed --sort-encoding without --sort") return False if args.sortKeyName and not lookupSortKey(args.sortKeyName): _valuesStr = ", ".join(_sk.name for _sk in namedSortKeyList) log.critical( f"Invalid sortKeyName={args.sortKeyName!r}" f". Supported values:\n{_valuesStr}", ) return False return True def configFromArgs( args: argparse.Namespace, log: logging.Logger, ) -> dict[str, Any]: config = {} for key, option in UIBase.configDefDict.items(): if not option.hasFlag: continue value = getattr(args, key, None) if value is None: continue log.debug(f"config: {key} = {value}") if not option.validate(value): log.error(f"invalid config value: {key} = {value!r}") continue config[key] = value return config
5,959
Python
.py
286
17.98951
76
0.673101
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,773
about.py
ilius_pyglossary/pyglossary/ui/gtk4_utils/about.py
# -*- coding: utf-8 -*- # mypy: ignore-errors # # Copyright © 2020 Saeed Rasooli <saeed.gnu@gmail.com> (ilius) # # This program is a free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # You can get a copy of GNU General Public License along this program # But you can always get it from http://www.gnu.org/licenses/gpl.txt # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. from __future__ import annotations from . import gtk from .utils import ( VBox, imageFromFile, pack, ) __all__ = ["AboutWidget"] class AboutTabTitleBox(gtk.Box): def __init__(self, title: str, icon: str) -> None: gtk.Box.__init__(self, orientation=gtk.Orientation.VERTICAL) self.set_spacing(10) pack(self, VBox(), expand=0) if icon: image = imageFromFile(icon) image.get_pixel_size() image.set_size_request(24, 24) # I don't know how to stop Gtk from resizing the image # I should probably use svg files to avoid blurry images pack(self, image, expand=0) if title: pack(self, gtk.Label(label=title), expand=0) pack(self, VBox(), expand=0) self.set_size_request(60, 60) # def do_get_preferred_height_for_width(self, size: int) -> tuple[int, int]: # height = int(size * 1.5) # return height, height # returns: (minimum: int, natural: int, # minimum_baseline: int, natural_baseline: int) # def do_measure(self, orientation, for_size): # return (for_size, for_size, for_size, for_size) class AboutWidget(gtk.Box): def __init__( # noqa: PLR0913 self, logo: str = "", header: str = "", about: str = "", authors: str = "", license_text: str = "", **_kwargs, ) -> None: gtk.Box.__init__(self, orientation=gtk.Orientation.VERTICAL) self.set_spacing(15) ## headerBox = gtk.Box(orientation=gtk.Orientation.HORIZONTAL) if logo: pack(headerBox, imageFromFile(logo)) headerLabel = gtk.Label(label=header) headerLabel.set_selectable(True) pack(headerBox, headerLabel) headerBox.show() pack(self, headerBox) ## notebook = gtk.Notebook() self.notebook = notebook pack(self, notebook, expand=True) notebook.set_tab_pos(gtk.PositionType.LEFT) ## tab1_about = self.newTabLabelWidget(about) tab2_authors = self.newTabWidgetTextView(authors) tab3_license = self.newTabWidgetTextView(license_text) ## tabs = [ (tab1_about, self.newTabTitle("About", "dialog-information-22.png")), (tab2_authors, self.newTabTitle("Authors", "author-22.png")), (tab3_license, self.newTabTitle("License", "license-22.png")), ] ## for widget, titleW in tabs: notebook.append_page(widget, titleW) ## self.show() # <a href="...">Something</a> does not work with TextView @staticmethod def newTabWidgetTextView( text: str, wrap: bool = False, justification: "gtk.Justification | None" = None, ): tv = gtk.TextView() if wrap: tv.set_wrap_mode(gtk.WrapMode.WORD) if justification is not None: tv.set_justification(justification) tv.set_cursor_visible(False) # tv.set_border_width(10) buf = tv.get_buffer() # buf.insert_markup(buf.get_end_iter(), markup=text, # len=len(text.encode("utf-8"))) buf.set_text(text) tv.show() swin = gtk.ScrolledWindow() swin.set_policy(gtk.PolicyType.AUTOMATIC, gtk.PolicyType.AUTOMATIC) # swin.set_border_width(0) swin.set_child(tv) return swin @staticmethod def newTabLabelWidget( text: str, # wrap: bool = False, # justification: "gtk.Justification | None" = None, ): box = VBox() # box.set_border_width(10) label = gtk.Label() label.set_selectable(True) label.set_xalign(0) label.set_yalign(0) pack(box, label, 0, 0) # if wrap: # tv.set_wrap_mode(gtk.WrapMode.WORD) # if justification is not None: # tv.set_justification(justification) # label.set_cursor_visible(False) # label.set_border_width(10) label.set_markup(text) label.show() swin = gtk.ScrolledWindow() swin.set_policy(gtk.PolicyType.AUTOMATIC, gtk.PolicyType.AUTOMATIC) # swin.set_border_width(0) swin.set_child(box) return swin @staticmethod def newTabTitle(title: str, icon: str): return AboutTabTitleBox(title, icon)
4,446
Python
.py
142
28.612676
77
0.717548
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,774
dialog.py
ilius_pyglossary/pyglossary/ui/gtk4_utils/dialog.py
# -*- coding: utf-8 -*- # mypy: ignore-errors # # Copyright © 2016-2017 Saeed Rasooli <saeed.gnu@gmail.com> (ilius) # # This program is a free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # You can get a copy of GNU General Public License along this program # But you can always get it from http://www.gnu.org/licenses/gpl.txt # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. from gi.repository import Gdk as gdk from .utils import gtk_event_iteration_loop class MyDialog: def startWaiting(self): self.queue_draw() self.vbox.set_sensitive(False) self.get_window().set_cursor(gdk.Cursor.new(gdk.CursorType.WATCH)) gtk_event_iteration_loop() def endWaiting(self): self.get_window().set_cursor(gdk.Cursor.new(gdk.CursorType.LEFT_PTR)) self.vbox.set_sensitive(True) def waitingDo(self, func, *args, **kwargs): self.startWaiting() try: func(*args, **kwargs) except Exception as e: raise e finally: self.endWaiting()
1,312
Python
.py
36
34.361111
72
0.762017
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,775
utils.py
ilius_pyglossary/pyglossary/ui/gtk4_utils/utils.py
# -*- coding: utf-8 -*- # mypy: ignore-errors # # Copyright © 2016-2019 Saeed Rasooli <saeed.gnu@gmail.com> (ilius) # # This program is a free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # You can get a copy of GNU General Public License along this program # But you can always get it from http://www.gnu.org/licenses/gpl.txt # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. from __future__ import annotations import logging from os.path import isabs, join from pyglossary.core import appResDir from . import gdk, glib, gtk __all__ = [ "HBox", "VBox", "dialog_add_button", "gtk_event_iteration_loop", "gtk_window_iteration_loop", "imageFromFile", "pack", "rgba_parse", "set_tooltip", "showInfo", ] log = logging.getLogger("pyglossary") def gtk_window_iteration_loop(): try: while gtk.Window.get_toplevels(): glib.MainContext.default().iteration(True) except KeyboardInterrupt: pass def gtk_event_iteration_loop(): ctx = glib.MainContext.default() try: while ctx.pending(): ctx.iteration(True) except KeyboardInterrupt: pass def VBox(**kwargs): return gtk.Box(orientation=gtk.Orientation.VERTICAL, **kwargs) def HBox(**kwargs): return gtk.Box(orientation=gtk.Orientation.HORIZONTAL, **kwargs) def set_tooltip(widget, text): try: widget.set_tooltip_text(text) # PyGTK 2.12 or above except AttributeError: try: widget.set_tooltip(gtk.Tooltips(), text) except Exception: log.exception("") def imageFromFile(path): # the file must exist if not isabs(path): path = join(appResDir, path) im = gtk.Image() try: im.set_from_file(path) except Exception: log.exception("") return im def imageFromIconName(iconName: str, size: int, nonStock=False) -> gtk.Image: # So gtk.Image.new_from_stock is deprecated # And the doc says we should use gtk.Image.new_from_icon_name # which does NOT have the same functionality! # because not all stock items are existing in all themes (even popular themes) # and new_from_icon_name does not seem to look in other (non-default) themes! # So for now we use new_from_stock, unless it's not a stock item # But we do not use either of these two outside this function # So that it's easy to switch if nonStock: return gtk.Image.new_from_icon_name(iconName) try: return gtk.Image.new_from_stock(iconName, size) except Exception: return gtk.Image.new_from_icon_name(iconName) def rgba_parse(colorStr): rgba = gdk.RGBA() if not rgba.parse(colorStr): raise ValueError(f"bad color string {colorStr!r}") return rgba def color_parse(colorStr): return rgba_parse(colorStr).to_color() def pack(box, child, expand=False, fill=False, padding=0): # noqa: ARG001 if padding > 0: print(f"pack: padding={padding} ignored") if isinstance(box, gtk.Box): box.append(child) if expand: if box.get_orientation() == gtk.Orientation.VERTICAL: child.set_vexpand(True) else: child.set_hexpand(True) # FIXME: what to do with: fill, padding elif isinstance(box, gtk.CellLayout): box.pack_start(child, expand) else: raise TypeError(f"pack: unknown type {type(box)}") def dialog_add_button( dialog, _iconName, label, resId, onClicked=None, tooltip="", ): button = gtk.Button( label=label, use_underline=True, # icon_name=iconName, ) # fixed bug: used to ignore resId and pass gtk.ResponseType.OK dialog.add_action_widget( button, resId, ) if onClicked: label.connect("clicked", onClicked) if tooltip: set_tooltip(label, tooltip) return label def showMsg( # noqa: PLR0913 msg, iconName="", parent=None, transient_for=None, title="", borderWidth=10, # noqa: ARG001 iconSize=gtk.IconSize.LARGE, selectable=False, ): win = gtk.Dialog( parent=parent, transient_for=transient_for, ) # flags=0 makes it skip task bar if title: win.set_title(title) hbox = HBox(spacing=10) # hbox.set_border_width(borderWidth) if iconName: # win.set_icon(...) pack(hbox, imageFromIconName(iconName, iconSize)) label = gtk.Label(label=msg) # set_line_wrap(True) makes the window go crazy tall (taller than screen) # and that's the reason for label.set_size_request and win.resize # label.set_line_wrap(True) # label.set_line_wrap_mode(pango.WrapMode.WORD) label.set_size_request(500, 1) if selectable: label.set_selectable(True) pack(hbox, label) hbox.show() content_area = win.get_content_area() pack(content_area, hbox) dialog_add_button( win, "gtk-close", "_Close", gtk.ResponseType.OK, ) def onResponse(_w, _response_id): win.destroy() win.connect("response", onResponse) # win.resize(600, 1) win.show() def showError(msg, **kwargs): # gtk-dialog-error is deprecated since version 3.10: # Use named icon “dialog-error”. showMsg(msg, iconName="gtk-dialog-error", **kwargs) def showWarning(msg, **kwargs): # gtk-dialog-warning is deprecated since version 3.10: # Use named icon “dialog-warning”. showMsg(msg, iconName="gtk-dialog-warning", **kwargs) def showInfo(msg, **kwargs): # gtk-dialog-info is deprecated since version 3.10: # Use named icon “dialog-information”. showMsg(msg, iconName="gtk-dialog-info", **kwargs)
5,505
Python
.py
186
27.241935
79
0.745586
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,776
__init__.py
ilius_pyglossary/pyglossary/ui/gtk4_utils/__init__.py
# mypy: ignore-errors # do not sort these imports! from gi.repository import Gtk as gtk # noqa: I001 from gi.repository import Gdk as gdk # noqa: I001 from gi.repository import Gio as gio # noqa: I001 from gi.repository import GLib as glib # noqa: I001
257
Python
.py
6
41.833333
52
0.760956
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,777
resize_button.py
ilius_pyglossary/pyglossary/ui/gtk4_utils/resize_button.py
# -*- coding: utf-8 -*- # mypy: ignore-errors # # Copyright © 2016-2017 Saeed Rasooli <saeed.gnu@gmail.com> (ilius) # # This program is a free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # You can get a copy of GNU General Public License along this program # But you can always get it from http://www.gnu.org/licenses/gpl.txt # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. from __future__ import annotations from . import gdk, gtk from .utils import imageFromFile class ResizeButton(gtk.Box): def __init__(self, win, edge=gdk.SurfaceEdge.SOUTH_EAST) -> None: gtk.Box.__init__(self) self.win = win self.edge = edge ### self.image = imageFromFile("resize.png") self.append(self.image) gesture = gtk.GestureClick.new() gesture.connect("pressed", self.buttonPress) self.add_controller(gesture) def buttonPress(self, gesture, button, x, y): # Gesture is subclass of EventController pass # FIXME # self.win.begin_resize( # self.edge, # button, # int(gevent.x_root), # int(gevent.y_root), # gesture.get_current_event_time(), # )
1,437
Python
.py
41
32.97561
72
0.738849
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,778
colors.py
ilius_pyglossary/pyglossary/ui/tools/colors.py
__all__ = ["green", "red", "reset", "yellow"] redCode = 1 greenCode = 2 yellowCode = 3 red = f"\x1b[38;5;{redCode}m" green = f"\x1b[38;5;{greenCode}m" yellow = f"\x1b[38;5;{yellowCode}m" reset = "\x1b[0;0;0m"
210
Python
.py
8
25.125
45
0.631841
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,779
diff_glossary.py
ilius_pyglossary/pyglossary/ui/tools/diff_glossary.py
#!/usr/bin/env python # mypy: ignore-errors from __future__ import annotations import atexit import difflib import os import os.path import shlex import sys from collections.abc import Iterator from subprocess import PIPE, Popen from typing import TYPE_CHECKING from pyglossary.core import log from pyglossary.glossary_v2 import Glossary from pyglossary.ui.tools.colors import ( green, red, reset, yellow, ) from pyglossary.ui.tools.format_entry import formatEntry from pyglossary.ui.tools.word_diff import ( formatDiff, xmlDiff, ) if TYPE_CHECKING: from pyglossary.glossary_types import EntryType __all__ = ["diffGlossary"] Glossary.init() log.setVerbosity(1) entrySep = f"\n{'_' * 40}\n\n" noInfo = os.getenv("GLOSSARY_DIFF_NO_INFO") == "1" def formatInfoValueDiff(diff: "Iterator[str]") -> str: a = "" b = "" for part in diff: if part[0] == " ": a += part[2:] b += part[2:] continue if part[0] == "-": a += red + part[2:] + reset continue if part[0] == "+": b += green + part[2:] + reset continue return a + "\n" + b def diffGlossary( # noqa: PLR0912, PLR0913 filename1: str, filename2: str, format1: "str | None" = None, format2: "str | None" = None, header: str = "", pager: bool = True, ) -> None: glos1 = Glossary(ui=None) if not glos1.directRead(filename1, format=format1): return glos2 = Glossary(ui=None) if not glos2.directRead(filename2, format=format2): return if pager: pagerCmd = ["less", "-R"] if os.getenv("PAGER"): pagerCmd = shlex.split(os.getenv("PAGER")) proc = Popen( pagerCmd, stdin=PIPE, ) def write(msg: str): proc.stdin.write(msg.encode("utf-8")) else: proc = None def write(msg: str): print(msg, end="") if header: write(header + "\n") iter1 = iter(glos1) iter2 = iter(glos2) # infoIter1 = iter(sorted(glos1.iterInfo())) # infoIter2 = iter(sorted(glos2.iterInfo())) if noInfo: infoIter1 = iter([]) infoIter2 = iter([]) else: infoIter1 = glos1.iterInfo() infoIter2 = glos2.iterInfo() index1 = -1 index2 = -1 def nextEntry1() -> None: nonlocal entry1, index1 entry1 = next(iter1) index1 += 1 def nextEntry2() -> None: nonlocal entry2, index2 entry2 = next(iter2) index2 += 1 def printEntry(color: str, prefix: str, index: int, entry: EntryType) -> None: formatted = ( f"{color}{prefix}#{index} " + formatEntry(entry).replace("\n", "\n" + color) + entrySep ) write(formatted) def printInfo(color: str, prefix: str, pair: "tuple[str, str]") -> None: key, value = pair spaces = " " * (len(prefix) + 7) valueColor = color + spaces + value.replace("\n", "\n" + spaces + color) formatted = f"{color}{prefix} Info: {key}\n{valueColor}" + entrySep write(formatted) def printChangedEntry(entry1: "EntryType", entry2: "EntryType") -> None: defiDiff = formatDiff(xmlDiff(entry1.defi, entry2.defi)) entry1._defi = defiDiff if index1 < 0: ids = "" elif index1 == index2: ids = f"#{index1}" else: ids = f"A#{index1} B#{index2}" formatted = f"=== {yellow}{ids}{reset} " + formatEntry(entry1) + entrySep write(formatted) def printChangedInfo(key: str, value1: str, value2: str) -> str: valueDiff = formatInfoValueDiff(xmlDiff(value1, value2)) printInfo(yellow, "=== ", (key, valueDiff)) infoPair1 = None infoPair2 = None def infoStep() -> None: nonlocal infoPair1, infoPair2 if infoPair1 is None: infoPair1 = next(infoIter1) if infoPair2 is None: infoPair2 = next(infoIter2) if infoPair1 == infoPair2: infoPair1, infoPair2 = None, None return if infoPair1[0] == infoPair2[0]: printChangedInfo(infoPair1[0], infoPair1[1], infoPair2[1]) infoPair1, infoPair2 = None, None return if infoPair1[0] < infoPair2[0]: printInfo(red, "--- A: ", infoPair1) infoPair1 = None return printInfo(green, "+++ B: ", infoPair2) infoPair2 = None def printAltsChangedEntry( entry1: "EntryType", entry2: "EntryType", showDefi: bool = True, ) -> None: ids = f"#{index1}" if index1 == index2 else f"A#{index1} B#{index2}" header = f"=== {yellow}{ids}{reset} " altsDiff = difflib.ndiff( [f"Alt: {alt}\n" for alt in entry1.l_word[1:]], [f"Alt: {alt}\n" for alt in entry2.l_word[1:]], linejunk=None, charjunk=None, ) if entry1.l_word[0] == entry2.l_word[0]: firstWordLine = f">> {entry1.l_word[0]}" else: firstWordLine = f">> {entry1.l_word[0]} (A)\n>> {entry2.l_word[0]} (B)" entryFormatted = "\n".join( [ firstWordLine, formatDiff(altsDiff), entry1.defi if showDefi else "", ], ) formatted = header + entryFormatted + entrySep write(formatted) count = 0 entry1 = None entry2 = None def step() -> None: nonlocal count, entry1, entry2 if entry1 is None: nextEntry1() if entry2 is None: nextEntry2() words1 = entry1.l_word words2 = entry2.l_word if words1 == words2: if entry1.defi == entry2.defi: entry1, entry2 = None, None return printChangedEntry(entry1, entry2) entry1, entry2 = None, None return if entry1.defi == entry2.defi and (words1[0] in words2 or words2[0] in words1): printAltsChangedEntry(entry1, entry2) entry1, entry2 = None, None return if words1 < words2: printEntry(red, "--- A", index1, entry1) entry1 = None else: printEntry(green, "+++ B", index2, entry2) entry2 = None if (count + 1) % 50 == 0: sys.stdout.flush() count += 1 def run(): # noqa: PLR0912 nonlocal index1, index2 while True: try: infoStep() except StopIteration: break except (OSError, BrokenPipeError): break if infoPair1: printInfo(red, "--- A: ", infoPair1) if infoPair2: printInfo(green, "+++ B: ", infoPair2) for pair in infoIter1: printInfo(red, "--- A: ", pair) for pair in infoIter2: printInfo(green, "+++ B: ", pair) while True: try: step() except StopIteration: break except (OSError, BrokenPipeError): break if entry1: printEntry(red, "--- A", index1, entry1) index1 += 1 if entry2: printEntry(green, "+++ B", index2, entry2) index2 += 1 for entry in iter1: printEntry(red, "--- A", index1, entry) index1 += 1 for entry in iter2: printEntry(green, "+++ B", index2, entry) index2 += 1 try: run() except (OSError, BrokenPipeError): pass # noqa: S110 except Exception as e: print(e) finally: if proc: proc.communicate() # proc.wait() # proc.terminate() sys.stdin.flush() sys.stdout.flush() # NOTE: make sure to set GIT_PAGER or config core.pager # for example GIT_PAGER=less # or GIT_PAGER='less -R -S -N' def gitDiffMain() -> None: # print(sys.argv[1:]) # arguments: # path old_file old_hex old_mode new_file new_hex new_mode old_hex = sys.argv[3][:7] new_hex = sys.argv[6][:7] filename1 = sys.argv[2] filename2 = sys.argv[1] header = f"{'_' * 80}\n\n### File: {filename2} ({old_hex}..{new_hex})\n" resDir = filename2 + "_res" if os.path.isdir(resDir): resDirTmp = filename1 + "_res" os.symlink(os.path.realpath(resDir), resDirTmp) atexit.register(os.remove, resDirTmp) diffGlossary( filename1, filename2, format1=None, format2=None, pager=False, header=header, ) def main() -> None: import os if os.getenv("GIT_DIFF_PATH_COUNTER"): return gitDiffMain() filename1 = sys.argv[1] filename2 = sys.argv[2] format1 = None format2 = None if len(sys.argv) > 3: format1 = sys.argv[3] if len(sys.argv) > 4: format2 = sys.argv[4] filename1 = os.path.expanduser(filename1) filename2 = os.path.expanduser(filename2) diffGlossary( filename1, filename2, format1=format1, format2=format2, pager=True, ) return None if __name__ == "__main__": main()
7,726
Python
.py
300
22.713333
81
0.674318
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,780
view_glossary.py
ilius_pyglossary/pyglossary/ui/tools/view_glossary.py
#!/usr/bin/env python # mypy: ignore-errors from __future__ import annotations import os.path import shlex import sys from collections.abc import Callable from subprocess import PIPE, Popen from typing import TYPE_CHECKING if TYPE_CHECKING: from pyglossary.glossary_types import EntryType, GlossaryType from pyglossary.core import log from pyglossary.glossary_v2 import Glossary from pyglossary.ui.tools.colors import reset, yellow from pyglossary.ui.tools.format_entry import formatEntry Glossary.init() log.setVerbosity(1) noColor = bool(os.getenv("NO_COLOR")) if noColor: yellow = reset = "" # noqa: F811 def getEntryHighlighter() -> Callable[[EntryType], None] | None: if noColor: return None try: import pygments # noqa: F401 except ModuleNotFoundError: return None from pygments import highlight from pygments.formatters import Terminal256Formatter as Formatter from pygments.lexers import HtmlLexer, XmlLexer formatter = Formatter() h_lexer = HtmlLexer() x_lexer = XmlLexer() def highlightEntry(entry: EntryType) -> None: entry.detectDefiFormat() if entry.defiFormat == "h": entry._defi = highlight(entry.defi, h_lexer, formatter) return if entry.defiFormat == "x": entry._defi = highlight(entry.defi, x_lexer, formatter) return return highlightEntry def viewGlossary( filename: str, format: "str | None" = None, glos: "GlossaryType | None" = None, ) -> None: highlightEntry = getEntryHighlighter() if glos is None: glos = Glossary(ui=None) if not glos.directRead(filename, format=format): return pagerCmd = ["less", "-R"] if os.getenv("PAGER"): pagerCmd = shlex.split(os.getenv("PAGER")) proc = Popen( pagerCmd, stdin=PIPE, ) index = 0 entrySep = "_" * 50 def handleEntry(entry: EntryType) -> None: nonlocal index if highlightEntry: highlightEntry(entry) entryStr = ( f"{yellow}#{index}{reset} " + formatEntry(entry) + "\n" + entrySep + "\n\n" ) proc.stdin.write(entryStr.encode("utf-8")) if (index + 1) % 50 == 0: sys.stdout.flush() index += 1 try: for entry in glos: try: handleEntry(entry) except (OSError, BrokenPipeError): break except (OSError, BrokenPipeError): pass # noqa: S110 except Exception as e: print(e) finally: proc.communicate() # proc.wait() # proc.terminate() sys.stdin.flush() sys.stdout.flush() def main() -> None: filename = sys.argv[1] format = None if len(sys.argv) > 2: format = sys.argv[2] filename = os.path.expanduser(filename) viewGlossary(filename, format=format) if __name__ == "__main__": main()
2,589
Python
.py
97
24.154639
78
0.735413
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,781
format_entry.py
ilius_pyglossary/pyglossary/ui/tools/format_entry.py
from __future__ import annotations from typing import TYPE_CHECKING if TYPE_CHECKING: from pyglossary.glossary_types import EntryType __all__ = ["formatEntry"] def formatEntry(entry: EntryType) -> str: words = entry.l_word headword = "" if words: headword = words[0] lines = [ f">> {headword}", ] if len(words) > 1: lines += [f"Alt: {alt}" for alt in words[1:]] lines.append(f"\n{entry.defi}") return "\n".join(lines)
438
Python
.py
17
23.588235
48
0.694712
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,782
word_diff.py
ilius_pyglossary/pyglossary/ui/tools/word_diff.py
from __future__ import annotations import difflib import re import sys from collections.abc import Iterator from pyglossary.ui.tools.colors import green, red, reset __all__ = ["formatDiff", "xmlDiff"] wordRE = re.compile(r"(\W)", re.MULTILINE) xmlTagRE = re.compile( "</?[a-z][0-9a-z]* *[^<>]*>", re.IGNORECASE | re.MULTILINE, ) def plainWordSplit(text: str) -> list[str]: return [word for word in wordRE.split(text) if word] def xmlWordSplit(text: str) -> list[str]: pos = 0 words = [] for m in xmlTagRE.finditer(text): start, end = m.span() match = m.group() if start > pos: words += plainWordSplit(text[pos:start]) words.append(match) pos = end if pos < len(text): words += plainWordSplit(text[pos:]) return words def xmlDiff(text1: str, text2: str) -> Iterator[str]: words1 = xmlWordSplit(text1) words2 = xmlWordSplit(text2) return difflib.ndiff(words1, words2, linejunk=None, charjunk=None) def formatDiff(diff: "Iterator[str]") -> str: res = "" for part in diff: if part[0] == " ": res += part[2:] continue if part[0] == "-": res += red + part[2:] + reset continue if part[0] == "+": res += green + part[2:] + reset continue return res def main_word_split() -> None: text = sys.argv[1] print(text) for word in xmlWordSplit(text): print(f"word: {word!r}") def main() -> None: filename1 = sys.argv[1] filename2 = sys.argv[2] with open(filename1, encoding="utf-8") as _file: text1 = _file.read() with open(filename2, encoding="utf-8") as _file: text2 = _file.read() print(formatDiff(xmlDiff(text1, text2))) if __name__ == "__main__": main()
1,633
Python
.py
59
25.169492
67
0.674823
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,783
__init__.py
ilius_pyglossary/pyglossary/ui/progressbar/__init__.py
# -*- coding: utf-8 -*- # # progressbar - Text progress bar library for Python. # Copyright (c) 2005 Nilton Volpato # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """ Text progress bar library for Python. A text progress bar is typically used to display the progress of a long running operation, providing a visual cue that processing is underway. The ProgressBar class manages the current progress, and the format of the line is given by a number of widgets. A widget is an object that may display differently depending on the state of the progress bar. There are three types of widgets: - a string, which always shows itself - a ProgressBarWidget, which may return a different value every time its update method is called - a ProgressBarWidgetHFill, which is like ProgressBarWidget, except it expands to fill the remaining width of the line. The progressbar module is very easy to use, yet very powerful. It will also automatically enable features like auto-resizing when the system supports it. """ __author__ = 'Nilton Volpato' __author_email__ = 'nilton.volpato@gmail.com' __date__ = '2011-05-14' __version__ = '2.5' from .progressbar import * # noqa: F403 from .widgets import * # noqa: F403
1,897
Python
.py
40
46
78
0.777177
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,784
widgets.py
ilius_pyglossary/pyglossary/ui/progressbar/widgets.py
# -*- coding: utf-8 -*- # mypy: ignore-errors # # progressbar - Text progress bar library for Python. # Copyright (c) 2005 Nilton Volpato # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA """Default ProgressBar widgets.""" from __future__ import annotations from __future__ import division import datetime import math try: from abc import ABCMeta, abstractmethod except ImportError: AbstractWidget = object def abstractmethod(fn): return fn else: AbstractWidget = ABCMeta('AbstractWidget', (object,), {}) class UnknownLength: pass def format_updatable(updatable, pbar): if hasattr(updatable, 'update'): return updatable.update(pbar) return updatable class Widget(AbstractWidget): """ The base class for all widgets. The ProgressBar will call the widget's update value when the widget should be updated. The widget's size may change between calls, but the widget may display incorrectly if the size changes drastically and repeatedly. The boolean TIME_SENSITIVE informs the ProgressBar that it should be updated more often because it is time sensitive. """ TIME_SENSITIVE = False __slots__ = () @abstractmethod def update(self, pbar): """ Updates the widget. pbar - a reference to the calling ProgressBar """ class WidgetHFill(Widget): """ The base class for all variable width widgets. This widget is much like the \\hfill command in TeX, it will expand to fill the line. You can use more than one in the same line, and they will all have the same width, and together will fill the line. """ @abstractmethod def update(self, pbar, width): """ Updates the widget providing the total width the widget must fill. pbar - a reference to the calling ProgressBar width - The total width the widget must fill """ class Timer(Widget): """Widget which displays the elapsed seconds.""" __slots__ = ('format_string',) TIME_SENSITIVE = True def __init__(self, format='Elapsed Time: %s') -> None: self.format_string = format @staticmethod def format_time(seconds): """Formats time as the string "HH:MM:SS".""" return str(datetime.timedelta(seconds=int(seconds))) def update(self, pbar): """Updates the widget to show the elapsed time.""" return self.format_string % self.format_time(pbar.seconds_elapsed) class ETA(Timer): """Widget which attempts to estimate the time of arrival.""" TIME_SENSITIVE = True def update(self, pbar): """Updates the widget to show the ETA or total time when finished.""" if pbar.maxval is UnknownLength or pbar.currval == 0: return 'ETA: --:--:--' if pbar.finished: return f'Time: {self.format_time(pbar.seconds_elapsed)}' elapsed = pbar.seconds_elapsed eta = elapsed * pbar.maxval / pbar.currval - elapsed return f'ETA: {self.format_time(eta)}' class AdaptiveETA(Timer): """ Widget which attempts to estimate the time of arrival. Uses a weighted average of two estimates: 1) ETA based on the total progress and time elapsed so far 2) ETA based on the progress as per the last 10 update reports The weight depends on the current progress so that to begin with the total progress is used and at the end only the most recent progress is used. """ TIME_SENSITIVE = True NUM_SAMPLES = 10 def _update_samples(self, currval, elapsed): sample = (currval, elapsed) if not hasattr(self, 'samples'): self.samples = [sample] * (self.NUM_SAMPLES + 1) else: self.samples.append(sample) return self.samples.pop(0) def _eta(self, maxval, currval, elapsed): return elapsed * maxval / float(currval) - elapsed def update(self, pbar): """Updates the widget to show the ETA or total time when finished.""" if pbar.maxval is UnknownLength or pbar.currval == 0: return 'ETA: --:--:--' if pbar.finished: return f'Time: {self.format_time(pbar.seconds_elapsed)}' elapsed = pbar.seconds_elapsed currval1, elapsed1 = self._update_samples(pbar.currval, elapsed) eta = self._eta(pbar.maxval, pbar.currval, elapsed) if pbar.currval > currval1: etasamp = self._eta(pbar.maxval - currval1, pbar.currval - currval1, elapsed - elapsed1) weight = (pbar.currval / float(pbar.maxval)) ** 0.5 eta = (1 - weight) * eta + weight * etasamp return f'ETA: {self.format_time(eta)}' class FileTransferSpeed(Widget): """Widget for showing the transfer speed (useful for file transfers).""" FMT = '%6.2f %s%s/s' PREFIXES = ' kMGTPEZY' __slots__ = ('unit',) def __init__(self, unit='B') -> None: self.unit = unit def update(self, pbar): """Updates the widget with the current SI prefixed speed.""" if pbar.seconds_elapsed < 2e-6 or pbar.currval < 2e-6: # =~ 0 scaled = power = 0 else: speed = pbar.currval / pbar.seconds_elapsed power = int(math.log(speed, 1000)) scaled = speed / 1000.**power return self.FMT % (scaled, self.PREFIXES[power], self.unit) class AnimatedMarker(Widget): """ An animated marker for the progress bar which defaults to appear as if it were rotating. """ __slots__ = ('markers', 'curmark') def __init__(self, markers='|/-\\') -> None: self.markers = markers self.curmark = -1 def update(self, pbar): """ Updates the widget to show the next marker or the first marker when finished. """ if pbar.finished: return self.markers[0] self.curmark = (self.curmark + 1) % len(self.markers) return self.markers[self.curmark] # Alias for backwards compatibility RotatingMarker = AnimatedMarker class Counter(Widget): """Displays the current count.""" __slots__ = ('format_string',) def __init__(self, format='%d') -> None: self.format_string = format def update(self, pbar): return self.format_string % pbar.currval class Percentage(Widget): """Displays the current percentage as a number with a percent sign.""" def __init__(self, prefix="%") -> None: Widget.__init__(self) self.prefix = prefix def update(self, pbar): return f"{self.prefix}{pbar.percentage():.1f}"\ .rjust(5 + len(self.prefix)) class FormatLabel(Timer): """Displays a formatted label.""" mapping = { 'elapsed': ('seconds_elapsed', Timer.format_time), 'finished': ('finished', None), 'last_update': ('last_update_time', None), 'max': ('maxval', None), 'seconds': ('seconds_elapsed', None), 'start': ('start_time', None), 'value': ('currval', None), } __slots__ = ('format_string',) def __init__(self, format) -> None: self.format_string = format def update(self, pbar): context = {} for name, (key, transform) in self.mapping.items(): try: value = getattr(pbar, key) if transform is None: context[name] = value else: context[name] = transform(value) except: # noqa: E722 pass # noqa: S110 return self.format_string % context class SimpleProgress(Widget): """Returns progress as a count of the total (e.g.: "5 of 47").""" __slots__ = ('sep',) def __init__(self, sep=' of ') -> None: self.sep = sep def update(self, pbar): if pbar.maxval is UnknownLength: return '%d%s?' % (pbar.currval, self.sep) return '%d%s%s' % (pbar.currval, self.sep, pbar.maxval) class Bar(WidgetHFill): """A progress bar which stretches to fill the line.""" __slots__ = ('marker', 'left', 'right', 'fill', 'fill_left') def __init__(self, marker='#', left='|', right='|', fill=' ', fill_left=True) -> None: """ Creates a customizable progress bar. marker - string or updatable object to use as a marker left - string or updatable object to use as a left border right - string or updatable object to use as a right border fill - character to use for the empty part of the progress bar fill_left - whether to fill from the left or the right """ self.marker = marker self.left = left self.right = right self.fill = fill self.fill_left = fill_left def update(self, pbar, width): """Updates the progress bar and its subcomponents.""" left, marked, right = ( format_updatable(i, pbar) for i in (self.left, self.marker, self.right) ) width -= len(left) + len(right) # Marked must *always* have length of 1 if pbar.maxval is not UnknownLength and pbar.maxval: marked *= int(pbar.currval / pbar.maxval * width) else: marked = '' if self.fill_left: return f'{left}{marked.ljust(width, self.fill)}{right}' return f'{left}{marked.rjust(width, self.fill)}{right}' class ReverseBar(Bar): """A bar which has a marker which bounces from side to side.""" def __init__(self, marker='#', left='|', right='|', fill=' ', fill_left=False) -> None: """ Creates a customizable progress bar. marker - string or updatable object to use as a marker left - string or updatable object to use as a left border right - string or updatable object to use as a right border fill - character to use for the empty part of the progress bar fill_left - whether to fill from the left or the right """ self.marker = marker self.left = left self.right = right self.fill = fill self.fill_left = fill_left class BouncingBar(Bar): def update(self, pbar, width): """Updates the progress bar and its subcomponents.""" left, marker, right = (format_updatable(i, pbar) for i in (self.left, self.marker, self.right)) width -= len(left) + len(right) if pbar.finished: return f'{left}{width * marker}{right}' position = int(pbar.currval % (width * 2 - 1)) if position > width: position = width * 2 - position lpad = self.fill * (position - 1) rpad = self.fill * (width - len(marker) - len(lpad)) # Swap if we want to bounce the other way if not self.fill_left: rpad, lpad = lpad, rpad return f'{left}{lpad}{marker}{rpad}{right}'
11,707
Python
.py
284
33.454225
78
0.623475
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,785
progressbar.py
ilius_pyglossary/pyglossary/ui/progressbar/progressbar.py
# -*- coding: utf-8 -*- # mypy: ignore-errors # # progressbar - Text progress bar library for Python. # Copyright (c) 2023 Saeed Rasooli # Copyright (c) 2005 Nilton Volpato # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA from __future__ import annotations """Main ProgressBar class.""" import math import os import signal import sys import time try: import termios from array import array from fcntl import ioctl except ImportError: pass from . import widgets class ProgressBar: """ The ProgressBar class which updates and prints the bar. A common way of using it is like: >>> pbar = ProgressBar().start() >>> for i in range(100): ... # do something ... pbar.update(i+1) ... >>> pbar.finish() You can also use a ProgressBar as an iterator: >>> progress = ProgressBar() >>> for i in progress(some_iterable): ... # do something ... Since the progress bar is incredibly customizable you can specify different widgets of any type in any order. You can even write your own widgets! However, since there are already a good number of widgets you should probably play around with them before moving on to create your own widgets. The term_width parameter represents the current terminal width. If the parameter is set to an integer then the progress bar will use that, otherwise it will attempt to determine the terminal width falling back to 80 columns if the width cannot be determined. When implementing a widget's update method you are passed a reference to the current progress bar. As a result, you have access to the ProgressBar's methods and attributes. Although there is nothing preventing you from changing the ProgressBar you should treat it as read only. Useful methods and attributes include (Public API): - currval: current progress (0 <= currval <= maxval) - maxval: maximum (and final) value - finished: True if the bar has finished (reached 100%) - start_time: the time when start() method of ProgressBar was called - seconds_elapsed: seconds elapsed since start_time and last call to update - percentage(): progress in percent [0..100] """ __slots__ = ('currval', 'fd', 'finished', 'last_update_time', 'left_justify', 'maxval', 'next_update', 'num_intervals', 'poll', 'seconds_elapsed', 'signal_set', 'start_time', 'term_width', 'update_interval', 'widgets', '_time_sensitive', '__iterable') _DEFAULT_MAXVAL = 100 _DEFAULT_TERMSIZE = 80 _DEFAULT_WIDGETS = [widgets.Percentage(), ' ', widgets.Bar()] def __init__( self, maxval=None, widgets=None, term_width=None, poll=1, left_justify=True, fd=None, ) -> None: """Initializes a progress bar with sane defaults.""" # Don't share a reference with any other progress bars if widgets is None: widgets = list(self._DEFAULT_WIDGETS) self.maxval = maxval self.widgets = widgets self.fd = fd if fd is not None else sys.stderr self.left_justify = left_justify self.signal_set = False if term_width is not None: self.term_width = term_width else: try: self._handle_resize() signal.signal(signal.SIGWINCH, self._handle_resize) self.signal_set = True except (SystemExit, KeyboardInterrupt): raise except: # noqa: E722 self.term_width = self._env_size() self.__iterable = None self._update_widgets() self.currval = 0 self.finished = False self.last_update_time = None self.poll = poll self.seconds_elapsed = 0 self.start_time = None self.update_interval = 1 self.next_update = 0 def __call__(self, iterable): """Use a ProgressBar to iterate through an iterable.""" try: self.maxval = len(iterable) except TypeError: if self.maxval is None: self.maxval = widgets.UnknownLength self.__iterable = iter(iterable) return self def __iter__(self): return self def __next__(self): try: value = next(self.__iterable) if self.start_time is None: self.start() else: self.update(self.currval + 1) return value except StopIteration: if self.start_time is None: self.start() self.finish() raise def _env_size(self): """Tries to find the term_width from the environment.""" return int(os.environ.get('COLUMNS', self._DEFAULT_TERMSIZE)) - 1 def _handle_resize(self, signum=None, frame=None): """Tries to catch resize signals sent from the terminal.""" h, w = array('h', ioctl(self.fd, termios.TIOCGWINSZ, '\0' * 8))[:2] self.term_width = w def percentage(self): """Returns the progress as a percentage.""" if self.maxval is widgets.UnknownLength: return float("NaN") if self.currval >= self.maxval: return 100.0 return (self.currval * 100.0 / self.maxval) if self.maxval else 100.00 percent = property(percentage) def _format_widgets(self): result = [] expanding = [] width = self.term_width for index, widget in enumerate(self.widgets): if isinstance(widget, widgets.WidgetHFill): result.append(widget) expanding.insert(0, index) else: widget = widgets.format_updatable(widget, self) result.append(widget) width -= len(widget) count = len(expanding) while count: portion = max(int(math.ceil(width * 1. / count)), 0) index = expanding.pop() count -= 1 widget = result[index].update(self, portion) width -= len(widget) result[index] = widget return result def _format_line(self): """Joins the widgets and justifies the line.""" widgets = ''.join(self._format_widgets()) if self.left_justify: return widgets.ljust(self.term_width) return widgets.rjust(self.term_width) def _need_update(self): """Returns whether the ProgressBar should redraw the line.""" if self.currval >= self.next_update or self.finished: return True return self._time_sensitive and time.perf_counter() - self.last_update_time > self.poll def _update_widgets(self): """Checks all widgets for the time sensitive bit.""" self._time_sensitive = any( getattr(w, 'TIME_SENSITIVE', False) for w in self.widgets ) def update(self, value=None): """Updates the ProgressBar to a new value.""" if value is not None and value is not widgets.UnknownLength: if ( self.maxval is not widgets.UnknownLength and not 0 <= value <= self.maxval ): raise ValueError('Value out of range') self.currval = value if not self._need_update(): return if self.start_time is None: raise RuntimeError('You must call "start" before calling "update"') now = time.perf_counter() self.seconds_elapsed = now - self.start_time self.next_update = self.currval + self.update_interval self.fd.write(self._format_line() + '\r') self.fd.flush() self.last_update_time = now def start(self, num_intervals=0): """ Starts measuring time, and prints the bar at 0%. It returns self so you can use it like this: >>> pbar = ProgressBar().start() >>> for i in range(100): ... # do something ... pbar.update(i+1) ... >>> pbar.finish() """ if self.maxval is None: self.maxval = self._DEFAULT_MAXVAL if num_intervals > 0: self.num_intervals = num_intervals else: self.num_intervals = max(100, self.term_width) self.next_update = 0 if self.maxval is not widgets.UnknownLength: if self.maxval < 0: raise ValueError('Value out of range') self.update_interval = self.maxval / self.num_intervals self.start_time = self.last_update_time = time.perf_counter() self.update(0) return self def finish(self): """Puts the ProgressBar bar in the finished state.""" if self.finished: return self.finished = True self.update(self.maxval) self.fd.write('\n') if self.signal_set: signal.signal(signal.SIGWINCH, signal.SIG_DFL)
9,759
Python
.py
248
30.645161
95
0.612661
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,786
about.py
ilius_pyglossary/pyglossary/ui/gtk3_utils/about.py
# -*- coding: utf-8 -*- # mypy: ignore-errors # # Copyright © 2020 Saeed Rasooli <saeed.gnu@gmail.com> (ilius) # # This program is a free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # You can get a copy of GNU General Public License along this program # But you can always get it from http://www.gnu.org/licenses/gpl.txt # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. from __future__ import annotations from . import gtk from .utils import ( VBox, imageFromFile, pack, ) __all__ = ["AboutWidget"] class AboutWidget(gtk.Box): def __init__( # noqa: PLR0913 self, logo: str = "", header: str = "", about: str = "", authors: str = "", license_text: str = "", **_kwargs, ) -> None: gtk.Box.__init__(self, orientation=gtk.Orientation.VERTICAL) ## headerBox = gtk.Box(orientation=gtk.Orientation.HORIZONTAL) if logo: headerBox.pack_start(imageFromFile(logo), False, False, 0) headerLabel = gtk.Label(label=header) headerLabel.set_selectable(True) headerLabel.set_can_focus(False) headerBox.pack_start(headerLabel, False, False, 15) headerBox.show_all() self.pack_start(headerBox, False, False, 0) ## notebook = gtk.Notebook() self.notebook = notebook self.pack_start(notebook, True, True, 5) notebook.set_tab_pos(gtk.PositionType.LEFT) notebook.set_can_focus(True) ## tab1_about = self.newTabLabelWidget(about) tab2_authors = self.newTabWidgetTextView(authors) tab3_license = self.newTabWidgetTextView(license_text) ## tabs = [ (tab1_about, self.newTabTitle("About", "dialog-information-22.png")), (tab2_authors, self.newTabTitle("Authors", "author-22.png")), (tab3_license, self.newTabTitle("License", "license-22.png")), ] ## for widget, titleW in tabs: notebook.append_page(widget, titleW) ## self.show_all() # <a href="...">Something</a> does not work with TextView @staticmethod def newTabWidgetTextView( text: str, wrap: bool = False, justification: gtk.Justification | None = None, ): tv = gtk.TextView() tv.set_editable(False) tv.set_can_focus(False) if wrap: tv.set_wrap_mode(gtk.WrapMode.WORD) if justification is not None: tv.set_justification(justification) tv.set_cursor_visible(False) tv.set_border_width(10) buf = tv.get_buffer() # buf.insert_markup(buf.get_end_iter(), markup=text, # len=len(text.encode("utf-8"))) buf.set_text(text) tv.show_all() swin = gtk.ScrolledWindow() swin.set_policy(gtk.PolicyType.AUTOMATIC, gtk.PolicyType.AUTOMATIC) swin.set_border_width(0) swin.add(tv) return swin @staticmethod def newTabLabelWidget( text: str, # wrap: bool = False, # justification: "gtk.Justification | None" = None, ): box = VBox() box.set_border_width(10) label = gtk.Label() label.set_selectable(True) label.set_xalign(0) label.set_yalign(0) pack(box, label, 0, 0) # if wrap: # tv.set_wrap_mode(gtk.WrapMode.WORD) # if justification is not None: # tv.set_justification(justification) label.set_can_focus(False) # label.set_border_width(10) label.set_markup(text) label.show_all() swin = gtk.ScrolledWindow() swin.set_policy(gtk.PolicyType.AUTOMATIC, gtk.PolicyType.AUTOMATIC) swin.set_border_width(0) swin.add(box) return swin @staticmethod def newTabTitle(title: str, icon: str): box = gtk.Box(orientation=gtk.Orientation.VERTICAL) if icon: box.pack_start(imageFromFile(icon), False, False, 5) if title: box.pack_start(gtk.Label(label=title), False, False, 5) box.show_all() return box
3,880
Python
.py
128
27.640625
72
0.724552
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,787
dialog.py
ilius_pyglossary/pyglossary/ui/gtk3_utils/dialog.py
# -*- coding: utf-8 -*- # mypy: ignore-errors # # Copyright © 2016-2017 Saeed Rasooli <saeed.gnu@gmail.com> (ilius) # # This program is a free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # You can get a copy of GNU General Public License along this program # But you can always get it from http://www.gnu.org/licenses/gpl.txt # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. from gi.repository import Gdk as gdk from gi.repository import Gtk as gtk __all__ = ["MyDialog"] class MyDialog: def startWaiting(self): self.queue_draw() self.vbox.set_sensitive(False) self.get_window().set_cursor(gdk.Cursor.new(gdk.CursorType.WATCH)) while gtk.events_pending(): gtk.main_iteration_do(False) def endWaiting(self): self.get_window().set_cursor(gdk.Cursor.new(gdk.CursorType.LEFT_PTR)) self.vbox.set_sensitive(True) def waitingDo(self, func, *args, **kwargs): self.startWaiting() try: func(*args, **kwargs) except Exception as e: raise e finally: self.endWaiting()
1,361
Python
.py
38
33.710526
72
0.756079
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,788
utils.py
ilius_pyglossary/pyglossary/ui/gtk3_utils/utils.py
# -*- coding: utf-8 -*- # mypy: ignore-errors # # Copyright © 2016-2019 Saeed Rasooli <saeed.gnu@gmail.com> (ilius) # # This program is a free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # You can get a copy of GNU General Public License along this program # But you can always get it from http://www.gnu.org/licenses/gpl.txt # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. from __future__ import annotations import logging from os.path import isabs, join from gi.repository import Pango as pango from pyglossary.core import appResDir from . import gdk, gtk __all__ = [ "HBox", "VBox", "dialog_add_button", "imageFromFile", "pack", "rgba_parse", "set_tooltip", "showInfo", ] log = logging.getLogger("pyglossary") def VBox(**kwargs): return gtk.Box(orientation=gtk.Orientation.VERTICAL, **kwargs) def HBox(**kwargs): return gtk.Box(orientation=gtk.Orientation.HORIZONTAL, **kwargs) def set_tooltip(widget, text): try: widget.set_tooltip_text(text) # PyGTK 2.12 or above except AttributeError: try: widget.set_tooltip(gtk.Tooltips(), text) except Exception: log.exception("") def imageFromFile(path): # the file must exist if not isabs(path): path = join(appResDir, path) im = gtk.Image() try: im.set_from_file(path) except Exception: log.exception("") return im def imageFromIconName(iconName: str, size: int, nonStock=False) -> gtk.Image: # So gtk.Image.new_from_stock is deprecated # And the doc says we should use gtk.Image.new_from_icon_name # which does NOT have the same functionality! # because not all stock items are existing in all themes (even popular themes) # and new_from_icon_name does not seem to look in other (non-default) themes! # So for now we use new_from_stock, unless it's not a stock item # But we do not use either of these two outside this function # So that it's easy to switch if nonStock: return gtk.Image.new_from_icon_name(iconName, size) try: return gtk.Image.new_from_stock(iconName, size) except Exception: return gtk.Image.new_from_icon_name(iconName, size) def rgba_parse(colorStr): rgba = gdk.RGBA() if not rgba.parse(colorStr): raise ValueError(f"bad color string {colorStr!r}") return rgba def color_parse(colorStr): return rgba_parse(colorStr).to_color() def pack(box, child, expand=False, fill=False, padding=0): if isinstance(box, gtk.Box): box.pack_start(child, expand, fill, padding) elif isinstance(box, gtk.CellLayout): box.pack_start(child, expand) else: raise TypeError(f"pack: unknown type {type(box)}") def dialog_add_button( dialog, _iconName, label, resId, onClicked=None, tooltip="", ): b = dialog.add_button(label, resId) if onClicked: b.connect("clicked", onClicked) if tooltip: set_tooltip(b, tooltip) return b def showMsg( # noqa: PLR0913 msg, iconName="", parent=None, transient_for=None, title="", borderWidth=10, iconSize=gtk.IconSize.DIALOG, selectable=False, ): win = gtk.Dialog( parent=parent, transient_for=transient_for, ) # flags=0 makes it skip task bar if title: win.set_title(title) hbox = HBox(spacing=10) hbox.set_border_width(borderWidth) if iconName: # win.set_icon(...) pack(hbox, imageFromIconName(iconName, iconSize)) label = gtk.Label(label=msg) # set_line_wrap(True) makes the window go crazy tall (taller than screen) # and that's the reason for label.set_size_request and win.resize label.set_line_wrap(True) label.set_line_wrap_mode(pango.WrapMode.WORD) label.set_size_request(500, 1) if selectable: label.set_selectable(True) pack(hbox, label) hbox.show_all() pack(win.vbox, hbox) dialog_add_button( win, "gtk-close", "_Close", gtk.ResponseType.OK, ) win.resize(600, 1) win.run() win.destroy() def showError(msg, **kwargs): # gtk-dialog-error is deprecated since version 3.10: # Use named icon “dialog-error”. showMsg(msg, iconName="gtk-dialog-error", **kwargs) def showWarning(msg, **kwargs): # gtk-dialog-warning is deprecated since version 3.10: # Use named icon “dialog-warning”. showMsg(msg, iconName="gtk-dialog-warning", **kwargs) def showInfo(msg, **kwargs): # gtk-dialog-info is deprecated since version 3.10: # Use named icon “dialog-information”. showMsg(msg, iconName="gtk-dialog-info", **kwargs)
4,643
Python
.py
152
28.322368
79
0.749381
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,789
__init__.py
ilius_pyglossary/pyglossary/ui/gtk3_utils/__init__.py
# mypy: ignore-errors # do not sort these imports! from gi.repository import Gtk as gtk # noqa: I001 from gi.repository import Gdk as gdk # noqa: I001
153
Python
.py
4
37.25
50
0.758389
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,790
resize_button.py
ilius_pyglossary/pyglossary/ui/gtk3_utils/resize_button.py
# -*- coding: utf-8 -*- # mypy: ignore-errors # # Copyright © 2016-2017 Saeed Rasooli <saeed.gnu@gmail.com> (ilius) # # This program is a free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3, or (at your option) # any later version. # # You can get a copy of GNU General Public License along this program # But you can always get it from http://www.gnu.org/licenses/gpl.txt # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. from __future__ import annotations from . import gdk, gtk from .utils import imageFromFile __all__ = ["ResizeButton"] class ResizeButton(gtk.EventBox): def __init__(self, win, edge=gdk.WindowEdge.SOUTH_EAST) -> None: gtk.EventBox.__init__(self) self.win = win self.edge = edge ### self.image = imageFromFile("resize.png") self.add(self.image) self.connect("button-press-event", self.buttonPress) def buttonPress(self, _obj, gevent): self.win.begin_resize_drag( self.edge, gevent.button, int(gevent.x_root), int(gevent.y_root), gevent.time, )
1,322
Python
.py
38
32.684211
72
0.743931
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,791
table_zero.py
ilius_pyglossary/pyglossary/ui/wcwidth/table_zero.py
'\nExports ZERO_WIDTH table keyed by supporting unicode version level.\n\nThis code generated by wcwidth/bin/update-tables.py on 2024-01-04 07:14:52 UTC.\n' ZERO_WIDTH={'4.1.0':((0,0),(173,173),(768,879),(1155,1158),(1160,1161),(1425,1465),(1467,1469),(1471,1471),(1473,1474),(1476,1477),(1479,1479),(1536,1539),(1552,1557),(1611,1630),(1648,1648),(1750,1764),(1767,1768),(1770,1773),(1807,1807),(1809,1809),(1840,1866),(1958,1968),(2305,2307),(2364,2364),(2366,2381),(2385,2388),(2402,2403),(2433,2435),(2492,2492),(2494,2500),(2503,2504),(2507,2509),(2519,2519),(2530,2531),(2561,2563),(2620,2620),(2622,2626),(2631,2632),(2635,2637),(2672,2673),(2689,2691),(2748,2748),(2750,2757),(2759,2761),(2763,2765),(2786,2787),(2817,2819),(2876,2876),(2878,2883),(2887,2888),(2891,2893),(2902,2903),(2946,2946),(3006,3010),(3014,3016),(3018,3021),(3031,3031),(3073,3075),(3134,3140),(3142,3144),(3146,3149),(3157,3158),(3202,3203),(3260,3260),(3262,3268),(3270,3272),(3274,3277),(3285,3286),(3330,3331),(3390,3395),(3398,3400),(3402,3405),(3415,3415),(3458,3459),(3530,3530),(3535,3540),(3542,3542),(3544,3551),(3570,3571),(3633,3633),(3636,3642),(3655,3662),(3761,3761),(3764,3769),(3771,3772),(3784,3789),(3864,3865),(3893,3893),(3895,3895),(3897,3897),(3902,3903),(3953,3972),(3974,3975),(3984,3991),(3993,4028),(4038,4038),(4140,4146),(4150,4153),(4182,4185),(4448,4607),(4959,4959),(5906,5908),(5938,5940),(5970,5971),(6002,6003),(6068,6099),(6109,6109),(6155,6157),(6313,6313),(6432,6443),(6448,6459),(6576,6592),(6600,6601),(6679,6683),(7616,7619),(8203,8207),(8232,8238),(8288,8291),(8298,8303),(8400,8427),(12330,12335),(12441,12442),(43010,43010),(43014,43014),(43019,43019),(43043,43047),(55216,55295),(64286,64286),(65024,65039),(65056,65059),(65279,65279),(65529,65531),(68097,68099),(68101,68102),(68108,68111),(68152,68154),(68159,68159),(119141,119145),(119149,119170),(119173,119179),(119210,119213),(119362,119364),(917505,917505),(917536,917631),(917760,917999)),'5.0.0':((0,0),(173,173),(768,879),(1155,1158),(1160,1161),(1425,1469),(1471,1471),(1473,1474),(1476,1477),(1479,1479),(1536,1539),(1552,1557),(1611,1630),(1648,1648),(1750,1764),(1767,1768),(1770,1773),(1807,1807),(1809,1809),(1840,1866),(1958,1968),(2027,2035),(2305,2307),(2364,2364),(2366,2381),(2385,2388),(2402,2403),(2433,2435),(2492,2492),(2494,2500),(2503,2504),(2507,2509),(2519,2519),(2530,2531),(2561,2563),(2620,2620),(2622,2626),(2631,2632),(2635,2637),(2672,2673),(2689,2691),(2748,2748),(2750,2757),(2759,2761),(2763,2765),(2786,2787),(2817,2819),(2876,2876),(2878,2883),(2887,2888),(2891,2893),(2902,2903),(2946,2946),(3006,3010),(3014,3016),(3018,3021),(3031,3031),(3073,3075),(3134,3140),(3142,3144),(3146,3149),(3157,3158),(3202,3203),(3260,3260),(3262,3268),(3270,3272),(3274,3277),(3285,3286),(3298,3299),(3330,3331),(3390,3395),(3398,3400),(3402,3405),(3415,3415),(3458,3459),(3530,3530),(3535,3540),(3542,3542),(3544,3551),(3570,3571),(3633,3633),(3636,3642),(3655,3662),(3761,3761),(3764,3769),(3771,3772),(3784,3789),(3864,3865),(3893,3893),(3895,3895),(3897,3897),(3902,3903),(3953,3972),(3974,3975),(3984,3991),(3993,4028),(4038,4038),(4140,4146),(4150,4153),(4182,4185),(4448,4607),(4959,4959),(5906,5908),(5938,5940),(5970,5971),(6002,6003),(6068,6099),(6109,6109),(6155,6157),(6313,6313),(6432,6443),(6448,6459),(6576,6592),(6600,6601),(6679,6683),(6912,6916),(6964,6980),(7019,7027),(7616,7626),(7678,7679),(8203,8207),(8232,8238),(8288,8291),(8298,8303),(8400,8431),(12330,12335),(12441,12442),(43010,43010),(43014,43014),(43019,43019),(43043,43047),(55216,55295),(64286,64286),(65024,65039),(65056,65059),(65279,65279),(65529,65531),(68097,68099),(68101,68102),(68108,68111),(68152,68154),(68159,68159),(119141,119145),(119149,119170),(119173,119179),(119210,119213),(119362,119364),(917505,917505),(917536,917631),(917760,917999)),'5.1.0':((0,0),(173,173),(768,879),(1155,1161),(1425,1469),(1471,1471),(1473,1474),(1476,1477),(1479,1479),(1536,1539),(1552,1562),(1611,1630),(1648,1648),(1750,1764),(1767,1768),(1770,1773),(1807,1807),(1809,1809),(1840,1866),(1958,1968),(2027,2035),(2305,2307),(2364,2364),(2366,2381),(2385,2388),(2402,2403),(2433,2435),(2492,2492),(2494,2500),(2503,2504),(2507,2509),(2519,2519),(2530,2531),(2561,2563),(2620,2620),(2622,2626),(2631,2632),(2635,2637),(2641,2641),(2672,2673),(2677,2677),(2689,2691),(2748,2748),(2750,2757),(2759,2761),(2763,2765),(2786,2787),(2817,2819),(2876,2876),(2878,2884),(2887,2888),(2891,2893),(2902,2903),(2914,2915),(2946,2946),(3006,3010),(3014,3016),(3018,3021),(3031,3031),(3073,3075),(3134,3140),(3142,3144),(3146,3149),(3157,3158),(3170,3171),(3202,3203),(3260,3260),(3262,3268),(3270,3272),(3274,3277),(3285,3286),(3298,3299),(3330,3331),(3390,3396),(3398,3400),(3402,3405),(3415,3415),(3426,3427),(3458,3459),(3530,3530),(3535,3540),(3542,3542),(3544,3551),(3570,3571),(3633,3633),(3636,3642),(3655,3662),(3761,3761),(3764,3769),(3771,3772),(3784,3789),(3864,3865),(3893,3893),(3895,3895),(3897,3897),(3902,3903),(3953,3972),(3974,3975),(3984,3991),(3993,4028),(4038,4038),(4139,4158),(4182,4185),(4190,4192),(4194,4196),(4199,4205),(4209,4212),(4226,4237),(4239,4239),(4448,4607),(4959,4959),(5906,5908),(5938,5940),(5970,5971),(6002,6003),(6068,6099),(6109,6109),(6155,6157),(6313,6313),(6432,6443),(6448,6459),(6576,6592),(6600,6601),(6679,6683),(6912,6916),(6964,6980),(7019,7027),(7040,7042),(7073,7082),(7204,7223),(7616,7654),(7678,7679),(8203,8207),(8232,8238),(8288,8292),(8298,8303),(8400,8432),(11744,11775),(12330,12335),(12441,12442),(42607,42610),(42620,42621),(43010,43010),(43014,43014),(43019,43019),(43043,43047),(43136,43137),(43188,43204),(43302,43309),(43335,43347),(43561,43574),(43587,43587),(43596,43597),(55216,55295),(64286,64286),(65024,65039),(65056,65062),(65279,65279),(65529,65531),(66045,66045),(68097,68099),(68101,68102),(68108,68111),(68152,68154),(68159,68159),(119141,119145),(119149,119170),(119173,119179),(119210,119213),(119362,119364),(917505,917505),(917536,917631),(917760,917999)),'5.2.0':((0,0),(173,173),(768,879),(1155,1161),(1425,1469),(1471,1471),(1473,1474),(1476,1477),(1479,1479),(1536,1539),(1552,1562),(1611,1630),(1648,1648),(1750,1764),(1767,1768),(1770,1773),(1807,1807),(1809,1809),(1840,1866),(1958,1968),(2027,2035),(2070,2073),(2075,2083),(2085,2087),(2089,2093),(2304,2307),(2364,2364),(2366,2382),(2385,2389),(2402,2403),(2433,2435),(2492,2492),(2494,2500),(2503,2504),(2507,2509),(2519,2519),(2530,2531),(2561,2563),(2620,2620),(2622,2626),(2631,2632),(2635,2637),(2641,2641),(2672,2673),(2677,2677),(2689,2691),(2748,2748),(2750,2757),(2759,2761),(2763,2765),(2786,2787),(2817,2819),(2876,2876),(2878,2884),(2887,2888),(2891,2893),(2902,2903),(2914,2915),(2946,2946),(3006,3010),(3014,3016),(3018,3021),(3031,3031),(3073,3075),(3134,3140),(3142,3144),(3146,3149),(3157,3158),(3170,3171),(3202,3203),(3260,3260),(3262,3268),(3270,3272),(3274,3277),(3285,3286),(3298,3299),(3330,3331),(3390,3396),(3398,3400),(3402,3405),(3415,3415),(3426,3427),(3458,3459),(3530,3530),(3535,3540),(3542,3542),(3544,3551),(3570,3571),(3633,3633),(3636,3642),(3655,3662),(3761,3761),(3764,3769),(3771,3772),(3784,3789),(3864,3865),(3893,3893),(3895,3895),(3897,3897),(3902,3903),(3953,3972),(3974,3975),(3984,3991),(3993,4028),(4038,4038),(4139,4158),(4182,4185),(4190,4192),(4194,4196),(4199,4205),(4209,4212),(4226,4237),(4239,4239),(4250,4253),(4448,4607),(4959,4959),(5906,5908),(5938,5940),(5970,5971),(6002,6003),(6068,6099),(6109,6109),(6155,6157),(6313,6313),(6432,6443),(6448,6459),(6576,6592),(6600,6601),(6679,6683),(6741,6750),(6752,6780),(6783,6783),(6912,6916),(6964,6980),(7019,7027),(7040,7042),(7073,7082),(7204,7223),(7376,7378),(7380,7400),(7405,7405),(7410,7410),(7616,7654),(7677,7679),(8203,8207),(8232,8238),(8288,8292),(8298,8303),(8400,8432),(11503,11505),(11744,11775),(12330,12335),(12441,12442),(42607,42610),(42620,42621),(42736,42737),(43010,43010),(43014,43014),(43019,43019),(43043,43047),(43136,43137),(43188,43204),(43232,43249),(43302,43309),(43335,43347),(43392,43395),(43443,43456),(43561,43574),(43587,43587),(43596,43597),(43643,43643),(43696,43696),(43698,43700),(43703,43704),(43710,43711),(43713,43713),(44003,44010),(44012,44013),(55216,55295),(64286,64286),(65024,65039),(65056,65062),(65279,65279),(65529,65531),(66045,66045),(68097,68099),(68101,68102),(68108,68111),(68152,68154),(68159,68159),(69760,69762),(69808,69818),(69821,69821),(119141,119145),(119149,119170),(119173,119179),(119210,119213),(119362,119364),(917505,917505),(917536,917631),(917760,917999)),'6.0.0':((0,0),(173,173),(768,879),(1155,1161),(1425,1469),(1471,1471),(1473,1474),(1476,1477),(1479,1479),(1536,1539),(1552,1562),(1611,1631),(1648,1648),(1750,1757),(1759,1764),(1767,1768),(1770,1773),(1807,1807),(1809,1809),(1840,1866),(1958,1968),(2027,2035),(2070,2073),(2075,2083),(2085,2087),(2089,2093),(2137,2139),(2304,2307),(2362,2364),(2366,2383),(2385,2391),(2402,2403),(2433,2435),(2492,2492),(2494,2500),(2503,2504),(2507,2509),(2519,2519),(2530,2531),(2561,2563),(2620,2620),(2622,2626),(2631,2632),(2635,2637),(2641,2641),(2672,2673),(2677,2677),(2689,2691),(2748,2748),(2750,2757),(2759,2761),(2763,2765),(2786,2787),(2817,2819),(2876,2876),(2878,2884),(2887,2888),(2891,2893),(2902,2903),(2914,2915),(2946,2946),(3006,3010),(3014,3016),(3018,3021),(3031,3031),(3073,3075),(3134,3140),(3142,3144),(3146,3149),(3157,3158),(3170,3171),(3202,3203),(3260,3260),(3262,3268),(3270,3272),(3274,3277),(3285,3286),(3298,3299),(3330,3331),(3390,3396),(3398,3400),(3402,3405),(3415,3415),(3426,3427),(3458,3459),(3530,3530),(3535,3540),(3542,3542),(3544,3551),(3570,3571),(3633,3633),(3636,3642),(3655,3662),(3761,3761),(3764,3769),(3771,3772),(3784,3789),(3864,3865),(3893,3893),(3895,3895),(3897,3897),(3902,3903),(3953,3972),(3974,3975),(3981,3991),(3993,4028),(4038,4038),(4139,4158),(4182,4185),(4190,4192),(4194,4196),(4199,4205),(4209,4212),(4226,4237),(4239,4239),(4250,4253),(4448,4607),(4957,4959),(5906,5908),(5938,5940),(5970,5971),(6002,6003),(6068,6099),(6109,6109),(6155,6157),(6313,6313),(6432,6443),(6448,6459),(6576,6592),(6600,6601),(6679,6683),(6741,6750),(6752,6780),(6783,6783),(6912,6916),(6964,6980),(7019,7027),(7040,7042),(7073,7082),(7142,7155),(7204,7223),(7376,7378),(7380,7400),(7405,7405),(7410,7410),(7616,7654),(7676,7679),(8203,8207),(8232,8238),(8288,8292),(8298,8303),(8400,8432),(11503,11505),(11647,11647),(11744,11775),(12330,12335),(12441,12442),(42607,42610),(42620,42621),(42736,42737),(43010,43010),(43014,43014),(43019,43019),(43043,43047),(43136,43137),(43188,43204),(43232,43249),(43302,43309),(43335,43347),(43392,43395),(43443,43456),(43561,43574),(43587,43587),(43596,43597),(43643,43643),(43696,43696),(43698,43700),(43703,43704),(43710,43711),(43713,43713),(44003,44010),(44012,44013),(55216,55295),(64286,64286),(65024,65039),(65056,65062),(65279,65279),(65529,65531),(66045,66045),(68097,68099),(68101,68102),(68108,68111),(68152,68154),(68159,68159),(69632,69634),(69688,69702),(69760,69762),(69808,69818),(69821,69821),(119141,119145),(119149,119170),(119173,119179),(119210,119213),(119362,119364),(917505,917505),(917536,917631),(917760,917999)),'6.1.0':((0,0),(173,173),(768,879),(1155,1161),(1425,1469),(1471,1471),(1473,1474),(1476,1477),(1479,1479),(1536,1540),(1552,1562),(1611,1631),(1648,1648),(1750,1757),(1759,1764),(1767,1768),(1770,1773),(1807,1807),(1809,1809),(1840,1866),(1958,1968),(2027,2035),(2070,2073),(2075,2083),(2085,2087),(2089,2093),(2137,2139),(2276,2302),(2304,2307),(2362,2364),(2366,2383),(2385,2391),(2402,2403),(2433,2435),(2492,2492),(2494,2500),(2503,2504),(2507,2509),(2519,2519),(2530,2531),(2561,2563),(2620,2620),(2622,2626),(2631,2632),(2635,2637),(2641,2641),(2672,2673),(2677,2677),(2689,2691),(2748,2748),(2750,2757),(2759,2761),(2763,2765),(2786,2787),(2817,2819),(2876,2876),(2878,2884),(2887,2888),(2891,2893),(2902,2903),(2914,2915),(2946,2946),(3006,3010),(3014,3016),(3018,3021),(3031,3031),(3073,3075),(3134,3140),(3142,3144),(3146,3149),(3157,3158),(3170,3171),(3202,3203),(3260,3260),(3262,3268),(3270,3272),(3274,3277),(3285,3286),(3298,3299),(3330,3331),(3390,3396),(3398,3400),(3402,3405),(3415,3415),(3426,3427),(3458,3459),(3530,3530),(3535,3540),(3542,3542),(3544,3551),(3570,3571),(3633,3633),(3636,3642),(3655,3662),(3761,3761),(3764,3769),(3771,3772),(3784,3789),(3864,3865),(3893,3893),(3895,3895),(3897,3897),(3902,3903),(3953,3972),(3974,3975),(3981,3991),(3993,4028),(4038,4038),(4139,4158),(4182,4185),(4190,4192),(4194,4196),(4199,4205),(4209,4212),(4226,4237),(4239,4239),(4250,4253),(4448,4607),(4957,4959),(5906,5908),(5938,5940),(5970,5971),(6002,6003),(6068,6099),(6109,6109),(6155,6157),(6313,6313),(6432,6443),(6448,6459),(6576,6592),(6600,6601),(6679,6683),(6741,6750),(6752,6780),(6783,6783),(6912,6916),(6964,6980),(7019,7027),(7040,7042),(7073,7085),(7142,7155),(7204,7223),(7376,7378),(7380,7400),(7405,7405),(7410,7412),(7616,7654),(7676,7679),(8203,8207),(8232,8238),(8288,8292),(8298,8303),(8400,8432),(11503,11505),(11647,11647),(11744,11775),(12330,12335),(12441,12442),(42607,42610),(42612,42621),(42655,42655),(42736,42737),(43010,43010),(43014,43014),(43019,43019),(43043,43047),(43136,43137),(43188,43204),(43232,43249),(43302,43309),(43335,43347),(43392,43395),(43443,43456),(43561,43574),(43587,43587),(43596,43597),(43643,43643),(43696,43696),(43698,43700),(43703,43704),(43710,43711),(43713,43713),(43755,43759),(43765,43766),(44003,44010),(44012,44013),(55216,55295),(64286,64286),(65024,65039),(65056,65062),(65279,65279),(65529,65531),(66045,66045),(68097,68099),(68101,68102),(68108,68111),(68152,68154),(68159,68159),(69632,69634),(69688,69702),(69760,69762),(69808,69818),(69821,69821),(69888,69890),(69927,69940),(70016,70018),(70067,70080),(71339,71351),(94033,94078),(94095,94098),(119141,119145),(119149,119170),(119173,119179),(119210,119213),(119362,119364),(917505,917505),(917536,917631),(917760,917999)),'6.2.0':((0,0),(173,173),(768,879),(1155,1161),(1425,1469),(1471,1471),(1473,1474),(1476,1477),(1479,1479),(1536,1540),(1552,1562),(1611,1631),(1648,1648),(1750,1757),(1759,1764),(1767,1768),(1770,1773),(1807,1807),(1809,1809),(1840,1866),(1958,1968),(2027,2035),(2070,2073),(2075,2083),(2085,2087),(2089,2093),(2137,2139),(2276,2302),(2304,2307),(2362,2364),(2366,2383),(2385,2391),(2402,2403),(2433,2435),(2492,2492),(2494,2500),(2503,2504),(2507,2509),(2519,2519),(2530,2531),(2561,2563),(2620,2620),(2622,2626),(2631,2632),(2635,2637),(2641,2641),(2672,2673),(2677,2677),(2689,2691),(2748,2748),(2750,2757),(2759,2761),(2763,2765),(2786,2787),(2817,2819),(2876,2876),(2878,2884),(2887,2888),(2891,2893),(2902,2903),(2914,2915),(2946,2946),(3006,3010),(3014,3016),(3018,3021),(3031,3031),(3073,3075),(3134,3140),(3142,3144),(3146,3149),(3157,3158),(3170,3171),(3202,3203),(3260,3260),(3262,3268),(3270,3272),(3274,3277),(3285,3286),(3298,3299),(3330,3331),(3390,3396),(3398,3400),(3402,3405),(3415,3415),(3426,3427),(3458,3459),(3530,3530),(3535,3540),(3542,3542),(3544,3551),(3570,3571),(3633,3633),(3636,3642),(3655,3662),(3761,3761),(3764,3769),(3771,3772),(3784,3789),(3864,3865),(3893,3893),(3895,3895),(3897,3897),(3902,3903),(3953,3972),(3974,3975),(3981,3991),(3993,4028),(4038,4038),(4139,4158),(4182,4185),(4190,4192),(4194,4196),(4199,4205),(4209,4212),(4226,4237),(4239,4239),(4250,4253),(4448,4607),(4957,4959),(5906,5908),(5938,5940),(5970,5971),(6002,6003),(6068,6099),(6109,6109),(6155,6157),(6313,6313),(6432,6443),(6448,6459),(6576,6592),(6600,6601),(6679,6683),(6741,6750),(6752,6780),(6783,6783),(6912,6916),(6964,6980),(7019,7027),(7040,7042),(7073,7085),(7142,7155),(7204,7223),(7376,7378),(7380,7400),(7405,7405),(7410,7412),(7616,7654),(7676,7679),(8203,8207),(8232,8238),(8288,8292),(8298,8303),(8400,8432),(11503,11505),(11647,11647),(11744,11775),(12330,12335),(12441,12442),(42607,42610),(42612,42621),(42655,42655),(42736,42737),(43010,43010),(43014,43014),(43019,43019),(43043,43047),(43136,43137),(43188,43204),(43232,43249),(43302,43309),(43335,43347),(43392,43395),(43443,43456),(43561,43574),(43587,43587),(43596,43597),(43643,43643),(43696,43696),(43698,43700),(43703,43704),(43710,43711),(43713,43713),(43755,43759),(43765,43766),(44003,44010),(44012,44013),(55216,55295),(64286,64286),(65024,65039),(65056,65062),(65279,65279),(65529,65531),(66045,66045),(68097,68099),(68101,68102),(68108,68111),(68152,68154),(68159,68159),(69632,69634),(69688,69702),(69760,69762),(69808,69818),(69821,69821),(69888,69890),(69927,69940),(70016,70018),(70067,70080),(71339,71351),(94033,94078),(94095,94098),(119141,119145),(119149,119170),(119173,119179),(119210,119213),(119362,119364),(917505,917505),(917536,917631),(917760,917999)),'6.3.0':((0,0),(173,173),(768,879),(1155,1161),(1425,1469),(1471,1471),(1473,1474),(1476,1477),(1479,1479),(1536,1540),(1552,1562),(1564,1564),(1611,1631),(1648,1648),(1750,1757),(1759,1764),(1767,1768),(1770,1773),(1807,1807),(1809,1809),(1840,1866),(1958,1968),(2027,2035),(2070,2073),(2075,2083),(2085,2087),(2089,2093),(2137,2139),(2276,2302),(2304,2307),(2362,2364),(2366,2383),(2385,2391),(2402,2403),(2433,2435),(2492,2492),(2494,2500),(2503,2504),(2507,2509),(2519,2519),(2530,2531),(2561,2563),(2620,2620),(2622,2626),(2631,2632),(2635,2637),(2641,2641),(2672,2673),(2677,2677),(2689,2691),(2748,2748),(2750,2757),(2759,2761),(2763,2765),(2786,2787),(2817,2819),(2876,2876),(2878,2884),(2887,2888),(2891,2893),(2902,2903),(2914,2915),(2946,2946),(3006,3010),(3014,3016),(3018,3021),(3031,3031),(3073,3075),(3134,3140),(3142,3144),(3146,3149),(3157,3158),(3170,3171),(3202,3203),(3260,3260),(3262,3268),(3270,3272),(3274,3277),(3285,3286),(3298,3299),(3330,3331),(3390,3396),(3398,3400),(3402,3405),(3415,3415),(3426,3427),(3458,3459),(3530,3530),(3535,3540),(3542,3542),(3544,3551),(3570,3571),(3633,3633),(3636,3642),(3655,3662),(3761,3761),(3764,3769),(3771,3772),(3784,3789),(3864,3865),(3893,3893),(3895,3895),(3897,3897),(3902,3903),(3953,3972),(3974,3975),(3981,3991),(3993,4028),(4038,4038),(4139,4158),(4182,4185),(4190,4192),(4194,4196),(4199,4205),(4209,4212),(4226,4237),(4239,4239),(4250,4253),(4448,4607),(4957,4959),(5906,5908),(5938,5940),(5970,5971),(6002,6003),(6068,6099),(6109,6109),(6155,6158),(6313,6313),(6432,6443),(6448,6459),(6576,6592),(6600,6601),(6679,6683),(6741,6750),(6752,6780),(6783,6783),(6912,6916),(6964,6980),(7019,7027),(7040,7042),(7073,7085),(7142,7155),(7204,7223),(7376,7378),(7380,7400),(7405,7405),(7410,7412),(7616,7654),(7676,7679),(8203,8207),(8232,8238),(8288,8292),(8294,8303),(8400,8432),(11503,11505),(11647,11647),(11744,11775),(12330,12335),(12441,12442),(42607,42610),(42612,42621),(42655,42655),(42736,42737),(43010,43010),(43014,43014),(43019,43019),(43043,43047),(43136,43137),(43188,43204),(43232,43249),(43302,43309),(43335,43347),(43392,43395),(43443,43456),(43561,43574),(43587,43587),(43596,43597),(43643,43643),(43696,43696),(43698,43700),(43703,43704),(43710,43711),(43713,43713),(43755,43759),(43765,43766),(44003,44010),(44012,44013),(55216,55295),(64286,64286),(65024,65039),(65056,65062),(65279,65279),(65529,65531),(66045,66045),(68097,68099),(68101,68102),(68108,68111),(68152,68154),(68159,68159),(69632,69634),(69688,69702),(69760,69762),(69808,69818),(69821,69821),(69888,69890),(69927,69940),(70016,70018),(70067,70080),(71339,71351),(94033,94078),(94095,94098),(119141,119145),(119149,119170),(119173,119179),(119210,119213),(119362,119364),(917505,917505),(917536,917631),(917760,917999)),'7.0.0':((0,0),(173,173),(768,879),(1155,1161),(1425,1469),(1471,1471),(1473,1474),(1476,1477),(1479,1479),(1536,1541),(1552,1562),(1564,1564),(1611,1631),(1648,1648),(1750,1757),(1759,1764),(1767,1768),(1770,1773),(1807,1807),(1809,1809),(1840,1866),(1958,1968),(2027,2035),(2070,2073),(2075,2083),(2085,2087),(2089,2093),(2137,2139),(2276,2307),(2362,2364),(2366,2383),(2385,2391),(2402,2403),(2433,2435),(2492,2492),(2494,2500),(2503,2504),(2507,2509),(2519,2519),(2530,2531),(2561,2563),(2620,2620),(2622,2626),(2631,2632),(2635,2637),(2641,2641),(2672,2673),(2677,2677),(2689,2691),(2748,2748),(2750,2757),(2759,2761),(2763,2765),(2786,2787),(2817,2819),(2876,2876),(2878,2884),(2887,2888),(2891,2893),(2902,2903),(2914,2915),(2946,2946),(3006,3010),(3014,3016),(3018,3021),(3031,3031),(3072,3075),(3134,3140),(3142,3144),(3146,3149),(3157,3158),(3170,3171),(3201,3203),(3260,3260),(3262,3268),(3270,3272),(3274,3277),(3285,3286),(3298,3299),(3329,3331),(3390,3396),(3398,3400),(3402,3405),(3415,3415),(3426,3427),(3458,3459),(3530,3530),(3535,3540),(3542,3542),(3544,3551),(3570,3571),(3633,3633),(3636,3642),(3655,3662),(3761,3761),(3764,3769),(3771,3772),(3784,3789),(3864,3865),(3893,3893),(3895,3895),(3897,3897),(3902,3903),(3953,3972),(3974,3975),(3981,3991),(3993,4028),(4038,4038),(4139,4158),(4182,4185),(4190,4192),(4194,4196),(4199,4205),(4209,4212),(4226,4237),(4239,4239),(4250,4253),(4448,4607),(4957,4959),(5906,5908),(5938,5940),(5970,5971),(6002,6003),(6068,6099),(6109,6109),(6155,6158),(6313,6313),(6432,6443),(6448,6459),(6576,6592),(6600,6601),(6679,6683),(6741,6750),(6752,6780),(6783,6783),(6832,6846),(6912,6916),(6964,6980),(7019,7027),(7040,7042),(7073,7085),(7142,7155),(7204,7223),(7376,7378),(7380,7400),(7405,7405),(7410,7412),(7416,7417),(7616,7669),(7676,7679),(8203,8207),(8232,8238),(8288,8292),(8294,8303),(8400,8432),(11503,11505),(11647,11647),(11744,11775),(12330,12335),(12441,12442),(42607,42610),(42612,42621),(42655,42655),(42736,42737),(43010,43010),(43014,43014),(43019,43019),(43043,43047),(43136,43137),(43188,43204),(43232,43249),(43302,43309),(43335,43347),(43392,43395),(43443,43456),(43493,43493),(43561,43574),(43587,43587),(43596,43597),(43643,43645),(43696,43696),(43698,43700),(43703,43704),(43710,43711),(43713,43713),(43755,43759),(43765,43766),(44003,44010),(44012,44013),(55216,55295),(64286,64286),(65024,65039),(65056,65069),(65279,65279),(65529,65531),(66045,66045),(66272,66272),(66422,66426),(68097,68099),(68101,68102),(68108,68111),(68152,68154),(68159,68159),(68325,68326),(69632,69634),(69688,69702),(69759,69762),(69808,69818),(69821,69821),(69888,69890),(69927,69940),(70003,70003),(70016,70018),(70067,70080),(70188,70199),(70367,70378),(70401,70403),(70460,70460),(70462,70468),(70471,70472),(70475,70477),(70487,70487),(70498,70499),(70502,70508),(70512,70516),(70832,70851),(71087,71093),(71096,71104),(71216,71232),(71339,71351),(92912,92916),(92976,92982),(94033,94078),(94095,94098),(113821,113822),(113824,113827),(119141,119145),(119149,119170),(119173,119179),(119210,119213),(119362,119364),(125136,125142),(917505,917505),(917536,917631),(917760,917999)),'8.0.0':((0,0),(173,173),(768,879),(1155,1161),(1425,1469),(1471,1471),(1473,1474),(1476,1477),(1479,1479),(1536,1541),(1552,1562),(1564,1564),(1611,1631),(1648,1648),(1750,1757),(1759,1764),(1767,1768),(1770,1773),(1807,1807),(1809,1809),(1840,1866),(1958,1968),(2027,2035),(2070,2073),(2075,2083),(2085,2087),(2089,2093),(2137,2139),(2275,2307),(2362,2364),(2366,2383),(2385,2391),(2402,2403),(2433,2435),(2492,2492),(2494,2500),(2503,2504),(2507,2509),(2519,2519),(2530,2531),(2561,2563),(2620,2620),(2622,2626),(2631,2632),(2635,2637),(2641,2641),(2672,2673),(2677,2677),(2689,2691),(2748,2748),(2750,2757),(2759,2761),(2763,2765),(2786,2787),(2817,2819),(2876,2876),(2878,2884),(2887,2888),(2891,2893),(2902,2903),(2914,2915),(2946,2946),(3006,3010),(3014,3016),(3018,3021),(3031,3031),(3072,3075),(3134,3140),(3142,3144),(3146,3149),(3157,3158),(3170,3171),(3201,3203),(3260,3260),(3262,3268),(3270,3272),(3274,3277),(3285,3286),(3298,3299),(3329,3331),(3390,3396),(3398,3400),(3402,3405),(3415,3415),(3426,3427),(3458,3459),(3530,3530),(3535,3540),(3542,3542),(3544,3551),(3570,3571),(3633,3633),(3636,3642),(3655,3662),(3761,3761),(3764,3769),(3771,3772),(3784,3789),(3864,3865),(3893,3893),(3895,3895),(3897,3897),(3902,3903),(3953,3972),(3974,3975),(3981,3991),(3993,4028),(4038,4038),(4139,4158),(4182,4185),(4190,4192),(4194,4196),(4199,4205),(4209,4212),(4226,4237),(4239,4239),(4250,4253),(4448,4607),(4957,4959),(5906,5908),(5938,5940),(5970,5971),(6002,6003),(6068,6099),(6109,6109),(6155,6158),(6313,6313),(6432,6443),(6448,6459),(6679,6683),(6741,6750),(6752,6780),(6783,6783),(6832,6846),(6912,6916),(6964,6980),(7019,7027),(7040,7042),(7073,7085),(7142,7155),(7204,7223),(7376,7378),(7380,7400),(7405,7405),(7410,7412),(7416,7417),(7616,7669),(7676,7679),(8203,8207),(8232,8238),(8288,8292),(8294,8303),(8400,8432),(11503,11505),(11647,11647),(11744,11775),(12330,12335),(12441,12442),(42607,42610),(42612,42621),(42654,42655),(42736,42737),(43010,43010),(43014,43014),(43019,43019),(43043,43047),(43136,43137),(43188,43204),(43232,43249),(43302,43309),(43335,43347),(43392,43395),(43443,43456),(43493,43493),(43561,43574),(43587,43587),(43596,43597),(43643,43645),(43696,43696),(43698,43700),(43703,43704),(43710,43711),(43713,43713),(43755,43759),(43765,43766),(44003,44010),(44012,44013),(55216,55295),(64286,64286),(65024,65039),(65056,65071),(65279,65279),(65529,65531),(66045,66045),(66272,66272),(66422,66426),(68097,68099),(68101,68102),(68108,68111),(68152,68154),(68159,68159),(68325,68326),(69632,69634),(69688,69702),(69759,69762),(69808,69818),(69821,69821),(69888,69890),(69927,69940),(70003,70003),(70016,70018),(70067,70080),(70090,70092),(70188,70199),(70367,70378),(70400,70403),(70460,70460),(70462,70468),(70471,70472),(70475,70477),(70487,70487),(70498,70499),(70502,70508),(70512,70516),(70832,70851),(71087,71093),(71096,71104),(71132,71133),(71216,71232),(71339,71351),(71453,71467),(92912,92916),(92976,92982),(94033,94078),(94095,94098),(113821,113822),(113824,113827),(119141,119145),(119149,119170),(119173,119179),(119210,119213),(119362,119364),(121344,121398),(121403,121452),(121461,121461),(121476,121476),(121499,121503),(121505,121519),(125136,125142),(127995,127999),(917505,917505),(917536,917631),(917760,917999)),'9.0.0':((0,0),(173,173),(768,879),(1155,1161),(1425,1469),(1471,1471),(1473,1474),(1476,1477),(1479,1479),(1536,1541),(1552,1562),(1564,1564),(1611,1631),(1648,1648),(1750,1757),(1759,1764),(1767,1768),(1770,1773),(1807,1807),(1809,1809),(1840,1866),(1958,1968),(2027,2035),(2070,2073),(2075,2083),(2085,2087),(2089,2093),(2137,2139),(2260,2307),(2362,2364),(2366,2383),(2385,2391),(2402,2403),(2433,2435),(2492,2492),(2494,2500),(2503,2504),(2507,2509),(2519,2519),(2530,2531),(2561,2563),(2620,2620),(2622,2626),(2631,2632),(2635,2637),(2641,2641),(2672,2673),(2677,2677),(2689,2691),(2748,2748),(2750,2757),(2759,2761),(2763,2765),(2786,2787),(2817,2819),(2876,2876),(2878,2884),(2887,2888),(2891,2893),(2902,2903),(2914,2915),(2946,2946),(3006,3010),(3014,3016),(3018,3021),(3031,3031),(3072,3075),(3134,3140),(3142,3144),(3146,3149),(3157,3158),(3170,3171),(3201,3203),(3260,3260),(3262,3268),(3270,3272),(3274,3277),(3285,3286),(3298,3299),(3329,3331),(3390,3396),(3398,3400),(3402,3405),(3415,3415),(3426,3427),(3458,3459),(3530,3530),(3535,3540),(3542,3542),(3544,3551),(3570,3571),(3633,3633),(3636,3642),(3655,3662),(3761,3761),(3764,3769),(3771,3772),(3784,3789),(3864,3865),(3893,3893),(3895,3895),(3897,3897),(3902,3903),(3953,3972),(3974,3975),(3981,3991),(3993,4028),(4038,4038),(4139,4158),(4182,4185),(4190,4192),(4194,4196),(4199,4205),(4209,4212),(4226,4237),(4239,4239),(4250,4253),(4448,4607),(4957,4959),(5906,5908),(5938,5940),(5970,5971),(6002,6003),(6068,6099),(6109,6109),(6155,6158),(6277,6278),(6313,6313),(6432,6443),(6448,6459),(6679,6683),(6741,6750),(6752,6780),(6783,6783),(6832,6846),(6912,6916),(6964,6980),(7019,7027),(7040,7042),(7073,7085),(7142,7155),(7204,7223),(7376,7378),(7380,7400),(7405,7405),(7410,7412),(7416,7417),(7616,7669),(7675,7679),(8203,8207),(8232,8238),(8288,8292),(8294,8303),(8400,8432),(11503,11505),(11647,11647),(11744,11775),(12330,12335),(12441,12442),(42607,42610),(42612,42621),(42654,42655),(42736,42737),(43010,43010),(43014,43014),(43019,43019),(43043,43047),(43136,43137),(43188,43205),(43232,43249),(43302,43309),(43335,43347),(43392,43395),(43443,43456),(43493,43493),(43561,43574),(43587,43587),(43596,43597),(43643,43645),(43696,43696),(43698,43700),(43703,43704),(43710,43711),(43713,43713),(43755,43759),(43765,43766),(44003,44010),(44012,44013),(55216,55295),(64286,64286),(65024,65039),(65056,65071),(65279,65279),(65529,65531),(66045,66045),(66272,66272),(66422,66426),(68097,68099),(68101,68102),(68108,68111),(68152,68154),(68159,68159),(68325,68326),(69632,69634),(69688,69702),(69759,69762),(69808,69818),(69821,69821),(69888,69890),(69927,69940),(70003,70003),(70016,70018),(70067,70080),(70090,70092),(70188,70199),(70206,70206),(70367,70378),(70400,70403),(70460,70460),(70462,70468),(70471,70472),(70475,70477),(70487,70487),(70498,70499),(70502,70508),(70512,70516),(70709,70726),(70832,70851),(71087,71093),(71096,71104),(71132,71133),(71216,71232),(71339,71351),(71453,71467),(72751,72758),(72760,72767),(72850,72871),(72873,72886),(92912,92916),(92976,92982),(94033,94078),(94095,94098),(113821,113822),(113824,113827),(119141,119145),(119149,119170),(119173,119179),(119210,119213),(119362,119364),(121344,121398),(121403,121452),(121461,121461),(121476,121476),(121499,121503),(121505,121519),(122880,122886),(122888,122904),(122907,122913),(122915,122916),(122918,122922),(125136,125142),(125252,125258),(127995,127999),(917505,917505),(917536,917631),(917760,917999)),'10.0.0':((0,0),(173,173),(768,879),(1155,1161),(1425,1469),(1471,1471),(1473,1474),(1476,1477),(1479,1479),(1536,1541),(1552,1562),(1564,1564),(1611,1631),(1648,1648),(1750,1757),(1759,1764),(1767,1768),(1770,1773),(1807,1807),(1809,1809),(1840,1866),(1958,1968),(2027,2035),(2070,2073),(2075,2083),(2085,2087),(2089,2093),(2137,2139),(2260,2307),(2362,2364),(2366,2383),(2385,2391),(2402,2403),(2433,2435),(2492,2492),(2494,2500),(2503,2504),(2507,2509),(2519,2519),(2530,2531),(2561,2563),(2620,2620),(2622,2626),(2631,2632),(2635,2637),(2641,2641),(2672,2673),(2677,2677),(2689,2691),(2748,2748),(2750,2757),(2759,2761),(2763,2765),(2786,2787),(2810,2815),(2817,2819),(2876,2876),(2878,2884),(2887,2888),(2891,2893),(2902,2903),(2914,2915),(2946,2946),(3006,3010),(3014,3016),(3018,3021),(3031,3031),(3072,3075),(3134,3140),(3142,3144),(3146,3149),(3157,3158),(3170,3171),(3201,3203),(3260,3260),(3262,3268),(3270,3272),(3274,3277),(3285,3286),(3298,3299),(3328,3331),(3387,3388),(3390,3396),(3398,3400),(3402,3405),(3415,3415),(3426,3427),(3458,3459),(3530,3530),(3535,3540),(3542,3542),(3544,3551),(3570,3571),(3633,3633),(3636,3642),(3655,3662),(3761,3761),(3764,3769),(3771,3772),(3784,3789),(3864,3865),(3893,3893),(3895,3895),(3897,3897),(3902,3903),(3953,3972),(3974,3975),(3981,3991),(3993,4028),(4038,4038),(4139,4158),(4182,4185),(4190,4192),(4194,4196),(4199,4205),(4209,4212),(4226,4237),(4239,4239),(4250,4253),(4448,4607),(4957,4959),(5906,5908),(5938,5940),(5970,5971),(6002,6003),(6068,6099),(6109,6109),(6155,6158),(6277,6278),(6313,6313),(6432,6443),(6448,6459),(6679,6683),(6741,6750),(6752,6780),(6783,6783),(6832,6846),(6912,6916),(6964,6980),(7019,7027),(7040,7042),(7073,7085),(7142,7155),(7204,7223),(7376,7378),(7380,7400),(7405,7405),(7410,7412),(7415,7417),(7616,7673),(7675,7679),(8203,8207),(8232,8238),(8288,8292),(8294,8303),(8400,8432),(11503,11505),(11647,11647),(11744,11775),(12330,12335),(12441,12442),(42607,42610),(42612,42621),(42654,42655),(42736,42737),(43010,43010),(43014,43014),(43019,43019),(43043,43047),(43136,43137),(43188,43205),(43232,43249),(43302,43309),(43335,43347),(43392,43395),(43443,43456),(43493,43493),(43561,43574),(43587,43587),(43596,43597),(43643,43645),(43696,43696),(43698,43700),(43703,43704),(43710,43711),(43713,43713),(43755,43759),(43765,43766),(44003,44010),(44012,44013),(55216,55295),(64286,64286),(65024,65039),(65056,65071),(65279,65279),(65529,65531),(66045,66045),(66272,66272),(66422,66426),(68097,68099),(68101,68102),(68108,68111),(68152,68154),(68159,68159),(68325,68326),(69632,69634),(69688,69702),(69759,69762),(69808,69818),(69821,69821),(69888,69890),(69927,69940),(70003,70003),(70016,70018),(70067,70080),(70090,70092),(70188,70199),(70206,70206),(70367,70378),(70400,70403),(70460,70460),(70462,70468),(70471,70472),(70475,70477),(70487,70487),(70498,70499),(70502,70508),(70512,70516),(70709,70726),(70832,70851),(71087,71093),(71096,71104),(71132,71133),(71216,71232),(71339,71351),(71453,71467),(72193,72202),(72243,72249),(72251,72254),(72263,72263),(72273,72283),(72330,72345),(72751,72758),(72760,72767),(72850,72871),(72873,72886),(73009,73014),(73018,73018),(73020,73021),(73023,73029),(73031,73031),(92912,92916),(92976,92982),(94033,94078),(94095,94098),(113821,113822),(113824,113827),(119141,119145),(119149,119170),(119173,119179),(119210,119213),(119362,119364),(121344,121398),(121403,121452),(121461,121461),(121476,121476),(121499,121503),(121505,121519),(122880,122886),(122888,122904),(122907,122913),(122915,122916),(122918,122922),(125136,125142),(125252,125258),(127995,127999),(917505,917505),(917536,917631),(917760,917999)),'11.0.0':((0,0),(173,173),(768,879),(1155,1161),(1425,1469),(1471,1471),(1473,1474),(1476,1477),(1479,1479),(1536,1541),(1552,1562),(1564,1564),(1611,1631),(1648,1648),(1750,1757),(1759,1764),(1767,1768),(1770,1773),(1807,1807),(1809,1809),(1840,1866),(1958,1968),(2027,2035),(2045,2045),(2070,2073),(2075,2083),(2085,2087),(2089,2093),(2137,2139),(2259,2307),(2362,2364),(2366,2383),(2385,2391),(2402,2403),(2433,2435),(2492,2492),(2494,2500),(2503,2504),(2507,2509),(2519,2519),(2530,2531),(2558,2558),(2561,2563),(2620,2620),(2622,2626),(2631,2632),(2635,2637),(2641,2641),(2672,2673),(2677,2677),(2689,2691),(2748,2748),(2750,2757),(2759,2761),(2763,2765),(2786,2787),(2810,2815),(2817,2819),(2876,2876),(2878,2884),(2887,2888),(2891,2893),(2902,2903),(2914,2915),(2946,2946),(3006,3010),(3014,3016),(3018,3021),(3031,3031),(3072,3076),(3134,3140),(3142,3144),(3146,3149),(3157,3158),(3170,3171),(3201,3203),(3260,3260),(3262,3268),(3270,3272),(3274,3277),(3285,3286),(3298,3299),(3328,3331),(3387,3388),(3390,3396),(3398,3400),(3402,3405),(3415,3415),(3426,3427),(3458,3459),(3530,3530),(3535,3540),(3542,3542),(3544,3551),(3570,3571),(3633,3633),(3636,3642),(3655,3662),(3761,3761),(3764,3769),(3771,3772),(3784,3789),(3864,3865),(3893,3893),(3895,3895),(3897,3897),(3902,3903),(3953,3972),(3974,3975),(3981,3991),(3993,4028),(4038,4038),(4139,4158),(4182,4185),(4190,4192),(4194,4196),(4199,4205),(4209,4212),(4226,4237),(4239,4239),(4250,4253),(4448,4607),(4957,4959),(5906,5908),(5938,5940),(5970,5971),(6002,6003),(6068,6099),(6109,6109),(6155,6158),(6277,6278),(6313,6313),(6432,6443),(6448,6459),(6679,6683),(6741,6750),(6752,6780),(6783,6783),(6832,6846),(6912,6916),(6964,6980),(7019,7027),(7040,7042),(7073,7085),(7142,7155),(7204,7223),(7376,7378),(7380,7400),(7405,7405),(7410,7412),(7415,7417),(7616,7673),(7675,7679),(8203,8207),(8232,8238),(8288,8292),(8294,8303),(8400,8432),(11503,11505),(11647,11647),(11744,11775),(12330,12335),(12441,12442),(42607,42610),(42612,42621),(42654,42655),(42736,42737),(43010,43010),(43014,43014),(43019,43019),(43043,43047),(43136,43137),(43188,43205),(43232,43249),(43263,43263),(43302,43309),(43335,43347),(43392,43395),(43443,43456),(43493,43493),(43561,43574),(43587,43587),(43596,43597),(43643,43645),(43696,43696),(43698,43700),(43703,43704),(43710,43711),(43713,43713),(43755,43759),(43765,43766),(44003,44010),(44012,44013),(55216,55295),(64286,64286),(65024,65039),(65056,65071),(65279,65279),(65529,65531),(66045,66045),(66272,66272),(66422,66426),(68097,68099),(68101,68102),(68108,68111),(68152,68154),(68159,68159),(68325,68326),(68900,68903),(69446,69456),(69632,69634),(69688,69702),(69759,69762),(69808,69818),(69821,69821),(69837,69837),(69888,69890),(69927,69940),(69957,69958),(70003,70003),(70016,70018),(70067,70080),(70089,70092),(70188,70199),(70206,70206),(70367,70378),(70400,70403),(70459,70460),(70462,70468),(70471,70472),(70475,70477),(70487,70487),(70498,70499),(70502,70508),(70512,70516),(70709,70726),(70750,70750),(70832,70851),(71087,71093),(71096,71104),(71132,71133),(71216,71232),(71339,71351),(71453,71467),(71724,71738),(72193,72202),(72243,72249),(72251,72254),(72263,72263),(72273,72283),(72330,72345),(72751,72758),(72760,72767),(72850,72871),(72873,72886),(73009,73014),(73018,73018),(73020,73021),(73023,73029),(73031,73031),(73098,73102),(73104,73105),(73107,73111),(73459,73462),(92912,92916),(92976,92982),(94033,94078),(94095,94098),(113821,113822),(113824,113827),(119141,119145),(119149,119170),(119173,119179),(119210,119213),(119362,119364),(121344,121398),(121403,121452),(121461,121461),(121476,121476),(121499,121503),(121505,121519),(122880,122886),(122888,122904),(122907,122913),(122915,122916),(122918,122922),(125136,125142),(125252,125258),(127995,127999),(917505,917505),(917536,917631),(917760,917999)),'12.0.0':((0,0),(173,173),(768,879),(1155,1161),(1425,1469),(1471,1471),(1473,1474),(1476,1477),(1479,1479),(1536,1541),(1552,1562),(1564,1564),(1611,1631),(1648,1648),(1750,1757),(1759,1764),(1767,1768),(1770,1773),(1807,1807),(1809,1809),(1840,1866),(1958,1968),(2027,2035),(2045,2045),(2070,2073),(2075,2083),(2085,2087),(2089,2093),(2137,2139),(2259,2307),(2362,2364),(2366,2383),(2385,2391),(2402,2403),(2433,2435),(2492,2492),(2494,2500),(2503,2504),(2507,2509),(2519,2519),(2530,2531),(2558,2558),(2561,2563),(2620,2620),(2622,2626),(2631,2632),(2635,2637),(2641,2641),(2672,2673),(2677,2677),(2689,2691),(2748,2748),(2750,2757),(2759,2761),(2763,2765),(2786,2787),(2810,2815),(2817,2819),(2876,2876),(2878,2884),(2887,2888),(2891,2893),(2902,2903),(2914,2915),(2946,2946),(3006,3010),(3014,3016),(3018,3021),(3031,3031),(3072,3076),(3134,3140),(3142,3144),(3146,3149),(3157,3158),(3170,3171),(3201,3203),(3260,3260),(3262,3268),(3270,3272),(3274,3277),(3285,3286),(3298,3299),(3328,3331),(3387,3388),(3390,3396),(3398,3400),(3402,3405),(3415,3415),(3426,3427),(3458,3459),(3530,3530),(3535,3540),(3542,3542),(3544,3551),(3570,3571),(3633,3633),(3636,3642),(3655,3662),(3761,3761),(3764,3772),(3784,3789),(3864,3865),(3893,3893),(3895,3895),(3897,3897),(3902,3903),(3953,3972),(3974,3975),(3981,3991),(3993,4028),(4038,4038),(4139,4158),(4182,4185),(4190,4192),(4194,4196),(4199,4205),(4209,4212),(4226,4237),(4239,4239),(4250,4253),(4448,4607),(4957,4959),(5906,5908),(5938,5940),(5970,5971),(6002,6003),(6068,6099),(6109,6109),(6155,6158),(6277,6278),(6313,6313),(6432,6443),(6448,6459),(6679,6683),(6741,6750),(6752,6780),(6783,6783),(6832,6846),(6912,6916),(6964,6980),(7019,7027),(7040,7042),(7073,7085),(7142,7155),(7204,7223),(7376,7378),(7380,7400),(7405,7405),(7412,7412),(7415,7417),(7616,7673),(7675,7679),(8203,8207),(8232,8238),(8288,8292),(8294,8303),(8400,8432),(11503,11505),(11647,11647),(11744,11775),(12330,12335),(12441,12442),(42607,42610),(42612,42621),(42654,42655),(42736,42737),(43010,43010),(43014,43014),(43019,43019),(43043,43047),(43136,43137),(43188,43205),(43232,43249),(43263,43263),(43302,43309),(43335,43347),(43392,43395),(43443,43456),(43493,43493),(43561,43574),(43587,43587),(43596,43597),(43643,43645),(43696,43696),(43698,43700),(43703,43704),(43710,43711),(43713,43713),(43755,43759),(43765,43766),(44003,44010),(44012,44013),(55216,55295),(64286,64286),(65024,65039),(65056,65071),(65279,65279),(65529,65531),(66045,66045),(66272,66272),(66422,66426),(68097,68099),(68101,68102),(68108,68111),(68152,68154),(68159,68159),(68325,68326),(68900,68903),(69446,69456),(69632,69634),(69688,69702),(69759,69762),(69808,69818),(69821,69821),(69837,69837),(69888,69890),(69927,69940),(69957,69958),(70003,70003),(70016,70018),(70067,70080),(70089,70092),(70188,70199),(70206,70206),(70367,70378),(70400,70403),(70459,70460),(70462,70468),(70471,70472),(70475,70477),(70487,70487),(70498,70499),(70502,70508),(70512,70516),(70709,70726),(70750,70750),(70832,70851),(71087,71093),(71096,71104),(71132,71133),(71216,71232),(71339,71351),(71453,71467),(71724,71738),(72145,72151),(72154,72160),(72164,72164),(72193,72202),(72243,72249),(72251,72254),(72263,72263),(72273,72283),(72330,72345),(72751,72758),(72760,72767),(72850,72871),(72873,72886),(73009,73014),(73018,73018),(73020,73021),(73023,73029),(73031,73031),(73098,73102),(73104,73105),(73107,73111),(73459,73462),(78896,78904),(92912,92916),(92976,92982),(94031,94031),(94033,94087),(94095,94098),(113821,113822),(113824,113827),(119141,119145),(119149,119170),(119173,119179),(119210,119213),(119362,119364),(121344,121398),(121403,121452),(121461,121461),(121476,121476),(121499,121503),(121505,121519),(122880,122886),(122888,122904),(122907,122913),(122915,122916),(122918,122922),(123184,123190),(123628,123631),(125136,125142),(125252,125258),(127995,127999),(917505,917505),(917536,917631),(917760,917999)),'12.1.0':((0,0),(173,173),(768,879),(1155,1161),(1425,1469),(1471,1471),(1473,1474),(1476,1477),(1479,1479),(1536,1541),(1552,1562),(1564,1564),(1611,1631),(1648,1648),(1750,1757),(1759,1764),(1767,1768),(1770,1773),(1807,1807),(1809,1809),(1840,1866),(1958,1968),(2027,2035),(2045,2045),(2070,2073),(2075,2083),(2085,2087),(2089,2093),(2137,2139),(2259,2307),(2362,2364),(2366,2383),(2385,2391),(2402,2403),(2433,2435),(2492,2492),(2494,2500),(2503,2504),(2507,2509),(2519,2519),(2530,2531),(2558,2558),(2561,2563),(2620,2620),(2622,2626),(2631,2632),(2635,2637),(2641,2641),(2672,2673),(2677,2677),(2689,2691),(2748,2748),(2750,2757),(2759,2761),(2763,2765),(2786,2787),(2810,2815),(2817,2819),(2876,2876),(2878,2884),(2887,2888),(2891,2893),(2902,2903),(2914,2915),(2946,2946),(3006,3010),(3014,3016),(3018,3021),(3031,3031),(3072,3076),(3134,3140),(3142,3144),(3146,3149),(3157,3158),(3170,3171),(3201,3203),(3260,3260),(3262,3268),(3270,3272),(3274,3277),(3285,3286),(3298,3299),(3328,3331),(3387,3388),(3390,3396),(3398,3400),(3402,3405),(3415,3415),(3426,3427),(3458,3459),(3530,3530),(3535,3540),(3542,3542),(3544,3551),(3570,3571),(3633,3633),(3636,3642),(3655,3662),(3761,3761),(3764,3772),(3784,3789),(3864,3865),(3893,3893),(3895,3895),(3897,3897),(3902,3903),(3953,3972),(3974,3975),(3981,3991),(3993,4028),(4038,4038),(4139,4158),(4182,4185),(4190,4192),(4194,4196),(4199,4205),(4209,4212),(4226,4237),(4239,4239),(4250,4253),(4448,4607),(4957,4959),(5906,5908),(5938,5940),(5970,5971),(6002,6003),(6068,6099),(6109,6109),(6155,6158),(6277,6278),(6313,6313),(6432,6443),(6448,6459),(6679,6683),(6741,6750),(6752,6780),(6783,6783),(6832,6846),(6912,6916),(6964,6980),(7019,7027),(7040,7042),(7073,7085),(7142,7155),(7204,7223),(7376,7378),(7380,7400),(7405,7405),(7412,7412),(7415,7417),(7616,7673),(7675,7679),(8203,8207),(8232,8238),(8288,8292),(8294,8303),(8400,8432),(11503,11505),(11647,11647),(11744,11775),(12330,12335),(12441,12442),(42607,42610),(42612,42621),(42654,42655),(42736,42737),(43010,43010),(43014,43014),(43019,43019),(43043,43047),(43136,43137),(43188,43205),(43232,43249),(43263,43263),(43302,43309),(43335,43347),(43392,43395),(43443,43456),(43493,43493),(43561,43574),(43587,43587),(43596,43597),(43643,43645),(43696,43696),(43698,43700),(43703,43704),(43710,43711),(43713,43713),(43755,43759),(43765,43766),(44003,44010),(44012,44013),(55216,55295),(64286,64286),(65024,65039),(65056,65071),(65279,65279),(65529,65531),(66045,66045),(66272,66272),(66422,66426),(68097,68099),(68101,68102),(68108,68111),(68152,68154),(68159,68159),(68325,68326),(68900,68903),(69446,69456),(69632,69634),(69688,69702),(69759,69762),(69808,69818),(69821,69821),(69837,69837),(69888,69890),(69927,69940),(69957,69958),(70003,70003),(70016,70018),(70067,70080),(70089,70092),(70188,70199),(70206,70206),(70367,70378),(70400,70403),(70459,70460),(70462,70468),(70471,70472),(70475,70477),(70487,70487),(70498,70499),(70502,70508),(70512,70516),(70709,70726),(70750,70750),(70832,70851),(71087,71093),(71096,71104),(71132,71133),(71216,71232),(71339,71351),(71453,71467),(71724,71738),(72145,72151),(72154,72160),(72164,72164),(72193,72202),(72243,72249),(72251,72254),(72263,72263),(72273,72283),(72330,72345),(72751,72758),(72760,72767),(72850,72871),(72873,72886),(73009,73014),(73018,73018),(73020,73021),(73023,73029),(73031,73031),(73098,73102),(73104,73105),(73107,73111),(73459,73462),(78896,78904),(92912,92916),(92976,92982),(94031,94031),(94033,94087),(94095,94098),(113821,113822),(113824,113827),(119141,119145),(119149,119170),(119173,119179),(119210,119213),(119362,119364),(121344,121398),(121403,121452),(121461,121461),(121476,121476),(121499,121503),(121505,121519),(122880,122886),(122888,122904),(122907,122913),(122915,122916),(122918,122922),(123184,123190),(123628,123631),(125136,125142),(125252,125258),(127995,127999),(917505,917505),(917536,917631),(917760,917999)),'13.0.0':((0,0),(173,173),(768,879),(1155,1161),(1425,1469),(1471,1471),(1473,1474),(1476,1477),(1479,1479),(1536,1541),(1552,1562),(1564,1564),(1611,1631),(1648,1648),(1750,1757),(1759,1764),(1767,1768),(1770,1773),(1807,1807),(1809,1809),(1840,1866),(1958,1968),(2027,2035),(2045,2045),(2070,2073),(2075,2083),(2085,2087),(2089,2093),(2137,2139),(2259,2307),(2362,2364),(2366,2383),(2385,2391),(2402,2403),(2433,2435),(2492,2492),(2494,2500),(2503,2504),(2507,2509),(2519,2519),(2530,2531),(2558,2558),(2561,2563),(2620,2620),(2622,2626),(2631,2632),(2635,2637),(2641,2641),(2672,2673),(2677,2677),(2689,2691),(2748,2748),(2750,2757),(2759,2761),(2763,2765),(2786,2787),(2810,2815),(2817,2819),(2876,2876),(2878,2884),(2887,2888),(2891,2893),(2901,2903),(2914,2915),(2946,2946),(3006,3010),(3014,3016),(3018,3021),(3031,3031),(3072,3076),(3134,3140),(3142,3144),(3146,3149),(3157,3158),(3170,3171),(3201,3203),(3260,3260),(3262,3268),(3270,3272),(3274,3277),(3285,3286),(3298,3299),(3328,3331),(3387,3388),(3390,3396),(3398,3400),(3402,3405),(3415,3415),(3426,3427),(3457,3459),(3530,3530),(3535,3540),(3542,3542),(3544,3551),(3570,3571),(3633,3633),(3636,3642),(3655,3662),(3761,3761),(3764,3772),(3784,3789),(3864,3865),(3893,3893),(3895,3895),(3897,3897),(3902,3903),(3953,3972),(3974,3975),(3981,3991),(3993,4028),(4038,4038),(4139,4158),(4182,4185),(4190,4192),(4194,4196),(4199,4205),(4209,4212),(4226,4237),(4239,4239),(4250,4253),(4448,4607),(4957,4959),(5906,5908),(5938,5940),(5970,5971),(6002,6003),(6068,6099),(6109,6109),(6155,6158),(6277,6278),(6313,6313),(6432,6443),(6448,6459),(6679,6683),(6741,6750),(6752,6780),(6783,6783),(6832,6848),(6912,6916),(6964,6980),(7019,7027),(7040,7042),(7073,7085),(7142,7155),(7204,7223),(7376,7378),(7380,7400),(7405,7405),(7412,7412),(7415,7417),(7616,7673),(7675,7679),(8203,8207),(8232,8238),(8288,8292),(8294,8303),(8400,8432),(11503,11505),(11647,11647),(11744,11775),(12330,12335),(12441,12442),(42607,42610),(42612,42621),(42654,42655),(42736,42737),(43010,43010),(43014,43014),(43019,43019),(43043,43047),(43052,43052),(43136,43137),(43188,43205),(43232,43249),(43263,43263),(43302,43309),(43335,43347),(43392,43395),(43443,43456),(43493,43493),(43561,43574),(43587,43587),(43596,43597),(43643,43645),(43696,43696),(43698,43700),(43703,43704),(43710,43711),(43713,43713),(43755,43759),(43765,43766),(44003,44010),(44012,44013),(55216,55295),(64286,64286),(65024,65039),(65056,65071),(65279,65279),(65529,65531),(66045,66045),(66272,66272),(66422,66426),(68097,68099),(68101,68102),(68108,68111),(68152,68154),(68159,68159),(68325,68326),(68900,68903),(69291,69292),(69446,69456),(69632,69634),(69688,69702),(69759,69762),(69808,69818),(69821,69821),(69837,69837),(69888,69890),(69927,69940),(69957,69958),(70003,70003),(70016,70018),(70067,70080),(70089,70092),(70094,70095),(70188,70199),(70206,70206),(70367,70378),(70400,70403),(70459,70460),(70462,70468),(70471,70472),(70475,70477),(70487,70487),(70498,70499),(70502,70508),(70512,70516),(70709,70726),(70750,70750),(70832,70851),(71087,71093),(71096,71104),(71132,71133),(71216,71232),(71339,71351),(71453,71467),(71724,71738),(71984,71989),(71991,71992),(71995,71998),(72000,72000),(72002,72003),(72145,72151),(72154,72160),(72164,72164),(72193,72202),(72243,72249),(72251,72254),(72263,72263),(72273,72283),(72330,72345),(72751,72758),(72760,72767),(72850,72871),(72873,72886),(73009,73014),(73018,73018),(73020,73021),(73023,73029),(73031,73031),(73098,73102),(73104,73105),(73107,73111),(73459,73462),(78896,78904),(92912,92916),(92976,92982),(94031,94031),(94033,94087),(94095,94098),(94180,94180),(94192,94193),(113821,113822),(113824,113827),(119141,119145),(119149,119170),(119173,119179),(119210,119213),(119362,119364),(121344,121398),(121403,121452),(121461,121461),(121476,121476),(121499,121503),(121505,121519),(122880,122886),(122888,122904),(122907,122913),(122915,122916),(122918,122922),(123184,123190),(123628,123631),(125136,125142),(125252,125258),(127995,127999),(917505,917505),(917536,917631),(917760,917999)),'14.0.0':((0,0),(173,173),(768,879),(1155,1161),(1425,1469),(1471,1471),(1473,1474),(1476,1477),(1479,1479),(1536,1541),(1552,1562),(1564,1564),(1611,1631),(1648,1648),(1750,1757),(1759,1764),(1767,1768),(1770,1773),(1807,1807),(1809,1809),(1840,1866),(1958,1968),(2027,2035),(2045,2045),(2070,2073),(2075,2083),(2085,2087),(2089,2093),(2137,2139),(2192,2193),(2200,2207),(2250,2307),(2362,2364),(2366,2383),(2385,2391),(2402,2403),(2433,2435),(2492,2492),(2494,2500),(2503,2504),(2507,2509),(2519,2519),(2530,2531),(2558,2558),(2561,2563),(2620,2620),(2622,2626),(2631,2632),(2635,2637),(2641,2641),(2672,2673),(2677,2677),(2689,2691),(2748,2748),(2750,2757),(2759,2761),(2763,2765),(2786,2787),(2810,2815),(2817,2819),(2876,2876),(2878,2884),(2887,2888),(2891,2893),(2901,2903),(2914,2915),(2946,2946),(3006,3010),(3014,3016),(3018,3021),(3031,3031),(3072,3076),(3132,3132),(3134,3140),(3142,3144),(3146,3149),(3157,3158),(3170,3171),(3201,3203),(3260,3260),(3262,3268),(3270,3272),(3274,3277),(3285,3286),(3298,3299),(3328,3331),(3387,3388),(3390,3396),(3398,3400),(3402,3405),(3415,3415),(3426,3427),(3457,3459),(3530,3530),(3535,3540),(3542,3542),(3544,3551),(3570,3571),(3633,3633),(3636,3642),(3655,3662),(3761,3761),(3764,3772),(3784,3789),(3864,3865),(3893,3893),(3895,3895),(3897,3897),(3902,3903),(3953,3972),(3974,3975),(3981,3991),(3993,4028),(4038,4038),(4139,4158),(4182,4185),(4190,4192),(4194,4196),(4199,4205),(4209,4212),(4226,4237),(4239,4239),(4250,4253),(4448,4607),(4957,4959),(5906,5909),(5938,5940),(5970,5971),(6002,6003),(6068,6099),(6109,6109),(6155,6159),(6277,6278),(6313,6313),(6432,6443),(6448,6459),(6679,6683),(6741,6750),(6752,6780),(6783,6783),(6832,6862),(6912,6916),(6964,6980),(7019,7027),(7040,7042),(7073,7085),(7142,7155),(7204,7223),(7376,7378),(7380,7400),(7405,7405),(7412,7412),(7415,7417),(7616,7679),(8203,8207),(8232,8238),(8288,8292),(8294,8303),(8400,8432),(11503,11505),(11647,11647),(11744,11775),(12330,12335),(12441,12442),(42607,42610),(42612,42621),(42654,42655),(42736,42737),(43010,43010),(43014,43014),(43019,43019),(43043,43047),(43052,43052),(43136,43137),(43188,43205),(43232,43249),(43263,43263),(43302,43309),(43335,43347),(43392,43395),(43443,43456),(43493,43493),(43561,43574),(43587,43587),(43596,43597),(43643,43645),(43696,43696),(43698,43700),(43703,43704),(43710,43711),(43713,43713),(43755,43759),(43765,43766),(44003,44010),(44012,44013),(55216,55295),(64286,64286),(65024,65039),(65056,65071),(65279,65279),(65529,65531),(66045,66045),(66272,66272),(66422,66426),(68097,68099),(68101,68102),(68108,68111),(68152,68154),(68159,68159),(68325,68326),(68900,68903),(69291,69292),(69446,69456),(69506,69509),(69632,69634),(69688,69702),(69744,69744),(69747,69748),(69759,69762),(69808,69818),(69821,69821),(69826,69826),(69837,69837),(69888,69890),(69927,69940),(69957,69958),(70003,70003),(70016,70018),(70067,70080),(70089,70092),(70094,70095),(70188,70199),(70206,70206),(70367,70378),(70400,70403),(70459,70460),(70462,70468),(70471,70472),(70475,70477),(70487,70487),(70498,70499),(70502,70508),(70512,70516),(70709,70726),(70750,70750),(70832,70851),(71087,71093),(71096,71104),(71132,71133),(71216,71232),(71339,71351),(71453,71467),(71724,71738),(71984,71989),(71991,71992),(71995,71998),(72000,72000),(72002,72003),(72145,72151),(72154,72160),(72164,72164),(72193,72202),(72243,72249),(72251,72254),(72263,72263),(72273,72283),(72330,72345),(72751,72758),(72760,72767),(72850,72871),(72873,72886),(73009,73014),(73018,73018),(73020,73021),(73023,73029),(73031,73031),(73098,73102),(73104,73105),(73107,73111),(73459,73462),(78896,78904),(92912,92916),(92976,92982),(94031,94031),(94033,94087),(94095,94098),(94180,94180),(94192,94193),(113821,113822),(113824,113827),(118528,118573),(118576,118598),(119141,119145),(119149,119170),(119173,119179),(119210,119213),(119362,119364),(121344,121398),(121403,121452),(121461,121461),(121476,121476),(121499,121503),(121505,121519),(122880,122886),(122888,122904),(122907,122913),(122915,122916),(122918,122922),(123184,123190),(123566,123566),(123628,123631),(125136,125142),(125252,125258),(127995,127999),(917505,917505),(917536,917631),(917760,917999)),'15.0.0':((0,0),(173,173),(768,879),(1155,1161),(1425,1469),(1471,1471),(1473,1474),(1476,1477),(1479,1479),(1536,1541),(1552,1562),(1564,1564),(1611,1631),(1648,1648),(1750,1757),(1759,1764),(1767,1768),(1770,1773),(1807,1807),(1809,1809),(1840,1866),(1958,1968),(2027,2035),(2045,2045),(2070,2073),(2075,2083),(2085,2087),(2089,2093),(2137,2139),(2192,2193),(2200,2207),(2250,2307),(2362,2364),(2366,2383),(2385,2391),(2402,2403),(2433,2435),(2492,2492),(2494,2500),(2503,2504),(2507,2509),(2519,2519),(2530,2531),(2558,2558),(2561,2563),(2620,2620),(2622,2626),(2631,2632),(2635,2637),(2641,2641),(2672,2673),(2677,2677),(2689,2691),(2748,2748),(2750,2757),(2759,2761),(2763,2765),(2786,2787),(2810,2815),(2817,2819),(2876,2876),(2878,2884),(2887,2888),(2891,2893),(2901,2903),(2914,2915),(2946,2946),(3006,3010),(3014,3016),(3018,3021),(3031,3031),(3072,3076),(3132,3132),(3134,3140),(3142,3144),(3146,3149),(3157,3158),(3170,3171),(3201,3203),(3260,3260),(3262,3268),(3270,3272),(3274,3277),(3285,3286),(3298,3299),(3315,3315),(3328,3331),(3387,3388),(3390,3396),(3398,3400),(3402,3405),(3415,3415),(3426,3427),(3457,3459),(3530,3530),(3535,3540),(3542,3542),(3544,3551),(3570,3571),(3633,3633),(3636,3642),(3655,3662),(3761,3761),(3764,3772),(3784,3790),(3864,3865),(3893,3893),(3895,3895),(3897,3897),(3902,3903),(3953,3972),(3974,3975),(3981,3991),(3993,4028),(4038,4038),(4139,4158),(4182,4185),(4190,4192),(4194,4196),(4199,4205),(4209,4212),(4226,4237),(4239,4239),(4250,4253),(4448,4607),(4957,4959),(5906,5909),(5938,5940),(5970,5971),(6002,6003),(6068,6099),(6109,6109),(6155,6159),(6277,6278),(6313,6313),(6432,6443),(6448,6459),(6679,6683),(6741,6750),(6752,6780),(6783,6783),(6832,6862),(6912,6916),(6964,6980),(7019,7027),(7040,7042),(7073,7085),(7142,7155),(7204,7223),(7376,7378),(7380,7400),(7405,7405),(7412,7412),(7415,7417),(7616,7679),(8203,8207),(8232,8238),(8288,8292),(8294,8303),(8400,8432),(11503,11505),(11647,11647),(11744,11775),(12330,12335),(12441,12442),(42607,42610),(42612,42621),(42654,42655),(42736,42737),(43010,43010),(43014,43014),(43019,43019),(43043,43047),(43052,43052),(43136,43137),(43188,43205),(43232,43249),(43263,43263),(43302,43309),(43335,43347),(43392,43395),(43443,43456),(43493,43493),(43561,43574),(43587,43587),(43596,43597),(43643,43645),(43696,43696),(43698,43700),(43703,43704),(43710,43711),(43713,43713),(43755,43759),(43765,43766),(44003,44010),(44012,44013),(55216,55295),(64286,64286),(65024,65039),(65056,65071),(65279,65279),(65529,65531),(66045,66045),(66272,66272),(66422,66426),(68097,68099),(68101,68102),(68108,68111),(68152,68154),(68159,68159),(68325,68326),(68900,68903),(69291,69292),(69373,69375),(69446,69456),(69506,69509),(69632,69634),(69688,69702),(69744,69744),(69747,69748),(69759,69762),(69808,69818),(69821,69821),(69826,69826),(69837,69837),(69888,69890),(69927,69940),(69957,69958),(70003,70003),(70016,70018),(70067,70080),(70089,70092),(70094,70095),(70188,70199),(70206,70206),(70209,70209),(70367,70378),(70400,70403),(70459,70460),(70462,70468),(70471,70472),(70475,70477),(70487,70487),(70498,70499),(70502,70508),(70512,70516),(70709,70726),(70750,70750),(70832,70851),(71087,71093),(71096,71104),(71132,71133),(71216,71232),(71339,71351),(71453,71467),(71724,71738),(71984,71989),(71991,71992),(71995,71998),(72000,72000),(72002,72003),(72145,72151),(72154,72160),(72164,72164),(72193,72202),(72243,72249),(72251,72254),(72263,72263),(72273,72283),(72330,72345),(72751,72758),(72760,72767),(72850,72871),(72873,72886),(73009,73014),(73018,73018),(73020,73021),(73023,73029),(73031,73031),(73098,73102),(73104,73105),(73107,73111),(73459,73462),(73472,73473),(73475,73475),(73524,73530),(73534,73538),(78896,78912),(78919,78933),(92912,92916),(92976,92982),(94031,94031),(94033,94087),(94095,94098),(94180,94180),(94192,94193),(113821,113822),(113824,113827),(118528,118573),(118576,118598),(119141,119145),(119149,119170),(119173,119179),(119210,119213),(119362,119364),(121344,121398),(121403,121452),(121461,121461),(121476,121476),(121499,121503),(121505,121519),(122880,122886),(122888,122904),(122907,122913),(122915,122916),(122918,122922),(123023,123023),(123184,123190),(123566,123566),(123628,123631),(124140,124143),(125136,125142),(125252,125258),(127995,127999),(917505,917505),(917536,917631),(917760,917999)),'15.1.0':((0,0),(173,173),(768,879),(1155,1161),(1425,1469),(1471,1471),(1473,1474),(1476,1477),(1479,1479),(1536,1541),(1552,1562),(1564,1564),(1611,1631),(1648,1648),(1750,1757),(1759,1764),(1767,1768),(1770,1773),(1807,1807),(1809,1809),(1840,1866),(1958,1968),(2027,2035),(2045,2045),(2070,2073),(2075,2083),(2085,2087),(2089,2093),(2137,2139),(2192,2193),(2200,2207),(2250,2307),(2362,2364),(2366,2383),(2385,2391),(2402,2403),(2433,2435),(2492,2492),(2494,2500),(2503,2504),(2507,2509),(2519,2519),(2530,2531),(2558,2558),(2561,2563),(2620,2620),(2622,2626),(2631,2632),(2635,2637),(2641,2641),(2672,2673),(2677,2677),(2689,2691),(2748,2748),(2750,2757),(2759,2761),(2763,2765),(2786,2787),(2810,2815),(2817,2819),(2876,2876),(2878,2884),(2887,2888),(2891,2893),(2901,2903),(2914,2915),(2946,2946),(3006,3010),(3014,3016),(3018,3021),(3031,3031),(3072,3076),(3132,3132),(3134,3140),(3142,3144),(3146,3149),(3157,3158),(3170,3171),(3201,3203),(3260,3260),(3262,3268),(3270,3272),(3274,3277),(3285,3286),(3298,3299),(3315,3315),(3328,3331),(3387,3388),(3390,3396),(3398,3400),(3402,3405),(3415,3415),(3426,3427),(3457,3459),(3530,3530),(3535,3540),(3542,3542),(3544,3551),(3570,3571),(3633,3633),(3636,3642),(3655,3662),(3761,3761),(3764,3772),(3784,3790),(3864,3865),(3893,3893),(3895,3895),(3897,3897),(3902,3903),(3953,3972),(3974,3975),(3981,3991),(3993,4028),(4038,4038),(4139,4158),(4182,4185),(4190,4192),(4194,4196),(4199,4205),(4209,4212),(4226,4237),(4239,4239),(4250,4253),(4448,4607),(4957,4959),(5906,5909),(5938,5940),(5970,5971),(6002,6003),(6068,6099),(6109,6109),(6155,6159),(6277,6278),(6313,6313),(6432,6443),(6448,6459),(6679,6683),(6741,6750),(6752,6780),(6783,6783),(6832,6862),(6912,6916),(6964,6980),(7019,7027),(7040,7042),(7073,7085),(7142,7155),(7204,7223),(7376,7378),(7380,7400),(7405,7405),(7412,7412),(7415,7417),(7616,7679),(8203,8207),(8232,8238),(8288,8292),(8294,8303),(8400,8432),(11503,11505),(11647,11647),(11744,11775),(12330,12335),(12441,12442),(42607,42610),(42612,42621),(42654,42655),(42736,42737),(43010,43010),(43014,43014),(43019,43019),(43043,43047),(43052,43052),(43136,43137),(43188,43205),(43232,43249),(43263,43263),(43302,43309),(43335,43347),(43392,43395),(43443,43456),(43493,43493),(43561,43574),(43587,43587),(43596,43597),(43643,43645),(43696,43696),(43698,43700),(43703,43704),(43710,43711),(43713,43713),(43755,43759),(43765,43766),(44003,44010),(44012,44013),(55216,55295),(64286,64286),(65024,65039),(65056,65071),(65279,65279),(65529,65531),(66045,66045),(66272,66272),(66422,66426),(68097,68099),(68101,68102),(68108,68111),(68152,68154),(68159,68159),(68325,68326),(68900,68903),(69291,69292),(69373,69375),(69446,69456),(69506,69509),(69632,69634),(69688,69702),(69744,69744),(69747,69748),(69759,69762),(69808,69818),(69821,69821),(69826,69826),(69837,69837),(69888,69890),(69927,69940),(69957,69958),(70003,70003),(70016,70018),(70067,70080),(70089,70092),(70094,70095),(70188,70199),(70206,70206),(70209,70209),(70367,70378),(70400,70403),(70459,70460),(70462,70468),(70471,70472),(70475,70477),(70487,70487),(70498,70499),(70502,70508),(70512,70516),(70709,70726),(70750,70750),(70832,70851),(71087,71093),(71096,71104),(71132,71133),(71216,71232),(71339,71351),(71453,71467),(71724,71738),(71984,71989),(71991,71992),(71995,71998),(72000,72000),(72002,72003),(72145,72151),(72154,72160),(72164,72164),(72193,72202),(72243,72249),(72251,72254),(72263,72263),(72273,72283),(72330,72345),(72751,72758),(72760,72767),(72850,72871),(72873,72886),(73009,73014),(73018,73018),(73020,73021),(73023,73029),(73031,73031),(73098,73102),(73104,73105),(73107,73111),(73459,73462),(73472,73473),(73475,73475),(73524,73530),(73534,73538),(78896,78912),(78919,78933),(92912,92916),(92976,92982),(94031,94031),(94033,94087),(94095,94098),(94180,94180),(94192,94193),(113821,113822),(113824,113827),(118528,118573),(118576,118598),(119141,119145),(119149,119170),(119173,119179),(119210,119213),(119362,119364),(121344,121398),(121403,121452),(121461,121461),(121476,121476),(121499,121503),(121505,121519),(122880,122886),(122888,122904),(122907,122913),(122915,122916),(122918,122922),(123023,123023),(123184,123190),(123566,123566),(123628,123631),(124140,124143),(125136,125142),(125252,125258),(127995,127999),(917505,917505),(917536,917631),(917760,917999))}
61,481
Python
.py
2
30,740
61,324
0.688793
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,792
table_vs16.py
ilius_pyglossary/pyglossary/ui/wcwidth/table_vs16.py
'\nExports VS16_NARROW_TO_WIDE table keyed by supporting unicode version level.\n\nThis code generated by wcwidth/bin/update-tables.py on 2023-11-07 16:43:49 UTC.\n' VS16_NARROW_TO_WIDE={'9.0.0':((35,35),(42,42),(48,57),(169,169),(174,174),(8252,8252),(8265,8265),(8482,8482),(8505,8505),(8596,8601),(8617,8618),(9000,9000),(9167,9167),(9197,9199),(9201,9202),(9208,9210),(9410,9410),(9642,9643),(9654,9654),(9664,9664),(9723,9724),(9728,9732),(9742,9742),(9745,9745),(9752,9752),(9757,9757),(9760,9760),(9762,9763),(9766,9766),(9770,9770),(9774,9775),(9784,9786),(9792,9792),(9794,9794),(9823,9824),(9827,9827),(9829,9830),(9832,9832),(9851,9851),(9854,9854),(9874,9874),(9876,9879),(9881,9881),(9883,9884),(9888,9888),(9895,9895),(9904,9905),(9928,9928),(9935,9935),(9937,9937),(9939,9939),(9961,9961),(9968,9969),(9972,9972),(9975,9977),(9986,9986),(9992,9993),(9996,9997),(9999,9999),(10002,10002),(10004,10004),(10006,10006),(10013,10013),(10017,10017),(10035,10036),(10052,10052),(10055,10055),(10083,10084),(10145,10145),(10548,10549),(11013,11015),(127344,127345),(127358,127359),(127777,127777),(127780,127788),(127798,127798),(127869,127869),(127894,127895),(127897,127899),(127902,127903),(127947,127950),(127956,127967),(127987,127987),(127989,127989),(127991,127991),(128063,128063),(128065,128065),(128253,128253),(128329,128330),(128367,128368),(128371,128377),(128391,128391),(128394,128397),(128400,128400),(128421,128421),(128424,128424),(128433,128434),(128444,128444),(128450,128452),(128465,128467),(128476,128478),(128481,128481),(128483,128483),(128488,128488),(128495,128495),(128499,128499),(128506,128506),(128715,128715),(128717,128719),(128736,128741),(128745,128745),(128752,128752),(128755,128755))}
1,729
Python
.py
2
864
1,563
0.711227
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,793
wcwidth.py
ilius_pyglossary/pyglossary/ui/wcwidth/wcwidth.py
'\nThis is a python implementation of wcwidth() and wcswidth().\n\nhttps://github.com/jquast/wcwidth\n\nfrom Markus Kuhn\'s C code, retrieved from:\n\n http://www.cl.cam.ac.uk/~mgk25/ucs/wcwidth.c\n\nThis is an implementation of wcwidth() and wcswidth() (defined in\nIEEE Std 1002.1-2001) for Unicode.\n\nhttp://www.opengroup.org/onlinepubs/007904975/functions/wcwidth.html\nhttp://www.opengroup.org/onlinepubs/007904975/functions/wcswidth.html\n\nIn fixed-width output devices, Latin characters all occupy a single\n"cell" position of equal width, whereas ideographic CJK characters\noccupy two such cells. Interoperability between terminal-line\napplications and (teletype-style) character terminals using the\nUTF-8 encoding requires agreement on which character should advance\nthe cursor by how many cell positions. No established formal\nstandards exist at present on which Unicode character shall occupy\nhow many cell positions on character terminals. These routines are\na first attempt of defining such behavior based on simple rules\napplied to data provided by the Unicode Consortium.\n\nFor some graphical characters, the Unicode standard explicitly\ndefines a character-cell width via the definition of the East Asian\nFullWidth (F), Wide (W), Half-width (H), and Narrow (Na) classes.\nIn all these cases, there is no ambiguity about which width a\nterminal shall use. For characters in the East Asian Ambiguous (A)\nclass, the width choice depends purely on a preference of backward\ncompatibility with either historic CJK or Western practice.\nChoosing single-width for these characters is easy to justify as\nthe appropriate long-term solution, as the CJK practice of\ndisplaying these characters as double-width comes from historic\nimplementation simplicity (8-bit encoded characters were displayed\nsingle-width and 16-bit ones double-width, even for Greek,\nCyrillic, etc.) and not any typographic considerations.\n\nMuch less clear is the choice of width for the Not East Asian\n(Neutral) class. Existing practice does not dictate a width for any\nof these characters. It would nevertheless make sense\ntypographically to allocate two character cells to characters such\nas for instance EM SPACE or VOLUME INTEGRAL, which cannot be\nrepresented adequately with a single-width glyph. The following\nroutines at present merely assign a single-cell width to all\nneutral characters, in the interest of simplicity. This is not\nentirely satisfactory and should be reconsidered before\nestablishing a formal standard in this area. At the moment, the\ndecision which Not East Asian (Neutral) characters should be\nrepresented by double-width glyphs cannot yet be answered by\napplying a simple rule from the Unicode database content. Setting\nup a proper standard for the behavior of UTF-8 character terminals\nwill require a careful analysis not only of each Unicode character,\nbut also of each presentation form, something the author of these\nroutines has avoided to do so far.\n\nhttp://www.unicode.org/unicode/reports/tr11/\n\nLatest version: http://www.cl.cam.ac.uk/~mgk25/ucs/wcwidth.c\n' from __future__ import division _B='auto' _A=None import os,sys,warnings from.table_vs16 import VS16_NARROW_TO_WIDE from.table_wide import WIDE_EASTASIAN from.table_zero import ZERO_WIDTH from.unicode_versions import list_versions try:from functools import lru_cache except ImportError:from backports.functools_lru_cache import lru_cache _PY3=sys.version_info[0]>=3 def _bisearch(ucs,table): '\n Auxiliary function for binary search in interval table.\n\n :arg int ucs: Ordinal value of unicode character.\n :arg list table: List of starting and ending ranges of ordinal values,\n in form of ``[(start, end), ...]``.\n :rtype: int\n :returns: 1 if ordinal value ucs is found within lookup table, else 0.\n ';B=ucs;A=table;E=0;C=len(A)-1 if B<A[0][0]or B>A[C][1]:return 0 while C>=E: D=(E+C)//2 if B>A[D][1]:E=D+1 elif B<A[D][0]:C=D-1 else:return 1 return 0 @lru_cache(maxsize=1000) def wcwidth(wc,unicode_version=_B): "\n Given one Unicode character, return its printable length on a terminal.\n\n :param str wc: A single Unicode character.\n :param str unicode_version: A Unicode version number, such as\n ``'6.0.0'``. A list of version levels suported by wcwidth\n is returned by :func:`list_versions`.\n\n Any version string may be specified without error -- the nearest\n matching version is selected. When ``latest`` (default), the\n highest Unicode version level is used.\n :return: The width, in cells, necessary to display the character of\n Unicode string character, ``wc``. Returns 0 if the ``wc`` argument has\n no printable effect on a terminal (such as NUL '\\0'), -1 if ``wc`` is\n not printable, or has an indeterminate effect on the terminal, such as\n a control character. Otherwise, the number of column positions the\n character occupies on a graphic terminal (1 or 2) is returned.\n :rtype: int\n\n See :ref:`Specification` for details of cell measurement.\n ";A=ord(wc)if wc else 0 if 32<=A<127:return 1 if A and A<32 or 127<=A<160:return-1 B=_wcmatch_version(unicode_version) if _bisearch(A,ZERO_WIDTH[B]):return 0 return 1+_bisearch(A,WIDE_EASTASIAN[B]) def wcswidth(pwcs,n=_A,unicode_version=_B): "\n Given a unicode string, return its printable length on a terminal.\n\n :param str pwcs: Measure width of given unicode string.\n :param int n: When ``n`` is None (default), return the length of the entire\n string, otherwise only the first ``n`` characters are measured. This\n argument exists only for compatibility with the C POSIX function\n signature. It is suggested instead to use python's string slicing\n capability, ``wcswidth(pwcs[:n])``\n :param str unicode_version: An explicit definition of the unicode version\n level to use for determination, may be ``auto`` (default), which uses\n the Environment Variable, ``UNICODE_VERSION`` if defined, or the latest\n available unicode version, otherwise.\n :rtype: int\n :returns: The width, in cells, needed to display the first ``n`` characters\n of the unicode string ``pwcs``. Returns ``-1`` for C0 and C1 control\n characters!\n\n See :ref:`Specification` for details of cell measurement.\n ";G=unicode_version;E=_A;H=len(pwcs)if n is _A else n;F=0;A=0;B=_A while A<H: C=pwcs[A] if C=='\u200d':A+=2;continue if C=='�'and B: if E is _A:E=_wcversion_value(_wcmatch_version(G)) if E>=(9,0,0):F+=_bisearch(ord(B),VS16_NARROW_TO_WIDE['9.0.0']);B=_A A+=1;continue D=wcwidth(C,G) if D<0:return D if D>0:B=C F+=D;A+=1 return F @lru_cache(maxsize=128) def _wcversion_value(ver_string):'\n Integer-mapped value of given dotted version string.\n\n :param str ver_string: Unicode version string, of form ``n.n.n``.\n :rtype: tuple(int)\n :returns: tuple of digit tuples, ``tuple(int, [...])``.\n ';A=tuple(map(int,ver_string.split('.')));return A @lru_cache(maxsize=8) def _wcmatch_version(given_version): "\n Return nearest matching supported Unicode version level.\n\n If an exact match is not determined, the nearest lowest version level is\n returned after a warning is emitted. For example, given supported levels\n ``4.1.0`` and ``5.0.0``, and a version string of ``4.9.9``, then ``4.1.0``\n is selected and returned:\n\n >>> _wcmatch_version('4.9.9')\n '4.1.0'\n >>> _wcmatch_version('8.0')\n '8.0.0'\n >>> _wcmatch_version('1')\n '4.1.0'\n\n :param str given_version: given version for compare, may be ``auto``\n (default), to select Unicode Version from Environment Variable,\n ``UNICODE_VERSION``. If the environment variable is not set, then the\n latest is used.\n :rtype: str\n :returns: unicode string, or non-unicode ``str`` type for python 2\n when given ``version`` is also type ``str``.\n ";G='latest';A=given_version;D=not _PY3 and isinstance(A,str) if D:B=list(map(lambda ucs:ucs.encode(),list_versions())) else:B=list_versions() C=B[-1] if A in(_B,_B):A=os.environ.get('UNICODE_VERSION',G if not D else C.encode()) if A in(G,G):return C if not D else C.encode() if A in B:return A if not D else A.encode() try:E=_wcversion_value(A) except ValueError:warnings.warn("UNICODE_VERSION value, {given_version!r}, is invalid. Value should be in form of `integer[.]+', the latest supported unicode version {latest_version!r} has been inferred.".format(given_version=A,latest_version=C));return C if not D else C.encode() F=B[0];J=_wcversion_value(F) if E<=J:warnings.warn('UNICODE_VERSION value, {given_version!r}, is lower than any available unicode version. Returning lowest version level, {earliest_version!r}'.format(given_version=A,earliest_version=F));return F if not D else F.encode() for(H,K)in enumerate(B): try:I=_wcversion_value(B[H+1]) except IndexError:return C if not D else C.encode() if E==I[:len(E)]:return B[H+1] if I>E:return K assert False,('Code path unreachable',A,B)
9,154
Python
.py
64
141.03125
3,115
0.731493
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,794
table_wide.py
ilius_pyglossary/pyglossary/ui/wcwidth/table_wide.py
'\nExports WIDE_EASTASIAN table keyed by supporting unicode version level.\n\nThis code generated by wcwidth/bin/update-tables.py on 2024-01-06 01:39:49 UTC.\n' WIDE_EASTASIAN={'4.1.0':((4352,4441),(4447,4447),(9001,9002),(11904,11929),(11931,12019),(12032,12245),(12272,12283),(12288,12329),(12336,12350),(12353,12438),(12443,12543),(12549,12588),(12593,12686),(12688,12727),(12736,12751),(12784,12830),(12832,12867),(12880,13054),(13056,19893),(19968,40891),(40960,42124),(42128,42182),(44032,55203),(63744,64045),(64048,64106),(64112,64217),(65040,65049),(65072,65106),(65108,65126),(65128,65131),(65281,65376),(65504,65510),(131072,196605),(196608,262141)),'5.0.0':((4352,4441),(4447,4447),(9001,9002),(11904,11929),(11931,12019),(12032,12245),(12272,12283),(12288,12329),(12336,12350),(12353,12438),(12443,12543),(12549,12588),(12593,12686),(12688,12727),(12736,12751),(12784,12830),(12832,12867),(12880,13054),(13056,19893),(19968,40891),(40960,42124),(42128,42182),(44032,55203),(63744,64045),(64048,64106),(64112,64217),(65040,65049),(65072,65106),(65108,65126),(65128,65131),(65281,65376),(65504,65510),(131072,196605),(196608,262141)),'5.1.0':((4352,4441),(4447,4447),(9001,9002),(11904,11929),(11931,12019),(12032,12245),(12272,12283),(12288,12329),(12336,12350),(12353,12438),(12443,12543),(12549,12589),(12593,12686),(12688,12727),(12736,12771),(12784,12830),(12832,12867),(12880,13054),(13056,19893),(19968,40899),(40960,42124),(42128,42182),(44032,55203),(63744,64045),(64048,64106),(64112,64217),(65040,65049),(65072,65106),(65108,65126),(65128,65131),(65281,65376),(65504,65510),(131072,196605),(196608,262141)),'5.2.0':((4352,4447),(9001,9002),(11904,11929),(11931,12019),(12032,12245),(12272,12283),(12288,12329),(12336,12350),(12353,12438),(12443,12543),(12549,12589),(12593,12686),(12688,12727),(12736,12771),(12784,12830),(12832,12871),(12880,13054),(13056,19903),(19968,42124),(42128,42182),(43360,43388),(44032,55203),(63744,64255),(65040,65049),(65072,65106),(65108,65126),(65128,65131),(65281,65376),(65504,65510),(127488,127488),(127504,127537),(127552,127560),(131072,196605),(196608,262141)),'6.0.0':((4352,4447),(9001,9002),(11904,11929),(11931,12019),(12032,12245),(12272,12283),(12288,12329),(12336,12350),(12353,12438),(12443,12543),(12549,12589),(12593,12686),(12688,12730),(12736,12771),(12784,12830),(12832,12871),(12880,13054),(13056,19903),(19968,42124),(42128,42182),(43360,43388),(44032,55203),(63744,64255),(65040,65049),(65072,65106),(65108,65126),(65128,65131),(65281,65376),(65504,65510),(110592,110593),(127488,127490),(127504,127546),(127552,127560),(127568,127569),(131072,196605),(196608,262141)),'6.1.0':((4352,4447),(9001,9002),(11904,11929),(11931,12019),(12032,12245),(12272,12283),(12288,12329),(12336,12350),(12353,12438),(12443,12543),(12549,12589),(12593,12686),(12688,12730),(12736,12771),(12784,12830),(12832,12871),(12880,13054),(13056,19903),(19968,42124),(42128,42182),(43360,43388),(44032,55203),(63744,64255),(65040,65049),(65072,65106),(65108,65126),(65128,65131),(65281,65376),(65504,65510),(110592,110593),(127488,127490),(127504,127546),(127552,127560),(127568,127569),(131072,196605),(196608,262141)),'6.2.0':((4352,4447),(9001,9002),(11904,11929),(11931,12019),(12032,12245),(12272,12283),(12288,12329),(12336,12350),(12353,12438),(12443,12543),(12549,12589),(12593,12686),(12688,12730),(12736,12771),(12784,12830),(12832,12871),(12880,13054),(13056,19903),(19968,42124),(42128,42182),(43360,43388),(44032,55203),(63744,64255),(65040,65049),(65072,65106),(65108,65126),(65128,65131),(65281,65376),(65504,65510),(110592,110593),(127488,127490),(127504,127546),(127552,127560),(127568,127569),(131072,196605),(196608,262141)),'6.3.0':((4352,4447),(9001,9002),(11904,11929),(11931,12019),(12032,12245),(12272,12283),(12288,12329),(12336,12350),(12353,12438),(12443,12543),(12549,12589),(12593,12686),(12688,12730),(12736,12771),(12784,12830),(12832,12871),(12880,13054),(13056,19903),(19968,42124),(42128,42182),(43360,43388),(44032,55203),(63744,64255),(65040,65049),(65072,65106),(65108,65126),(65128,65131),(65281,65376),(65504,65510),(110592,110593),(127488,127490),(127504,127546),(127552,127560),(127568,127569),(131072,196605),(196608,262141)),'7.0.0':((4352,4447),(9001,9002),(11904,11929),(11931,12019),(12032,12245),(12272,12283),(12288,12329),(12336,12350),(12353,12438),(12443,12543),(12549,12589),(12593,12686),(12688,12730),(12736,12771),(12784,12830),(12832,12871),(12880,13054),(13056,19903),(19968,42124),(42128,42182),(43360,43388),(44032,55203),(63744,64255),(65040,65049),(65072,65106),(65108,65126),(65128,65131),(65281,65376),(65504,65510),(110592,110593),(127488,127490),(127504,127546),(127552,127560),(127568,127569),(131072,196605),(196608,262141)),'8.0.0':((4352,4447),(9001,9002),(11904,11929),(11931,12019),(12032,12245),(12272,12283),(12288,12329),(12336,12350),(12353,12438),(12443,12543),(12549,12589),(12593,12686),(12688,12730),(12736,12771),(12784,12830),(12832,12871),(12880,13054),(13056,19903),(19968,42124),(42128,42182),(43360,43388),(44032,55203),(63744,64255),(65040,65049),(65072,65106),(65108,65126),(65128,65131),(65281,65376),(65504,65510),(110592,110593),(127488,127490),(127504,127546),(127552,127560),(127568,127569),(131072,196605),(196608,262141)),'9.0.0':((4352,4447),(8986,8987),(9001,9002),(9193,9196),(9200,9200),(9203,9203),(9725,9726),(9748,9749),(9800,9811),(9855,9855),(9875,9875),(9889,9889),(9898,9899),(9917,9918),(9924,9925),(9934,9934),(9940,9940),(9962,9962),(9970,9971),(9973,9973),(9978,9978),(9981,9981),(9989,9989),(9994,9995),(10024,10024),(10060,10060),(10062,10062),(10067,10069),(10071,10071),(10133,10135),(10160,10160),(10175,10175),(11035,11036),(11088,11088),(11093,11093),(11904,11929),(11931,12019),(12032,12245),(12272,12283),(12288,12329),(12336,12350),(12353,12438),(12443,12543),(12549,12589),(12593,12686),(12688,12730),(12736,12771),(12784,12830),(12832,12871),(12880,13054),(13056,19903),(19968,42124),(42128,42182),(43360,43388),(44032,55203),(63744,64255),(65040,65049),(65072,65106),(65108,65126),(65128,65131),(65281,65376),(65504,65510),(94176,94176),(94208,100332),(100352,101106),(110592,110593),(126980,126980),(127183,127183),(127374,127374),(127377,127386),(127488,127490),(127504,127547),(127552,127560),(127568,127569),(127744,127776),(127789,127797),(127799,127868),(127870,127891),(127904,127946),(127951,127955),(127968,127984),(127988,127988),(127992,127994),(128000,128062),(128064,128064),(128066,128252),(128255,128317),(128331,128334),(128336,128359),(128378,128378),(128405,128406),(128420,128420),(128507,128591),(128640,128709),(128716,128716),(128720,128722),(128747,128748),(128756,128758),(129296,129310),(129312,129319),(129328,129328),(129331,129342),(129344,129355),(129360,129374),(129408,129425),(129472,129472),(131072,196605),(196608,262141)),'10.0.0':((4352,4447),(8986,8987),(9001,9002),(9193,9196),(9200,9200),(9203,9203),(9725,9726),(9748,9749),(9800,9811),(9855,9855),(9875,9875),(9889,9889),(9898,9899),(9917,9918),(9924,9925),(9934,9934),(9940,9940),(9962,9962),(9970,9971),(9973,9973),(9978,9978),(9981,9981),(9989,9989),(9994,9995),(10024,10024),(10060,10060),(10062,10062),(10067,10069),(10071,10071),(10133,10135),(10160,10160),(10175,10175),(11035,11036),(11088,11088),(11093,11093),(11904,11929),(11931,12019),(12032,12245),(12272,12283),(12288,12329),(12336,12350),(12353,12438),(12443,12543),(12549,12590),(12593,12686),(12688,12730),(12736,12771),(12784,12830),(12832,12871),(12880,13054),(13056,19903),(19968,42124),(42128,42182),(43360,43388),(44032,55203),(63744,64255),(65040,65049),(65072,65106),(65108,65126),(65128,65131),(65281,65376),(65504,65510),(94176,94177),(94208,100332),(100352,101106),(110592,110878),(110960,111355),(126980,126980),(127183,127183),(127374,127374),(127377,127386),(127488,127490),(127504,127547),(127552,127560),(127568,127569),(127584,127589),(127744,127776),(127789,127797),(127799,127868),(127870,127891),(127904,127946),(127951,127955),(127968,127984),(127988,127988),(127992,127994),(128000,128062),(128064,128064),(128066,128252),(128255,128317),(128331,128334),(128336,128359),(128378,128378),(128405,128406),(128420,128420),(128507,128591),(128640,128709),(128716,128716),(128720,128722),(128747,128748),(128756,128760),(129296,129342),(129344,129356),(129360,129387),(129408,129431),(129472,129472),(129488,129510),(131072,196605),(196608,262141)),'11.0.0':((4352,4447),(8986,8987),(9001,9002),(9193,9196),(9200,9200),(9203,9203),(9725,9726),(9748,9749),(9800,9811),(9855,9855),(9875,9875),(9889,9889),(9898,9899),(9917,9918),(9924,9925),(9934,9934),(9940,9940),(9962,9962),(9970,9971),(9973,9973),(9978,9978),(9981,9981),(9989,9989),(9994,9995),(10024,10024),(10060,10060),(10062,10062),(10067,10069),(10071,10071),(10133,10135),(10160,10160),(10175,10175),(11035,11036),(11088,11088),(11093,11093),(11904,11929),(11931,12019),(12032,12245),(12272,12283),(12288,12329),(12336,12350),(12353,12438),(12443,12543),(12549,12591),(12593,12686),(12688,12730),(12736,12771),(12784,12830),(12832,12871),(12880,13054),(13056,19903),(19968,42124),(42128,42182),(43360,43388),(44032,55203),(63744,64255),(65040,65049),(65072,65106),(65108,65126),(65128,65131),(65281,65376),(65504,65510),(94176,94177),(94208,100337),(100352,101106),(110592,110878),(110960,111355),(126980,126980),(127183,127183),(127374,127374),(127377,127386),(127488,127490),(127504,127547),(127552,127560),(127568,127569),(127584,127589),(127744,127776),(127789,127797),(127799,127868),(127870,127891),(127904,127946),(127951,127955),(127968,127984),(127988,127988),(127992,127994),(128000,128062),(128064,128064),(128066,128252),(128255,128317),(128331,128334),(128336,128359),(128378,128378),(128405,128406),(128420,128420),(128507,128591),(128640,128709),(128716,128716),(128720,128722),(128747,128748),(128756,128761),(129296,129342),(129344,129392),(129395,129398),(129402,129402),(129404,129442),(129456,129465),(129472,129474),(129488,129535),(131072,196605),(196608,262141)),'12.0.0':((4352,4447),(8986,8987),(9001,9002),(9193,9196),(9200,9200),(9203,9203),(9725,9726),(9748,9749),(9800,9811),(9855,9855),(9875,9875),(9889,9889),(9898,9899),(9917,9918),(9924,9925),(9934,9934),(9940,9940),(9962,9962),(9970,9971),(9973,9973),(9978,9978),(9981,9981),(9989,9989),(9994,9995),(10024,10024),(10060,10060),(10062,10062),(10067,10069),(10071,10071),(10133,10135),(10160,10160),(10175,10175),(11035,11036),(11088,11088),(11093,11093),(11904,11929),(11931,12019),(12032,12245),(12272,12283),(12288,12329),(12336,12350),(12353,12438),(12443,12543),(12549,12591),(12593,12686),(12688,12730),(12736,12771),(12784,12830),(12832,12871),(12880,13054),(13056,19903),(19968,42124),(42128,42182),(43360,43388),(44032,55203),(63744,64255),(65040,65049),(65072,65106),(65108,65126),(65128,65131),(65281,65376),(65504,65510),(94176,94179),(94208,100343),(100352,101106),(110592,110878),(110928,110930),(110948,110951),(110960,111355),(126980,126980),(127183,127183),(127374,127374),(127377,127386),(127488,127490),(127504,127547),(127552,127560),(127568,127569),(127584,127589),(127744,127776),(127789,127797),(127799,127868),(127870,127891),(127904,127946),(127951,127955),(127968,127984),(127988,127988),(127992,127994),(128000,128062),(128064,128064),(128066,128252),(128255,128317),(128331,128334),(128336,128359),(128378,128378),(128405,128406),(128420,128420),(128507,128591),(128640,128709),(128716,128716),(128720,128722),(128725,128725),(128747,128748),(128756,128762),(128992,129003),(129293,129393),(129395,129398),(129402,129442),(129445,129450),(129454,129482),(129485,129535),(129648,129651),(129656,129658),(129664,129666),(129680,129685),(131072,196605),(196608,262141)),'12.1.0':((4352,4447),(8986,8987),(9001,9002),(9193,9196),(9200,9200),(9203,9203),(9725,9726),(9748,9749),(9800,9811),(9855,9855),(9875,9875),(9889,9889),(9898,9899),(9917,9918),(9924,9925),(9934,9934),(9940,9940),(9962,9962),(9970,9971),(9973,9973),(9978,9978),(9981,9981),(9989,9989),(9994,9995),(10024,10024),(10060,10060),(10062,10062),(10067,10069),(10071,10071),(10133,10135),(10160,10160),(10175,10175),(11035,11036),(11088,11088),(11093,11093),(11904,11929),(11931,12019),(12032,12245),(12272,12283),(12288,12329),(12336,12350),(12353,12438),(12443,12543),(12549,12591),(12593,12686),(12688,12730),(12736,12771),(12784,12830),(12832,12871),(12880,19903),(19968,42124),(42128,42182),(43360,43388),(44032,55203),(63744,64255),(65040,65049),(65072,65106),(65108,65126),(65128,65131),(65281,65376),(65504,65510),(94176,94179),(94208,100343),(100352,101106),(110592,110878),(110928,110930),(110948,110951),(110960,111355),(126980,126980),(127183,127183),(127374,127374),(127377,127386),(127488,127490),(127504,127547),(127552,127560),(127568,127569),(127584,127589),(127744,127776),(127789,127797),(127799,127868),(127870,127891),(127904,127946),(127951,127955),(127968,127984),(127988,127988),(127992,127994),(128000,128062),(128064,128064),(128066,128252),(128255,128317),(128331,128334),(128336,128359),(128378,128378),(128405,128406),(128420,128420),(128507,128591),(128640,128709),(128716,128716),(128720,128722),(128725,128725),(128747,128748),(128756,128762),(128992,129003),(129293,129393),(129395,129398),(129402,129442),(129445,129450),(129454,129482),(129485,129535),(129648,129651),(129656,129658),(129664,129666),(129680,129685),(131072,196605),(196608,262141)),'13.0.0':((4352,4447),(8986,8987),(9001,9002),(9193,9196),(9200,9200),(9203,9203),(9725,9726),(9748,9749),(9800,9811),(9855,9855),(9875,9875),(9889,9889),(9898,9899),(9917,9918),(9924,9925),(9934,9934),(9940,9940),(9962,9962),(9970,9971),(9973,9973),(9978,9978),(9981,9981),(9989,9989),(9994,9995),(10024,10024),(10060,10060),(10062,10062),(10067,10069),(10071,10071),(10133,10135),(10160,10160),(10175,10175),(11035,11036),(11088,11088),(11093,11093),(11904,11929),(11931,12019),(12032,12245),(12272,12283),(12288,12329),(12336,12350),(12353,12438),(12443,12543),(12549,12591),(12593,12686),(12688,12771),(12784,12830),(12832,12871),(12880,19903),(19968,42124),(42128,42182),(43360,43388),(44032,55203),(63744,64255),(65040,65049),(65072,65106),(65108,65126),(65128,65131),(65281,65376),(65504,65510),(94176,94179),(94208,100343),(100352,101589),(101632,101640),(110592,110878),(110928,110930),(110948,110951),(110960,111355),(126980,126980),(127183,127183),(127374,127374),(127377,127386),(127488,127490),(127504,127547),(127552,127560),(127568,127569),(127584,127589),(127744,127776),(127789,127797),(127799,127868),(127870,127891),(127904,127946),(127951,127955),(127968,127984),(127988,127988),(127992,127994),(128000,128062),(128064,128064),(128066,128252),(128255,128317),(128331,128334),(128336,128359),(128378,128378),(128405,128406),(128420,128420),(128507,128591),(128640,128709),(128716,128716),(128720,128722),(128725,128727),(128747,128748),(128756,128764),(128992,129003),(129292,129338),(129340,129349),(129351,129400),(129402,129483),(129485,129535),(129648,129652),(129656,129658),(129664,129670),(129680,129704),(129712,129718),(129728,129730),(129744,129750),(131072,196605),(196608,262141)),'14.0.0':((4352,4447),(8986,8987),(9001,9002),(9193,9196),(9200,9200),(9203,9203),(9725,9726),(9748,9749),(9800,9811),(9855,9855),(9875,9875),(9889,9889),(9898,9899),(9917,9918),(9924,9925),(9934,9934),(9940,9940),(9962,9962),(9970,9971),(9973,9973),(9978,9978),(9981,9981),(9989,9989),(9994,9995),(10024,10024),(10060,10060),(10062,10062),(10067,10069),(10071,10071),(10133,10135),(10160,10160),(10175,10175),(11035,11036),(11088,11088),(11093,11093),(11904,11929),(11931,12019),(12032,12245),(12272,12283),(12288,12329),(12336,12350),(12353,12438),(12443,12543),(12549,12591),(12593,12686),(12688,12771),(12784,12830),(12832,12871),(12880,19903),(19968,42124),(42128,42182),(43360,43388),(44032,55203),(63744,64255),(65040,65049),(65072,65106),(65108,65126),(65128,65131),(65281,65376),(65504,65510),(94176,94179),(94208,100343),(100352,101589),(101632,101640),(110576,110579),(110581,110587),(110589,110590),(110592,110882),(110928,110930),(110948,110951),(110960,111355),(126980,126980),(127183,127183),(127374,127374),(127377,127386),(127488,127490),(127504,127547),(127552,127560),(127568,127569),(127584,127589),(127744,127776),(127789,127797),(127799,127868),(127870,127891),(127904,127946),(127951,127955),(127968,127984),(127988,127988),(127992,127994),(128000,128062),(128064,128064),(128066,128252),(128255,128317),(128331,128334),(128336,128359),(128378,128378),(128405,128406),(128420,128420),(128507,128591),(128640,128709),(128716,128716),(128720,128722),(128725,128727),(128733,128735),(128747,128748),(128756,128764),(128992,129003),(129008,129008),(129292,129338),(129340,129349),(129351,129535),(129648,129652),(129656,129660),(129664,129670),(129680,129708),(129712,129722),(129728,129733),(129744,129753),(129760,129767),(129776,129782),(131072,196605),(196608,262141)),'15.0.0':((4352,4447),(8986,8987),(9001,9002),(9193,9196),(9200,9200),(9203,9203),(9725,9726),(9748,9749),(9800,9811),(9855,9855),(9875,9875),(9889,9889),(9898,9899),(9917,9918),(9924,9925),(9934,9934),(9940,9940),(9962,9962),(9970,9971),(9973,9973),(9978,9978),(9981,9981),(9989,9989),(9994,9995),(10024,10024),(10060,10060),(10062,10062),(10067,10069),(10071,10071),(10133,10135),(10160,10160),(10175,10175),(11035,11036),(11088,11088),(11093,11093),(11904,11929),(11931,12019),(12032,12245),(12272,12283),(12288,12329),(12336,12350),(12353,12438),(12443,12543),(12549,12591),(12593,12686),(12688,12771),(12784,12830),(12832,12871),(12880,19903),(19968,42124),(42128,42182),(43360,43388),(44032,55203),(63744,64255),(65040,65049),(65072,65106),(65108,65126),(65128,65131),(65281,65376),(65504,65510),(94176,94179),(94208,100343),(100352,101589),(101632,101640),(110576,110579),(110581,110587),(110589,110590),(110592,110882),(110898,110898),(110928,110930),(110933,110933),(110948,110951),(110960,111355),(126980,126980),(127183,127183),(127374,127374),(127377,127386),(127488,127490),(127504,127547),(127552,127560),(127568,127569),(127584,127589),(127744,127776),(127789,127797),(127799,127868),(127870,127891),(127904,127946),(127951,127955),(127968,127984),(127988,127988),(127992,127994),(128000,128062),(128064,128064),(128066,128252),(128255,128317),(128331,128334),(128336,128359),(128378,128378),(128405,128406),(128420,128420),(128507,128591),(128640,128709),(128716,128716),(128720,128722),(128725,128727),(128732,128735),(128747,128748),(128756,128764),(128992,129003),(129008,129008),(129292,129338),(129340,129349),(129351,129535),(129648,129660),(129664,129672),(129680,129725),(129727,129733),(129742,129755),(129760,129768),(129776,129784),(131072,196605),(196608,262141)),'15.1.0':((4352,4447),(8986,8987),(9001,9002),(9193,9196),(9200,9200),(9203,9203),(9725,9726),(9748,9749),(9800,9811),(9855,9855),(9875,9875),(9889,9889),(9898,9899),(9917,9918),(9924,9925),(9934,9934),(9940,9940),(9962,9962),(9970,9971),(9973,9973),(9978,9978),(9981,9981),(9989,9989),(9994,9995),(10024,10024),(10060,10060),(10062,10062),(10067,10069),(10071,10071),(10133,10135),(10160,10160),(10175,10175),(11035,11036),(11088,11088),(11093,11093),(11904,11929),(11931,12019),(12032,12245),(12272,12329),(12336,12350),(12353,12438),(12443,12543),(12549,12591),(12593,12686),(12688,12771),(12783,12830),(12832,12871),(12880,19903),(19968,42124),(42128,42182),(43360,43388),(44032,55203),(63744,64255),(65040,65049),(65072,65106),(65108,65126),(65128,65131),(65281,65376),(65504,65510),(94176,94179),(94208,100343),(100352,101589),(101632,101640),(110576,110579),(110581,110587),(110589,110590),(110592,110882),(110898,110898),(110928,110930),(110933,110933),(110948,110951),(110960,111355),(126980,126980),(127183,127183),(127374,127374),(127377,127386),(127488,127490),(127504,127547),(127552,127560),(127568,127569),(127584,127589),(127744,127776),(127789,127797),(127799,127868),(127870,127891),(127904,127946),(127951,127955),(127968,127984),(127988,127988),(127992,127994),(128000,128062),(128064,128064),(128066,128252),(128255,128317),(128331,128334),(128336,128359),(128378,128378),(128405,128406),(128420,128420),(128507,128591),(128640,128709),(128716,128716),(128720,128722),(128725,128727),(128732,128735),(128747,128748),(128756,128764),(128992,129003),(129008,129008),(129292,129338),(129340,129349),(129351,129535),(129648,129660),(129664,129672),(129680,129725),(129727,129733),(129742,129755),(129760,129768),(129776,129784),(131072,196605),(196608,262141))}
20,432
Python
.py
2
10,215.5
20,271
0.719397
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,795
unicode_versions.py
ilius_pyglossary/pyglossary/ui/wcwidth/unicode_versions.py
'\nExports function list_versions() for unicode version level support.\n\nThis code generated by wcwidth/bin/update-tables.py on 2023-09-14 15:45:33 UTC.\n' def list_versions():'\n Return Unicode version levels supported by this module release.\n\n Any of the version strings returned may be used as keyword argument\n ``unicode_version`` to the ``wcwidth()`` family of functions.\n\n :returns: Supported Unicode version numbers in ascending sorted order.\n :rtype: list[str]\n ';return'4.1.0','5.0.0','5.1.0','5.2.0','6.0.0','6.1.0','6.2.0','6.3.0','7.0.0','8.0.0','9.0.0','10.0.0','11.0.0','12.0.0','12.1.0','13.0.0','14.0.0','15.0.0','15.1.0'
663
Python
.py
2
331
506
0.664653
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,796
pureSalsa20.py
ilius_pyglossary/pyglossary/plugin_lib/pureSalsa20.py
# coding: utf-8 # mypy: ignore-errors # Copyright (C) 2016-2023 Saeed Rasooli on https://github.com/ilius/pyglossary/ # Copyright (C) 2015 Z. H. Liu on https://github.com/zhansliu/writemdict # pureSalsa20.py -- a pure Python implementation of the Salsa20 cipher, # ported to Python 3 # v4.0: Added Python 3 support, dropped support for Python <= 2.5. # // zhansliu # Original comments below. # ==================================================================== # There are comments here by two authors about three pieces of software: # comments by Larry Bugbee about # Salsa20, the stream cipher by Daniel J. Bernstein # (including comments about the speed of the C version) and # pySalsa20, Bugbee's own Python wrapper for salsa20.c # (including some references), and # comments by Steve Witham about # pureSalsa20, Witham's pure Python 2.5 implementation of Salsa20, # which follows pySalsa20's API, and is in this file. # Salsa20: a Fast Streaming Cipher (comments by Larry Bugbee) # ----------------------------------------------------------- # Salsa20 is a fast stream cipher written by Daniel Bernstein # that basically uses a hash function and XOR making for fast # encryption. (Decryption uses the same function.) Salsa20 # is simple and quick. # Some Salsa20 parameter values... # design strength 128 bits # key length 128 or 256 bits, exactly # IV, aka nonce 64 bits, always # chunk size must be in multiples of 64 bytes # Salsa20 has two reduced versions, 8 and 12 rounds each. # One benchmark (10 MB): # 1.5GHz PPC G4 102/97/89 MB/sec for 8/12/20 rounds # AMD Athlon 2500+ 77/67/53 MB/sec for 8/12/20 rounds # (no I/O and before Python GC kicks in) # Salsa20 is a Phase 3 finalist in the EU eSTREAM competition # and appears to be one of the fastest ciphers. It is well # documented so I will not attempt any injustice here. Please # see "References" below. # ...and Salsa20 is "free for any use". # pySalsa20: a Python wrapper for Salsa20 (Comments by Larry Bugbee) # ------------------------------------------------------------------ # pySalsa20.py is a simple ctypes Python wrapper. Salsa20 is # as it's name implies, 20 rounds, but there are two reduced # versions, 8 and 12 rounds each. Because the APIs are # identical, pySalsa20 is capable of wrapping all three # versions (number of rounds hardcoded), including a special # version that allows you to set the number of rounds with a # set_rounds() function. Compile the version of your choice # as a shared library (not as a Python extension), name and # install it as libsalsa20.so. # Sample usage: # from pySalsa20 import Salsa20 # s20 = Salsa20(key, IV) # dataout = s20.encryptBytes(datain) # same for decrypt # This is EXPERIMENTAL software and intended for educational # purposes only. To make experimentation less cumbersome, # pySalsa20 is also free for any use. # THIS PROGRAM IS PROVIDED WITHOUT WARRANTY OR GUARANTEE OF # ANY KIND. USE AT YOUR OWN RISK. # Enjoy, # Larry Bugbee # bugbee@seanet.com # April 2007 # References: # ----------- # http://en.wikipedia.org/wiki/Salsa20 # http://en.wikipedia.org/wiki/Daniel_Bernstein # http://cr.yp.to/djb.html # http://www.ecrypt.eu.org/stream/salsa20p3.html # http://www.ecrypt.eu.org/stream/p3ciphers/salsa20/salsa20_p3source.zip # Prerequisites for pySalsa20: # ---------------------------- # - Python 2.5 (haven't tested in 2.4) # pureSalsa20: Salsa20 in pure Python 2.5 (comments by Steve Witham) # ------------------------------------------------------------------ # pureSalsa20 is the stand-alone Python code in this file. # It implements the underlying Salsa20 core algorithm # and emulates pySalsa20's Salsa20 class API (minus a bug(*)). # pureSalsa20 is MUCH slower than libsalsa20.so wrapped with pySalsa20-- # about 1/1000 the speed for Salsa20/20 and 1/500 the speed for Salsa20/8, # when encrypting 64k-byte blocks on my computer. # pureSalsa20 is for cases where portability is much more important than # speed. I wrote it for use in a "structured" random number generator. # There are comments about the reasons for this slowness in # http://www.tiac.net/~sw/2010/02/PureSalsa20 # Sample usage: # from pureSalsa20 import Salsa20 # s20 = Salsa20(key, IV) # dataout = s20.encryptBytes(datain) # same for decrypt # I took the test code from pySalsa20, added a bunch of tests including # rough speed tests, and moved them into the file testSalsa20.py. # To test both pySalsa20 and pureSalsa20, type # python testSalsa20.py # (*)The bug (?) in pySalsa20 is this. The rounds variable is global to the # libsalsa20.so library and not switched when switching between instances # of the Salsa20 class. # s1 = Salsa20( key, IV, 20 ) # s2 = Salsa20( key, IV, 8 ) # In this example, # with pySalsa20, both s1 and s2 will do 8 rounds of encryption. # with pureSalsa20, s1 will do 20 rounds and s2 will do 8 rounds. # Perhaps giving each instance its own nRounds variable, which # is passed to the salsa20wordtobyte() function, is insecure. I'm not a # cryptographer. # pureSalsa20.py and testSalsa20.py are EXPERIMENTAL software and # intended for educational purposes only. To make experimentation less # cumbersome, pureSalsa20.py and testSalsa20.py are free for any use. # Revisions: # ---------- # p3.2 Fixed bug that initialized the output buffer with plaintext! # Saner ramping of nreps in speed test. # Minor changes and print statements. # p3.1 Took timing variability out of add32() and rot32(). # Made the internals more like pySalsa20/libsalsa . # Put the semicolons back in the main loop! # In encryptBytes(), modify a byte array instead of appending. # Fixed speed calculation bug. # Used subclasses instead of patches in testSalsa20.py . # Added 64k-byte messages to speed test to be fair to pySalsa20. # p3 First version, intended to parallel pySalsa20 version 3. # More references: # ---------------- # http://www.seanet.com/~bugbee/crypto/salsa20/ [pySalsa20] # http://cr.yp.to/snuffle.html [The original name of Salsa20] # http://cr.yp.to/snuffle/salsafamily-20071225.pdf [ Salsa20 design] # http://www.tiac.net/~sw/2010/02/PureSalsa20 # THIS PROGRAM IS PROVIDED WITHOUT WARRANTY OR GUARANTEE OF # ANY KIND. USE AT YOUR OWN RISK. # Cheers, # Steve Witham sw at remove-this tiac dot net # February, 2010 import operator from struct import Struct __all__ = ["Salsa20"] little_u64 = Struct("<Q") # little-endian 64-bit unsigned. # Unpacks to a tuple of one element! little16_i32 = Struct("<16i") # 16 little-endian 32-bit signed ints. little4_i32 = Struct("<4i") # 4 little-endian 32-bit signed ints. little2_i32 = Struct("<2i") # 2 little-endian 32-bit signed ints. _version = "p4.0" # ----------- Salsa20 class which emulates pySalsa20.Salsa20 --------------- class Salsa20: def __init__(self, key=None, IV=None, rounds=20) -> None: self._lastChunk64 = True self._IVbitlen = 64 # must be 64 bits self.ctx = [0] * 16 if key: self.setKey(key) if IV: self.setIV(IV) self.setRounds(rounds) def setKey(self, key): assert isinstance(key, bytes) ctx = self.ctx if len(key) == 32: # recommended constants = b"expand 32-byte k" ctx[1], ctx[2], ctx[3], ctx[4] = little4_i32.unpack(key[0:16]) ctx[11], ctx[12], ctx[13], ctx[14] = little4_i32.unpack(key[16:32]) elif len(key) == 16: constants = b"expand 16-byte k" ctx[1], ctx[2], ctx[3], ctx[4] = little4_i32.unpack(key[0:16]) ctx[11], ctx[12], ctx[13], ctx[14] = little4_i32.unpack(key[0:16]) else: raise ValueError("key length isn't 32 or 16 bytes.") ctx[0], ctx[5], ctx[10], ctx[15] = little4_i32.unpack(constants) def setIV(self, IV): assert isinstance(IV, bytes) assert len(IV) * 8 == 64, "nonce (IV) not 64 bits" self.IV = IV ctx = self.ctx ctx[6], ctx[7] = little2_i32.unpack(IV) ctx[8], ctx[9] = 0, 0 # Reset the block counter. setNonce = setIV # support an alternate name def setCounter(self, counter): assert isinstance(counter, int) assert 0 <= counter < 1 << 64, "counter < 0 or >= 2**64" ctx = self.ctx ctx[8], ctx[9] = little2_i32.unpack(little_u64.pack(counter)) def getCounter(self): return little_u64.unpack(little2_i32.pack(*self.ctx[8:10]))[0] def setRounds(self, rounds, testing=False): assert testing or rounds in {8, 12, 20}, "rounds must be 8, 12, 20" self.rounds = rounds def encryptBytes(self, data: bytes) -> bytes: assert isinstance(data, bytes), "data must be byte string" assert self._lastChunk64, "previous chunk not multiple of 64 bytes" lendata = len(data) munged = bytearray(lendata) for i in range(0, lendata, 64): h = salsa20_wordtobyte(self.ctx, self.rounds, checkRounds=False) self.setCounter((self.getCounter() + 1) % 2**64) # Stopping at 2^70 bytes per nonce is user's responsibility. for j in range(min(64, lendata - i)): munged[i + j] = data[i + j] ^ h[j] self._lastChunk64 = not lendata % 64 return bytes(munged) decryptBytes = encryptBytes # encrypt and decrypt use same function # -------------------------------------------------------------------------- def salsa20_wordtobyte(input_, nRounds=20, checkRounds=True): """ Do nRounds Salsa20 rounds on a copy of input: list or tuple of 16 ints treated as little-endian unsigneds. Returns a 64-byte string. """ assert isinstance(input_, list | tuple) and len(input_) == 16 assert not checkRounds or nRounds in {8, 12, 20} x = list(input_) XOR = operator.xor ROTATE = rot32 PLUS = add32 for _ in range(nRounds // 2): # These ...XOR...ROTATE...PLUS... lines are from ecrypt-linux.c # unchanged except for indents and the blank line between rounds: x[4] = XOR(x[4], ROTATE(PLUS(x[0], x[12]), 7)) x[8] = XOR(x[8], ROTATE(PLUS(x[4], x[0]), 9)) x[12] = XOR(x[12], ROTATE(PLUS(x[8], x[4]), 13)) x[0] = XOR(x[0], ROTATE(PLUS(x[12], x[8]), 18)) x[9] = XOR(x[9], ROTATE(PLUS(x[5], x[1]), 7)) x[13] = XOR(x[13], ROTATE(PLUS(x[9], x[5]), 9)) x[1] = XOR(x[1], ROTATE(PLUS(x[13], x[9]), 13)) x[5] = XOR(x[5], ROTATE(PLUS(x[1], x[13]), 18)) x[14] = XOR(x[14], ROTATE(PLUS(x[10], x[6]), 7)) x[2] = XOR(x[2], ROTATE(PLUS(x[14], x[10]), 9)) x[6] = XOR(x[6], ROTATE(PLUS(x[2], x[14]), 13)) x[10] = XOR(x[10], ROTATE(PLUS(x[6], x[2]), 18)) x[3] = XOR(x[3], ROTATE(PLUS(x[15], x[11]), 7)) x[7] = XOR(x[7], ROTATE(PLUS(x[3], x[15]), 9)) x[11] = XOR(x[11], ROTATE(PLUS(x[7], x[3]), 13)) x[15] = XOR(x[15], ROTATE(PLUS(x[11], x[7]), 18)) x[1] = XOR(x[1], ROTATE(PLUS(x[0], x[3]), 7)) x[2] = XOR(x[2], ROTATE(PLUS(x[1], x[0]), 9)) x[3] = XOR(x[3], ROTATE(PLUS(x[2], x[1]), 13)) x[0] = XOR(x[0], ROTATE(PLUS(x[3], x[2]), 18)) x[6] = XOR(x[6], ROTATE(PLUS(x[5], x[4]), 7)) x[7] = XOR(x[7], ROTATE(PLUS(x[6], x[5]), 9)) x[4] = XOR(x[4], ROTATE(PLUS(x[7], x[6]), 13)) x[5] = XOR(x[5], ROTATE(PLUS(x[4], x[7]), 18)) x[11] = XOR(x[11], ROTATE(PLUS(x[10], x[9]), 7)) x[8] = XOR(x[8], ROTATE(PLUS(x[11], x[10]), 9)) x[9] = XOR(x[9], ROTATE(PLUS(x[8], x[11]), 13)) x[10] = XOR(x[10], ROTATE(PLUS(x[9], x[8]), 18)) x[12] = XOR(x[12], ROTATE(PLUS(x[15], x[14]), 7)) x[13] = XOR(x[13], ROTATE(PLUS(x[12], x[15]), 9)) x[14] = XOR(x[14], ROTATE(PLUS(x[13], x[12]), 13)) x[15] = XOR(x[15], ROTATE(PLUS(x[14], x[13]), 18)) for idx, item in enumerate(input_): x[idx] = PLUS(x[idx], item) return little16_i32.pack(*x) # --------------------------- 32-bit ops ------------------------------- def trunc32(w): """ Return the bottom 32 bits of w as a Python int. This creates longs temporarily, but returns an int. """ w = int((w & 0x7FFFFFFF) | -(w & 0x80000000)) assert isinstance(w, int) return w def add32(a, b): """ Add two 32-bit words discarding carry above 32nd bit, and without creating a Python long. Timing shouldn't vary. """ lo = (a & 0xFFFF) + (b & 0xFFFF) hi = (a >> 16) + (b >> 16) + (lo >> 16) return (-(hi & 0x8000) | (hi & 0x7FFF)) << 16 | (lo & 0xFFFF) def rot32(w, nLeft): """ Rotate 32-bit word left by nLeft or right by -nLeft without creating a Python long. Timing depends on nLeft but not on w. """ nLeft &= 31 # which makes nLeft >= 0 if nLeft == 0: return w # Note: now 1 <= nLeft <= 31. # RRRsLLLLLL There are nLeft RRR's, (31-nLeft) LLLLLL's, # => sLLLLLLRRR and one s which becomes the sign bit. RRR = ((w >> 1) & 0x7FFFFFFF) >> (31 - nLeft) sLLLLLL = -((1 << (31 - nLeft)) & w) | (0x7FFFFFFF >> nLeft) & w return RRR | (sLLLLLL << nLeft) # --------------------------------- end -----------------------------------
12,652
Python
.py
283
42.60424
79
0.657824
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,797
readmdict.py
ilius_pyglossary/pyglossary/plugin_lib/readmdict.py
# -*- coding: utf-8 -*- # mypy: ignore-errors # # readmdict.py from https://bitbucket.org/xwang/mdict-analysis # Octopus MDict Dictionary File (.mdx) and Resource File (.mdd) Analyser # # Copyright (C) 2016-2023 Saeed Rasooli on https://github.com/ilius/pyglossary/ # Copyright (C) 2012, 2013, 2015, 2022 Xiaoqiang Wang <xiaoqiangwang AT gmail DOT com> # # This program is a free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, version 3 of the License. # # You can get a copy of GNU General Public License along this program # But you can always get it from http://www.gnu.org/licenses/gpl.txt # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. import logging import re import sys # zlib compression is used for engine version >=2.0 import zlib from io import BytesIO from struct import pack, unpack from .pureSalsa20 import Salsa20 from .ripemd128 import ripemd128 # LZO compression is used for engine version < 2.0 try: import lzo except ImportError: lzo = None # xxhash is used for engine version >= 3.0 try: import xxhash except ImportError: xxhash = None __all__ = ["MDD", "MDX"] log = logging.getLogger(__name__) def _unescape_entities(text): """Unescape offending tags < > " &.""" text = text.replace(b"&lt;", b"<") text = text.replace(b"&gt;", b">") text = text.replace(b"&quot;", b'"') text = text.replace(b"&amp;", b"&") return text # noqa: RET504 def _fast_decrypt(data, key): """XOR decryption.""" b = bytearray(data) key = bytearray(key) previous = 0x36 for i, bi in enumerate(b): t = (bi >> 4 | bi << 4) & 0xFF t = t ^ previous ^ (i & 0xFF) ^ key[i % len(key)] previous = bi b[i] = t return bytes(b) def _salsa_decrypt(ciphertext, encrypt_key): """salsa20 (8 rounds) decryption.""" s20 = Salsa20(key=encrypt_key, IV=b"\x00" * 8, rounds=8) return s20.encryptBytes(ciphertext) def _decrypt_regcode_by_userid(reg_code: bytes, userid: bytes) -> bytes: userid_digest = ripemd128(userid) s20 = Salsa20(key=userid_digest, IV=b"\x00" * 8, rounds=8) return s20.encryptBytes(reg_code) class MDict: """ Base class which reads in header and key block. It has no public methods and serves only as code sharing base class. """ def __init__( self, fname: str, encoding: str = "", passcode: "tuple[bytes, bytes] | None" = None, ) -> None: self._fname = fname self._encoding = encoding.upper() self._encrypted_key = None self.header = self._read_header() # decrypt regcode to get the encrypted key if passcode is not None: regcode, userid = passcode if isinstance(userid, str): userid = userid.encode("utf8") self._encrypted_key = _decrypt_regcode_by_userid(regcode, userid) # MDict 3.0 encryption key derives from UUID if present elif self._version >= 3.0: uuid = self.header.get(b"UUID") if uuid: if xxhash is None: raise RuntimeError( "xxhash module is needed to read MDict 3.0 format" "\n" "Run `pip3 install xxhash` to install", ) mid = (len(uuid) + 1) // 2 self._encrypted_key = xxhash.xxh64_digest( uuid[:mid], ) + xxhash.xxh64_digest(uuid[mid:]) self._key_list = self._read_keys() def __repr__(self): return ( f"MDict({self._fname!r}, " f"encoding={self._encoding!r}, " f"passcode={self._passcode})" ) @property def filename(self): return self._fname def __len__(self): return self._num_entries def __iter__(self): return self.keys() def keys(self): """Return an iterator over dictionary keys.""" return (key_value for key_id, key_value in self._key_list) def _read_number(self, f): return unpack(self._number_format, f.read(self._number_width))[0] @staticmethod def _read_int32(f): return unpack(">I", f.read(4))[0] @staticmethod def _parse_header(header): """Extract attributes from <Dict attr="value" ... >.""" return { key: _unescape_entities(value) for key, value in re.findall(rb'(\w+)="(.*?)"', header, re.DOTALL) } def _decode_block(self, block, decompressed_size): # block info: compression, encryption info = unpack("<L", block[:4])[0] compression_method = info & 0xF encryption_method = (info >> 4) & 0xF encryption_size = (info >> 8) & 0xFF # adler checksum of the block data used as the encryption key if none given adler32 = unpack(">I", block[4:8])[0] encrypted_key = self._encrypted_key if encrypted_key is None: encrypted_key = ripemd128(block[4:8]) # block data data = block[8:] # decrypt if encryption_method == 0: decrypted_block = data elif encryption_method == 1: decrypted_block = ( _fast_decrypt(data[:encryption_size], encrypted_key) + data[encryption_size:] ) elif encryption_method == 2: decrypted_block = ( _salsa_decrypt(data[:encryption_size], encrypted_key) + data[encryption_size:] ) else: raise ValueError(f"encryption method {encryption_method} not supported") # check adler checksum over decrypted data if self._version >= 3: assert hex(adler32) == hex(zlib.adler32(decrypted_block) & 0xFFFFFFFF) # decompress if compression_method == 0: decompressed_block = decrypted_block elif compression_method == 1: if lzo is None: raise RuntimeError("LZO compression is not supported") header = b"\xf0" + pack(">I", decompressed_size) decompressed_block = lzo.decompress(header + decrypted_block) elif compression_method == 2: decompressed_block = zlib.decompress(decrypted_block) else: raise ValueError(f"compression method {compression_method} not supported") # check adler checksum over decompressed data if self._version < 3: assert hex(adler32) == hex(zlib.adler32(decompressed_block) & 0xFFFFFFFF) return decompressed_block def _decode_key_block_info(self, key_block_info_compressed): if self._version >= 2: # zlib compression assert key_block_info_compressed[:4] == b"\x02\x00\x00\x00" # decrypt if needed if self._encrypt & 0x02: key = ripemd128(key_block_info_compressed[4:8] + pack(b"<L", 0x3695)) key_block_info_compressed = key_block_info_compressed[ :8 ] + _fast_decrypt(key_block_info_compressed[8:], key) # decompress key_block_info = zlib.decompress(key_block_info_compressed[8:]) # adler checksum adler32 = unpack(">I", key_block_info_compressed[4:8])[0] assert adler32 == zlib.adler32(key_block_info) & 0xFFFFFFFF else: # no compression key_block_info = key_block_info_compressed # decode key_block_info_list = [] num_entries = 0 i = 0 if self._version >= 2: byte_format = ">H" byte_width = 2 text_term = 1 else: byte_format = ">B" byte_width = 1 text_term = 0 while i < len(key_block_info): # number of entries in current key block num_entries += unpack( self._number_format, key_block_info[i : i + self._number_width], )[0] i += self._number_width # text head size text_head_size = unpack(byte_format, key_block_info[i : i + byte_width])[0] i += byte_width # text head if self._encoding != "UTF-16": i += text_head_size + text_term else: i += (text_head_size + text_term) * 2 # text tail size text_tail_size = unpack(byte_format, key_block_info[i : i + byte_width])[0] i += byte_width # text tail if self._encoding != "UTF-16": i += text_tail_size + text_term else: i += (text_tail_size + text_term) * 2 # key block compressed size key_block_compressed_size = unpack( self._number_format, key_block_info[i : i + self._number_width], )[0] i += self._number_width # key block decompressed size key_block_decompressed_size = unpack( self._number_format, key_block_info[i : i + self._number_width], )[0] i += self._number_width key_block_info_list.append( (key_block_compressed_size, key_block_decompressed_size), ) # assert num_entries == self._num_entries return key_block_info_list def _decode_key_block(self, key_block_compressed, key_block_info_list): key_list = [] i = 0 for compressed_size, decompressed_size in key_block_info_list: key_block = self._decode_block( key_block_compressed[i : i + compressed_size], decompressed_size, ) # extract one single key block into a key list key_list += self._split_key_block(key_block) i += compressed_size return key_list def _split_key_block(self, key_block): key_list = [] key_start_index = 0 while key_start_index < len(key_block): # the corresponding record's offset in record block key_id = unpack( self._number_format, key_block[key_start_index : key_start_index + self._number_width], )[0] # key text ends with '\x00' if self._encoding == "UTF-16": delimiter = b"\x00\x00" width = 2 else: delimiter = b"\x00" width = 1 i = key_start_index + self._number_width while i < len(key_block): if key_block[i : i + width] == delimiter: key_end_index = i break i += width key_text = ( key_block[key_start_index + self._number_width : key_end_index] .decode(self._encoding, errors="ignore") .encode("utf-8") .strip() ) key_start_index = key_end_index + width key_list += [(key_id, key_text)] return key_list def _read_header(self): f = open(self._fname, "rb") # number of bytes of header text header_bytes_size = unpack(">I", f.read(4))[0] header_bytes = f.read(header_bytes_size) # 4 bytes: adler32 checksum of header, in little endian adler32 = unpack("<I", f.read(4))[0] assert adler32 == zlib.adler32(header_bytes) & 0xFFFFFFFF # mark down key block offset self._key_block_offset = f.tell() f.close() # header text in utf-16 encoding ending with '\x00\x00' if header_bytes[-2:] == b"\x00\x00": header_text = header_bytes[:-2].decode("utf-16").encode("utf-8") else: header_text = header_bytes[:-1] header_tag = self._parse_header(header_text) if not self._encoding: encoding = header_tag.get(b"Encoding", b"utf-8") if sys.hexversion >= 0x03000000: encoding = encoding.decode("utf-8") # GB18030 > GBK > GB2312 if encoding in {"GBK", "GB2312"}: encoding = "GB18030" self._encoding = encoding # encryption flag # 0x00 - no encryption, "Allow export to text" is checked in MdxBuilder 3. # 0x01 - encrypt record block, "Encryption Key" is given in MdxBuilder 3. # 0x02 - encrypt key info block, # "Allow export to text" is unchecked in MdxBuilder 3. if b"Encrypted" not in header_tag or header_tag[b"Encrypted"] == b"No": self._encrypt = 0 elif header_tag[b"Encrypted"] == b"Yes": self._encrypt = 1 else: self._encrypt = int(header_tag[b"Encrypted"]) # stylesheet attribute if present takes form of: # style_number # 1-255 # style_begin # or '' # style_end # or '' # store stylesheet in dict in the form of # {'number' : ('style_begin', 'style_end')} self._stylesheet = {} if header_tag.get("StyleSheet"): lines = header_tag["StyleSheet"].splitlines() self._stylesheet = { lines[i]: (lines[i + 1], lines[i + 2]) for i in range(0, len(lines), 3) } # before version 2.0, number is 4 bytes integer # version 2.0 and above uses 8 bytes self._version = float(header_tag[b"GeneratedByEngineVersion"]) if self._version < 2.0: self._number_width = 4 self._number_format = ">I" else: self._number_width = 8 self._number_format = ">Q" # version 3.0 uses UTF-8 only if self._version >= 3: self._encoding = "UTF-8" return header_tag def _read_keys(self): if self._version >= 3: return self._read_keys_v3() # if no regcode is given, try brute-force (only for engine <= 2) if (self._encrypt & 0x01) and self._encrypted_key is None: log.warning("Trying brute-force on encrypted key blocks") return self._read_keys_brutal() return self._read_keys_v1v2() def _read_keys_v3(self): f = open(self._fname, "rb") f.seek(self._key_block_offset) # find all blocks offset while True: block_type = self._read_int32(f) block_size = self._read_number(f) block_offset = f.tell() # record data if block_type == 0x01000000: self._record_block_offset = block_offset # record index elif block_type == 0x02000000: self._record_index_offset = block_offset # key data elif block_type == 0x03000000: self._key_data_offset = block_offset # key index elif block_type == 0x04000000: self._key_index_offset = block_offset else: raise RuntimeError(f"Unknown block type {block_type}") f.seek(block_size, 1) # test the end of file if f.read(4): f.seek(-4, 1) else: break # read key data f.seek(self._key_data_offset) number = self._read_int32(f) self._read_number(f) # total_size key_list = [] for _ in range(number): decompressed_size = self._read_int32(f) compressed_size = self._read_int32(f) block_data = f.read(compressed_size) decompressed_block_data = self._decode_block(block_data, decompressed_size) key_list.extend(self._split_key_block(decompressed_block_data)) f.close() self._num_entries = len(key_list) return key_list def _read_keys_v1v2(self): f = open(self._fname, "rb") f.seek(self._key_block_offset) # the following numbers could be encrypted num_bytes = 8 * 5 if self._version >= 2.0 else 4 * 4 block = f.read(num_bytes) if self._encrypt & 1: block = _salsa_decrypt(block, self._encrypted_key) # decode this block sf = BytesIO(block) # number of key blocks num_key_blocks = self._read_number(sf) # number of entries self._num_entries = self._read_number(sf) # number of bytes of key block info after decompression if self._version >= 2.0: self._read_number(sf) # key_block_info_decomp_size # number of bytes of key block info key_block_info_size = self._read_number(sf) # number of bytes of key block key_block_size = self._read_number(sf) # 4 bytes: adler checksum of previous 5 numbers if self._version >= 2.0: adler32 = unpack(">I", f.read(4))[0] assert adler32 == (zlib.adler32(block) & 0xFFFFFFFF) # read key block info, which indicates key block's compressed # and decompressed size key_block_info = f.read(key_block_info_size) key_block_info_list = self._decode_key_block_info(key_block_info) assert num_key_blocks == len(key_block_info_list) # read key block key_block_compressed = f.read(key_block_size) # extract key block key_list = self._decode_key_block(key_block_compressed, key_block_info_list) self._record_block_offset = f.tell() f.close() return key_list def _read_keys_brutal(self): f = open(self._fname, "rb") f.seek(self._key_block_offset) # the following numbers could be encrypted, disregard them! if self._version >= 2.0: num_bytes = 8 * 5 + 4 key_block_type = b"\x02\x00\x00\x00" else: num_bytes = 4 * 4 key_block_type = b"\x01\x00\x00\x00" f.read(num_bytes) # block # key block info # 4 bytes '\x02\x00\x00\x00' # 4 bytes adler32 checksum # unknown number of bytes follows until '\x02\x00\x00\x00' # which marks the beginning of key block key_block_info = f.read(8) if self._version >= 2.0: assert key_block_info[:4] == b"\x02\x00\x00\x00" while True: fpos = f.tell() t = f.read(1024) index = t.find(key_block_type) if index != -1: key_block_info += t[:index] f.seek(fpos + index) break key_block_info += t key_block_info_list = self._decode_key_block_info(key_block_info) key_block_size = sum(list(zip(*key_block_info_list, strict=False))[0]) # read key block key_block_compressed = f.read(key_block_size) # extract key block key_list = self._decode_key_block(key_block_compressed, key_block_info_list) self._record_block_offset = f.tell() f.close() self._num_entries = len(key_list) return key_list def items(self): """ Return a generator which in turn produce tuples in the form of (filename, content). """ return self._read_records() def _read_records(self): if self._version >= 3: yield from self._read_records_v3() else: yield from self._read_records_v1v2() def _read_records_v3(self): f = open(self._fname, "rb") f.seek(self._record_block_offset) offset = 0 i = 0 size_counter = 0 num_record_blocks = self._read_int32(f) self._read_number(f) # num_bytes for _ in range(num_record_blocks): decompressed_size = self._read_int32(f) compressed_size = self._read_int32(f) record_block = self._decode_block( f.read(compressed_size), decompressed_size, ) # split record block according to the offset info from key block while i < len(self._key_list): record_start, key_text = self._key_list[i] # reach the end of current record block if record_start - offset >= len(record_block): break # record end index if i < len(self._key_list) - 1: record_end = self._key_list[i + 1][0] else: record_end = len(record_block) + offset i += 1 data = record_block[record_start - offset : record_end - offset] yield key_text, self._treat_record_data(data) offset += len(record_block) size_counter += compressed_size def _read_records_v1v2(self): f = open(self._fname, "rb") f.seek(self._record_block_offset) num_record_blocks = self._read_number(f) num_entries = self._read_number(f) assert num_entries == self._num_entries record_block_info_size = self._read_number(f) self._read_number(f) # record_block_size # record block info section record_block_info_list = [] size_counter = 0 for _ in range(num_record_blocks): compressed_size = self._read_number(f) decompressed_size = self._read_number(f) record_block_info_list += [(compressed_size, decompressed_size)] size_counter += self._number_width * 2 assert size_counter == record_block_info_size # actual record block offset = 0 i = 0 size_counter = 0 for compressed_size, decompressed_size in record_block_info_list: record_block_compressed = f.read(compressed_size) try: record_block = self._decode_block( record_block_compressed, decompressed_size, ) except zlib.error: log.error("zlib decompress error") log.debug(f"record_block_compressed = {record_block_compressed!r}") continue # split record block according to the offset info from key block while i < len(self._key_list): record_start, key_text = self._key_list[i] # reach the end of current record block if record_start - offset >= len(record_block): break # record end index if i < len(self._key_list) - 1: record_end = self._key_list[i + 1][0] else: record_end = len(record_block) + offset i += 1 data = record_block[record_start - offset : record_end - offset] yield key_text, self._treat_record_data(data) offset += len(record_block) size_counter += compressed_size # assert size_counter == record_block_size f.close() def _treat_record_data(self, data): # noqa: PLR6301 return data class MDD(MDict): """ MDict resource file format (*.MDD) reader. >>> mdd = MDD("example.mdd") >>> len(mdd) 208 >>> for filename,content in mdd.items(): ... print(filename, content[:10]) """ def __init__( self, fname: str, passcode: "tuple[bytes, bytes] | None" = None, ) -> None: MDict.__init__(self, fname, encoding="UTF-16", passcode=passcode) class MDX(MDict): """ MDict dictionary file format (*.MDD) reader. >>> mdx = MDX("example.mdx") >>> len(mdx) 42481 >>> for key,value in mdx.items(): ... print(key, value[:10]) """ def __init__( self, fname: str, encoding: str = "", substyle: bool = False, passcode: "tuple[bytes, bytes] | None" = None, ) -> None: MDict.__init__(self, fname, encoding, passcode) self._substyle = substyle def _substitute_stylesheet(self, txt): # substitute stylesheet definition txt_list = re.split(r"`\d+`", txt) txt_tag = re.findall(r"`\d+`", txt) txt_styled = txt_list[0] for j, p in enumerate(txt_list[1:]): key = txt_tag[j][1:-1] try: style = self._stylesheet[key] except KeyError: log.error(f'invalid stylesheet key "{key}"') continue if p and p[-1] == "\n": txt_styled = txt_styled + style[0] + p.rstrip() + style[1] + "\r\n" else: txt_styled = txt_styled + style[0] + p + style[1] return txt_styled def _treat_record_data(self, data): # convert to utf-8 data = ( data.decode(self._encoding, errors="ignore").strip("\x00").encode("utf-8") ) # substitute styles if self._substyle and self._stylesheet: data = self._substitute_stylesheet(data) return data # noqa: RET504
20,877
Python
.py
630
29.631746
86
0.67841
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,798
mutf8.py
ilius_pyglossary/pyglossary/plugin_lib/mutf8.py
# Copyright (c) 2012-2015 Tyler Kennedy <tk@tkte.ch>. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. # # -- # # Code to convert Python strings to/from Java's modified UTF-8 encoding. # The code is from https://github.com/TkTech/mutf8 (MIT License) with fixes # by @gentlegiantJGC (https://github.com/TkTech/mutf8/pull/7). __all__ = ["decode_modified_utf8", "encode_modified_utf8"] def decode_modified_utf8(s: bytes) -> str: """ Decodes a bytestring containing modified UTF-8 as defined in section 4.4.7 of the JVM specification. :param s: bytestring to be converted. :returns: A unicode representation of the original string. """ s_out = [] s_len = len(s) s_ix = 0 while s_ix < s_len: b1 = s[s_ix] s_ix += 1 if b1 == 0: raise UnicodeDecodeError( "mutf-8", s, s_ix - 1, s_ix, "Embedded NULL byte in input.", ) if b1 < 0x80: # ASCII/one-byte codepoint. s_out.append(chr(b1)) elif (b1 & 0xE0) == 0xC0: # Two-byte codepoint. if s_ix >= s_len: raise UnicodeDecodeError( "mutf-8", s, s_ix - 1, s_ix, "2-byte codepoint started, but input too short to finish.", ) s_out.append( chr( (b1 & 0x1F) << 0x06 | (s[s_ix] & 0x3F), ), ) s_ix += 1 elif (b1 & 0xF0) == 0xE0: # Three-byte codepoint. if s_ix + 1 >= s_len: raise UnicodeDecodeError( "mutf-8", s, s_ix - 1, s_ix, "3-byte or 6-byte codepoint started, but input too" " short to finish.", ) b2 = s[s_ix] b3 = s[s_ix + 1] if b1 == 0xED and (b2 & 0xF0) == 0xA0: # Possible six-byte codepoint. if s_ix + 4 >= s_len: raise UnicodeDecodeError( "mutf-8", s, s_ix - 1, s_ix, "3-byte or 6-byte codepoint started, but input too" " short to finish.", ) b4 = s[s_ix + 2] b5 = s[s_ix + 3] b6 = s[s_ix + 4] if b4 == 0xED and (b5 & 0xF0) == 0xB0: # Definite six-byte codepoint. s_out.append( chr( 0x10000 + ( (b2 & 0x0F) << 0x10 | (b3 & 0x3F) << 0x0A | (b5 & 0x0F) << 0x06 | (b6 & 0x3F) ), ), ) s_ix += 5 continue s_out.append( chr( (b1 & 0x0F) << 0x0C | (b2 & 0x3F) << 0x06 | (b3 & 0x3F), ), ) s_ix += 2 else: raise RuntimeError return "".join(s_out) def encode_modified_utf8(u: str) -> bytes: """ Encodes a unicode string as modified UTF-8 as defined in section 4.4.7 of the JVM specification. :param u: unicode string to be converted. :returns: A decoded bytearray. """ final_string = bytearray() for c in (ord(char) for char in u): if c == 0x00: # NULL byte encoding shortcircuit. final_string.extend([0xC0, 0x80]) elif c <= 0x7F: # ASCII final_string.append(c) elif c <= 0x7FF: # Two-byte codepoint. final_string.extend( [ (0xC0 | (0x1F & (c >> 0x06))), (0x80 | (0x3F & c)), ], ) elif c <= 0xFFFF: # Three-byte codepoint. final_string.extend( [ (0xE0 | (0x0F & (c >> 0x0C))), (0x80 | (0x3F & (c >> 0x06))), (0x80 | (0x3F & c)), ], ) else: # Six-byte codepoint. final_string.extend( [ 0xED, 0xA0 | ((c >> 0x10) - 1 & 0x0F), 0x80 | ((c >> 0x0A) & 0x3F), 0xED, 0xB0 | ((c >> 0x06) & 0x0F), 0x80 | (c & 0x3F), ], ) return bytes(final_string)
4,412
Python
.py
162
23.080247
77
0.620983
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)
6,799
ripemd128.py
ilius_pyglossary/pyglossary/plugin_lib/ripemd128.py
# -*- coding: utf-8 -*- # mypy: ignore-errors # # Copyright (C) 2016-2023 Saeed Rasooli on https://github.com/ilius/pyglossary/ # Copyright (C) 2015 Z. H. Liu on https://github.com/zhansliu/writemdict # # ripemd128.py - A simple ripemd128 library in pure Python. # # Supports both Python 2 (versions >= 2.6) and Python 3. # # Usage: # from ripemd128 import ripemd128 # digest = ripemd128(b"The quick brown fox jumps over the lazy dog") # assert( # digest == b"\x3f\xa9\xb5\x7f\x05\x3c\x05\x3f\xbe\x27\x35\xb2\x38\x0d\xb5\x96" # ) import struct __all__ = ["ripemd128"] # follows this description: http://homes.esat.kuleuven.be/~bosselae/ripemd/rmd128.txt def f(j, x, y, z): assert 0 <= j < 64 if j < 16: return x ^ y ^ z if j < 32: return (x & y) | (z & ~x) if j < 48: return (x | (0xFFFFFFFF & ~y)) ^ z return (x & z) | (y & ~z) def K(j): assert 0 <= j < 64 if j < 16: return 0x00000000 if j < 32: return 0x5A827999 if j < 48: return 0x6ED9EBA1 return 0x8F1BBCDC def Kp(j): assert 0 <= j < 64 if j < 16: return 0x50A28BE6 if j < 32: return 0x5C4DD124 if j < 48: return 0x6D703EF3 return 0x00000000 def padandsplit(message: bytes): """ returns a two-dimensional array X[i][j] of 32-bit integers, where j ranges from 0 to 16. First pads the message to length in bytes is congruent to 56 (mod 64), by first adding a byte 0x80, and then padding with 0x00 bytes until the message length is congruent to 56 (mod 64). Then adds the little-endian 64-bit representation of the original length. Finally, splits the result up into 64-byte blocks, which are further parsed as 32-bit integers. """ origlen = len(message) padlength = 64 - ((origlen - 56) % 64) # minimum padding is 1! message += b"\x80" message += b"\x00" * (padlength - 1) message += struct.pack("<Q", origlen * 8) assert len(message) % 64 == 0 return [ [struct.unpack("<L", message[i + j : i + j + 4])[0] for j in range(0, 64, 4)] for i in range(0, len(message), 64) ] def add(*args): return sum(args) & 0xFFFFFFFF def rol(s, x): assert s < 32 return (x << s | x >> (32 - s)) & 0xFFFFFFFF r = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, ] rp = [ 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, ] s = [ 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, ] sp = [ 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, ] def ripemd128(message: bytes) -> bytes: h0 = 0x67452301 h1 = 0xEFCDAB89 h2 = 0x98BADCFE h3 = 0x10325476 X = padandsplit(message) for Xi in X: A, B, C, D = h0, h1, h2, h3 Ap, Bp, Cp, Dp = h0, h1, h2, h3 for j in range(64): T = rol( s[j], add( A, f(j, B, C, D), Xi[r[j]], K(j), ), ) A, D, C, B = D, C, B, T T = rol( sp[j], add( Ap, f(63 - j, Bp, Cp, Dp), Xi[rp[j]], Kp(j), ), ) Ap, Dp, Cp, Bp = Dp, Cp, Bp, T T = add(h1, C, Dp) h1 = add(h2, D, Ap) h2 = add(h3, A, Bp) h3 = add(h0, B, Cp) h0 = T return struct.pack("<LLLL", h0, h1, h2, h3) def hexstr(bstr): return "".join(f"{b:02x}" for b in bstr)
3,757
Python
.py
133
25.736842
85
0.578012
ilius/pyglossary
2,176
238
22
GPL-3.0
9/5/2024, 5:10:09 PM (Europe/Amsterdam)