-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmake_timelapse.py
More file actions
328 lines (274 loc) Β· 12 KB
/
Copy pathmake_timelapse.py
File metadata and controls
328 lines (274 loc) Β· 12 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
#!/usr/bin/env python3
"""
make_timelapse.py β Daily Sun Journey Timelapse
Stitches patio cam sunrise frames + front yard cam sunset frames
into a single MP4 showing the sun's full arc over the house.
Optionally overlays Powerwall solar production data as a live meter.
Usage:
python3 make_timelapse.py [YYYY-MM-DD] # defaults to today
python3 make_timelapse.py --yesterday
Output:
sky-watcher/timelapses/YYYY-MM-DD.mp4
Author: Sam (github.com/jasonacox-sam)
"""
import os
import sys
import json
import subprocess
import tempfile
from datetime import date, datetime, timedelta
from pathlib import Path
from zoneinfo import ZoneInfo
# ββ Config βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
BASE_DIR = Path(__file__).parent
PATIO_DIR = BASE_DIR / "images"
FRONTYARD_DIR = BASE_DIR / "images" / "frontyard"
OUTPUT_DIR = BASE_DIR / "timelapses"
TIMEZONE = "America/Los_Angeles"
FRAME_DURATION = 0.25 # seconds per frame (0.25 = 4fps, smooth timelapse)
NOON_HOUR = 13 # split: before this = sunrise set, after = sunset set
# Powerwall integration (optional β set to None to skip)
POWERWALL_IP = "10.0.1.2" # your Powerwall gateway IP
# ββ Powerwall solar data ββββββββββββββββββββββββββββββββββββββββββββββββββββ
def get_solar_peak(target_date: date) -> float:
"""
Pull today's peak solar production from Powerwall.
Returns peak kW, or 0.0 if unavailable.
"""
try:
import pypowerwall
pw = pypowerwall.Powerwall(POWERWALL_IP, "", "", "", gw_pwd="")
solar = pw.solar()
if solar:
return round(float(solar) / 1000, 2)
except Exception:
pass
return 0.0
def get_solar_timeseries(target_date: date) -> list[tuple[str, float]]:
"""
Returns list of (HH-MM, kW) tuples for the target date if available.
Falls back to empty list.
"""
try:
import pypowerwall
pw = pypowerwall.Powerwall(POWERWALL_IP, "", "", "", gw_pwd="")
data = pw.get_history(period="day")
if not data:
return []
result = []
for entry in data:
ts = entry.get("timestamp", "")
solar_w = entry.get("solar_power", 0)
try:
dt = datetime.fromisoformat(ts).astimezone(ZoneInfo(TIMEZONE))
if dt.date() == target_date:
result.append((dt.strftime("%H-%M"), round(solar_w / 1000, 2)))
except Exception:
pass
return result
except Exception:
return []
# ββ Frame collection ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def collect_frames(target_date: date) -> tuple[list[Path], list[Path]]:
"""
Return (sunrise_frames, sunset_frames) for the target date.
Sunrise = patio cam images with hour < NOON_HOUR
Sunset = frontyard cam images with hour >= NOON_HOUR
Files named HH-MM.jpg; use mtime date to filter to target_date.
"""
tz = ZoneInfo(TIMEZONE)
def date_filter(p: Path) -> bool:
mtime = datetime.fromtimestamp(p.stat().st_mtime, tz=tz)
return mtime.date() == target_date
def hour_of(p: Path) -> int:
try:
return int(p.stem.split("-")[0])
except (ValueError, IndexError):
return 0
sunrise_frames = sorted(
[p for p in PATIO_DIR.glob("*.jpg")
if date_filter(p) and hour_of(p) < NOON_HOUR],
key=lambda p: p.stem
)
sunset_frames = sorted(
[p for p in FRONTYARD_DIR.glob("*.jpg")
if date_filter(p) and hour_of(p) >= NOON_HOUR],
key=lambda p: p.stem
)
# Fallback: if frontyard has nothing, use patio sunset frames too
if not sunset_frames:
sunset_frames = sorted(
[p for p in PATIO_DIR.glob("*.jpg")
if date_filter(p) and hour_of(p) >= NOON_HOUR],
key=lambda p: p.stem
)
return sunrise_frames, sunset_frames
# ββ ffmpeg timelapse ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def stem_to_label(stem: str, cam_name: str) -> str:
"""Convert '06-24' β '6:24 AM π· Patio'"""
try:
h, m = int(stem[:2]), int(stem[3:5])
period = "AM" if h < 12 else "PM"
display_h = h if h <= 12 else h - 12
display_h = 12 if display_h == 0 else display_h
return f"{display_h}:{m:02d} {period} {cam_name}"
except Exception:
return stem
def build_timelapse(
sunrise_frames: list[Path],
sunset_frames: list[Path],
target_date: date,
solar_data: list[tuple[str, float]],
output_path: Path,
) -> bool:
"""
Stitch frames into MP4 using ffmpeg concat demuxer.
Adds timestamp overlay and optional solar meter.
"""
if not sunrise_frames and not sunset_frames:
print("No frames found β nothing to stitch.")
return False
solar_lookup = dict(solar_data)
max_solar = max((v for _, v in solar_data), default=0) or 10.0
# Build concat list with per-frame metadata
all_frames: list[tuple[Path, str, str]] = []
for p in sunrise_frames:
label = stem_to_label(p.stem, "π
Patio")
all_frames.append((p, label, p.stem))
for p in sunset_frames:
cam = "π Front Yard" if FRONTYARD_DIR in p.parents else "π Patio"
label = stem_to_label(p.stem, cam)
all_frames.append((p, label, p.stem))
if not all_frames:
print("No frames to stitch.")
return False
date_str = target_date.strftime("%B %-d, %Y")
with tempfile.TemporaryDirectory() as tmpdir:
tmpdir = Path(tmpdir)
# Write concat file
concat_path = tmpdir / "concat.txt"
with open(concat_path, "w") as f:
for frame_path, _, _ in all_frames:
f.write(f"file '{frame_path.resolve()}'\n")
f.write(f"duration {FRAME_DURATION}\n")
# ffmpeg needs a final file line without duration
f.write(f"file '{all_frames[-1][0].resolve()}'\n")
# Build drawtext filter chain
# Line 1: date
# Line 2: time + camera label
# Line 3 (optional): solar meter if data available
filter_parts = []
# Date header
filter_parts.append(
f"drawtext=text='{date_str} β Valencia, CA':"
f"fontsize=28:fontcolor=white:x=20:y=20:"
f"shadowcolor=black:shadowx=2:shadowy=2"
)
# We'll use a single static drawtext per frame via concat + individual frames
# For dynamic text, use ffmpeg's overlay with a script β but for simplicity,
# burn the label per frame using a two-pass approach.
# Simpler: just overlay date + static labels via the concat + drawtext
# For per-frame labels we need individual frame processing.
# Let's do it right: process each frame individually first.
labeled_dir = tmpdir / "labeled"
labeled_dir.mkdir()
print(f"Processing {len(all_frames)} frames...")
for i, (frame_path, label, stem) in enumerate(all_frames):
out_frame = labeled_dir / f"{i:04d}.jpg"
solar_kw = solar_lookup.get(stem, None)
# Build filter
filters = [
# Semi-transparent black bar at bottom
"drawbox=x=0:y=ih-80:w=iw:h=80:color=black@0.55:t=fill",
# Date top-left
f"drawtext=text='{date_str}':fontsize=22:fontcolor=white@0.9:"
f"x=20:y=20:shadowcolor=black@0.8:shadowx=1:shadowy=1",
# Time + camera bottom-left
f"drawtext=text='{label}':fontsize=30:fontcolor=white:"
f"x=20:y=ih-60:shadowcolor=black:shadowx=2:shadowy=2",
]
# Solar meter bottom-right
if solar_kw is not None and solar_kw > 0:
bar_pct = min(solar_kw / max_solar, 1.0)
bar_w = int(200 * bar_pct)
filters += [
# Label
f"drawtext=text='β {solar_kw:.1f} kW':fontsize=22:fontcolor=yellow:"
f"x=iw-220:y=ih-60:shadowcolor=black:shadowx=1:shadowy=1",
# Bar background
f"drawbox=x=iw-222:y=ih-28:w=204:h=16:color=white@0.3:t=fill",
# Bar fill
f"drawbox=x=iw-222:y=ih-28:w={bar_w}:h=16:color=yellow@0.8:t=fill",
]
vf = ",".join(filters)
cmd = [
"ffmpeg", "-y", "-loglevel", "error",
"-i", str(frame_path),
"-vf", vf,
"-q:v", "3",
str(out_frame)
]
result = subprocess.run(cmd, capture_output=True)
if result.returncode != 0:
# Fallback: copy frame without overlay
import shutil
shutil.copy(frame_path, out_frame)
# Build new concat from labeled frames
labeled_concat = tmpdir / "labeled_concat.txt"
labeled_frames = sorted(labeled_dir.glob("*.jpg"))
with open(labeled_concat, "w") as f:
for lf in labeled_frames:
f.write(f"file '{lf.resolve()}'\n")
f.write(f"duration {FRAME_DURATION}\n")
f.write(f"file '{labeled_frames[-1].resolve()}'\n")
# Final ffmpeg encode
output_path.parent.mkdir(parents=True, exist_ok=True)
cmd = [
"ffmpeg", "-y", "-loglevel", "warning",
"-f", "concat", "-safe", "0",
"-i", str(labeled_concat),
"-vf", "scale=1920:-2:flags=lanczos,fps=10",
"-c:v", "libx264", "-crf", "23", "-preset", "fast",
"-pix_fmt", "yuv420p",
str(output_path)
]
print(f"Encoding β {output_path}")
result = subprocess.run(cmd, capture_output=True)
if result.returncode != 0:
print(f"ffmpeg error: {result.stderr.decode()[-500:]}")
return False
size_mb = output_path.stat().st_size / 1_048_576
print(f"β
Done: {output_path} ({size_mb:.1f} MB, {len(all_frames)} frames)")
return True
# ββ Main ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def main():
tz = ZoneInfo(TIMEZONE)
# Parse date argument
if "--yesterday" in sys.argv:
target_date = (datetime.now(tz) - timedelta(days=1)).date()
elif len(sys.argv) > 1 and not sys.argv[1].startswith("-"):
target_date = date.fromisoformat(sys.argv[1])
else:
target_date = datetime.now(tz).date()
print(f"\n{'='*60}")
print(f" Sun Journey Timelapse β {target_date}")
print(f"{'='*60}")
sunrise_frames, sunset_frames = collect_frames(target_date)
print(f" Sunrise frames (Patio) : {len(sunrise_frames)}")
print(f" Sunset frames (Front Yard): {len(sunset_frames)}")
if not sunrise_frames and not sunset_frames:
print("\nNo frames found for this date. Run during or after a capture window.")
sys.exit(1)
# Optional solar data
print(" Fetching Powerwall solar data...")
solar_data = get_solar_timeseries(target_date)
if solar_data:
peak = max(v for _, v in solar_data)
print(f" Solar data: {len(solar_data)} points, peak {peak:.1f} kW")
else:
print(" Solar data: unavailable (continuing without meter)")
output_path = OUTPUT_DIR / f"{target_date}.mp4"
success = build_timelapse(sunrise_frames, sunset_frames, target_date, solar_data, output_path)
sys.exit(0 if success else 1)
if __name__ == "__main__":
main()