├── .envrc ├── .gitignore ├── Dockerfile ├── LICENSE ├── README.md ├── filter-timelapse-frames.py ├── grab-timelapse-frame.py ├── process-file-once-redis.py ├── process-file-once.py ├── process_file_once ├── .gitignore ├── Cargo.lock ├── Cargo.toml └── src │ └── main.rs ├── requirements.txt └── stack_images.py /.envrc: -------------------------------------------------------------------------------- 1 | layout python3 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .direnv/ 2 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:3 2 | 3 | WORKDIR /sandbox 4 | COPY requirements.txt ./ 5 | RUN pip install --no-cache-dir -r requirements.txt 6 | RUN apt update 7 | RUN apt-get install -y ffmpeg 8 | 9 | RUN apt-get clean autoclean 10 | RUN apt-get autoremove --yes 11 | RUN rm -rf /var/lib/{apt,dpkg,cache,log}/ 12 | RUN rm -rf /var/lib/apt/lists/* 13 | 14 | ENV TZ=America/Los_Angeles 15 | COPY . . 16 | 17 | CMD [ "sh", "-c", "python grab-timelapse-frame.py --output-directory /output --output-filenames $PREFIX --interval $INTERVAL --url $URL" ] 18 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Overview 2 | 3 | These scripts are basically (slightly) cleaned up versions of personal 4 | scripts I used to turn an RTSP stream into a timelapse video. I 5 | capture video to a NAS via UniFi cameras with 6 | `grab-timelapse-frame.py` via cron and periodically use `ffmpeg` with 7 | the files provided by `filter-timelapse-frames.py` to produce an 8 | actual video. 9 | 10 | ## Interesting, Motivating Details 11 | 12 | My project was backyard construction. This means I am only interested 13 | in weekday work when there is daylight, hence defaults that are tuned 14 | to that (e.g. using `astral` to determine when sunrise and sunset are 15 | to avoid capturing frames, and skipping weekends). 16 | 17 | I want to capture roughly one image every 10 seconds so I can have a 18 | smooth video per day but also can then sample over longer periods. 19 | Hence: 20 | 21 | - `grab-timelapse-frame.py` passes filename and directory names to `strftime` so as to avoid too many files in a single directory. 22 | - `grab-timelapse-frame.py` is made robust by intentionally being short lived and run from cron; no complexities from `systemd` though you do lose some monitoring/management. Oh well, it works for me and seems worth it. 23 | - `filter-timelapse-frames.py` supports a `--sample` parameter to only print every Nth matching file for when you want to produce faster videos by not including every frame. (TODO: eventually process images directly with ML to filter in/out people, animals, bitcoins, etc). 24 | - Sunrise and sunset are relative to wherever you are, so `grab-timelapse-frame.py` accepts a `--city` parameter (full list of cities is provided by `astral`'s [`geocoder.py`](https://github.com/sffjunkie/astral/blob/master/src/astral/geocoder.py) module. 25 | 26 | ## Basic Usage 27 | 28 | First, install `ffmpeg` with whatever libraries are most approriate 29 | for output formats you want. I like x264 for speed and compression 30 | ratio. 31 | 32 | ### Capturing 33 | 34 | First, you need to capture frames. `grab-timelapse-frame.py` is 35 | designed to be run in a cron. It is a short-running script that, 36 | ideally, you invoke every minute and let it run for one minute. 37 | During that time it will produce N evenly spaced out frames into the 38 | specified output directory. Example cronjob: 39 | 40 | ``` 41 | * * * * * /path/to/grab-timelapse-frame.py --output-directory /path/to/outputs --output-filenames cam1 --url rtsp://HOST:PORT/PATH 42 | ``` 43 | 44 | **NOTE**: If you use `strftime` in the output strings, don't forget to 45 | backslash `%` in your crontab -- cron translates them to newlines.. 46 | 47 | ### Creating a video 48 | 49 | Congratulations, you have a pile of png files. To make a video, you 50 | need to use `ffmpeg` with a list of files. Since you likely have too 51 | many files, you want to filter: 52 | 53 | ``` 54 | $ ./filter-timelapse-frames.py /path/to/pile --sample 10 > /tmp/filelist 55 | $ ffmpeg -r 30 -f concat -safe 0 -i <(sed 's/^/file /' /tmp/filelist) -c:v libx264rgb -preset veryslow -crf 21 -vf fps=30 /path/to/output.mp4 56 | ``` 57 | 58 | You can google for what the `ffmpeg` line does and learn how to 59 | produce other output file formats, but the above works well for me. 60 | Note it will be slow. The `<(sed ...)` bit is to prefix each line 61 | with 'file ' to produce an instruction file that `ffmpeg` likes. 62 | 63 | And you're done! Enjoy your fun video. VLC is probably the best tool 64 | to view it in. 65 | 66 | ### Reducing PNG Storage Space 67 | 68 | The PNG files created by ffmpeg are not as optimized as they could 69 | be. ImageMagick can help with this, but if you end up with a large 70 | pile of files, reprocessing them all can be annoying. The generic 71 | `process-file-once.py` script here is meant to be used avoid 72 | re-running expensive operations on files by tracking if a given 73 | command line has been run on a file before and, if so, skipping 74 | running. This makes commands idempotent no-ops and lets you lazily 75 | re-run `find` commands over and over without wasting time reprocessing 76 | already processed files. 77 | 78 | Here's how I use it in this project: 79 | 80 | ``` 81 | $ find /path/to/pile -name '*.png' | parallel --progress -I{} 'process-file-once.py {} mogrify -format png -define png:compression-level=9 {}' 82 | ``` 83 | 84 | The use of GNU `parallel` here effectively saturates your CPU. 85 | 86 | This saves me roughly 25% space. 87 | -------------------------------------------------------------------------------- /filter-timelapse-frames.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import astral # type: ignore 4 | import astral.geocoder # type: ignore 5 | import astral.sun # type: ignore 6 | 7 | import fileinput 8 | import argparse 9 | import datetime 10 | import os 11 | import pathlib 12 | import pytz 13 | import random 14 | import re 15 | import sys 16 | from typing import List 17 | 18 | 19 | # Simple arg namespace so we get typing of our arguments. Awkward but 20 | # adds type safety. 21 | class ArgNamespace: 22 | skip_weekends: bool 23 | sample_rate: int 24 | supersample_ranges: str # R:YYYYMMDD-YYYYMMDD, ... 25 | 26 | 27 | class TimeBucket: 28 | start_time: int 29 | sample_scale: int 30 | files: List[str] 31 | 32 | def __init__(self, s, r): 33 | self.start_time = s 34 | self.sample_scale = r 35 | self.files = [] 36 | 37 | def __repr__(self): 38 | return f"TimeBucket({self.start_time}, {self.sample_scale}, {len(self.files)})" 39 | 40 | def select(self, sample_rate): 41 | stride = int(sample_rate / self.sample_scale) 42 | return sorted(self.files[::stride]) 43 | 44 | 45 | # read all files 46 | # snapshot file list? maybe take from stdin? yeah use fdfind not walk 47 | # start with (-inf, inf) and walk timeline, splitting at each bucket start/stop 48 | # select() picks n entries from range (TODO: select ones near-ish noon) 49 | 50 | 51 | def main() -> None: 52 | parser = argparse.ArgumentParser( 53 | description="Grab timelapse frames from an RTSP source" 54 | ) 55 | parser.add_argument( 56 | "--skip-weekends", 57 | type=bool, 58 | default=True, 59 | ) 60 | parser.add_argument("--sample", type=int, default=1) 61 | parser.add_argument("--supersample_ranges", type=str) 62 | args = parser.parse_args(namespace=ArgNamespace) 63 | 64 | split_points = [] 65 | if args.supersample_ranges: 66 | ss_re = re.compile(r"^(\d{8})-(\d{8}):(\d+)$") 67 | for bucket in args.supersample_ranges.split(","): 68 | m = ss_re.match(bucket) 69 | if not m: 70 | continue 71 | start, stop, rate = map(int, m.groups()) 72 | split_points.append((int(start), int(stop), int(rate))) 73 | 74 | # Look for files with name components YYYY-MM-DD_HHMMSS 75 | filename_regex = re.compile( 76 | r"\D(\d\d\d\d)-(\d\d)-(\d\d)_(\d\d)(\d\d)(\d\d)\D.*png$" 77 | ) 78 | 79 | # Use Astral to lookup dawn and dusk for the dates of files we 80 | # find, relative to a specific city. 81 | astral_db = astral.geocoder.database() 82 | camera_city = astral.geocoder.lookup("Seattle", astral_db) 83 | timezone = pytz.timezone(camera_city.timezone) 84 | 85 | seen_count = 0 # for sampling 86 | sorted_files = [] 87 | for filename in fileinput.input(files=[]): 88 | filename = filename.strip() 89 | 90 | sorted_files.append(filename) 91 | sorted_files.sort() 92 | 93 | buckets = {} 94 | for filename in sorted_files: 95 | # Skip names that don't match our patterh 96 | match = filename_regex.search(filename) 97 | if match is None: 98 | continue 99 | 100 | # Localize the time in the filename string 101 | yy, mm, dd, h, m, s = (int(x) for x in match.groups()) 102 | bucket_key = dd + 100 * mm + 100 * 100 * yy 103 | if bucket_key not in buckets: 104 | bucket = TimeBucket(bucket_key, 1) 105 | buckets[bucket_key] = bucket 106 | else: 107 | bucket = buckets[bucket_key] 108 | 109 | for (start, stop, scale) in split_points: 110 | if start <= bucket_key <= stop: 111 | bucket.sample_scale = max(scale, bucket.sample_scale) 112 | 113 | image_datetime = datetime.datetime(yy, mm, dd, h, m, s, tzinfo=timezone) 114 | 115 | # Skip weekends if requested. 116 | if args.skip_weekends and image_datetime.weekday() >= 5: 117 | continue 118 | 119 | # Only print filenames when the sun is up and that meet our sampling requirement. 120 | sun_info = astral.sun.sun( 121 | camera_city.observer, date=image_datetime, tzinfo=timezone 122 | ) 123 | if sun_info["dawn"] <= image_datetime <= sun_info["dusk"]: 124 | numeric_time = dd + 100 * mm + 100 * 100 * yy 125 | buckets[numeric_time].files.append(filename) 126 | 127 | for bucket in buckets.values(): 128 | if len(bucket.files) > 0: 129 | print("\n".join(bucket.select(args.sample))) 130 | 131 | 132 | if __name__ == "__main__": 133 | main() 134 | -------------------------------------------------------------------------------- /grab-timelapse-frame.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import astral # type: ignore 4 | import astral.geocoder # type: ignore 5 | import astral.sun # type: ignore 6 | 7 | import argparse 8 | import datetime 9 | import logging 10 | import pathlib 11 | import pytz 12 | import subprocess 13 | import sys 14 | import time 15 | from typing import Tuple 16 | 17 | 18 | # Check if the sun is currently "out" in the specified city based on 19 | # today's dawn and dusk in that city. 20 | def sun_is_out(city: str, buffer_minutes: int) -> bool: 21 | astral_db = astral.geocoder.database() 22 | camera_city = astral.geocoder.lookup(city, astral_db) 23 | timezone = pytz.timezone(camera_city.timezone) 24 | sun_info = astral.sun.sun(camera_city.observer, tzinfo=timezone) 25 | delta = datetime.timedelta(minutes=buffer_minutes) 26 | 27 | now = datetime.datetime.now(tz=timezone) 28 | lower = sun_info["dawn"] - delta 29 | upper = sun_info["dusk"] + delta 30 | return lower <= now <= upper 31 | 32 | 33 | # Simple arg namespace so we get typing of our arguments. Awkward but 34 | # adds type safety. 35 | class ArgNamespace: 36 | output_directory: str 37 | output_filenames: str 38 | url: str 39 | interval: int 40 | duration: int 41 | daylight_only: bool 42 | daylight_buffer_minutes: int 43 | city: str 44 | 45 | 46 | def main() -> None: 47 | logging.basicConfig( 48 | format="%(asctime)s.%(msecs)03d %(levelname)s %(module)s - %(funcName)s: %(message)s", 49 | datefmt="%Y-%m-%d %H:%M:%S", 50 | level=logging.DEBUG, 51 | ) 52 | parser = argparse.ArgumentParser( 53 | description="Grab timelapse frames from an RTSP source" 54 | ) 55 | parser.add_argument("--output-directory", type=str, required=True) 56 | parser.add_argument( 57 | "--output-filenames", 58 | type=str, 59 | required=True, 60 | default="cam-%Y-%m-%d_%H%M%S.png", 61 | ) 62 | parser.add_argument("--url", type=str, required=True) 63 | parser.add_argument("--interval", type=int, default=10) 64 | parser.add_argument("--duration", type=int, default=60) 65 | parser.add_argument( 66 | "--daylight-only", 67 | type=bool, 68 | default=True, 69 | action=argparse.BooleanOptionalAction, 70 | ) 71 | parser.add_argument("--daylight-buffer-minutes", type=int, default=15) 72 | parser.add_argument("--city", type=str, default="Seattle") 73 | args = parser.parse_args(namespace=ArgNamespace) 74 | 75 | if args.daylight_only: 76 | if not sun_is_out(args.city, args.daylight_buffer_minutes): 77 | logging.info("Skipping snapshot outside of daylight hours") 78 | sys.exit(0) 79 | 80 | output_filenames = args.output_filenames 81 | if "%Y" not in output_filenames: 82 | output_filenames += "-%Y-%m-%d_%H%M%S.png" 83 | 84 | basedir = pathlib.Path(time.strftime(args.output_directory)) 85 | if "%Y" not in args.output_directory: 86 | basedir /= pathlib.Path(time.strftime("%Y/%m/%d/%H")) 87 | 88 | basedir.mkdir(mode=0o755, parents=True, exist_ok=True) 89 | end_time = time.time() + args.duration 90 | 91 | failed = 0 92 | succeeded = 0 93 | while time.time() < end_time: 94 | output = basedir / time.strftime(output_filenames) 95 | begin = time.time() 96 | logging.info(f"Capturing image {succeeded + failed + 1}...") 97 | res = subprocess.call( 98 | f"ffmpeg -y -loglevel fatal -rtsp_transport tcp -i {args.url} -frames:v 1 {output}", 99 | shell=True, 100 | ) 101 | if res == 0: 102 | succeeded += 1 103 | else: 104 | failed += 1 105 | end = time.time() 106 | time.sleep(max(1, int(args.interval) - (end - begin))) 107 | 108 | logging.info(f"Succeeded: {succeeded}, failed: {failed}") 109 | if failed >= args.duration / args.interval / 2: 110 | sys.exit(1) 111 | else: 112 | sys.exit(0) 113 | 114 | 115 | if __name__ == "__main__": 116 | main() 117 | -------------------------------------------------------------------------------- /process-file-once-redis.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import os 4 | import pathlib 5 | import redis 6 | import sqlite3 7 | import subprocess 8 | import sys 9 | import time 10 | 11 | KEY_NAME = "process_once" 12 | 13 | 14 | def main() -> None: 15 | r = redis.Redis(unix_socket_path="/var/run/redis/redis-server.sock") 16 | filename, args = sys.argv[1], sys.argv[2:] 17 | args_string = b"\0".join(arg.encode("utf-8") for arg in args) 18 | filename = os.path.realpath(filename) 19 | for idx in range(len(args)): 20 | args[idx] = args[idx].replace("{}", filename) 21 | 22 | key = f"{filename}:{args_string}" 23 | res = r.sismember(KEY_NAME, key) 24 | if not res: 25 | res = -1 26 | try: 27 | res = subprocess.call(args) 28 | except Exception as ex: 29 | pass 30 | if res == 0: 31 | st = os.stat(filename) 32 | r.sadd(KEY_NAME, key) 33 | else: 34 | print(f"Call of {args} failed with return code {res}") 35 | 36 | 37 | if __name__ == "__main__": 38 | main() 39 | -------------------------------------------------------------------------------- /process-file-once.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | import os 4 | import pathlib 5 | import sqlite3 6 | import subprocess 7 | import sys 8 | import time 9 | 10 | 11 | def main() -> None: 12 | conn = sqlite3.connect(pathlib.Path("~/.process-file-once.db").expanduser()) 13 | conn.execute("pragma journal_mode = WAL") 14 | conn.execute("pragma synchronous = normal") 15 | conn.execute("pragma mmap_size = 30000000000") 16 | conn.execute("pragma page_size = 32768") 17 | conn.execute( 18 | """ 19 | CREATE TABLE IF NOT EXISTS files ( 20 | path BLOB NOT NULL, 21 | cmd BLOB NOT NULL, 22 | device INT NOT NULL, 23 | inode INT NOT NULL, 24 | last_processed INT NOT NULL, 25 | PRIMARY KEY(path, cmd) 26 | ) 27 | """, 28 | ) 29 | conn.commit() 30 | 31 | filename, args = sys.argv[1], sys.argv[2:] 32 | args_string = b"\0".join(arg.encode("utf-8") for arg in args) 33 | filename = os.path.realpath(filename) 34 | for idx in range(len(args)): 35 | args[idx] = args[idx].replace("{}", filename) 36 | 37 | r = conn.execute( 38 | "SELECT cmd, device, inode, last_processed FROM files WHERE path = ? AND cmd = ?", 39 | (filename, args_string), 40 | ) 41 | row = r.fetchone() 42 | if row is None: 43 | res = -1 44 | try: 45 | res = subprocess.call(args) 46 | except Exception as ex: 47 | pass 48 | if res == 0: 49 | st = os.stat(filename) 50 | conn.execute( 51 | "INSERT INTO files (path, cmd, device, inode, last_processed) VALUES (?, ?, ?, ?, ?)", 52 | (filename, args_string, st.st_dev, st.st_ino, time.time()), 53 | ) 54 | conn.commit() 55 | else: 56 | print(f"Call of {args} failed with return code {res}") 57 | 58 | 59 | if __name__ == "__main__": 60 | main() 61 | -------------------------------------------------------------------------------- /process_file_once/.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | -------------------------------------------------------------------------------- /process_file_once/Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | version = 3 4 | 5 | [[package]] 6 | name = "async-trait" 7 | version = "0.1.53" 8 | source = "registry+https://github.com/rust-lang/crates.io-index" 9 | checksum = "ed6aa3524a2dfcf9fe180c51eae2b58738348d819517ceadf95789c51fff7600" 10 | dependencies = [ 11 | "proc-macro2", 12 | "quote", 13 | "syn", 14 | ] 15 | 16 | [[package]] 17 | name = "bytes" 18 | version = "1.1.0" 19 | source = "registry+https://github.com/rust-lang/crates.io-index" 20 | checksum = "c4872d67bab6358e59559027aa3b9157c53d9358c51423c17554809a8858e0f8" 21 | 22 | [[package]] 23 | name = "combine" 24 | version = "4.6.4" 25 | source = "registry+https://github.com/rust-lang/crates.io-index" 26 | checksum = "2a604e93b79d1808327a6fca85a6f2d69de66461e7620f5a4cbf5fb4d1d7c948" 27 | dependencies = [ 28 | "bytes", 29 | "memchr", 30 | ] 31 | 32 | [[package]] 33 | name = "dtoa" 34 | version = "0.4.8" 35 | source = "registry+https://github.com/rust-lang/crates.io-index" 36 | checksum = "56899898ce76aaf4a0f24d914c97ea6ed976d42fec6ad33fcbb0a1103e07b2b0" 37 | 38 | [[package]] 39 | name = "form_urlencoded" 40 | version = "1.0.1" 41 | source = "registry+https://github.com/rust-lang/crates.io-index" 42 | checksum = "5fc25a87fa4fd2094bffb06925852034d90a17f0d1e05197d4956d3555752191" 43 | dependencies = [ 44 | "matches", 45 | "percent-encoding", 46 | ] 47 | 48 | [[package]] 49 | name = "idna" 50 | version = "0.2.3" 51 | source = "registry+https://github.com/rust-lang/crates.io-index" 52 | checksum = "418a0a6fab821475f634efe3ccc45c013f742efe03d853e8d3355d5cb850ecf8" 53 | dependencies = [ 54 | "matches", 55 | "unicode-bidi", 56 | "unicode-normalization", 57 | ] 58 | 59 | [[package]] 60 | name = "itoa" 61 | version = "0.4.8" 62 | source = "registry+https://github.com/rust-lang/crates.io-index" 63 | checksum = "b71991ff56294aa922b450139ee08b3bfc70982c6b2c7562771375cf73542dd4" 64 | 65 | [[package]] 66 | name = "matches" 67 | version = "0.1.9" 68 | source = "registry+https://github.com/rust-lang/crates.io-index" 69 | checksum = "a3e378b66a060d48947b590737b30a1be76706c8dd7b8ba0f2fe3989c68a853f" 70 | 71 | [[package]] 72 | name = "memchr" 73 | version = "2.5.0" 74 | source = "registry+https://github.com/rust-lang/crates.io-index" 75 | checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d" 76 | 77 | [[package]] 78 | name = "percent-encoding" 79 | version = "2.1.0" 80 | source = "registry+https://github.com/rust-lang/crates.io-index" 81 | checksum = "d4fd5641d01c8f18a23da7b6fe29298ff4b55afcccdf78973b24cf3175fee32e" 82 | 83 | [[package]] 84 | name = "proc-macro2" 85 | version = "1.0.38" 86 | source = "registry+https://github.com/rust-lang/crates.io-index" 87 | checksum = "9027b48e9d4c9175fa2218adf3557f91c1137021739951d4932f5f8268ac48aa" 88 | dependencies = [ 89 | "unicode-xid", 90 | ] 91 | 92 | [[package]] 93 | name = "process_file_once" 94 | version = "0.1.0" 95 | dependencies = [ 96 | "redis", 97 | ] 98 | 99 | [[package]] 100 | name = "quote" 101 | version = "1.0.18" 102 | source = "registry+https://github.com/rust-lang/crates.io-index" 103 | checksum = "a1feb54ed693b93a84e14094943b84b7c4eae204c512b7ccb95ab0c66d278ad1" 104 | dependencies = [ 105 | "proc-macro2", 106 | ] 107 | 108 | [[package]] 109 | name = "redis" 110 | version = "0.21.5" 111 | source = "registry+https://github.com/rust-lang/crates.io-index" 112 | checksum = "1a80b5f38d7f5a020856a0e16e40a9cfabf88ae8f0e4c2dcd8a3114c1e470852" 113 | dependencies = [ 114 | "async-trait", 115 | "combine", 116 | "dtoa", 117 | "itoa", 118 | "percent-encoding", 119 | "sha1", 120 | "url", 121 | ] 122 | 123 | [[package]] 124 | name = "sha1" 125 | version = "0.6.1" 126 | source = "registry+https://github.com/rust-lang/crates.io-index" 127 | checksum = "c1da05c97445caa12d05e848c4a4fcbbea29e748ac28f7e80e9b010392063770" 128 | dependencies = [ 129 | "sha1_smol", 130 | ] 131 | 132 | [[package]] 133 | name = "sha1_smol" 134 | version = "1.0.0" 135 | source = "registry+https://github.com/rust-lang/crates.io-index" 136 | checksum = "ae1a47186c03a32177042e55dbc5fd5aee900b8e0069a8d70fba96a9375cd012" 137 | 138 | [[package]] 139 | name = "syn" 140 | version = "1.0.92" 141 | source = "registry+https://github.com/rust-lang/crates.io-index" 142 | checksum = "7ff7c592601f11445996a06f8ad0c27f094a58857c2f89e97974ab9235b92c52" 143 | dependencies = [ 144 | "proc-macro2", 145 | "quote", 146 | "unicode-xid", 147 | ] 148 | 149 | [[package]] 150 | name = "tinyvec" 151 | version = "1.6.0" 152 | source = "registry+https://github.com/rust-lang/crates.io-index" 153 | checksum = "87cc5ceb3875bb20c2890005a4e226a4651264a5c75edb2421b52861a0a0cb50" 154 | dependencies = [ 155 | "tinyvec_macros", 156 | ] 157 | 158 | [[package]] 159 | name = "tinyvec_macros" 160 | version = "0.1.0" 161 | source = "registry+https://github.com/rust-lang/crates.io-index" 162 | checksum = "cda74da7e1a664f795bb1f8a87ec406fb89a02522cf6e50620d016add6dbbf5c" 163 | 164 | [[package]] 165 | name = "unicode-bidi" 166 | version = "0.3.8" 167 | source = "registry+https://github.com/rust-lang/crates.io-index" 168 | checksum = "099b7128301d285f79ddd55b9a83d5e6b9e97c92e0ea0daebee7263e932de992" 169 | 170 | [[package]] 171 | name = "unicode-normalization" 172 | version = "0.1.19" 173 | source = "registry+https://github.com/rust-lang/crates.io-index" 174 | checksum = "d54590932941a9e9266f0832deed84ebe1bf2e4c9e4a3554d393d18f5e854bf9" 175 | dependencies = [ 176 | "tinyvec", 177 | ] 178 | 179 | [[package]] 180 | name = "unicode-xid" 181 | version = "0.2.3" 182 | source = "registry+https://github.com/rust-lang/crates.io-index" 183 | checksum = "957e51f3646910546462e67d5f7599b9e4fb8acdd304b087a6494730f9eebf04" 184 | 185 | [[package]] 186 | name = "url" 187 | version = "2.2.2" 188 | source = "registry+https://github.com/rust-lang/crates.io-index" 189 | checksum = "a507c383b2d33b5fc35d1861e77e6b383d158b2da5e14fe51b83dfedf6fd578c" 190 | dependencies = [ 191 | "form_urlencoded", 192 | "idna", 193 | "matches", 194 | "percent-encoding", 195 | ] 196 | -------------------------------------------------------------------------------- /process_file_once/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "process_file_once" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | 10 | [dependencies.redis] 11 | version = "*" 12 | -------------------------------------------------------------------------------- /process_file_once/src/main.rs: -------------------------------------------------------------------------------- 1 | extern crate redis; 2 | use redis::Commands; 3 | use std::env; 4 | use std::fs; 5 | use std::io; 6 | use std::io::Write; 7 | use std::process::Command; 8 | 9 | const KEY_NAME: &str = "process_once"; 10 | 11 | fn main() -> Result<(), Box> { 12 | let args: Vec = env::args().collect(); 13 | let filename = fs::canonicalize(&args[1])? 14 | .into_os_string() 15 | .into_string() 16 | .unwrap(); 17 | let params: Vec = args[2..] 18 | .iter() 19 | .map(|s| s.replace("{}", &filename)) 20 | .collect(); 21 | let args_string = args[2..].join("\0"); 22 | let key = format!("{}\0{}", filename, args_string); 23 | 24 | let client = redis::Client::open("redis+unix:///var/run/redis/redis-server.sock")?; 25 | let mut con = client.get_connection()?; 26 | 27 | let count: bool = con.sismember(KEY_NAME, &key)?; 28 | if !count { 29 | let res = Command::new(String::from(¶ms[0])) 30 | .args(params[1..].iter()) 31 | .output(); 32 | match res { 33 | Ok(output) if output.status.success() => con.sadd(KEY_NAME, &key)?, 34 | Ok(output) => { 35 | eprintln!( 36 | "Non-zero command exit status: {:?} -> {}", 37 | params, output.status 38 | ); 39 | io::stderr().write_all(&output.stderr)?; 40 | } 41 | Err(e) => { 42 | eprintln!("Command execution failed: {:?} -> {}", params, e); 43 | } 44 | } 45 | } 46 | 47 | Ok(()) 48 | } 49 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | astral 2 | pytz 3 | pillow 4 | -------------------------------------------------------------------------------- /stack_images.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | from PIL import Image 4 | import os 5 | import sys 6 | import multiprocessing 7 | from typing import Tuple 8 | 9 | 10 | def main() -> None: 11 | file1 = [l.strip() for l in open(sys.argv[2])] 12 | file2 = [l.strip() for l in open(sys.argv[3])] 13 | 14 | with multiprocessing.Pool(processes=32) as pool: 15 | pool.map( 16 | handle_file, 17 | [(idx, top, bottom) for idx, (top, bottom) in enumerate(zip(file1, file2))], 18 | ) 19 | 20 | 21 | def handle_file(op: Tuple[int, str, str]) -> None: 22 | idx, top, bottom = op 23 | top_img = Image.open(top) 24 | bottom_img = Image.open(bottom) 25 | new_size = (top_img.size[0], top_img.size[1] + bottom_img.size[1]) 26 | 27 | output_dir = sys.argv[1] 28 | output_name = f"{output_dir}/output{idx:04d}.png" 29 | print(f"Writing {output_name} from {top} and {bottom}...") 30 | 31 | try: 32 | output_img = Image.new("RGBA", new_size) 33 | output_img.paste(top_img) 34 | output_img.paste(bottom_img, (0, top_img.size[1])) 35 | output_img.save(output_name) 36 | except Exception as e: 37 | print(f"Skipping {output_name} -> {e}") 38 | try: 39 | os.unlink(output_name) 40 | except: 41 | pass 42 | 43 | 44 | if __name__ == "__main__": 45 | main() 46 | --------------------------------------------------------------------------------