def video_crop(self, arguments: list = sys.argv[2:]): """Crop video in the same directory""" parser = argparse.ArgumentParser( prog='ti video_crop', description=f"{self.video_crop.__doc__}") parser.add_argument('-i', '--input', required=True, dest='input_file', type=TaichiMain._mp4_file, help="Path to input MP4 video file") parser.add_argument('--x1', required=True, dest='x_begin', type=float, help="X coordinate of the beginning crop point") parser.add_argument('--x2', required=True, dest='x_end', type=float, help="X coordinate of the ending crop point") parser.add_argument('--y1', required=True, dest='y_begin', type=float, help="Y coordinate of the beginning crop point") parser.add_argument('--y2', required=True, dest='y_end', type=float, help="Y coordinate of the ending crop point") args = parser.parse_args(arguments) args.output_file = str( Path(args.input_file).with_name( f"{Path(args.input_file).stem}-cropped{Path(args.input_file).suffix}" )) # Short circuit for testing if self.test_mode: return args video.crop_video(args.input_file, args.output_file, args.x_begin, args.x_end, args.y_begin, args.y_end) return None
def main(debug=False): argc = len(sys.argv) if argc == 1: mode = 'help' parser_args = sys.argv else: mode = sys.argv[1] parser_args = sys.argv[2:] parser = make_argument_parser() args = parser.parse_args(args=parser_args) lines = [] print() lines.append(u' *******************************************') lines.append(u' ** Taichi Programming Language **') lines.append(u' *******************************************') if 'TI_DEBUG' in os.environ: val = os.environ['TI_DEBUG'] if val not in ['0', '1']: raise ValueError( "Environment variable TI_DEBUG can only have value 0 or 1.") if debug: lines.append(u' *****************Debug Mode****************') os.environ['TI_DEBUG'] = '1' print(u'\n'.join(lines)) print() import taichi as ti if args.arch is not None: arch = args.arch if args.exclusive: arch = '^' + arch print(f'Running on Arch={arch}') os.environ['TI_WANTED_ARCHS'] = arch if mode == 'help': print( " Usage: ti run [task name] |-> Run a specific task\n" " ti test |-> Run all the tests\n" " ti benchmark |-> Run python tests in benchmark mode\n" " ti baseline |-> Archive current benchmark result as baseline\n" " ti regression |-> Display benchmark regression test result\n" " ti format |-> Reformat modified source files\n" " ti format_all |-> Reformat all source files\n" " ti build |-> Build C++ files\n" " ti video |-> Make a video using *.png files in the current folder\n" " ti video_scale |-> Scale video resolution \n" " ti video_crop |-> Crop video\n" " ti video_speed |-> Speed up video\n" " ti gif |-> Convert mp4 file to gif\n" " ti doc |-> Build documentation\n" " ti release |-> Make source code release\n" " ti debug [script.py] |-> Debug script\n" " ti example [name] |-> Run an example by name\n" ) return 0 t = time.time() if mode.endswith('.py'): import subprocess subprocess.call([sys.executable, mode] + sys.argv[1:]) elif mode == "run": if argc <= 1: print("Please specify [task name], e.g. test_math") return -1 print(sys.argv) name = sys.argv[1] task = ti.Task(name) task.run(*sys.argv[2:]) elif mode == "debug": ti.core.set_core_trigger_gdb_when_crash(True) if argc <= 2: print("Please specify [file name], e.g. render.py") return -1 name = sys.argv[2] with open(name) as script: script = script.read() exec(script, {'__name__': '__main__'}) elif mode == "test": if len(args.files): if args.cpp: return test_cpp(args) else: return test_python(args) elif args.cpp: return test_cpp(args) else: ret = test_python(args) if ret != 0: return ret return test_cpp(args) elif mode == "benchmark": import shutil commit_hash = ti.core.get_commit_hash() with os.popen('git rev-parse HEAD') as f: current_commit_hash = f.read().strip() assert commit_hash == current_commit_hash, f"Built commit {commit_hash:.6} differs from current commit {current_commit_hash:.6}, refuse to benchmark" os.environ['TI_PRINT_BENCHMARK_STAT'] = '1' output_dir = get_benchmark_output_dir() shutil.rmtree(output_dir, True) os.mkdir(output_dir) os.environ['TI_BENCHMARK_OUTPUT_DIR'] = output_dir if os.environ.get('TI_WANTED_ARCHS') is None and not args.tprt: # since we only do number-of-statements benchmark for SPRT os.environ['TI_WANTED_ARCHS'] = 'x64' if args.tprt: os.system('python benchmarks/run.py') # TODO: benchmark_python(args) else: test_python(args) elif mode == "baseline": import shutil baseline_dir = get_benchmark_baseline_dir() output_dir = get_benchmark_output_dir() shutil.rmtree(baseline_dir, True) shutil.copytree(output_dir, baseline_dir) print('[benchmark] baseline data saved') elif mode == "regression": baseline_dir = get_benchmark_baseline_dir() output_dir = get_benchmark_output_dir() display_benchmark_regression(baseline_dir, output_dir, args) elif mode == "build": ti.core.build() elif mode == "format": diff = None if len(sys.argv) >= 3: diff = sys.argv[2] ti.core.format(diff=diff) elif mode == "format_all": ti.core.format(all=True) elif mode == "statement": exec(sys.argv[2]) elif mode == "update": ti.core.update(True) ti.core.build() elif mode == "asm": fn = sys.argv[2] os.system( r"sed '/^\s*\.\(L[A-Z]\|[a-z]\)/ d' {0} > clean_{0}".format(fn)) elif mode == "interpolate": interpolate_frames('.') elif mode == "doc": os.system('cd {}/docs && sphinx-build -b html . build'.format( ti.get_repo_directory())) elif mode == "video": files = sorted(os.listdir('.')) files = list(filter(lambda x: x.endswith('.png'), files)) if len(sys.argv) >= 3: frame_rate = int(sys.argv[2]) else: frame_rate = 24 if len(sys.argv) >= 4: trunc = int(sys.argv[3]) files = files[:trunc] ti.info('Making video using {} png files...', len(files)) ti.info("frame_rate={}", frame_rate) output_fn = 'video.mp4' make_video(files, output_path=output_fn, frame_rate=frame_rate) ti.info('Done! Output video file = {}', output_fn) elif mode == "video_scale": input_fn = sys.argv[2] assert input_fn[-4:] == '.mp4' output_fn = input_fn[:-4] + '-scaled.mp4' ratiow = float(sys.argv[3]) if len(sys.argv) >= 5: ratioh = float(sys.argv[4]) else: ratioh = ratiow scale_video(input_fn, output_fn, ratiow, ratioh) elif mode == "video_crop": if len(sys.argv) != 7: print('Usage: ti video_crop fn x_begin x_end y_begin y_end') return -1 input_fn = sys.argv[2] assert input_fn[-4:] == '.mp4' output_fn = input_fn[:-4] + '-cropped.mp4' x_begin = float(sys.argv[3]) x_end = float(sys.argv[4]) y_begin = float(sys.argv[5]) y_end = float(sys.argv[6]) crop_video(input_fn, output_fn, x_begin, x_end, y_begin, y_end) elif mode == "video_speed": if len(sys.argv) != 4: print('Usage: ti video_speed fn speed_up_factor') return -1 input_fn = sys.argv[2] assert input_fn[-4:] == '.mp4' output_fn = input_fn[:-4] + '-sped.mp4' speed = float(sys.argv[3]) accelerate_video(input_fn, output_fn, speed) elif mode == "gif": input_fn = sys.argv[2] assert input_fn[-4:] == '.mp4' output_fn = input_fn[:-4] + '.gif' ti.info('Converting {} to {}'.format(input_fn, output_fn)) framerate = 24 mp4_to_gif(input_fn, output_fn, framerate) elif mode == "convert": import shutil # http://www.commandlinefu.com/commands/view/3584/remove-color-codes-special-characters-with-sed # TODO: Windows support for fn in sys.argv[2:]: print("Converting logging file: {}".format(fn)) tmp_fn = '/tmp/{}.{:05d}.backup'.format(fn, random.randint(0, 10000)) shutil.move(fn, tmp_fn) command = r'sed -r "s/\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]//g"' os.system('{} {} > {}'.format(command, tmp_fn, fn)) elif mode == "release": from git import Git import zipfile import hashlib g = Git(ti.get_repo_directory()) g.init() with zipfile.ZipFile('release.zip', 'w') as zip: files = g.ls_files().split('\n') os.chdir(ti.get_repo_directory()) for f in files: if not os.path.isdir(f): zip.write(f) ver = ti.__version__ md5 = hashlib.md5() with open('release.zip', "rb") as f: for chunk in iter(lambda: f.read(4096), b""): md5.update(chunk) md5 = md5.hexdigest() commit = ti.core.get_commit_hash()[:8] fn = f'taichi-src-v{ver[0]}-{ver[1]}-{ver[2]}-{commit}-{md5}.zip' import shutil shutil.move('release.zip', fn) elif mode == "example": if len(sys.argv) != 3: sys.exit( f"Invalid arguments! Usage: ti example [name]\nAvailable example names are: {sorted(get_available_examples())}" ) example = sys.argv[2] run_example(name=example) else: name = sys.argv[1] print('Running task [{}]...'.format(name)) task = ti.Task(name) task.run(*sys.argv[2:]) print() print(">>> Running time: {:.2f}s".format(time.time() - t)) return 0
def main(debug=False): lines = [] print() lines.append(u' *******************************************') lines.append(u' ** Taichi Programming Language **') lines.append(u' *******************************************') if debug: lines.append(u' *****************Debug Mode****************') os.environ['TI_DEBUG'] = '1' print(u'\n'.join(lines)) print() import taichi as ti ti.tc_core.set_core_debug(debug) argc = len(sys.argv) if argc == 1 or sys.argv[1] == 'help': print( " Usage: ti run [task name] |-> Run a specific task\n" " ti benchmark |-> Run performance benchmark\n" " ti test |-> Run all tests\n" " ti test_verbose |-> Run all tests with verbose outputs\n" " ti test_python |-> Run python tests\n" " ti test_cpp |-> Run cpp tests\n" " ti format |-> Reformat modified source files\n" " ti format_all |-> Reformat all source files\n" " ti build |-> Build C++ files\n" " ti video |-> Make a video using *.png files in the current folder\n" " ti video_scale |-> Scale video resolution \n" " ti video_crop |-> Crop video\n" " ti video_speed |-> Speed up video\n" " ti gif |-> Convert mp4 file to gif\n" " ti doc |-> Build documentation\n" " ti release |-> Make source code release\n" " ti debug [script.py] |-> Debug script\n") exit(0) mode = sys.argv[1] t = time.time() if mode.endswith('.py'): import subprocess subprocess.call([sys.executable] + sys.argv[1:]) elif mode == "run": if argc <= 2: print("Please specify [task name], e.g. test_math") exit(-1) name = sys.argv[2] task = ti.Task(name) task.run(*sys.argv[3:]) elif mode == "debug": ti.core.set_core_trigger_gdb_when_crash(True) if argc <= 2: print("Please specify [file name], e.g. render.py") exit(-1) name = sys.argv[2] with open(name) as script: script = script.read() exec(script, {'__name__': '__main__'}) elif mode == "test_python": return test_python() elif mode == "test_cpp": return test_cpp() elif mode == "test": if test_python() != 0: return -1 return test_cpp() elif mode == "test_verbose": if test_python(True) != 0: return -1 return test_cpp() elif mode == "build": ti.core.build() elif mode == "format": ti.core.format() elif mode == "format_all": ti.core.format(all=True) elif mode == "statement": exec(sys.argv[2]) elif mode == "update": ti.core.update(True) ti.core.build() elif mode == "asm": fn = sys.argv[2] os.system(r"sed '/^\s*\.\(L[A-Z]\|[a-z]\)/ d' {0} > clean_{0}".format(fn)) elif mode == "interpolate": interpolate_frames('.') elif mode == "amal": cwd = os.getcwd() os.chdir(ti.get_repo_directory()) with open('misc/amalgamate.py') as script: script = script.read() exec(script, {'__name__': '__main__'}) os.chdir(cwd) shutil.copy( os.path.join(ti.get_repo_directory(), 'build/taichi.h'), './taichi.h') elif mode == "doc": os.system('cd {}/docs && sphinx-build -b html . build'.format(ti.get_repo_directory())) elif mode == "video": files = sorted(os.listdir('.')) files = list(filter(lambda x: x.endswith('.png'), files)) if len(sys.argv) >= 3: frame_rate = int(sys.argv[2]) else: frame_rate = 24 if len(sys.argv) >= 4: trunc = int(sys.argv[3]) files = files[:trunc] ti.info('Making video using {} png files...', len(files)) ti.info("frame_rate={}", frame_rate) output_fn = 'video.mp4' make_video(files, output_path=output_fn, frame_rate=frame_rate) ti.info('Done! Output video file = {}', output_fn) elif mode == "video_scale": input_fn = sys.argv[2] assert input_fn[-4:] == '.mp4' output_fn = input_fn[:-4] + '-scaled.mp4' ratiow = float(sys.argv[3]) if len(sys.argv) >= 5: ratioh = float(sys.argv[4]) else: ratioh = ratiow scale_video(input_fn, output_fn, ratiow, ratioh) elif mode == "video_crop": if len(sys.argv) != 7: print('Usage: ti video_crop fn x_begin x_end y_begin y_end') exit(-1) input_fn = sys.argv[2] assert input_fn[-4:] == '.mp4' output_fn = input_fn[:-4] + '-cropped.mp4' x_begin = float(sys.argv[3]) x_end = float(sys.argv[4]) y_begin = float(sys.argv[5]) y_end = float(sys.argv[6]) crop_video(input_fn, output_fn, x_begin, x_end, y_begin, y_end) elif mode == "video_speed": if len(sys.argv) != 4: print('Usage: ti video_speed fn speed_up_factor') exit(-1) input_fn = sys.argv[2] assert input_fn[-4:] == '.mp4' output_fn = input_fn[:-4] + '-sped.mp4' speed = float(sys.argv[3]) accelerate_video(input_fn, output_fn, speed) elif mode == "gif": input_fn = sys.argv[2] assert input_fn[-4:] == '.mp4' output_fn = input_fn[:-4] + '.gif' ti.info('Converting {} to {}'.format(input_fn, output_fn)) framerate = 24 mp4_to_gif(input_fn, output_fn, framerate) elif mode == "convert": # http://www.commandlinefu.com/commands/view/3584/remove-color-codes-special-characters-with-sed # TODO: Windows support for fn in sys.argv[2:]: print("Converting logging file: {}".format(fn)) tmp_fn = '/tmp/{}.{:05d}.backup'.format(fn, random.randint(0, 10000)) shutil.move(fn, tmp_fn) command = r'sed -r "s/\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]//g"' os.system('{} {} > {}'.format(command, tmp_fn, fn)) elif mode == "release": from git import Git import zipfile import hashlib g = Git(ti.get_repo_directory()) g.init() with zipfile.ZipFile('release.zip', 'w') as zip: files = g.ls_files().split('\n') os.chdir(ti.get_repo_directory()) for f in files: if not os.path.isdir(f): zip.write(f) ver = ti.__version__ md5 = hashlib.md5() with open('release.zip', "rb") as f: for chunk in iter(lambda: f.read(4096), b""): md5.update(chunk) md5 = md5.hexdigest() commit = ti.core.get_commit_hash()[:8] fn = f'taichi-src-v{ver[0]}-{ver[1]}-{ver[2]}-{commit}-{md5}.zip' import shutil shutil.move('release.zip', fn) else: name = sys.argv[1] print('Running task [{}]...'.format(name)) task = ti.Task(name) task.run(*sys.argv[2:]) print() print(">>> Running time: {:.2f}s".format(time.time() - t))
def main(debug=False): lines = [] print() lines.append(u' *******************************************') lines.append(u' ** Taichi **') lines.append(u' ** **') lines.append(u' ** High-Performance Programming Language **') lines.append(u' *******************************************') if debug: lines.append(u' *****************Debug Mode****************') lines.append(u' *******************************************') os.environ['TI_DEBUG'] = '1' print(u'\n'.join(lines)) print() import taichi as ti ti.tc_core.set_core_debug(debug) argc = len(sys.argv) if argc == 1 or sys.argv[1] == 'help': print( " Usage: ti run [task name] |-> Run a specific task\n" " ti test |-> Run all tests\n" " ti test_python |-> Run python tests\n" " ti test_cpp |-> Run cpp tests\n" " ti build |-> Build C++ files\n" " ti video |-> Make a video using *.png files in the current folder\n" " ti video_scale |-> Scale video resolution \n" " ti video_crop |-> Crop video\n" " ti video_speed |-> Speed up video\n" " ti gif |-> Convert mp4 file to gif\n" " ti doc |-> Build documentation\n" " ti debug [script.py] |-> Debug script\n") exit(-1) mode = sys.argv[1] t = time.time() if mode.endswith('.py'): import subprocess subprocess.call([sys.executable] + sys.argv[1:]) elif mode == "run": if argc <= 2: print("Please specify [task name], e.g. test_math") exit(-1) name = sys.argv[2] task = ti.Task(name) task.run(*sys.argv[3:]) elif mode == "debug": ti.core.set_core_trigger_gdb_when_crash(True) if argc <= 2: print("Please specify [file name], e.g. render.py") exit(-1) name = sys.argv[2] with open(name) as script: script = script.read() exec(script, {'__name__': '__main__'}) elif mode == "test_python": return test_python() elif mode == "test_cpp": return test_cpp() elif mode == "test": if test_python() != 0: return -1 return test_cpp() elif mode == "build": ti.core.build() elif mode == "format": ti.core.format() elif mode == "statement": exec(sys.argv[2]) elif mode == "update": ti.core.update(True) ti.core.build() elif mode == "asm": fn = sys.argv[2] os.system( r"sed '/^\s*\.\(L[A-Z]\|[a-z]\)/ d' {0} > clean_{0}".format(fn)) elif mode == "interpolate": interpolate_frames('.') elif mode == "amal": cwd = os.getcwd() os.chdir(ti.get_repo_directory()) with open('misc/amalgamate.py') as script: script = script.read() exec(script, {'__name__': '__main__'}) os.chdir(cwd) shutil.copy(os.path.join(ti.get_repo_directory(), 'build/taichi.h'), './taichi.h') elif mode == "doc": os.system('cd docs && sphinx-build -b html . build') elif mode == "video": files = sorted(os.listdir('.')) files = list(filter(lambda x: x.endswith('.png'), files)) if len(sys.argv) >= 3: frame_rate = int(sys.argv[2]) else: frame_rate = 24 if len(sys.argv) >= 4: trunc = int(sys.argv[3]) files = files[:trunc] ti.info('Making video using {} png files...', len(files)) ti.info("frame_rate={}", frame_rate) output_fn = 'video.mp4' make_video(files, output_path=output_fn, frame_rate=frame_rate) ti.info('Done! Output video file = {}', output_fn) elif mode == "video_scale": input_fn = sys.argv[2] assert input_fn[-4:] == '.mp4' output_fn = input_fn[:-4] + '-scaled.mp4' ratiow = float(sys.argv[3]) if len(sys.argv) >= 5: ratioh = float(sys.argv[4]) else: ratioh = ratiow scale_video(input_fn, output_fn, ratiow, ratioh) elif mode == "video_crop": if len(sys.argv) != 7: print('Usage: ti video_crop fn x_begin x_end y_begin y_end') exit(-1) input_fn = sys.argv[2] assert input_fn[-4:] == '.mp4' output_fn = input_fn[:-4] + '-cropped.mp4' x_begin = float(sys.argv[3]) x_end = float(sys.argv[4]) y_begin = float(sys.argv[5]) y_end = float(sys.argv[6]) crop_video(input_fn, output_fn, x_begin, x_end, y_begin, y_end) elif mode == "video_speed": if len(sys.argv) != 4: print('Usage: ti video_speed fn speed_up_factor') exit(-1) input_fn = sys.argv[2] assert input_fn[-4:] == '.mp4' output_fn = input_fn[:-4] + '-sped.mp4' speed = float(sys.argv[3]) accelerate_video(input_fn, output_fn, speed) elif mode == "gif": input_fn = sys.argv[2] assert input_fn[-4:] == '.mp4' output_fn = input_fn[:-4] + '.gif' ti.info('Converting {} to {}'.format(input_fn, output_fn)) framerate = 24 mp4_to_gif(input_fn, output_fn, framerate) elif mode == "convert": # http://www.commandlinefu.com/commands/view/3584/remove-color-codes-special-characters-with-sed # TODO: Windows support for fn in sys.argv[2:]: print("Converting logging file: {}".format(fn)) tmp_fn = '/tmp/{}.{:05d}.backup'.format(fn, random.randint(0, 10000)) shutil.move(fn, tmp_fn) command = r'sed -r "s/\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]//g"' os.system('{} {} > {}'.format(command, tmp_fn, fn)) elif mode == "merge": import cv2 # TODO: remove this dependency import numpy as np folders = sys.argv[2:] os.makedirs('merged', exist_ok=True) for fn in sorted(os.listdir(folders[0])): imgs = [] for fld in folders: img = cv2.imread(os.path.join(fld, fn)) imgs.append(img) img = np.hstack(imgs) cv2.imwrite(os.path.join('merged', fn), img) else: name = sys.argv[1] print('Running task [{}]...'.format(name)) task = ti.Task(name) task.run(*sys.argv[2:]) print() print(">>> Running time: {:.2f}s".format(time.time() - t))