summaryrefslogtreecommitdiff
path: root/python-pyglossary.spec
blob: 2205d2db4d4ed5253df099f67e2f0032bb8af4c0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
%global _empty_manifest_terminate_build 0
Name:		python-pyglossary
Version:	4.6.1
Release:	1
Summary:	A tool for converting dictionary files aka glossaries.
License:	GPLv3+
URL:		https://github.com/ilius/pyglossary
Source0:	https://mirrors.aliyun.com/pypi/web/packages/24/be/c1652b5ed637d83b33955d73c5a311309ef5328c2e30b197c84a35d3403d/pyglossary-4.6.1.tar.gz
BuildArch:	noarch

Requires:	python3-PyICU
Requires:	python3-PyYAML
Requires:	python3-beautifulsoup4
Requires:	python3-html5lib
Requires:	python3-libzim
Requires:	python3-lxml
Requires:	python3-marisa-trie
Requires:	python3-lzo

%description
# PyGlossary

A 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.

## Screenshots

<img src="https://raw.githubusercontent.com/wiki/ilius/pyglossary/screenshots/44-gtk-txt-stardict-aryanpur-dark.png" width="50%" height="50%"/>

Linux - Gtk3-based interface

______________________________________________________________________

<img src="https://raw.githubusercontent.com/wiki/ilius/pyglossary/screenshots/40b-tk-bgl-epub-es-en-2.png" width="50%" height="50%"/>

Windows - Tkinter-based interface

______________________________________________________________________

<img src="https://raw.githubusercontent.com/wiki/ilius/pyglossary/screenshots/32-cmd-freedict-mids-de-ru.png" width="50%" height="50%"/>

Linux - command-line interface

______________________________________________________________________

<img src="https://raw.githubusercontent.com/wiki/ilius/pyglossary/screenshots/40-cmdi-termux-zim-slob-en-med.jpg" width="50%" height="50%"/>

Android Termux - interactive command-line interface

## Supported formats

| Format                                                  |     |    Extension    | Read | Write |
| ------------------------------------------------------- | :-: | :-------------: | :--: | :---: |
| [Aard 2 (slob)](./doc/p/aard2_slob.md)                  |  🔢  |      .slob      |  ✔   |   ✔   |
| [ABBYY Lingvo DSL](./doc/p/dsl.md)                      |  📝  |      .dsl       |  ✔   |       |
| [Almaany.com](./doc/p/almaany.md) (SQLite3, Arabic)     |  🔢  |       .db       |  ✔   |       |
| [AppleDict Binary](./doc/p/appledict_bin.md)            |  🔢  |   .dictionary   |  ✔   |   ❌   |
| [AppleDict Source](./doc/p/appledict.md)                |  📁  |                 |      |   ✔   |
| [Babylon BGL](./doc/p/babylon_bgl.md)                   |  🔢  |      .bgl       |  ✔   |   ❌   |
| [CC-CEDICT](./doc/p/cc_cedict.md) (Chinese)             |  📝  |                 |  ✔   |   ❌   |
| [cc-kedict](./doc/p/cc_kedict.md) (Korean)              |  📝  |                 |  ✔   |   ❌   |
| [CSV](./doc/p/csv.md)                                   |  📝  |      .csv       |  ✔   |   ✔   |
| [Dict.cc](./doc/p/dict_cc.md) (SQLite3, German)         |  🔢  |       .db       |  ✔   |       |
| [DICT.org / Dictd server](./doc/p/dict_org.md)          |  📁  |    (📝.index)    |  ✔   |   ✔   |
| [DICT.org / dictfmt source](./doc/p/dict_org_source.md) |  📝  |     (.dtxt)     |      |   ✔   |
| [dictunformat output file](./doc/p/dictunformat.md)     |  📝  | (.dictunformat) |  ✔   |       |
| [DictionaryForMIDs](./doc/p/dicformids.md)              |  📁  |    (📁.mids)     |  ✔   |   ✔   |
| [DigitalNK](./doc/p/digitalnk.md) (SQLite3, N-Korean)   |  🔢  |       .db       |  ✔   |       |
| [DIKT JSON](./doc/p/dikt_json.md)                       |  📝  |     (.json)     |      |   ✔   |
| [EDLIN](./doc/p/edlin.md)                               |  📁  |     .edlin      |  ✔   |   ✔   |
| [EPUB-2 E-Book](./doc/p/epub2.md)                       |  📦  |      .epub      |  ❌   |   ✔   |
| [FreeDict](./doc/p/freedict.md)                         |  📝  |      .tei       |  ✔   |   ❌   |
| [Gettext Source](./doc/p/gettext_po.md)                 |  📝  |       .po       |  ✔   |   ✔   |
| [HTML Directory (by file size)](./doc/p/html_dir.md)    |  📁  |                 |  ❌   |   ✔   |
| [JMDict](./doc/p/jmdict.md) (Japanese)                  |  📝  |                 |  ✔   |   ❌   |
| [JSON](./doc/p/json.md)                                 |  📝  |      .json      |      |   ✔   |
| [Kobo E-Reader Dictionary](./doc/p/kobo.md)             |  📦  |    .kobo.zip    |  ❌   |   ✔   |
| [Kobo E-Reader Dictfile](./doc/p/kobo_dictfile.md)      |  📝  |       .df       |  ✔   |   ✔   |
| [Lingoes Source](./doc/p/lingoes_ldf.md)                |  📝  |      .ldf       |  ✔   |   ✔   |
| [Mobipocket E-Book](./doc/p/mobi.md)                    |  🔢  |      .mobi      |  ❌   |   ✔   |
| [Octopus MDict](./doc/p/octopus_mdict.md)               |  🔢  |      .mdx       |  ✔   |   ❌   |
| [SQL](./doc/p/sql.md)                                   |  📝  |      .sql       |  ❌   |   ✔   |
| [StarDict](./doc/p/stardict.md)                         |  📁  |     (📝.ifo)     |  ✔   |   ✔   |
| [StarDict Textual File](./doc/p/stardict_textual.md)    |  📝  |     (.xml)      |  ✔   |   ✔   |
| [Tabfile](./doc/p/tabfile.md)                           |  📝  |   .txt, .tab    |  ✔   |   ✔   |
| [Wordset.org](./doc/p/wordset.md)                       |  📁  |                 |  ✔   |       |
| [XDXF](./doc/p/xdxf.md)                                 |  📝  |      .xdxf      |  ✔   |   ❌   |
| [Yomichan](./doc/p/yomichan.md)                         |  📦  |     (.zip)      |      |   ✔   |
| [Zim (Kiwix)](./doc/p/zim.md)                           |  🔢  |      .zim       |  ✔   |       |

