forked from nndeploy/nndeploy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild_linux.py
More file actions
349 lines (287 loc) · 10.4 KB
/
build_linux.py
File metadata and controls
349 lines (287 loc) · 10.4 KB
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Linux Build Script for nndeploy
This script automates the build process for nndeploy on Linux platform
Based on GitHub Actions workflow configuration
"""
import os
import sys
import shutil
import subprocess
import platform
from pathlib import Path
import argparse
import multiprocessing
def run_command(cmd, check=True, shell=True):
"""Execute command and handle errors"""
print(f"Executing: {cmd}")
try:
result = subprocess.run(cmd, shell=shell, check=check, capture_output=True, text=True)
if result.stdout:
print(result.stdout)
return result
except subprocess.CalledProcessError as e:
print(f"Error executing command: {cmd}")
print(f"Return code: {e.returncode}")
if e.stderr:
print(f"Error output: {e.stderr}")
if check:
sys.exit(1)
return e
def check_system():
"""Check system information"""
system_info = {
'platform': platform.platform(),
'machine': platform.machine(),
'python_version': platform.python_version(),
'system': platform.system()
}
print("System Information:")
for key, value in system_info.items():
print(f" {key}: {value}")
if system_info['system'] != 'Linux':
print("Warning: This script is designed for Linux systems")
return system_info
def parse_arguments():
"""Parse command line arguments"""
parser = argparse.ArgumentParser(description='Build nndeploy on Linux')
parser.add_argument('--config',
default='config_opencv_ort_mnn_tokenizer.cmake',
type=str,
help='Config file name (config_opencv_ort_mnn_tokenizer.cmake, config_opencv_ort_mnn.cmake, config_opencv_ort.cmake, config_opencv.cmake)')
parser.add_argument('--build-type',
default='Release',
choices=['Debug', 'Release', 'RelWithDebInfo', 'MinSizeRel'],
help='CMake build type')
parser.add_argument('--jobs',
type=int,
default=multiprocessing.cpu_count(),
help='Number of parallel jobs for compilation')
parser.add_argument('--clean',
action='store_true',
help='Clean build directory before building')
parser.add_argument('--skip-deps',
action='store_true',
help='Skip dependency installation')
parser.add_argument('--skip-third-party',
action='store_true',
help='Skip third-party library installation')
return parser.parse_args()
def install_system_dependencies():
"""Install system dependencies using apt-get"""
print("Installing system dependencies...")
# Update package manager index
print("Updating package manager index...")
run_command("sudo apt-get update")
# Install build tools and dependencies
dependencies = [
"build-essential",
"cmake",
"make-build",
"pkg-config",
"libopencv-dev",
"protobuf-compiler",
"libprotobuf-dev",
"git",
"wget",
"curl",
"unzip",
"python3-dev",
"python3-pip"
]
print("Installing build tools and dependencies...")
for dep in dependencies:
print(f"Installing {dep}...")
result = run_command(f"sudo apt-get install -y {dep}", check=False)
if result.returncode != 0:
print(f"Warning: {dep} installation failed")
print("System dependencies installation completed!")
def install_python_dependencies():
"""Install Python dependencies"""
print("Installing Python dependencies...")
# Upgrade pip
print("Upgrading pip...")
run_command("python3 -m pip install --upgrade pip")
# Install Python dependencies
python_deps = [
"pybind11",
"setuptools",
"wheel",
"twine",
"requests",
"pathlib2",
"cython",
"numpy"
]
for dep in python_deps:
print(f"Installing {dep}...")
result = run_command(f"pip3 install {dep}", check=False)
if result.returncode != 0:
print(f"Warning: {dep} installation failed")
print("Python dependencies installation completed!")
def install_rust():
"""Install Rust programming language"""
print("Checking Rust installation status...")
# Check if Rust is already installed
try:
result = run_command("rustc --version", check=False)
if result.returncode == 0:
print(f"Rust is already installed: {result.stdout.strip()}")
return True
except:
pass
print("Rust not installed, installing...")
# Install Rust using rustup
print("Downloading and installing Rust...")
run_command("curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y")
# Source cargo environment
cargo_env = os.path.expanduser("~/.cargo/env")
if os.path.exists(cargo_env):
print("Sourcing cargo environment...")
run_command(f"source {cargo_env}")
print("Rust installation completed!")
return True
def install_third_party_libraries():
"""Install third-party libraries"""
print("Installing third-party libraries...")
# Switch to tool script directory
script_dir = Path("tool") / "script"
if not script_dir.exists():
print(f"Error: Script directory {script_dir} does not exist")
return False
original_dir = os.getcwd()
os.chdir(script_dir)
try:
# Install OpenCV
print("Installing OpenCV...")
result = run_command("python3 install_opencv.py", check=False)
if result.returncode != 0:
print("Warning: OpenCV installation failed")
# Install ONNX Runtime
print("Installing ONNX Runtime...")
result = run_command("python3 install_onnxruntime.py", check=False)
if result.returncode != 0:
print("Warning: ONNX Runtime installation failed")
# Build MNN
print("Building MNN...")
result = run_command("python3 build_mnn.py", check=False)
if result.returncode != 0:
print("Warning: MNN build failed")
finally:
# Restore original directory
os.chdir(original_dir)
print("Third-party libraries installation completed!")
return True
def configure_and_build(config_file, build_type, jobs):
"""Configure CMake and build project"""
print("Configuring and building project...")
# Create build directory
build_dir = Path("build")
if build_dir.exists() and args.clean:
print(f"Cleaning build directory: {build_dir}")
shutil.rmtree(build_dir)
build_dir.mkdir(exist_ok=True)
print(f"Using build directory: {build_dir}")
# Copy configuration file
config_source = Path("cmake") / config_file
config_dest = build_dir / "config.cmake"
if config_source.exists():
shutil.copy2(config_source, config_dest)
print(f"Copied configuration file: {config_source} -> {config_dest}")
else:
print(f"Warning: Configuration file {config_source} does not exist")
# Switch to build directory
original_dir = os.getcwd()
os.chdir(build_dir)
try:
# Configure CMake
print("Configuring CMake...")
cmake_cmd = f"cmake -DCMAKE_BUILD_TYPE={build_type} .."
run_command(cmake_cmd)
# Build project
print(f"Building project with {jobs} parallel jobs...")
make_cmd = f"make -j{jobs}"
run_command(make_cmd)
# Install
print("Installing...")
run_command("make install")
# Package
print("Packaging...")
run_command("cpack")
# List generated files
print("Generated files:")
run_command("ls -la")
print("Compilation, installation and packaging completed")
finally:
# Restore original directory
os.chdir(original_dir)
return True
def install_python_package():
"""Install Python package in developer mode and verify"""
print("Installing Python package in developer mode...")
# Switch to python directory
python_dir = Path("python")
if not python_dir.exists():
print(f"Error: Python directory {python_dir} does not exist")
return False
original_dir = os.getcwd()
os.chdir(python_dir)
try:
# Install in developer mode
print("Installing Python package in developer mode...")
run_command("pip3 install -e .")
finally:
os.chdir(original_dir)
# Verify installation
print("Verifying Python package installation...")
verification_script = """
import platform
try:
import nndeploy
print(f'✓ Successfully imported nndeploy {nndeploy.__version__}')
print(f'Platform: {platform.platform()}')
print(f'Architecture: {platform.machine()}')
print(f'Python version: {platform.python_version()}')
except ImportError as e:
print(f'✗ Import failed: {e}')
exit(1)
"""
result = run_command(f'python3 -c "{verification_script}"', check=False)
if result.returncode == 0:
print("Python package developer mode installation and verification completed")
return True
else:
print("Python package verification failed")
return False
def main():
"""Main build function"""
print("=" * 60)
print("nndeploy Linux Build Script")
print("=" * 60)
# Parse arguments
global args
args = parse_arguments()
# Check system
system_info = check_system()
# Install dependencies
if not args.skip_deps:
# install_system_dependencies()
install_python_dependencies()
install_rust()
else:
print("Skipping dependency installation")
# Install third-party libraries
if not args.skip_third_party:
install_third_party_libraries()
else:
print("Skipping third-party library installation")
# Configure and build
configure_and_build(args.config, args.build_type, args.jobs)
# Install Python package
install_python_package()
print("=" * 60)
print("Build completed successfully!")
print("=" * 60)
if __name__ == "__main__":
main()