/
installer.py
173 lines (136 loc) · 6.58 KB
/
installer.py
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
from distutils.dir_util import copy_tree
import logging
import os
import platform
import shutil
import subprocess
import tempfile
from typing import List, Optional
from urllib.request import urlretrieve
from zipfile import ZipFile
class Windows:
"""Download ApertiumWin64 and Move to %localappdata%"""
base_link = 'http://apertium.projectjj.com/{}'
def __init__(self) -> None:
self._install_path = os.getenv('LOCALAPPDATA')
self._apertium_path = os.path.join(self._install_path, 'apertium-all-dev')
self._download_path = tempfile.mkdtemp()
logging.basicConfig(format='%(asctime)s %(message)s', level=logging.DEBUG)
self._logger = logging.getLogger()
self._logger.setLevel(logging.DEBUG)
def _download_zip(self, download_files: dict, extract_path: Optional[str]) -> None:
for zip_name, zip_link in download_files.items():
zip_download_path = os.path.join(self._download_path, zip_name)
urlretrieve(Windows.base_link.format(zip_link), filename=zip_download_path)
self._logger.info('%s download completed', zip_name)
# Extract the zip
with ZipFile(zip_download_path) as zip_file:
zip_file.extractall(path=extract_path)
self._logger.info('%s Extraction completed', zip_name)
os.remove(zip_download_path)
self._logger.info('%s removed', zip_name)
def _download_apertium_windows(self) -> None:
"""Installs Apertium-all-dev to %localappdata%"""
apertium_windows = {
'apertium-all-dev.zip': '/win64/nightly/apertium-all-dev.zip',
}
self._download_zip(apertium_windows, self._install_path)
def _download_packages(self, packages: List[str]) -> None:
"""Installs Packages to %localappdata%/Apertium"""
zip_path = 'win32/nightly/data.php?zip='
package_zip = {}
for curr_package in packages:
package_zip[curr_package] = zip_path + curr_package
self._download_zip(package_zip, self._download_path)
# move the extracted files to desired location
lang_data_path = os.path.join(self._download_path, 'usr', 'share', 'apertium')
self._logger.info('Copying Language Data to Apertium')
for directory in os.listdir(lang_data_path):
source = os.path.join(lang_data_path, directory)
destination = os.path.join(self._apertium_path, 'share', 'apertium', directory)
copy_tree(source, destination)
self._logger.info('%s -> %s', source, destination)
shutil.rmtree(os.path.join(self._download_path, 'usr'))
def _edit_modes(self) -> None:
r"""The mode files need to be modified before being used on Windows System
1. Replace /usr/share with %localappdata%\apertium-all-dev\share
2. Replace "/" with "\" to make path compatible with Windows System
"""
# List of Mode Files
mode_path = os.path.join(self._apertium_path, 'share', 'apertium', 'modes')
for f in os.listdir(mode_path):
if os.path.isfile(os.path.join(mode_path, f)) and f.endswith('.mode'):
self._logger.info('Editing mode %s ', f)
with open(os.path.join(mode_path, f)) as infile:
line = infile.read()
contents = line.split(' ')
# Editing mode file to be compatible with windows platform
for i, t in enumerate(contents):
if len(t) > 2 and t[0] == "'" and t[1] == '/':
t = t.replace('/', os.sep)
t = t.replace(r'\usr', self._apertium_path)
contents[i] = t
line = ' '.join(contents)
with open(os.path.join(mode_path, f), 'w') as outfile:
outfile.write(line)
outfile.close()
def install_apertium_base(self) -> None:
self._download_apertium_windows()
def install_apertium_language(self, language: List[str]) -> None:
self._download_packages(language)
self._edit_modes()
def install_wrapper(self, swig_wrappers: List[str]) -> None:
pass
class Ubuntu:
def __init__(self) -> None:
pass
@staticmethod
def _install_package_source() -> None:
install_script_url = 'http://apertium.projectjj.com/apt/install-nightly.sh'
with tempfile.NamedTemporaryFile('w') as install_script:
urlretrieve(install_script_url, install_script.name)
execute = subprocess.run(['sudo', 'bash', install_script.name])
execute.check_returncode()
@staticmethod
def _download_packages(packages: List[str]) -> None:
command = ['sudo', 'apt-get', 'install'] + packages
execute = subprocess.run(command)
execute.check_returncode()
@staticmethod
def _rename_wrappers():
dist_package = '/usr/lib/python3/dist-packages'
for f in os.listdir(dist_package):
if f.startswith('_lttoolbox'):
old_name = os.path.join(dist_package, f)
new_name = os.path.join(dist_package, '{}.so'.format(f.split('.')[0]))
subprocess.run(['sudo', 'mv', old_name, new_name])
def install_apertium_language(self, languages: List[str]) -> None:
self._download_packages(languages)
def install_apertium_base(self) -> None:
self._install_package_source()
self._download_packages(['apertium-all-dev'])
def install_wrapper(self, swig_wrappers: List[str]) -> None:
self._download_packages(swig_wrappers)
self._rename_wrappers()
def get_installer_object():
if platform.system() == 'Windows':
apertium_installer = Windows()
elif platform.system() == 'Linux':
with open('/etc/os-release') as os_release:
distro_name = os_release.readline().split('=')[-1].strip().replace('"', '')
if distro_name == 'Ubuntu':
apertium_installer = Ubuntu()
else:
raise ValueError('Installation on {} not supported'.format(distro_name))
return apertium_installer
def install_apertium() -> None:
apertium_installer = get_installer_object()
apertium_installer.install_apertium_base()
def install_language_pack(languages: List[str] = None) -> None:
if languages is None:
languages = ['apertium-eng', 'apertium-en-es']
apertium_installer = get_installer_object()
apertium_installer.install_apertium_language(languages)
def install_wrapper(swig_wrappers: List[str]) -> None:
apertium_installer = get_installer_object()
apertium_installer.install_wrapper(swig_wrappers)