Legend:

- 📁	Directory
- 📝	Text file
- 📦	Package/archive file
- 🔢	Binary file
- ✔		Supported
- ❌ 	Will not be supported

**Note**: SQLite-based formats are not detected by extension (`.db`);
So you need to select the format (with UI or `--read-format` flag).
**Also don't confuse SQLite-based formats with [SQLite mode](#sqlite-mode).**

## Requirements

PyGlossary requires **Python 3.9 or higher**, and works in practically all
modern operating systems. While primarily designed for *GNU/Linux*, it works
on *Windows*, *Mac OS X* and 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**, uses [PyGI (Python Gobject Introspection)](http://pygobject.readthedocs.io/en/latest/getting_started.html)
  You can install it on:

  - Debian/Ubuntu: `apt install python3-gi python3-gi-cairo gir1.2-gtk-3.0`
  - openSUSE: `zypper install python3-gobject gtk3`
  - Fedora: `dnf install pygobject3 python3-gobject gtk3`
  - ArchLinux:
    - `pacman -S python-gobject gtk3`
    - https://aur.archlinux.org/packages/pyglossary/
  - Mac OS X: `brew install pygobject3 gtk+3`
  - Nix / NixOS: `nix-shell -p pkgs.gobject-introspection python38Packages.pygobject3 python38Packages.pycairo`

- **Tkinter-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 tix`
  - openSUSE: `zypper install python3-tk tix`
  - Fedora: `yum install python3-tkinter tix`
  - Mac OS X: read <https://www.python.org/download/mac/tcltk/>
  - Nix / NixOS: `nix-shell -p python38Packages.tkinter tix`

- **Command-line interface**, works in all operating systems without
  any specific requirements, just type:

  `python3 main.py --help`

  - **Interactive command-line interface**
    - Requires: `pip install prompt_toolkit`
    - Perfect for mobile devices (like Termux on Android) where no GUI is available
    - Automatically selected if output file argument is not passed **and** one of these:
      - On Linux and `$DISPLAY` environment variable is empty or not set
        - For example when you are using a remote Linux machine over SSH
      - On Mac and no `tkinter` module is found
    - Manually select with `--cmd` or `--ui=cmd`
      - Minimally: `python3 main.py --cmd`
      - You can still pass input file, or any flag/option
    - If both input and output files are passed, non-interactive cmd ui will be default
    - If you are writing a script, you can pass `--no-interactive` to force disable interactive ui
      - Then you have to pass both input and output file arguments
    - Don't forget to use *Up/Down* or *Tab* keys in prompts!
      - Up/Down key shows you recent values you have used
      - Tab key shows available values/options
    - You can press Control+C (on Linux/Windows) at any prompt to exit

## UI (User Interface) selection

When 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 find `prompt_toolkit` and 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 `--ui`

- `python3 main.py --ui=gtk`
- `python3 main.py --ui=tk`
- `python3 main.py --ui=cmd`

## Installation on Windows

- [Download and install Python](https://www.python.org/downloads/windows/) (3.9 or above)
- Open Start -> type Command -> right-click on Command Prompt -> Run as administrator
- To ensure you have `pip`, run: `python -m ensurepip --upgrade`
- To install, run: `pip install --upgrade pyglossary`
- Now you should be able to run `pyglossary` command
- If command was not found, make sure Python environment variables are set up:
  <img src="https://raw.githubusercontent.com/wiki/ilius/pyglossary/screenshots/windows-python39-env-vars.png" width="50%" height="50%"/>

## Feature-specific requirements

- Using [Sort by Locale](#sorting) feature requires [PyICU](./doc/pyicu.md)

- Using `--remove-html-all` flag requires:

  `pip install lxml beautifulsoup4`

Some formats have additional requirements.
If you have trouble with any format, please check the [link given for that format](#supported-formats) to see its documentations.

**Using Termux on Android?** See [doc/termux.md](./doc/termux.md)

## Configuration

See [doc/config.rst](./doc/config.rst).

## Direct and indirect modes

Indirect 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 (before [3.0.0](https://github.com/ilius/pyglossary/releases/tag/3.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 requires [sorting](#sorting) entries:

- [StarDict](./doc/p/stardict.md)
- [EPUB-2](./doc/p/epub2.md)
- [Mobipocket E-Book](./doc/p/mobi.md)

That's why direct mode will not work for these formats, and PyGlossary has to
switch to indirect mode (or it previously had to, see [SQLite mode](#sqlite-mode)).

For other formats, direct mode will be the default. You may override this by `--indirect` flag.

## SQLite mode

As 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 `--sqlite` flag 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 in [cache directory](#cache-directory) then
deleted after conversion (unless you pass `--no-cleanup` flag).

SQLite mode is automatically enabled for writing these formats if `auto_sqlite`
[config parameter](./doc/config.rst) is `true` (which is the default).
This also applies to when you pass `--sort` flag for any format.
You may use `--no-sqlite` to override this and switch to indirect mode.

Currently you can not disable alternates in SQLite mode (`--no-alts` is ignored).

## Sorting

There are two things than can activate sorting entries:

- Output format requires sorting (as explained [above](#direct-and-indirect-modes))
- You pass `--sort` flag in command line.

In the case of passing `--sort`, you can also pass:

- `--sort-key` to select sort key aka sorting order (including locale), see [doc/sort-key.md](./doc/sort-key.md)

- `--sort-encoding` to change the encoding used for sort

  - UTF-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 / definition
  - Non-encodable characters are replaced with `?` byte (*only for sorting*)
  - Conflicts with `--sort-locale`

## Cache directory

Cache directory is used for storing temporary files which are either moved or deleted
after conversion. You can pass `--no-cleanup` flag 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 plugins

If 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 library

There are a few examples in [doc/lib-examples](./doc/lib-examples) directory.

Here is a basic script that converts any supported glossary format to [Tabfile](./doc/p/tabfile.md):

```python
import sys
from pyglossary import Glossary

# Glossary.init() should 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"},
)
```

And if you choose to use `glossary_v2`:

```python
import sys
from pyglossary.glossary_v2 import ConvertArgs, Glossary

