Compare commits

...

17 Commits

Author SHA1 Message Date
Rhet Turnbull
90b493b7a4 Merge pull request #327 from synox/patch-1
doc: start with examples before the export reference, thanks to @synox
2021-01-03 10:30:28 -08:00
Rhet Turnbull
2480f2a325 Added tag_groups arg to ExifTool.asdict(), issue #324 2021-01-03 10:28:44 -08:00
Aravindo Wingeier
a59bb5b02f remove extra spaces 2021-01-03 19:09:29 +01:00
Aravindo Wingeier
7c8bfc811a Adding back dependency https://github.com/RhetTbull/PhotoScript) 2021-01-03 19:08:32 +01:00
Aravindo Wingeier
7c7bf1be6b doc: start with examples before the export reference
Because the very long export reference might makes it hard to spot the examples.
2021-01-03 19:04:49 +01:00
Rhet Turnbull
b1cab32ff4 Updated dependencies in README.md 2021-01-03 09:48:01 -08:00
Rhet Turnbull
05f111a287 Added exception handling/capture for convert-to-jpeg, issue #322 2021-01-03 09:36:26 -08:00
Rhet Turnbull
83915c65ab Add @synox as a contributor 2021-01-03 09:24:45 -08:00
Rhet Turnbull
22f44f7f40 Merge pull request #326 from synox/master
Make readme easier for beginners, thanks to @synox
2021-01-03 09:21:20 -08:00
Aravindo Wingeier
02ef0f9a25 doc simplify readme 2021-01-03 18:04:51 +01:00
Rhet Turnbull
6347d94dfb Updated CHANGELOG.md 2021-01-03 08:47:16 -08:00
Rhet Turnbull
a32c102d62 Updated CHANGELOG.md 2021-01-03 08:46:36 -08:00
Aravindo Wingeier
38842ff924 Cleanup up the readme
simplify as much as possible
2021-01-03 17:31:42 +01:00
Rhet Turnbull
478715a363 Implemented text replacement for templates, issue #316 2021-01-03 07:38:07 -08:00
Rhet Turnbull
74f1002b9a Updated CHANGELOG.md 2020-12-31 13:11:21 -08:00
Rhet Turnbull
2f57abd23c Fixed modified template to use creation time if no modificationd date, issue #312 2020-12-31 13:07:00 -08:00
Rhet Turnbull
f9a43b92c1 Updated CHANGELOG.md 2020-12-31 12:36:16 -08:00
15 changed files with 804 additions and 334 deletions

View File

@@ -118,6 +118,15 @@
"contributions": [
"doc"
]
},
{
"login": "synox",
"name": "Aravindo Wingeier",
"avatar_url": "https://avatars2.githubusercontent.com/u/2250964?v=4",
"profile": "https://github.com/synox",
"contributions": [
"doc"
]
}
],
"contributorsPerLine": 7

View File

