-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhxltmcli
executable file
·7637 lines (6160 loc) · 253 KB
/
hxltmcli
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
#!/usr/bin/env python3
# ==============================================================================
#
# FILE: hxltmcli.py
#
# USAGE: hxltmcli un-htcds.tm.hxl.csv un-htcds.xliff
# cat un-htcds.tm.hxl.csv | hxltmcli > un-htcds.xliff
#
# DESCRIPTION: _[eng-Latn] The HXLTM reference implementation in python.
# While this can installed with hdp-toolchain:
# pip install hdp-toolchain
# The one--big-file hxltmcli.py (along with the
# cor.hxltm.yml) can be customized as single
# python script. But on this case, you will need
# to install at least the hard dependencies
# of hxltmcli:
#
# pip install libhxl langcodes pyyaml python-liquid
#
# [eng-Latn]_
# @see http://docs.oasis-open.org/xliff/xliff-core/v2.1
# /os/xliff-core-v2.1-os.html
# @see https://www.gala-global.org/lisa-oscar-standards
# @see https://github.com/HXL-CPLP/forum/issues/58
# @see https://github.com/HXL-CPLP/Auxilium-Humanitarium-API
# /issues/16
#
# OPTIONS: ---
#
# REQUIREMENTS: - python3
# - libhxl (@see https://pypi.org/project/libhxl/)
# - pip3 install libhxl
# - langcodes (@see https://github.com/rspeer/langcodes)
# - pip3 install langcodes
# - pyyaml (@see https://github.com/yaml/pyyaml)
# - pip3 install pyyaml
# - langcodes (@see https://github.com/jg-rp/liquid)
# - pip3 install python-liquid
# - Know to work with at least python-liquid v0.8.1
# BUGS: ---
# NOTES: ---
# AUTHORS: Emerson Rocha <rocha[at]ieee.org>
# COLLABORATORS:
# <@TODO: put additional non-anonymous names here>
#
# COMPANY: EticaAI
# LICENSE: Public Domain dedication
# SPDX-License-Identifier: Unlicense
# VERSION: v0.8.8
# CREATED: 2021-06-27 19:50 UTC v0.5, de github.com/EticaAI
# /HXL-Data-Science-file-formats/blob/main/bin/hxl2example
# REVISION: 2021-06-27 21:16 UTC v0.6 de hxl2tab
# REVISION: 2021-06-27 23:53 UTC v0.7 --archivum-extensionem=.csv
# 2021-06-29 22:29 UTC v0.8 MVP of --archivum-extensionem=.tmx
# Translation Memory eXchange format (TMX).
# 2021-06-29 23:16 UTC v0.8.1 hxltm2xliff renamed to hxltmcli;
# Moved from github.com/HXL-CPLP/Auxilium-Humanitarium-API
# to github.com/EticaAI/HXL-Data-Science-file-formats
# 2021-07-04 04:35 UTC v0.8.2 Configurations on cor.hxltm.yml
# 2021-07-15 00:02 UTC v0.8.3 HXLTM ASA working draft
# 2021-07-18 21:39 UTC v0.8.4 HXLTM ASA MVP (TMX and XLIFF 2)
# 2021-07-19 17:50 UTC v0.8.5 HXLTM ASA MVP XLIFF 1, TBX-Basic
# 2021-07-20 00:32 UTC v0.8.6 HXLTM ASA MVP CSV-3, TSV-3
# 2021-10-15 17:08 UTC v0.8.7 MVP of --objectivum-formulam
# 2021-10-15 17:08 UTC v0.8.8 --objectivum-formulam, allow
# save result to file (was working for stdout)
# ==============================================================================
"""hxltmcli.py: Humanitarian Exchange Language Trānslātiōnem Memoriam CLI
_[eng-Latn]
Crash course from names in Latin to English
----------
- datum:
- Dataset
- columnam (or crudum columnam):
- Column, spreadsheet column, variable (of a item)
- līneam (or crudum līneam):
- row, spreadsheet row, line (used mostly for 'crudum rem', raw item)
- rem:
- Thing (generic)
- conceptum
- Concept (used on HXLTM to diferenciate what is translation, rem, from
concept that applies to all language variants of the sabe thing)
- fontem:
- Source
- objectīvum:
- Objective, target (as in target language, output archive)
- linguam:
- Language, natural language
- bilingue
- bilingual (as used on operations with source to target language in XLIFF)
- multiplum linguam
- 1 to n languages (as used on operations that work with many languages
like TMX and TBX)
- collēctiōnem:
- collection, List, array (not sure if exist better naming in Latin, sorry)
- obiectum
- Object (or Python Dict)
- Caput
- Header
- Vēnandum īnsectum
- Debugging
- 'Exemplōrum gratiā (et Python doctest, id est, testum automata)'
- 'For example (and python doctest, that is, automated testing)'
- @see https://docs.python.org/3/library/doctest.html
- python3 -m doctest hxltmcli-fork-from-marcus.py
- python3 -m doctest hxlm/core/bin/hxltmcli.py
Some other very frequent generic terms:
- ad:
- @see https://en.wiktionary.org/wiki/ad#Latin
- (direction) toward, to
- up to (indicating direction upwards)
- in consequence of
- for, to, toward (indicating purpose or aim)
- in order to, to, for (indicating means)
- (...)
- de:
- @see https://en.wiktionary.org/wiki/de#Latin
- of, concerning, about
- from, away from, down from, out of
- in:
- @see https://en.wiktionary.org/wiki/in#Latin
- toward, towards, against, at
- until, for
- about
- according to
> Tips:
> - HXL-CPLP-Vocab_Auxilium-Humanitarium-API spreadsheet have additional terms
> - Google _wiktionary term-in-english_. Sometimes Google Translate will
> give the perfect term, but to keep consistent, we use:
> - Accusative
> - Singular
> - Neuter (You know, inclusive language)
> - 'Marcus loves/likes his dog', in Latin (same meaning different emphasis):
> - Marcus canem amat.
> - Canem Marcus amat.
> - Amat canem Marcus.
> - Marcus amat canem.
> - Canem amat Marcus.
> - Amat Marcus canem.
> - Marcum canis amat.
> - Canis Marcum amat.
> - Amat canis Marcum.
> - Marcum amat canis.
> - Canis amat Marcum.
> - Amat Marcum canis.
> - Latin, while very expressive/verbose language (and great to use on
> ontologies, naming animals, etc, and this is the reason to use a few terms
> in Latin on hxltmcli.py), was not what 'the people' used because was
> hard even for the first class citizen with elite education 2000 years ago.
> - Most example usages with HXLTM will use the 'prestige dialect' for a
> ISO 15924 script (like translate from lat-Latn to ara-Arab, zho-Hant,
> rus-Cyrl, and etc...) even when in fact we, 'the people', will use
> more specific language/dialects, like por-Latn.
Missing 'good' Latin terms to express meaning in English (for software)
----------
- array, list
- @see https://en.wiktionary.org/wiki/array
- Sometimes we use 'Python List' as in
- "Rem collēctiōnem, id est, Python List"
- output (preferable some short word, not like prōductiōnem)
- @see https://en.wiktionary.org/wiki/output#English
- input
- @see https://en.wiktionary.org/wiki/input
To Do
---------
- Improve the terms used for 'questions', like
'quid'/ 'quod'
- @see https://dcc.dickinson.edu/grammar/latin/questions
[eng-Latn]_
"""
import sys
import os
import logging
import argparse
from pathlib import Path
import re
# from abc import ABC, abstractmethod
from abc import ABC
import csv
import tempfile
from functools import reduce
from typing import (
Any,
Dict,
Iterable,
Optional,
List,
TextIO,
Type,
Union,
)
from dataclasses import dataclass, InitVar
# from dataclasses import dataclass, InitVar, field
# from copy import deepcopy
from collections import OrderedDict
import json
import yaml
# @see https://github.com/HXLStandard/libhxl-python
# pip3 install libhxl --upgrade
# Do not import hxl, to avoid circular imports
import hxl.converters
import hxl.filters
import hxl.io
import hxl.datatypes
# @see https://github.com/rspeer/langcodes
# pip3 install langcodes
import langcodes
# @see https://github.com/jg-rp/liquid
# pip3 install -U python-liquid
# from liquid import Template as LiquidTemplate
from liquid import Environment as LiquidEnvironment
# from liquid.tag import Tag as LiquidTag
# from liquid.parse import get_parser as liquid_get_parser
# from liquid.parse import expect as liquid_expect
from liquid.loaders import DictLoader as LiquiDictLoader
from liquid.filter import string_filter as liquid_string_filter
from liquid.filter import array_filter as liquid_array_filter
# ...
from liquid.ast import Node as LiquidNode
from liquid.builtin.statement import StatementNode as LiquidStatementNode
# from liquid.lex import tokenize_filtered_expression
# from liquid.parse import parse_filtered_expression
from liquid.parse import expect as liquid_expect
from liquid.stream import TokenStream as LiquidTokenStream
from liquid.tag import Tag as LiquidTag
from liquid.token import TOKEN_TAG as LIQUID_TOKEN_TAG
from liquid.token import Token as LiquidToken
# from liquid.expression import Expression as LiquidExpression
from liquid.context import Context as LiquidContext
# from liquid.token import TOKEN_EXPRESSION as LIQUID_TOKEN_EXPRESSION
__VERSION__ = "v0.8.8"
# _[eng-Latn]
# Note: If you are doing a fork and making it public, please customize
# __SYSTEMA_VARIANS__, even if the __VERSION__ keeps the same
# [eng-Latn]_
__SYSTEMA_VARIANS__ = "hxltmcli.py;EticaAI+voluntārium-commūne"
# Trivia:
# - systēma, https://en.wiktionary.org/wiki/systema#Latin
# - variāns, https://en.wiktionary.org/wiki/varians#Latin
# - furcam, https://en.wiktionary.org/wiki/furca#Latin
# - commūne, https://en.wiktionary.org/wiki/communis#Latin
# - voluntārium, https://en.wiktionary.org/wiki/voluntarius#Latin
__DESCRIPTIONEM_BREVE__ = """
_[eng-Latn] hxltmcli {0} is an implementation of HXLTM tagging conventions
on HXL to manage and export tabular data to popular translation memories
and glossaries file formats with non-close standards.
[eng-Latn]_"
""".format(__VERSION__)
# tag::epilogum[]
__EPILOGUM__ = """
Exemplōrum gratiā:
HXLTM (csv) -> Translation Memory eXchange format (TMX):
hxltmcli fontem.tm.hxl.csv objectivum.tmx --objectivum-TMX
HXLTM (xlsx; sheet 7) -> Translation Memory eXchange format (TMX):
hxltmcli fontem.xlsx objectivum.tmx --sheet 7 --objectivum-TMX
HXLTM (xlsx; sheet 7, Situs interretialis) -> HXLTM (csv):
hxltmcli https://example.org/fontem.xlsx --sheet 7 fontem.tm.hxl.csv
HXLTM (Google Docs) -> HXLTM (csv):
hxltmcli https://docs.google.com/spreadsheets/(...) fontem.tm.hxl.csv
HXLTM (Google Docs) -> Translation Memory eXchange format (TMX):
hxltmcli https://docs.google.com/spreadsheets/(...) objectivum.tmx \
--objectivum-TMX
"""
# end::epilogum[]
# systēma
# In Python2, sys.stdin is a byte stream; in Python3, it's a text stream
STDIN = sys.stdin.buffer
_HOME = str(Path.home())
# TODO: clean up redundancy from hxlm/core/schema/urn/util.py
HXLM_CONFIG_BASE = os.getenv(
'HXLM_CONFIG_BASE', _HOME + '/.config/hxlm')
# ~/.config/hxlm/cor.hxltm.yml
# _[eng-Latn]
# This can be customized with enviroment variable HXLM_CONFIG_BASE
#
# Since hpd-toolchain is not a hard requeriment, we first try to load
# hdp-toolchain lib, but if hxltmcli is a standalone script with
# only libhxl, yaml, etc installed, we tolerate it
# [eng-Latn]_
try:
from hxlm.core.constant import (
HXLM_ROOT,
HDATUM_EXEMPLUM
)
HXLTM_SCRIPT_DIR = HXLM_ROOT + '/core/bin'
HXLTM_TESTUM_BASIM_DEFALLO = str(HDATUM_EXEMPLUM).replace('file://', '')
except ImportError:
HXLTM_SCRIPT_DIR = str(Path(__file__).parent.resolve())
HXLTM_TESTUM_BASIM_DEFALLO = str(Path(
HXLTM_SCRIPT_DIR + '/../../../testum/hxltm').resolve())
HXLTM_RUNNING_DIR = str(Path().resolve())
class HXLTMCLI: # pylint: disable=too-many-instance-attributes
"""
_[eng-Latn] hxltmcli is an working draft of a tool to
convert prototype of translation memory stored with HXL to
XLIFF v2.1
[eng-Latn]_
"""
def __init__(self):
"""
_[eng-Latn] Constructs all the necessary attributes for the
HXLTMCLI object.
[eng-Latn]_
"""
self.hxlhelper = None
# self.args = None
self.conf = {} # Crudum, raw file
# Only for initialization. Use self.hxltm_asa.ontologia (if need)
self._ontologia = None # HXLTMOntologia object
# Only for initialization. Use self.hxltm_asa.argumentum (if need)
self._argumentum: Type['HXLTMArgumentum'] = None
# TODO: replace self.datum by HXLTMASA
# self.datum: HXLTMDatum = None
self.hxltm_asa: Type['HXLTMASA'] = None
# self.meta_archivum_fontem = {}
self.meta_archivum_fontem = {}
# self.errors = []
# Posix exit codes
self.EXIT_OK = 0 # pylint: disable=invalid-name
self.EXIT_ERROR = 1 # pylint: disable=invalid-name
self.EXIT_SYNTAX = 2 # pylint: disable=invalid-name
self.original_outfile = None
self.original_outfile_is_stdout = True
# TODO: move _objectivum_formatum_from_outfile to HXLTMOntologia
def _objectivum_formatum_from_outfile(self, outfile):
"""Uses cor.hxltm.yml fontem_archivum_extensionem to detect output
format without user need to explicitly inform the option.
This is not used if the result is stdout
Args:
outfile ([str]): Path string of output file
Returns:
[str]: A valid cor.hxltm.yml formatum
"""
outfile_lower = outfile.lower()
if self.conf and self.conf['fontem_archivum_extensionem']:
for key in self.conf['fontem_archivum_extensionem']:
if outfile_lower.endswith(key):
return self.conf['fontem_archivum_extensionem'][key]
return 'INCOGNITUM'
def _initiale(self, pyargs):
"""Trivia: initiāle, https://en.wiktionary.org/wiki/initialis#Latin
"""
# if pyargs.expertum_metadatum_est:
# self.expertum_metadatum_est = pyargs.expertum_metadatum_est
# TODO: migrate all this to HXLTMASA._initiale
# pyargs.est_stdout = True
if pyargs:
self._argumentum = HXLTMArgumentum().de_argparse(pyargs)
else:
self._argumentum = HXLTMArgumentum()
self.conf = HXLTMUtil.load_hxltm_options(
pyargs.archivum_configurationem,
pyargs.venandum_insectum
)
self._ontologia = HXLTMOntologia(self.conf)
def _initiale_hxltm_asa(self, archivum: str) -> bool:
"""
_[eng-Latn]
Pre-populate metadata about source file
Requires already HXLated file saved on disk.
[eng-Latn]_
Trivia:
- initiāle, https://en.wiktionary.org/wiki/initialis#Latin
- HXLTM, https://hdp.etica.ai/hxltm
- HXLTM ASA, https://hdp.etica.ai/hxltm/archivum/#HXLTM-ASA
Args:
archivum (str): Archīvum trivia
argumentum (Dict):
_[lat-Latn]
Python argumentum,
https://docs.python.org/3/library/argparse.html
[lat-Latn]_
Returns:
bool: If okay.
"""
# with open(archivum, 'r') as arch:
# hxltm_crudum = arch.read().splitlines()
self.hxltm_asa = HXLTMASA(
archivum,
ontologia=self._ontologia,
# argumentum=argumentum,
argumentum=self._argumentum,
# verbosum=argumentum.hxltm_asa_verbosum
)
# Only for initialization. Now use self.hxltm_asa.ontologia (if need)
self._ontologia = None
# Only for initialization. Now use self.hxltm_asa.argumentum (if need)
self._argumentum = None
def make_args_hxltmcli(self):
"""make_args_hxltmcli
"""
self.hxlhelper = HXLUtils()
parser = self.hxlhelper.make_args(
description=__DESCRIPTIONEM_BREVE__,
epilog=__EPILOGUM__
)
parser.add_argument(
'--fontem-linguam', '-FL',
help='(For bilingual operations) Source natural language ' +
'(use if not auto-detected). ' +
'Must be like {ISO 639-3}-{ISO 15924}. Example: lat-Latn. ' +
'Accept a single value.',
# dest='fontem_linguam',
metavar='fontem_linguam',
action='store',
default='lat-Latn',
nargs='?'
)
parser.add_argument(
'--objectivum-linguam', '-OL',
help='(For bilingual and monolingual operations) ' +
'Target natural language ' +
'(use if not auto-detected). ' +
'Must be like {ISO 639-3}-{ISO 15924}. Example: arb-Arab. ' +
'Requires: mono or bilingual operation. ' +
'Accept a single value.',
metavar='objectivum_linguam',
action='store',
default='arb-Arab',
nargs='?'
)
# --agendum-linguam is a draft. Not 100% implemented
parser.add_argument(
'--agendum-linguam', '-AL',
help='(Planned, but not fully implemented yet) ' +
'Restrict working languages to a list. Useful for ' +
'HXLTM to HXLTM or multilingual formats like TBX and TMX. ' +
'Requires: multilingual operation. ' +
'Accepts multiple values.',
metavar='agendum_linguam',
type=lambda x: x.split(',')
# action='append',
# nargs='?'
)
# --non-agendum-linguam is a draft. Not 100% implemented
parser.add_argument(
'--non-agendum-linguam', '-non-AL',
help='(Planned, but not implemented yet) ' +
'Inverse of --agendum-linguam. Document one or more ' +
'languages that should be ignored if they exist. ' +
'Requires: multilingual operation. ' +
'Accept multiple values.',
metavar='non_agendum_linguam',
# action='append',
type=lambda x: x.split(',')
# nargs='?'
)
# @see https://la.wikipedia.org/wiki/Lingua_auxiliaris_internationalis
# --agendum-linguam is a draft. Not 100% implemented
parser.add_argument(
'--auxilium-linguam', '-AUXL',
help='(Planned, but not implemented yet) '
'Define auxiliary language. '
'Requires: bilingual operation (and file format allow metadata). '
'Default: Esperanto and Interlingua ' +
'Accepts multiple values.',
metavar='auxilium_linguam',
# default='epo-Latn@eo',
# action='append',
type=lambda x: x.split(',')
# nargs='?'
)
parser.add_argument(
'--fontem-normam',
help='(For data exchange) Source of data convention ' +
'Recommended convention: use "{UN M49}_{P-Code}" ' +
'when endorsed by regional government, ' +
'and reverse domain name notation with "_" for other cases. ' +
'Examples: 076_BR (Brazil, adm0, Federal level); ' +
'076_BR33 (Brazil, adm1, Minas Gerais State, uses PCode); ' +
'076_BR3106200 (Brazil, adm2, Belo Horizonte city, uses PCode).',
# dest='fontem_linguam',
metavar='fontem_normam',
action='store',
# default='',
nargs='?'
)
parser.add_argument(
'--tmeta-archivum',
help='(Draft, not fully implemented) ' +
'Optional YAML metadata for advanced processing operations.',
# dest='fontem_linguam',
metavar='tmeta_archivum',
action='store',
# default='lat-Latn',
nargs='?'
)
parser.add_argument(
'--objectivum-normam',
help='(For data exchange) Target of data convention ' +
'Recommended convention: use "{UN M49}_{P-Code}" ' +
'when endorsed by regional government, ' +
'and reverse domain name notation with "_" for other cases. ' +
'Example: org_hxlstandard ',
metavar='objectivum_normam',
action='store',
# default=',
nargs='?'
)
parser.add_argument(
'--objectivum-formulam',
help='Template file to use as reference to generate an output. ' +
'Less powerful than custom file but can be used for ' +
'simple cases.',
# metavar='objectivum_formatum',
dest='objectivum_formulam',
action='store'
)
parser.add_argument(
'--objectivum-HXLTM', '--HXLTM',
help='Save output as HXLTM (default). Multilingual output format.',
# metavar='objectivum_formatum',
dest='objectivum_formatum',
action='append_const',
const='HXLTM'
)
parser.add_argument(
'--objectivum-TMX', '--TMX',
help='Export to Translation Memory eXchange (TMX) v1.4b. ' +
' Multilingual output format',
# metavar='objectivum_formatum',
dest='objectivum_formatum',
action='append_const',
const='TMX'
)
parser.add_argument(
'--objectivum-TBX-Basim', '--TBX-Basim',
help='(Working draft) ' +
'Export to Term Base eXchange (TBX) Basic ' +
' Multilingual output format',
# metavar='objectivum_formatum',
dest='objectivum_formatum',
action='append_const',
const='TBX-Basim'
)
parser.add_argument(
'--objectivum-UTX', '--UTX',
help='(Planned, but not implemented yet) ' +
'Export to Universal Terminology eXchange (UTX). ' +
' Multilingual output format',
# metavar='objectivum_formatum',
dest='objectivum_formatum',
action='append_const',
const='UTX'
)
parser.add_argument(
'--objectivum-XML',
help='Export to XML format. ' +
'Multilingual output format',
# metavar='objectivum_formatum',
dest='objectivum_formatum',
action='append_const',
const='XML'
)
parser.add_argument(
'--objectivum-XLIFF', '--XLIFF', '--XLIFF2',
help='Export to XLIFF (XML Localization Interchange File Format)' +
' v2.1. ' +
'(mono or bi-lingual support only as per XLIFF specification)',
dest='objectivum_formatum',
action='append_const',
const='XLIFF'
)
parser.add_argument(
'--objectivum-XLIFF-obsoletum', '--XLIFF-obsoletum', '--XLIFF1',
help='(Not implemented) ' +
'Export to XLIFF (XML Localization Interchange ' +
'File Format) v1.2, an obsolete format for lazy developers who ' +
'don\'t implemented XLIFF 2 (released in 2014) yet.',
dest='objectivum_formatum',
action='append_const',
const='XLIFF-obsoletum'
)
parser.add_argument(
'--objectivum-CSV-3', '--CSV-3',
help='(Not implemented yet) ' +
'Export to Bilingual CSV with BCP47 headers (source to target) ' +
'plus comments on last column '
'Bilingual operation. ',
dest='objectivum_formatum',
action='append_const',
const='CSV-3'
)
parser.add_argument(
'--objectivum-TSV-3', '--TSV-3',
help='(Not implemented yet) ' +
'Export to Bilingual TAB with BCP47 headers (source to target) ' +
'plus comments on last column '
'Bilingual operation. ',
dest='objectivum_formatum',
action='append_const',
const='TSV-3'
)
# parser.add_argument(
# '--objectivum-CSV-HXL-XLIFF', '--CSV-HXL-XLIFF',
# help='(experimental) ' +
# 'HXLated bilingual CSV (feature compatible with XLIFF)',
# dest='objectivum_formatum',
# action='append_const',
# const='CSV-HXL-XLIFF'
# )
parser.add_argument(
'--objectivum-JSON-kv', '--JSON-kv',
help='(Not implemented yet) ' +
'Export to Bilingual JSON. Keys are ID (if available) or source '
'natural language. Values are target language. '
'No comments are exported. Monolingual/Bilingual',
dest='objectivum_formatum',
action='append_const',
const='JSON-kv'
)
parser.add_argument(
'--objectivum-formatum-speciale',
help='(Not fully implemented yet) ' +
'In addition to use a output format (like --objectivum-TMX) '
'inform an special additional key that customize '
'the base format (like normam.TMX) '
'already existing on '
'ego.hxltm.yml/venditorem.hxltm.yml/cor.hxltm.yml. '
'Example: "hxltmcli fontem.hxl.csv objectivum.tmx '
'--objectivum-TMX --objectivum-formatum-speciale TMX-de-marcus"',
dest='objectivum_formatum_speciale',
metavar='objectivum_formatum_speciale',
action='store',
default=None,
nargs='?'
)
parser.add_argument(
'--limitem-quantitatem',
help='(Advanced, large data sets) '
'Customize the limit of the maximum number of raw rows can '
'be in a single step. Try increments of 1 million.'
'Use value -1 to disable limits (even if means exhaust '
'all computer memory require full restart). '
'Defaults to 1048576 (but to avoid non-expert humans or '
'automated work flows generate output with missing data '
'without no one reading the warning messages '
'if the --limitem-quantitatem was reached AND '
'no customization was done on --limitem-initiale-lineam '
'an exception will abort',
metavar='limitem_quantitatem',
type=int,
default=1048576,
nargs='?'
)
parser.add_argument(
'--limitem-initiale-lineam',
help='(Advanced, large data sets) ' +
'When working in batches and the initial row to process is not '
'the first one (starts from 0) use this option if is '
'inviable increase to simply --limitem-quantitatem',
metavar='limitem_initiale_lineam',
type=int,
default=-1,
nargs='?'
)
parser.add_argument(
'--non-securum-limitem', '--ad-astra-per-aspera',
help='(For situational/temporary usage, as '
'in "one weekend" NOT six months) '
'Disable any secure hardware limits and make the program '
'try harder tolerate (even if means '
'ignore entire individual rows or columns) but still work with '
'what was left from the dataset. '
'This option assume is acceptable not try protect from exhaust '
'all memory or disk space when working with large data sets '
'and (even for smaller, but not well know from the '
'python or YAML ontologia) the current human user evaluated that '
'the data loss is either false positive or tolerable '
'until permanent fix.',
metavar='ad_astra',
action='store_const',
const=True,
default=None
)
# sēlēctum
# @see https://stackoverflow.com/questions/15459997
# /passing-integer-lists-to-python/15460288
parser.add_argument(
'--selectum-columnam-numerum',
help='(Advanced) ' +
'Select only columns from source HXLTM dataset by a list of '
'index numbers (starts by zero). As example: '
'to select the first 3 columns '
'use "0,1,2" and NOT "1,2,3"',
metavar='columnam_numerum',
# type=lambda x: x.split(',')
type=lambda x: map(int, x.split(','))
)
# @see https://stackoverflow.com/questions/15459997
# /passing-integer-lists-to-python/15460288
parser.add_argument(
'--non-selectum-columnam-numerum',
help='(Advanced) ' +
'Exclude columns from source HXLTM dataset by a list of '
'index numbers (starts by zero). As example: '
'to ignore the first ("Excel A"), and fifth ("Excel: E") column:'
'use "0,4" and not "1,5"',
metavar='non_columnam_numerum',
# type=lambda x: x.split(',')
type=lambda x: map(int, x.split(','))
)
# Trivia: caput, https://en.wiktionary.org/wiki/caput#Latin
# --crudum-objectivum-caput is a draft. Not 100% implemented
parser.add_argument(
'--crudum-objectivum-caput',
help='(Advanced override for tabular output, like CSV). ' +
'Explicit define first line of output (separed by ,) ' +
'Example: "la,ar,Annotationem"',
metavar='fon_hxlattrs',
action='store',
default=None,
nargs='?'
)
# --crudum-fontem-linguam-hxlattrs is a draft. Not 100% implemented
parser.add_argument(
'--crudum-fontem-linguam-hxlattrs', '--fon-hxlattrs',
help='(Advanced override for --fontem-linguam). ' +
'Explicit HXL Attributes for source language. ' +
'Example: "+i_la+i_lat+is_latn"',
metavar='fon_hxlattrs',
action='store',
default=None,
nargs='?'
)
# --crudum-fontem-linguam-bcp47 is a draft. Not 100% implemented
parser.add_argument(
'--crudum-fontem-linguam-bcp47', '--fon-bcp47',
help='(Advanced override for --fontem-linguam). ' +
'Explicit IETF BCP 47 language tag for source language. ' +
'Example: "la"',
metavar='fon_bcp47',
action='store',
default=None,
nargs='?'
)
# --crudum-objectivum-linguam-hxlattrs is a draft. Not 100% implemented
parser.add_argument(
'--crudum-objectivum-linguam-hxlattrs', '--obj-hxlattrs',
help='(Advanced override for --objectivum-linguam). ' +
'Explicit HXL Attributes for target language. ' +
'Example: "+i_ar+i_arb+is_arab"',
metavar='obj_hxlattrs',
action='store',
default=None,
nargs='?'
)
# --crudum-objectivum-linguam-bcp47 is a draft. Not 100% implemented
parser.add_argument(
'--crudum-objectivum-linguam-bcp47', '--obj-bcp47',
help='(Advanced override for --objectivum-linguam). ' +
'Explicit IETF BCP 47 language tag for target language. ' +
'Example: "ar"',
metavar='obj_bcp47',
action='store',
default=None,
nargs='?'
)
# https://hdp.etica.ai/ontologia/cor.hxltm.yml
parser.add_argument(
'--archivum-configurationem',
help='Path to custom configuration file (The cor.hxltm.yml)',
action='store_const',
const=True,
default=None
)
# TODO: --archivum-configurationem-appendicem
parser.add_argument(
'--archivum-configurationem-appendicem',
help='(Not implemented yet)' +
'Path to custom configuration file (The cor.hxltm.yml)',
action='store_const',
const=True,
default=None
)
parser.add_argument(
'--silentium',
help='Silence warnings? Try to not generate any warning. ' +
'May generate invalid output',
action='store_const',
const=True,
default=False
)
parser.add_argument(
'--expertum-HXLTM-ASA',
help='(Expert mode) Save an Abstract Syntax Tree ' +
'in JSON format to a file path. ' +
'With --expertum-HXLTM-ASA-verbosum output entire dataset data. ' +
'File extensions with .yml/.yaml = YAML output. ' +
'Files extensions with .json/.json5 = JSONs output. ' +
'Default: JSON output. ' +
'Good for debugging.',
# dest='fontem_linguam',
metavar='hxltm_asa',
dest='hxltm_asa',
action='store',
default=None,
nargs='?'
)
# verbōsum, https://en.wiktionary.org/wiki/verbosus#Latin
parser.add_argument(
'--expertum-HXLTM-ASA-verbosum',
help='(Expert mode) Enable --expertum-HXLTM-ASA verbose mode',
# dest='fontem_linguam',
metavar='hxltm_asa_verbosum',
dest='hxltm_asa_verbosum',
action='store_const',
const=True,
default=False
)
# Trivia: experīmentum, https://en.wiktionary.org/wiki/experimentum
parser.add_argument(
# '--venandum-insectum-est, --debug',
'--experimentum-est',
help='(Internal testing only) Enable undocumented feature',
metavar="experimentum_est",
action='store_const',
const=True,
default=False
)
parser.add_argument(
# '--venandum-insectum-est, --debug',
'--venandum-insectum-est', '--debug',
help='Enable debug? Extra information for program debugging',
metavar="venandum_insectum",
dest="venandum_insectum",
action='store_const',
const=True,
default=False
)
# self.args = parser.parse_args()
est_args = parser.parse_args()
return est_args
def execute_cli(self, pyargs,
stdin=STDIN, stdout=sys.stdout, _stderr=sys.stderr):
"""
The execute_cli is the main entrypoint of HXLTMCLI. When
called will convert the HXL source to example format.
"""
# pylint: disable=too-many-branches,too-many-statements
self._initiale(pyargs)
# _[eng-Latn]
# If the user specified an output file, we will save on
# self.original_outfile. The pyargs.outfile will be used for temporary
# output
# [eng-Latn]_
if pyargs.outfile:
self.original_outfile = pyargs.outfile
self.original_outfile_is_stdout = False
if not self._argumentum.objectivum_formatum:
self._argumentum.est_objectivum_formatum(
self._objectivum_formatum_from_outfile(
self.original_outfile))
# print(self._argumentum.v())
try:
temp = tempfile.NamedTemporaryFile()
temp_csv4xliff = tempfile.NamedTemporaryFile()
pyargs.outfile = temp.name
with self.hxlhelper.make_source(pyargs, stdin) as source, \
self.hxlhelper.make_output(pyargs, stdout) as output:
# _[eng-Latn]
# Save the HXL TM locally. It will be used by either in_csv
# or in_csv + in_xliff
# [eng-Latn]_
hxl.io.write_hxl(output.output, source,
show_tags=not pyargs.strip_tags)
hxlated_input = pyargs.outfile
# _[eng-Latn]
# This step will do raw analysis of the hxlated_input on a
# temporary on the disk.
# [eng-Latn]_
self._initiale_hxltm_asa(hxlated_input)
if pyargs.hxltm_asa:
self.in_asa(pyargs.hxltm_asa)
if self.original_outfile_is_stdout is True and \
self.hxltm_asa.argumentum.objectivum_formatum is None and \
self.hxltm_asa.argumentum.objectivum_formulam is None:
self.hxltm_asa.argumentum.objectivum_formatum = 'HXLTM'
if self.hxltm_asa.argumentum.objectivum_formatum == 'HXLTM':
# TODO: make it work with elf.in_archivum_formatum
self.in_noop(hxlated_input, self.original_outfile,
self.original_outfile_is_stdout)
else:
if self.original_outfile_is_stdout:
objectivum_farchivum = False
else:
objectivum_farchivum = self.original_outfile
# print(self.hxltm_asa.argumentum)