# Glossary.init() should be called only once, so make sure you put it
# in the right place
Glossary.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 outputFormat
	outputFormat="Tabfile",
	# you can pass readOptions or writeOptions as a dict
	# writeOptions={"encoding": "utf-8"},
))
```

You may look at docstring of `Glossary.convert` for full list of keyword arguments.


If you need to add entries inside your Python program (rather than converting one glossary into another), then you use `write` instead of `convert`, here is an example:

```python
from pyglossary import Glossary

Glossary.init()

glos = Glossary()
mydict = {
	"a": "test1",
	"b": "test2",
	"c": "test3",
}
for word, defi in mydict.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:** `addEntryObj` is renamed to `addEntry` in `pyglossary.glossary_v2`.

**Note:** Switching to `glossary_v2` is optional and recommended.


And if you need to read a glossary from file into a `Glossary` object in RAM (without immediately converting it), you can use `glos.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 as **Data Entries**, for example:

```python
with open(os.path.join(imageDir, "a.jpeg")) as fp:
	glos.addEntry(glos.newDataEntry("img/a.jpeg", fp.read()))
```

The first argument to `newDataEntry` must be the relative path (that generally html codes of your definitions points to).

## Internal glossary structure

A glossary contains a number of entries.

Each entry contains:

- Headword (title or main phrase for lookup)
- Alternates (some alternative phrases for lookup)
- Definition

In PyGlossary, headword and alternates together are accessible as a single Python list `entry.l_word`

`entry.defi` is the definition as a Python Unicode `str`. Also `entry.b_defi` is definition in UTF-8 byte array.

`entry.defiFormat` is definition format. If definition is plaintext (not rich text), the value is `m`. And if it's in HTML (contains any html tag), then `defiFormat` is `h`. The value `x` is also allowed for XFXF, but XDXF is not widely supported in dictionary applications.

There is another type of entry which is called **Data Entry**, and generally contains an image, audio, css, or any other file that was included in input glossary. For data entries:

- `entry.s_word` is file name (and `l_word` is still a list containing this string),
- `entry.defiFormat` is `b`
- `entry.data` gives the content of file in `bytes`.

## Entry filters

Entry 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 a `reader` object to a `writer` object
(with both of their classes defined in plugins and instantiated in `Glossary` class).

You can enable/disable some of these filters using config parameters / command like flags, which
are documented in [doc/config.rst](./doc/config.rst).

The full list of entry filters is also documented in [doc/entry-filters.md](./doc/entry-filters.md).


%package -n python3-pyglossary
Summary:	A tool for converting dictionary files aka glossaries.
Provides:	python-pyglossary
BuildRequires:	python3-devel
BuildRequires:	python3-setuptools
BuildRequires:	python3-pip
%description -n python3-pyglossary
# PyGlossary

A 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.

## Screenshots

<img src="https://raw.githubusercontent.com/wiki/ilius/pyglossary/screenshots/44-gtk-txt-stardict-aryanpur-dark.png" width="50%" height="50%"/>

Linux - Gtk3-based interface

______________________________________________________________________

<img src="https://raw.githubusercontent.com/wiki/ilius/pyglossary/screenshots/40b-tk-bgl-epub-es-en-2.png" width="50%" height="50%"/>

Windows - Tkinter-based interface

______________________________________________________________________

<img src="https://raw.githubusercontent.com/wiki/ilius/pyglossary/screenshots/32-cmd-freedict-mids-de-ru.png" width="50%" height="50%"/>

Linux - command-line interface

______________________________________________________________________

<img src="https://raw.githubusercontent.com/wiki/ilius/pyglossary/screenshots/40-cmdi-termux-zim-slob-en-med.jpg" width="50%" height="50%"/>

Android Termux - interactive command-line interface

## Supported formats

| Format                                                  |     |    Extension    | Read | Write |
| ------------------------------------------------------- | :-: | :-------------: | :--: | :---: |
| [Aard 2 (slob)](./doc/p/aard2_slob.md)                  |  🔢  |      .slob      |  ✔   |   ✔   |
| [ABBYY Lingvo DSL](./doc/p/dsl.md)                      |  📝  |      .dsl       |  ✔   |       |
| [Almaany.com](./doc/p/almaany.md) (SQLite3, Arabic)     |  🔢  |       .db       |  ✔   |       |
| [AppleDict Binary](./doc/p/appledict_bin.md)            |  🔢  |   .dictionary   |  ✔   |   ❌   |
| [AppleDict Source](./doc/p/appledict.md)                |  📁  |                 |      |   ✔   |
| [Babylon BGL](./doc/p/babylon_bgl.md)                   |  🔢  |      .bgl       |  ✔   |   ❌   |
| [CC-CEDICT](./doc/p/cc_cedict.md) (Chinese)             |  📝  |                 |  ✔   |   ❌   |
| [cc-kedict](./doc/p/cc_kedict.md) (Korean)              |  📝  |                 |  ✔   |   ❌   |
| [CSV](./doc/p/csv.md)                                   |  📝  |      .csv       |  ✔   |   ✔   |
| [Dict.cc](./doc/p/dict_cc.md) (SQLite3, German)         |  🔢  |       .db       |  ✔   |       |
| [DICT.org / Dictd server](./doc/p/dict_org.md)          |  📁  |    (📝.index)    |  ✔   |   ✔   |
| [DICT.org / dictfmt source](./doc/p/dict_org_source.md) |  📝  |     (.dtxt)     |      |   ✔   |
| [dictunformat output file](./doc/p/dictunformat.md)     |  📝  | (.dictunformat) |  ✔   |       |
| [DictionaryForMIDs](./doc/p/dicformids.md)              |  📁  |    (📁.mids)     |  ✔   |   ✔   |
| [DigitalNK](./doc/p/digitalnk.md) (SQLite3, N-Korean)   |  🔢  |       .db       |  ✔   |       |
| [DIKT JSON](./doc/p/dikt_json.md)                       |  📝  |     (.json)     |      |   ✔   |
| [EDLIN](./doc/p/edlin.md)                               |  📁  |     .edlin      |  ✔   |   ✔   |
| [EPUB-2 E-Book](./doc/p/epub2.md)                       |  📦  |      .epub      |  ❌   |   ✔   |
| [FreeDict](./doc/p/freedict.md)                         |  📝  |      .tei       |  ✔   |   ❌   |
| [Gettext Source](./doc/p/gettext_po.md)                 |  📝  |       .po       |  ✔   |   ✔   |
| [HTML Directory (by file size)](./doc/p/html_dir.md)    |  📁  |                 |  ❌   |   ✔   |
| [JMDict](./doc/p/jmdict.md) (Japanese)                  |  📝  |                 |  ✔   |   ❌   |
| [JSON](./doc/p/json.md)                                 |  📝  |      .json      |      |   ✔   |
| [Kobo E-Reader Dictionary](./doc/p/kobo.md)             |  📦  |    .kobo.zip    |  ❌   |   ✔   |
| [Kobo E-Reader Dictfile](./doc/p/kobo_dictfile.md)      |  📝  |       .df       |  ✔   |   ✔   |
| [Lingoes Source](./doc/p/lingoes_ldf.md)                |  📝  |      .ldf       |  ✔   |   ✔   |
| [Mobipocket E-Book](./doc/p/mobi.md)                    |  🔢  |      .mobi      |  ❌   |   ✔   |
| [Octopus MDict](./doc/p/octopus_mdict.md)               |  🔢  |      .mdx       |  ✔   |   ❌   |
| [SQL](./doc/p/sql.md)                                   |  📝  |      .sql       |  ❌   |   ✔   |
| [StarDict](./doc/p/stardict.md)                         |  📁  |     (📝.ifo)     |  ✔   |   ✔   |
| [StarDict Textual File](./doc/p/stardict_textual.md)    |  📝  |     (.xml)      |  ✔   |   ✔   |
| [Tabfile](./doc/p/tabfile.md)                           |  📝  |   .txt, .tab    |  ✔   |   ✔   |
| [Wordset.org](./doc/p/wordset.md)                       |  📁  |                 |  ✔   |       |
| [XDXF](./doc/p/xdxf.md)                                 |  📝  |      .xdxf      |  ✔   |   ❌   |
| [Yomichan](./doc/p/yomichan.md)                         |  📦  |     (.zip)      |      |   ✔   |
| [Zim (Kiwix)](./doc/p/zim.md)                           |  🔢  |      .zim       |  ✔   |       |

Legend:

- 📁	Directory
- 📝	Text file
- 📦	Package/archive file
- 🔢	Binary file
- ✔		Supported
- ❌ 	Will not be supported

**Note**: SQLite-based formats are not detected by extension (`.db`);
So you need to select the format (with UI or `--read-format` flag).
**Also don't confuse SQLite-based formats with [SQLite mode](#sqlite-mode).**

## Requirements

PyGlossary requires **Python 3.9 or higher**, and works in practically all
modern operating systems. While primarily designed for *GNU/Linux*, it works
on *Windows*, *Mac OS X* and 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**, uses [PyGI (Python Gobject Introspection)](http://pygobject.readthedocs.io/en/latest/getting_started.html)
  You can install it on:

  - Debian/Ubuntu: `apt install python3-gi python3-gi-cairo gir1.2-gtk-3.0`
  - openSUSE: `zypper install python3-gobject gtk3`
  - Fedora: `dnf install pygobject3 python3-gobject gtk3`
  - ArchLinux:
    - `pacman -S python-gobject gtk3`
    - https://aur.archlinux.org/packages/pyglossary/
  - Mac OS X: `brew install pygobject3 gtk+3`
  - Nix / NixOS: `nix-shell -p pkgs.gobject-introspection python38Packages.pygobject3 python38Packages.pycairo`

- **Tkinter-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 tix`
  - openSUSE: `zypper install python3-tk tix`
  - Fedora: `yum install python3-tkinter tix`
  - Mac OS X: read <https://www.python.org/download/mac/tcltk/>
  - Nix / NixOS: `nix-shell -p python38Packages.tkinter tix`

