OSXPhotos python API#
- class osxphotos.AlbumInfo(db=None, uuid=None)[source]#
Info about a specific Album, contains all the details about the album including folders, photos, etc.
- property folder_list#
return hierarchical list of folders the album is contained in as list of FolderInfo objects in form [“Top level folder”, “sub folder 1”, “sub folder 2”, …] returns empty list if album is not in any folders
- property folder_names#
return hierarchical list of folders the album is contained in the folder list is in form: [“Top level folder”, “sub folder 1”, “sub folder 2”, …] returns empty list if album is not in any folders
- property parent#
returns FolderInfo object for parent folder or None if no parent (e.g. top-level album)
- property photos#
return list of photos contained in album sorted in same sort order as Photos
- property sort_order#
return sort order of album
- property title#
return title / name of album
- class osxphotos.CommentInfo(datetime: datetime.datetime, user: str, ismine: bool, text: str)[source]#
Class for shared photo comments
- class osxphotos.ExifInfo(flash_fired: bool, iso: int, metering_mode: int, sample_rate: int, track_format: int, white_balance: int, aperture: float, bit_rate: float, duration: float, exposure_bias: float, focal_length: float, fps: float, latitude: float, longitude: float, shutter_speed: float, camera_make: str, camera_model: str, codec: str, lens_model: str)[source]#
EXIF info associated with a photo from the Photos library
- class osxphotos.ExifTool(filepath, exiftool=None, overwrite=True, flags=None)[source]#
Basic exiftool interface for reading and writing EXIF tags
- addvalues(tag, *values)[source]#
- Add one or more value(s) to tag
If more than one value is passed, each value will be added to the tag
- Parameters
tag – str; tag to set
*values – str; one or more values to set
- Returns
True if success otherwise False
If error generated by exiftool, returns False and sets self.error to error string If warning generated by exiftool, returns True (unless there was also an error) and sets self.warning to warning string If called in context manager, returns True (execution is delayed until exiting context manager)
- Notes: exiftool may add duplicate values for some tags so the caller must ensure
the values being added are not already in the EXIF data For some tags, such as IPTC:Keywords, this will add a new value to the list of keywords, but for others, such as EXIF:ISO, this will literally add a value to the existing value. It’s up to the caller to know what exiftool will do for each tag If setvalue called before addvalues, exiftool does not appear to add duplicates, but if addvalues called without first calling setvalue, exiftool will add duplicate values
- asdict(tag_groups=True, normalized=False)[source]#
return dictionary of all EXIF tags and values from exiftool returns empty dict if no tags
- Parameters
tag_groups – if True (default), dict keys have tag groups, e.g. “IPTC:Keywords”; if False, drops groups from keys, e.g. “Keywords”
normalized – if True, dict keys are all normalized to lower case (default is False)
- property pid#
return process id (PID) of the exiftool process
- run_commands(*commands, no_file=False)[source]#
Run commands in the exiftool process and return result.
- Parameters
*commands – exiftool commands to run
no_file – (bool) do not pass the filename to exiftool (default=False) by default, all commands will be run against self.file use no_file=True to run a command without passing the filename
- Returns
(output, warning, errror) output: bytes is containing output of exiftool commands warning: if exiftool generated warnings, string containing warning otherwise empty string error: if exiftool generated errors, string containing otherwise empty string
Note: Also sets self.warning and self.error if warning or error generated.
- setvalue(tag, value)[source]#
Set tag to value(s); if value is None, will delete tag
- Parameters
tag – str; name of tag to set
value – str; value to set tag to
- Returns
True if success otherwise False
If error generated by exiftool, returns False and sets self.error to error string If warning generated by exiftool, returns True (unless there was also an error) and sets self.warning to warning string If called in context manager, returns True (execution is delayed until exiting context manager)
- property version#
returns exiftool version
- class osxphotos.ExportDB(dbfile, export_dir)[source]#
Interface to sqlite3 database used to store state information for osxphotos export command
- create_file_record(filename: Union[pathlib.Path, str], uuid: str) osxphotos.export_db.ExportRecord [source]#
create a new record for filename and uuid
Returns: an ExportRecord object
- create_or_get_file_record(filename: Union[pathlib.Path, str], uuid: str) osxphotos.export_db.ExportRecord [source]#
create a new record for filename and uuid or return existing record
Returns: an ExportRecord object
- property export_dir#
returns path to export directory
- get_export_results(run: int = 0)[source]#
Retrieve export results from database
- Parameters
run (-1 = previous) – which run to retrieve results for;
run –
run –
that (-2 = run prior to) –
etc. –
- Returns
ExportResults object or None if no results found
- get_exported_files()[source]#
Returns tuple of (uuid, filepath) for all paths of all exported files tracked in the database
- get_file_record(filename: Union[pathlib.Path, str]) osxphotos.export_db.ExportRecord [source]#
get info for filename and uuid
Returns: an ExportRecord object or None if filename not found
- get_files_for_uuid(uuid: str) List [source]#
query database for UUID and return list of files associated with UUID or empty list
- get_previous_uuids()[source]#
returns list of UUIDs of previously exported photos found in export database
- get_target_for_file(uuid: str, filename: Union[str, pathlib.Path]) Optional[str] [source]#
- query database for file matching file name and return the matching filename if there is one;
otherwise return None; looks for file.ext, file (1).ext, file (2).ext and so on to find the actual target name that was used to export filename
Returns: the matching filename or None if no match found
- get_uuid_for_file(filename)[source]#
query database for filename and return UUID returns None if filename not found in database
- property path#
returns path to export database
- class osxphotos.ExportOptions(convert_to_jpeg: bool = False, description_template: Optional[str] = None, download_missing: bool = False, dry_run: bool = False, edited: bool = False, exiftool_flags: Optional[List] = None, exiftool: bool = False, export_as_hardlink: bool = False, export_db: Optional[osxphotos.export_db.ExportDB] = None, face_regions: bool = True, fileutil: Optional[osxphotos.fileutil.FileUtil] = None, force_update: bool = False, ignore_date_modified: bool = False, ignore_signature: bool = False, increment: bool = True, jpeg_ext: Optional[str] = None, jpeg_quality: float = 1.0, keyword_template: Optional[List[str]] = None, live_photo: bool = False, location: bool = True, merge_exif_keywords: bool = False, merge_exif_persons: bool = False, overwrite: bool = False, persons: bool = True, preview_suffix: str = '_preview', preview: bool = False, raw_photo: bool = False, render_options: Optional[osxphotos.phototemplate.RenderOptions] = None, replace_keywords: bool = False, rich: bool = False, sidecar_drop_ext: bool = False, sidecar: int = 0, strip: bool = False, timeout: int = 120, touch_file: bool = False, update: bool = False, use_albums_as_keywords: bool = False, use_persons_as_keywords: bool = False, use_photokit: bool = False, use_photos_export: bool = False, verbose: Optional[Callable] = None, tmpdir: Optional[str] = None)[source]#
Options class for exporting photos with export
- convert_to_jpeg#
if True, converts non-jpeg images to jpeg
- Type
bool
- description_template#
t.Optional template string that will be rendered for use as photo description
- Type
str
- download_missing#
(bool, default=False): if True will attempt to export photo via applescript interaction with Photos if missing (see also use_photokit, use_photos_export)
- Type
bool
- dry_run#
(bool, default=False): set to True to run in “dry run” mode
- Type
bool
- edited#
(bool, default=False): if True will export the edited version of the photo otherwise exports the original version
- Type
bool
- exiftool_flags#
t.Optional list of flags to pass to exiftool when using exiftool option, e.g [“-m”, “-F”]
- Type
list of str
- exiftool#
(bool, default = False): if True, will use exiftool to write metadata to export file
- Type
bool
- export_as_hardlink#
(bool, default=False): if True, will hardlink files instead of copying them
- Type
bool
- export_db#
(ExportDB): instance of a class that conforms to ExportDB with methods for getting/setting data related to exported files to compare update state
- Type
Optional[osxphotos.export_db.ExportDB]
- face_regions#
(bool, default=True): if True, will export face regions
- Type
bool
- fileutil#
(FileUtilABC): class that conforms to FileUtilABC with various file utilities
- Type
Optional[osxphotos.fileutil.FileUtil]
- force_update#
(bool, default=False): if True, will export photo if any metadata has changed but export otherwise would not be triggered (e.g. metadata changed but not using exiftool)
- Type
bool
- ignore_date_modified#
for use with sidecar and exiftool; if True, sets EXIF:ModifyDate to EXIF:DateTimeOriginal even if date_modified is set
- Type
bool
- ignore_signature#
ignore file signature when used with update (look only at filename)
- Type
bool, default=False
- increment#
if True, will increment file name until a non-existant name is found if overwrite=False and increment=False, export will fail if destination file already exists
- Type
bool, default=True
- jpeg_ext#
if set, will use this value for extension on jpegs converted to jpeg with convert_to_jpeg; if not set, uses jpeg; do not include the leading “.”
- Type
str
- jpeg_quality#
a value of 1.0 specifies use best quality, a value of 0.0 specifies use maximum compression.
- Type
float in range 0.0 <= jpeg_quality <= 1.0
- keyword_template#
list of template strings that will be rendered as used as keywords
- Type
list of str
- live_photo#
if True, will also export the associated .mov for live photos
- Type
bool, default=False
- location#
if True, include location in exported metadata
- Type
bool
- merge_exif_keywords#
if True, merged keywords found in file’s exif data (requires exiftool)
- Type
bool
- merge_exif_persons#
if True, merged persons found in file’s exif data (requires exiftool)
- Type
bool
- overwrite#
if True will overwrite files if they already exist
- Type
bool, default=False
- persons#
if True, include persons in exported metadata
- Type
bool
- preview_suffix#
t.Optional string to append to end of filename for preview images
- Type
str
- preview#
if True, also exports preview image
- Type
bool
- raw_photo#
if True, will also export the associated RAW photo
- Type
bool, default=False
- render_options#
t.Optional osxphotos.phototemplate.RenderOptions instance to specify options for rendering templates
- Type
RenderOptions
- replace_keywords#
if True, keyword_template replaces any keywords, otherwise it’s additive
- Type
bool
- rich#
if True, will use rich markup with verbose output
- Type
bool
- sidecar_drop_ext#
if True, drops the photo’s extension from sidecar filename (e.g. ‘IMG_1234.json’ instead of ‘IMG_1234.JPG.json’)
- Type
bool, default=False
- sidecar#
bit field (int): set to one or more of SIDECAR_XMP, SIDECAR_JSON, SIDECAR_EXIFTOOL - SIDECAR_JSON: if set will write a json sidecar with data in format readable by exiftool sidecar filename will be dest/filename.json; includes exiftool tag group names (e.g. exiftool -G -j) - SIDECAR_EXIFTOOL: if set will write a json sidecar with data in format readable by exiftool sidecar filename will be dest/filename.json; does not include exiftool tag group names (e.g. exiftool -j) - SIDECAR_XMP: if set will write an XMP sidecar with IPTC data sidecar filename will be dest/filename.xmp
- Type
int
- strip#
if True, strip whitespace from rendered templates
- Type
bool
- timeout#
timeout in seconds used with use_photos_export
- Type
int, default=120
- touch_file#
if True, sets file’s modification time upon photo date
- Type
bool, default=False
- update#
if True export will run in update mode, that is, it will not export the photo if the current version already exists in the destination
- Type
bool, default=False
- use_albums_as_keywords#
if True, will include album names in keywords when exporting metadata with exiftool or sidecar
- Type
bool, default = False
- use_persons_as_keywords#
if True, will include person names in keywords when exporting metadata with exiftool or sidecar
- Type
bool, default = False
- use_photos_export#
if True will attempt to export photo via applescript interaction with Photos even if not missing (see also use_photokit, download_missing)
- Type
bool, default=False
- use_photokit#
if True, will use photokit to export photos when use_photos_export is True
- Type
bool, default=False
- verbose#
optional callable function to use for printing verbose text during processing; if None (default), does not print output.
- Type
callable
- tmpdir#
(str, default=None): Optional directory to use for temporary files, if None (default) uses system tmp directory
- Type
Optional[str]
- property bit_flags#
Return bit flags representing options that affect export
- class osxphotos.ExportResults(converted_to_jpeg=None, deleted_directories=None, deleted_files=None, error=None, exif_updated=None, exiftool_error=None, exiftool_warning=None, exported_album=None, exported=None, metadata_changed=None, missing_album=None, missing=None, new=None, sidecar_exiftool_skipped=None, sidecar_exiftool_written=None, sidecar_json_skipped=None, sidecar_json_written=None, sidecar_xmp_skipped=None, sidecar_xmp_written=None, skipped_album=None, skipped=None, to_touch=None, touched=None, updated=None, xattr_skipped=None, xattr_written=None)[source]#
Results class which holds export results for export
- class osxphotos.FileUtilNoOp(verbose=None)[source]#
No-Op implementation of FileUtil for testing / dry-run mode all methods with exception of tmpdir, cmp, cmp_file_sig and file_cmp are no-op cmp and cmp_file_sig functions as FileUtil methods do file_cmp returns mock data
- classmethod convert_to_jpeg(src_file, dest_file, compression_quality=1.0)[source]#
converts image file src_file to jpeg format as dest_file
- Parameters
src_file – image file to convert
dest_file – destination path to write converted file to
quality (compression) – JPEG compression quality in range 0.0 <= compression_quality <= 1.0; default 1.0 (best quality)
- Returns
True if success, otherwise False
- classmethod copy(src, dest, norsrc=False)[source]#
Copies a file from src path to dest path
- Parameters
src – source path as string; must be a valid file path
dest – destination path as string dest may be either directory or file; in either case, src file must not exist in dest
Note – src and dest may be either a string or a pathlib.Path object
- Returns
True if copy succeeded
- Raises
OSError if copy fails –
TypeError if either path is None –
- classmethod file_sig(file1)[source]#
return os.stat signature for file f1 as tuple of (mode, size, mtime)
- classmethod hardlink(src, dest)[source]#
Hardlinks a file from src path to dest path src: source path as string dest: destination path as string Raises exception if linking fails or either path is None
- classmethod rename(src, dest)[source]#
Copy src to dest
- Parameters
src – path to source file
dest – path to destination file
- Returns
Name of renamed file (dest)
- classmethod tmpdir(prefix: Optional[str] = None, dir: Optional[str] = None) tempfile.TemporaryDirectory [source]#
Securely creates a temporary directory using the same rules as mkdtemp(). The resulting object can be used as a context manager. On completion of the context or destruction of the temporary directory object, the newly created temporary directory and all its contents are removed from the filesystem.
- class osxphotos.FolderInfo(db=None, uuid=None)[source]#
Info about a specific folder, contains all the details about the folder including folders, albums, etc
- property album_info#
return list of albums (as AlbumInfo objects) contained in the folder
- property parent#
returns FolderInfo object for parent or None if no parent (e.g. top-level folder)
- property subfolders#
return list of folders (as FolderInfo objects) contained in the folder
- property title#
return title / name of folder
- property uuid#
return uuid of folder
- class osxphotos.ImportInfo(db=None, uuid=None)[source]#
Information about import sessions
- property photos#
return list of photos contained in import session
- class osxphotos.LikeInfo(datetime: datetime.datetime, user: str, ismine: bool)[source]#
Class for shared photo likes
- class osxphotos.MomentInfo(db, moment_pk)[source]#
Info about a photo moment
- property date#
Date of the moment.
- property end_date#
Stop date of the moment.
- property location#
Location of the moment.
- property modification_date#
Modification date of the moment.
- property photos#
All photos in this moment
- property pk#
Primary key of the moment.
- property start_date#
Start date of the moment.
- property subtitle#
Subtitle of the moment.
- property title#
Title of the moment.
- class osxphotos.PersonInfo(db=None, pk=None)[source]#
Info about a person in the Photos library
- property face_info#
Returns a list of FaceInfo objects associated with this person sorted by quality score Highest quality face is result[0] and lowest quality face is result[n]
- property photos#
Returns list of PhotoInfo objects associated with this person
- class osxphotos.PhotoExporter(photo: PhotoInfo, tmpdir: Optional[str] = None)[source]#
Export a photo
- exiftool_json_sidecar(options: Optional[osxphotos.photoexporter.ExportOptions] = None, tag_groups: bool = True, filename: Optional[str] = None)[source]#
- Return dict of EXIF details for building exiftool JSON sidecar or sending commands to ExifTool.
Does not include all the EXIF fields as those are likely already in the image.
- Parameters
options (ExportOptions) – options for export
tag_groups (bool, default=True) – if True, include tag groups in the output
filename (str) – name of source image file (without path); if not None, exiftool JSON signature will be included; if None, signature will not be included
Returns: dict with exiftool tags / values
- Exports the following:
EXIF:ImageDescription XMP:Description (may include template) IPTC:CaptionAbstract XMP:Title IPTC:ObjectName XMP:TagsList IPTC:Keywords (may include album name, person name, or template) XMP:Subject (set to keywords + person) XMP:PersonInImage EXIF:GPSLatitudeRef, EXIF:GPSLongitudeRef EXIF:GPSLatitude, EXIF:GPSLongitude EXIF:GPSPosition EXIF:DateTimeOriginal EXIF:OffsetTimeOriginal EXIF:ModifyDate IPTC:DigitalCreationDate IPTC:DateCreated QuickTime:CreationDate QuickTime:CreateDate (UTC) QuickTime:ModifyDate (UTC) QuickTime:GPSCoordinates UserData:GPSCoordinates
- export(dest, filename=None, options: Optional[osxphotos.photoexporter.ExportOptions] = None) osxphotos.photoexporter.ExportResults [source]#
Export photo
- Parameters
dest – must be valid destination path or exception raised
filename – (optional): name of exported picture; if not provided, will use current filename NOTE: if provided, user must ensure file extension (suffix) is correct. For example, if photo is .CR2 file, edited image may be .jpeg. If you provide an extension different than what the actual file is, will export the photo using the incorrect file extension (unless use_photos_export is true, in which case export will use the extension provided by Photos upon export. e.g. to get the extension of the edited photo, reference PhotoInfo.path_edited
options (ExportOptions) – t.Optional ExportOptions instance
- Returns
ExportResults instance
Note
- To use dry run mode, you must set options.dry_run=True and also pass in memory version of export_db,
and no-op fileutil (e.g. ExportDBInMemory and FileUtilNoOp) in options.export_db and options.fileutil respectively
- write_exiftool_metadata_to_file(src, dest, options: osxphotos.photoexporter.ExportOptions) osxphotos.photoexporter.ExportResults [source]#
Write exif metadata to src file using exiftool
Caution: This method modifies src, not dest, so src must be a copy of the original file if you don’t want the source modified; it also does not write to dest (dest is the intended destination for purposes of referencing the export database. This allows the exiftool update to be done on the local machine prior to being copied to the export destination which may be on a network drive or other slower external storage).
- class osxphotos.PhotoInfo(db=None, uuid=None, info=None)[source]#
Info about a specific photo, contains all the details about the photo including keywords, persons, albums, uuid, path, etc.
- property adjustments#
Returns AdjustmentsInfo class for adjustment data or None if no adjustments; Photos 5+ only
- property album_info#
list of AlbumInfo objects representing albums the photo is contained in
- property albums#
list of albums picture is contained in
- property burst#
Returns True if photo is part of a Burst photo set, otherwise False
- property burst_album_info#
If photo is a burst photo, returns list of AlbumInfo objects representing albums the photo is contained in as well as albums the burst key photo is contained in, otherwise returns self.album_info.
- property burst_albums#
If photo is burst photo, list of albums it is contained in as well as any albums the key photo is contained in, otherwise returns self.albums
- property burst_default_pick#
Returns True if photo is a burst image and is the photo that Photos selected as the default image for the burst set, otherwise False
- property burst_key#
Returns True if photo is a burst photo and is the key image for the burst set (the image that Photos shows on top of the burst stack), otherwise False
- property burst_photos#
If photo is a burst photo, returns list of PhotoInfo objects that are part of the same burst photo set; otherwise returns empty list. self is not included in the returned list
- property burst_selected#
Returns True if photo is a burst photo and has been selected from the burst set by the user, otherwise False
- property cloud_metadata: Dict#
Returns contents of ZCLOUDMASTERMEDIAMETADATA as dict
- property comments#
Returns list of Comment objects for any comments on the photo (sorted by date)
- property date#
image creation date as timezone aware datetime object
- property date_added#
Date photo was added to the database
- property date_modified#
image modification date as timezone aware datetime object or None if no modification date set
- property date_trashed#
Date asset was placed in the trash or None
- property description#
long / extended description of picture
- detected_text(confidence_threshold=0.75)[source]#
Detects text in photo and returns lists of results as (detected text, confidence)
confidence_threshold: float between 0.0 and 1.0. If text detection confidence is below this threshold, text will not be returned. Default is TEXT_DETECTION_CONFIDENCE_THRESHOLD
If photo is edited, uses the edited photo, otherwise the original; falls back to the preview image if neither edited or original is available
Returns: list of (detected text, confidence) tuples
- property duplicates#
return list of PhotoInfo objects for possible duplicates (matching signature of original size, date, height, width) or empty list if no matching duplicates
- property exif_info#
Returns an ExifInfo object with the EXIF data for photo Note: the returned EXIF data is the data Photos stores in the database on import; ExifInfo does not provide access to the EXIF info in the actual image file Some or all of the fields may be None Only valid for Photos 5; on earlier database returns None
- property exiftool#
Returns a ExifToolCaching (read-only instance of ExifTool) object for the photo. Requires that exiftool (https://exiftool.org/) be installed If exiftool not installed, logs warning and returns None If photo path is missing, returns None
- export(dest, filename=None, edited=False, live_photo=False, raw_photo=False, export_as_hardlink=False, overwrite=False, increment=True, sidecar_json=False, sidecar_exiftool=False, sidecar_xmp=False, use_photos_export=False, timeout=120, exiftool=False, use_albums_as_keywords=False, use_persons_as_keywords=False, keyword_template=None, description_template=None, render_options: Optional[osxphotos.phototemplate.RenderOptions] = None)[source]#
Export a photo
- Parameters
dest – must be valid destination path (or exception raised)
filename – (optional): name of exported picture; if not provided, will use current filename NOTE: if provided, user must ensure file extension (suffix) is correct. For example, if photo is .CR2 file, edited image may be .jpeg. If you provide an extension different than what the actual file is, export will print a warning but will export the photo using the incorrect file extension (unless use_photos_export is true, in which case export will use the extension provided by Photos upon export; in this case, an incorrect extension is silently ignored). e.g. to get the extension of the edited photo, reference PhotoInfo.path_edited
edited – (boolean, default=False); if True will export the edited version of the photo, otherwise exports the original version (or raise exception if no edited version)
live_photo – (boolean, default=False); if True, will also export the associated .mov for live photos
raw_photo – (boolean, default=False); if True, will also export the associated RAW photo
export_as_hardlink – (boolean, default=False); if True, will hardlink files instead of copying them
overwrite – (boolean, default=False); if True will overwrite files if they already exist
increment – (boolean, default=True); if True, will increment file name until a non-existant name is found if overwrite=False and increment=False, export will fail if destination file already exists
sidecar_json – if set will write a json sidecar with data in format readable by exiftool sidecar filename will be dest/filename.json; includes exiftool tag group names (e.g. exiftool -G -j)
sidecar_exiftool – if set will write a json sidecar with data in format readable by exiftool sidecar filename will be dest/filename.json; does not include exiftool tag group names (e.g. exiftool -j)
sidecar_xmp – if set will write an XMP sidecar with IPTC data sidecar filename will be dest/filename.xmp
use_photos_export – (boolean, default=False); if True will attempt to export photo via applescript interaction with Photos
timeout – (int, default=120) timeout in seconds used with use_photos_export
exiftool – (boolean, default = False); if True, will use exiftool to write metadata to export file
files (returns list of full paths to the exported) –
use_albums_as_keywords – (boolean, default = False); if True, will include album names in keywords
sidecar (when exporting metadata with exiftool or) –
use_persons_as_keywords – (boolean, default = False); if True, will include person names in keywords
sidecar –
keyword_template – (list of strings); list of template strings that will be rendered as used as keywords
description_template – string; optional template string that will be rendered for use as photo description
render_options – an optional osxphotos.phototemplate.RenderOptions instance with options to pass to template renderer
- Returns
list of photos exported
- property external_edit#
Returns True if picture was edited outside of Photos using external editor
- property face_info#
list of FaceInfo objects for faces in picture
- property favorite#
True if picture is marked as favorite
- property filename#
filename of the picture
- property has_raw#
returns True if photo has an associated raw image (that is, it’s a RAW+JPEG pair), otherwise False
- property hasadjustments#
True if picture has adjustments / edits
- property hdr#
Returns True if photo is an HDR photo, otherwise False
- property height#
returns height of the current photo version in pixels
- property hexdigest#
Returns a unique digest of the photo’s properties and metadata; useful for detecting changes in any property/metadata of the photo
True if picture is hidden
- property import_info#
ImportInfo object representing import session for the photo or None if no import session
- property incloud#
Returns True if photo is cloud asset and is synched to cloud False if photo is cloud asset and not yet synched to cloud None if photo is not cloud asset
- property intrash#
True if picture is in trash (‘Recently Deleted’ folder)
- property iscloudasset#
Returns True if photo is a cloud asset (in an iCloud library), otherwise False
- property ismissing#
returns true if photo is missing from disk (which means it’s not been downloaded from iCloud)
- NOTE: the photos.db database uses an asynchrounous write-ahead log so changes in Photos
do not immediately get written to disk. In particular, I’ve noticed that downloading an image from the cloud does not force the database to be updated until something else e.g. an edit, keyword, etc. occurs forcing a database synch The exact process / timing is a mystery to be but be aware that if some photos were recently downloaded from cloud to local storate their status in the database might still show isMissing = 1
- property ismovie#
Returns True if file is a movie, otherwise False
- property isphoto#
Returns True if file is an image, otherwise False
- property israw#
returns True if photo is a raw image. For images with an associated RAW+JPEG pair, see has_raw
- property isreference#
Returns True if photo is a reference (not copied to the Photos library), otherwise False
- property keywords#
list of keywords for picture
- property labels#
returns list of labels applied to photo by Photos image categorization only valid on Photos 5, on older libraries returns empty list
- property labels_normalized#
returns normalized list of labels applied to photo by Photos image categorization only valid on Photos 5, on older libraries returns empty list
- property likes#
Returns list of Like objects for any likes on the photo (sorted by date)
- property live_photo#
Returns True if photo is a live photo, otherwise False
- property location#
returns (latitude, longitude) as float in degrees or None
- property moment_info#
Moment photo belongs to
- property orientation#
returns EXIF orientation of the current photo version as int or 0 if current orientation cannot be determined
- property original_filename#
original filename of the picture Photos 5 mangles filenames upon import
- property original_filesize#
returns filesize of original photo in bytes as int
- property original_height#
returns height of the original photo version in pixels
- property original_orientation#
returns EXIF orientation of the original photo version as int
- property original_width#
returns width of the original photo version in pixels
- property owner#
Return name of photo owner for shared photos (Photos 5+ only), or None if not shared
- property panorama#
Returns True if photo is a panorama, otherwise False
- property path#
absolute path on disk of the original picture
- property path_derivatives#
Return any derivative (preview) images associated with the photo as a list of paths, sorted by file size (largest first)
- property path_edited#
absolute path on disk of the edited picture
- property path_edited_live_photo#
return path to edited version of live photo movie; only valid for Photos 5+
- property path_live_photo#
Returns path to the associated video file for a live photo If photo is not a live photo, returns None If photo is missing, returns None
- property path_raw#
absolute path of associated RAW image or None if there is not one
- property person_info#
list of PersonInfo objects for person in picture
- property persons#
list of persons in picture
- property place#
Returns PlaceInfo object containing reverse geolocation info
- property portrait#
Returns True if photo is a portrait, otherwise False
- property project_info#
list of AlbumInfo objects representing projects for the photo or None if no projects
- property raw_original#
returns True if associated raw image and the raw image is selected in Photos via “Use RAW as Original ” otherwise returns False
- render_template(template_str: str, options: Optional[osxphotos.phototemplate.RenderOptions] = None)[source]#
Renders a template string for PhotoInfo instance using PhotoTemplate
- Parameters
template_str – a template string with fields to render
options – a RenderOptions instance
- Returns
tuple of list of rendered strings and list of unmatched template values
- Return type
([rendered_strings], [unmatched])
- property score#
Computed score information for a photo
- Returns
ScoreInfo instance
- property screenshot#
Returns True if photo is an HDR photo, otherwise False
- property search_info#
returns SearchInfo object for photo only valid on Photos 5, on older libraries, returns None
- property search_info_normalized#
returns SearchInfo object for photo that produces normalized results only valid on Photos 5, on older libraries, returns None
- property selfie#
Returns True if photo is a selfie (front facing camera), otherwise False
returns True if photos is in a shared iCloud album otherwise false Only valid on Photos 5; returns None on older versions
- property slow_mo#
Returns True if photo is a slow motion video, otherwise False
- property time_lapse#
Returns True if photo is a time lapse video, otherwise False
- property title#
name / title of picture
- property tzoffset#
timezone offset from UTC in seconds
- property uti#
Returns Uniform Type Identifier (UTI) for the image for example: public.jpeg or com.apple.quicktime-movie
- property uti_edited#
Returns Uniform Type Identifier (UTI) for the edited image if the photo has been edited, otherwise None; for example: public.jpeg
- property uti_original#
Returns Uniform Type Identifier (UTI) for the original image for example: public.jpeg or com.apple.quicktime-movie
- property uti_raw#
Returns Uniform Type Identifier (UTI) for the RAW image if there is one for example: com.canon.cr2-raw-image Returns None if no associated RAW image
- property uuid#
UUID of picture
- property visible#
True if picture is visble
- property width#
returns width of the current photo version in pixels
- class osxphotos.PhotoTemplate(photo, exiftool_path=None)[source]#
PhotoTemplate class to render a template string from a PhotoInfo object
- expand_variables_to_str(value: str, name: str) str [source]#
Expand variables in value and return a str of the expanded value. Enforce that the expanded value is a single value, raises ValueError if not.
- Parameters
value – the value to expand
name – the name of the value being expanded (used in error messages)
- get_field_values(field: str, subfield: Optional[str], field_arg: Optional[str], default: List[str]) Tuple[List[str], List[str]] [source]#
Get the values for a field
- get_format_values(field: str, subfield: str, default: List[str]) Optional[List[Optional[str]]] [source]#
Return values for {format} templates
- get_media_type(default)[source]#
return special media type, e.g. slow_mo, panorama, etc., defaults to photo or video if no special type
- get_photo_bool_attribute(attr, default, bool_val)[source]#
Return the boolean value for a photo attribute
- get_template_value(field, default, subfield, field_arg)[source]#
lookup value for template field (single-value template substitutions)
- Parameters
field – template field to find value for.
default – the default value provided by the user
bool_val – True value if expression is boolean
delim – delimiter for expand in place
path_sep – path separator for fields that are path-like
subfield – subfield (value after : in field)
- Returns
The matching template value (which may be None).
- Raises
ValueError if no rule exists for field. –
- get_template_value_exiftool(subfield)[source]#
Get template value for format “{exiftool:EXIF:Model}”
- get_template_value_filter_function(filter_, args, values)[source]#
Filter template value from external function
- get_template_value_multi(field, subfield, path_sep, default)[source]#
lookup value for template field (multi-value template substitutions)
- Parameters
field – template field to find value for.
subfield – the template subfield value
path_sep – path separator to use for folder_album field
default – value of default field
- Returns
List of the matching template values or [].
- Raises
ValueError if no rule exists for field. –
- get_template_value_pathlib(field)[source]#
lookup value for template pathlib template fields
- Parameters
field – template field to find value for.
- Returns
The matching template value (which may be None).
- Raises
ValueError if no rule exists for field. –
- render(template: str, options: osxphotos.phototemplate.RenderOptions)[source]#
Render a filename or directory template
- Parameters
template – str template
options – a RenderOptions instance
- Returns
tuple of list of rendered strings and list of unmatched template values
- Return type
([rendered_strings], [unmatched])
- class osxphotos.PhotosDB(dbfile=None, verbose=None, exiftool=None, rich=None)[source]#
Processes a Photos.app library database to extract information about photos
- property album_info#
return list of AlbumInfo objects for each album in the photos database
return list of AlbumInfo objects for each shared album in the photos database only valid for Photos 5; on Photos <= 4, prints warning and returns empty list
- property albums#
return list of albums found in photos database
- property albums_as_dict#
return albums as dict of albums, count in reverse sorted order (descending)
return list of shared albums found in photos database only valid for Photos 5; on Photos <= 4, prints warning and returns empty list
returns shared albums as dict of albums, count in reverse sorted order (descending) valid only on Photos 5; on Photos <= 4, prints warning and returns empty dict
- property db_path#
returns path to the Photos library database PhotosDB was initialized with
- property db_version#
return the database version as stored in LiGlobals table
- property folder_info#
return list FolderInfo objects representing top-level folders in the photos database
- property folders#
return list of top-level folder names in the photos database
- get_db_connection()[source]#
Get connection to the working copy of the Photos database
- Returns
tuple of (connection, cursor) to sqlite3 database
- get_photo(uuid)[source]#
Returns a single photo matching uuid
- Parameters
uuid – the UUID of photo to get
- Returns
PhotoInfo instance for photo with UUID matching uuid or None if no match
- property import_info#
return list of ImportInfo objects for each import session in the database
- property keywords#
return list of keywords found in photos database
- property keywords_as_dict#
return keywords as dict of keyword, count in reverse sorted order (descending)
- property labels#
return list of all search info labels found in the library
- property labels_as_dict#
count in reverse sorted order (descending)
- Type
return labels as dict of label
- property labels_normalized#
return list of all normalized search info labels found in the library
- property labels_normalized_as_dict#
count in reverse sorted order (descending)
- Type
return normalized labels as dict of label
- property library_path#
returns path to the Photos library PhotosDB was initialized with
- property person_info#
return list of PersonInfo objects for each person in the photos database
- property persons#
return list of persons found in photos database
- property persons_as_dict#
return persons as dict of person, count in reverse sorted order (descending)
- photos(keywords: Optional[List[str]] = None, uuid: Optional[List[str]] = None, persons: Optional[List[str]] = None, albums: Optional[List[str]] = None, images: bool = True, movies: bool = True, from_date: Optional[datetime.datetime] = None, to_date: Optional[datetime.datetime] = None, intrash: bool = False) List[osxphotos.photoinfo.PhotoInfo] [source]#
Return a list of PhotoInfo objects If called with no args, returns the entire database of photos If called with args, returns photos matching the args (e.g. keywords, persons, etc.) If more than one arg, returns photos matching all the criteria (e.g. keywords AND persons) If more than one keyword, uuid, persons, albums is passed, they are treated as “OR” criteria e.g. keywords=[“wedding”,”vacation”] returns photos matching either keyword from_date and to_date may be either naive or timezone-aware datetime.datetime objects. If naive, timezone will be assumed to be local timezone.
- Parameters
keywords – list of keywords to search for
uuid – list of UUIDs to search for
persons – list of persons to search for
albums – list of album names to search for
images – if True, returns image files, if False, does not return images; default is True
movies – if True, returns movie files, if False, does not return movies; default is True
from_date – return photos with creation date >= from_date (datetime.datetime object, default None)
to_date – return photos with creation date <= to_date (datetime.datetime object, default None)
intrash – if True, returns only images in “Recently deleted items” folder, if False returns only photos that aren’t deleted; default is False
- Returns
list of PhotoInfo objects
- photos_by_uuid(uuids)[source]#
- Returns a list of photos with UUID in uuids.
Does not generate error if invalid or missing UUID passed. This is faster than using PhotosDB.photos if you have list of UUIDs. Returns photos regardless of intrash state.
- Parameters
uuid – list of UUIDs of photos to get
- Returns
list of PhotoInfo instance for photo with UUID matching uuid or [] if no match
- property project_info#
return list of AlbumInfo projects for each project in the database
- query(options: osxphotos.queryoptions.QueryOptions) List[osxphotos.photoinfo.PhotoInfo] [source]#
Run a query against PhotosDB to extract the photos based on user supplied options
- Parameters
options – a QueryOptions instance
- class osxphotos.ProjectInfo(db=None, uuid=None)[source]#
ProjectInfo with info about projects Projects are cards, calendars, slideshows, etc.
- class osxphotos.QueryOptions(added_after: Optional[datetime.datetime] = None, added_before: Optional[datetime.datetime] = None, added_in_last: Optional[datetime.timedelta] = None, album: Optional[Iterable[str]] = None, burst_photos: Optional[bool] = None, burst: Optional[bool] = None, cloudasset: Optional[bool] = None, deleted_only: Optional[bool] = None, deleted: Optional[bool] = None, description: Optional[Iterable[str]] = None, duplicate: Optional[bool] = None, edited: Optional[bool] = None, exif: Optional[Iterable[Tuple[str, str]]] = None, external_edit: Optional[bool] = None, favorite: Optional[bool] = None, folder: Optional[Iterable[str]] = None, from_date: Optional[datetime.datetime] = None, from_time: Optional[datetime.time] = None, function: Optional[List[Tuple[callable, str]]] = None, has_comment: Optional[bool] = None, has_likes: Optional[bool] = None, has_raw: Optional[bool] = None, hdr: Optional[bool] = None, hidden: Optional[bool] = None, ignore_case: Optional[bool] = None, in_album: Optional[bool] = None, incloud: Optional[bool] = None, is_reference: Optional[bool] = None, keyword: Optional[Iterable[str]] = None, label: Optional[Iterable[str]] = None, live: Optional[bool] = None, location: Optional[bool] = None, max_size: Optional[bitmath.Byte] = None, min_size: Optional[bitmath.Byte] = None, missing_bursts: Optional[bool] = None, missing: Optional[bool] = None, movies: Optional[bool] = True, name: Optional[Iterable[str]] = None, no_comment: Optional[bool] = None, no_description: Optional[bool] = None, no_likes: Optional[bool] = None, no_location: Optional[bool] = None, no_keyword: Optional[bool] = None, no_place: Optional[bool] = None, no_title: Optional[bool] = None, not_burst: Optional[bool] = None, not_cloudasset: Optional[bool] = None, not_favorite: Optional[bool] = None, not_hdr: Optional[bool] = None, not_hidden: Optional[bool] = None, not_in_album: Optional[bool] = None, not_incloud: Optional[bool] = None, not_live: Optional[bool] = None, not_missing: Optional[bool] = None, not_panorama: Optional[bool] = None, not_portrait: Optional[bool] = None, not_screenshot: Optional[bool] = None, not_selfie: Optional[bool] = None, not_shared: Optional[bool] = None, not_slow_mo: Optional[bool] = None, not_time_lapse: Optional[bool] = None, panorama: Optional[bool] = None, person: Optional[Iterable[str]] = None, photos: Optional[bool] = True, place: Optional[Iterable[str]] = None, portrait: Optional[bool] = None, query_eval: Optional[Iterable[str]] = None, regex: Optional[Iterable[Tuple[str, str]]] = None, screenshot: Optional[bool] = None, selected: Optional[bool] = None, selfie: Optional[bool] = None, shared: Optional[bool] = None, slow_mo: Optional[bool] = None, time_lapse: Optional[bool] = None, title: Optional[Iterable[str]] = None, to_date: Optional[datetime.datetime] = None, to_time: Optional[datetime.time] = None, uti: Optional[Iterable[str]] = None, uuid: Optional[Iterable[str]] = None, year: Optional[Iterable[int]] = None)[source]#
QueryOptions class for PhotosDB.query
- added_after#
search for photos added after a given date
- Type
Optional[datetime.datetime]
- added_before#
search for photos added before a given date
- Type
Optional[datetime.datetime]
- added_in_last#
search for photos added in last X datetime.timedelta
- Type
Optional[datetime.timedelta]
- album#
list of album names to search for
- Type
Optional[Iterable[str]]
- burst_photos#
search for burst photos
- Type
Optional[bool]
- burst#
search for burst photos
- Type
Optional[bool]
- cloudasset#
search for photos that are managed by iCloud
- Type
Optional[bool]
- deleted_only#
search only for deleted photos
- Type
Optional[bool]
- deleted#
also include deleted photos
- Type
Optional[bool]
- description#
list of descriptions to search for
- Type
Optional[Iterable[str]]
- duplicate#
search for duplicate photos
- Type
Optional[bool]
- edited#
search for edited photos
- Type
Optional[bool]
- exif#
search for photos with EXIF tags that matches the given data
- Type
Optional[Iterable[Tuple[str, str]]]
- external_edit#
search for photos edited in external apps
- Type
Optional[bool]
- favorite#
search for favorite photos
- Type
Optional[bool]
- folder#
list of folder names to search for
- Type
Optional[Iterable[str]]
- from_date#
search for photos taken on or after this date
- Type
Optional[datetime.datetime]
- function#
list of query functions to evaluate
- Type
Optional[List[Tuple[callable, str]]]
- has_comment#
search for photos with comments
- Type
Optional[bool]
- has_likes#
search for shared photos with likes
- Type
Optional[bool]
- has_raw#
search for photos with associated raw files
- Type
Optional[bool]
- hdr#
search for HDR photos
- Type
Optional[bool]
search for hidden photos
- Type
Optional[bool]
- ignore_case#
ignore case when searching
- Type
Optional[bool]
- in_album#
search for photos in an album
- Type
Optional[bool]
- incloud#
search for cloud assets that are synched to iCloud
- Type
Optional[bool]
- is_reference#
search for photos stored by reference (that is, they are not managed by Photos)
- Type
Optional[bool]
- keyword#
list of keywords to search for
- Type
Optional[Iterable[str]]
- label#
list of labels to search for
- Type
Optional[Iterable[str]]
- live#
search for live photos
- Type
Optional[bool]
- location#
search for photos with a location
- Type
Optional[bool]
- max_size#
maximum size of photos to search for
- Type
Optional[bitmath.Byte]
- min_size#
minimum size of photos to search for
- Type
Optional[bitmath.Byte]
- missing_bursts#
for burst photos, also include burst photos that are missing
- Type
Optional[bool]
- missing#
search for missing photos
- Type
Optional[bool]
- movies#
search for movies
- Type
Optional[bool]
- name#
list of names to search for
- Type
Optional[Iterable[str]]
- no_comment#
search for photos with no comments
- Type
Optional[bool]
- no_description#
search for photos with no description
- Type
Optional[bool]
- no_likes#
search for shared photos with no likes
- Type
Optional[bool]
- no_location#
search for photos with no location
- Type
Optional[bool]
- no_keyword#
search for photos with no keywords
- Type
Optional[bool]
- no_place#
search for photos with no place
- Type
Optional[bool]
- no_title#
search for photos with no title
- Type
Optional[bool]
- not_burst#
search for non-burst photos
- Type
Optional[bool]
- not_cloudasset#
search for photos that are not managed by iCloud
- Type
Optional[bool]
- not_favorite#
search for non-favorite photos
- Type
Optional[bool]
- not_hdr#
search for non-HDR photos
- Type
Optional[bool]
search for non-hidden photos
- Type
Optional[bool]
- not_in_album#
search for photos not in an album
- Type
Optional[bool]
- not_incloud#
search for cloud asset photos that are not yet synched to iCloud
- Type
Optional[bool]
- not_live#
search for non-live photos
- Type
Optional[bool]
- not_missing#
search for non-missing photos
- Type
Optional[bool]
- not_panorama#
search for non-panorama photos
- Type
Optional[bool]
- not_portrait#
search for non-portrait photos
- Type
Optional[bool]
- not_screenshot#
search for non-screenshot photos
- Type
Optional[bool]
- not_selfie#
search for non-selfie photos
- Type
Optional[bool]
search for non-shared photos
- Type
Optional[bool]
- not_slow_mo#
search for non-slow-mo photos
- Type
Optional[bool]
- not_time_lapse#
search for non-time-lapse photos
- Type
Optional[bool]
- panorama#
search for panorama photos
- Type
Optional[bool]
- person#
list of person names to search for
- Type
Optional[Iterable[str]]
- photos#
search for photos
- Type
Optional[bool]
- place#
list of place names to search for
- Type
Optional[Iterable[str]]
- portrait#
search for portrait photos
- Type
Optional[bool]
- query_eval#
list of query expressions to evaluate
- Type
Optional[Iterable[str]]
- regex#
list of regular expressions to search for
- Type
Optional[Iterable[Tuple[str, str]]]
- screenshot#
search for screenshot photos
- Type
Optional[bool]
- selected#
search for selected photos
- Type
Optional[bool]
- selfie#
search for selfie photos
- Type
Optional[bool]
search for shared photos
- Type
Optional[bool]
- slow_mo#
search for slow-mo photos
- Type
Optional[bool]
- time_lapse#
search for time-lapse photos
- Type
Optional[bool]
- title#
list of titles to search for
- Type
Optional[Iterable[str]]
- to_date#
search for photos taken on or before this date
- Type
Optional[datetime.datetime]
- uti#
list of UTIs to search for
- Type
Optional[Iterable[str]]
- uuid#
list of uuids to search for
- Type
Optional[Iterable[str]]
- year#
search for photos taken in a given year
- Type
Optional[Iterable[int]]
- class osxphotos.ScoreInfo(overall: float, curation: float, promotion: float, highlight_visibility: float, behavioral: float, failure: float, harmonious_color: float, immersiveness: float, interaction: float, interesting_subject: float, intrusive_object_presence: float, lively_color: float, low_light: float, noise: float, pleasant_camera_tilt: float, pleasant_composition: float, pleasant_lighting: float, pleasant_pattern: float, pleasant_perspective: float, pleasant_post_processing: float, pleasant_reflection: float, pleasant_symmetry: float, sharply_focused_subject: float, tastefully_blurred: float, well_chosen_subject: float, well_framed_subject: float, well_timed_shot: float)[source]#
Computed photo score info associated with a photo from the Photos library
- class osxphotos.SearchInfo(photo, normalized=False)[source]#
Info about search terms such as machine learning labels that Photos knows about a photo
- property activities#
returns list of activity names
- property all#
return all search info properties in a single list
- property bodies_of_water#
returns list of body of water names
- property city#
returns city/town
- property country#
returns country name
- property holidays#
returns list of holiday names
- property labels#
return list of labels associated with Photo
- property locality_names#
returns list of other locality names
- property media_types#
returns list of media types (photo, video, panorama, etc)
- property month#
returns month name
- property neighborhoods#
returns list of neighborhoods
- property place_names#
returns list of place names
- property season#
returns season name
- property state#
returns state name
- property state_abbreviation#
returns state abbreviation
- property streets#
returns list of street names
- property venue_types#
returns list of venue types
- property venues#
returns list of venue names
- property year#
returns year