Unofficial archive. This is a read-only, community-run archive of the Apple Support Community. It is not affiliated with or endorsed by Apple Inc.

Anyone scripting Photos.app yet?

I have just started exploring the (quite limited) Applescript support in the new Photos app introduced with OS X 10.10.3.


One of my first tests was to try adding a keyword to every "media item" (photos & videos) to resolve a discrepancy in the item counts the app shows in its Info window & in the main one when the latter is set to the "All Photos" view. This is the not particularly elegant script I used:

tell application "Photos"
set newKeyword to "found_it"
set medTot to count of media items
repeat with mediaIndx from 1 to medTot
tell media item mediaIndx
if keywords = missing value then
set keywords to newKeyword
else
set keywords to keywords & newKeyword
end if
delay 0.1

end tell
end repeat
end tell

It works, but there are two things about it that seem odd & I would appreciate any comments about:


• One is that even though the app's dictionary says keywords is a list of text, to add a keyword, I had to treat it as a single text object & concatenate the added keyword to it in the usual way with the & operator. Attempting to access the individual items of the list by an index reference into the list failed. I would like to know if anyone has had success with this, & if so what syntax worked.


It is perhaps worth noting that there is some internal logic at work here: if I try to add an existing keyword through a script action, it does not create a second instance of that keyword. So it is sort of a 'smart' list, I guess.


• The other thing is the delay action. Without it, the repeat loop fails on some random media item with a 'can't get missing value' error. It seems that it takes a brief amount of time for Photos to create the first keyword for an item, & without the delay the script tells the app to get the next item's keywords before it has finished writing to the last one.


I would like to know if anyone else sees the same thing (failure without the delay) & if so, is the 0.1 second delay enough to avoid it. I'm using a 2012 iMac with a 2.9 GHz core i5 CPU, a moderately fast machine, so I would like to know if slower ones would need a longer delay, & if faster ones can get by with a shorter one (or none at all).


My tests were done with a media library of about 1200 items, but without the delay the failure always occurred somewhere in the first 50 or so, so 50 to 100 items should be enough for testing purposes. Also, once the test is done, you can use the app's Keyword Manager (in the windows menu) to remove the added keyword to return the library to its previous state. Be advised that this could take some time -- longer than the script takes to run, so if you are testing with a lot of items be patient -- the progress bar that will appear in the app may appear to hang at the end but it will eventually go away by itself.


Thanks for reading this far, & in advance for any comments you are kind enough to add to my overly long ramble.

37 replies

Hi


I have test AppleScript and the new App Photos for keyword operation


to add several keyword you must do that

-- create list

set listKeyWord to {}

- add keyword to list

copy "keyword1" to the end of listKeyWord

copy "keyword2" to the end of listKeyWord

--apply keyword to a picture

set keywords to listKeyWord


and you can retrieve these 2 keyword in Photos App


it's works for me


Regards

Thanks for that. The way Photos handles keywords is unusual. As my script demonstrates you can add a keyword by treating the keywords list as a text string (using the & operator), but as yours demonstrates that only works when adding a single keyword.


Weird!

Hi,


I try to make something the same (more or less). My test code for today is:


tell application "Photos"

set theContainersList to every container whose name is "XXX"

set theItemsList to every media item of the first item of theContainersList

repeat with theItem in theItemsList

get keywords of theItem

set theCurrentKeywordsList to result

if ”YYY” is not in theCurrentKeywordsList then tell theItem to set keywords to theCurrentKeywordsList & {”YYY”}

end repeat

end tell


It works mainly but sometimes I receive an AppleEvent error with incorrect index of the item, sometimes not. It looks that Photos doesn't keep ids of items permanently and I don't know for today how I can cope with it.


If anybody has an idea I would be really appreciated.

B

.

