1
+ import os
1
2
import subprocess
2
3
import tempfile
3
4
from typing import List
4
5
6
+ import lextools
5
7
import lttoolbox
6
8
7
9
import apertium # noqa: F401
@@ -27,32 +29,48 @@ def to_alpha3_code(code: str) -> str:
27
29
28
30
def execute_pipeline (inp : str , commands : List [List [str ]]) -> str :
29
31
"""
30
- Args:
31
- inp (str)
32
- commands (List[List[str]])
32
+ Executes the given list of commands and returns the final output
33
33
34
34
Returns:
35
35
str
36
36
"""
37
37
end = inp .encode ()
38
38
for command in commands :
39
+ # On Windows platform the file can't be opened once again
40
+ # The file is first opened in python for writing and then
41
+ # opened again with swig wrapper
42
+ # NamedTemporaryFile gets deleted (if delete=True) upon closing,
43
+ # so manually delete the file afterwards
44
+ input_file = tempfile .NamedTemporaryFile (delete = False )
45
+ output_file = tempfile .NamedTemporaryFile (delete = False )
46
+ arg = command [1 ][1 ] if len (command ) == 3 else ''
47
+ path = command [- 1 ]
48
+ used_wrapper = True
49
+ input_file_name , output_file_name = input_file .name , output_file .name
50
+ with open (input_file_name , 'w' ) as input_file :
51
+ text = end .decode ()
52
+ input_file .write (text )
39
53
if 'lt-proc' == command [0 ]:
40
- arg = command [1 ][1 ] if len (command ) == 3 else ''
41
- path = command [- 1 ]
42
- with tempfile .NamedTemporaryFile ('w' ) as input_file , tempfile .NamedTemporaryFile ('r' ) as output_file :
43
- text = end .decode ()
44
- input_file .write (text )
45
- input_file .flush ()
46
- lttoolbox .LtLocale .tryToSetLocale ()
47
- fst = lttoolbox .FST ()
48
- if not fst .valid ():
49
- raise ValueError ('FST Invalid' )
50
- fst .lt_proc (arg , path , input_file .name , output_file .name )
51
- end = output_file .read ().encode ()
54
+ lttoolbox .LtLocale .tryToSetLocale ()
55
+ fst = lttoolbox .FST ()
56
+ if not fst .valid ():
57
+ raise ValueError ('FST Invalid' )
58
+ fst = lttoolbox .FST ()
59
+ fst .lt_proc (arg , path , input_file_name , output_file_name )
60
+ elif 'lrx-proc' == command [0 ]:
61
+ lextools .LtLocale .tryToSetLocale ()
62
+ lrx = lextools .LRX ()
63
+ lrx .lrx_proc (arg , path , input_file .name , output_file .name )
52
64
else :
53
65
apertium .logger .warning ('Calling subprocess %s' , command [0 ])
54
66
proc = subprocess .Popen (command , stdin = subprocess .PIPE , stdout = subprocess .PIPE )
55
67
end , _ = proc .communicate (end )
68
+ used_wrapper = False
69
+ if used_wrapper :
70
+ with open (output_file_name ) as output_file :
71
+ end = output_file .read ().encode ()
72
+ os .remove (input_file_name )
73
+ os .remove (output_file_name )
56
74
return end .decode ()
57
75
58
76
0 commit comments