Package: pyglossary
PyGlossaryA tool for converting dictionary files aka glossaries.The primary purpose is to be able to use our offline glossaries in any Open
Source dictionary we like on any OS/device.There are countless formats, and my time is limited, so I implement formats that
seem more useful for myself, or for Open Source community. Also diversity of
languages is taken into account. Pull requests are welcome.ScreenshotsLinux - Gtk3-based interfaceWindows - Tkinter-based interfaceLinux - command-line interfaceAndroid Termux - interactive command-line interfaceSupported formatsFormatExtensionReadWriteAard 2 (slob)🔢.slob✔✔ABBYY Lingvo DSL📝.dsl✔Almaany.com(SQLite3, Arabic)🔢.db✔AppleDict Binary🔢.dictionary✔❌AppleDict Source📁✔Babylon BGL🔢.bgl✔❌CC-CEDICT(Chinese)📝✔❌cc-kedict(Korean)📝✔❌CSV📝.csv✔✔Dict.cc(SQLite3, German)🔢.db✔DICT.org / Dictd server📁(📝.index)✔✔DICT.org / dictfmt source📝(.dtxt)✔dictunformat output file📝(.dictunformat)✔DictionaryForMIDs📁(📁.mids)✔✔DigitalNK(SQLite3, N-Korean)🔢.db✔DIKT JSON📝(.json)✔EDLIN📁.edlin✔✔EPUB-2 E-Book📦.epub❌✔FreeDict📝.tei✔❌Gettext Source📝.po✔✔HTML Directory (by file size)📁❌✔JMDict(Japanese)📝✔❌JSON📝.json✔Kobo E-Reader Dictionary📦.kobo.zip❌✔Kobo E-Reader Dictfile📝.df✔✔Lingoes Source📝.ldf✔✔Mobipocket E-Book🔢.mobi❌✔Octopus MDict🔢.mdx✔❌SQL📝.sql❌✔StarDict📁(📝.ifo)✔✔StarDict Textual File📝(.xml)✔✔Tabfile📝.txt, .tab✔✔Wordset.org📁✔XDXF📝.xdxf✔❌Yomichan📦(.zip)✔Zim (Kiwix)🔢.zim✔Legend:📁	Directory📝	Text file📦	Package/archive file🔢	Binary file✔		Supported❌ 	Will not be supportedNote: SQLite-based formats are not detected by extension (.db);
So you need to select the format (with UI or--read-formatflag).Also don't confuse SQLite-based formats withSQLite mode.RequirementsPyGlossary requiresPython 3.9 or higher, and works in practically all
modern operating systems. While primarily designed forGNU/Linux, it works
onWindows,Mac OS Xand other Unix-based operating systems as well.As shown in the screenshots, there are multiple User Interface types (multiple
ways to use the program).Gtk3-based interface, usesPyGI (Python Gobject Introspection)You can install it on:Debian/Ubuntu:apt install python3-gi python3-gi-cairo gir1.2-gtk-3.0openSUSE:zypper install python3-gobject gtk3Fedora:dnf install pygobject3 python3-gobject gtk3ArchLinux:pacman -S python-gobject gtk3https://aur.archlinux.org/packages/pyglossary/Mac OS X:brew install pygobject3 gtk+3Nix / NixOS:nix-shell -p pkgs.gobject-introspection python38Packages.pygobject3 python38Packages.pycairoTkinter-based interface, works in the lack of Gtk. Specially on
Windows where Tkinter library is installed with the Python itself.
You can also install it on:Debian/Ubuntu:apt-get install python3-tk tixopenSUSE:zypper install python3-tk tixFedora:yum install python3-tkinter tixMac OS X: readhttps://www.python.org/download/mac/tcltk/Nix / NixOS:nix-shell -p python38Packages.tkinter tixCommand-line interface, works in all operating systems without
any specific requirements, just type:python3 main.py --helpInteractive command-line interfaceRequires:pip install prompt_toolkitPerfect for mobile devices (like Termux on Android) where no GUI is availableAutomatically selected if output file argument is not passedandone of these:On Linux and$DISPLAYenvironment variable is empty or not setFor example when you are using a remote Linux machine over SSHOn Mac and notkintermodule is foundManually select with--cmdor--ui=cmdMinimally:python3 main.py --cmdYou can still pass input file, or any flag/optionIf both input and output files are passed, non-interactive cmd ui will be defaultIf you are writing a script, you can pass--no-interactiveto force disable interactive uiThen you have to pass both input and output file argumentsDon't forget to useUp/DownorTabkeys in prompts!Up/Down key shows you recent values you have usedTab key shows available values/optionsYou can press Control+C (on Linux/Windows) at any prompt to exitUI (User Interface) selectionWhen you run PyGlossary without any command-line arguments or options/flags,
PyGlossary tries to find PyGI and open the Gtk3-based interface. If it fails,
it tries to find Tkinter and open the Tkinter-based interface. If that fails,
it tries to findprompt_toolkitand run interactive command-line interface.
And if none of these libraries are found, it exits with an error.But you can explicitly determine the user interface type using--uipython3 main.py --ui=gtkpython3 main.py --ui=tkpython3 main.py --ui=cmdInstallation on WindowsDownload and install Python(3.9 or above)Open Start -> type Command -> right-click on Command Prompt -> Run as administratorTo ensure you havepip, run:python -m ensurepip --upgradeTo install, run:pip install --upgrade pyglossaryNow you should be able to runpyglossarycommandIf command was not found, make sure Python environment variables are set up:Feature-specific requirementsUsingSort by Localefeature requiresPyICUUsing--remove-html-allflag requires:pip install lxml beautifulsoup4Some formats have additional requirements.
If you have trouble with any format, please check thelink given for that formatto see its documentations.Using Termux on Android?Seedoc/termux.mdConfigurationSeedoc/config.rst.Direct and indirect modesIndirect mode means the input glossary is completely read and loaded into RAM, then converted
into the output format. This was the only method available in old versions (before3.0.0).Direct mode means entries are one-at-a-time read, processed and written into output glossary.Direct mode was added to limit the memory usage for large glossaries; But it may reduce the
conversion time for most cases as well.Converting glossaries into these formats requiressortingentries:StarDictEPUB-2Mobipocket E-BookThat's why direct mode will not work for these formats, and PyGlossary has to
switch to indirect mode (or it previously had to, seeSQLite mode).For other formats, direct mode will be the default. You may override this by--indirectflag.SQLite modeAs mentioned above, converting glossaries to some specific formats will
need them to loaded into RAM.This can be problematic if the glossary is too big to fit into RAM. That's when
you should try adding--sqliteflag to your command. Then it uses SQLite3 as intermediate
storage for storing, sorting and then fetching entries. This fixes the memory issue, and may
even reduce running time of conversion (depending on your home directory storage).The temporary SQLite file is stored incache directorythen
deleted after conversion (unless you pass--no-cleanupflag).SQLite mode is automatically enabled for writing these formats ifauto_sqliteconfig parameteristrue(which is the default).
This also applies to when you pass--sortflag for any format.
You may use--no-sqliteto override this and switch to indirect mode.Currently you can not disable alternates in SQLite mode (--no-altsis ignored).SortingThere are two things than can activate sorting entries:Output format requires sorting (as explainedabove)You pass--sortflag in command line.In the case of passing--sort, you can also pass:--sort-keyto select sort key aka sorting order (including locale), seedoc/sort-key.md--sort-encodingto change the encoding used for sortUTF-8 is the default encoding for all sort keys and all output formats (unless mentioned otherwise)This will only effect the order of entries, and will not corrupt words / definitionNon-encodable characters are replaced with?byte (only for sorting)Conflicts with--sort-localeCache directoryCache directory is used for storing temporary files which are either moved or deleted
after conversion. You can pass--no-cleanupflag in order to keep them.The path for cache directory:Linux or BSD:~/.cache/pyglossary/Mac:~/Library/Caches/PyGlossary/Windows:C:\Users\USERNAME\AppData\Local\PyGlossary\Cache\User pluginsIf you want to add your own plugin without adding it to source code directory,
or you want to use a plugin that has been removed from repository,
you can place it in this directory:Linux or BSD:~/.pyglossary/plugins/Mac:~/Library/Preferences/PyGlossary/plugins/Windows:C:\Users\USERNAME\AppData\Roaming\PyGlossary\plugins\Using PyGlossary as a Python libraryThere are a few examples indoc/lib-examplesdirectory.Here is a basic script that converts any supported glossary format toTabfile:importsysfrompyglossaryimportGlossary# Glossary.init() should be called only once, so make sure you put it# in the right placeGlossary.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 outputFormatoutputFormat="Tabfile",# you can pass readOptions or writeOptions as a dict# writeOptions={"encoding": "utf-8"},)And if you choose to useglossary_v2:importsysfrompyglossary.glossary_v2importConvertArgs,Glossary# Glossary.init() should be called only once, so make sure you put it# in the right placeGlossary.init()glos=Glossary()glos.convert(ConvertArgs(inputFilename=sys.argv[1],outputFilename=f"{sys.argv[1]}.txt",# although it can detect format for *.txt, you can still pass outputFormatoutputFormat="Tabfile",# you can pass readOptions or writeOptions as a dict# writeOptions={"encoding": "utf-8"},))You may look at docstring ofGlossary.convertfor full list of keyword arguments.If you need to add entries inside your Python program (rather than converting one glossary into another), then you usewriteinstead ofconvert, here is an example:frompyglossaryimportGlossaryGlossary.init()glos=Glossary()mydict={"a":"test1","b":"test2","c":"test3",}forword,defiinmydict.items():glos.addEntryObj(glos.newEntry(word,defi,defiFormat="m",# "m" for plain text, "h" for HTML))glos.setInfo("title","My Test StarDict")glos.setInfo("author","John Doe")glos.write("test.ifo",format="Stardict")Note:addEntryObjis renamed toaddEntryinpyglossary.glossary_v2.Note:Switching toglossary_v2is optional and recommended.And if you need to read a glossary from file into aGlossaryobject in RAM (without immediately converting it), you can useglos.read(filename, format=inputFormat). Be wary of RAM usage in this case.If you want to include images, css, js or other files in a glossary that you are creating, you need to add them asData Entries, for example:withopen(os.path.join(imageDir,"a.jpeg"))asfp:glos.addEntry(glos.newDataEntry("img/a.jpeg",fp.read()))The first argument tonewDataEntrymust be the relative path (that generally html codes of your definitions points to).Internal glossary structureA glossary contains a number of entries.Each entry contains:Headword (title or main phrase for lookup)Alternates (some alternative phrases for lookup)DefinitionIn PyGlossary, headword and alternates together are accessible as a single Python listentry.l_wordentry.defiis the definition as a Python Unicodestr. Alsoentry.b_defiis definition in UTF-8 byte array.entry.defiFormatis definition format. If definition is plaintext (not rich text), the value ism. And if it's in HTML (contains any html tag), thendefiFormatish. The valuexis also allowed for XFXF, but XDXF is not widely supported in dictionary applications.There is another type of entry which is calledData Entry, and generally contains an image, audio, css, or any other file that was included in input glossary. For data entries:entry.s_wordis file name (andl_wordis still a list containing this string),entry.defiFormatisbentry.datagives the content of file inbytes.Entry filtersEntry filters are internal objects that modify words/definition of entries,
or remove entries (in some special cases).Like several filters in a pipe which connects areaderobject to awriterobject
(with both of their classes defined in plugins and instantiated inGlossaryclass).You can enable/disable some of these filters using config parameters / command like flags, which
are documented indoc/config.rst.The full list of entry filters is also documented indoc/entry-filters.md.