I think it might be that an empty keyword list returns missing value (which despite what it looks like isn't a text string) so you can't concatenate that with a text string like "YYY."


That's why I had to use the if/then/else clause in my script to test for the missing value result. You might try something like that & see if you get better results.

Thanks a lot R C-R. It was one reason of mistakes. I've already made it like it was in your example. But the other type of mistakes 'invalid index of media item'. I made some experiments. The script is working when the album is opened and isn't working when album is not opened (not in front window, for instance when we launched app but haven't opened any albums yet - model of situation when we have used 'activate' or 'launch' commands). So, the conclusion which we have a right to make: Photos.app is recalculating indexes (id) of all items in time when you open an album (container) and doesn't keep indexes of items permanently. Statement 'tell container "XXX" to activate' doesn't work unfortunately. For implementing keywords only to items in special album we should push Photo.app to open (bring on the front window) this album firstly... And it is a case which I can't solve.


My aim is to add special keywords to all items in album automatically especially when I add new items. Like it works in Folder actions. It is simple to make it by hands but I'm sure that in the future i will forget to make it and my smart-album wouldn't recognize these items.

I'm hitting the same wall over and over again trying to simply get any details out of a 'media item' object. No mater how I try and reference any of the attributes (filename, name, keywords, etc.) I continually get the error "Photos got an error: AppleEvent handler failed." number -10000


Here is a very simple script to log the filenames of selected items. I would truly appreciate some assistance on what I might be doing wrong here:

tellapplication "Photos"

try

set itemlist to selection

on error errStrnumbererrorNumber

return errorstr

endtry

set medTot to count of itemlist

ifmedTot = 0 then

display dialog "You have to select the images" buttons {"Cancel"}

errornumber -128

endif

log "Number of selected media items is " & medTot

repeat with mediaIndex in itemlist

logitemlist

tell mediaIndex

log "The filename is " & filename

endtell

endrepeat

endtell


The output currently is:


tell application "Photos"


get selection


(*Number of selected media items is 3*)


(*media item id P2nHm5%RR72aCQnj9TvNrg, media item id xGYuPCjsTz2JcUM3qLYBuw, media item id 249VfpJzTBaGRcRdluXCSw*)


get filename of media item id "P2nHm5%RR72aCQnj9TvNrg"

Result:

error "Photos got an error: AppleEvent handler failed." number -10000


Again, any help appreciated. I've tried it with several variants (assigning variables instead of logging, casting to different types, trying different media type attributes) but every time I try and deference the media type attribute, I get the handler failure.

I ran into similar problems trying to access media items by id inside tell statements. No idea why, but if you remove the tell mediaIndex & its matching endtell, & change the log statement that enclosed to log "The filename is " & filename of mediaIndex it should run fine.


EDIT: BTW, how did you get your script so nicely formatted in your reply? I have a script that used to format other scripts for display in web pages & put that on the clipboard, but it does not work with this version of the ASC software. 😟

Thanks R C-R, I had already tried that as well and just tried it again. Exact same outcome. Here is the revised script:


tell application "Photos"

try

set itemlist to selection

on error errStr number errorNumber

return errorstr

end try


set medTot to count of itemlist

if medTot = 0 then

display dialog "You have to select the images" buttons {"Cancel"}

error number -128

end if


log "Number of selected media items is " & medTot

log itemlist

repeat with mediaIndex in itemlist

log "The filename is " & filename of mediaIndex

end repeat

end tell


The results were:


(*Number of selected media items is 3*)

(*media item id P2nHm5%RR72aCQnj9TvNrg, media item id xGYuPCjsTz2JcUM3qLYBuw, media item id 249VfpJzTBaGRcRdluXCSw*)

Result:

error "Photos got an error: AppleEvent handler failed." number -10000



Does it work for you?


p.s. the nice formatting was a cut/past from applescript editor which maintained the coloring - but messed up the indentation, I then manually re-indented. I took too much time to do first time around, thus the rather plain cut/paste in the script above.

It does work fine for me. Below is the Events log for a typical run:


tell application "Photos"


get selection


(*Number of selected media items is 3*)


(*media item id 3OiTNwpkQYCuHm%6QZ+PCQ, media item id DYMmv0sXQySn97VSkQWlFw, media item id utzUBReNQZCaTPjOZMSlIA*)


get filename of media item id "3OiTNwpkQYCuHm%6QZ+PCQ"


(*The filename is TaDa!.jpg*)


get filename of media item id "DYMmv0sXQySn97VSkQWlFw"


(*The filename is BigTex.jpg*)


get filename of media item id "utzUBReNQZCaTPjOZMSlIA"


(*The filename is Woof.jpg*)

end tell

Hmm, maybe it's not an applescript error then. Perhaps something with my library.

Just to help debug, can you tell me the context of your selection in the Photos app? Were you in an album, the "moments/Photos" or something else.


Thanks again

I was in an Album view, one with 90 photos, all jpegs.


OK, found something very interesting in the debugging. When I used a different, smaller library - the code worked. When I switched back to my main library of about ~20K photos, it failed. Then, all of a sudden, it worked - but only a few times, then started failing again. I modified the code to keep trying on the error and keep track of the failures and I got some very interesting results. Below is a run from a selection of six images, the "errorcount" value is the number of time I received an error trying to get the filename before it finally got one.


(*Number of selected media items is 6*)

(*media item id lfb089rDQ1aQn%kESlLw5A, media item id 5JldvvOvTO2INNFHjWTQ2A, media item id WLM%GPU1QH6Wuv+2M7+2TQ, media item id EpZGePUFTWqTBgbSRqCsTQ, media item id FHV9oElTRZWxf56VC4ix6Q, media item id C4z2L0UKSH2t8Gph1AhY3A*)

(*The filename is suz_disp800.jpg and errorcount=8*)

(*The filename is DSC_1170.JPG and errorcount=6*)

(*The filename is suzh.jpg and errorcount=1*)

(*The filename is DSC_1169.JPG and errorcount=27*)

(*The filename is DSC_1169.JPG and errorcount=22*)

(*The filename is DSC_1170.JPG and errorcount=5*)


Later, it worked consistently with my large album several times for a few minutes, then started failing again. No change in code, no change in which images I'm selecting.


There definitely seems to be some sort of race condition going on. I would appreciate it if someone else with a large library could try the code and report back, I'd like to identify if this is a problem with my library or with larger libraries in general.

The code I'm using is:

tellapplication "Photos"

try

setitemlisttoselection

on error errStrnumbererrorNumber

returnerrorstr

endtry

set medTot to count of itemlist

ifmedTot = 0 then

display dialog "You have to select the images" buttons {"Cancel"}

errornumber -128

endif

log "Number of selected media items is " & medTot

logitemlist

repeat with mediaIndex in itemlist

seterrorcountto 0

repeat

try

log "The filename is " & filenameofmediaIndex & " and errorcount=" & errorcount

exitrepeat

onerrornumbererrNum

if (errNumis notequal to -10000) then

errornumbererrNum

endif

set errorcount to errorcount + 1

endtry

endrepeat

endrepeat

endtell

Have you tried introducing a short delay in the main repeat loop, sort of like what I had to do in the add keyword script in my first post?

I did, no noticeable effect

Since about 6,000 of my iPhoto photos ended up without titles after conversion to Photos, I have tried using a script someone shared on how to create photo titles out of the file names. I could not get it to work on my main computer, even though it works well for the author, and curiously enough it works on a different Mac I have. The script looks like this:


on run {input, parameters}

tell application "Photos"

activate

set imageSel to (get selection)

if imageSel is {} then

error "Please select an image."

else

repeat with im in imageSel

set title to the name of im

if not (exists (title)) then

set the name of im to the filename of im

end if

end repeat

end if

end tell

return input

end run


On my main iMac, if I have not selected any photos in Photos, it returns the message to "Please select an image.", but if I select one or more, there is an error message in running AppleScript. Strangely enough, on my secondary Mac, selecting no photos returns an error message, but with photos selected, it works like a charm...


Any ideas what could be causing this?

léonie's script is intended for use in an Automator "Run Applescript" action that creates an OS X Service workflow accessible from the Photos > Services menu item. For that use, it is desirable to begin by creating a new document of type Service in Automator:

User uploaded file

and in Automator to set the "Service receives" choices like this:

User uploaded file


If this is not how you created & are using her script, you may get unexpected results.


However, a few users who apparently are using it that way have reported errors occurring at the "set the name of im to the filename of im" line of the script. We are not sure why this is happening -- the script run as a service works without errors on my system so it is hard for me to see what the problem might be.


It may be helpful to run the script in Script Editor with the Replies log open to see exactly what the reported error is. I tried running it that way but Script Editor kept crashing. To avoid that, I had to comment out the following three lines in the script:

-- on run {input, parameters}

-- return input

-- end run


I don't know why that was necessary -- at worst I expected to get an error, not a crash!

Is it possible to automate the following three actions?


1. Automatically import items from selected folder (let's call it "ABC")


2. Share to iCloud Share Photos (let's call it "ABC-Shared"


3. Delete the files from the local library?


Thanks!

To answer (or suggest an answer) a couple of the questions in this thread:


  1. I have discovered that the "get selection" in Photos is extremely buggy. I notice also that the developers of Duplicate Annihilator are having the same problem. Furthermore, there are other discussions where one user has had zero problems when working with a selection, while other users (with the same script) have had huge problems.
    For me, with 25k media items in my library, getting the selection rarely works, returning the ""Photos got an error: AppleEvent handler failed." number -10000." In a repeat loop, sometimes it will process a few items in the selection and fail, other times it fails to even get the selection.
    But, it works perfectly using albums. So instead of using selection, I use a smart folder to get the items I want, and then add them to a temporary album and then use that album for my AppleScript... and it works fine. NOTE: AppleScript will not see Smart Albums, hence me adding items to a temporary album.
  2. To paste a script text so that it appears in this discussion as legible is a bit cumbersome, but not as cumbersome as a previous poster:
    1. Select all and copy the script from Script Editor.
    2. Paste this into a new Text Editor document.
    3. Save the Text Editor document as HTML to a temp file name (on your desktop).
    4. Open the saved file in Safari (just double click on the file)
    5. Copy the text from the Safari Windows...
    6. ... and paste into the discussion editor.
  3. I haven't yet played with KeyWords, but I do know that there seems to be a bug in Photos where a description or title that does not exist is treated differently both in Smart Folders and in AppleScript.
    1. If the media item never had a description or title, then it will appear in AppleScript as a missing value.
    2. But if it did once exist, and the user manually in Photos deleted it, then it will return an empty string in AppleScript
    3. EXCEPT... that you can't test myItem = "" as you would expect for an empty string. I only got it to work by counting the number of characters:
      ifcountofmyTitle) = 0 then ...

If anyone is interested, here is a script I have posted on some other discussions, that adds titles to items without titles from their filename (or even overwrites). You can download it form my DropBox: Photos Filename to Title V1.2

Regarding your #1 item, I suspect that it isn't so much a bug as that Photos does not always respond to script requests as quickly as it does to other events. Thus, it may be necessary to include delay statements in scripts, or where possible to use a try & repeat structure, to make sure Photos has time to respond to avoid the AE handler timing out & failing. Limiting the scope of the objects it references, like to an album, may accomplish much the same thing.


Regarding the #3 item, this isn't a bug, or at least if it is, it is one common to many apps. Basically, since there is no compelling reasons for apps to set an empty string value for anything unless & until there is a good reason to do so, it is up to the script writer to test for both an empty text string & no text string at all (IOW, the infamous missing value). countof works nicely for that in your script, but so do some other tests. Depending on the purpose of the script & the objects it works with, some other test might be faster or in some other way a better choice.


However, your #2 item is a great tip, & well worth the 'helpful' I gave it! 🙂 I have an old Applescript that would format one nicely for forums like this one, but the "new" ASC trashes it, so I will be using your method in the future. Well done!

I posted yesterday regarding the export function ofPhotos. Just wanted to mention that with the container statement it is possible to access smart albums. I can access them and for example log the names of the pics within, but export of the list is not possible.



Unlight

I stand corrected!


It is perfectly possible to get Smart Album containers.


I think I came to this conclusion early in playing with Photos, and I was failing for different reasons. But I have tested, and I can easily get the Smart Album and do anything with it that I can with any container (doh... it's a container)!


Apologies for the confusion.


BTW, I can export the photos from a Smart Album (aka any container) - I've answered your other thread / discussion.

Thanks for your comment on what I called a "bug."


I fully agree with your statement... but I called it a bug because not only can it catch out an Apple Scripter... it has caught out the developers of Photos because in a Smart Album, once I have had an item that once had a title or description that was subsequently removed, it will not return those items if I use the condition "Description is Empty" or "Title is Empty" - even though to the user they are absolutely empty. That is a bug in my opinion!

unlight wrote:

I posted yesterday regarding the export function ofPhotos. Just wanted to mention that with the container statement it is possible to access smart albums. I can access them and for example log the names of the pics within, but export of the list is not possible.

I posted a simple change to your Photos and Applescript export discussion that I think will make your export script run without errors. It wasn't obvious in that topic if your "NEW PHOTOS" album was a smart one or not, so I tested on my system using both smart & regular albums as the source, & with the change your script ran fine for me.


Good to know that the container reference works & that the "whose name is" specifier is supported with it. 🙂


Inspired by your script, I played around a little with container references & discovered a couple of things that might be useful:


• You can reference an album (smart or regular) directly if you know its name with a statement like set theAlbum to container "test"


• get name of every container demonstrates that Faces & the built-in Panoramas, Videos, Time-lapse, & Bursts items that are listed as "albums" in the Photos sidebar are not containers, at least as far as Applescript is concerned, but Last Import is.

R C-R wrote:


• You can reference an album (smart or regular) directly if you know its name with a statement like set theAlbum to container "test"



But only if it is at the top level.


If you have an album in a folder, then you will also need to reference the folder:


set srcContainer to container "my album" of container "my folder"


or if you have sub folders, you'll need to continue, etc.


set srcContainer to container "my album" of container "my subfolder" of container "my main folder"

As far as I know, there is no support for a "Description is Empty" or "Title is Empty" test in the Photos Applescript dictionary, or for that matter an "empty" property of any 'noun' object in the dictionary of any app I am familiar with. If you were to try to compile an script with either of these forms inside a tell application "Photos" construction, "empty" would be interpreted as a variable, which you would have to set to something to use it as a test.


That's one of the things you have to be careful about when writing Applescripts -- you cannot assume that anything in the user interface of an app is directly comparable to anything in its dictionary. Even though Applescript uses an English-like language, & smart enough to do certain unambiguous class coercions that are not explicitly stated in a script, it is still just an interface to an abstract, object oriented model of the app that exposes script writers to things that the UI hides.


One of those things is text strings. Consider for instance that in the UI users can't easily tell if a text item is truly empty, unassigned, or consists only of white space (spaces, tabs, etc.). In the UI, that distinction may not be significant; at the scripting level it always is (which is what your 'count of' test addresses).

NicFletcher wrote:

R C-R wrote:

• You can reference an album (smart or regular) directly if you know its name with a statement like set theAlbum to container "test"

But only if it is at the top level.

Of course. You always have to take into account the object hierarchy in any app's Applescript dictionary.

Sorry if I wasn't clear. I meant while using the Photos app and creating a Smart Album through the user interface.

There is, in my opinion, a serious bug with Title & Description when searching for "is empty" or "is not empty" because it doesn't return the correct results.


But I fully agree with everything you write about Applescript. Indeed we could overcome the above "bug" in the app.

I found this post as the only help for Photos scripting, I used to use a bunch of apple scripts to label photos quickly. It of course no longer works in Photos. I was trying to update it with the help of this set of posts but I only hit errors like "Photos got an error: Can’t get keywords."

I was wondering if anyone could help me get this working. This is an amalgamation of my original script and what I learned here. Any help or direction would be greatly appreciated.

tell application "Photos"

set myPictures to selection

repeat with mypicture in myPictures

(choose from list {"Picture: Color", "Picture: B/W"} ¬


with prompt "Color?")

set theword to result as text

set keywords to keywords & theword

end repeat

end tell

The error occurs because you have not specified what the keywords property refers to. You need to change the set keywords line to something like this:

set keywords of mypicture to keywords of mypicture & theword


That will work as long as the selected items already have at least one keyword. If not, you will get an error, "Can’t make missing value into type text" because "missing value" isn't text, so you can't concatenate text with it. Trap that out with a test for missing value & the script should do what you want for any selection.

Hi,


Try this:


tell application "Photos"

set myPictures to selection

repeat with mypicture in myPictures

(choose from list {"Picture: Color", "Picture: B/W"} ¬

with prompt "Color?")

set theword to result as text

set oldKeyWords to keywords of mypicture

if theword is not in oldKeyWords then

if not (existsoldKeyWords) then set oldKeyWords to {}

copy theword to end of oldKeyWords

set keywords of mypicture to oldKeyWords

end if

#set keywords to keywords & theword <-- This won't work!

end repeat

end tell


This contains both a test for no keywords existing (in which case you need to create an empty list) and also to make sure that you don't already have that keyword attached to the photo (although I haven't tested what happens if you try to set the keywords with a duplicate keyword, I think it's best to be safe).


Also, for what it's worth, many users have had issues using selection. You might want to do this by getting the album instead... but then it seems other users have not had issues. But if you see an AppleEvent Handler -1000 error, then you will need to put these pictures into a temporary album instead and loop through a reference to the album.


Finally, I wrote a script around a few weeks ago, mainly for me just to test how different things worked... and I've not had time to do much more with it. But it will show you different ways of referencing albums. etc.


You're welcome to take a look at it here: Testing with Photos V1.0


But please NOTE: It's a NOT a script to necessarily do anything (although I do have a go at finding duplicates, updating keywords, etc.)... RATHER, it is a collection of sections that show how to perform base functions such as getting containers or lists, and I wrote lots of notes to explain my findings. You will probably want to COMMENT out several sections when running it... and you will certainly need to read the script.

NicFletcher wrote:

This contains both a test for no keywords existing (in which case you need to create an empty list) and also to make sure that you don't already have that keyword attached to the photo (although I haven't tested what happens if you try to set the keywords with a duplicate keyword, I think it's best to be safe).

Although the keywords property is a list, Photos does not object if you treat it as a text object for concatenation purposes, which is why the and operator ("&") works when adding a keyword to a keyword list. It also won't duplicate keywords, even if a script tells it to do so. Because of that, the test for duplicates is unnecessary.


Also, the if not (existsoldKeyWords) test works to detect the missing value condition, which occurs if no keyword has ever been set for the item, but won't detect an empty keywords list (a string value of ""), which occurs if all existing keywords for the item have been deleted, or even if a user clicks on the title area of a thumbnail but doesn't type anything before clicking elsewhere. That shouldn't matter in your script because you are explicitly treating the keywords list as a list (with the end of construction), but it is one of the things that can complicate 'exists' tests in many apps that behave the same way.

Thanks for your observations.


Good to know that one doesn't need to test for a Keyword already existing.


Also a useful comment on the if not (existsoldKeyWords) test. However, as you seem to observe, I believe for clarity's sake it is best to always treat a property in it's right class - in this case a list. And (apart from my redundancy already discussed) this script will work, and it's not necessary to check further.


But, you are right, that if I was only checking for the absence of a keyword, I would fail to trap those media items that had once had Keywords and then had them removed. So I would also need to test for an empty list as well. Thank you!

I only mentioned how Photos handles keywords lists because it is unusual. I agree that it is always best to treat objects in their proper class but one of the nice features of Applescript is automatic coercion between classes when it is unambiguous. Of course, I'm not sure that's what's happening with keywords, or even if this will continue to work in updated versions of the app.


In a few other topics about using Applescript with Photos some other oddities have been noted, so at this point I consider it a work in progress.

Thank you so much! This is script saves me so much time!

To all posters:


Are Applescript actions working any better in the El Capitan version of Photos?


Or are you all seeing the same set of problems?


Thanks!