From 67144440c3eef883a470a6809b21f8abd12ad3fc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rafal=20W=C3=B3jcik?= Date: Wed, 18 Nov 2026 15:31:19 +0100 Subject: [PATCH 1/3] Look files up in the upload history by size and fingerprint check_upload_history and upload no longer read whole files to compute MD5s. A file is new if no uploaded file had its size; otherwise it is looked up by a fingerprint: a BLAKE2b hash of its size and of 64 KiB from its start, middle and end. Both commands apply the same rule, so upload skips exactly the files that check_upload_history reports as uploaded. Uploads are recorded by fingerprint; the records by checksum of earlier versions are no longer read. Records of uploads that Mapillary didn't finish are not taken as uploaded, as #956 does for the records by checksum. --- docs/command_reference.md | 22 +- mapillary_tools/fingerprint.py | 64 ++ mapillary_tools/history.py | 242 +++---- mapillary_tools/upload.py | 235 +++--- mapillary_tools/uploader.py | 127 +--- tests/integration/test_history.py | 6 +- tests/integration/test_organization_name.py | 2 +- tests/unit/test_authenticate.py | 2 +- tests/unit/test_check_upload_history.py | 748 ++++++++++++++------ tests/unit/test_fingerprint.py | 98 +++ tests/unit/test_history.py | 357 +++++----- tests/unit/test_uploader.py | 69 -- 12 files changed, 1120 insertions(+), 852 deletions(-) create mode 100644 mapillary_tools/fingerprint.py create mode 100644 tests/unit/test_fingerprint.py diff --git a/docs/command_reference.md b/docs/command_reference.md index 3a5a9702b..8a0205983 100644 --- a/docs/command_reference.md +++ b/docs/command_reference.md @@ -366,13 +366,14 @@ Gotchas: - With no profile yet, it asks you to log in. With several profiles, it asks which one, unless you give `--user_name`. When it cannot prompt (no terminal, or `MAPILLARY_TOOLS_PROMPT_DISABLED=YES`), it fails instead. -- Image sequences, videos and zip files already uploaded from this computer are skipped. Each is compared as a - whole, by a checksum: a sequence with one image added or removed counts as new and is uploaded again, and a - video is recognized by its file alone, even if its track changed. The upload history is kept on this computer - only. `--dry_run` neither reads nor writes it. -- To look files up in the history, `upload` reads each one in full to compute its checksum, with a progress bar. - The checksums are cached in the upload history folder by file path, size and modification time, so the next - run skips uploaded files without reading them. +- Image sequences, videos and zip files already uploaded from this computer are skipped. Files are looked up one + by one: a sequence is skipped when all its images were uploaded, also as part of a larger sequence, and a + sequence with one image added is uploaded whole again. A video or zip file is recognized by its file alone, even + if a video's track changed or the file was renamed. The upload history is kept on this computer only. + `--dry_run` neither reads nor writes it. +- To look a file up, `upload` compares its size with the sizes of the files uploaded before. Only when one + matches does it read the file's fingerprint: 64 KiB from its start, middle and end. Files uploaded with earlier + versions were recorded by checksum instead, so they are not found, and are uploaded once more. - An interrupted upload resumes where it stopped the next time you upload the same files. - `--organization_key` takes a numeric ID. Organization names are 2 to 32 letters, digits, `-` and `_`, starting with a letter, and are case-sensitive. Saving a name again with another ID replaces it. @@ -502,9 +503,10 @@ mapillary_tools check_upload_history IMPORT_PATH [IMPORT_PATH ...] [--desc_path Tells whether the processed image sequences, videos and zip files were uploaded from this computer before. Takes the same import paths and description file as `upload`, and prints a JSON array with one entry per sequence, -video or zip file: its file type, sequence UUID, checksum, file names, `already_uploaded_filenames`, and -`already_uploaded`, which is true only when all its files are in the history. Images are looked up one by one, -also in sequences uploaded before, so it can report as uploaded a sequence that `upload` would upload again. +video or zip file: its file type, sequence UUID, an empty `sequence_md5sum` (no checksum is computed; kept for +compatibility), file names, `already_uploaded_filenames`, and `already_uploaded`, which is true only when all its +files are in the history. Files are looked up as `upload` looks them up, so `upload` skips the entries reported +as uploaded. A file is read only when a file of the same size was uploaded, and then only for its fingerprint. It reads only the local upload history: it needs no login, makes no network requests, and changes nothing. Uploads from another computer, or with `--dry_run`, are not in it. diff --git a/mapillary_tools/fingerprint.py b/mapillary_tools/fingerprint.py new file mode 100644 index 000000000..604944995 --- /dev/null +++ b/mapillary_tools/fingerprint.py @@ -0,0 +1,64 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + +""" +Fingerprints identify files in the upload history without reading them whole. + +A fingerprint is a BLAKE2b hash of the file size and of three blocks of the +file: at the start, in the middle and at the end. A file no larger than the +three blocks is hashed whole. Every block of a compressed image or video +differs from one capture to another, and an MP4 index sits at one end of the +file, so two different captures of the same size do not share a fingerprint +in practice. Computing one takes three small reads, whatever the file size. +""" + +from __future__ import annotations + +import hashlib +import os +import typing as T +from pathlib import Path + +BLOCK_SIZE = 64 * 1024 + +# Hashed along, so that no other hash of the same bytes is taken for a +# fingerprint, and a new way to fingerprint can be told apart +_PERSONALIZATION = b"mly-fingerprint1" + +FINGERPRINT_LENGTH = 32 + + +def fingerprint_file(path: Path) -> str: + """Return the fingerprint of the file, as 32 hexadecimal digits""" + hasher = hashlib.blake2b(digest_size=16, person=_PERSONALIZATION) + with path.open("rb") as fp: + size = os.fstat(fp.fileno()).st_size + hasher.update(size.to_bytes(8, "little")) + if size <= 3 * BLOCK_SIZE: + hasher.update(fp.read()) + else: + for offset in (0, (size - BLOCK_SIZE) // 2, size - BLOCK_SIZE): + fp.seek(offset) + hasher.update(fp.read(BLOCK_SIZE)) + return hasher.hexdigest() + + +def combine_fingerprints(fingerprints: T.Iterable[str]) -> str: + """Return a fingerprint for files taken together, in this order""" + hasher = hashlib.blake2b(digest_size=16, person=_PERSONALIZATION) + for fingerprint in fingerprints: + hasher.update(fingerprint.encode("ascii")) + return hasher.hexdigest() + + +_LOWERCASE_HEXDIGITS = frozenset("0123456789abcdef") + + +def is_fingerprint(value: T.Any) -> bool: + return ( + isinstance(value, str) + and len(value) == FINGERPRINT_LENGTH + and set(value) <= _LOWERCASE_HEXDIGITS + ) diff --git a/mapillary_tools/history.py b/mapillary_tools/history.py index 158044e15..c2d1257c5 100644 --- a/mapillary_tools/history.py +++ b/mapillary_tools/history.py @@ -5,45 +5,76 @@ from __future__ import annotations +import dataclasses import json import logging import os import sqlite3 -import string import threading import time import typing as T from functools import wraps from pathlib import Path -from . import constants, store, types -from .serializer.description import DescriptionJSONSerializer +from . import constants, fingerprint, store JSONDict = T.Dict[str, T.Union[str, int, float, None]] LOG = logging.getLogger(__name__) -def _validate_hexdigits(md5sum: str): - try: - assert set(md5sum).issubset(string.hexdigits) - assert 4 <= len(md5sum) - _ = int(md5sum, 16) - except Exception: - raise ValueError(f"Invalid md5sum {md5sum}") - - -def history_desc_path(md5sum: str) -> Path: - _validate_hexdigits(md5sum) - subfolder = md5sum[:2] - assert subfolder, f"Invalid md5sum {md5sum}" - basename = md5sum[2:] - assert basename, f"Invalid md5sum {md5sum}" - return ( - Path(constants.MAPILLARY_UPLOAD_HISTORY_PATH) - .joinpath(subfolder) - .joinpath(f"{basename}.json") - ) +# Uploaded files are recorded by fingerprint (see fingerprint.py), one record +# per uploaded image sequence, video or zip file, in this folder of the upload +# history. Records written by earlier versions, by checksum, are not read +UPLOADED_FILES_DIR = "fingerprints_v1" + + +@dataclasses.dataclass(frozen=True) +class UploadedFile: + filename: Path + filesize: int + fingerprint: str + + +@dataclasses.dataclass +class UploadedFiles: + """ + The files recorded in the upload history: their sizes, and when each + fingerprint was uploaded (None if not known) + """ + + sizes: set[int] = dataclasses.field(default_factory=set) + uploaded_at: dict[str, float | None] = dataclasses.field(default_factory=dict) + + def find( + self, path: Path, fingerprints: dict[Path, str] | None = None + ) -> str | None: + """ + Return the fingerprint of the file if it was uploaded, or None. The + file is read only when an uploaded file had the same size. Computed + fingerprints are kept in the fingerprints given, by path. + """ + if os.path.getsize(path) not in self.sizes: + return None + file_fingerprint = None if fingerprints is None else fingerprints.get(path) + if file_fingerprint is None: + file_fingerprint = fingerprint.fingerprint_file(path) + if fingerprints is not None: + fingerprints[path] = file_fingerprint + if file_fingerprint not in self.uploaded_at: + return None + return file_fingerprint + + def add(self, files: T.Iterable[UploadedFile], uploaded_at: float | None) -> None: + for file in files: + self.sizes.add(file.filesize) + previous = self.uploaded_at.get(file.fingerprint) + if previous is None or (uploaded_at is not None and previous < uploaded_at): + self.uploaded_at[file.fingerprint] = uploaded_at + + +def _uploaded_files_dir() -> Path: + return Path(constants.MAPILLARY_UPLOAD_HISTORY_PATH).joinpath(UPLOADED_FILES_DIR) def is_unfinished_upload(record: T.Any) -> bool: @@ -64,128 +95,99 @@ def is_unfinished_upload(record: T.Any) -> bool: ) -def read_history_record(md5sum: str) -> None | T.Dict[str, T.Any]: +def read_uploaded_files() -> UploadedFiles | None: """ - Read the upload history record of the checksum, or return None if there - is none, or if it is of an upload that Mapillary did not finish + Read the files recorded in the upload history, in one pass over its + records, or return None if there is no upload history """ if not constants.MAPILLARY_UPLOAD_HISTORY_PATH: return None - path = history_desc_path(md5sum) - - if not path.is_file(): - return None - - with path.open("r") as fp: - try: - record = json.load(fp) - except json.JSONDecodeError as ex: - LOG.error(f"Failed to read upload history {path}: {ex}") - return None - - if is_unfinished_upload(record): - LOG.info( - "Not taken as uploaded: the upload in the history record %s was not finished", - path, - ) - return None - - return record - - -def _normalize_md5sum(value: T.Any) -> str | None: - if not isinstance(value, str) or len(value) != 32: - return None - - try: - _validate_hexdigits(value) - except ValueError: - return None - - return value.lower() - - -def find_uploaded_image_md5s(md5sums: T.Iterable[str]) -> set[str]: - """Find image checksums stored in upload-history descriptions. - - Upload history is sharded by the checksum of a whole sequence, so checking - whether images came from a previously uploaded larger sequence requires a - bounded scan of the records. Only requested checksums are retained, and the - scan stops as soon as all of them have been found. - """ - if not constants.MAPILLARY_UPLOAD_HISTORY_PATH: - return set() - - wanted = { - normalized - for md5sum in md5sums - if (normalized := _normalize_md5sum(md5sum)) is not None - } - if not wanted: - return set() - - root = Path(constants.MAPILLARY_UPLOAD_HISTORY_PATH) + uploaded = UploadedFiles() + root = _uploaded_files_dir() if not root.is_dir(): - return set() + return uploaded - found: set[str] = set() try: - history_paths = root.glob("*/*.json") - for path in history_paths: + for path in root.glob("*/*.json"): try: with path.open("r", encoding="utf-8") as fp: record = json.load(fp) except (OSError, UnicodeError, json.JSONDecodeError) as ex: LOG.warning("Failed to read upload history %s: %s", path, ex) continue - - if not isinstance(record, dict): - LOG.warning("Invalid upload history record %s", path) - continue - if is_unfinished_upload(record): + LOG.info( + "Not taken as uploaded: the upload in the history record %s was not finished", + path, + ) continue - - descs = record.get("descs") - if not isinstance(descs, list): - continue - - for desc in descs: - if not isinstance(desc, dict): - continue - if desc.get("filetype") != types.FileType.IMAGE.value: - continue - md5sum = _normalize_md5sum(desc.get("md5sum")) - if md5sum in wanted: - found.add(md5sum) - - if found == wanted: - break + if not _add_uploaded_files_record(uploaded, record): + LOG.warning("Invalid upload history record %s", path) except OSError as ex: LOG.warning("Failed to scan upload history %s: %s", root, ex) - return found + return uploaded -def write_history( - md5sum: str, - params: JSONDict, - summary: JSONDict, - metadatas: T.Sequence[types.Metadata] | None = None, +def _add_uploaded_files_record(uploaded: UploadedFiles, record: T.Any) -> bool: + if not isinstance(record, dict) or not isinstance(record.get("files"), list): + return False + + summary = record.get("summary") + uploaded_at = summary.get("upload_end_time") if isinstance(summary, dict) else None + if isinstance(uploaded_at, bool) or not isinstance(uploaded_at, (int, float)): + uploaded_at = None + + files: list[UploadedFile] = [] + for entry in record["files"]: + if not isinstance(entry, dict): + return False + filesize = entry.get("filesize") + file_fingerprint = entry.get("fingerprint") + if ( + isinstance(filesize, bool) + or not isinstance(filesize, int) + or filesize < 0 + or not fingerprint.is_fingerprint(file_fingerprint) + ): + return False + files.append( + UploadedFile( + Path(str(entry.get("filename"))), + filesize, + T.cast(str, file_fingerprint), + ) + ) + + uploaded.add(files, uploaded_at) + return True + + +def write_uploaded_files( + files: T.Sequence[UploadedFile], params: JSONDict, summary: JSONDict ) -> None: - if not constants.MAPILLARY_UPLOAD_HISTORY_PATH: + """Record the files of an uploaded image sequence, video or zip file""" + if not constants.MAPILLARY_UPLOAD_HISTORY_PATH or not files: return - path = history_desc_path(md5sum) + key = fingerprint.combine_fingerprints(file.fingerprint for file in files) + path = _uploaded_files_dir().joinpath(key[:2]).joinpath(f"{key[2:]}.json") LOG.debug("Writing upload history: %s", path) - path.resolve().parent.mkdir(parents=True, exist_ok=True) - history: dict[str, T.Any] = {"params": params, "summary": summary} - if metadatas is not None: - history["descs"] = [ - DescriptionJSONSerializer.as_desc(metadata) for metadata in metadatas - ] + path.parent.mkdir(parents=True, exist_ok=True) + record = { + "params": params, + "summary": summary, + "files": [ + { + "filename": os.path.abspath(file.filename), + "filesize": file.filesize, + "fingerprint": file.fingerprint, + } + for file in files + ], + } with open(path, "w") as fp: - fp.write(json.dumps(history)) + fp.write(json.dumps(record)) def _retry_on_database_lock_error(fn): diff --git a/mapillary_tools/upload.py b/mapillary_tools/upload.py index 456fd59d8..25ebd0b09 100644 --- a/mapillary_tools/upload.py +++ b/mapillary_tools/upload.py @@ -23,6 +23,7 @@ config, constants, exceptions, + fingerprint, history, http, ipc, @@ -77,8 +78,6 @@ def upload( emitter = uploader.EventEmitter() - checksum_cache: history.PersistentCache | None = None - # Check duplications first if not _is_history_disabled(dry_run): upload_run_params: JSONDict = { @@ -92,11 +91,6 @@ def upload( _setup_history( emitter, upload_run_params, metadatas, reupload=reupload, nofinish=nofinish ) - # Cache the checksums that the history is looked up by, so that files - # already uploaded are not read again to be skipped - checksum_cache = uploader.create_checksum_cache( - Path(constants.MAPILLARY_UPLOAD_HISTORY_PATH).joinpath("checksum_cache") - ) # Set up tdqm _setup_tdqm(emitter) @@ -121,7 +115,7 @@ def upload( mly_uploader = uploader.Uploader(upload_options, emitter=emitter) results = _gen_upload_everything( - mly_uploader, metadatas, import_paths, skip_subfolders, checksum_cache + mly_uploader, metadatas, import_paths, skip_subfolders ) upload_successes = 0 @@ -177,105 +171,68 @@ def _history_check_result( } -def _has_upload_history_record(md5sum: str) -> bool: - try: - record = history.read_history_record(md5sum) - except (OSError, UnicodeError) as ex: - LOG.warning("Failed to read upload history %s: %s", md5sum, ex) - return False - return isinstance(record, dict) - - def check_upload_history( import_path: Path | T.Sequence[Path], desc_path: str | None = None, skip_subfolders: bool = False, _metadatas_from_process: T.Sequence[types.MetadataOrError] | None = None, ) -> list[UploadHistoryCheckResult]: - """Return upload-history matches without uploading or changing history.""" + """ + Return upload-history matches without uploading or changing history. + + Files are looked up as upload looks them up: a file was uploaded if an + uploaded file had the same size and fingerprint (see fingerprint.py). A + file is read only when an uploaded file had its size, and then only for + its fingerprint. No checksum is computed: sequence_md5sum is empty, and + kept for the callers that expect it. + """ import_paths = _normalize_import_paths(import_path) metadatas = _load_descs(_metadatas_from_process, import_paths, desc_path) candidates = _find_upload_candidates( metadatas, import_paths, skip_subfolders=skip_subfolders ) + uploaded = history.read_uploaded_files() + fingerprints: dict[Path, str] = {} + + def find_uploaded(filenames: T.Sequence[Path]) -> list[Path]: + if uploaded is None: + return [] + return [ + filename + for filename in filenames + if uploaded.find(filename, fingerprints) is not None + ] results: list[UploadHistoryCheckResult] = [] - image_results_to_check: list[ - tuple[UploadHistoryCheckResult, list[types.ImageMetadata]] - ] = [] - image_md5sums_to_check: set[str] = set() for sequence_uuid, sequence in types.group_and_sort_images( candidates.image_metadatas ).items(): - sequence_md5sum = types.update_sequence_md5sum(sequence) filenames = [metadata.filename for metadata in sequence] - sequence_already_uploaded = _has_upload_history_record(sequence_md5sum) - if sequence_already_uploaded: - already_uploaded_filenames = filenames - else: - already_uploaded_filenames = [] - for metadata in sequence: - assert isinstance(metadata.md5sum, str), "md5sum should be calculated" - image_md5sums_to_check.add(metadata.md5sum) - - result = _history_check_result( - types.FileType.IMAGE, - sequence_uuid, - sequence_md5sum, - filenames, - already_uploaded_filenames, - ) - results.append(result) - - if not sequence_already_uploaded: - image_results_to_check.append((result, sequence)) - - uploaded_image_md5sums = history.find_uploaded_image_md5s(image_md5sums_to_check) - for result, sequence in image_results_to_check: - already_uploaded_filename_strings: list[str] = [] - for metadata in sequence: - assert isinstance(metadata.md5sum, str), "md5sum should be calculated" - if metadata.md5sum.lower() in uploaded_image_md5sums: - already_uploaded_filename_strings.append(str(metadata.filename)) - result["already_uploaded_filenames"] = already_uploaded_filename_strings - result["already_uploaded"] = len(already_uploaded_filename_strings) == len( - result["filenames"] + results.append( + _history_check_result( + types.FileType.IMAGE, + sequence_uuid, + "", + filenames, + find_uploaded(filenames), + ) ) for video_metadata in sorted( candidates.video_metadatas, key=lambda metadata: metadata.filename ): - video_metadata.update_md5sum() - assert isinstance(video_metadata.md5sum, str), "md5sum should be calculated" filenames = [video_metadata.filename] - already_uploaded_filenames = ( - filenames if _has_upload_history_record(video_metadata.md5sum) else [] - ) results.append( _history_check_result( - video_metadata.filetype, - None, - video_metadata.md5sum, - filenames, - already_uploaded_filenames, + video_metadata.filetype, None, "", filenames, find_uploaded(filenames) ) ) for zip_path in sorted(candidates.zip_paths): - with zip_path.open("rb") as zip_fp: - sequence_md5sum = uploader.ZipUploader._extract_sequence_md5sum(zip_fp) - filenames = [zip_path] - already_uploaded_filenames = ( - filenames if _has_upload_history_record(sequence_md5sum) else [] - ) results.append( _history_check_result( - types.FileType.ZIP, - None, - sequence_md5sum, - filenames, - already_uploaded_filenames, + types.FileType.ZIP, None, "", [zip_path], find_uploaded([zip_path]) ) ) @@ -346,47 +303,20 @@ def _setup_history( reupload: bool, nofinish: bool, ) -> None: - @emitter.on("upload_start") - def check_duplication(payload: uploader.Progress): - md5sum = payload.get("sequence_md5sum") - assert md5sum is not None, f"md5sum has to be set for {payload}" - - record = history.read_history_record(md5sum) - - if record is not None: - history_desc_path = history.history_desc_path(md5sum) - uploaded_at = record.get("summary", {}).get("upload_end_time", None) - - upload_name = uploader.Uploader._upload_name(payload) - - if reupload: - if uploaded_at is not None: - LOG.info( - f"Reuploading {upload_name}, despite being uploaded {humanize.naturaldelta(time.time() - uploaded_at)} ago ({time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(uploaded_at))})" - ) - else: - LOG.info( - f"Reuploading {upload_name}, despite already being uploaded (see {history_desc_path})" - ) - else: - if uploaded_at is not None: - msg = f"Skipping {upload_name}, already uploaded {humanize.naturaldelta(time.time() - uploaded_at)} ago ({time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(uploaded_at))})" - else: - msg = f"Skipping {upload_name}, already uploaded (see {history_desc_path})" - raise UploadedAlready(msg) - - @emitter.on("upload_finished") - def write_history(payload: uploader.Progress): - if nofinish: - return + """ + Skip the image sequences, videos and zip files found in the upload + history, and record the uploaded ones. A sequence is found when each of + its images is: an uploaded file had the same size and fingerprint (see + fingerprint.py), so that a file whose size no uploaded file had is not read. + """ + uploaded = history.read_uploaded_files() or history.UploadedFiles() + # Computed to look the files up, and reused to record them + fingerprints: dict[Path, str] = {} + def uploaded_filenames(payload: uploader.Progress) -> list[Path]: + """The images of the sequence, or the video or zip file""" sequence_uuid = payload.get("sequence_uuid") - md5sum = payload.get("sequence_md5sum") - assert md5sum is not None, f"md5sum has to be set for {payload}" - - if sequence_uuid is None: - sequence = None - else: + if sequence_uuid is not None: sequence = [ metadata for metadata in metadatas @@ -394,13 +324,77 @@ def write_history(payload: uploader.Progress): and metadata.MAPSequenceUUID == sequence_uuid ] sequence.sort(key=lambda metadata: metadata.sort_key()) + return [metadata.filename for metadata in sequence] + import_path = payload.get("import_path") + assert import_path is not None, f"import_path has to be set for {payload}" + return [Path(import_path)] + + def skip_or_reupload(payload: uploader.Progress, uploaded_at: float | None) -> None: + upload_name = uploader.Uploader._upload_name(payload) + if uploaded_at is not None: + ago = f"{humanize.naturaldelta(time.time() - uploaded_at)} ago ({time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(uploaded_at))})" + if reupload: + LOG.info(f"Reuploading {upload_name}, despite being uploaded {ago}") + else: + raise UploadedAlready(f"Skipping {upload_name}, already uploaded {ago}") + elif reupload: + LOG.info(f"Reuploading {upload_name}, despite already being uploaded") + else: + raise UploadedAlready(f"Skipping {upload_name}, already uploaded") + + @emitter.on("upload_start") + def check_duplication(payload: uploader.Progress): + found: list[str] = [] + for filename in uploaded_filenames(payload): + try: + file_fingerprint = uploaded.find(filename, fingerprints) + except OSError as ex: + LOG.warning("Failed to look %s up in upload history: %s", filename, ex) + return + if file_fingerprint is None: + return + found.append(file_fingerprint) + + if found: + uploaded_ats = [ + uploaded_at + for file_fingerprint in found + if (uploaded_at := uploaded.uploaded_at.get(file_fingerprint)) + is not None + ] + skip_or_reupload(payload, max(uploaded_ats, default=None)) + + @emitter.on("upload_finished") + def write_history(payload: uploader.Progress): + if nofinish: + return try: - history.write_history( - md5sum, upload_run_params, T.cast(JSONDict, payload), sequence + files = [ + history.UploadedFile( + filename, + utils.get_file_size(filename), + fingerprints.get(filename) + or fingerprint.fingerprint_file(filename), + ) + for filename in uploaded_filenames(payload) + ] + history.write_uploaded_files( + files, upload_run_params, T.cast(JSONDict, payload) ) except OSError: - LOG.warning("Error writing upload history %s", md5sum, exc_info=True) + LOG.warning( + "Error writing upload history for %s", + uploader.Uploader._upload_name(payload), + exc_info=True, + ) + return + + uploaded_at = payload.get("upload_end_time") + uploaded.add( + files, + uploaded_at if isinstance(uploaded_at, (int, float)) else None, + ) def _setup_tdqm(emitter: uploader.EventEmitter) -> None: @@ -758,7 +752,6 @@ def _gen_upload_everything( metadatas: T.Sequence[types.Metadata], import_paths: T.Sequence[Path], skip_subfolders: bool, - checksum_cache: history.PersistentCache | None = None, ): candidates = _find_upload_candidates( metadatas, import_paths, skip_subfolders=skip_subfolders @@ -766,15 +759,13 @@ def _gen_upload_everything( # Upload images image_uploader = uploader.ImageSequenceUploader( - mly_uploader.upload_options, - emitter=mly_uploader.emitter, - checksum_cache=checksum_cache, + mly_uploader.upload_options, emitter=mly_uploader.emitter ) yield from image_uploader.upload_images(candidates.image_metadatas) # Upload videos yield from uploader.VideoUploader.upload_videos( - mly_uploader, candidates.video_metadatas, checksum_cache=checksum_cache + mly_uploader, candidates.video_metadatas ) # Upload zip files diff --git a/mapillary_tools/uploader.py b/mapillary_tools/uploader.py index 2d14107f7..883828d2c 100644 --- a/mapillary_tools/uploader.py +++ b/mapillary_tools/uploader.py @@ -15,7 +15,6 @@ import logging import os import queue -import sqlite3 import struct import sys import tempfile @@ -33,7 +32,6 @@ from typing_extensions import Required import requests -from tqdm import tqdm from . import ( api_v4, @@ -60,10 +58,6 @@ LOG = logging.getLogger(__name__) -# Only bounds the size of the checksum cache: a checksum stays valid while its -# file is unchanged -CHECKSUM_CACHE_EXPIRES_IN = 3600 * 24 * 30 - @dataclasses.dataclass(frozen=True) class UploadOptions: @@ -121,8 +115,9 @@ class UploaderProgress(T.TypedDict, total=True): class SequenceProgress(T.TypedDict, total=False): """Progress data at sequence level""" - # Used to check if it is uploaded or not - sequence_md5sum: Required[str] + # Used to check if a zip file is uploaded or not. Images and videos are + # looked up in the upload history by file fingerprint instead + sequence_md5sum: str # Used to resume from the previous upload, # so it has to an unique identifier (hash) of the upload content @@ -248,32 +243,17 @@ def upload_videos( cls, mly_uploader: Uploader, video_metadatas: T.Sequence[types.VideoMetadata], - checksum_cache: history.PersistentCache | None = None, ) -> T.Generator[tuple[types.VideoMetadata, UploadResult], None, None]: # If upload in a random order, then interrupted uploads has a higher chance to expire. # Therefore sort videos to make sure interrupted uploads are resumed as early as possible sorted_video_metadatas = sorted(video_metadatas, key=lambda m: m.filename) for idx, video_metadata in enumerate(sorted_video_metadatas): - LOG.debug(f"Checksum for video {video_metadata.filename}...") - try: - _update_md5sums( - [video_metadata], - desc=f"Checksumming {video_metadata.filetype.value.upper()} {video_metadata.filename.name} ({idx + 1}/{len(sorted_video_metadatas)})", - checksum_cache=checksum_cache, - ) - except Exception as ex: - yield video_metadata, UploadResult(error=ex) - continue - - assert isinstance(video_metadata.md5sum, str), "md5sum should be updated" - progress: SequenceProgress = { "total_sequence_count": len(sorted_video_metadatas), "sequence_idx": idx, "file_type": video_metadata.filetype.value, "import_path": str(video_metadata.filename), - "sequence_md5sum": video_metadata.md5sum, } try: @@ -602,11 +582,9 @@ def __init__( self, upload_options: UploadOptions, emitter: EventEmitter, - checksum_cache: history.PersistentCache | None = None, ): self.upload_options = upload_options self.emitter = emitter - self.checksum_cache = checksum_cache # Create a single shared SingleImageUploader instance that will be used across all uploads cache = _maybe_create_persistent_cache_instance(self.upload_options) self.cached_image_uploader = CachedImageUploader( @@ -619,21 +597,12 @@ def upload_images( sequences = types.group_and_sort_images(image_metadatas) for sequence_idx, (sequence_uuid, sequence) in enumerate(sequences.items()): - LOG.debug(f"Checksum for image sequence {sequence_uuid}...") - _update_md5sums( - sequence, - desc=f"Checksumming IMAGE ({sequence_idx + 1}/{len(sequences)})", - checksum_cache=self.checksum_cache, - ) - sequence_md5sum = types.update_sequence_md5sum(sequence) - sequence_progress: SequenceProgress = { "sequence_idx": sequence_idx, "total_sequence_count": len(sequences), "sequence_image_count": len(sequence), "sequence_uuid": sequence_uuid, "file_type": types.FileType.IMAGE.value, - "sequence_md5sum": sequence_md5sum, } try: @@ -914,9 +883,6 @@ def upload_stream( if progress is None: progress = {} - if session_key is None: - session_key = self._gen_session_key(fp, progress) - fp.seek(0, io.SEEK_END) entity_size = fp.tell() @@ -925,8 +891,17 @@ def upload_stream( progress["retries"] = 0 progress["begin_offset"] = None + # Emitted before the stream is read for the session key, so that an + # upload found in the upload history is skipped without reading it self.emitter.emit("upload_start", progress) + if session_key is None: + try: + session_key = self._gen_session_key(fp, progress) + except BaseException: # Include KeyboardInterrupt + self.emitter.emit("upload_failed", progress) + raise + while True: try: if self.user_session is not None: @@ -1146,84 +1121,6 @@ def _gen_session_key(self, fp: T.IO[bytes], progress: dict[str, T.Any]) -> str: return session_key -def create_checksum_cache(path: Path) -> history.PersistentCache | None: - """ - Open the cache of file checksums at the path and clear its expired - entries, or return None if it can not be used. - """ - try: - path.parent.mkdir(parents=True, exist_ok=True) - cache = history.PersistentCache(str(path.resolve())) - cache.clear_expired() - except (OSError, sqlite3.Error) as ex: - LOG.warning("Not caching checksums in %s: %s", path, ex) - return None - return cache - - -def _checksum_cache_key(path: Path) -> str: - # A file whose path, size and modification time are unchanged is taken - # as unchanged, as rsync does by default - stat = path.stat() - return json.dumps([os.path.abspath(path), stat.st_size, stat.st_mtime_ns]) - - -def _update_md5sums( - metadatas: T.Sequence[types.ImageMetadata] | T.Sequence[types.VideoMetadata], - desc: str, - checksum_cache: history.PersistentCache | None = None, -) -> None: - """ - Compute the checksums that the metadatas miss, showing the progress, as - reading the files takes long for large sequences or slow drives, before - the upload history is checked. - - With a checksum cache, take the checksums of the files from it, and cache - the checksums computed, so that uploading the files again, as when they - were already uploaded, does not read them again. - """ - missing = [metadata for metadata in metadatas if metadata.md5sum is None] - if not missing: - return - - cache_keys: dict[Path, str] = {} - if checksum_cache is not None: - cache_keys = { - metadata.filename: _checksum_cache_key(metadata.filename) - for metadata in missing - } - cached = checksum_cache.get_many(cache_keys.values()) - for metadata in missing: - metadata.md5sum = cached.get(cache_keys[metadata.filename]) - missing = [metadata for metadata in missing if metadata.md5sum is None] - if not missing: - return - - with tqdm( - total=sum(utils.get_file_size(metadata.filename) for metadata in missing), - desc=desc, - unit="B", - unit_scale=True, - unit_divisor=1024, - disable=LOG.isEnabledFor(logging.DEBUG), - ) as pbar: - for metadata in missing: - with metadata.filename.open("rb") as fp: - metadata.md5sum = utils.md5sum_fp(fp, progress=pbar.update).hexdigest() - - if checksum_cache is not None: - try: - checksum_cache.set_many( - { - cache_keys[metadata.filename]: T.cast(str, metadata.md5sum) - for metadata in missing - }, - expires_in=CHECKSUM_CACHE_EXPIRES_IN, - ) - except sqlite3.Error as ex: - LOG.warning("Failed to cache checksums: %s", ex) - - def _validate_metadatas(metadatas: T.Sequence[types.ImageMetadata]): for metadata in metadatas: validate_image_desc(DescriptionJSONSerializer.as_desc(metadata)) diff --git a/tests/integration/test_history.py b/tests/integration/test_history.py index f30b9e494..7f430bc35 100644 --- a/tests/integration/test_history.py +++ b/tests/integration/test_history.py @@ -62,8 +62,7 @@ def test_check_upload_history_is_read_only_and_matches_upload( sequence for sequence in image_descs_by_sequence.values() if 1 < len(sequence) ) - # A smaller current sequence has a different sequence checksum, but each - # image is still identifiable in the stored descriptions of the old upload. + # Each image of a smaller current sequence is found by its fingerprint. subset_descs = uploaded_sequence[:1] subset_desc_path = setup_data.join("uploaded-subset-description.json") subset_desc_path.write(json.dumps(subset_descs)) @@ -75,9 +74,6 @@ def test_check_upload_history_is_read_only_and_matches_upload( ] ) assert len(subset_results) == 1 - assert subset_results[0]["sequence_md5sum"] not in { - result["sequence_md5sum"] for result in results - } assert subset_results[0]["already_uploaded_filenames"] == [ desc["filename"] for desc in subset_descs ] diff --git a/tests/integration/test_organization_name.py b/tests/integration/test_organization_name.py index 2e0a43f6c..49d6444da 100644 --- a/tests/integration/test_organization_name.py +++ b/tests/integration/test_organization_name.py @@ -79,7 +79,7 @@ def _history_organization_keys() -> list: history_path = Path(os.environ["MAPILLARY_UPLOAD_HISTORY_PATH"]) return [ json.loads(p.read_text())["params"]["organization_key"] - for p in history_path.glob("*/*.json") + for p in history_path.glob("**/*.json") ] diff --git a/tests/unit/test_authenticate.py b/tests/unit/test_authenticate.py index 76315db93..a5b4ee1b1 100644 --- a/tests/unit/test_authenticate.py +++ b/tests/unit/test_authenticate.py @@ -834,7 +834,7 @@ def test_upload_history_records_the_saved_organization( ) commands.main() - [record] = [json.loads(p.read_text()) for p in history_path.glob("*/*.json")] + [record] = [json.loads(p.read_text()) for p in history_path.glob("**/*.json")] assert record["params"]["organization_key"] == "1234567890" assert fetched == ["1234567890", "1234567890"] diff --git a/tests/unit/test_check_upload_history.py b/tests/unit/test_check_upload_history.py index ef69cf127..583275897 100644 --- a/tests/unit/test_check_upload_history.py +++ b/tests/unit/test_check_upload_history.py @@ -3,16 +3,33 @@ # This source code is licensed under the BSD license found in the # LICENSE file in the root directory of this source tree. +from __future__ import annotations + import hashlib import json +import os +import shutil import sys import zipfile from pathlib import Path -from mapillary_tools import constants, history, types, upload +from mapillary_tools import ( + constants, + fingerprint, + geo, + history, + types, + upload, + uploader, + utils, +) from mapillary_tools.commands import __main__ as commands from mapillary_tools.serializer.description import DescriptionJSONSerializer +from .test_uploader import _write_empty_mp4 + +TEST_IMAGE_DIR = Path(__file__).parent.parent.joinpath("data", "images") + def _image(filename: Path, sequence_uuid: str, capture_time: float): return types.ImageMetadata( @@ -26,6 +43,67 @@ def _image(filename: Path, sequence_uuid: str, capture_time: float): ) +def _video(filename: Path) -> types.VideoMetadata: + return types.VideoMetadata( + filename=filename, filetype=types.FileType.CAMM, points=[] + ) + + +def _record_upload(*paths: Path, uploaded_at: float | None = 123.0) -> None: + """Record the files as one uploaded video or image sequence, as upload does""" + history.write_uploaded_files( + [ + history.UploadedFile( + path, path.stat().st_size, fingerprint.fingerprint_file(path) + ) + for path in paths + ], + {"version": "test"}, + {"upload_end_time": uploaded_at}, + ) + + +def _count_reads(monkeypatch) -> list[str]: + """ + Record the name of each file read for its fingerprint, and of each file + read in full for a checksum (prefixed with "md5:") + """ + reads: list[str] = [] + fingerprint_file = fingerprint.fingerprint_file + md5sum_fp = utils.md5sum_fp + + def _fingerprint_file(path): + reads.append(path.name) + return fingerprint_file(path) + + def _md5sum_fp(fp, *args, **kwargs): + reads.append(f"md5:{os.path.basename(getattr(fp, 'name', ''))}") + return md5sum_fp(fp, *args, **kwargs) + + monkeypatch.setattr(fingerprint, "fingerprint_file", _fingerprint_file) + monkeypatch.setattr(utils, "md5sum_fp", _md5sum_fp) + return reads + + +def _history_files(history_path: Path) -> dict[Path, bytes]: + return { + path: path.read_bytes() for path in history_path.rglob("*") if path.is_file() + } + + +def _result(file_type, sequence_uuid, filenames, uploaded_filenames): + return { + "file_type": file_type, + "sequence_uuid": sequence_uuid, + "sequence_md5sum": "", + "filenames": [str(filename) for filename in filenames], + "already_uploaded_filenames": [ + str(filename) for filename in uploaded_filenames + ], + "already_uploaded": list(filenames) == list(uploaded_filenames), + } + + def test_check_upload_history_for_images_and_video(tmp_path, monkeypatch): history_path = tmp_path / "history" monkeypatch.setattr(constants, "MAPILLARY_UPLOAD_HISTORY_PATH", str(history_path)) @@ -36,327 +114,321 @@ def test_check_upload_history_for_images_and_video(tmp_path, monkeypatch): first_image_path.write_bytes(b"first image") second_image_path.write_bytes(b"second image") video_path.write_bytes(b"video") + images = [first_image_path, second_image_path] metadatas = [ _image(second_image_path, "sequence", 2.0), _image(first_image_path, "sequence", 1.0), - types.VideoMetadata( - filename=video_path, - filetype=types.FileType.CAMM, - points=[], - ), + _video(video_path), ] + reads = _count_reads(monkeypatch) results = upload.check_upload_history( - [first_image_path, second_image_path, video_path], - _metadatas_from_process=metadatas, + [*images, video_path], _metadatas_from_process=metadatas ) - first_md5 = hashlib.md5(first_image_path.read_bytes()).hexdigest() - second_md5 = hashlib.md5(second_image_path.read_bytes()).hexdigest() - expected_sequence_md5 = hashlib.md5(f"{first_md5}{second_md5}".encode()).hexdigest() - expected_video_md5 = hashlib.md5(video_path.read_bytes()).hexdigest() - assert results == [ - { - "file_type": "image", - "sequence_uuid": "sequence", - "sequence_md5sum": expected_sequence_md5, - "filenames": [str(first_image_path), str(second_image_path)], - "already_uploaded_filenames": [], - "already_uploaded": False, - }, - { - "file_type": "camm", - "sequence_uuid": None, - "sequence_md5sum": expected_video_md5, - "filenames": [str(video_path)], - "already_uploaded_filenames": [], - "already_uploaded": False, - }, + _result("image", "sequence", images, []), + _result("camm", None, [video_path], []), ] + # Nothing was uploaded: no file is read, no history is created + assert reads == [] + assert not history_path.exists() - history.write_history( - expected_sequence_md5, - {"version": "test"}, - {"upload_end_time": 123.0}, - ) - history_record_path = history.history_desc_path(expected_sequence_md5) - history_record = history_record_path.read_bytes() + _record_upload(*images) + history_files = _history_files(history_path) + reads.clear() results = upload.check_upload_history( - [first_image_path, second_image_path, video_path], - _metadatas_from_process=metadatas, + [*images, video_path], _metadatas_from_process=metadatas ) - assert results[0]["already_uploaded"] is True - assert results[0]["already_uploaded_filenames"] == [ - str(first_image_path), - str(second_image_path), + assert results == [ + _result("image", "sequence", images, images), + _result("camm", None, [video_path], []), ] - assert results[1]["already_uploaded"] is False - assert results[1]["already_uploaded_filenames"] == [] - assert history_record_path.read_bytes() == history_record + # Only the files of uploaded sizes are read, for their fingerprints + assert sorted(reads) == ["first.jpg", "second.jpg"] + # The upload history is only read + assert _history_files(history_path) == history_files - history.write_history( - expected_video_md5, - {"version": "test"}, - {"upload_end_time": 456.0}, - ) + _record_upload(video_path, uploaded_at=456.0) results = upload.check_upload_history( - [first_image_path, second_image_path, video_path], - _metadatas_from_process=metadatas, + [*images, video_path], _metadatas_from_process=metadatas ) - assert results[0]["already_uploaded"] is True - assert results[1]["already_uploaded"] is True - assert results[1]["already_uploaded_filenames"] == [str(video_path)] - - -def test_check_upload_history_for_zip(tmp_path, monkeypatch): - history_path = tmp_path / "history" - monkeypatch.setattr(constants, "MAPILLARY_UPLOAD_HISTORY_PATH", str(history_path)) - - zip_path = tmp_path / "sequence.zip" - sequence_md5sum = "1" * 32 - with zipfile.ZipFile(zip_path, "w") as zip_file: - zip_file.comment = json.dumps({"sequence_md5sum": sequence_md5sum}).encode() - - results = upload.check_upload_history( - [zip_path], - _metadatas_from_process=[], - ) assert results == [ - { - "file_type": "zip", - "sequence_uuid": None, - "sequence_md5sum": sequence_md5sum, - "filenames": [str(zip_path)], - "already_uploaded_filenames": [], - "already_uploaded": False, - } + _result("image", "sequence", images, images), + _result("camm", None, [video_path], [video_path]), ] - history.write_history( - sequence_md5sum, - {"version": "test"}, - {"upload_end_time": 123.0}, + +def test_check_upload_history_tells_apart_files_of_the_same_size(tmp_path, monkeypatch): + monkeypatch.setattr( + constants, "MAPILLARY_UPLOAD_HISTORY_PATH", str(tmp_path / "history") ) - history_record_path = history.history_desc_path(sequence_md5sum) - history_record = history_record_path.read_bytes() + uploaded_path = tmp_path / "uploaded.mp4" + uploaded_path.write_bytes(b"video A") + _record_upload(uploaded_path) + same_size_path = tmp_path / "same-size.mp4" + same_size_path.write_bytes(b"video B") + other_size_path = tmp_path / "other-size.mp4" + other_size_path.write_bytes(b"another video") + reads = _count_reads(monkeypatch) results = upload.check_upload_history( - [zip_path], - _metadatas_from_process=[], + [same_size_path, other_size_path], + _metadatas_from_process=[_video(same_size_path), _video(other_size_path)], ) - assert results[0]["already_uploaded_filenames"] == [str(zip_path)] - assert results[0]["already_uploaded"] is True - assert history_record_path.read_bytes() == history_record + assert results == [ + _result("camm", None, [other_size_path], []), + _result("camm", None, [same_size_path], []), + ] + assert reads == ["same-size.mp4"] -def test_check_upload_history_skips_the_apple_double_file_of_a_zip( - tmp_path, monkeypatch, caplog -): - """ - The AppleDouble file (._NAME) that macOS writes beside a zip file, named - like a zip file but none, was read as one and stopped the run - """ + +def test_check_upload_history_finds_renamed_files(tmp_path, monkeypatch): monkeypatch.setattr( constants, "MAPILLARY_UPLOAD_HISTORY_PATH", str(tmp_path / "history") ) - zip_path = tmp_path / "sequence.zip" - with zipfile.ZipFile(zip_path, "w") as zip_file: - zip_file.comment = json.dumps({"sequence_md5sum": "1" * 32}).encode() - apple_double = tmp_path / "._sequence.zip" - apple_double.write_bytes(b"\x00\x05\x16\x07\x00\x02\x00\x00Mac OS X") + uploaded_path = tmp_path / "GX010001.MP4" + uploaded_path.write_bytes(b"a video") + _record_upload(uploaded_path) + renamed_path = tmp_path / "renamed.mp4" + uploaded_path.rename(renamed_path) - with caplog.at_level("WARNING"): - results = upload.check_upload_history( - [apple_double, zip_path], _metadatas_from_process=[] - ) - - assert [result["filenames"] for result in results] == [[str(zip_path)]] - assert ( - f"Skipping {apple_double}, which is not a supported image or video" - in caplog.text + results = upload.check_upload_history( + [renamed_path], _metadatas_from_process=[_video(renamed_path)] ) + assert results == [_result("camm", None, [renamed_path], [renamed_path])] + def test_check_upload_history_matches_subset_of_uploaded_image_sequence( tmp_path, monkeypatch ): - history_path = tmp_path / "history" - monkeypatch.setattr(constants, "MAPILLARY_UPLOAD_HISTORY_PATH", str(history_path)) - + monkeypatch.setattr( + constants, "MAPILLARY_UPLOAD_HISTORY_PATH", str(tmp_path / "history") + ) first_image_path = tmp_path / "first.jpg" second_image_path = tmp_path / "second.jpg" + old_extra_path = tmp_path / "old-extra.jpg" first_image_path.write_bytes(b"first image") second_image_path.write_bytes(b"second image") - current_sequence = [ - _image(first_image_path, "current-sequence", 1.0), - _image(second_image_path, "current-sequence", 2.0), - ] - types.update_sequence_md5sum(current_sequence) - - old_extra = _image(tmp_path / "old-extra.jpg", "old-sequence", 0.0) - old_extra.md5sum = hashlib.md5(b"old extra").hexdigest() - uploaded_sequence = [old_extra, *current_sequence] - history.write_history( - "1" * 32, - {"version": "test"}, - {"upload_end_time": 123.0}, - uploaded_sequence, - ) + old_extra_path.write_bytes(b"an image uploaded with them") + # Uploaded in a larger sequence + _record_upload(old_extra_path, first_image_path, second_image_path) results = upload.check_upload_history( [first_image_path, second_image_path], - _metadatas_from_process=current_sequence, + _metadatas_from_process=[ + _image(first_image_path, "current-sequence", 1.0), + _image(second_image_path, "current-sequence", 2.0), + ], ) - assert len(results) == 1 - assert results[0]["sequence_md5sum"] != "1" * 32 - assert results[0]["already_uploaded_filenames"] == [ - str(first_image_path), - str(second_image_path), - ] - assert results[0]["already_uploaded"] is True + images = [first_image_path, second_image_path] + assert results == [_result("image", "current-sequence", images, images)] def test_check_upload_history_reports_mixed_uploaded_image_subset( tmp_path, monkeypatch ): - history_path = tmp_path / "history" - monkeypatch.setattr(constants, "MAPILLARY_UPLOAD_HISTORY_PATH", str(history_path)) - + monkeypatch.setattr( + constants, "MAPILLARY_UPLOAD_HISTORY_PATH", str(tmp_path / "history") + ) first_image_path = tmp_path / "first.jpg" second_image_path = tmp_path / "second.jpg" first_image_path.write_bytes(b"first image") second_image_path.write_bytes(b"second image") - current_sequence = [ - _image(first_image_path, "current-sequence", 1.0), - _image(second_image_path, "current-sequence", 2.0), - ] - types.update_sequence_md5sum(current_sequence) - - # The matching video checksum must not be mistaken for an uploaded image. - matching_video = types.VideoMetadata( - filename=tmp_path / "old-video.mp4", - filetype=types.FileType.CAMM, - points=[], - md5sum=current_sequence[1].md5sum, - ) - history.write_history( - "2" * 32, - {"version": "test"}, - {"upload_end_time": 123.0}, - [current_sequence[0], matching_video], - ) + _record_upload(first_image_path) results = upload.check_upload_history( [first_image_path, second_image_path], - _metadatas_from_process=current_sequence, + _metadatas_from_process=[ + _image(first_image_path, "current-sequence", 1.0), + _image(second_image_path, "current-sequence", 2.0), + ], ) - assert results[0]["already_uploaded_filenames"] == [str(first_image_path)] - assert results[0]["already_uploaded"] is False + assert results == [ + _result( + "image", + "current-sequence", + [first_image_path, second_image_path], + [first_image_path], + ) + ] -def test_check_upload_history_skips_malformed_records_and_preserves_file_order( - tmp_path, monkeypatch +def test_check_upload_history_skips_invalid_records_and_preserves_file_order( + tmp_path, monkeypatch, caplog ): history_path = tmp_path / "history" monkeypatch.setattr(constants, "MAPILLARY_UPLOAD_HISTORY_PATH", str(history_path)) image_paths = [tmp_path / f"image-{index}.jpg" for index in range(3)] for index, image_path in enumerate(image_paths): - image_path.write_bytes(f"image {index}".encode()) - current_sequence = [ - _image(image_path, "current-sequence", float(index)) - for index, image_path in enumerate(image_paths) - ] - types.update_sequence_md5sum(current_sequence) - - malformed_records = { - history_path / "00" / "invalid-json.json": b"{", - history_path / "01" / "invalid-record.json": b"[]", - history_path / "02" / "invalid-descriptions.json": json.dumps( - { - "descs": [ - None, - {"filetype": "image", "md5sum": 123}, - {"filetype": "image", "md5sum": "not-an-md5"}, - ] - } + image_path.write_bytes(f"image {index}".encode() * (index + 1)) + root = history_path / history.UPLOADED_FILES_DIR + invalid_records = { + root / "00" / "invalid-json.json": b"{", + root / "01" / "not-utf8.json": b"\xff", + root / "02" / "invalid-record.json": b"[]", + root / "03" / "invalid-files.json": json.dumps( + {"files": [None, {"filesize": 7, "fingerprint": "not one"}]} ).encode(), } - for record_path, contents in malformed_records.items(): + for record_path, contents in invalid_records.items(): record_path.parent.mkdir(parents=True, exist_ok=True) record_path.write_bytes(contents) + # Recorded in another order + _record_upload(image_paths[2], image_paths[0]) + history_files = _history_files(history_path) + + with caplog.at_level("WARNING"): + results = upload.check_upload_history( + image_paths, + _metadatas_from_process=[ + _image(image_path, "current-sequence", float(index)) + for index, image_path in enumerate(image_paths) + ], + ) + + assert results == [ + _result( + "image", + "current-sequence", + image_paths, + [image_paths[0], image_paths[2]], + ) + ] + for record_path in invalid_records: + assert record_path.name in caplog.text + assert _history_files(history_path) == history_files + + +def _write_checksum_record(history_path: Path, md5sum: str, record: dict) -> None: + """Write an upload history record as earlier versions did, by checksum""" + path = history_path / md5sum[:2] / f"{md5sum[2:]}.json" + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(record)) - valid_record_path = history_path / "03" / "valid.json" - valid_record_path.parent.mkdir(parents=True) - valid_record_path.write_text( - json.dumps( - { - "descs": [ - { - "filetype": "image", - "md5sum": current_sequence[2].md5sum.upper(), - }, - { - "filetype": "video", - "md5sum": current_sequence[1].md5sum, - }, - { - "filetype": "image", - "md5sum": current_sequence[0].md5sum.upper(), - }, - ] - } - ), - encoding="utf-8", + +def test_check_upload_history_does_not_use_records_by_checksum(tmp_path, monkeypatch): + """ + Files recorded by checksum, before uploads were recorded by fingerprint, + are not found: they would be uploaded again + """ + history_path = tmp_path / "history" + monkeypatch.setattr(constants, "MAPILLARY_UPLOAD_HISTORY_PATH", str(history_path)) + image_path = tmp_path / "image.jpg" + image_path.write_bytes(b"image") + video_path = tmp_path / "video.mp4" + video_path.write_bytes(b"video") + zip_path = tmp_path / "sequence.zip" + with zipfile.ZipFile(zip_path, "w") as zip_file: + zip_file.comment = json.dumps({"sequence_md5sum": "1" * 32}).encode() + image_md5sum = hashlib.md5(b"image").hexdigest() + _write_checksum_record( + history_path, + hashlib.md5(image_md5sum.encode()).hexdigest(), + { + "summary": {"upload_end_time": 1.0}, + "descs": [ + { + "filename": str(image_path), + "filetype": "image", + "md5sum": image_md5sum, + "filesize": 5, + } + ], + }, ) - history_snapshot = { - path: path.read_bytes() for path in history_path.glob("*/*.json") - } + _write_checksum_record( + history_path, hashlib.md5(b"video").hexdigest(), {"summary": {}} + ) + _write_checksum_record(history_path, "1" * 32, {"summary": {}}) + reads = _count_reads(monkeypatch) results = upload.check_upload_history( - image_paths, - _metadatas_from_process=current_sequence, + [image_path, video_path, zip_path], + _metadatas_from_process=[ + _image(image_path, "sequence", 1.0), + _video(video_path), + ], ) - assert len(results) == 1 - assert results[0]["already_uploaded_filenames"] == [ - str(image_paths[0]), - str(image_paths[2]), + assert results == [ + _result("image", "sequence", [image_path], []), + _result("camm", None, [video_path], []), + _result("zip", None, [zip_path], []), ] - assert results[0]["already_uploaded"] is False - assert { - path: path.read_bytes() for path in history_path.glob("*/*.json") - } == history_snapshot + assert reads == [] -def test_check_upload_history_treats_corrupt_record_as_not_uploaded( - tmp_path, monkeypatch -): +def test_check_upload_history_without_history(tmp_path, monkeypatch): + monkeypatch.setattr(constants, "MAPILLARY_UPLOAD_HISTORY_PATH", "") + monkeypatch.chdir(tmp_path) + video_path = tmp_path / "video.mp4" + video_path.write_bytes(b"video") + reads = _count_reads(monkeypatch) + + results = upload.check_upload_history( + [video_path], _metadatas_from_process=[_video(video_path)] + ) + + assert results == [_result("camm", None, [video_path], [])] + assert reads == [] + assert [path.name for path in tmp_path.iterdir()] == ["video.mp4"] + + +def test_check_upload_history_for_zip(tmp_path, monkeypatch): history_path = tmp_path / "history" monkeypatch.setattr(constants, "MAPILLARY_UPLOAD_HISTORY_PATH", str(history_path)) - image_path = tmp_path / "image.jpg" - image_path.write_bytes(b"image") - metadata = _image(image_path, "sequence", 1.0) - sequence_md5sum = types.update_sequence_md5sum([metadata]) - history_record_path = history.history_desc_path(sequence_md5sum) - history_record_path.parent.mkdir(parents=True) - history_record_path.write_bytes(b"\xff") + zip_path = tmp_path / "sequence.zip" + with zipfile.ZipFile(zip_path, "w") as zip_file: + zip_file.comment = json.dumps({"sequence_md5sum": "1" * 32}).encode() - results = upload.check_upload_history( - [image_path], - _metadatas_from_process=[metadata], + results = upload.check_upload_history([zip_path], _metadatas_from_process=[]) + assert results == [_result("zip", None, [zip_path], [])] + + _record_upload(zip_path) + history_files = _history_files(history_path) + + results = upload.check_upload_history([zip_path], _metadatas_from_process=[]) + assert results == [_result("zip", None, [zip_path], [zip_path])] + assert _history_files(history_path) == history_files + + +def test_check_upload_history_skips_the_apple_double_file_of_a_zip( + tmp_path, monkeypatch, caplog +): + """ + The AppleDouble file (._NAME) that macOS writes beside a zip file, named + like a zip file but none, was read as one and stopped the run + """ + monkeypatch.setattr( + constants, "MAPILLARY_UPLOAD_HISTORY_PATH", str(tmp_path / "history") ) + zip_path = tmp_path / "sequence.zip" + with zipfile.ZipFile(zip_path, "w") as zip_file: + zip_file.comment = json.dumps({"sequence_md5sum": "1" * 32}).encode() + apple_double = tmp_path / "._sequence.zip" + apple_double.write_bytes(b"\x00\x05\x16\x07\x00\x02\x00\x00Mac OS X") - assert results[0]["already_uploaded"] is False - assert results[0]["already_uploaded_filenames"] == [] + with caplog.at_level("WARNING"): + results = upload.check_upload_history( + [apple_double, zip_path], _metadatas_from_process=[] + ) + + assert [result["filenames"] for result in results] == [[str(zip_path)]] + assert ( + f"Skipping {apple_double}, which is not a supported image or video" + in caplog.text + ) def test_check_upload_history_command_outputs_json_without_authentication( @@ -391,3 +463,215 @@ def test_check_upload_history_command_outputs_json_without_authentication( assert results[0]["filenames"] == [str(image_path)] assert results[0]["already_uploaded_filenames"] == [] assert results[0]["already_uploaded"] is False + + +def _setup_dry_run_upload(tmp_path: Path, monkeypatch) -> tuple[Path, Path]: + history_path = tmp_path / "history" + upload_path = tmp_path / "uploads" + upload_path.mkdir() + monkeypatch.setattr(constants, "MAPILLARY_UPLOAD_HISTORY_PATH", str(history_path)) + monkeypatch.setattr(constants, "MAPILLARY__ENABLE_UPLOAD_HISTORY_FOR_DRY_RUN", True) + monkeypatch.setenv("MAPILLARY_UPLOAD_ENDPOINT", str(upload_path)) + monkeypatch.setenv( + "MAPILLARY_TOOLS_UPLOAD_CACHE_DIR", str(tmp_path / "upload_cache") + ) + return history_path, upload_path + + +def _uploaded_files(upload_path: Path) -> list[str]: + return sorted(path.name for path in upload_path.iterdir() if path.is_file()) + + +def test_upload_records_images_and_skips_them_the_next_time( + tmp_path, monkeypatch, caplog +): + history_path, upload_path = _setup_dry_run_upload(tmp_path, monkeypatch) + image_dir = tmp_path / "images" + image_dir.mkdir() + image_paths = [] + for name in ["DSC00001.JPG", "DSC00497.JPG"]: + shutil.copy(TEST_IMAGE_DIR.joinpath(name), image_dir) + image_paths.append(image_dir.joinpath(name)) + + def _metadatas() -> list[types.Metadata]: + return [ + types.ImageMetadata( + filename=image_path, + lat=58.5927694 + idx * 0.0001, + lon=16.1840944, + alt=None, + angle=None, + time=1613222681.0 + idx, + MAPSequenceUUID="sequence", + filesize=image_path.stat().st_size, + ) + for idx, image_path in enumerate(image_paths) + ] + + reads = _count_reads(monkeypatch) + upload.upload( + image_dir, + {"user_upload_token": "YOUR_USER_ACCESS_TOKEN"}, + num_upload_workers=1, + _metadatas_from_process=_metadatas(), + dry_run=True, + ) + + assert _uploaded_files(upload_path) + # No image is read in full for a checksum, only for its fingerprint + # when recorded + assert not [read for read in reads if read.startswith("md5:DSC")] + [record_path] = history_path.glob(f"{history.UPLOADED_FILES_DIR}/*/*.json") + record = json.loads(record_path.read_text()) + assert [ + (entry["filename"], entry["filesize"], entry["fingerprint"]) + for entry in record["files"] + ] == [ + ( + os.path.abspath(image_path), + image_path.stat().st_size, + fingerprint.fingerprint_file(image_path), + ) + for image_path in image_paths + ] + assert isinstance(record["summary"]["upload_end_time"], float) + + # check_upload_history agrees with upload + [result] = upload.check_upload_history( + image_dir, _metadatas_from_process=_metadatas() + ) + assert result["already_uploaded"] is True + + for name in _uploaded_files(upload_path): + upload_path.joinpath(name).unlink() + caplog.clear() + upload.upload( + image_dir, + {"user_upload_token": "YOUR_USER_ACCESS_TOKEN"}, + num_upload_workers=1, + _metadatas_from_process=_metadatas(), + dry_run=True, + ) + + assert _uploaded_files(upload_path) == [] + assert ( + "UploadedAlready: Skipping sequence_sequence, already uploaded" in caplog.text + ) + + +def test_upload_skips_an_uploaded_video_without_reading_it_for_the_session_key( + tmp_path, monkeypatch, caplog +): + _, upload_path = _setup_dry_run_upload(tmp_path, monkeypatch) + video_dir = tmp_path / "videos" + video_dir.mkdir() + video_path = video_dir / "video.mp4" + _write_empty_mp4(video_path, 60000) + + def _metadatas() -> list[types.Metadata]: + return [ + types.VideoMetadata( + video_path, + types.FileType.VIDEO, + points=[ + geo.Point(time=0.0, lat=1, lon=1, alt=None, angle=None), + geo.Point(time=1.0, lat=1.0001, lon=1, alt=None, angle=None), + ], + ) + ] + + session_keys: list[str | None] = [] + gen_session_key = uploader.Uploader._gen_session_key + + def _gen_session_key(self, fp, progress): + session_keys.append(progress.get("import_path")) + return gen_session_key(self, fp, progress) + + monkeypatch.setattr(uploader.Uploader, "_gen_session_key", _gen_session_key) + reads = _count_reads(monkeypatch) + + def _upload(reupload: bool = False): + upload.upload( + video_dir, + {"user_upload_token": "YOUR_USER_ACCESS_TOKEN"}, + num_upload_workers=1, + _metadatas_from_process=_metadatas(), + reupload=reupload, + dry_run=True, + ) + + _upload() + assert session_keys == [str(video_path)] + # The video is read in full once, for the session key: not for a checksum + assert [read for read in reads if read.startswith("md5:")] == ["md5:"] + assert _uploaded_files(upload_path) + + for name in _uploaded_files(upload_path): + upload_path.joinpath(name).unlink() + caplog.clear() + _upload() + + assert session_keys == [str(video_path)] + assert _uploaded_files(upload_path) == [] + assert "UploadedAlready: Skipping video.mp4, already uploaded" in caplog.text + + caplog.clear() + _upload(reupload=True) + + assert session_keys == [str(video_path), str(video_path)] + assert _uploaded_files(upload_path) + assert "Reuploading video.mp4, despite being uploaded" in caplog.text + + +def test_upload_records_a_zip_file_and_skips_it_the_next_time( + tmp_path, monkeypatch, caplog +): + history_path, upload_path = _setup_dry_run_upload(tmp_path, monkeypatch) + image_dir = tmp_path / "images" + image_dir.mkdir() + shutil.copy(TEST_IMAGE_DIR.joinpath("DSC00001.JPG"), image_dir) + image_path = image_dir.joinpath("DSC00001.JPG") + zip_dir = tmp_path / "zips" + uploader.ZipUploader.zip_images( + [ + types.ImageMetadata( + filename=image_path, + lat=58.5927694, + lon=16.1840944, + alt=None, + angle=None, + time=1613222681.0, + MAPSequenceUUID="sequence", + filesize=image_path.stat().st_size, + ) + ], + zip_dir, + ) + [zip_path] = zip_dir.glob("*.zip") + + def _upload(): + upload.upload( + zip_dir, + {"user_upload_token": "YOUR_USER_ACCESS_TOKEN"}, + num_upload_workers=1, + _metadatas_from_process=[], + dry_run=True, + ) + + _upload() + assert _uploaded_files(upload_path) + [record_path] = history_path.glob(f"{history.UPLOADED_FILES_DIR}/*/*.json") + assert [ + entry["filename"] for entry in json.loads(record_path.read_text())["files"] + ] == [os.path.abspath(zip_path)] + assert upload.check_upload_history(zip_dir, _metadatas_from_process=[]) == [ + _result("zip", None, [zip_path], [zip_path]) + ] + + for name in _uploaded_files(upload_path): + upload_path.joinpath(name).unlink() + caplog.clear() + _upload() + + assert _uploaded_files(upload_path) == [] + assert f"UploadedAlready: Skipping {zip_path.name}, already uploaded" in caplog.text diff --git a/tests/unit/test_fingerprint.py b/tests/unit/test_fingerprint.py new file mode 100644 index 000000000..1c9a2dc62 --- /dev/null +++ b/tests/unit/test_fingerprint.py @@ -0,0 +1,98 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the BSD license found in the +# LICENSE file in the root directory of this source tree. + +import hashlib +import os +from pathlib import Path + +import pytest +from mapillary_tools import fingerprint + +BLOCK = fingerprint.BLOCK_SIZE + + +def _write(path: Path, data: bytes) -> Path: + path.write_bytes(data) + return path + + +def _change_byte(path: Path, offset: int) -> None: + data = bytearray(path.read_bytes()) + data[offset] ^= 0xFF + path.write_bytes(bytes(data)) + + +def test_small_file_is_hashed_whole(tmp_path: Path): + path = _write(tmp_path / "small.jpg", os.urandom(3 * BLOCK)) + + expected = hashlib.blake2b(digest_size=16, person=b"mly-fingerprint1") + expected.update((3 * BLOCK).to_bytes(8, "little")) + expected.update(path.read_bytes()) + assert fingerprint.fingerprint_file(path) == expected.hexdigest() + + # Any byte counts + before = fingerprint.fingerprint_file(path) + _change_byte(path, BLOCK + 10) + assert fingerprint.fingerprint_file(path) != before + + +def test_large_file_is_fingerprinted_by_its_start_middle_and_end(tmp_path: Path): + size = 10 * BLOCK + 123 + path = _write(tmp_path / "video.mp4", os.urandom(size)) + original = fingerprint.fingerprint_file(path) + assert fingerprint.is_fingerprint(original) + + middle = (size - BLOCK) // 2 + # Bytes outside the three blocks are not read + for offset in [BLOCK, middle - 1, middle + BLOCK, size - BLOCK - 1]: + _change_byte(path, offset) + assert fingerprint.fingerprint_file(path) == original + _change_byte(path, offset) + + # Bytes in the three blocks are + for offset in [0, BLOCK - 1, middle, middle + BLOCK - 1, size - BLOCK, size - 1]: + _change_byte(path, offset) + assert fingerprint.fingerprint_file(path) != original + _change_byte(path, offset) + + assert fingerprint.fingerprint_file(path) == original + + +def test_the_size_is_part_of_the_fingerprint(tmp_path: Path): + # All three blocks are zeros in both files: only the size differs + path = _write(tmp_path / "video.mp4", bytes(10 * BLOCK)) + longer = _write(tmp_path / "longer.mp4", bytes(10 * BLOCK + 2)) + assert fingerprint.fingerprint_file(path) != fingerprint.fingerprint_file(longer) + + +def test_the_same_bytes_have_the_same_fingerprint(tmp_path: Path): + data = os.urandom(5 * BLOCK) + first = _write(tmp_path / "GX010001.MP4", data) + renamed = _write(tmp_path / "renamed.mp4", data) + assert fingerprint.fingerprint_file(first) == fingerprint.fingerprint_file(renamed) + + +def test_combine_fingerprints_depends_on_the_order(): + first, second = "0" * 32, "f" * 32 + combined = fingerprint.combine_fingerprints([first, second]) + assert fingerprint.is_fingerprint(combined) + assert combined != fingerprint.combine_fingerprints([second, first]) + assert combined == fingerprint.combine_fingerprints([first, second]) + + +@pytest.mark.parametrize( + "value, expected", + [ + ("0123456789abcdef0123456789abcdef", True), + ("0123456789ABCDEF0123456789ABCDEF", False), + ("0123456789abcdef0123456789abcde", False), + ("0x23456789abcdef0123456789abcdef", False), + ("0123456789abcdef_123456789abcdef", False), + (None, False), + (123, False), + ], +) +def test_is_fingerprint(value, expected): + assert fingerprint.is_fingerprint(value) is expected diff --git a/tests/unit/test_history.py b/tests/unit/test_history.py index da659798b..df3365067 100644 --- a/tests/unit/test_history.py +++ b/tests/unit/test_history.py @@ -4,163 +4,168 @@ # LICENSE file in the root directory of this source tree. import json -import tempfile +import os import typing as T from pathlib import Path -from unittest.mock import patch import pytest -from mapillary_tools import constants, history, types, upload - - -class TestValidateHexdigits: - def test_valid_md5sum(self): - # Should not raise - history._validate_hexdigits("abcdef1234567890") - - def test_valid_short_hex(self): - history._validate_hexdigits("abcd") - - def test_too_short_raises(self): - with pytest.raises(ValueError, match="Invalid md5sum"): - history._validate_hexdigits("abc") - - def test_non_hex_raises(self): - with pytest.raises(ValueError, match="Invalid md5sum"): - history._validate_hexdigits("xyz123") - - def test_empty_raises(self): - with pytest.raises(ValueError, match="Invalid md5sum"): - history._validate_hexdigits("") - - -class TestHistoryDescPath: - def test_returns_path_with_subfolder(self): - path = history.history_desc_path("aabbccdd") - assert "aa" in str(path) - assert path.name == "bbccdd.json" - - def test_long_md5sum(self): - md5 = "d41d8cd98f00b204e9800998ecf8427e" - path = history.history_desc_path(md5) - assert path.name == md5[2:] + ".json" - assert path.parent.name == "d4" - - -class TestReadHistoryRecord: - def test_returns_none_when_no_history_path(self): - with patch.object(history.constants, "MAPILLARY_UPLOAD_HISTORY_PATH", ""): - result = history.read_history_record("aabbccdd") - assert result is None - - def test_returns_none_when_file_not_found(self): - with tempfile.TemporaryDirectory() as tmpdir: - with patch.object( - history.constants, - "MAPILLARY_UPLOAD_HISTORY_PATH", - tmpdir, - ): - result = history.read_history_record("aabbccdd") - assert result is None - - def test_reads_valid_history(self): - with tempfile.TemporaryDirectory() as tmpdir: - with patch.object( - history.constants, - "MAPILLARY_UPLOAD_HISTORY_PATH", - tmpdir, - ): - path = history.history_desc_path("aabbccdd") - path.parent.mkdir(parents=True, exist_ok=True) - record = {"params": {"key": "val"}, "summary": {"count": 1}} - with open(path, "w") as fp: - json.dump(record, fp) - - result = history.read_history_record("aabbccdd") - assert result is not None - assert result["params"]["key"] == "val" - - def test_returns_none_on_corrupt_json(self): - with tempfile.TemporaryDirectory() as tmpdir: - with patch.object( - history.constants, - "MAPILLARY_UPLOAD_HISTORY_PATH", - tmpdir, - ): - path = history.history_desc_path("aabbccdd") - path.parent.mkdir(parents=True, exist_ok=True) - with open(path, "w") as fp: - fp.write("not valid json{{{") - - result = history.read_history_record("aabbccdd") - assert result is None - - -class TestWriteHistory: - def test_write_history_creates_file(self): - with tempfile.TemporaryDirectory() as tmpdir: - with patch.object( - history.constants, - "MAPILLARY_UPLOAD_HISTORY_PATH", - tmpdir, - ): - history.write_history( - "aabbccdd", - params={"user": "test"}, - summary={"uploaded": 5}, - ) - path = history.history_desc_path("aabbccdd") - assert path.exists() - with open(path) as fp: - data = json.load(fp) - assert data["params"]["user"] == "test" - assert data["summary"]["uploaded"] == 5 - - def test_write_history_no_path(self): - with patch.object(history.constants, "MAPILLARY_UPLOAD_HISTORY_PATH", ""): - # Should be a no-op - history.write_history("aabbccdd", params={}, summary={}) - - def test_write_history_with_metadatas(self): - with tempfile.TemporaryDirectory() as tmpdir: - with patch.object( - history.constants, - "MAPILLARY_UPLOAD_HISTORY_PATH", - tmpdir, - ): - metadata = types.ImageMetadata( - time=1000.0, - lat=48.0, - lon=11.0, - alt=100.0, - angle=45.0, - filename=Path("img.jpg"), - MAPFilename="img.jpg", - ) - history.write_history( - "aabbccdd", - params={}, - summary={}, - metadatas=[metadata], - ) - path = history.history_desc_path("aabbccdd") - with open(path) as fp: - data = json.load(fp) - assert "descs" in data - assert len(data["descs"]) == 1 +from mapillary_tools import constants, fingerprint, history, types, upload + + +def _uploaded_file(path: Path) -> history.UploadedFile: + return history.UploadedFile( + path, path.stat().st_size, fingerprint.fingerprint_file(path) + ) + + +class TestUploadedFiles: + def test_written_files_are_read_back(self, tmp_path, monkeypatch): + history_path = tmp_path / "history" + monkeypatch.setattr( + history.constants, "MAPILLARY_UPLOAD_HISTORY_PATH", str(history_path) + ) + first = tmp_path / "first.jpg" + first.write_bytes(b"first image") + second = tmp_path / "second.jpg" + second.write_bytes(b"second image, longer") + files = [_uploaded_file(first), _uploaded_file(second)] + + history.write_uploaded_files( + files, {"version": "test"}, {"upload_end_time": 123.0} + ) + + [record_path] = history_path.glob(f"{history.UPLOADED_FILES_DIR}/*/*.json") + record = json.loads(record_path.read_text()) + assert record["params"] == {"version": "test"} + assert record["files"] == [ + { + "filename": os.path.abspath(first), + "filesize": len(b"first image"), + "fingerprint": files[0].fingerprint, + }, + { + "filename": os.path.abspath(second), + "filesize": len(b"second image, longer"), + "fingerprint": files[1].fingerprint, + }, + ] + # No checksum record is written + assert list(history_path.glob("*/*.json")) == [] + + uploaded = history.read_uploaded_files() + assert uploaded is not None + assert uploaded.sizes == {len(b"first image"), len(b"second image, longer")} + assert uploaded.uploaded_at == { + files[0].fingerprint: 123.0, + files[1].fingerprint: 123.0, + } + + def test_find_reads_only_files_of_uploaded_sizes(self, tmp_path, monkeypatch): + uploaded_path = tmp_path / "uploaded.mp4" + uploaded_path.write_bytes(b"video A") + uploaded = history.UploadedFiles() + uploaded.add([_uploaded_file(uploaded_path)], 1.0) + new_size = tmp_path / "new.mp4" + new_size.write_bytes(b"a new video") + same_size = tmp_path / "same-size.mp4" + same_size.write_bytes(b"video B") + + reads: list[str] = [] + fingerprint_file = fingerprint.fingerprint_file + + def _fingerprint_file(path): + reads.append(path.name) + return fingerprint_file(path) + + monkeypatch.setattr(fingerprint, "fingerprint_file", _fingerprint_file) + fingerprints: dict[Path, str] = {} + + assert uploaded.find(new_size, fingerprints) is None + assert reads == [] + assert uploaded.find(same_size, fingerprints) is None + assert uploaded.find(uploaded_path, fingerprints) is not None + assert reads == ["same-size.mp4", "uploaded.mp4"] + # Fingerprints computed are kept + assert uploaded.find(uploaded_path, fingerprints) is not None + assert reads == ["same-size.mp4", "uploaded.mp4"] + assert set(fingerprints) == {same_size, uploaded_path} + + def test_add_keeps_the_latest_upload_time(self): + file = history.UploadedFile(Path("video.mp4"), 1, "0" * 32) + uploaded = history.UploadedFiles() + uploaded.add([file], None) + assert uploaded.uploaded_at == {"0" * 32: None} + uploaded.add([file], 2.0) + uploaded.add([file], 1.0) + assert uploaded.uploaded_at == {"0" * 32: 2.0} + + def test_invalid_records_are_skipped(self, tmp_path, monkeypatch, caplog): + history_path = tmp_path / "history" + monkeypatch.setattr( + history.constants, "MAPILLARY_UPLOAD_HISTORY_PATH", str(history_path) + ) + root = history_path / history.UPLOADED_FILES_DIR + records = { + "00/invalid-json.json": b"{", + "01/not-utf8.json": b"\xff", + "02/not-a-dict.json": b"[]", + "03/no-files.json": json.dumps({"summary": {}}).encode(), + "04/bad-entry.json": json.dumps( + {"files": [{"filesize": "1", "fingerprint": "0" * 32}]} + ).encode(), + "05/bad-fingerprint.json": json.dumps( + {"files": [{"filesize": 1, "fingerprint": "not one"}]} + ).encode(), + "06/valid.json": json.dumps( + { + "summary": {"upload_end_time": "yesterday"}, + "files": [ + {"filename": "a.jpg", "filesize": 7, "fingerprint": "a" * 32} + ], + } + ).encode(), + } + for name, contents in records.items(): + root.joinpath(name).parent.mkdir(parents=True, exist_ok=True) + root.joinpath(name).write_bytes(contents) + + with caplog.at_level("WARNING"): + uploaded = history.read_uploaded_files() + + assert uploaded is not None + assert uploaded.sizes == {7} + assert uploaded.uploaded_at == {"a" * 32: None} + for name in list(records)[:-1]: + assert name.split("/")[1] in caplog.text + + def test_no_history(self, tmp_path, monkeypatch): + monkeypatch.setattr(history.constants, "MAPILLARY_UPLOAD_HISTORY_PATH", "") + monkeypatch.chdir(tmp_path) + assert history.read_uploaded_files() is None + path = tmp_path / "video.mp4" + path.write_bytes(b"video") + history.write_uploaded_files([_uploaded_file(path)], {}, {}) + assert [p.name for p in tmp_path.iterdir()] == ["video.mp4"] + + def test_empty_history(self, tmp_path, monkeypatch): + monkeypatch.setattr( + history.constants, + "MAPILLARY_UPLOAD_HISTORY_PATH", + str(tmp_path / "history"), + ) + uploaded = history.read_uploaded_files() + assert uploaded == history.UploadedFiles() + assert not (tmp_path / "history").exists() TEST_IMAGE_DIR = Path(__file__).parent.parent.joinpath("data", "images") -def _write_record(md5sum: str, summary: dict, descs: T.Optional[list] = None) -> Path: - path = history.history_desc_path(md5sum) - path.parent.mkdir(parents=True, exist_ok=True) - record: dict = {"params": {}, "summary": summary} - if descs is not None: - record["descs"] = descs - path.write_text(json.dumps(record)) - return path +def _write_record(summary: dict, *paths: Path) -> Path: + files = [_uploaded_file(path) for path in paths] + history.write_uploaded_files(files, {}, T.cast(history.JSONDict, summary)) + key = fingerprint.combine_fingerprints(file.fingerprint for file in files) + return history._uploaded_files_dir() / key[:2] / f"{key[2:]}.json" class TestUnfinishedUploads: @@ -174,37 +179,38 @@ def _history_path(self, tmp_path, monkeypatch): constants, "MAPILLARY_UPLOAD_HISTORY_PATH", str(tmp_path / "history") ) - def test_unfinished_record_is_not_read(self): - _write_record("a" * 32, {"cluster_id": None, "upload_end_time": 1.0}) - assert history.read_history_record("a" * 32) is None + def test_unfinished_record_is_not_read(self, tmp_path, caplog): + video_path = tmp_path / "video.mp4" + video_path.write_bytes(b"video") + record_path = _write_record( + {"cluster_id": None, "upload_end_time": 1.0}, video_path + ) + + with caplog.at_level("INFO"): + uploaded = history.read_uploaded_files() + + assert uploaded == history.UploadedFiles() + assert f"the upload in the history record {record_path} was not finished" in ( + caplog.text + ) + assert "Invalid upload history record" not in caplog.text @pytest.mark.parametrize( "summary", [ - # Written before 0.14.0, which added the cluster ID {"upload_end_time": 1.0}, {"cluster_id": "123", "upload_end_time": 1.0}, # Uploaded with --dry_run {"cluster_id": "0", "upload_end_time": 1.0}, ], ) - def test_finished_record_is_read(self, summary: dict): - _write_record("a" * 32, summary) - record = history.read_history_record("a" * 32) - assert record is not None - assert record["summary"] == summary - - def test_find_uploaded_image_md5s_skips_unfinished_records(self): - unfinished_image, finished_image = "b" * 32, "c" * 32 - _write_record( - "a" * 32, - {"cluster_id": None}, - [{"filetype": "image", "md5sum": unfinished_image}], - ) - _write_record("d" * 32, {}, [{"filetype": "image", "md5sum": finished_image}]) - assert history.find_uploaded_image_md5s([unfinished_image, finished_image]) == { - finished_image - } + def test_finished_record_is_read(self, tmp_path, summary: dict): + video_path = tmp_path / "video.mp4" + video_path.write_bytes(b"video") + _write_record(summary, video_path) + uploaded = history.read_uploaded_files() + assert uploaded is not None + assert uploaded.find(video_path) == fingerprint.fingerprint_file(video_path) def test_check_upload_history_ignores_unfinished_records(self, tmp_path): image_paths = [tmp_path / "first.jpg", tmp_path / "second.jpg"] @@ -229,17 +235,12 @@ def check() -> dict: ) return result - sequence_md5sum = check()["sequence_md5sum"] - image_descs = [ - {"filetype": "image", "md5sum": metadata.md5sum} for metadata in metadatas - ] - # Neither the sequence nor its images, also looked up one by one - _write_record(sequence_md5sum, {"cluster_id": None}, image_descs) + _write_record({"cluster_id": None}, *image_paths) result = check() assert result["already_uploaded"] is False assert result["already_uploaded_filenames"] == [] - _write_record(sequence_md5sum, {"cluster_id": "123"}, image_descs) + _write_record({"cluster_id": "123"}, *image_paths) assert check()["already_uploaded"] is True def test_upload_uploads_unfinished_upload_again(self, tmp_path, monkeypatch): @@ -279,7 +280,9 @@ def upload_images() -> None: ) upload_images() - [record_path] = (tmp_path / "history").glob("*/*.json") + [record_path] = (tmp_path / "history").glob( + f"{history.UPLOADED_FILES_DIR}/*/*.json" + ) def rewrite_summary(**summary) -> None: record = json.loads(record_path.read_text()) diff --git a/tests/unit/test_uploader.py b/tests/unit/test_uploader.py index 7f2c4bf97..63d5c5c95 100644 --- a/tests/unit/test_uploader.py +++ b/tests/unit/test_uploader.py @@ -4,8 +4,6 @@ # LICENSE file in the root directory of this source tree. import dataclasses -import hashlib -import os import typing as T from pathlib import Path from unittest.mock import patch @@ -874,70 +872,3 @@ def on_upload_finished(payload): ) assert "entity_size" in start_payload, "upload_start should contain entity_size" assert start_payload["sequence_uuid"] == "event_test_sequence" - - -def test_update_md5sums(tmpdir: py.path.local): - image_path = Path(tmpdir.join("image.jpg")) - image_path.write_bytes(b"image bytes") - other_path = Path(tmpdir.join("other.jpg")) - other_path.write_bytes(b"other bytes") - metadatas = [ - types.ImageMetadata( - filename=image_path, lat=0, lon=0, alt=None, angle=None, time=0 - ), - types.ImageMetadata( - filename=other_path, - lat=0, - lon=0, - alt=None, - angle=None, - time=1, - md5sum="0" * 32, - ), - ] - - uploader._update_md5sums(metadatas, desc="Checksumming IMAGE (1/1)") - - assert metadatas[0].md5sum == hashlib.md5(b"image bytes").hexdigest() - # Checksums given are kept - assert metadatas[1].md5sum == "0" * 32 - - -def test_update_md5sums_with_checksum_cache(tmpdir: py.path.local): - image_path = Path(tmpdir.join("image.jpg")) - image_path.write_bytes(b"image bytes") - other_path = Path(tmpdir.join("other.jpg")) - other_path.write_bytes(b"other bytes") - checksum_cache = uploader.create_checksum_cache( - Path(tmpdir.join("history", "checksum_cache")) - ) - assert checksum_cache is not None - - def _metadatas() -> list[types.ImageMetadata]: - return [ - types.ImageMetadata( - filename=path, lat=0, lon=0, alt=None, angle=None, time=idx - ) - for idx, path in enumerate([image_path, other_path]) - ] - - metadatas = _metadatas() - uploader._update_md5sums(metadatas, desc="", checksum_cache=checksum_cache) - assert [m.md5sum for m in metadatas] == [ - hashlib.md5(b"image bytes").hexdigest(), - hashlib.md5(b"other bytes").hexdigest(), - ] - - # Same size and modification time: taken from the cache, not read again - stat = image_path.stat() - image_path.write_bytes(b"IMAGE BYTES") - os.utime(image_path, ns=(stat.st_atime_ns, stat.st_mtime_ns)) - # Changed size: read again - other_path.write_bytes(b"other bytes, changed") - - metadatas = _metadatas() - uploader._update_md5sums(metadatas, desc="", checksum_cache=checksum_cache) - assert [m.md5sum for m in metadatas] == [ - hashlib.md5(b"image bytes").hexdigest(), - hashlib.md5(b"other bytes, changed").hexdigest(), - ] From 7e61b846ff47e8541e8ae21d21086474dbdda0c2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rafal=20W=C3=B3jcik?= Date: Wed, 18 Nov 2026 16:36:58 +0100 Subject: [PATCH 2/3] Record only the images that upload uploads, and key their progress events Review fixes: - The history step took every image of the description file with the sequence UUID, not the images uploaded: uploading some files of a folder recorded the whole sequence, and an image deleted after process made recording fail, so the sequence was uploaded on every run. upload now finds the files to upload once and records exactly those. - Progress events of images and videos have a non-empty sequence_md5sum again, a key of the file paths, as the Desktop Uploader counts the bytes uploaded by it. - The upload tests that check INFO lines set the log level. - The command reference tells the fingerprint's known limit. --- docs/command_reference.md | 2 + mapillary_tools/fingerprint.py | 3 + mapillary_tools/upload.py | 38 ++++---- mapillary_tools/uploader.py | 24 ++++- tests/unit/test_check_upload_history.py | 124 ++++++++++++++++++++++++ tests/unit/test_uploader.py | 78 ++++++++++++++- 6 files changed, 245 insertions(+), 24 deletions(-) diff --git a/docs/command_reference.md b/docs/command_reference.md index 8a0205983..7ce57fd5e 100644 --- a/docs/command_reference.md +++ b/docs/command_reference.md @@ -374,6 +374,8 @@ Gotchas: - To look a file up, `upload` compares its size with the sizes of the files uploaded before. Only when one matches does it read the file's fingerprint: 64 KiB from its start, middle and end. Files uploaded with earlier versions were recorded by checksum instead, so they are not found, and are uploaded once more. +- A file of the same size as an uploaded file that differs from it only outside these three blocks is taken as + uploaded. Captures from cameras don't differ that way; `--reupload` uploads such a file anyway. - An interrupted upload resumes where it stopped the next time you upload the same files. - `--organization_key` takes a numeric ID. Organization names are 2 to 32 letters, digits, `-` and `_`, starting with a letter, and are case-sensitive. Saving a name again with another ID replaces it. diff --git a/mapillary_tools/fingerprint.py b/mapillary_tools/fingerprint.py index 604944995..0a2668e0a 100644 --- a/mapillary_tools/fingerprint.py +++ b/mapillary_tools/fingerprint.py @@ -12,6 +12,9 @@ differs from one capture to another, and an MP4 index sits at one end of the file, so two different captures of the same size do not share a fingerprint in practice. Computing one takes three small reads, whatever the file size. + +Two files of the same size that differ only outside the three blocks have +the same fingerprint: one is taken as the other in the upload history. """ from __future__ import annotations diff --git a/mapillary_tools/upload.py b/mapillary_tools/upload.py index 25ebd0b09..1a78334af 100644 --- a/mapillary_tools/upload.py +++ b/mapillary_tools/upload.py @@ -74,6 +74,12 @@ def upload( config.UserItemSchemaValidator.validate(user_items) + # The files to upload: the processed files found in the import paths. The + # upload history records these, not every file of the description file + candidates = _find_upload_candidates( + metadatas, import_paths, skip_subfolders=skip_subfolders + ) + # Setup the emitter -- the order matters here emitter = uploader.EventEmitter() @@ -89,7 +95,11 @@ def upload( "run_at": time.time(), } _setup_history( - emitter, upload_run_params, metadatas, reupload=reupload, nofinish=nofinish + emitter, + upload_run_params, + candidates.image_metadatas, + reupload=reupload, + nofinish=nofinish, ) # Set up tdqm @@ -114,9 +124,7 @@ def upload( mly_uploader = uploader.Uploader(upload_options, emitter=emitter) - results = _gen_upload_everything( - mly_uploader, metadatas, import_paths, skip_subfolders - ) + results = _gen_upload_everything(mly_uploader, candidates) upload_successes = 0 upload_errors: list[Exception] = [] @@ -299,7 +307,7 @@ def _is_history_disabled(dry_run: bool) -> bool: def _setup_history( emitter: uploader.EventEmitter, upload_run_params: JSONDict, - metadatas: list[types.Metadata], + image_metadatas: T.Sequence[types.ImageMetadata], reupload: bool, nofinish: bool, ) -> None: @@ -312,19 +320,14 @@ def _setup_history( uploaded = history.read_uploaded_files() or history.UploadedFiles() # Computed to look the files up, and reused to record them fingerprints: dict[Path, str] = {} + # The images that upload uploads, by sequence, as it groups them + sequences = types.group_and_sort_images(image_metadatas) def uploaded_filenames(payload: uploader.Progress) -> list[Path]: """The images of the sequence, or the video or zip file""" sequence_uuid = payload.get("sequence_uuid") if sequence_uuid is not None: - sequence = [ - metadata - for metadata in metadatas - if isinstance(metadata, types.ImageMetadata) - and metadata.MAPSequenceUUID == sequence_uuid - ] - sequence.sort(key=lambda metadata: metadata.sort_key()) - return [metadata.filename for metadata in sequence] + return [metadata.filename for metadata in sequences.get(sequence_uuid, [])] import_path = payload.get("import_path") assert import_path is not None, f"import_path has to be set for {payload}" return [Path(import_path)] @@ -748,15 +751,8 @@ def _find_upload_candidates( def _gen_upload_everything( - mly_uploader: uploader.Uploader, - metadatas: T.Sequence[types.Metadata], - import_paths: T.Sequence[Path], - skip_subfolders: bool, + mly_uploader: uploader.Uploader, candidates: _UploadCandidates ): - candidates = _find_upload_candidates( - metadatas, import_paths, skip_subfolders=skip_subfolders - ) - # Upload images image_uploader = uploader.ImageSequenceUploader( mly_uploader.upload_options, emitter=mly_uploader.emitter diff --git a/mapillary_tools/uploader.py b/mapillary_tools/uploader.py index 883828d2c..7865c5ee4 100644 --- a/mapillary_tools/uploader.py +++ b/mapillary_tools/uploader.py @@ -115,8 +115,10 @@ class UploaderProgress(T.TypedDict, total=True): class SequenceProgress(T.TypedDict, total=False): """Progress data at sequence level""" - # Used to check if a zip file is uploaded or not. Images and videos are - # looked up in the upload history by file fingerprint instead + # Tells the uploads apart in the progress events, also across runs: the + # checksum that a zip file carries, or a key of the file paths of the + # images or video (see upload_key). The upload history doesn't use it: it + # looks files up by fingerprint sequence_md5sum: str # Used to resume from the previous upload, @@ -254,6 +256,7 @@ def upload_videos( "sequence_idx": idx, "file_type": video_metadata.filetype.value, "import_path": str(video_metadata.filename), + "sequence_md5sum": upload_key([video_metadata.filename]), } try: @@ -603,6 +606,9 @@ def upload_images( "sequence_image_count": len(sequence), "sequence_uuid": sequence_uuid, "file_type": types.FileType.IMAGE.value, + "sequence_md5sum": upload_key( + [metadata.filename for metadata in sequence] + ), } try: @@ -1121,6 +1127,20 @@ def _gen_session_key(self, fp: T.IO[bytes], progress: dict[str, T.Any]) -> str: return session_key +def upload_key(paths: T.Iterable[Path]) -> str: + """ + The key of an upload of these files in its progress events: the same files + give the same key, also in another run, so that the progress of an upload + started again is counted once. Computed from the file paths: no file is + read. + """ + hasher = hashlib.blake2b(digest_size=16) + for path in paths: + hasher.update(os.fsencode(os.path.abspath(path))) + hasher.update(b"\0") + return hasher.hexdigest() + + def _validate_metadatas(metadatas: T.Sequence[types.ImageMetadata]): for metadata in metadatas: validate_image_desc(DescriptionJSONSerializer.as_desc(metadata)) diff --git a/tests/unit/test_check_upload_history.py b/tests/unit/test_check_upload_history.py index 583275897..7318ff286 100644 --- a/tests/unit/test_check_upload_history.py +++ b/tests/unit/test_check_upload_history.py @@ -7,6 +7,7 @@ import hashlib import json +import logging import os import shutil import sys @@ -485,6 +486,7 @@ def _uploaded_files(upload_path: Path) -> list[str]: def test_upload_records_images_and_skips_them_the_next_time( tmp_path, monkeypatch, caplog ): + caplog.set_level(logging.INFO) history_path, upload_path = _setup_dry_run_upload(tmp_path, monkeypatch) image_dir = tmp_path / "images" image_dir.mkdir() @@ -562,6 +564,7 @@ def _metadatas() -> list[types.Metadata]: def test_upload_skips_an_uploaded_video_without_reading_it_for_the_session_key( tmp_path, monkeypatch, caplog ): + caplog.set_level(logging.INFO) _, upload_path = _setup_dry_run_upload(tmp_path, monkeypatch) video_dir = tmp_path / "videos" video_dir.mkdir() @@ -626,6 +629,7 @@ def _upload(reupload: bool = False): def test_upload_records_a_zip_file_and_skips_it_the_next_time( tmp_path, monkeypatch, caplog ): + caplog.set_level(logging.INFO) history_path, upload_path = _setup_dry_run_upload(tmp_path, monkeypatch) image_dir = tmp_path / "images" image_dir.mkdir() @@ -675,3 +679,123 @@ def _upload(): assert _uploaded_files(upload_path) == [] assert f"UploadedAlready: Skipping {zip_path.name}, already uploaded" in caplog.text + + +def _distinct_images(image_dir: Path, count: int) -> list[Path]: + """Images of the same size that are different images""" + data = TEST_IMAGE_DIR.joinpath("DSC00001.JPG").read_bytes() + image_paths = [] + for idx in range(count): + image = bytearray(data) + # A byte of the image data + image[-10] = idx + 1 if data[-10] != idx + 1 else idx + 101 + image_path = image_dir / f"IMG_{idx:04d}.jpg" + image_path.write_bytes(bytes(image)) + image_paths.append(image_path) + return image_paths + + +def _image_metadatas(image_paths: list[Path]) -> list[types.Metadata]: + return [ + types.ImageMetadata( + filename=image_path, + lat=58.5927694 + idx * 0.0001, + lon=16.1840944, + alt=None, + angle=None, + time=1613222681.0 + idx, + MAPSequenceUUID="sequence", + filesize=image_path.stat().st_size, + ) + for idx, image_path in enumerate(image_paths) + ] + + +def _upload_images(import_path, image_paths: list[Path]) -> None: + upload.upload( + import_path, + {"user_upload_token": "YOUR_USER_ACCESS_TOKEN"}, + num_upload_workers=1, + _metadatas_from_process=_image_metadatas(image_paths), + dry_run=True, + ) + + +def _recorded_filenames(history_path: Path) -> list[list[str]]: + return [ + [entry["filename"] for entry in json.loads(path.read_text())["files"]] + for path in history_path.glob(f"{history.UPLOADED_FILES_DIR}/*/*.json") + ] + + +def test_upload_records_only_the_images_that_it_uploads(tmp_path, monkeypatch, caplog): + """ + Uploading some of the images of a description file records those, not + the other images of their sequence in it + """ + caplog.set_level(logging.INFO) + history_path, upload_path = _setup_dry_run_upload(tmp_path, monkeypatch) + image_dir = tmp_path / "images" + image_dir.mkdir() + image_paths = _distinct_images(image_dir, 4) + + _upload_images(image_paths[:2], image_paths) + + assert _recorded_filenames(history_path) == [ + [os.path.abspath(image_path) for image_path in image_paths[:2]] + ] + assert upload.check_upload_history( + image_dir, _metadatas_from_process=_image_metadatas(image_paths) + ) == [_result("image", "sequence", image_paths, image_paths[:2])] + + # The other images were not uploaded, so the sequence is uploaded + for name in _uploaded_files(upload_path): + upload_path.joinpath(name).unlink() + caplog.clear() + _upload_images(image_dir, image_paths) + + assert _uploaded_files(upload_path) + assert "UploadedAlready" not in caplog.text + + +def test_upload_records_a_sequence_with_an_image_deleted_after_process( + tmp_path, monkeypatch, caplog +): + """ + An image of the description file that was deleted is not uploaded, nor + recorded: the sequence of the others is, and is skipped the next time + """ + caplog.set_level(logging.INFO) + history_path, upload_path = _setup_dry_run_upload(tmp_path, monkeypatch) + image_dir = tmp_path / "images" + image_dir.mkdir() + image_paths = _distinct_images(image_dir, 3) + metadatas = _image_metadatas(image_paths) + image_paths[1].unlink() + + def _upload(): + upload.upload( + image_dir, + {"user_upload_token": "YOUR_USER_ACCESS_TOKEN"}, + num_upload_workers=1, + _metadatas_from_process=metadatas, + dry_run=True, + ) + + _upload() + + assert _uploaded_files(upload_path) + assert "Error writing upload history" not in caplog.text + assert _recorded_filenames(history_path) == [ + [os.path.abspath(image_paths[0]), os.path.abspath(image_paths[2])] + ] + + for name in _uploaded_files(upload_path): + upload_path.joinpath(name).unlink() + caplog.clear() + _upload() + + assert _uploaded_files(upload_path) == [] + assert ( + "UploadedAlready: Skipping sequence_sequence, already uploaded" in caplog.text + ) diff --git a/tests/unit/test_uploader.py b/tests/unit/test_uploader.py index 63d5c5c95..a578eca12 100644 --- a/tests/unit/test_uploader.py +++ b/tests/unit/test_uploader.py @@ -310,18 +310,28 @@ def test_upload_continues_after_points_too_far_apart( ) ) + emitter = uploader.EventEmitter() + video_events: list[dict] = [] + emitter.on("upload_start")(lambda payload: video_events.append(dict(payload))) + emitter.on("upload_end")(lambda payload: video_events.append(dict(payload))) + results = { metadata.filename.name: result for metadata, result in uploader.VideoUploader.upload_videos( uploader.Uploader( uploader.UploadOptions( {"user_upload_token": "YOUR_USER_ACCESS_TOKEN"}, dry_run=True - ) + ), + emitter=emitter, ), metadatas, ) } assert isinstance(results["a_bad.mp4"].error, uploader.GPSPointsTooFarApartError) + # The video uploaded is keyed by its path in its progress events + assert {payload["sequence_md5sum"] for payload in video_events} == { + uploader.upload_key([video_dir / "b_good.mp4"]) + } assert str(results["a_bad.mp4"].error) == ( "a_bad.mp4: The GPS timestamps of the video jump by 22.1 hours between " "0.000 s and 79740.000 s, more than the uploaded video can store (19.9 " @@ -801,6 +811,72 @@ def test_image_sequence_uploader_multiple_sequences( ) assert result_2.result is not None, "Sequence 2 should have result" + def test_image_sequence_uploader_keys_its_progress_events( + self, setup_unittest_data: py.path.local + ): + """ + Every event of the upload of a sequence carries the same sequence_md5sum, + the key by which progress consumers like the Desktop Uploader count the + bytes uploaded: not only the sequence events, but also the ones of its + images, which carry the image path in import_path + """ + upload_options = uploader.UploadOptions( + {"user_upload_token": "YOUR_USER_ACCESS_TOKEN"}, + upload_cache_path=Path(setup_unittest_data.join("upload_cache")), + dry_run=True, + ) + emitter = uploader.EventEmitter() + events: list[tuple[str, dict]] = [] + for event_name in [ + "upload_start", + "upload_progress", + "upload_end", + "upload_finished", + ]: + emitter.on(event_name)( + lambda payload, name=event_name: events.append((name, dict(payload))) + ) + + data = Path(setup_unittest_data.join("test_exif.jpg")).read_bytes() + image_paths = [] + for idx in range(2): + image = bytearray(data) + image[-10] = idx + 1 if data[-10] != idx + 1 else idx + 101 + image_path = Path(setup_unittest_data.join(f"image_{idx}.jpg")) + image_path.write_bytes(bytes(image)) + image_paths.append(image_path) + image_metadatas = [ + description.DescriptionJSONSerializer.from_desc( + { + "MAPLatitude": 58.5927694, + "MAPLongitude": 16.1840944 + idx * 0.0001, + "MAPCaptureTime": f"2021_02_13_13_24_4{idx}_140", + "filename": str(image_path), + "filetype": "image", + "MAPSequenceUUID": "keyed_sequence", + } + ) + for idx, image_path in enumerate(image_paths) + ] + + results = list( + uploader.ImageSequenceUploader(upload_options, emitter).upload_images( + image_metadatas + ) + ) + + assert [result.error for _, result in results] == [None] + assert sorted( + payload["import_path"] + for name, payload in events + if name == "upload_progress" + ) == sorted(str(image_path) for image_path in image_paths) + # The same images give the same key, also in another run + assert {payload.get("sequence_md5sum") for _, payload in events} == { + uploader.upload_key(image_paths) + } + assert uploader.upload_key(image_paths) != uploader.upload_key(image_paths[:1]) + def test_image_sequence_uploader_event_emission( self, setup_unittest_data: py.path.local ): From 5bb3696dc17e9d6410a233eb521641fbb1f6ab92 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rafal=20W=C3=B3jcik?= Date: Thu, 19 Nov 2026 00:36:16 -0800 Subject: [PATCH 3/3] Take upload times out of range in upload history records as not known A record with an upload_end_time that can't be shown as a local time, like 1e30 or Infinity in a hand-edited record, made upload fail when it skipped a file of that record. Such times are now taken as not known, like times that are not numbers. --- mapillary_tools/history.py | 11 ++++++++++- tests/unit/test_history.py | 29 +++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/mapillary_tools/history.py b/mapillary_tools/history.py index c2d1257c5..5f46a5cef 100644 --- a/mapillary_tools/history.py +++ b/mapillary_tools/history.py @@ -28,6 +28,10 @@ # history. Records written by earlier versions, by checksum, are not read UPLOADED_FILES_DIR = "fingerprints_v1" +# Later upload times are not taken: 3000-01-01, which every platform shows as +# a local time +_MAX_UPLOADED_AT = 32503680000 + @dataclasses.dataclass(frozen=True) class UploadedFile: @@ -136,7 +140,12 @@ def _add_uploaded_files_record(uploaded: UploadedFiles, record: T.Any) -> bool: summary = record.get("summary") uploaded_at = summary.get("upload_end_time") if isinstance(summary, dict) else None - if isinstance(uploaded_at, bool) or not isinstance(uploaded_at, (int, float)): + if ( + isinstance(uploaded_at, bool) + or not isinstance(uploaded_at, (int, float)) + # Also not NaN + or not 0 <= uploaded_at <= _MAX_UPLOADED_AT + ): uploaded_at = None files: list[UploadedFile] = [] diff --git a/tests/unit/test_history.py b/tests/unit/test_history.py index df3365067..2ed080d12 100644 --- a/tests/unit/test_history.py +++ b/tests/unit/test_history.py @@ -138,6 +138,35 @@ def test_invalid_records_are_skipped(self, tmp_path, monkeypatch, caplog): for name in list(records)[:-1]: assert name.split("/")[1] in caplog.text + @pytest.mark.parametrize( + "upload_end_time", + ["yesterday", True, -1, 10**30, 10**400, float("inf"), float("nan")], + ) + def test_upload_times_out_of_range_are_not_known( + self, tmp_path, monkeypatch, upload_end_time + ): + history_path = tmp_path / "history" + monkeypatch.setattr( + history.constants, "MAPILLARY_UPLOAD_HISTORY_PATH", str(history_path) + ) + record = history_path / history.UPLOADED_FILES_DIR / "00" / "record.json" + record.parent.mkdir(parents=True) + record.write_text( + json.dumps( + { + "summary": {"upload_end_time": upload_end_time}, + "files": [ + {"filename": "a.jpg", "filesize": 7, "fingerprint": "a" * 32} + ], + } + ) + ) + + uploaded = history.read_uploaded_files() + + assert uploaded is not None + assert uploaded.uploaded_at == {"a" * 32: None} + def test_no_history(self, tmp_path, monkeypatch): monkeypatch.setattr(history.constants, "MAPILLARY_UPLOAD_HISTORY_PATH", "") monkeypatch.chdir(tmp_path)