@@ -4,6 +4,39 @@ All notable changes to this project will be documented in this file. Dates are d
Generated by [`auto-changelog`](https://github.com/CookPete/auto-changelog).
#### [v0.39.6](https://github.com/RhetTbull/osxphotos/compare/v0.39.5...v0.39.6)
> 3 January 2021
- Make readme easier for beginners, thanks to @synox [`#326`](https://github.com/RhetTbull/osxphotos/pull/326)
- doc simplify readme [`02ef0f9`](https://github.com/RhetTbull/osxphotos/commit/02ef0f9a254e83a3729a09cea1ae523407074896)
- Added exception handling/capture for convert-to-jpeg, issue #322 [`05f111a`](https://github.com/RhetTbull/osxphotos/commit/05f111a287e882ed6b451a550a87753501316aba)
- Add @synox as a contributor [`83915c6`](https://github.com/RhetTbull/osxphotos/commit/83915c65abb880036f80ebd830eb1e34292f9599)
#### [v0.39.5](https://github.com/RhetTbull/osxphotos/compare/v0.39.4...v0.39.5)
> 3 January 2021
- Cleanup up the readme [`38842ff`](https://github.com/RhetTbull/osxphotos/commit/38842ff9249e6f5b3069a88a759c8df97ddce51c)
#### [v0.39.4](https://github.com/RhetTbull/osxphotos/compare/v0.39.3...v0.39.4)
> 3 January 2021
- Implemented text replacement for templates, issue #316 [`478715a`](https://github.com/RhetTbull/osxphotos/commit/478715a363f5009e4a38148e832bf0ad3c4cc4f8)
#### [v0.39.3](https://github.com/RhetTbull/osxphotos/compare/v0.39.2...v0.39.3)
> 31 December 2020
- Fixed modified template to use creation time if no modificationd date, issue #312 [`2f57abd`](https://github.com/RhetTbull/osxphotos/commit/2f57abd23cabe57bcf667a1713c37689b330a702)
#### [v0.39.2](https://github.com/RhetTbull/osxphotos/compare/v0.39.1...v0.39.2)
> 31 December 2020
- Added --xattr-template, closes #242 [`#242`](https://github.com/RhetTbull/osxphotos/issues/242)
#### [v0.39.1](https://github.com/RhetTbull/osxphotos/compare/v0.39.0...v0.39.1)
> 31 December 2020

328
README.md
View File

@@ -3,7 +3,7 @@
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Python package](https://github.com/RhetTbull/osxphotos/workflows/Python%20package/badge.svg)](https://github.com/RhetTbull/osxphotos/workflows/Python%20package/badge.svg)
<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->
[![All Contributors](https://img.shields.io/badge/all_contributors-12-orange.svg?style=flat-square)](#contributors-)
[![All Contributors](https://img.shields.io/badge/all_contributors-13-orange.svg?style=flat-square)](#contributors-)
<!-- ALL-CONTRIBUTORS-BADGE:END -->
- [OSXPhotos](#osxphotos)
@@ -11,7 +11,8 @@
* [Supported operating systems](#supported-operating-systems)
* [Installation instructions](#installation-instructions)
* [Command Line Usage](#command-line-usage)
* [Example uses of the package](#example-uses-of-the-package)
+ [Command line examples](#command-line-examples)
+ [Command line reference: export](#command-line-reference-export)
* [Package Interface](#package-interface)
+ [PhotosDB](#photosdb)
+ [PhotoInfo](#photoinfo)
@@ -40,31 +41,29 @@
## What is osxphotos?
OSXPhotos provides the ability to interact with and query Apple's Photos.app library database on MacOS. Using this package you can query the Photos database for information about the photos stored in a Photos library on your Mac--for example, file name, file path, and metadata such as keywords/tags, persons/faces, albums, etc. You can also easily export both the original and edited photos.
OSXPhotos provides the ability to interact with and query Apple's Photos.app library on macOS. You can query the Photos library database -- for example, file name, file path, and metadata such as keywords/tags, persons/faces, albums, etc. You can also easily export both the original and edited photos.
## Supported operating systems
Only works on MacOS (aka Mac OS X). Tested on MacOS 10.12.6 / Photos 2.0, 10.13.6 / Photos 3.0, MacOS 10.14.5, 10.14.6 / Photos 4.0, MacOS 10.15.1 - 10.15.7 / Photos 5.0.
Only works on macOS (aka Mac OS X). Tested on macOS Sierra (10.12.6) until macOS Catalina (10.15.7).
Beta support for MacOS 10.16/MacOS 11 Big Sur Beta / Photos 6.0. Not tested on M1 / Apple silicon Macs.
| macOS Version | macOS name | Photos.app version |
| ----------------- |------------|:-------------------|
| 10.16 | Big Sur | 6.0 ⚠️ Beta support, not tested on M1 / Apple silicon Macs. |
| 10.15.1 - 10.15.7 | Catalina | 5.0 ✅ |
| 10.14.5, 10.14.6 | Mojave | 4.0 ✅ |
| 10.13.6 | High Sierra| 3.0 ✅ |
| 10.12.6 | Sierra | 2.0 ✅ |
Requires python >= 3.7.
This package will read Photos databases for any supported version on any supported macOS version. E.g. you can read a database created with Photos 5.0 on MacOS 10.15 on a machine running macOS 10.12 and vice versa.
This package will read Photos databases for any supported version on any supported OS version. E.g. you can read a database created with Photos 5.0 on MacOS 10.15 on a machine running MacOS 10.12 and vice versa.
Requires python >= `3.7`.
## Installation instructions
OSXPhotos uses setuptools, thus simply run:
python3 setup.py install
You can also install directly from [pypi](https://pypi.org/project/osxphotos/):
pip install osxphotos
I recommend you create a [virtual environment](https://docs.python.org/3/tutorial/venv.html) before installing osxphotos.
## Installation
If you are new to python, I recommend you to install using pipx. See other advanced options below.
### Installation using pipx
If you aren't familiar with installing python applications, I recommend you install `osxphotos` with [pipx](https://github.com/pipxproject/pipx). If you use `pipx`, you will not need to create a virtual environment as `pipx` takes care of this. The easiest way to do this on a Mac is to use [homebrew](https://brew.sh/):
- Open `Terminal` (search for `Terminal` in Spotlight or look in `Applications/Utilities`)
@@ -73,13 +72,26 @@ If you aren't familiar with installing python applications, I recommend you inst
- Then type this: `pipx install osxphotos`
- Now you should be able to run `osxphotos` by typing: `osxphotos`
**WARNING** The git repo for this project is very large (> 1GB) because it contains multiple Photos libraries used for testing on different versions of MacOS. If you just want to use the osxphotos package in your own code, I recommend you install the latest version from [PyPI](https://pypi.org/project/osxphotos/) which does not include all the test libraries. If you just want to use the command line utility, you can download a pre-built executable of the latest [release](https://github.com/RhetTbull/osxphotos/releases) or you can install via `pip` which also installs the command line app. If you aren't comfortable with running python on your Mac, start with the pre-built executable or `pipx` as described above.
### Installation using pip
You can also install directly from [pypi](https://pypi.org/project/osxphotos/):
pip install osxphotos
### Installation from git repository
OSXPhotos uses setuptools, thus simply run:
git clone https://github.com/RhetTbull/osxphotos.git
cd osxphotos
python3 setup.py install
I recommend you create a [virtual environment](https://docs.python.org/3/tutorial/venv.html) before installing osxphotos.
**WARNING** The git repo for this project is very large (> 1GB) because it contains multiple Photos libraries used for testing on different versions of macOS. If you just want to use the osxphotos package in your own code, I recommend you install the latest version from [PyPI](https://pypi.org/project/osxphotos/) which does not include all the test libraries. If you just want to use the command line utility, you can download a pre-built executable of the latest [release](https://github.com/RhetTbull/osxphotos/releases) or you can install via `pip` which also installs the command line app. If you aren't comfortable with running python on your Mac, start with the pre-built executable or `pipx` as described above.
## Command Line Usage
This package will install a command line utility called `osxphotos` that allows you to query the Photos database. Alternatively, you can also run the command line utility like this: `python3 -m osxphotos`
After installing per instructions above, you should be able to run `osxphotos` on the command line:
```
> osxphotos
@@ -114,7 +126,37 @@ Commands:
To get help on a specific command, use `osxphotos help <command_name>`
Example: `osxphotos help export`
### Command line examples
#### export all photos to ~/Desktop/export group in folders by date created
`osxphotos export --export-by-date ~/Pictures/Photos\ Library.photoslibrary ~/Desktop/export`
**Note**: Photos library/database path can also be specified using `--db` option:
`osxphotos export --export-by-date --db ~/Pictures/Photos\ Library.photoslibrary ~/Desktop/export`
#### find all photos with keyword "Kids" and output results to json file named results.json:
`osxphotos query --keyword Kids --json ~/Pictures/Photos\ Library.photoslibrary >results.json`
#### export photos to file structure based on 4-digit year and full name of month of photo's creation date:
`osxphotos export ~/Desktop/export --directory "{created.year}/{created.month}"`
(by default, it will attempt to use the system library)
#### export photos to file structure based on 4-digit year of photo's creation date and add keywords for media type and labels (labels are only awailable on Photos 5 and higher):
`osxphotos export ~/Desktop/export --directory "{created.year}" --keyword-template "{label}" --keyword-template "{media_type}"`
#### export default library using 'country name/year' as output directory (but use "NoCountry/year" if country not specified), add persons, album names, and year as keywords, write exif metadata to files when exporting, update only changed files, print verbose ouput
`osxphotos export ~/Desktop/export --directory "{place.name.country,NoCountry}/{created.year}" --person-keyword --album-keyword --keyword-template "{created.year}" --exiftool --update --verbose`
### Command line reference: export
`osxphotos help export`
```
Usage: osxphotos export [OPTIONS] [PHOTOS_LIBRARY]... DEST
@@ -446,6 +488,13 @@ Options:
do not include an extension in the FILENAME
template. See below for additional details
on templating system.
--strip Optionally strip leading and trailing
whitespace from any rendered templates. For
example, if --filename template is "{title,}
{original_name}" and image has no title,
resulting file would have a leading space
but if used with --strip, this will be
removed.
--edited-suffix SUFFIX Optional suffix template for naming edited
photos. Default name for edited photos is
in form 'photoname_edited.ext'. For example,
@@ -588,50 +637,24 @@ _keys
** Templating System **
Several options, such as --directory, allow you to specify a template which
will be rendered to substitute template fields with values from the photo.
For example, '{created.month}' would be replaced with the month name of the
photo creation date. e.g. 'November'.
will be rendered to substitute template fields with values from the photo. For
example, '{created.month}' would be replaced with the month name of the photo
creation date. e.g. 'November'.
Some options supporting templates may be repeated e.g., --keyword-template
'{label}' --keyword-template '{media_type}' to add both labels and media
types to the keywords.
The general format for a template is '{TEMPLATE_FIELD[,[DEFAULT]]}'. Some
templates have optional modifiers in form
'{[[DELIM]+]TEMPLATE_FIELD[(PATH_SEP)][?VALUE_IF_TRUE][,[DEFAULT]]}'
The general format for a template is '{TEMPLATE_FIELD,DEFAULT}'. The full
template format is:
'{DELIM+TEMPLATE_FIELD(PATH_SEP)[OLD,NEW]?VALUE_IF_TRUE,DEFAULT}'
The ',' and DEFAULT value are optional. If TEMPLATE_FIELD results in a null
(empty) value, the default is '_'. You may specify an alternate default
value by appending ',DEFAULT' after template_field. e.g. '{title,no_title}'
would result in 'no_title' if the photo had no title. You may include other
text in the template string outside the {} and use more than one template
field, e.g. '{created.year} - {created.month}' (e.g. '2020 - November').
With a few exceptions (like '{created.strftime}') everything but the
TEMPLATE_FIELD is optional.
Some template fields such as 'hdr' are boolean and resolve to True or False.
These take the form: '{TEMPLATE_FIELD?VALUE_IF_TRUE,VALUE_IF_FALSE}', e.g.
{hdr?is_hdr,not_hdr} which would result in 'is_hdr' if photo is an HDR image
and 'not_hdr' otherwise.
Some template fields such as 'folder_template' are "path-like" in that they
join multiple elements into a single path-like string. For example, if photo
is in album Album1 in folder Folder1, '{folder_album}` results in
'Folder1/Album1'. This is so these template fields may be used as paths in
--directory. If you intend to use such a field as a string, e.g. in the
filename, you may specify a different path separator using the form:
'{TEMPLATE_FIELD(PATH_SEP)}'. For example, using the example above,
'{folder_album(-)}' would result in 'Folder1-Album1' and '{folder_album()}'
would result in 'Folder1Album1'.
Some templates may resolve to more than one value. For example, a photo can
have multiple keywords so '{keyword}' can result in multiple values. If used
in a filename or directory, these templates may result in more than one copy
of the photo being exported. For example, if photo has keywords "foo" and
"bar", --directory '{keyword}' will result in copies of the photo being
exported to 'foo/image_name.jpeg' and 'bar/image_name.jpeg'.
Multi-value template fields such as '{keyword}' may be expanded 'in place'
with an optional delimiter using the template form '{DELIM+TEMPLATE_FIELD}'.
For example, a photo with keywords 'foo' and 'bar':
- 'DELIM+' Multi-value template fields such as '{keyword}' may be expanded 'in
place' with an optional delimiter using the template form
'{DELIM+TEMPLATE_FIELD}'. For example, a photo with keywords 'foo' and 'bar':
'{keyword}' renders to 'foo' and 'bar'
@@ -641,6 +664,62 @@ For example, a photo with keywords 'foo' and 'bar':
'{+keyword}' renders to 'foobar'
- 'TEMPLATE_FIELD' The name of the template field, for example 'keyword'
- '(PATH_SEP)' Some template fields such as '{folder_album}' are "path-like"
in that they join multiple elements into a single path-like string. For
example, if photo is in album Album1 in folder Folder1, '{folder_album}'
results in 'Folder1/Album1'. This is so these template fields may be used as
paths in --directory. If you intend to use such a field as a string, e.g. in
the filename, you may specify a different path separator using the form:
'{TEMPLATE_FIELD(PATH_SEP)}'. For example, using the example above,
'{folder_album(-)}' would result in 'Folder1-Album1' and '{folder_album()}'
would result in 'Folder1Album1'.
- '[OLD,NEW]' Use the [OLD,NEW] option to replace text "OLD" in the template
value with text "NEW". For example, if you have album names with '/' in the
album name you could replace '/' with "-" using the template '{album[/,-]}'.
This would replace any occurence of "/" in the album name with "-"; album
"Vacation/2019" would thus become "Vacation-2019". You may specify more than
one pair of OLD,NEW values by listing them delimited by '|'. For example:
'{album[/,-|:,-]}' to replace both '/' and ':' by '-'. You can also use the
[OLD,NEW] syntax to delete a character by omitting the NEW value as in
'{album[/,]}'.
- '?' Some template fields such as 'hdr' are boolean and resolve to True or
False. These take the form: '{TEMPLATE_FIELD?VALUE_IF_TRUE,VALUE_IF_FALSE}',
e.g. {hdr?is_hdr,not_hdr} which would result in 'is_hdr' if photo is an HDR
image and 'not_hdr' otherwise.
- ',DEFAULT' The ',' and DEFAULT value are optional. If TEMPLATE_FIELD
results in a null (empty) value, the template will result in default value of
'_'. You may specify an alternate default value by appending ',DEFAULT' after
template_field. Example: '{title,no_title}' would result in 'no_title' if the
photo had no title. Example: '{created.year}/{place.address,NO_ADDRESS}' but
there was no address associated with the photo, the resulting output would
be: '2020/NO_ADDRESS/photoname.jpg'. If specified, the default value may not
contain a brace symbol ('{' or '}').
Again, if you do not specify a default value and the template substitution has
no value, '_' (underscore) will be used as the default value. For example, in
the above example, this would result in '2020/_/photoname.jpg' if address was
null.
You may specify a null default (e.g. "" or empty string) by omitting the value
after the comma, e.g. {title,} which would render to "" if title had no value
thus effectively deleting the template from the resulting string.
You may include other text in the template string outside the {} and use more
than one template field in a single string, e.g. '{created.year} -
{created.month}' (e.g. '2020 - November').
Some templates may resolve to more than one value. For example, a photo can
have multiple keywords so '{keyword}' can result in multiple values. If used
in a filename or directory, these templates may result in more than one copy
of the photo being exported. For example, if photo has keywords "foo" and
"bar", --directory '{keyword}' will result in copies of the photo being
exported to 'foo/image_name.jpeg' and 'bar/image_name.jpeg'.
Some template fields such as '{media_type}' use the 'DEFAULT' value to allow
customization of the output. For example, '{media_type}' resolves to the
special media type of the photo such as 'panorama' or 'selfie'. You may use
@@ -650,6 +729,28 @@ photo is a time_lapse photo, 'media_type' would resolve to 'vidéo_accélérée
instead of 'time_lapse' and video would resolve to 'vidéo' if photo is an
ordinary video.
With the --directory and --filename options you may specify a template for the
export directory or filename, respectively. The directory will be appended to
the export path specified in the export DEST argument to export. For example,
if template is '{created.year}/{created.month}', and export destination DEST
is '/Users/maria/Pictures/export', the actual export directory for a photo
would be '/Users/maria/Pictures/export/2020/March' if the photo was created in
March 2020.
The templating system may also be used with the --keyword-template option to
set keywords on export (with --exiftool or --sidecar), for example, to set a
new keyword in format 'folder/subfolder/album' to preserve the folder/album
structure, you can use --keyword-template "{folder_album}"
In the template, valid template substitutions will be replaced by the
corresponding value from the table below. Invalid substitutions will result
in an error.
If you want the actual text of the template substition to appear in the
rendered name, use double braces, e.g. '{{' or '}}', thus using
'{created.year}/{{name}}' for --directory would result in output of
2020/{name}/photoname.jpg
With the --directory and --filename options you may specify a template for the
export directory or filename, respectively. The directory will be appended to
the export path specified in the export DEST argument to export. For example,
@@ -740,27 +841,39 @@ Substitution Description
https://strftime.org/ for help on strftime
templates.
{modified.date} Photo's modification date in ISO format,
e.g. '2020-03-22'
{modified.year} 4-digit year of photo modification time
{modified.yy} 2-digit year of photo modification time
e.g. '2020-03-22'; uses creation date if
photo is not modified
{modified.year} 4-digit year of photo modification time;
uses creation date if photo is not modified
{modified.yy} 2-digit year of photo modification time;
uses creation date if photo is not modified
{modified.mm} 2-digit month of the photo modification time
(zero padded)
(zero padded); uses creation date if photo
is not modified
{modified.month} Month name in user's locale of the photo
modification time
modification time; uses creation date if
photo is not modified
{modified.mon} Month abbreviation in the user's locale of
the photo modification time
the photo modification time; uses creation
date if photo is not modified
{modified.dd} 2-digit day of the month (zero padded) of
the photo modification time
the photo modification time; uses creation
date if photo is not modified
{modified.dow} Day of week in user's locale of the photo
modification time
modification time; uses creation date if
photo is not modified
{modified.doy} 3-digit day of year (e.g Julian day) of
photo modification time, starting from 1
(zero padded)
{modified.hour} 2-digit hour of the photo modification time
(zero padded); uses creation date if photo
is not modified
{modified.hour} 2-digit hour of the photo modification time;
uses creation date if photo is not modified
{modified.min} 2-digit minute of the photo modification
time
time; uses creation date if photo is not
modified
{modified.sec} 2-digit second of the photo modification
time
time; uses creation date if photo is not
modified
{today.date} Current date in iso format, e.g.
'2020-03-22'
{today.year} 4-digit year of current date
@@ -821,6 +934,19 @@ Substitution Description
e.g. 'Summer'; (Photos 5+ only, applied
automatically by Photos' image
categorization algorithms).
{exif.camera_make} Camera make from original photo's EXIF
inormation as imported by Photos, e.g.
'Apple'
{exif.camera_model} Camera model from original photo's EXIF
inormation as imported by Photos, e.g.
'iPhone 6s'
{exif.lens_model} Lens model from original photo's EXIF
inormation as imported by Photos, e.g.
'iPhone 6s back camera 4.15mm f/2.2'
{uuid} Photo's internal universally unique
identifier (UUID) for the photo, a
36-character string unique to the photo,
e.g. '128FB4C6-0B16-4E7D-9108-FB2E90DA1546'
The following substitutions may result in multiple values. Thus if specified
for --directory these could result in multiple copies of a photo being being
@@ -865,29 +991,7 @@ Substitution Description
algorithms).
```
Example: export all photos to ~/Desktop/export group in folders by date created
`osxphotos export --export-by-date ~/Pictures/Photos\ Library.photoslibrary ~/Desktop/export`
**Note**: Photos library/database path can also be specified using --db option:
`osxphotos export --export-by-date --db ~/Pictures/Photos\ Library.photoslibrary ~/Desktop/export`
Example: find all photos with keyword "Kids" and output results to json file named results.json:
`osxphotos query --keyword Kids --json ~/Pictures/Photos\ Library.photoslibrary >results.json`
Example: export photos to file structure based on 4-digit year and full name of month of photo's creation date:
`osxphotos export ~/Desktop/export --directory "{created.year}/{created.month}"`
Example: export photos to file structure based on 4-digit year of photo's creation date and add keywords for media type and labels (labels are only awailable on Photos 5 and higher):
`osxphotos export ~/Desktop/export --directory "{created.year}" --keyword-template "{label}" --keyword-template "{media_type}"`
Example: export default library using 'country name/year' as output directory (but use "NoCountry/year" if country not specified), add persons, album names, and year as keywords, write exif metadata to files when exporting, update only changed files, print verbose ouput
`osxphotos export ~/Desktop/export --directory "{place.name.country,NoCountry}/{created.year}" --person-keyword --album-keyword --keyword-template "{created.year}" --exiftool --update --verbose`
## Example uses of the package
@@ -1634,7 +1738,7 @@ exiftool must be installed in the path for this to work. If exiftool cannot be
`ExifTool` provides the following methods:
- `asdict()`: returns all EXIF metadata found in the file as a dictionary in following form (Note: this shows just a subset of available metadata). See [exiftool](https://exiftool.org/) documentation to understand which metadata keys are available.
- `asdict(tag_groups=True)`: returns all EXIF metadata found in the file as a dictionary in following form (Note: this shows just a subset of available metadata). See [exiftool](https://exiftool.org/) documentation to understand which metadata keys are available. If `tag_groups` is True (default) dict keys are in form "GROUP:TAG", e.g. "IPTC:Keywords". If `tag_groups` is False, dict keys do not have group names, e.g. "Keywords".
```python
{'Composite:Aperture': 2.2,
@@ -1714,7 +1818,7 @@ If overwrite=False and increment=False, export will fail if destination file alr
#### <a name="rendertemplate">`render_template()`</a>
`render_template(template_str, none_str = "_", path_sep = None, expand_inplace = False, inplace_sep = None, filename=False, dirname=False, replacement=":",)`
`render_template(template_str, none_str = "_", path_sep = None, expand_inplace = False, inplace_sep = None, filename=False, dirname=False, strip=False)`
Render template string for photo. none_str is used if template substitution results in None value and no default specified.
@@ -1725,7 +1829,7 @@ Render template string for photo. none_str is used if template substitution res
- `inplace_sep`: optional string to use as separator between multi-valued keywords with expand_inplace; default is ','
- `filename`: if True, template output will be sanitized to produce valid file name
- `dirname`: if True, template output will be sanitized to produce valid directory name
- `replacement`: str, value to replace any illegal file path characters with; default = ":"
- `strip`: if True, leading/trailign whitespace will be stripped from rendered template strings
Returns a tuple of (rendered, unmatched) where rendered is a list of rendered strings with all substitutions made and unmatched is a list of any strings that resembled a template substitution but did not match a known substitution. E.g. if template contained "{foo}", unmatched would be ["foo"].
@@ -1739,7 +1843,7 @@ Some substitutions, notably `album`, `keyword`, and `person` could return multip
The template field format contains optional modifiers:
`"{[[DELIM]+]name[(PATH_SEP)][?TRUE_VALUE][,[DEFAULT]]}"`
`"{DELIM+name(PATH_SEP)[OLD,NEW]?TRUE_VALUE,DEFAULT}"`
`DELIM`: optional delimiter string to use when expanding multi-valued template values in-place
@@ -1760,6 +1864,8 @@ e.g. If Photo is in `Album1` in `Folder1`:
- `"{folder_album(:)}"` renders to `["Folder1:Album1"]`
- `"{folder_album()}"` renders to `["Folder1Album1"]`
`[OLD,NEW]`: optional text replacement to perform on rendered template value. For example, to replace "/" in an album name, you could use the template `"{album[/,-]}"`.
`?TRUE_VALUE`: optional value to use if name is boolean-type field which evaluates to true. For example `"{hdr}"` evaluates to True if photo is an high dynamic range (HDR) image and False otherwise. In these types of fields, use `?TRUE_VALUE` to provide the value if True and `,DEFAULT` to provide the value of False.
e.g. if photo is an HDR image,
@@ -2297,18 +2403,18 @@ The following template field substitutions are availabe for use with `PhotoInfo.
|{created.min}|2-digit minute of the photo creation time|
|{created.sec}|2-digit second of the photo creation time|
|{created.strftime}|Apply strftime template to file creation date/time. Should be used in form {created.strftime,TEMPLATE} where TEMPLATE is a valid strftime template, e.g. {created.strftime,%Y-%U} would result in year-week number of year: '2020-23'. If used with no template will return null value. See https://strftime.org/ for help on strftime templates.|
|{modified.date}|Photo's modification date in ISO format, e.g. '2020-03-22'|
|{modified.year}|4-digit year of photo modification time|
|{modified.yy}|2-digit year of photo modification time|
|{modified.mm}|2-digit month of the photo modification time (zero padded)|
|{modified.month}|Month name in user's locale of the photo modification time|
|{modified.mon}|Month abbreviation in the user's locale of the photo modification time|
|{modified.dd}|2-digit day of the month (zero padded) of the photo modification time|
|{modified.dow}|Day of week in user's locale of the photo modification time|
|{modified.doy}|3-digit day of year (e.g Julian day) of photo modification time, starting from 1 (zero padded)|
|{modified.hour}|2-digit hour of the photo modification time|
|{modified.min}|2-digit minute of the photo modification time|
|{modified.sec}|2-digit second of the photo modification time|
|{modified.date}|Photo's modification date in ISO format, e.g. '2020-03-22'; uses creation date if photo is not modified|
|{modified.year}|4-digit year of photo modification time; uses creation date if photo is not modified|
|{modified.yy}|2-digit year of photo modification time; uses creation date if photo is not modified|
|{modified.mm}|2-digit month of the photo modification time (zero padded); uses creation date if photo is not modified|
|{modified.month}|Month name in user's locale of the photo modification time; uses creation date if photo is not modified|
|{modified.mon}|Month abbreviation in the user's locale of the photo modification time; uses creation date if photo is not modified|
|{modified.dd}|2-digit day of the month (zero padded) of the photo modification time; uses creation date if photo is not modified|
|{modified.dow}|Day of week in user's locale of the photo modification time; uses creation date if photo is not modified|
|{modified.doy}|3-digit day of year (e.g Julian day) of photo modification time, starting from 1 (zero padded); uses creation date if photo is not modified|
|{modified.hour}|2-digit hour of the photo modification time; uses creation date if photo is not modified|
|{modified.min}|2-digit minute of the photo modification time; uses creation date if photo is not modified|
|{modified.sec}|2-digit second of the photo modification time; uses creation date if photo is not modified|
|{today.date}|Current date in iso format, e.g. '2020-03-22'|
|{today.year}|4-digit year of current date|
|{today.yy}|2-digit year of current date|
@@ -2336,6 +2442,10 @@ The following template field substitutions are availabe for use with `PhotoInfo.
|{place.address.country}|Country name of the postal address, e.g. 'United States'|
|{place.address.country_code}|ISO country code of the postal address, e.g. 'US'|
|{searchinfo.season}|Season of the year associated with a photo, e.g. 'Summer'; (Photos 5+ only, applied automatically by Photos' image categorization algorithms).|
|{exif.camera_make}|Camera make from original photo's EXIF inormation as imported by Photos, e.g. 'Apple'|
|{exif.camera_model}|Camera model from original photo's EXIF inormation as imported by Photos, e.g. 'iPhone 6s'|
|{exif.lens_model}|Lens model from original photo's EXIF inormation as imported by Photos, e.g. 'iPhone 6s back camera 4.15mm f/2.2'|
|{uuid}|Photo's internal universally unique identifier (UUID) for the photo, a 36-character string unique to the photo, e.g. '128FB4C6-0B16-4E7D-9108-FB2E90DA1546'|
|{album}|Album(s) photo is contained in|
|{folder_album}|Folder path + album photo is contained in. e.g. 'Folder/Subfolder/Album' or just 'Album' if no enclosing folder|
|{keyword}|Keyword(s) assigned to photo|
@@ -2471,6 +2581,7 @@ Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/d
<td align="center"><a href="https://github.com/hhoeck"><img src="https://avatars1.githubusercontent.com/u/6313998?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Horst Höck</b></sub></a><br /><a href="https://github.com/RhetTbull/osxphotos/commits?author=hhoeck" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/jstrine"><img src="https://avatars1.githubusercontent.com/u/33943447?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Jonathan Strine</b></sub></a><br /><a href="https://github.com/RhetTbull/osxphotos/commits?author=jstrine" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/finestream"><img src="https://avatars1.githubusercontent.com/u/16638513?v=4?s=100" width="100px;" alt=""/><br /><sub><b>finestream</b></sub></a><br /><a href="https://github.com/RhetTbull/osxphotos/commits?author=finestream" title="Documentation">📖</a></td>
<td align="center"><a href="https://github.com/synox"><img src="https://avatars2.githubusercontent.com/u/2250964?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Aravindo Wingeier</b></sub></a><br /><a href="https://github.com/RhetTbull/osxphotos/commits?author=synox" title="Documentation">📖</a></td>
</tr>
</table>
@@ -2506,6 +2617,7 @@ For additional details about how osxphotos is implemented or if you would like t
- [pathvalidate](https://pypi.org/project/pathvalidate/)
- [wurlitzer](https://pypi.org/project/wurlitzer/)
- [toml](https://github.com/uiri/toml)
- [PhotoScript](https://github.com/RhetTbull/PhotoScript)
## Acknowledgements

View File

@@ -222,66 +222,118 @@ The following attributes may be used with '--xattr-template':
formatter.write("\n")
formatter.write_text(
"""
Several options, such as --directory, allow you to specify a template
which will be rendered to substitute template fields with values from the photo.
For example, '{created.month}' would be replaced with the month name of the photo creation date.
e.g. 'November'.
\n
Some options supporting templates may be repeated e.g., --keyword-template '{label}'
--keyword-template '{media_type}' to add both labels and media types to the
keywords.
\n
The general format for a template is '{TEMPLATE_FIELD[,[DEFAULT]]}'.
Some templates have optional modifiers in form
'{[[DELIM]+]TEMPLATE_FIELD[(PATH_SEP)][?VALUE_IF_TRUE][,[DEFAULT]]}'
\n
The ',' and DEFAULT value are optional.
If TEMPLATE_FIELD results in a null (empty) value, the default is '_'.
You may specify an alternate default value by appending ',DEFAULT' after template_field.
e.g. '{title,no_title}' would result in 'no_title' if the photo had no title.
You may include other text in the template string outside the {} and use more than
one template field, e.g. '{created.year} - {created.month}' (e.g. '2020 - November').
\n
Some template fields such as 'hdr' are boolean and resolve to True or False.
These take the form: '{TEMPLATE_FIELD?VALUE_IF_TRUE,VALUE_IF_FALSE}', e.g.
{hdr?is_hdr,not_hdr} which would result in 'is_hdr' if photo is an HDR
image and 'not_hdr' otherwise.
\n
Some template fields such as 'folder_template' are "path-like" in that they join
multiple elements into a single path-like string. For example, if photo is in
album Album1 in folder Folder1, '{folder_album}` results in 'Folder1/Album1'.
This is so these template fields may be used as paths in --directory.
If you intend to use such a field as a string, e.g. in the filename, you may specify
a different path separator using the form: '{TEMPLATE_FIELD(PATH_SEP)}'.
For example, using the example above, '{folder_album(-)}' would result in
'Folder1-Album1' and '{folder_album()}' would result in
'Folder1Album1'.
\n
Some templates may resolve to more than one value. For example, a photo can have
multiple keywords so '{keyword}' can result in multiple values. If used in a filename
or directory, these templates may result in more than one copy of the photo being exported.
For example, if photo has keywords "foo" and "bar", --directory '{keyword}' will result in
copies of the photo being exported to 'foo/image_name.jpeg' and 'bar/image_name.jpeg'.
\n
Multi-value template fields such as '{keyword}' may be expanded 'in place' with an optional
delimiter using the template form '{DELIM+TEMPLATE_FIELD}'. For example, a photo with
keywords 'foo' and 'bar':
\n
Several options, such as --directory, allow you to specify a template which
will be rendered to substitute template fields with values from the photo.
For example, '{created.month}' would be replaced with the month name of the
photo creation date. e.g. 'November'.
Some options supporting templates may be repeated e.g., --keyword-template
'{label}' --keyword-template '{media_type}' to add both labels and media
types to the keywords.
The general format for a template is '{TEMPLATE_FIELD,DEFAULT}'. The full template format is:
'{DELIM+TEMPLATE_FIELD(PATH_SEP)[OLD,NEW]?VALUE_IF_TRUE,DEFAULT}'
With a few exceptions (like '{created.strftime}') everything but the TEMPLATE_FIELD
is optional.
- 'DELIM+' Multi-value template fields such as '{keyword}' may be expanded 'in place'
with an optional delimiter using the template form '{DELIM+TEMPLATE_FIELD}'.
For example, a photo with keywords 'foo' and 'bar':
'{keyword}' renders to 'foo' and 'bar'
\n
'{,+keyword}' renders to: 'foo,bar'
\n
'{; +keyword}' renders to: 'foo; bar'
\n
'{+keyword}' renders to 'foobar'
\n
Some template fields such as '{media_type}' use the 'DEFAULT' value to allow customization
of the output. For example, '{media_type}' resolves to the special media type of the
photo such as 'panorama' or 'selfie'. You may use the 'DEFAULT' value to override
these in form: '{media_type,video=vidéo;time_lapse=vidéo_accélérée}'.
In this example, if photo is a time_lapse photo, 'media_type' would resolve to
'vidéo_accélérée' instead of 'time_lapse' and video would resolve to 'vidéo' if photo
is an ordinary video.
- 'TEMPLATE_FIELD' The name of the template field, for example 'keyword'
- '(PATH_SEP)' Some template fields such as '{folder_album}' are "path-like" in
that they join multiple elements into a single path-like string. For example,
if photo is in album Album1 in folder Folder1, '{folder_album}' results in
'Folder1/Album1'. This is so these template fields may be used as paths in
--directory. If you intend to use such a field as a string, e.g. in the
filename, you may specify a different path separator using the form:
'{TEMPLATE_FIELD(PATH_SEP)}'. For example, using the example above,
'{folder_album(-)}' would result in 'Folder1-Album1' and '{folder_album()}'
would result in 'Folder1Album1'.
- '[OLD,NEW]' Use the [OLD,NEW] option to replace text "OLD" in the template value
with text "NEW". For example, if you have album names with '/' in the album name you
could replace '/' with "-" using the template '{album[/,-]}'. This would replace
any occurence of "/" in the album name with "-"; album "Vacation/2019" would thus
become "Vacation-2019". You may specify more than one pair of OLD,NEW values by
listing them delimited by '|'. For example: '{album[/,-|:,-]}' to replace both
'/' and ':' by '-'. You can also use the [OLD,NEW] syntax to delete a character by
omitting the NEW value as in '{album[/,]}'.
- '?' Some template fields such as 'hdr' are boolean and resolve to True or False.
These take the form: '{TEMPLATE_FIELD?VALUE_IF_TRUE,VALUE_IF_FALSE}', e.g.
{hdr?is_hdr,not_hdr} which would result in 'is_hdr' if photo is an HDR image
and 'not_hdr' otherwise.
- ',DEFAULT' The ',' and DEFAULT value are optional. If TEMPLATE_FIELD results
in a null (empty) value, the template will result in default value of '_'.
You may specify an alternate default value by appending ',DEFAULT' after
template_field. Example: '{title,no_title}' would result in 'no_title' if the photo
had no title. Example: '{created.year}/{place.address,NO_ADDRESS}' but there was
no address associated with the photo, the resulting output would be:
'2020/NO_ADDRESS/photoname.jpg'. If specified, the default value may not
contain a brace symbol ('{' or '}').
Again, if you do not specify a default value and the template substitution has no
value, '_' (underscore) will be used as the default value. For example, in the
above example, this would result in '2020/_/photoname.jpg' if address was
null.
You may specify a null default (e.g. "" or empty string) by omitting the value
after the comma, e.g. {title,} which would render to "" if title had no value thus
effectively deleting the template from the resulting string.
You may include other text in the template string outside the {}
and use more than one template field in a single string,
e.g. '{created.year} - {created.month}' (e.g. '2020 - November').
Some templates may resolve to more than one value. For example, a photo can
have multiple keywords so '{keyword}' can result in multiple values. If used
in a filename or directory, these templates may result in more than one copy
of the photo being exported. For example, if photo has keywords "foo" and
"bar", --directory '{keyword}' will result in copies of the photo being
exported to 'foo/image_name.jpeg' and 'bar/image_name.jpeg'.
Some template fields such as '{media_type}' use the 'DEFAULT' value to allow
customization of the output. For example, '{media_type}' resolves to the
special media type of the photo such as 'panorama' or 'selfie'. You may use
the 'DEFAULT' value to override these in form:
'{media_type,video=vidéo;time_lapse=vidéo_accélérée}'. In this example, if
photo is a time_lapse photo, 'media_type' would resolve to 'vidéo_accélérée'
instead of 'time_lapse' and video would resolve to 'vidéo' if photo is an
ordinary video.
With the --directory and --filename options you may specify a template for the
export directory or filename, respectively. The directory will be appended to
the export path specified in the export DEST argument to export. For example,
if template is '{created.year}/{created.month}', and export destination DEST
is '/Users/maria/Pictures/export', the actual export directory for a photo
would be '/Users/maria/Pictures/export/2020/March' if the photo was created in
March 2020.
The templating system may also be used with the --keyword-template option to
set keywords on export (with --exiftool or --sidecar), for example, to set a
new keyword in format 'folder/subfolder/album' to preserve the folder/album
structure, you can use --keyword-template "{folder_album}"
In the template, valid template substitutions will be replaced by the
corresponding value from the table below. Invalid substitutions will result
in an error.
If you want the actual text of the template substition to appear in the
rendered name, use double braces, e.g. '{{' or '}}', thus using
'{created.year}/{{name}}' for --directory would result in output of
2020/{name}/photoname.jpg
"""
)
formatter.write("\n")
@@ -1515,7 +1567,7 @@ def query(
help="Set extended attribute ATTRIBUTE to TEMPLATE value. Valid attributes are: "
f"{', '.join(EXTENDED_ATTRIBUTE_NAMES_QUOTED)}. "
"For example, to set Finder comment to the photo's title and description: "
"'--xattr-template findercomment \"{title}; {descr}\" "
'\'--xattr-template findercomment "{title}; {descr}" '
"See Extended Attributes below for additional details on this option.",
)
@click.option(
@@ -1534,6 +1586,14 @@ def query(
"File extension will be added automatically--do not include an extension in the FILENAME template. "
"See below for additional details on templating system.",
)
@click.option(
"--strip",
is_flag=True,
help="Optionally strip leading and trailing whitespace from any rendered templates. "
'For example, if --filename template is "{title,} {original_name}" and image has no '
"title, resulting file would have a leading space but if used with --strip, this will "
"be removed.",
)
@click.option(
"--edited-suffix",
metavar="SUFFIX",
@@ -1697,6 +1757,7 @@ def export(
has_raw,
directory,
filename_template,
strip,
edited_suffix,
original_suffix,
place,
@@ -1835,6 +1896,7 @@ def export(
has_raw = cfg.has_raw
directory = cfg.directory
filename_template = cfg.filename_template
strip = cfg.strip
edited_suffix = cfg.edited_suffix
original_suffix = cfg.original_suffix
place = cfg.place
@@ -2200,6 +2262,7 @@ def export(
ignore_date_modified=ignore_date_modified,
use_photokit=use_photokit,
exiftool_option=exiftool_option,
strip=strip,
)
results += export_results
@@ -2224,13 +2287,14 @@ def export(
person_keyword=person_keyword,
exiftool_merge_keywords=exiftool_merge_keywords,
finder_tag_template=finder_tag_template,
strip=strip,
)
results.xattr_written.extend(tags_written)
results.xattr_skipped.extend(tags_skipped)
if xattr_template:
xattr_written, xattr_skipped = write_extended_attributes(
p, photo_files, xattr_template
p, photo_files, xattr_template, strip=strip
)
results.xattr_written.extend(xattr_written)
results.xattr_skipped.extend(xattr_skipped)
@@ -2770,6 +2834,7 @@ def export_photo(
ignore_date_modified=False,
use_photokit=False,
exiftool_option=None,
strip=False,
):
"""Helper function for export that does the actual export
@@ -2860,12 +2925,20 @@ def export_photo(
if photo.hasadjustments and photo.path_edited is None:
missing_edited = True
filenames = get_filenames_from_template(photo, filename_template, original_name)
filenames = get_filenames_from_template(
photo, filename_template, original_name, strip=strip
)
for filename in filenames:
if original_suffix:
rendered_suffix, unmatched = photo.render_template(
original_suffix, filename=True
)
try:
rendered_suffix, unmatched = photo.render_template(
original_suffix, filename=True, strip=strip
)
except ValueError:
raise click.BadOptionUsage(
"original_suffix",
f"Invalid template for --original-suffix '{original_suffix}'",
)
if not rendered_suffix or unmatched:
raise click.BadOptionUsage(
"original_suffix",
@@ -2892,7 +2965,7 @@ def export_photo(
)
dest_paths = get_dirnames_from_template(
photo, directory, export_by_date, dest, dry_run
photo, directory, export_by_date, dest, dry_run, strip=strip
)
sidecar = [s.lower() for s in sidecar]
@@ -3002,10 +3075,15 @@ def export_photo(
edited_ext = pathlib.Path(photo.filename).suffix
if edited_suffix:
rendered_suffix, unmatched = photo.render_template(
edited_suffix, filename=True
)
try:
rendered_suffix, unmatched = photo.render_template(
edited_suffix, filename=True, strip=strip
)
except ValueError:
raise click.BadOptionUsage(
"edited_suffix",
f"Invalid template for --edited-suffix '{edited_suffix}'",
)
if not rendered_suffix or unmatched:
raise click.BadOptionUsage(
"edited_suffix",
@@ -3104,7 +3182,7 @@ def export_photo(
return results
def get_filenames_from_template(photo, filename_template, original_name):
def get_filenames_from_template(photo, filename_template, original_name, strip=False):
"""get list of export filenames for a photo
Args:
@@ -3120,9 +3198,14 @@ def get_filenames_from_template(photo, filename_template, original_name):
"""
if filename_template:
photo_ext = pathlib.Path(photo.original_filename).suffix
filenames, unmatched = photo.render_template(
filename_template, path_sep="_", filename=True
)
try:
filenames, unmatched = photo.render_template(
filename_template, path_sep="_", filename=True, strip=strip
)
except ValueError:
raise click.BadOptionUsage(
"filename_template", f"Invalid template '{filename_template}'"
)
if not filenames or unmatched:
raise click.BadOptionUsage(
"filename_template",
@@ -3140,7 +3223,9 @@ def get_filenames_from_template(photo, filename_template, original_name):
return filenames
def get_dirnames_from_template(photo, directory, export_by_date, dest, dry_run):
def get_dirnames_from_template(
photo, directory, export_by_date, dest, dry_run, strip=False
):
"""get list of directories to export a photo into, creates directories if they don't exist
Args:
@@ -3167,7 +3252,12 @@ def get_dirnames_from_template(photo, directory, export_by_date, dest, dry_run):
dest_paths = [dest_path]
elif directory:
# got a directory template, render it and check results are valid
dirnames, unmatched = photo.render_template(directory, dirname=True)
try:
dirnames, unmatched = photo.render_template(
directory, dirname=True, strip=strip
)
except ValueError:
raise click.BadOptionUsage("directory", f"Invalid template '{directory}'")
if not dirnames or unmatched:
raise click.BadOptionUsage(
"directory",
@@ -3427,6 +3517,7 @@ def write_finder_tags(
person_keyword=None,
exiftool_merge_keywords=None,
finder_tag_template=None,
strip=False,
):
"""Write Finder tags (extended attributes) to files; only writes attributes if attributes on file differ from what would be written
@@ -3464,9 +3555,19 @@ def write_finder_tags(
if finder_tag_template:
rendered_tags = []
for template_str in finder_tag_template:
rendered, unmatched = photo.render_template(
template_str, none_str=_OSXPHOTOS_NONE_SENTINEL, path_sep="/"
)
try:
rendered, unmatched = photo.render_template(
template_str,
none_str=_OSXPHOTOS_NONE_SENTINEL,
path_sep="/",
strip=strip,
)
except ValueError:
raise click.BadOptionUsage(
"finder_tag_template",
f"Invalid template for --finder-tag-template': {template_str}",
)
if unmatched:
click.echo(
click.style(
@@ -3497,7 +3598,7 @@ def write_finder_tags(
return (written, skipped)
def write_extended_attributes(photo, files, xattr_template):
def write_extended_attributes(photo, files, xattr_template, strip=False):
""" Writes extended attributes to exported files
Args:
@@ -3510,9 +3611,18 @@ def write_extended_attributes(photo, files, xattr_template):
attributes = {}
for xattr, template_str in xattr_template:
rendered, unmatched = photo.render_template(
template_str, none_str=_OSXPHOTOS_NONE_SENTINEL, path_sep="/"
)
try:
rendered, unmatched = photo.render_template(
template_str,
none_str=_OSXPHOTOS_NONE_SENTINEL,
path_sep="/",
strip=strip,
)
except ValueError:
raise click.BadOptionUsage(
"xattr_template",
f"Invalid template for --xattr-template': {template_str}",
)
if unmatched:
click.echo(
click.style(

View File

@@ -1,5 +1,5 @@
""" version info """
__version__ = "0.39.2"
__version__ = "0.39.6"

View File

@@ -9,11 +9,11 @@
import json
import logging
import os
import re
import shutil
import subprocess
from functools import lru_cache # pylint: disable=syntax-error
# exiftool -stay_open commands outputs this EOF marker after command is run
EXIFTOOL_STAYOPEN_EOF = "{ready}"
EXIFTOOL_STAYOPEN_EOF_LEN = len(EXIFTOOL_STAYOPEN_EOF)
@@ -300,17 +300,28 @@ class ExifTool:
ver, _, _ = self.run_commands("-ver", no_file=True)
return ver.decode("utf-8")
def asdict(self):
def asdict(self, tag_groups=True):
"""return dictionary of all EXIF tags and values from exiftool
returns empty dict if no tags
Args:
tag_groups: if True (default), dict keys have tag groups, e.g. "IPTC:Keywords"; if False, drops groups from keys, e.g. "Keywords"
"""
json_str, _, _ = self.run_commands("-json")
if json_str:
exifdict = json.loads(json_str)
return exifdict[0]
else:
if not json_str:
return dict()
exifdict = json.loads(json_str)
exifdict = exifdict[0]
if not tag_groups:
# strip tag groups
exif_new = {}
for k, v in exifdict.items():
k = re.sub(r".*:", "", k)
exif_new[k] = v
exifdict = exif_new
return exifdict
def json(self):
""" returns JSON string containing all EXIF tags and values from exiftool """
json, _, _ = self.run_commands("-json")

View File

@@ -4,7 +4,6 @@
# reference: https://stackoverflow.com/questions/59330149/coreimage-ciimage-write-jpg-is-shifting-colors-macos/59334308#59334308
import logging
import pathlib
import Metal
@@ -16,6 +15,11 @@ from Foundation import NSDictionary
from wurlitzer import pipes
class ImageConversionError(Exception):
"""Base class for exceptions in this module. """
pass
class ImageConverter:
""" Convert images to jpeg. This class is a singleton
which will re-use the Core Image CIContext to avoid
@@ -60,6 +64,7 @@ class ImageConverter:
Raises:
ValueError if compression quality not in range 0.0 to 1.0
FileNotFoundError if input_path doesn't exist
ImageConversionError if error during conversion
"""
# accept input_path or output_path as pathlib.Path
@@ -89,8 +94,7 @@ class ImageConverter:
input_image = Quartz.CIImage.imageWithContentsOfURL_(input_url)
if input_image is None:
logging.debug(f"Could not create CIImage for {input_path}")
return False
raise ImageConversionError(f"Could not create CIImage for {input_path}")
output_colorspace = input_image.colorSpace() or Quartz.CGColorSpaceCreateWithName(
Quartz.CoreGraphics.kCGColorSpaceSRGB
@@ -105,8 +109,7 @@ class ImageConverter:
if not error:
return True
else:
logging.debug(
raise ImageConversionError(
"Error converting file {input_path} to jpeg at {output_path}: {error}"
)
return False

View File

@@ -832,7 +832,7 @@ class PhotoInfo:
inplace_sep=None,
filename=False,
dirname=False,
replacement=":",
strip=False,
):
"""Renders a template string for PhotoInfo instance using PhotoTemplate
@@ -847,7 +847,7 @@ class PhotoInfo:
with expand_inplace; default is ','
filename: if True, template output will be sanitized to produce valid file name
dirname: if True, template output will be sanitized to produce valid directory name
replacement: str, value to replace any illegal file path characters with; default = ":"
strip: if True, strips leading/trailing white space from resulting template
Returns:
([rendered_strings], [unmatched]): tuple of list of rendered strings and list of unmatched template values
@@ -861,7 +861,7 @@ class PhotoInfo:
inplace_sep=inplace_sep,
filename=filename,
dirname=dirname,
replacement=replacement,
strip=strip,
)
@property

View File

@@ -6,9 +6,9 @@
# 2. Needed to handle default values if template not found
# 3. Didn't want user to need to know python (e.g. by using Mako which is
# already used elsewhere in this project)
# 4. Couldn't figure out how to do #1 and #2 with str.format()
#
# This code isn't elegant but it seems to work well. PRs gladly accepted.
# This code isn't elegant and is prime for refactoring but it seems to work well. PRs gladly accepted.
import datetime
import locale
import os
@@ -70,18 +70,18 @@ TEMPLATE_SUBSTITUTIONS = {
+ "{created.strftime,%Y-%U} would result in year-week number of year: '2020-23'. "
+ "If used with no template will return null value. "
+ "See https://strftime.org/ for help on strftime templates.",
"{modified.date}": "Photo's modification date in ISO format, e.g. '2020-03-22'",
"{modified.year}": "4-digit year of photo modification time",
"{modified.yy}": "2-digit year of photo modification time",
"{modified.mm}": "2-digit month of the photo modification time (zero padded)",
"{modified.month}": "Month name in user's locale of the photo modification time",
"{modified.mon}": "Month abbreviation in the user's locale of the photo modification time",
"{modified.dd}": "2-digit day of the month (zero padded) of the photo modification time",
"{modified.dow}": "Day of week in user's locale of the photo modification time",
"{modified.doy}": "3-digit day of year (e.g Julian day) of photo modification time, starting from 1 (zero padded)",
"{modified.hour}": "2-digit hour of the photo modification time",
"{modified.min}": "2-digit minute of the photo modification time",
"{modified.sec}": "2-digit second of the photo modification time",
"{modified.date}": "Photo's modification date in ISO format, e.g. '2020-03-22'; uses creation date if photo is not modified",
"{modified.year}": "4-digit year of photo modification time; uses creation date if photo is not modified",
"{modified.yy}": "2-digit year of photo modification time; uses creation date if photo is not modified",
"{modified.mm}": "2-digit month of the photo modification time (zero padded); uses creation date if photo is not modified",
"{modified.month}": "Month name in user's locale of the photo modification time; uses creation date if photo is not modified",
"{modified.mon}": "Month abbreviation in the user's locale of the photo modification time; uses creation date if photo is not modified",
"{modified.dd}": "2-digit day of the month (zero padded) of the photo modification time; uses creation date if photo is not modified",
"{modified.dow}": "Day of week in user's locale of the photo modification time; uses creation date if photo is not modified",
"{modified.doy}": "3-digit day of year (e.g Julian day) of photo modification time, starting from 1 (zero padded); uses creation date if photo is not modified",
"{modified.hour}": "2-digit hour of the photo modification time; uses creation date if photo is not modified",
"{modified.min}": "2-digit minute of the photo modification time; uses creation date if photo is not modified",
"{modified.sec}": "2-digit second of the photo modification time; uses creation date if photo is not modified",
# "{modified.strftime}": "Apply strftime template to file modification date/time. Should be used in form "
# + "{modified.strftime,TEMPLATE} where TEMPLATE is a valid strftime template, e.g. "
# + "{modified.strftime,%Y-%U} would result in year-week number of year: '2020-23'. "
@@ -118,6 +118,10 @@ TEMPLATE_SUBSTITUTIONS = {
"{place.address.country}": "Country name of the postal address, e.g. 'United States'",
"{place.address.country_code}": "ISO country code of the postal address, e.g. 'US'",
"{searchinfo.season}": "Season of the year associated with a photo, e.g. 'Summer'; (Photos 5+ only, applied automatically by Photos' image categorization algorithms).",
"{exif.camera_make}": "Camera make from original photo's EXIF inormation as imported by Photos, e.g. 'Apple'",
"{exif.camera_model}": "Camera model from original photo's EXIF inormation as imported by Photos, e.g. 'iPhone 6s'",
"{exif.lens_model}": "Lens model from original photo's EXIF inormation as imported by Photos, e.g. 'iPhone 6s back camera 4.15mm f/2.2'",
"{uuid}": "Photo's internal universally unique identifier (UUID) for the photo, a 36-character string unique to the photo, e.g. '128FB4C6-0B16-4E7D-9108-FB2E90DA1546'",
}
# Permitted multi-value substitutions (each of these returns None or 1 or more values)
@@ -145,6 +149,29 @@ MULTI_VALUE_SUBSTITUTIONS = [
for field in TEMPLATE_SUBSTITUTIONS_MULTI_VALUED
]
# regular expressions for matching template syntax
RE_OPENING_BRACE = r"(?<!\{)\{" # match { but not {{
RE_DELIM = r"([^}]*\+)?" # group 1: optional DELIM+
RE_FIELD_NAME = r"([^\\,}+\?]+)" # group 2: field name
RE_PATH_SEP = r"(\([^{}\)]*\))?" # group 3: optional (PATH_SEP)
# + r"(\[[^{}\)]*\])?" # group 4: optional [REPLACE]
RE_REPLACE = r"(\[[^{}]*\])?" # group 4: optional [REPLACE]
RE_BOOL_VAL = r"(\?[^\\,}]*)?" # group 5: optional ?TRUE_VALUE for boolean fields
RE_DEFAULT_VAL = r"(,[\w\=\;\-\%. ]*)?" # group 6: optional ,DEFAULT
RE_CLOSING_BRACE = r"(?=\}(?!\}))\}" # match } but not }}
MATCH_GROUPS_TOTAL = 6
MATCH_GROUPS_DELIM = 1
MATCH_GROUPS_FIELD = 2
MATCH_GROUPS_PATH_SEP = 3
MATCH_GROUPS_REPLACE = 4
MATCH_GROUPS_BOOL_VAL = 5
MATCH_GROUPS_DEFAULT = 6
# default values for string manipulation template options
INPLACE_DEFAULT = ","
PATH_SEP_DEFAULT = os.path.sep
class PhotoTemplate:
""" PhotoTemplate class to render a template string from a PhotoInfo object """
@@ -163,9 +190,7 @@ class PhotoTemplate:
# gets initialized in get_template_value
self.today = None
def make_subst_function(
self, none_str, filename, dirname, replacement, get_func=None
):
def make_subst_function(self, none_str, filename, dirname, get_func=None):
""" returns: substitution function for use in re.sub
none_str: value to use if substitution lookup is None and no default provided
get_func: function that gets the substitution value for a given template field
@@ -174,37 +199,39 @@ class PhotoTemplate:
if get_func is None:
# used by make_subst_function to get the value for a template substitution
get_func = partial(
self.get_template_value,
filename=filename,
dirname=dirname,
replacement=replacement,
self.get_template_value, filename=filename, dirname=dirname
)
# closure to capture photo, none_str, filename, dirname in subst
def subst(matchobj):
groups = len(matchobj.groups())
if groups != 5:
if groups != MATCH_GROUPS_TOTAL:
raise ValueError(
f"Unexpected number of groups: expected 4, got {groups}"
f"Unexpected number of groups: expected {MATCH_GROUPS_TOTAL}, got {groups}"
)
delim = matchobj.group(1)
field = matchobj.group(2)
path_sep = matchobj.group(3)
bool_val = matchobj.group(4)
default = matchobj.group(5)
delim = matchobj.group(MATCH_GROUPS_DELIM)
field = matchobj.group(MATCH_GROUPS_FIELD)
path_sep = matchobj.group(MATCH_GROUPS_PATH_SEP)
replace = matchobj.group(MATCH_GROUPS_REPLACE)
bool_val = matchobj.group(MATCH_GROUPS_BOOL_VAL)
default = matchobj.group(MATCH_GROUPS_DEFAULT)
# drop the '+' on delim
delim = delim[:-1] if delim is not None else None
# drop () from path_sep
path_sep = path_sep.strip("()") if path_sep is not None else None
# drop [] from replace
replace = replace[1:-1] if replace is not None else None
# drop the ? on bool_val
bool_val = bool_val[1:] if bool_val is not None else None
# drop the comma on default
default_val = default[1:] if default is not None else None
try:
val = get_func(field, default_val, bool_val, delim, path_sep)
val = get_func(
field, default_val, bool_val, delim, path_sep, replacement=replace
)
except ValueError:
return matchobj.group(0)
@@ -228,7 +255,7 @@ class PhotoTemplate:
inplace_sep=None,
filename=False,
dirname=False,
replacement=":",
strip=False,
):
""" Render a filename or directory template
@@ -242,17 +269,17 @@ class PhotoTemplate:
with expand_inplace; default is ','
filename: if True, template output will be sanitized to produce valid file name
dirname: if True, template output will be sanitized to produce valid directory name
replacement: str, value to replace any illegal file path characters with; default = ":"
strip: if True, strips leading/trailing whitespace from rendered templates
Returns:
([rendered_strings], [unmatched]): tuple of list of rendered strings and list of unmatched template values
"""
if path_sep is None:
path_sep = os.path.sep
path_sep = PATH_SEP_DEFAULT
if inplace_sep is None:
inplace_sep = ","
inplace_sep = INPLACE_DEFAULT
# the rendering happens in two phases:
# phase 1: handle all the single-value template substitutions
@@ -265,19 +292,20 @@ class PhotoTemplate:
# regex to find {template_field,optional_default} in strings
# pylint: disable=anomalous-backslash-in-string
regex = (
r"(?<!\{)\{" # match { but not {{
+ r"([^}]*\+)?" # group 1: optional DELIM+
+ r"([^\\,}+\?]+)" # group 2: field name
+ r"(\([^{}\)]*\))?" # group 3: optional (PATH_SEP)
+ r"(\?[^\\,}]*)?" # group 4: optional ?TRUE_VALUE for boolean fields
+ r"(,[\w\=\;\-\%. ]*)?" # group 5: optional ,DEFAULT
+ r"(?=\}(?!\}))\}" # match } but not }}
RE_OPENING_BRACE
+ RE_DELIM
+ RE_FIELD_NAME
+ RE_PATH_SEP
+ RE_REPLACE
+ RE_BOOL_VAL
+ RE_DEFAULT_VAL
+ RE_CLOSING_BRACE
)
if type(template) is not str:
raise TypeError(f"template must be type str, not {type(template)}")
subst_func = self.make_subst_function(none_str, filename, dirname, replacement)
subst_func = self.make_subst_function(none_str, filename, dirname)
# do the replacements
rendered = re.sub(regex, subst_func, template)
@@ -306,14 +334,7 @@ class PhotoTemplate:
# '2011/Album2/keyword2/person1',]
rendered_strings = self._render_multi_valued_templates(
rendered,
none_str,
path_sep,
expand_inplace,
inplace_sep,
filename,
dirname,
replacement,
rendered, none_str, path_sep, expand_inplace, inplace_sep, filename, dirname
)
# process exiftool: templates
@@ -325,7 +346,6 @@ class PhotoTemplate:
inplace_sep,
filename,
dirname,
replacement,
)
# find any {fields} that weren't replaced
@@ -350,6 +370,11 @@ class PhotoTemplate:
sanitize_filename(rendered_str) for rendered_str in rendered_strings
]
if strip:
rendered_strings = [
rendered_str.strip() for rendered_str in rendered_strings
]
return rendered_strings, unmatched
def _render_multi_valued_templates(
@@ -361,7 +386,6 @@ class PhotoTemplate:
inplace_sep,
filename,
dirname,
replacement,
):
rendered_strings = [rendered]
new_rendered_strings = []
@@ -370,15 +394,16 @@ class PhotoTemplate:
for field in MULTI_VALUE_SUBSTITUTIONS:
# Build a regex that matches only the field being processed
re_str = (
r"(?<!\{)\{" # match { but not {{
+ r"([^}]*\+)?" # group 1: optional DELIM+
RE_OPENING_BRACE
+ RE_DELIM
+ r"("
+ field # group 2: field name
+ r")"
+ r"(\([^{}\)]*\))?" # group 3: optional (PATH_SEP)
+ r"(\?[^\\,}]*)?" # group 4: optional ?TRUE_VALUE for boolean fields
+ r"(,[\w\=\;\-\%. ]*)?" # group 5: optional ,DEFAULT
+ r"(?=\}(?!\}))\}" # match } but not }}
+ RE_PATH_SEP
+ RE_REPLACE
+ RE_BOOL_VAL
+ RE_DEFAULT_VAL
+ RE_CLOSING_BRACE
)
regex_multi = re.compile(re_str)
@@ -389,21 +414,29 @@ class PhotoTemplate:
matches = regex_multi.search(str_template)
if matches:
path_sep = (
matches.group(3).strip("()")
if matches.group(3) is not None
matches.group(MATCH_GROUPS_PATH_SEP).strip("()")
if matches.group(MATCH_GROUPS_PATH_SEP) is not None
else path_sep
)
replace = (
matches.group(MATCH_GROUPS_REPLACE)[1:-1]
if matches.group(MATCH_GROUPS_REPLACE) is not None
else None
)
values = self.get_template_value_multi(
field,
path_sep,
filename=filename,
dirname=dirname,
replacement=replacement,
replacement=replace,
)
if expand_inplace or matches.group(1) is not None:
if (
expand_inplace
or matches.group(MATCH_GROUPS_DELIM) is not None
):
delim = (
matches.group(1)[:-1]
if matches.group(1) is not None
matches.group(MATCH_GROUPS_DELIM)[:-1]
if matches.group(MATCH_GROUPS_DELIM) is not None
else inplace_sep
)
# instead of returning multiple strings, join values into a single string
@@ -413,7 +446,9 @@ class PhotoTemplate:
else None
)
def lookup_template_value_multi(lookup_value, *_):
def lookup_template_value_multi(
lookup_value, *args, **kwargs
):
""" Closure passed to make_subst_function get_func
Capture val and field in the closure
Allows make_subst_function to be re-used w/o modification
@@ -429,7 +464,6 @@ class PhotoTemplate:
none_str,
filename,
dirname,
replacement,
get_func=lookup_template_value_multi,
)
new_string = regex_multi.sub(subst, str_template)
@@ -440,7 +474,9 @@ class PhotoTemplate:
# create a new template string for each value
for val in values:
def lookup_template_value_multi(lookup_value, *_):
def lookup_template_value_multi(
lookup_value, *args, **kwargs
):
""" Closure passed to make_subst_function get_func
Capture val and field in the closure
Allows make_subst_function to be re-used w/o modification
@@ -456,7 +492,6 @@ class PhotoTemplate:
none_str,
filename,
dirname,
replacement,
get_func=lookup_template_value_multi,
)
new_string = regex_multi.sub(subst, str_template)
@@ -475,7 +510,6 @@ class PhotoTemplate:
inplace_sep,
filename,
dirname,
replacement,
):
# TODO: lots of code commonality with render_multi_valued_templates -- combine or pull out
# TODO: put these in globals
@@ -486,15 +520,15 @@ class PhotoTemplate:
inplace_sep = ","
# Build a regex that matches only the field being processed
# todo: pull out regexes into globals?
re_str = (
r"(?<!\{)\{" # match { but not {{
+ r"([^}]*\+)?" # group 1: optional DELIM+
+ r"(exiftool:[^\\,}+\?]+)" # group 3 field name
+ r"(\([^{}\)]*\))?" # group 3: optional (PATH_SEP)
+ r"(\?[^\\,}]*)?" # group 4: optional ?TRUE_VALUE for boolean fields
+ r"(,[\w\=\;\-\%. ]*)?" # group 5: optional ,DEFAULT
+ r"(?=\}(?!\}))\}" # match } but not }}
RE_OPENING_BRACE
+ RE_DELIM
+ r"(exiftool:[^\\,}+\?\[\]]+)" # group 3 field name
+ RE_PATH_SEP
+ RE_REPLACE
+ RE_BOOL_VAL
+ RE_DEFAULT_VAL
+ RE_CLOSING_BRACE
)
regex_multi = re.compile(re_str)
@@ -509,13 +543,17 @@ class PhotoTemplate:
# allmatches = regex_multi.finditer(str_template)
# for matches in allmatches:
path_sep = (
matches.group(3).strip("()")
if matches.group(3) is not None
matches.group(MATCH_GROUPS_PATH_SEP).strip("()")
if matches.group(MATCH_GROUPS_PATH_SEP) is not None
else path_sep
)
field = matches.group(2)
replace = (
matches.group(MATCH_GROUPS_REPLACE)[1:-1]
if matches.group(MATCH_GROUPS_REPLACE) is not None
else None
)
field = matches.group(MATCH_GROUPS_FIELD)
subfield = field[9:]
if not self.photo.path:
values = [None]
else:
@@ -528,12 +566,24 @@ class PhotoTemplate:
values = (
[values] if not isinstance(values, list) else values
)
if replace and values:
new_values = []
for value in values:
new_values.append(self.replace(value, replace))
values = new_values
# sanitize directory names if needed
if filename:
values = [sanitize_pathpart(value) for value in values]
elif dirname:
values = [sanitize_dirname(value) for value in values]
else:
values = [None]
if expand_inplace or matches.group(1) is not None:
if expand_inplace or matches.group(MATCH_GROUPS_DELIM) is not None:
delim = (
matches.group(1)[:-1]
if matches.group(1) is not None
matches.group(MATCH_GROUPS_DELIM)[:-1]
if matches.group(MATCH_GROUPS_DELIM) is not None
else inplace_sep
)
# instead of returning multiple strings, join values into a single string
@@ -541,7 +591,7 @@ class PhotoTemplate:
delim.join(sorted(values)) if values and values[0] else None
)
def lookup_template_value_exif(lookup_value, *_):
def lookup_template_value_exif(lookup_value, *args, **kwargs):
""" Closure passed to make_subst_function get_func
Capture val and field in the closure
Allows make_subst_function to be re-used w/o modification
@@ -555,7 +605,6 @@ class PhotoTemplate:
none_str,
filename,
dirname,
replacement,
get_func=lookup_template_value_exif,
)
new_string = regex_multi.sub(subst, str_template)
@@ -565,7 +614,9 @@ class PhotoTemplate:
# create a new template string for each value
for val in values:
def lookup_template_value_exif(lookup_value, *_):
def lookup_template_value_exif(
lookup_value, *args, **kwargs
):
""" Closure passed to make_subst_function get_func
Capture val and field in the closure
Allows make_subst_function to be re-used w/o modification
@@ -581,7 +632,6 @@ class PhotoTemplate:
none_str,
filename,
dirname,
replacement,
get_func=lookup_template_value_exif,
)
new_string = regex_multi.sub(subst, str_template)
@@ -599,7 +649,7 @@ class PhotoTemplate:
path_sep=None,
filename=False,
dirname=False,
replacement=":",
replacement=None,
):
"""lookup value for template field (single-value template substitutions)
@@ -679,73 +729,73 @@ class PhotoTemplate:
value = (
DateTimeFormatter(self.photo.date_modified).date
if self.photo.date_modified
else None
else DateTimeFormatter(self.photo.date).date
)
elif field == "modified.year":
value = (
DateTimeFormatter(self.photo.date_modified).year
if self.photo.date_modified
else None
else DateTimeFormatter(self.photo.date).year
)
elif field == "modified.yy":
value = (
DateTimeFormatter(self.photo.date_modified).yy
if self.photo.date_modified
else None
else DateTimeFormatter(self.photo.date).yy
)
elif field == "modified.mm":
value = (
DateTimeFormatter(self.photo.date_modified).mm
if self.photo.date_modified
else None
else DateTimeFormatter(self.photo.date).mm
)
elif field == "modified.month":
value = (
DateTimeFormatter(self.photo.date_modified).month
if self.photo.date_modified
else None
else DateTimeFormatter(self.photo.date).month
)
elif field == "modified.mon":
value = (
DateTimeFormatter(self.photo.date_modified).mon
if self.photo.date_modified
else None
else DateTimeFormatter(self.photo.date).mon
)
elif field == "modified.dd":
value = (
DateTimeFormatter(self.photo.date_modified).dd
if self.photo.date_modified
else None
else DateTimeFormatter(self.photo.date).dd
)
elif field == "modified.dow":
value = (
DateTimeFormatter(self.photo.date_modified).dow
if self.photo.date_modified
else None
else DateTimeFormatter(self.photo.date).dow
)
elif field == "modified.doy":
value = (
DateTimeFormatter(self.photo.date_modified).doy
if self.photo.date_modified
else None
else DateTimeFormatter(self.photo.date).doy
)
elif field == "modified.hour":
value = (
DateTimeFormatter(self.photo.date_modified).hour
if self.photo.date_modified
else None
else DateTimeFormatter(self.photo.date).hour
)
elif field == "modified.min":
value = (
DateTimeFormatter(self.photo.date_modified).min
if self.photo.date_modified
else None
else DateTimeFormatter(self.photo.date).min
)
elif field == "modified.sec":
value = (
DateTimeFormatter(self.photo.date_modified).sec
if self.photo.date_modified
else None
else DateTimeFormatter(self.photo.date).sec
)
elif field == "today.date":
value = DateTimeFormatter(self.today).date
@@ -851,18 +901,56 @@ class PhotoTemplate:
)
elif field == "searchinfo.season":
value = self.photo.search_info.season if self.photo.search_info else None
elif field == "exif.camera_make":
value = self.photo.exif_info.camera_make if self.photo.exif_info else None
elif field == "exif.camera_model":
value = self.photo.exif_info.camera_model if self.photo.exif_info else None
elif field == "exif.lens_model":
value = self.photo.exif_info.lens_model if self.photo.exif_info else None
elif field == "uuid":
value = self.photo.uuid
else:
# if here, didn't get a match
raise ValueError(f"Unhandled template value: {field}")
if value and replacement:
value = self.replace(value, replacement)
# process character replacements
if filename:
value = sanitize_pathpart(value, replacement=replacement)
value = sanitize_pathpart(value)
elif dirname:
value = sanitize_dirname(value, replacement=replacement)
value = sanitize_dirname(value)
return value
def replace(self, value, replacement):
""" process REPLACE template option
Args:
value: str value to process
replacement: str in form OLD,NEW|OLD,NEW... with old and new values for replacement
Returns:
value with all replacements done
Raises:
ValueError if replacement string is in wrong format
"""
if not value:
return value
replacements = replacement.split("|")
for r in replacements:
try:
old, new = r.split(",")
except ValueError:
raise ValueError(f"Invalid template REPLACE value: {replacement}")
value = value.replace(old, new)
return value
def get_template_value_multi(
self, field, path_sep, filename=False, dirname=False, replacement=":"
self, field, path_sep, filename=False, dirname=False, replacement=None
):
"""lookup value for template field (multi-value template substitutions)
@@ -901,12 +989,9 @@ class PhotoTemplate:
if dirname:
# being used as a filepath so sanitize each part
folder = path_sep.join(
sanitize_dirname(f, replacement=replacement)
for f in album.folder_names
)
folder += path_sep + sanitize_dirname(
album.title, replacement=replacement
sanitize_dirname(f) for f in album.folder_names
)
folder += path_sep + sanitize_dirname(album.title)
else:
folder = path_sep.join(album.folder_names)
folder += path_sep + album.title
@@ -914,9 +999,7 @@ class PhotoTemplate:
else:
# album not in folder
if dirname:
values.append(
sanitize_dirname(album.title, replacement=replacement)
)
values.append(sanitize_dirname(album.title))
else:
values.append(album.title)
elif field == "comment":
@@ -934,18 +1017,23 @@ class PhotoTemplate:
self.photo.search_info.venue_types if self.photo.search_info else []
)
elif not field.startswith("exiftool:"):
# exiftool: templates handled by _render_exiftool_template
raise ValueError(f"Unhandled template value: {field}")
# do any replacements needs
if replacement:
new_values = []
for value in values:
# process replacements
new_values.append(self.replace(value, replacement))
values = new_values
# sanitize directory names if needed, folder_album handled differently above
if filename:
values = [
sanitize_pathpart(value, replacement=replacement) for value in values
]
values = [sanitize_pathpart(value) for value in values]
elif dirname and field != "folder_album":
# skip folder_album because it would have been handled above
values = [
sanitize_dirname(value, replacement=replacement) for value in values
]
values = [sanitize_dirname(value) for value in values]
# If no values, insert None so code below will substite none_str for None
values = values or [None]

View File

@@ -51,7 +51,7 @@ with open(os.path.join(this_directory, "README.md"), encoding="utf-8") as f:
setup(
name="osxphotos",
version=about["__version__"],
description="Manipulate (read-only) Apple's Photos app library on Mac OS X",
description="Export photos from Apple's macOS Photos app and query the Photos library database to access metadata about images.",
long_description=about["long_description"],
long_description_content_type="text/markdown",
author="Rhet Turnbull",

File diff suppressed because one or more lines are too long

View File

@@ -2880,7 +2880,6 @@ def test_export_filename_template_1():
],
)
assert result.exit_code == 0
workdir = os.getcwd()
files = glob.glob("*.*")
assert sorted(files) == sorted(CLI_EXPORTED_FILENAME_TEMPLATE_FILENAMES1)
@@ -2915,6 +2914,37 @@ def test_export_filename_template_2():
assert sorted(files) == sorted(CLI_EXPORTED_FILENAME_TEMPLATE_FILENAMES2)
def test_export_filename_template_strip():
""" export photos using filename template with --strip """
import glob
import locale
import os
import os.path
import osxphotos
from osxphotos.__main__ import export
locale.setlocale(locale.LC_ALL, "en_US")
runner = CliRunner()
cwd = os.getcwd()
# pylint: disable=not-context-manager
with runner.isolated_filesystem():
result = runner.invoke(
export,
[
os.path.join(cwd, CLI_PHOTOS_DB),
".",
"-V",
"--filename",
"{searchinfo.venue,} {created.year}-{original_name}",
"--strip",
],
)
assert result.exit_code == 0
files = glob.glob("*.*")
assert sorted(files) == sorted(CLI_EXPORTED_FILENAME_TEMPLATE_FILENAMES1)
def test_export_filename_template_pathsep_in_name_1():
""" export photos using filename template with folder_album and "/" in album name """
import locale

View File

@@ -57,6 +57,36 @@ EXIF_UUID = {
"IPTC:DateCreated": "2019:04:15",
},
}
EXIF_UUID_NO_GROUPS = {
"6191423D-8DB8-4D4C-92BE-9BBBA308AAC4": {
"DateTimeOriginal": "2019:07:04 16:24:01",
"LensModel": "XF18-55mmF2.8-4 R LM OIS",
"Keywords": [
"Digital Nomad",
"Indoor",
"Reiseblogger",
"Stock Photography",
"Top Shot",
"close up",
"colorful",
"design",
"display",
"fake",
"flower",
"outdoor",
"photography",
"plastic",
"stock photo",
"vibrant",
],
"DocumentNotes": "https://flickr.com/e/l7FkSm4f2lQkSV3CG6xlv8Sde5uF3gVu4Hf0Qk11AnU%3D",
},
"E9BC5C36-7CD1-40A1-A72B-8B8FAC227D51": {
"Make": "NIKON CORPORATION",
"Model": "NIKON D810",
"DateCreated": "2019:04:15",
},
}
EXIF_UUID_NONE = ["A1DD1F98-2ECD-431F-9AC9-5AFEFE2D3A5C"]
try:
@@ -319,6 +349,14 @@ def test_as_dict():
assert exifdata["XMP:TagsList"] == "wedding"
def test_as_dict_no_tag_groups():
import osxphotos.exiftool
exif1 = osxphotos.exiftool.ExifTool(TEST_FILE_ONE_KEYWORD)
exifdata = exif1.asdict(tag_groups=False)
assert exifdata["TagsList"] == "wedding"
def test_json():
import osxphotos.exiftool
import json
@@ -349,6 +387,19 @@ def test_photoinfo_exiftool():
assert exif_dict[key] == val
def test_photoinfo_exiftool_no_groups():
""" test PhotoInfo.exiftool which returns ExifTool object for photo without tag group names"""
import osxphotos
photosdb = osxphotos.PhotosDB(dbfile=PHOTOS_DB)
for uuid in EXIF_UUID_NO_GROUPS:
photo = photosdb.photos(uuid=[uuid])[0]
exiftool = photo.exiftool
exif_dict = exiftool.asdict(tag_groups=False)
for key, val in EXIF_UUID_NO_GROUPS[uuid].items():
assert exif_dict[key] == val
def test_photoinfo_exiftool_none():
import osxphotos

View File

@@ -89,14 +89,15 @@ def test_image_converter_bad_file():
""" Try to convert a file that's not an image """
import pathlib
import tempfile
from osxphotos.imageconverter import ImageConverter
from osxphotos.imageconverter import ImageConverter, ImageConversionError
converter = ImageConverter()
tempdir = tempfile.TemporaryDirectory(prefix="osxphotos_")
with tempdir:
imgfile = pathlib.Path(TEST_NOT_AN_IMAGE)
outfile = pathlib.Path(tempdir.name) / f"{imgfile.stem}.jpeg"
assert not converter.write_jpeg(imgfile, outfile)
with pytest.raises(ImageConversionError):
converter.write_jpeg(imgfile, outfile)
def test_image_converter_missing_file():

View File

@@ -53,6 +53,7 @@ TEMPLATE_VALUES_MULTI_KEYWORDS = {
UUID_TITLE = "6191423D-8DB8-4D4C-92BE-9BBBA308AAC4"
TEMPLATE_VALUES_TITLE = {
"{title}": ["Tulips tied together at a flower shop"],
"{title[ ,_]}": ["Tulips_tied_together_at_a_flower_shop"],
"{+title}": ["Tulips tied together at a flower shop"],
"{,+title}": ["Tulips tied together at a flower shop"],
"{, +title}": ["Tulips tied together at a flower shop"],
@@ -74,7 +75,9 @@ UUID_BOOL_VALUES_NOT = {
UUID_EXIFTOOL = {
"A92D9C26-3A50-4197-9388-CB5F7DB9FA91": {
"{exiftool:EXIF:Make}": ["Canon"],
"{exiftool:EXIF:Make[Canon,CANON]}": ["CANON"],
"{exiftool:EXIF:Model}": ["Canon PowerShot G10"],
"{exiftool:EXIF:Model[ G10,]}": ["Canon PowerShot"],
"{exiftool:EXIF:Make}/{exiftool:EXIF:Model}": ["Canon/Canon PowerShot G10"],
"{exiftool:IPTC:Keywords,foo}": ["foo"],
},
@@ -87,6 +90,14 @@ UUID_EXIFTOOL = {
"UK",
"United Kingdom",
],
"{exiftool:IPTC:Keywords[ ,_|.,]}": [
"England",
"London",
"London_2018",
"St_James's_Park",
"UK",
"United_Kingdom",
],
"{,+exiftool:IPTC:Keywords}": [
"England,London,London 2018,St. James's Park,UK,United Kingdom"
],
@@ -96,7 +107,9 @@ UUID_EXIFTOOL = {
TEMPLATE_VALUES = {
"{name}": "128FB4C6-0B16-4E7D-9108-FB2E90DA1546",
"{original_name}": "IMG_1064",
"{original_name[_,-]}": "IMG-1064",
"{title}": "Glen Ord",
"{title[ ,]}": "GlenOrd",
"{descr}": "Jack Rose Dining Saloon",
"{created.date}": "2020-02-04",
"{created.year}": "2020",
@@ -123,6 +136,10 @@ TEMPLATE_VALUES = {
"{place.address.postal_code}": "20009",
"{place.address.country}": "United States",
"{place.address.country_code}": "US",
"{uuid}": "128FB4C6-0B16-4E7D-9108-FB2E90DA1546",
"{exif.camera_make}": "Apple",
"{exif.camera_model}": "iPhone 6s",
"{exif.lens_model}": "iPhone 6s back camera 4.15mm f/2.2",
}
@@ -170,17 +187,21 @@ TEMPLATE_VALUES_DATE_MODIFIED = {
}
TEMPLATE_VALUES_DATE_NOT_MODIFIED = {
# uses creation date instead of modified date
"{name}": "128FB4C6-0B16-4E7D-9108-FB2E90DA1546",
"{original_name}": "IMG_1064",
"{modified.date}": "_",
"{modified.year}": "_",
"{modified.yy}": "_",
"{modified.mm}": "_",
"{modified.month}": "_",
"{modified.mon}": "_",
"{modified.dd}": "_",
"{modified.doy}": "_",
"{modified.dow}": "_",
"{modified.date}": "2020-02-04",
"{modified.year}": "2020",
"{modified.yy}": "20",
"{modified.mm}": "02",
"{modified.month}": "February",
"{modified.mon}": "Feb",
"{modified.dd}": "04",
"{modified.dow}": "Tuesday",
"{modified.doy}": "035",
"{modified.hour}": "19",
"{modified.min}": "07",
"{modified.sec}": "38",
}
@@ -785,3 +806,4 @@ def test_exiftool_template():
for template in UUID_EXIFTOOL[uuid]:
rendered, _ = photo.render_template(template)
assert sorted(rendered) == sorted(UUID_EXIFTOOL[uuid][template])