- **Command-line interface**, works in all operating systems without
  any specific requirements, just type:

  `python3 main.py --help`

  - **Interactive command-line interface**
    - Requires: `pip install prompt_toolkit`
    - Perfect for mobile devices (like Termux on Android) where no GUI is available
    - Automatically selected if output file argument is not passed **and** one of these:
      - On Linux and `$DISPLAY` environment variable is empty or not set
        - For example when you are using a remote Linux machine over SSH
      - On Mac and no `tkinter` module is found
    - Manually select with `--cmd` or `--ui=cmd`
      - Minimally: `python3 main.py --cmd`
      - You can still pass input file, or any flag/option
    - If both input and output files are passed, non-interactive cmd ui will be default
    - If you are writing a script, you can pass `--no-interactive` to force disable interactive ui
      - Then you have to pass both input and output file arguments
    - Don't forget to use *Up/Down* or *Tab* keys in prompts!
      - Up/Down key shows you recent values you have used
      - Tab key shows available values/options
    - You can press Control+C (on Linux/Windows) at any prompt to exit

## UI (User Interface) selection

When 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 find `prompt_toolkit` and 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 `--ui`

- `python3 main.py --ui=gtk`
- `python3 main.py --ui=tk`
- `python3 main.py --ui=cmd`

## Installation on Windows

