virtual-uav-camera 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. virtual_uav_camera/__init__.py +71 -0
  2. virtual_uav_camera/__main__.py +184 -0
  3. virtual_uav_camera/arrays.py +13 -0
  4. virtual_uav_camera/camera_device.py +84 -0
  5. virtual_uav_camera/camera_sensor.py +74 -0
  6. virtual_uav_camera/conditions.py +26 -0
  7. virtual_uav_camera/dated_imagery.py +202 -0
  8. virtual_uav_camera/daylight.py +92 -0
  9. virtual_uav_camera/downloads.py +55 -0
  10. virtual_uav_camera/drawing.py +97 -0
  11. virtual_uav_camera/geotiff.py +146 -0
  12. virtual_uav_camera/ground_imagery.py +40 -0
  13. virtual_uav_camera/ground_view.py +76 -0
  14. virtual_uav_camera/interface.py +515 -0
  15. virtual_uav_camera/live_camera.py +178 -0
  16. virtual_uav_camera/live_flight.py +142 -0
  17. virtual_uav_camera/map_tiles.py +97 -0
  18. virtual_uav_camera/mapped_ground.py +161 -0
  19. virtual_uav_camera/mavlink_poses.py +183 -0
  20. virtual_uav_camera/page/assets/index-CBXgxz7a.js +284 -0
  21. virtual_uav_camera/page/assets/index-yOTG8Eco.css +1 -0
  22. virtual_uav_camera/page/index.html +13 -0
  23. virtual_uav_camera/places.py +48 -0
  24. virtual_uav_camera/planned_flight.py +96 -0
  25. virtual_uav_camera/pose.py +101 -0
  26. virtual_uav_camera/pose_lines.py +145 -0
  27. virtual_uav_camera/py.typed +0 -0
  28. virtual_uav_camera/route.py +105 -0
  29. virtual_uav_camera/scene_light.py +194 -0
  30. virtual_uav_camera/season.py +248 -0
  31. virtual_uav_camera/sentinel.py +78 -0
  32. virtual_uav_camera/served_camera.py +217 -0
  33. virtual_uav_camera/settings.py +364 -0
  34. virtual_uav_camera/sharper_ground.py +150 -0
  35. virtual_uav_camera/sun.py +97 -0
  36. virtual_uav_camera/synthetic_camera.py +958 -0
  37. virtual_uav_camera/terrain.py +85 -0
  38. virtual_uav_camera/terrain_tiles.py +161 -0
  39. virtual_uav_camera/tile_server.py +35 -0
  40. virtual_uav_camera/unmapped_ground.py +189 -0
  41. virtual_uav_camera/utm.py +69 -0
  42. virtual_uav_camera/web.py +47 -0
  43. virtual_uav_camera/world.py +342 -0
  44. virtual_uav_camera/world_folder.py +19 -0
  45. virtual_uav_camera-0.1.0.dist-info/METADATA +535 -0
  46. virtual_uav_camera-0.1.0.dist-info/RECORD +50 -0
  47. virtual_uav_camera-0.1.0.dist-info/WHEEL +4 -0
  48. virtual_uav_camera-0.1.0.dist-info/entry_points.txt +2 -0
  49. virtual_uav_camera-0.1.0.dist-info/licenses/LICENSE +202 -0
  50. virtual_uav_camera-0.1.0.dist-info/licenses/NOTICE +23 -0