- [Download and install Python](https://www.python.org/downloads/windows/) (3.9 or above)
- Open Start -> type Command -> right-click on Command Prompt -> Run as administrator
- To ensure you have `pip`, run: `python -m ensurepip --upgrade`
- To install, run: `pip install --upgrade pyglossary`
- Now you should be able to run `pyglossary` command
- If command was not found, make sure Python environment variables are set up:
  <img src="https://raw.githubusercontent.com/wiki/ilius/pyglossary/screenshots/windows-python39-env-vars.png" width="50%" height="50%"/>

## Feature-specific requirements

- Using [Sort by Locale](#sorting) feature requires [PyICU](./doc/pyicu.md)

- Using `--remove-html-all` flag requires:

  `pip install lxml beautifulsoup4`

Some formats have additional requirements.
If you have trouble with any format, please check the [link given for that format](#supported-formats) to see its documentations.

**Using Termux on Android?** See [doc/termux.md](./doc/termux.md)

## Configuration

See [doc/config.rst](./doc/config.rst).

## Direct and indirect modes

Indirect 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 (before [3.0.0](https://github.com/ilius/pyglossary/releases/tag/3.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 requires [sorting](#sorting) entries:

- [StarDict](./doc/p/stardict.md)
- [EPUB-2](./doc/p/epub2.md)
- [Mobipocket E-Book](./doc/p/mobi.md)

That's why direct mode will not work for these formats, and PyGlossary has to
switch to indirect mode (or it previously had to, see [SQLite mode](#sqlite-mode)).

For other formats, direct mode will be the default. You may override this by `--indirect` flag.

## SQLite mode

As 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 `--sqlite` flag 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 in [cache directory](#cache-directory) then
deleted after conversion (unless you pass `--no-cleanup` flag).

SQLite mode is automatically enabled for writing these formats if `auto_sqlite`
[config parameter](./doc/config.rst) is `true` (which is the default).
This also applies to when you pass `--sort` flag for any format.
You may use `--no-sqlite` to override this and switch to indirect mode.

Currently you can not disable alternates in SQLite mode (`--no-alts` is ignored).

## Sorting

There are two things than can activate sorting entries:

- Output format requires sorting (as explained [above](#direct-and-indirect-modes))
- You pass `--sort` flag in command line.

In the case of passing `--sort`, you can also pass:

- `--sort-key` to select sort key aka sorting order (including locale), see [doc/sort-key.md](./doc/sort-key.md)

- `--sort-encoding` to change the encoding used for sort

  - UTF-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 / definition
  - Non-encodable characters are replaced with `?` byte (*only for sorting*)
  - Conflicts with `--sort-locale`

## Cache directory

Cache directory is used for storing temporary files which are either moved or deleted
after conversion. You can pass `--no-cleanup` flag 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 plugins

If 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 library

There are a few examples in [doc/lib-examples](./doc/lib-examples) directory.

Here is a basic script that converts any supported glossary format to [Tabfile](./doc/p/tabfile.md):

```python
import sys
from pyglossary import Glossary

# Glossary.init() should 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"},
)
```

And if you choose to use `glossary_v2`:

```python
import sys
from pyglossary.glossary_v2 import ConvertArgs, Glossary

# Glossary.init() should be called only once, so make sure you put it
# in the right place
Glossary.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 outputFormat
	outputFormat="Tabfile",
	# you can pass readOptions or writeOptions as a dict
	# writeOptions={"encoding": "utf-8"},
))
```

You may look at docstring of `Glossary.convert` for full list of keyword arguments.


If you need to add entries inside your Python program (rather than converting one glossary into another), then you use `write` instead of `convert`, here is an example:

```python
from pyglossary import Glossary

Glossary.init()

glos = Glossary()
mydict = {
	"a": "test1",
	"b": "test2",
	"c": "test3",
}
for word, defi in mydict.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:** `addEntryObj` is renamed to `addEntry` in `pyglossary.glossary_v2`.

**Note:** Switching to `glossary_v2` is optional and recommended.


And if you need to read a glossary from file into a `Glossary` object in RAM (without immediately converting it), you can use `glos.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 as **Data Entries**, for example:

```python
with open(os.path.join(imageDir, "a.jpeg")) as fp:
	glos.addEntry(glos.newDataEntry("img/a.jpeg", fp.read()))
```

The first argument to `newDataEntry` must be the relative path (that generally html codes of your definitions points to).

## Internal glossary structure

A glossary contains a number of entries.

Each entry contains:

- Headword (title or main phrase for lookup)
- Alternates (some alternative phrases for lookup)
- Definition

In PyGlossary, headword and alternates together are accessible as a single Python list `entry.l_word`

`entry.defi` is the definition as a Python Unicode `str`. Also `entry.b_defi` is definition in UTF-8 byte array.

`entry.defiFormat` is definition format. If definition is plaintext (not rich text), the value is `m`. And if it's in HTML (contains any html tag), then `defiFormat` is `h`. The value `x` is also allowed for XFXF, but XDXF is not widely supported in dictionary applications.

There is another type of entry which is called **Data Entry**, and generally contains an image, audio, css, or any other file that was included in input glossary. For data entries:

- `entry.s_word` is file name (and `l_word` is still a list containing this string),
- `entry.defiFormat` is `b`
- `entry.data` gives the content of file in `bytes`.

## Entry filters

Entry 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 a `reader` object to a `writer` object
(with both of their classes defined in plugins and instantiated in `Glossary` class).

You can enable/disable some of these filters using config parameters / command like flags, which
are documented in [doc/config.rst](./doc/config.rst).

The full list of entry filters is also documented in [doc/entry-filters.md](./doc/entry-filters.md).


%package help
Summary:	Development documents and examples for pyglossary
Provides:	python3-pyglossary-doc
%description help
# PyGlossary

A 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.

## Screenshots

<img src="https://raw.githubusercontent.com/wiki/ilius/pyglossary/screenshots/44-gtk-txt-stardict-aryanpur-dark.png" width="50%" height="50%"/>

Linux - Gtk3-based interface

______________________________________________________________________

<img src="https://raw.githubusercontent.com/wiki/ilius/pyglossary/screenshots/40b-tk-bgl-epub-es-en-2.png" width="50%" height="50%"/>

Windows - Tkinter-based interface

______________________________________________________________________

<img src="https://raw.githubusercontent.com/wiki/ilius/pyglossary/screenshots/32-cmd-freedict-mids-de-ru.png" width="50%" height="50%"/>

Linux - command-line interface

______________________________________________________________________

<img src="https://raw.githubusercontent.com/wiki/ilius/pyglossary/screenshots/40-cmdi-termux-zim-slob-en-med.jpg" width="50%" height="50%"/>

Android Termux - interactive command-line interface

## Supported formats

| Format                                                  |     |    Extension    | Read | Write |
| ------------------------------------------------------- | :-: | :-------------: | :--: | :---: |
| [Aard 2 (slob)](./doc/p/aard2_slob.md)                  |  🔢  |      .slob      |  ✔   |   ✔   |
| [ABBYY Lingvo DSL](./doc/p/dsl.md)                      |  📝  |      .dsl       |  ✔   |       |
| [Almaany.com](./doc/p/almaany.md) (SQLite3, Arabic)     |  🔢  |       .db       |  ✔   |       |
| [AppleDict Binary](./doc/p/appledict_bin.md)            |  🔢  |   .dictionary   |  ✔   |   ❌   |
| [AppleDict Source](./doc/p/appledict.md)                |  📁  |                 |      |   ✔   |
| [Babylon BGL](./doc/p/babylon_bgl.md)                   |  🔢  |      .bgl       |  ✔   |   ❌   |
| [CC-CEDICT](./doc/p/cc_cedict.md) (Chinese)             |  📝  |                 |  ✔   |   ❌   |
| [cc-kedict](./doc/p/cc_kedict.md) (Korean)              |  📝  |                 |  ✔   |   ❌   |
| [CSV](./doc/p/csv.md)                                   |  📝  |      .csv       |  ✔   |   ✔   |
| [Dict.cc](./doc/p/dict_cc.md) (SQLite3, German)         |  🔢  |       .db       |  ✔   |       |
| [DICT.org / Dictd server](./doc/p/dict_org.md)          |  📁  |    (📝.index)    |  ✔   |   ✔   |
| [DICT.org / dictfmt source](./doc/p/dict_org_source.md) |  📝  |     (.dtxt)     |      |   ✔   |
| [dictunformat output file](./doc/p/dictunformat.md)     |  📝  | (.dictunformat) |  ✔   |       |
| [DictionaryForMIDs](./doc/p/dicformids.md)              |  📁  |    (📁.mids)     |  ✔   |   ✔   |
| [DigitalNK](./doc/p/digitalnk.md) (SQLite3, N-Korean)   |  🔢  |       .db       |  ✔   |       |
| [DIKT JSON](./doc/p/dikt_json.md)                       |  📝  |     (.json)     |      |   ✔   |
| [EDLIN](./doc/p/edlin.md)                               |  📁  |     .edlin      |  ✔   |   ✔   |
| [EPUB-2 E-Book](./doc/p/epub2.md)                       |  📦  |      .epub      |  ❌   |   ✔   |
| [FreeDict](./doc/p/freedict.md)                         |  📝  |      .tei       |  ✔   |   ❌   |
| [Gettext Source](./doc/p/gettext_po.md)                 |  📝  |       .po       |  ✔   |   ✔   |
| [HTML Directory (by file size)](./doc/p/html_dir.md)    |  📁  |                 |  ❌   |   ✔   |
| [JMDict](./doc/p/jmdict.md) (Japanese)                  |  📝  |                 |  ✔   |   ❌   |
| [JSON](./doc/p/json.md)                                 |  📝  |      .json      |      |   ✔   |
| [Kobo E-Reader Dictionary](./doc/p/kobo.md)             |  📦  |    .kobo.zip    |  ❌   |   ✔   |
| [Kobo E-Reader Dictfile](./doc/p/kobo_dictfile.md)      |  📝  |       .df       |  ✔   |   ✔   |
| [Lingoes Source](./doc/p/lingoes_ldf.md)                |  📝  |      .ldf       |  ✔   |   ✔   |
| [Mobipocket E-Book](./doc/p/mobi.md)                    |  🔢  |      .mobi      |  ❌   |   ✔   |
| [Octopus MDict](./doc/p/octopus_mdict.md)               |  🔢  |      .mdx       |  ✔   |   ❌   |
| [SQL](./doc/p/sql.md)                                   |  📝  |      .sql       |  ❌   |   ✔   |
| [StarDict](./doc/p/stardict.md)                         |  📁  |     (📝.ifo)     |  ✔   |   ✔   |
| [StarDict Textual File](./doc/p/stardict_textual.md)    |  📝  |     (.xml)      |  ✔   |   ✔   |
| [Tabfile](./doc/p/tabfile.md)                           |  📝  |   .txt, .tab    |  ✔   |   ✔   |
| [Wordset.org](./doc/p/wordset.md)                       |  📁  |                 |  ✔   |       |
| [XDXF](./doc/p/xdxf.md)                                 |  📝  |      .xdxf      |  ✔   |   ❌   |
| [Yomichan](./doc/p/yomichan.md)                         |  📦  |     (.zip)      |      |   ✔   |
| [Zim (Kiwix)](./doc/p/zim.md)                           |  🔢  |      .zim       |  ✔   |       |

Legend:

- 📁	Directory
- 📝	Text file
- 📦	Package/archive file
- 🔢	Binary file
- ✔		Supported
- ❌ 	Will not be supported

**Note**: SQLite-based formats are not detected by extension (`.db`);
So you need to select the format (with UI or `--read-format` flag).
**Also don't confuse SQLite-based formats with [SQLite mode](#sqlite-mode).**

## Requirements

PyGlossary requires **Python 3.9 or higher**, and works in practically all
modern operating systems. While primarily designed for *GNU/Linux*, it works
on *Windows*, *Mac OS X* and 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**, uses [PyGI (Python Gobject Introspection)](http://pygobject.readthedocs.io/en/latest/getting_started.html)
  You can install it on:

  - Debian/Ubuntu: `apt install python3-gi python3-gi-cairo gir1.2-gtk-3.0`
  - openSUSE: `zypper install python3-gobject gtk3`
  - Fedora: `dnf install pygobject3 python3-gobject gtk3`
  - ArchLinux:
    - `pacman -S python-gobject gtk3`
    - https://aur.archlinux.org/packages/pyglossary/
  - Mac OS X: `brew install pygobject3 gtk+3`
  - Nix / NixOS: `nix-shell -p pkgs.gobject-introspection python38Packages.pygobject3 python38Packages.pycairo`

- **Tkinter-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 tix`
  - openSUSE: `zypper install python3-tk tix`
  - Fedora: `yum install python3-tkinter tix`
  - Mac OS X: read <https://www.python.org/download/mac/tcltk/>
  - Nix / NixOS: `nix-shell -p python38Packages.tkinter tix`

- **Command-line interface**, works in all operating systems without
  any specific requirements, just type:

  `python3 main.py --help`

  - **Interactive command-line interface**
    - Requires: `pip install prompt_toolkit`
    - Perfect for mobile devices (like Termux on Android) where no GUI is available
    - Automatically selected if output file argument is not passed **and** one of these:
      - On Linux and `$DISPLAY` environment variable is empty or not set
        - For example when you are using a remote Linux machine over SSH
      - On Mac and no `tkinter` module is found
    - Manually select with `--cmd` or `--ui=cmd`
      - Minimally: `python3 main.py --cmd`
      - You can still pass input file, or any flag/option
    - If both input and output files are passed, non-interactive cmd ui will be default
    - If you are writing a script, you can pass `--no-interactive` to force disable interactive ui
      - Then you have to pass both input and output file arguments
    - Don't forget to use *Up/Down* or *Tab* keys in prompts!
      - Up/Down key shows you recent values you have used
      - Tab key shows available values/options
    - You can press Control+C (on Linux/Windows) at any prompt to exit

## UI (User Interface) selection

When 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 find `prompt_toolkit` and 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 `--ui`

- `python3 main.py --ui=gtk`
- `python3 main.py --ui=tk`
- `python3 main.py --ui=cmd`

## Installation on Windows

- [Download and install Python](https://www.python.org/downloads/windows/) (3.9 or above)
- Open Start -> type Command -> right-click on Command Prompt -> Run as administrator
- To ensure you have `pip`, run: `python -m ensurepip --upgrade`
- To install, run: `pip install --upgrade pyglossary`
- Now you should be able to run `pyglossary` command
- If command was not found, make sure Python environment variables are set up:
  <img src="https://raw.githubusercontent.com/wiki/ilius/pyglossary/screenshots/windows-python39-env-vars.png" width="50%" height="50%"/>

## Feature-specific requirements

- Using [Sort by Locale](#sorting) feature requires [PyICU](./doc/pyicu.md)

- Using `--remove-html-all` flag requires:

  `pip install lxml beautifulsoup4`

Some formats have additional requirements.
If you have trouble with any format, please check the [link given for that format](#supported-formats) to see its documentations.

**Using Termux on Android?** See [doc/termux.md](./doc/termux.md)

## Configuration

See [doc/config.rst](./doc/config.rst).

## Direct and indirect modes

Indirect 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 (before [3.0.0](https://github.com/ilius/pyglossary/releases/tag/3.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 requires [sorting](#sorting) entries:

- [StarDict](./doc/p/stardict.md)
- [EPUB-2](./doc/p/epub2.md)
- [Mobipocket E-Book](./doc/p/mobi.md)

That's why direct mode will not work for these formats, and PyGlossary has to
switch to indirect mode (or it previously had to, see [SQLite mode](#sqlite-mode)).

For other formats, direct mode will be the default. You may override this by `--indirect` flag.

## SQLite mode

As 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 `--sqlite` flag 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 in [cache directory](#cache-directory) then
deleted after conversion (unless you pass `--no-cleanup` flag).

SQLite mode is automatically enabled for writing these formats if `auto_sqlite`
[config parameter](./doc/config.rst) is `true` (which is the default).
This also applies to when you pass `--sort` flag for any format.
You may use `--no-sqlite` to override this and switch to indirect mode.

Currently you can not disable alternates in SQLite mode (`--no-alts` is ignored).

## Sorting

There are two things than can activate sorting entries:

- Output format requires sorting (as explained [above](#direct-and-indirect-modes))
- You pass `--sort` flag in command line.

In the case of passing `--sort`, you can also pass:

- `--sort-key` to select sort key aka sorting order (including locale), see [doc/sort-key.md](./doc/sort-key.md)

- `--sort-encoding` to change the encoding used for sort

  - UTF-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 / definition
  - Non-encodable characters are replaced with `?` byte (*only for sorting*)
  - Conflicts with `--sort-locale`

## Cache directory

Cache directory is used for storing temporary files which are either moved or deleted
after conversion. You can pass `--no-cleanup` flag 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 plugins

If 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 library

There are a few examples in [doc/lib-examples](./doc/lib-examples) directory.

Here is a basic script that converts any supported glossary format to [Tabfile](./doc/p/tabfile.md):

```python
import sys
from pyglossary import Glossary

# Glossary.init() should 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"},
)
```

And if you choose to use `glossary_v2`:

```python
import sys
from pyglossary.glossary_v2 import ConvertArgs, Glossary

# Glossary.init() should be called only once, so make sure you put it
# in the right place
Glossary.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 outputFormat
	outputFormat="Tabfile",
	# you can pass readOptions or writeOptions as a dict
	# writeOptions={"encoding": "utf-8"},
))
```

You may look at docstring of `Glossary.convert` for full list of keyword arguments.


If you need to add entries inside your Python program (rather than converting one glossary into another), then you use `write` instead of `convert`, here is an example:

```python
from pyglossary import Glossary

Glossary.init()

glos = Glossary()
mydict = {
	"a": "test1",
	"b": "test2",
	"c": "test3",
}
for word, defi in mydict.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:** `addEntryObj` is renamed to `addEntry` in `pyglossary.glossary_v2`.

**Note:** Switching to `glossary_v2` is optional and recommended.


And if you need to read a glossary from file into a `Glossary` object in RAM (without immediately converting it), you can use `glos.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 as **Data Entries**, for example:

```python
with open(os.path.join(imageDir, "a.jpeg")) as fp:
	glos.addEntry(glos.newDataEntry("img/a.jpeg", fp.read()))
```

The first argument to `newDataEntry` must be the relative path (that generally html codes of your definitions points to).

## Internal glossary structure

A glossary contains a number of entries.

Each entry contains:

- Headword (title or main phrase for lookup)
- Alternates (some alternative phrases for lookup)
- Definition

In PyGlossary, headword and alternates together are accessible as a single Python list `entry.l_word`

`entry.defi` is the definition as a Python Unicode `str`. Also `entry.b_defi` is definition in UTF-8 byte array.

`entry.defiFormat` is definition format. If definition is plaintext (not rich text), the value is `m`. And if it's in HTML (contains any html tag), then `defiFormat` is `h`. The value `x` is also allowed for XFXF, but XDXF is not widely supported in dictionary applications.

There is another type of entry which is called **Data Entry**, and generally contains an image, audio, css, or any other file that was included in input glossary. For data entries:

- `entry.s_word` is file name (and `l_word` is still a list containing this string),
- `entry.defiFormat` is `b`
- `entry.data` gives the content of file in `bytes`.

## Entry filters

Entry 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 a `reader` object to a `writer` object
(with both of their classes defined in plugins and instantiated in `Glossary` class).

You can enable/disable some of these filters using config parameters / command like flags, which
are documented in [doc/config.rst](./doc/config.rst).

The full list of entry filters is also documented in [doc/entry-filters.md](./doc/entry-filters.md).


%prep
%autosetup -n pyglossary-4.6.1

%build
%py3_build

%install
%py3_install
install -d -m755 %{buildroot}/%{_pkgdocdir}
if [ -d doc ]; then cp -arf doc %{buildroot}/%{_pkgdocdir}; fi
if [ -d docs ]; then cp -arf docs %{buildroot}/%{_pkgdocdir}; fi
if [ -d example ]; then cp -arf example %{buildroot}/%{_pkgdocdir}; fi
if [ -d examples ]; then cp -arf examples %{buildroot}/%{_pkgdocdir}; fi
pushd %{buildroot}
if [ -d usr/lib ]; then
	find usr/lib -type f -printf "\"/%h/%f\"\n" >> filelist.lst
fi
if [ -d usr/lib64 ]; then
	find usr/lib64 -type f -printf "\"/%h/%f\"\n" >> filelist.lst
fi
if [ -d usr/bin ]; then
	find usr/bin -type f -printf "\"/%h/%f\"\n" >> filelist.lst
fi
if [ -d usr/sbin ]; then
	find usr/sbin -type f -printf "\"/%h/%f\"\n" >> filelist.lst
fi
touch doclist.lst
if [ -d usr/share/man ]; then
	find usr/share/man -type f -printf "\"/%h/%f.gz\"\n" >> doclist.lst
fi
popd
mv %{buildroot}/filelist.lst .
mv %{buildroot}/doclist.lst .

%files -n python3-pyglossary -f filelist.lst
%dir %{python3_sitelib}/*

%files help -f doclist.lst
%{_docdir}/*

%changelog
* Tue Jun 20 2023 Python_Bot <Python_Bot@openeuler.org> - 4.6.1-1
- Package Spec generated