@@ -0,0 +1,71 @@
1
+ """A camera for simulated UAV flights: the frames a camera hung under the aircraft would see,
2
+ drawn from dated aerial imagery and terrain of the ground along a route.
3
+
4
+ A world is created once for a route (a QGC WPL 110 waypoints file) and its settings, and then
5
+ drawn from any pose: one frame at a time (``camera_over``), live for a flight in progress
6
+ (``LiveCamera``), or served as a video stream (``served_camera_over``).
7
+ """
8
+ from __future__ import annotations
9
+
10
+ from importlib.metadata import version
11
+
12
+ from .downloads import KeptDownloads, default_downloads_folder
13
+ from .drawing import WorldCamera, camera_over
14
+ from .live_camera import ArrivedPose, ExposedFrame, FramesOfAFlight, LiveCamera, NewestPose, Poses
15
+ from .live_flight import LiveViewOnThePage
16
+ from .mavlink_poses import PosesOverMavlink
17
+ from .pose import AircraftPose, Pose
18
+ from .pose_lines import PosesSaidInLines
19
+ from .served_camera import ServedCamera, served_camera_over
20
+ from .settings import (
21
+ Air,
22
+ CameraMount,
23
+ CameraSettings,
24
+ EsriWayback,
25
+ FlightAllowance,
26
+ Look,
27
+ Sensor,
28
+ TileServer,
29
+ WorldSettings,
30
+ )
31
+ from .web import TheInternet, Web
32
+ from .world import CreatedWorld, create_world, settings_of, world_name, world_record
33
+
34
+ __version__ = version("virtual-uav-camera")
35
+
36
+ __all__ = [
37
+ "Air",
38
+ "AircraftPose",
39
+ "ArrivedPose",
40
+ "CameraMount",
41
+ "CameraSettings",
42
+ "CreatedWorld",
43
+ "EsriWayback",
44
+ "ExposedFrame",
45
+ "FlightAllowance",
46
+ "FramesOfAFlight",
47
+ "KeptDownloads",
48
+ "LiveCamera",
49
+ "LiveViewOnThePage",
50
+ "Look",
51
+ "NewestPose",
52
+ "Pose",
53
+ "Poses",
54
+ "PosesOverMavlink",
55
+ "PosesSaidInLines",
56
+ "Sensor",
57
+ "ServedCamera",
58
+ "TheInternet",
59
+ "TileServer",
60
+ "Web",
61
+ "WorldCamera",
62
+ "WorldSettings",
63
+ "__version__",
64
+ "camera_over",
65
+ "create_world",
66
+ "default_downloads_folder",
67
+ "served_camera_over",
68
+ "settings_of",
69
+ "world_name",
70
+ "world_record",
71
+ ]
@@ -0,0 +1,184 @@
1
+ """The command line.
2
+
3
+ virtual-uav-camera settings > settings.json
4
+ virtual-uav-camera world --route route.waypoints [--settings settings.json] --worlds worlds/
5
+ virtual-uav-camera frame --world worlds/<name> --latitude 50.78 --longitude 30.12 \\
6
+ --agl-m 400 --output frame.png
7
+ virtual-uav-camera camera --world worlds/<name> [--poses mavlink:tcp:127.0.0.1:5763]
8
+ virtual-uav-camera interface --worlds worlds/
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import argparse
13
+ import json
14
+ import sys
15
+ from pathlib import Path
16
+
17
+ from .downloads import KeptDownloads, default_downloads_folder
18
+ from .drawing import camera_over
19
+ from .interface import DEFAULT_PORT, ServedInterface
20
+ from .pose import Pose
21
+ from .served_camera import DEFAULT_PORT as DEFAULT_CAMERA_PORT
22
+ from .served_camera import (
23
+ DEFAULT_POSES_AT,
24
+ POSES_OVER_MAVLINK,
25
+ STANDARD_INPUT,
26
+ THIS_MACHINE,
27
+ served_camera_over,
28
+ )
29
+ from .settings import WorldSettings
30
+ from .web import TheInternet, Web
31
+ from .world import CreatedWorld, ImageryRecord, create_world
32
+
33
+ PROGRAM = "virtual-uav-camera"
34
+ DONE = 0
35
+ NOT_DONE = 1
36
+
37
+
38
+ def main(argv: list[str] | None = None, web: Web | None = None) -> int:
39
+ parser = argparse.ArgumentParser(
40
+ prog=PROGRAM,
41
+ description="A camera for simulated UAV flights, drawn from dated aerial imagery and "
42
+ "terrain of the ground along a route.")
43
+ commands = parser.add_subparsers(dest="command", required=True)
44
+ commands.add_parser("settings", help="write every world setting with its default, as JSON")
45
+ world = commands.add_parser("world", help="create the world of a route")
46
+ world.add_argument("--route", type=Path, required=True,
47
+ help="the route's waypoints file (QGC WPL 110)")
48
+ world.add_argument("--settings", type=Path,
49
+ help="the world's settings (JSON); every setting's default when left out")
50
+ world.add_argument("--worlds", type=Path, required=True,
51
+ help="the folder worlds are kept in, one folder each")
52
+ _downloads_argument(world)
53
+ frame = commands.add_parser("frame", help="draw the frame a world's camera sees from a pose")
54
+ frame.add_argument("--world", type=Path, required=True, help="the world to draw")
55
+ frame.add_argument("--latitude", type=float, required=True, help="degrees")
56
+ frame.add_argument("--longitude", type=float, required=True, help="degrees")
57
+ frame.add_argument("--agl-m", type=float, required=True,
58
+ help="the aircraft's height above the ground under it")
59
+ frame.add_argument("--yaw-deg", type=float, default=0.0, help="heading, from north")
60
+ frame.add_argument("--roll-deg", type=float, default=0.0, help="right wing down")
61
+ frame.add_argument("--pitch-deg", type=float, default=0.0, help="nose up")
62
+ frame.add_argument("--output", type=Path, required=True, help="the picture file to write")
63
+ camera = commands.add_parser(
64
+ "camera", help="serve the camera of a flight in progress as a video stream")
65
+ camera.add_argument("--world", type=Path, required=True, help="the world to draw")
66
+ camera.add_argument("--poses", default=DEFAULT_POSES_AT,
67
+ help="where the flight's poses are said, a JSON object a line: "
68
+ f"udp://HOST:PORT, or {STANDARD_INPUT} for standard input; or "
69
+ f"{POSES_OVER_MAVLINK}ENDPOINT to read a simulated aircraft's "
70
+ "true pose over MAVLink, as pymavlink names a link")
71
+ camera.add_argument("--host", default=THIS_MACHINE,
72
+ help="the address the stream is served at; this machine only when "
73
+ "left out")
74
+ camera.add_argument("--port", type=int, default=DEFAULT_CAMERA_PORT)
75
+ camera.add_argument("--device",
76
+ help="a loopback camera device on this machine to write the frames "
77
+ "into as well, /dev/video10 for one; needs ffmpeg")
78
+ camera.add_argument("--live-view",
79
+ help="the web address of an interface to show the frames on as well, "
80
+ f"http://127.0.0.1:{DEFAULT_PORT} for one started here")
81
+ interface = commands.add_parser(
82
+ "interface", help="serve the web interface to a browser on this machine")
83
+ interface.add_argument("--worlds", type=Path, required=True,
84
+ help="the folder worlds are kept in, one folder each")
85
+ interface.add_argument("--port", type=int, default=DEFAULT_PORT)
86
+ _downloads_argument(interface)
87
+ asked = parser.parse_args(argv)
88
+ try:
89
+ if asked.command == "settings":
90
+ print(json.dumps(WorldSettings().record(), indent=2))
91
+ return DONE
92
+ if asked.command == "frame":
93
+ return _frame_drawn(asked)
94
+ if asked.command == "camera":
95
+ return _camera_served(asked)
96
+ kept = KeptDownloads(web or TheInternet(), asked.downloads)
97
+ if asked.command == "interface":
98
+ return _interface_served(asked, kept)
99
+ return _world_created(asked, kept)
100
+ except (ValueError, LookupError, OSError) as refusal:
101
+ print(f"{PROGRAM}: {refusal}", file=sys.stderr)
102
+ return NOT_DONE
103
+
104
+
105
+ def _downloads_argument(command: argparse.ArgumentParser) -> None:
106
+ command.add_argument("--downloads", type=Path, default=default_downloads_folder(),
107
+ help="the folder downloads are kept in for the next world; "
108
+ f"{default_downloads_folder()} when left out")
109
+
110
+
111
+ def _world_created(asked: argparse.Namespace, web: Web) -> int:
112
+ settings = WorldSettings() if asked.settings is None else WorldSettings.read(asked.settings)
113
+ created = create_world(asked.route, settings, asked.worlds, web, said=print)
114
+ print(_what_was_made(created))
115
+ return DONE
116
+
117
+
118
+ def _what_was_made(created: CreatedWorld) -> str:
119
+ if created.reused:
120
+ return f"{created.folder}: this world was made before"
121
+ imagery, season = created.imagery, created.season
122
+ sharper = imagery["sharper"]
123
+ return (f"created {created.folder}: {imagery['tiles']} imagery tiles "
124
+ + _where_the_imagery_came_from(imagery) + "; "
125
+ + ("no sharper imagery, where a frame is finer than the world's own or the "
126
+ "imagery holds none" if not sharper else
127
+ "sharper imagery where a frame is finer: " + ", ".join(
128
+ f"{level['tiles']} tiles of zoom {level['zoom']} below "
129
+ f"{level['seen_from_below_agl_m']:.0f} m" for level in sharper))
130
+ + ("" if season is None else
131
+ f"; in the colour of {season['taken']}, {season['hidden_share']:.1%} of the "
132
+ "ground hidden by cloud"))
133
+
134
+
135
+ def _where_the_imagery_came_from(imagery: ImageryRecord) -> str:
136
+ if "release" not in imagery:
137
+ return f"from {imagery.get('address')}, credited to {imagery['credit']}"
138
+ taken = ", ".join(imagery.get("taken", [])) or "on a day the release does not state"
139
+ now_taken = (", ".join(imagery.get("current_picture_taken", []))
140
+ or "on a day it does not state")
141
+ return (f"taken {taken}, from the release published {imagery.get('published')} "
142
+ f"(number {imagery['release']}); the current picture was taken {now_taken}")
143
+
144
+
145
+ def _interface_served(asked: argparse.Namespace, web: Web) -> int:
146
+ asked.worlds.mkdir(parents=True, exist_ok=True)
147
+ served = ServedInterface(asked.worlds, web, asked.port)
148
+ print(f"the interface is at {served.address} (Ctrl-C stops it)", flush=True)
149
+ try:
150
+ served.serve_until_stopped()
151
+ except KeyboardInterrupt:
152
+ served.close()
153
+ return DONE
154
+
155
+
156
+ def _camera_served(asked: argparse.Namespace) -> int:
157
+ served = served_camera_over(
158
+ asked.world, poses_at=asked.poses, host=asked.host, port=asked.port,
159
+ device=asked.device, live_view=asked.live_view)
160
+ print(f"the camera of {asked.world} is at {served.address}"
161
+ + ("" if asked.device is None else f" and on {asked.device}")
162
+ + ("" if asked.live_view is None else f", shown on {asked.live_view}")
163
+ + f", following the poses said at {served.poses_at} (Ctrl-C stops it)", flush=True)
164
+ try:
165
+ served.serve_until_stopped()
166
+ except KeyboardInterrupt:
167
+ served.close()
168
+ return DONE
169
+
170
+
171
+ def _frame_drawn(asked: argparse.Namespace) -> int:
172
+ import cv2
173
+
174
+ camera = camera_over(asked.world)
175
+ picture = camera.frame(Pose(asked.latitude, asked.longitude, asked.agl_m, asked.yaw_deg,
176
+ asked.roll_deg, asked.pitch_deg))
177
+ if not cv2.imwrite(str(asked.output), cv2.cvtColor(picture, cv2.COLOR_RGB2BGR)):
178
+ raise OSError(f"{asked.output} could not be written")
179
+ print(f"drew {asked.output}: {camera.width_px} by {camera.height_px} pixels")
180
+ return DONE
181
+
182
+
183
+ if __name__ == "__main__":
184
+ raise SystemExit(main())
@@ -0,0 +1,13 @@
1
+ """The kinds of array the camera works with."""
2
+ from __future__ import annotations
3
+
4
+ from typing import TypeAlias
5
+
6
+ import numpy as np
7
+ import numpy.typing as npt
8
+
9
+ FloatArray: TypeAlias = npt.NDArray[np.float64]
10
+ Float32Array: TypeAlias = npt.NDArray[np.float32]
11
+ UInt8Array: TypeAlias = npt.NDArray[np.uint8]
12
+ IntArray: TypeAlias = npt.NDArray[np.intp]
13
+ BoolArray: TypeAlias = npt.NDArray[np.bool_]
@@ -0,0 +1,84 @@
1
+ """A camera device: a flight's frames written into a loopback camera device (``v4l2loopback``
2
+ on Linux), so that a program which only opens a camera device reads them as it reads a
3
+ camera. ffmpeg copies the frames in as the JPEG pictures they are; this needs ffmpeg and is
4
+ the one part of the application that does.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import contextlib
9
+ import subprocess
10
+ import sys
11
+ import tempfile
12
+ from collections.abc import Callable, Sequence
13
+ from typing import IO
14
+
15
+ FFMPEG = ("ffmpeg",)
16
+ # The rate ffmpeg is told the pictures come at. They are copied in as they arrive, whatever
17
+ # their rate; this is a common camera's.
18
+ DEVICE_FRAMES_A_SECOND = 30
19
+ FFMPEG_STOPPED_WITHIN_S = 2.0
20
+ MOST_OF_WHAT_FFMPEG_SAID_BYTES = 2000
21
+
22
+
23
+ def copies_into_the_device(device: str, ffmpeg: Sequence[str] = FFMPEG) -> list[str]:
24
+ """The ffmpeg command that copies MJPEG pictures from its standard input into ``device``."""
25
+ return [*ffmpeg, "-loglevel", "error", "-f", "mjpeg", "-framerate",
26
+ str(DEVICE_FRAMES_A_SECOND), "-i", "-", "-c:v", "copy", "-f", "v4l2", device]
27
+
28
+
29
+ def _to_standard_error(what: str) -> None:
30
+ print(f"virtual-uav-camera: {what}", file=sys.stderr, flush=True)
31
+
32
+
33
+ class CameraDevice:
34
+ """A loopback camera device shown a flight's frames. A device that takes no frames (it
35
+ is not there, it may not be written, ffmpeg cannot write one) is said once, with what
36
+ ffmpeg said of it, and is shown nothing more."""
37
+
38
+ def __init__(self, device: str, *, ffmpeg: Sequence[str] = FFMPEG,
39
+ said: Callable[[str], None] = _to_standard_error) -> None:
40
+ self._device = device
41
+ self._say = said
42
+ self._what_ffmpeg_said: IO[bytes] = tempfile.TemporaryFile()
43
+ try:
44
+ self._ffmpeg: subprocess.Popen[bytes] | None = subprocess.Popen(
45
+ copies_into_the_device(device, ffmpeg), stdin=subprocess.PIPE,
46
+ stdout=subprocess.DEVNULL, stderr=self._what_ffmpeg_said)
47
+ except FileNotFoundError as not_installed:
48
+ self._what_ffmpeg_said.close()
49
+ raise ValueError(
50
+ f"writing a camera device needs ffmpeg, and {ffmpeg[0]} is not installed"
51
+ ) from not_installed
52
+
53
+ def show(self, jpeg: bytes) -> None:
54
+ ffmpeg = self._ffmpeg
55
+ if ffmpeg is None or ffmpeg.stdin is None:
56
+ return
57
+ try:
58
+ ffmpeg.stdin.write(jpeg)
59
+ ffmpeg.stdin.flush()
60
+ except OSError:
61
+ self._stop()
62
+ self._say(f"{self._device} takes no frames: {self._what_was_said()}")
63
+
64
+ def close(self) -> None:
65
+ self._stop()
66
+ self._what_ffmpeg_said.close()
67
+
68
+ def _stop(self) -> None:
69
+ ffmpeg, self._ffmpeg = self._ffmpeg, None
70
+ if ffmpeg is None:
71
+ return
72
+ if ffmpeg.stdin is not None:
73
+ with contextlib.suppress(OSError):
74
+ ffmpeg.stdin.close()
75
+ try:
76
+ ffmpeg.wait(FFMPEG_STOPPED_WITHIN_S)
77
+ except subprocess.TimeoutExpired:
78
+ ffmpeg.kill()
79
+ ffmpeg.wait()
80
+
81
+ def _what_was_said(self) -> str:
82
+ self._what_ffmpeg_said.seek(0)
83
+ said = self._what_ffmpeg_said.read(MOST_OF_WHAT_FFMPEG_SAID_BYTES)
84
+ return said.decode("utf-8", errors="replace").strip() or "ffmpeg stopped and said nothing"
@@ -0,0 +1,74 @@
1
+ """The camera's sensor: what the camera itself does to the picture that reaches it. Blur, an
2
+ exposure that makes up for the daylight, one that drifts and one that is commanded, and
3
+ noise, ending in the 8-bit picture a camera hands over.
4
+
5
+ These soften the picture; they do not model the UAV-to-satellite appearance gap.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import numpy as np
10
+
11
+ from .arrays import Float32Array, UInt8Array
12
+ from .conditions import CAMERA_GAMMA, EIGHT_BIT_LEVEL_RANGE, FrameConditions
13
+ from .daylight import brightening_for, daylight
14
+ from .settings import UNCHANGED_EXPOSURE_GAIN
15
+
16
+ # A wider blur takes seconds a frame, and past this the picture is mush anyway.
17
+ BLUR_SIGMA_LIMIT_PX = 16.0
18
+ BLUR_SEEN_AT_SIGMA_PX = 0.3
19
+ BLUR_PX_UNDER_FULL_RAIN = 0.8
20
+ EXPOSURE_DRIFT_STEP = 0.01
21
+
22
+
23
+ class CameraSensor:
24
+ """``blur_px``, in pixels of the frame, ``noise_std`` and ``exposure_jitter`` are the
25
+ sensor's own; a frame's conditions override the first two and command ``exposure_gain`` for that frame, while
26
+ ``exposure_jitter`` bounds the sensor's own slow drift. Under a sun the conditions place,
27
+ the sensor exposes for that sun's daylight as far as its exposure reaches."""
28
+
29
+ def __init__(self, blur_px: float, exposure_jitter: float, noise_std: float,
30
+ rng: np.random.Generator) -> None:
31
+ self._blur_px = blur_px
32
+ self._exposure_jitter = exposure_jitter
33
+ self._noise_std = noise_std
34
+ self._rng = rng
35
+ self._drifting_exposure_gain = UNCHANGED_EXPOSURE_GAIN
36
+
37
+ def exposed(
38
+ self,
39
+ seen: UInt8Array | Float32Array,
40
+ conditions: FrameConditions,
41
+ ) -> UInt8Array:
42
+ """The 8-bit frame of the picture ``seen``."""
43
+ import cv2
44
+
45
+ blur_px = float(conditions.get("blur_px", self._blur_px))
46
+ noise_std = float(conditions.get("noise_std", self._noise_std))
47
+ exposure_gain = float(conditions.get("exposure_gain", UNCHANGED_EXPOSURE_GAIN))
48
+ rain = float(np.clip(conditions.get("rain", 0.0), 0.0, 1.0))
49
+ if rain > 0:
50
+ blur_px += BLUR_PX_UNDER_FULL_RAIN * rain
51
+ picture = seen
52
+ if blur_px > 0:
53
+ sigma = min(BLUR_SIGMA_LIMIT_PX, blur_px)
54
+ if sigma > BLUR_SEEN_AT_SIGMA_PX:
55
+ picture = cv2.GaussianBlur(picture, (0, 0), sigmaX=float(sigma))
56
+ if "sun_elevation_deg" in conditions:
57
+ exposed_for_the_light = brightening_for(
58
+ daylight(conditions["sun_elevation_deg"])) ** (1.0 / CAMERA_GAMMA)
59
+ picture = np.clip(
60
+ picture.astype(np.float32) * exposed_for_the_light, *EIGHT_BIT_LEVEL_RANGE)
61
+ if self._exposure_jitter > 0:
62
+ self._drifting_exposure_gain = float(np.clip(
63
+ self._drifting_exposure_gain + self._rng.normal(0, EXPOSURE_DRIFT_STEP),
64
+ UNCHANGED_EXPOSURE_GAIN - self._exposure_jitter,
65
+ UNCHANGED_EXPOSURE_GAIN + self._exposure_jitter))
66
+ picture = np.clip(
67
+ picture.astype(np.float32) * self._drifting_exposure_gain, *EIGHT_BIT_LEVEL_RANGE)
68
+ if exposure_gain != UNCHANGED_EXPOSURE_GAIN:
69
+ picture = np.clip(picture.astype(np.float32) * exposure_gain, *EIGHT_BIT_LEVEL_RANGE)
70
+ if noise_std > 0:
71
+ noisy: Float32Array = picture.astype(np.float32)
72
+ noisy += noise_std * self._rng.standard_normal(picture.shape, dtype=np.float32)
73
+ picture = np.clip(noisy, *EIGHT_BIT_LEVEL_RANGE, out=noisy)
74
+ return np.asarray(picture, dtype=np.uint8)
@@ -0,0 +1,26 @@
1
+ """The conditions a frame is drawn under."""
2
+ from __future__ import annotations
3
+
4
+ from typing import TypedDict
5
+
6
+ #: The levels an 8-bit picture holds.
7
+ EIGHT_BIT_LEVEL_RANGE = (0, 255)
8
+ #: A camera's picture is brighter than the light it shows by the light's power of one over this.
9
+ CAMERA_GAMMA = 2.2
10
+
11
+
12
+ class FrameConditions(TypedDict, total=False):
13
+ """The conditions one synthetic camera frame is drawn under: where the sun stands, the
14
+ weather between the ground and the camera, and what the camera's sensor is set or
15
+ commanded to. What is left out is the imagery's own light, clear air or the sensor's own
16
+ setting."""
17
+
18
+ blur_px: float
19
+ noise_std: float
20
+ exposure_gain: float
21
+ visibility_km: float
22
+ fog: float
23
+ rain: float
24
+ cloud: float
25
+ sun_elevation_deg: float
26
+ sun_azimuth_deg: float
@@ -0,0 +1,202 @@
1
+ """Dated imagery: the past releases of Esri World Imagery. Each release holds a picture of the
2
+ whole world, most of it the same picture as the release before, sometimes drawn anew; its
3
+ metadata says when the picture of a place was taken. Unless told otherwise, a world draws the
4
+ newest picture of its ground that was taken on another day than the current release's: maps
5
+ built for navigation are built from the current picture, and a camera that shows the very
6
+ picture a map holds is matched far more easily than a real one."""
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import re
11
+ import urllib.parse
12
+ from collections.abc import Sequence
13
+ from dataclasses import dataclass
14
+ from datetime import UTC, date, datetime
15
+ from typing import cast
16
+
17
+ from .map_tiles import MapTile
18
+ from .settings import CURRENT_RELEASE, ESRI_WAYBACK, OLDER_THAN_CURRENT_RELEASE, EsriWayback
19
+ from .web import Web
20
+ from .world_folder import IMAGERY_ZOOM
21
+
22
+ RELEASES_ADDRESS = (
23
+ "https://s3-us-west-2.amazonaws.com/config.maptiles.arcgis.com/waybackconfig.json")
24
+ _PUBLISHED = re.compile(r"(\d{4})-(\d{2})-(\d{2})")
25
+ # Which map tiles of a block a release holds: a release publishes a place no finer than the
26
+ # picture it holds of it was taken.
27
+ TILES_HELD_ADDRESS = (
28
+ "https://wayback.maptiles.arcgis.com/arcgis/rest/services/World_Imagery/MapServer/tilemap/"
29
+ "{release}/{level}/{row}/{col}/{across}/{down}")
30
+ # A release's metadata has one layer for each zoom, the finest zoom's first.
31
+ METADATA_LAYER_OF_ZOOM_ZERO = 23
32
+ TAKEN_FIELD = "SRC_DATE2"
33
+ CREDIT = "Esri, Vantor, Earthstar Geographics, and the GIS User Community"
34
+ MILLISECONDS_PER_SECOND = 1000.0
35
+
36
+
37
+ class NoOtherPicture(LookupError):
38
+ """The ground has only ever had the picture the current release holds."""
39
+
40
+
41
+ #: A latitude and a longitude, in degrees.
42
+ Place = tuple[float, float]
43
+
44
+
45
+ @dataclass(frozen=True)
46
+ class Release:
47
+ number: int
48
+ published: date
49
+ tile_address: str
50
+ metadata_address: str
51
+
52
+ def address_of(self, tile: MapTile) -> str:
53
+ return (self.tile_address.replace("{level}", str(tile.zoom))
54
+ .replace("{row}", str(tile.y)).replace("{col}", str(tile.x)))
55
+
56
+ def address_of_what_holds(self, latitude_deg: float, longitude_deg: float) -> str:
57
+ """Where the release says which picture it holds of a place, at the imagery's zoom."""
58
+ asked = urllib.parse.urlencode({
59
+ "f": "json", "where": "1=1", "geometry": f"{longitude_deg},{latitude_deg}",
60
+ "geometryType": "esriGeometryPoint", "inSR": 4326,
61
+ "spatialRel": "esriSpatialRelIntersects", "outFields": TAKEN_FIELD,
62
+ "returnGeometry": "false"})
63
+ return (f"{self.metadata_address}/{METADATA_LAYER_OF_ZOOM_ZERO - IMAGERY_ZOOM}"
64
+ f"/query?{asked}")
65
+
66
+
67
+ class DatedImagery:
68
+ def __init__(self, web: Web) -> None:
69
+ self._web = web
70
+ self._releases: list[Release] | None = None
71
+ self._pictures: dict[tuple[int, MapTile], bytes] = {}
72
+ self._taken: dict[tuple[int, Place], date | None] = {}
73
+
74
+ def releases(self) -> list[Release]:
75
+ """Every release, from the oldest to the current one."""
76
+ if self._releases is None:
77
+ listed = cast(dict[str, dict[str, str]], json.loads(
78
+ self._web.fetched(RELEASES_ADDRESS)))
79
+ releases: list[Release] = []
80
+ for number, entry in listed.items():
81
+ published = _PUBLISHED.search(entry["itemTitle"])
82
+ if published is None:
83
+ raise ValueError(f"release {number} does not say when it was published")
84
+ year, month, day = (int(part) for part in published.groups())
85
+ releases.append(Release(int(number), date(year, month, day), entry["itemURL"],
86
+ entry["metadataLayerUrl"]))
87
+ if not releases:
88
+ raise ValueError("the release list is empty")
89
+ self._releases = sorted(
90
+ releases, key=lambda release: (release.published, release.number))
91
+ return self._releases
92
+
93
+ def release(self, number: int) -> Release:
94
+ for release in self.releases():
95
+ if release.number == number:
96
+ return release
97
+ raise ValueError(f"there is no release {number}")
98
+
99
+ def picture(self, release: Release, tile: MapTile) -> bytes:
100
+ """The release's picture of one map tile, as the web serves it."""
101
+ key = (release.number, tile)
102
+ if key not in self._pictures:
103
+ self._pictures[key] = self._web.fetched(release.address_of(tile))
104
+ return self._pictures[key]
105
+
106
+ def holds_every_tile_of(self, release: Release, north_west: MapTile,
107
+ side_tiles: int) -> bool:
108
+ """Whether the release holds a picture of every map tile of the block ``side_tiles``
109
+ by ``side_tiles`` that has ``north_west`` at its corner."""
110
+ held = cast(dict[str, list[int]], json.loads(self._web.fetched(
111
+ TILES_HELD_ADDRESS.format(
112
+ release=release.number, level=north_west.zoom, row=north_west.y,
113
+ col=north_west.x, across=side_tiles, down=side_tiles))))
114
+ return bool(held.get("data")) and all(held["data"])
115
+
116
+ def taken(self, release: Release, latitude_deg: float, longitude_deg: float) -> date | None:
117
+ """The day the release's picture of a place was taken; None where it does not say."""
118
+ key = (release.number, (latitude_deg, longitude_deg))
119
+ if key not in self._taken:
120
+ answer = cast(dict[str, list[dict[str, dict[str, float | None]]]], json.loads(
121
+ self._web.fetched(release.address_of_what_holds(latitude_deg, longitude_deg))))
122
+ features = answer.get("features") or []
123
+ stamp_ms = features[0]["attributes"].get(TAKEN_FIELD) if features else None
124
+ self._taken[key] = None if stamp_ms is None else datetime.fromtimestamp(
125
+ stamp_ms / MILLISECONDS_PER_SECOND, UTC).date()
126
+ return self._taken[key]
127
+
128
+ def newest_release_with_another_picture_of(self, places: Sequence[Place]) -> Release:
129
+ """The newest release whose picture was taken on another day than the current
130
+ release's at every one of ``places`` that has ever had another picture. Releases are
131
+ told apart by when their picture was taken, not by the tiles they serve: a release
132
+ often draws the same picture anew. A place's picture changes from one release to a
133
+ later one and stays, so each place is searched by halves."""
134
+ releases = self.releases()
135
+ current = releases[-1]
136
+ newest_differing: list[int] = []
137
+ for place in places:
138
+ now_taken = self.taken(current, *place)
139
+
140
+ def differs(index: int, place: Place = place,
141
+ now_taken: date | None = now_taken) -> bool:
142
+ then_taken = self.taken(releases[index], *place)
143
+ return then_taken is not None and then_taken != now_taken
144
+
145
+ if now_taken is None or len(releases) < 2 or not differs(0):
146
+ continue
147
+ differing, same = 0, len(releases) - 1
148
+ while same - differing > 1:
149
+ middle = (differing + same) // 2
150
+ if differs(middle):
151
+ differing = middle
152
+ else:
153
+ same = middle
154
+ newest_differing.append(differing)
155
+ if not newest_differing:
156
+ raise NoOtherPicture(
157
+ "no release holds a picture of this ground taken on another day than the "
158
+ "current one's")
159
+ return releases[min(newest_differing)]
160
+
161
+
162
+ class WaybackRelease:
163
+ """The release of Esri World Imagery Wayback a world draws its ground from, as its
164
+ settings choose it for the places along the ground."""
165
+
166
+ provider = ESRI_WAYBACK
167
+
168
+ def __init__(self, asked: EsriWayback, web: Web, places: Sequence[Place]) -> None:
169
+ self._imagery = DatedImagery(web)
170
+ self._places = places
171
+ if asked.release == OLDER_THAN_CURRENT_RELEASE:
172
+ self._release = self._imagery.newest_release_with_another_picture_of(places)
173
+ elif asked.release == CURRENT_RELEASE:
174
+ self._release = self._imagery.releases()[-1]
175
+ else:
176
+ self._release = self._imagery.release(asked.release)
177
+
178
+ def picture(self, tile: MapTile) -> bytes:
179
+ return self._imagery.picture(self._release, tile)
180
+
181
+ def holds_every_tile_of(self, north_west: MapTile, side_tiles: int) -> bool:
182
+ return self._imagery.holds_every_tile_of(self._release, north_west, side_tiles)
183
+
184
+ def described(self) -> str:
185
+ return f"of the release published {self._release.published.isoformat()}"
186
+
187
+ def record(self) -> dict[str, object]:
188
+ return {
189
+ "source": ESRI_WAYBACK,
190
+ "credit": CREDIT,
191
+ "release": self._release.number,
192
+ "published": self._release.published.isoformat(),
193
+ "taken": self._days_taken(self._release),
194
+ "current_picture_taken": self._days_taken(self._imagery.releases()[-1]),
195
+ }
196
+
197
+ def _days_taken(self, release: Release) -> list[str]:
198
+ """The days the release's pictures of the places were taken, each once, oldest
199
+ first."""
200
+ return sorted({
201
+ taken.isoformat() for place in self._places
202
+ if (taken := self._imagery.taken(release, *place)) is not None})