Friday, July 19, 2019

#26 2019-05-13 09:42:00 am

Yvan Koenig
Member
Registered: 2006-09-14
Posts: 3471

Re: Can Applescript read an XML file stored as a variable?

What you get is logical.
When your script execute return theName it exits the loop.

Try with:

Applescript:

set theseFiles to (choose file with multiple selections allowed)
set theNames to {}
repeat with thisFile in theseFiles
   set tracks to the mediainfoFile(thisFile)'s tracks
   set PromoCodec to (trackInfo given type:"Video", key:"Commercial_name")
   set thename to name of (info for the thisFile) & " " & PromoCodec & " "
   set end of theNames to thename
end repeat
return theNames
# Here are the handlers

Yvan KOENIG running High Sierra 10.13.6 in French (VALLAURIS, France) lundi 13 mai 2019  17:41:53

Offline

 

#27 2019-05-13 10:42:16 am

JQ
Member
Registered: 2019-02-04
Posts: 36

Re: Can Applescript read an XML file stored as a variable?

Here is the almost finished script.  It works exactly how I need it to.  It can read multiple files and the error checks I've built in process everything correctly.  The only step left is to figure out how to make it work as a droplet/application.  Thank you all for your help getting me this far.

Applescript:


set theseFiles to (choose file with multiple selections allowed)
-- THESE ARE THE ERROR VARIABLES
set CodecError to 0 --Codec Errors will highlight the file GRAY
set DurationError to 0 --Duration Errors will highlight the file YELLOW
set InvalidDuration to 0
set InvalidS4MNumber to 0
set TotalCodecErrors to 0 -- COUNTS CODEC ERRORS
set TotalDurationErrors to 0 -- COUNTS PROMO DURATION ERRORS
set TotalS4MNumberErrors to 0 -- COUNTS BAD S4M NUMBERS IN FILENAMES
set TotalFileNameErrors to 0 -- COUNTS DURATION ERRORS OF TOP OF FILENAMES
set TotalPromoError to 0 -- RESULTS IN "FILE NOT PROPERLY PROCESSED"
set FilesWithCodecErrors to "" -- CREATES A LIST OF THE PROMOS THAT HAVE CODEC ERRORS
set FilesWithDurationErrors to "" -- CREATES A LIST OF THE PROMOS THAT HAVE DURATION ERRORS
set FilesWithFileNameErrors to "" -- CREATES A LIST OF THE PROMOS THAT HAVE FILENAME ERRORS
set FilesWithS4MNumberErrors to "" -- CREATES A LIST OF THE PROMOS THAT HAVE S4M NUMBER ERRORS
set FilesNotProcessed to "" -- CREATES A LIST OF PROMOS THAT WERE NOT PROCESSED
set theRightFormats to {"XDCAM HD422", "50.0 Mbps", "29.970 fps"} as list

repeat with x from 1 to count of theseFiles -- STARTS CHECKING FILES IN SEQUENCE
   set thePromo to item x of theseFiles
   set tracks to the mediainfoFile(thePromo)'s tracks
   
   --WHEN MEDIAINFO READS AN MXF WITH XDCAM HD422 AS THE CODEC THE FIELD IS LABELLED
   --"Commercial_Name". THIS TRY BLOCK CHECKS THE CODEC FIELD OF THE XML
   --TO MAKE SURE THE PROPER CODEC FIELD IS PRESENT
   try
       set PromoCodec to (trackInfo given type:"Video", key:"Commercial_name")
       if the PromoCodec = false then
           set CodecError to 1
       end if
       
       --IF THE PROPER CODEC IS PRESENT THIS IS WHERE THE VARIABLES ARE POPULATED BY THE MEDIAINFOFILE HANDLER
       if CodecError is equal to 0 then
           set PromoBitRate to (trackInfo given type:"Video", key:"Bit_rate")
           set PromoDuration to (trackInfo given type:"Audio", id:2, key:"Duration")
           set PromoFrameRate to (trackInfo given type:"Video", key:"Frame_rate")
           set theDuration to returnNumbersInString(PromoDuration)
           set Duration to SAR(theDuration, ", ", ".")
           set FileName to do shell script "basename " & quoted form of POSIX path of thePromo
           set S4MDuration to the first word of FileName
       end if
   end try
   
   --THIS SECTION IS WHERE THE TRUNCATED FILE NAME IS CREATED
   try
       tell application "Finder"
           set extension hidden of thePromo to false
       end tell
       
       set theName to name of (info for thePromo)
       set thePath to the POSIX path of thePromo
       
       set n to the number of characters in theName
       
       set n to (n - 11)
       
       set JustS4MNumber to (characters n through end of theName) as string
       
       set theNewPath to quoted form of ("/Users/jquimby/Desktop/Proxies/" & JustS4MNumber)
       --THE ABOVE LINE IS WHERE THE FILE WILL BE POSTED IF IT PASSES ALL TECH CHECKS
       
       set theOldpath to quoted form of thePath
       set PromoError to 0
       
   on error
       set PromoError to 1
   end try
   
   --THIS IS THE BEGINNING OF THE TECH CHECKS
   if PromoError is equal to 0 and CodecError is equal to 0 then
       set theS4MNumber to the word -2 of theName --word -2 removes the file extension
       set S4MNumberCheck to the first word of JustS4MNumber
       
       --THIS SECTION CHECKS THAT THE FIRST WORD OF THE FILE NAME IS ACTUALLY A VALID NUMBER
       try
           set DurationCheck to (S4MDuration + 2)
       on error
           set InvalidDuration to 1
       end try
       
       --THIS SECTION ENSURES THE PROMO DURATION IS WITHIN A 2 FRAME RANGE OF THE TARGET DURATION
       if InvalidDuration is equal to 0 then
           set FramesHeavy to (S4MDuration + 0.66)
           set FramesLight to (S4MDuration - 0.66)
           if Duration is greater than FramesLight and Duration is less than FramesHeavy then
               set DurationError to 0
           else
               set DurationError to 1
           end if
       end if
       
       --THIS SECTION CHECKS THAT THE S4M NUMBER IS 8 DIGITS AND CONTAINS ONLY NUMBERS
       if the number of characters of theS4MNumber is equal to 8 then
           try
               set theS4MCalc to (theS4MNumber + 2)
           on error
               set InvalidS4MNumber to 1
           end try
       else
           set InvalidS4MNumber to 1
       end if
       if the number of characters of S4MNumberCheck is not equal to 8 then
           set InvalidS4MNumber to 1
       end if
       
       --THIS SECTION CHECKS TO ENSURE THE CODEC AND BIT RATE ARE CORRECT
       if PromoCodec is not in theRightFormats and PromoBitRate is not in theRightFormats then
           set CodecError to 1
       else
           set CodecError to 0
       end if
   end if
   
   --THIS SECTION CHECKS ALL THE ERROR COUNTERS, LABELS THE FILES IN FINDER, CREATES THE ERROR LIST, AND IF THE FILE PASSES ALL CHECKS IT WILL PASTE THE FILE INTO THE DESIRED DESTINATION    
   if PromoError is equal to 0 then
       tell application "Finder"
           if CodecError is not equal to 0 then -- CODEC ERROR CHECK
               set label index of thePromo to 2
               set TotalCodecErrors to TotalCodecErrors + 1
               set FilesWithCodecErrors to FilesWithCodecErrors & theName & "" & "    • codec is " & PromoCodec & "
               "

               set CodecError to 0
           else
               if InvalidS4MNumber is not equal to 0 then -- BAD S4M NUMBER FORMAT IN FILENAME
                   set label index of thePromo to 4
                   set FilesWithS4MNumberErrors to FilesWithS4MNumberErrors & theName & "
                   "

                   set TotalS4MNumberErrors to TotalS4MNumberErrors + 1
                   set InvalidS4MNumber to 0
               else
                   if DurationError is not equal to 0 then -- PROMO IS NOT WITHIN THE 2 FRAME BUFFER FOR DURATION
                       set label index of thePromo to 7
                       set TotalDurationErrors to TotalDurationErrors + 1
                       set FilesWithDurationErrors to FilesWithDurationErrors & theName & "
                       "

                       set DurationError to 0
                   else
                       if InvalidDuration is not equal to 0 then -- BAD DURATION FORMAT IN FILENAME
                           set label index of thePromo to 3
                           set TotalFileNameErrors to TotalFileNameErrors + 1
                           set FilesWithFileNameErrors to FilesWithFileNameErrors & theName & "
                   "
& "    • length is " & (round (Duration / 30)) & " seconds
                   "

                           set InvalidDuration to 0
                       else
                           set label index of thePromo to 6
                           do shell script "cp " & theOldpath & " " & theNewPath --THIS IS THE STEP THAT ACTUALLY COPIES THE FILE TO THE NEW LOCATION
                       end if
                   end if
               end if
           end if
       end tell
       set PromoError to 0
   end if
   if PromoError is not equal to 0 then
       tell application "Finder"
           set label index of thePromo to 5
           set TotalPromoError to TotalPromoError + 1
           set FilesNotProcessed to FilesNotProcessed & (name of (info for thePromo)) & "
               "

       end tell
   end if
end repeat -- END OF INDIVIDUAL FILE CHECK REPEAT LOOP

--THIS IS WHERE THE BATCH ERROR MESSAGES BEGIN

tell application "Finder"
   if FilesWithCodecErrors is not equal to "" then
       display dialog "..." & TotalCodecErrors & " file(s) are not the proper codec...
"
& FilesWithCodecErrors & "
(Label colour: red)"
buttons "Thanks"
   end if
   if FilesWithS4MNumberErrors is not equal to "" then
       display dialog "..." & TotalS4MNumberErrors & " file(s) do not have a proper S4M number...
   "
& FilesWithS4MNumberErrors & "(Label colour: blue)" buttons "Thanks"
   end if
   if FilesWithDurationErrors is not equal to "" then
       display dialog "..." & TotalDurationErrors & " file(s) were not the proper duration...
   "
& FilesWithDurationErrors & "(Label colour: yellow)" buttons "Thanks"
   end if
   if FilesWithFileNameErrors is not equal to "" then
       display dialog "..." & TotalFileNameErrors & " file(s) had incorrect durations in their file name(s).
   "
& FilesWithFileNameErrors & "(Label colour: purple)" buttons "Thanks"
   end if
   if FilesNotProcessed is not equal to "" then
       display dialog "..." & TotalPromoError & " file(s) were not properly processed.
       "
& FilesNotProcessed & "(Label colour: orange)" buttons "Thanks"
   end if
   if FilesWithCodecErrors is equal to "" and FilesWithS4MNumberErrors is equal to "" and FilesWithDurationErrors is equal to "" and FilesWithFileNameErrors is equal to "" and FilesNotProcessed is equal to "" then
       display dialog "All OK!" & theName & "
       (Label colour: green)"
buttons "Thanks"
   end if
end tell


--THIS HANDLER READS THE XML DATA:
on trackInfo given type:type as text, id:|id| as text : -1, key:key as text
   local key, |id|, type
   global tracks
   
   tell application "System Events"
       if |id| = -1 then
           set {trackdata} to the |tracks| where ¬
               value of the XML attribute "type" = |type|
       else
           set {trackdata} to the |tracks| where ¬
               value of the XML attribute "type" = |type| and ¬
               value of the XML attribute "streamid" = |id|
       end if
       
       tell (a reference to XML element named key in the trackdata) to ¬
           if it exists then
               return its value
           else
               return false
           end if
   end tell
end trackInfo

--THIS HANDLER GENERATES THE XML DATA
on mediainfoFile(inputstring) -- Only call this once per script run
   set theFile to quoted form of POSIX path of (inputstring)
   set xmltext to do shell script "usr/local/bin/mediainfo " & ¬
       theFile & " --Output=XML"
   
   tell application "System Events"
       set xml to make new XML data with properties {text:xmltext}
       set mediaInfo to XML element "Mediainfo" of xml
       set |file| to XML element "File" of mediaInfo
       
       return {|tracks|:a reference to XML elements of |file|}
   end tell
end mediainfoFile

--THIS HANDLER EXTRACTS NUMBERS FROM A STRING
on returnNumbersInString(inputstring)
   set s to quoted form of inputstring
   do shell script "sed s/[a-zA-Z\\']//g <<< " & s
   set dx to the result
   set numlist to {}
   repeat with i from 1 to count of words in dx
       set this_item to word i of dx
       try
           set this_item to this_item as number
           set the end of numlist to this_item
       end try
   end repeat
   return numlist
end returnNumbersInString

--THIS HANDLER SEARCHES A STRING FOR SPECIFIED CHARACTERS AND REPLACES THEM WITH THE DESIGNATED CHARACTERS
on SAR(main_text, search_text, replace_text)
   set old_delims to AppleScript's text item delimiters
   try
       set AppleScript's text item delimiters to search_text
       considering case
           set parts to every text item of main_text
       end considering
       set AppleScript's text item delimiters to replace_text
       set newText to (parts as string)
   end try
   set AppleScript's text item delimiters to old_delims
   return newText
end SAR

I thought it would be as simple as changing:

Applescript:


set theseFiles to (choose file with multiple selections allowed)

to:

Applescript:


on open theseFiles

then adding an "End Open" after I end the repeat.  But I start getting the "PromoCodec" not defined error again.  Is there something I'm missing in modifying the script so it can work as a droplet?

Offline

 

#28 2019-05-13 11:54:17 am

Yvan Koenig
Member
Registered: 2006-09-14
Posts: 3471

Re: Can Applescript read an XML file stored as a variable?

Save the code below as an application.
It will behave as a droplet if you dop selected files on its icon.

Applescript:

on run
   
   set theseFiles to (choose file with multiple selections allowed)
   common(theseFiles)
end run

on open sel
   common(sel)
   # CAUTION. Given a feature of the open handler, the list of files may be trated as two separate lists according to the quarantine status of the dropped files.
end open

on common(theseFiles)
   # Here most of your code
   
   # Fake code
   set thePaths to my recolle(theseFiles, linefeed)
   display dialog thePaths
end common

# Now your existing handlers


#===== Just to show the structure at work

on recolle(l, d)
   local oTIDs, t
   set {oTIDs, AppleScript's text item delimiters} to {AppleScript's text item delimiters, d}
   set t to l as text
   set AppleScript's text item delimiters to oTIDs
   return t
end recolle

#=====

Yvan KOENIG running High Sierra 10.13.6 in French (VALLAURIS, France) lundi 13 mai 2019  19:53:54

Offline

 

#29 2019-05-13 07:41:20 pm

CK
Member
From:: UK
Registered: 2018-11-04
Posts: 91

Re: Can Applescript read an XML file stored as a variable?

JQ wrote:

Ok, I've got the repeat step working with this script:

Applescript:

set theseFiles to (choose file with multiple selections allowed)
set thelist to ""
repeat with x from 1 to count of theseFiles
       set thisFile to item x of theseFiles
       set tracks to the mediainfoFile(thisFile)'s tracks
       set PromoCodec to (trackInfo given type:"Video", key:"Commercial_name")
       set thename to name of (info for the thisFile) & " " & PromoCodec & " "
       set thelist to thelist & " " & thename & " "
end repeat
return thelist


This might be better done like this:

Applescript:

set theseFiles to (choose file with multiple selections allowed)
set thelist to {}
repeat with i from 1 to count of theseFiles
       set thisFile to item i of theseFiles
       set tracks to the mediainfoFile(thisFile)'s tracks
       set PromoCodec to (trackInfo given type:"Video", key:"Commercial_name")
       set thename to name of (info for the thisFile) & space & PromoCodec
       set the end of thelist to thename
end repeat
return thelist

This returns an AppleScript list that looks like this: (I used the same infofile twice)

{"mediainfo.xml XDCAM HD422", "mediainfo.xml XDCAM HD422"}

If you want it as a text-based list, say, one item per line, then:

Applescript:

set the text item delimiters to linefeed
return thelist as text

which produces this:

"mediainfo.xml XDCAM HD422
mediainfo.xml XDCAM HD422"

It feels a bit awkward having to resort to using a counter variable to iterate through the list.  The reason you felt you had to do that is because of the way the two different types of loop reference the items in the list: using a counter variable as above, one retrieves the list item directly:

Applescript:

set thisFile to item i of theseFiles

Using an iterator, the items in the list are retrieved as references, and need to be dereferenced (or evaluated) first:

Applescript:

repeat with thisFile in theseFiles
       thisFile as alias
       --OR:
       thisFile's contents
               .
               .
               .
end repeat

Therefore, you may find the problem that was solved by using the counter variable also gets solved like this:

Applescript:

set theseFiles to (choose file with multiple selections allowed)
set thelist to {}
repeat with thisFile in theseFiles
       set tracks to the mediainfoFile(thisFile as alias)'s tracks
       set PromoCodec to (trackInfo given type:"Video", key:"Commercial_name")
       set thename to name of (info for the thisFile) & space & PromoCodec
       set the end of thelist to thename
end repeat
return thelist

I'm still not a fan of the way you blanket lines of code within try blocks that don't need it.  Here's an example:

Applescript:

try
       tell application "Finder"
        set extension hidden of thePromo to false
       end tell

       set theName to name of (info for thePromo)
       set thePath to the POSIX path of thePromo
       set n to the number of characters in theName
       set n to (n - 11)
       set JustS4MNumber to (characters n through end of theName) as string
       set theNewPath to quoted form of ("/Users/jquimby/Desktop/Proxies/" & JustS4MNumber)
       --THE ABOVE LINE IS WHERE THE FILE WILL BE POSTED IF IT PASSES ALL TECH CHECKS
       set theOldpath to quoted form of thePath
       set PromoError to 0
on error
       set PromoError to 1
end try

This was chosen at random, actually, but having gone through each line individually, I can't discern how any of them would ever throw an error; and, if there were a risk, how there wouldn't be a very simple way to prevent it, or rectify it upon catching.

One line that is very potentially capable of throwing an error (and it would only be through bad luck and not poor coding), is set extension hidden of thePromo to false.  Assuming thePromo is a well-formed file reference that Finder can understand, then the only risk is from Finder being temperamental: so, if it were busy, or it just decided not to let you access the property, it might error.  Simply waiting until Finder is not blocked and then re-running the script solves that problem.

However, consider whether you need to set this property at all...  It looks like you might be doing it to ensure theName is assigned the full filename including extension, however this property is not affected by the visibility of the extension in Finder (only the displayed name accounts for this).  If you do need to set the property, then you may as well move the declaration of theName into the Finder block, and use Finder to access the name (rather than the deprecated info for).  It doesn't make a huge difference, given that info for has been deprecated for about ten years and still works perfectly reliably and actually much faster than Finder.  I'll let you decide.

The only other line capable of throwing an error is: set JustS4MNumber to (characters n through end of theName) as string.  Firstly, I'm going to suggest you re-write this line to:

Applescript:

set JustS4MNumber to text n thru -1 of theName

The reason for this is that retrieving characters produces a list, which you then have to coerce back to text, and that is subject to text item delimiters, which you haven't set.  Instead, obtain a text range gives you the substring as one chunk of text, so there's no need to coerce and no risk of getting back a string you didn't expect.  Now, the only way this can throw an error is if n is 0, i.e. if theName happened to be 11 characters long.

In summation for this particular try block, I would suggest it is completely unnecessary, and you simply need to ensure the thePromo is a valid file reference; and n isn't 0 (or, rather, the name of your files are at least 12 characters long).

I see Yvan has given some guidance about moving the script to an application.

Offline

 

#30 2019-05-13 08:08:31 pm

CK
Member
From:: UK
Registered: 2018-11-04
Posts: 91

Re: Can Applescript read an XML file stored as a variable?

JQ wrote:

Applescript:


on open theseFiles

then adding an "End Open" after I end the repeat.  But I start getting the "PromoCodec" not defined error again.  Is there something I'm missing in modifying the script so it can work as a droplet?

Oh, you can debug this quite simply by:

Applescript:

on open theseFiles
       return choose from list paragraphs of (theseFiles as text)

which will allow you to examine exactly what list of files is getting passed through to the on open handler.  Given what Yvan noted about the possibility of split lists of files if some are quarantined, resulting in theseFiles being a list of lists, you might see if it makes a difference were you to flatten the list and guarantee it is one-dimensional.  Here's a simple flatten() handler:

Applescript:

to flatten(L)
       local L
       
       if L = {} then return {}
       if L's class ≠ list then return {L}
       
       flatten(L's first item) & flatten(rest of L)
end flatten

To illustrate its function:

Applescript:

set L to {{1, 3, 4, {4, 5, {4, {{5}}, 5}, 5, {4, 3, 4}}, 4, 2, 3, 3}, {2, 3, {4, 5}}, 4}
flatten(L)

Result:
{1, 3, 4, 4, 5, 4, 5, 5, 5, 4, 3, 4, 4, 2, 3, 3, 2, 3, 4, 5, 4}

Offline

 

#31 2019-05-14 01:36:16 am

KniazidisR
Member
Registered: 2019-03-03
Posts: 222

Re: Can Applescript read an XML file stored as a variable?

KniazidisR wrote:
JQ wrote:



Is the code different when trying to make an application? I'm obviously missing something.



Of course you have a mistake. on open is the name of the special handler in AppleScript. This is the same as clicking on a specific file to open it. And you open the files one by one. After all, there is no multiple click ... Therefore, you need to use a different approach: create a new hot folder, attach a script of the following type to it:


Applescript:


on adding folder items to this_folder after receiving theseFiles
   set thelist to ""
   repeat with x from 1 to count of theseFiles
       set thisFile to item x of theseFiles
       set tracks to the mediainfoFile(thisFile)'s tracks
       set PromoCodec to (trackInfo given type:"Video", key:"Commercial_name")
       set thename to name of (info for the thisFile) & " " & PromoCodec & " "
       set thelist to thelist & " " & thename & " "
   end repeat
   display dialog "..." & thelist
end adding folder items to


--THIS HANDLER READS THE XML DATA:
on trackInfo given type:type as text, id:|id| as text : -1, key:key as text
   local key, |id|, |type|
   global tracks
   
   tell application "System Events"
       if |id| = -1 then
           set {trackdata} to the |tracks| where ¬
               value of the XML attribute "type" = |type|
       else
           set {trackdata} to the |tracks| where ¬
               value of the XML attribute "type" = |type| and ¬
               value of the XML attribute "streamid" = |id|
       end if
       
       tell (a reference to XML element named key in the trackdata) to ¬
           if it exists then
               return its value
           else
               return false
           end if
   end tell
end trackInfo

--THIS HANDLER GENERATES THE XML DOCUMENT
on mediainfoFile(inputstring) -- Only call this once per script run
   set theFile to quoted form of POSIX path of (inputstring)
   set xmltext to do shell script "usr/local/bin/mediainfo " & ¬
       theFile & " --Output=XML"
   
   tell application "System Events"
       set xml to make new XML data with properties {text:xmltext}
       set mediaInfo to XML element "Mediainfo" of xml
       set |file| to XML element "File" of mediaInfo
       
       return {|tracks|:a reference to XML elements of |file|}
   end tell
end mediainfoFile

Then you can drag or paste multiply files to HOT folder and process as batch. How to create HOT folder, I describe HERE. On adding files to this hot folder, will automatically start your script. Choose files command no need - you use hot folder like droplet.

Last edited by KniazidisR (2019-05-14 10:15:04 am)


macOS Mojave -- version 10.14.4
Safari -- version 12.1

Offline

 

#32 2019-05-14 11:33:54 am

JQ
Member
Registered: 2019-02-04
Posts: 36

Re: Can Applescript read an XML file stored as a variable?

I've tried all suggestions, and I'm still getting the error.  I think the error is within these lines:

Applescript:


on open theseFiles
repeat with i from 1 to count of theseFiles -- STARTS CHECKING FILES IN SEQUENCE
   set thePromo to item i of theseFiles
   set tracks to the mediainfoFile(thePromo)'s tracks
   
   try
       set PromoCodec to (trackInfo given type:"Video", key:"Commercial_name")
       if the PromoCodec = false then
           set CodecError to 1
       end if
       
       if CodecError is equal to 0 then
           set PromoBitRate to (trackInfo given type:"Video", key:"Bit_rate")
           set PromoDuration to (trackInfo given type:"Audio", id:2, key:"Duration")
           set PromoFrameRate to (trackInfo given type:"Video", key:"Frame_rate")
           set theDuration to returnNumbersInString(PromoDuration)
           set Duration to SAR(theDuration, ", ", ".")
           set FileName to do shell script "basename " & quoted form of POSIX path of thePromo
           set S4MDuration to the first word of FileName
       end if
   end try
end open

Inevitably, when I get to this line further down the script:

Applescript:


if PromoCodec is not in theRightFormats and PromoBitRate is not in theRightFormats then

I receive an error saying PromoCodec is not defined.

Yvan - I tried your suggestion, and I still run into the same issue.

If I remove the Try block from the above script it tells me that "tracks" is not defined.  Looking at Yvan's suggestion, I see that it shouldn't be an issue using a handler within a handler. I'm just confused as to why I can have a script working perfectly, but as soon as I try to make it an application it breaks.

If I add "on run" at the top and "end run" at the bottom (before my handlers) and export as an application it works, but I can't drag/drop files onto it. I have to double click on the app, select the files I want to process, then it will process them correctly. I just can't get my head around why using "on open" seems to break(for lack of a better word) this line:

Applescript:


set tracks to the mediainfoFile(thePromo)'s tracks

CK - I used your suggested return line to see what was being passed through the on open command, and all the files I selected were passed through.  Once I add "on open" it just for some reason will either not read or not generate the XML properly is my only guess. Or maybe it's the repeat line? I've tried both of these versions to no avail:

Applescript:


   repeat with i from 1 to count of theseFiles -- STARTS CHECKING FILES IN SEQUENCE
       set thePromo to item i of theseFiles
       set tracks to the mediainfoFile(thePromo)'s tracks

and

Applescript:


repeat with i from 1 to count of theseFiles -- STARTS CHECKING FILES IN SEQUENCE
set thePromo to item i of theseFiles
set tracks to the mediainfoFile(thePromo as alias)'s tracks

Offline

 

#33 2019-05-14 12:21:33 pm

JQ
Member
Registered: 2019-02-04
Posts: 36

Re: Can Applescript read an XML file stored as a variable?

I've progressively moved the "return" command down through the script to find where things stop populating.

Applescript:


on open theseFiles
   -- THESE ARE THE ERROR VARIABLES
   set CodecError to 0 --Codec Errors will highlight the file GRAY
   set DurationError to 0 --Duration Errors will highlight the file YELLOW
   set InvalidDuration to 0
   set InvalidS4MNumber to 0
   set TotalCodecErrors to 0 -- COUNTS CODEC ERRORS
   set TotalDurationErrors to 0 -- COUNTS PROMO DURATION ERRORS
   set TotalS4MNumberErrors to 0 -- COUNTS BAD S4M NUMBERS IN FILENAMES
   set TotalFileNameErrors to 0 -- COUNTS DURATION ERRORS OF TOP OF FILENAMES
   set TotalPromoError to 0 -- RESULTS IN "FILE NOT PROPERLY PROCESSED"
   set FilesWithCodecErrors to "" -- CREATES A LIST OF THE PROMOS THAT HAVE CODEC ERRORS
   set FilesWithDurationErrors to "" -- CREATES A LIST OF THE PROMOS THAT HAVE DURATION ERRORS
   set FilesWithFileNameErrors to "" -- CREATES A LIST OF THE PROMOS THAT HAVE FILENAME ERRORS
   set FilesWithS4MNumberErrors to "" -- CREATES A LIST OF THE PROMOS THAT HAVE S4M NUMBER ERRORS
   set FilesNotProcessed to "" -- CREATES A LIST OF PROMOS THAT WERE NOT PROCESSED
   set theRightFormats to {"XDCAM HD422", "50.0 Mbps", "29.970 fps"} as list
   
   repeat with i from 1 to count of theseFiles -- STARTS CHECKING FILES IN SEQUENCE
       set thePromo to item i of theseFiles
       set tracks to the mediainfoFile(thePromo)'s tracks
       
       --WHEN MEDIAINFO READS AN MXF WITH XDCAM HD422 AS THE CODEC THE FIELD IS LABELLED
       --"Commercial_Name". THIS TRY BLOCK CHECKS THE CODEC FIELD OF THE XML
       --TO MAKE SURE THE PROPER CODEC FIELD IS PRESENT
       try
           set PromoCodec to trackInfo given type:"Video", key:"Commercial_name"
----------------------------------------------------------------------------------------------------------------
           return choose from list paragraphs of (PromoCodec as text)
----------------------------------------------------------------------------------------------------------------
           if the PromoCodec = false then
               set CodecError to 1
           end if
           
           --IF THE PROPER CODEC IS PRESENT THIS IS WHERE THE VARIABLES ARE POPULATED BY THE MEDIAINFOFILE HANDLER
           if CodecError is equal to 0 then
               set PromoBitRate to (trackInfo given type:"Video", key:"Bit_rate")
               set PromoDuration to (trackInfo given type:"Audio", id:2, key:"Duration")
               set PromoFrameRate to (trackInfo given type:"Video", key:"Frame_rate")
               set theDuration to returnNumbersInString(PromoDuration)
               set Duration to SAR(theDuration, ", ", ".")
               set FileName to do shell script "basename " & quoted form of POSIX path of thePromo
               set S4MDuration to the first word of FileName
           end if
       end try
end open

--THIS HANDLER READS THE XML DATA:
on trackInfo given type:type as text, id:|id| as text : -1, key:key as text
   local key, |id|, type
   global tracks
   
   tell application "System Events"
       if |id| = -1 then
           set {trackdata} to the |tracks| where ¬
               value of the XML attribute "type" = |type|
       else
           set {trackdata} to the |tracks| where ¬
               value of the XML attribute "type" = |type| and ¬
               value of the XML attribute "streamid" = |id|
       end if
       
       tell (a reference to XML element named key in the trackdata) to ¬
           if it exists then
               return its value
           else
               return false
           end if
   end tell
end trackInfo

--THIS HANDLER GENERATES THE XML DATA
on mediainfoFile(inputstring) -- Only call this once per script run
   set theFile to quoted form of POSIX path of (inputstring)
   set xmltext to do shell script "usr/local/bin/mediainfo " & ¬
       theFile & " --Output=XML"
   
   tell application "System Events"
       set xml to make new XML data with properties {text:xmltext}
       set mediaInfo to XML element "Mediainfo" of xml
       set |file| to XML element "File" of mediaInfo
       
       return {|tracks|:a reference to XML elements of |file|}
   end tell
end mediainfoFile

--THIS HANDLER EXTRACTS NUMBERS FROM A STRING
on returnNumbersInString(inputstring)
   set s to quoted form of inputstring
   do shell script "sed s/[a-zA-Z\\']//g <<< " & s
   set dx to the result
   set numlist to {}
   repeat with i from 1 to count of words in dx
       set this_item to word i of dx
       try
           set this_item to this_item as number
           set the end of numlist to this_item
       end try
   end repeat
   return numlist
end returnNumbersInString

--THIS HANDLER SEARCHES A STRING FOR SPECIFIED CHARACTERS AND REPLACES THEM WITH THE DESIGNATED CHARACTERS
on SAR(main_text, search_text, replace_text)
   set old_delims to AppleScript's text item delimiters
   try
       set AppleScript's text item delimiters to search_text
       considering case
           set parts to every text item of main_text
       end considering
       set AppleScript's text item delimiters to replace_text
       set newText to (parts as string)
   end try
   set AppleScript's text item delimiters to old_delims
   return newText
end SAR

theseFiles populates and thePromo populates, which leads me to believe my XML handlers should work properly. But for some reason they aren't.

Last edited by JQ (2019-05-14 12:22:00 pm)

Offline

 

#34 2019-05-14 01:41:42 pm

Yvan Koenig
Member
Registered: 2006-09-14
Posts: 3471

Re: Can Applescript read an XML file stored as a variable?

I was reluctant to do that but see no alternate way to exchange seriously.

I inserted your original code in the proposed structure. I got :

Applescript:

on run
   set theseFiles to (choose file with multiple selections allowed)
   common(theseFiles)
end run
on open sel
   common(sel)
end open

on common(theseFiles)
   -- THESE ARE THE ERROR VARIABLES
   set CodecError to 0 --Codec Errors will highlight the file GRAY
   set DurationError to 0 --Duration Errors will highlight the file YELLOW
   set InvalidDuration to 0
   set InvalidS4MNumber to 0
   set TotalCodecErrors to 0 -- COUNTS CODEC ERRORS
   set TotalDurationErrors to 0 -- COUNTS PROMO DURATION ERRORS
   set TotalS4MNumberErrors to 0 -- COUNTS BAD S4M NUMBERS IN FILENAMES
   set TotalFileNameErrors to 0 -- COUNTS DURATION ERRORS OF TOP OF FILENAMES
   set TotalPromoError to 0 -- RESULTS IN "FILE NOT PROPERLY PROCESSED"
   set FilesWithCodecErrors to "" -- CREATES A LIST OF THE PROMOS THAT HAVE CODEC ERRORS
   set FilesWithDurationErrors to "" -- CREATES A LIST OF THE PROMOS THAT HAVE DURATION ERRORS
   set FilesWithFileNameErrors to "" -- CREATES A LIST OF THE PROMOS THAT HAVE FILENAME ERRORS
   set FilesWithS4MNumberErrors to "" -- CREATES A LIST OF THE PROMOS THAT HAVE S4M NUMBER ERRORS
   set FilesNotProcessed to "" -- CREATES A LIST OF PROMOS THAT WERE NOT PROCESSED
   set theRightFormats to {"XDCAM HD422", "50.0 Mbps", "29.970 fps"} as list
   
   repeat with x from 1 to count of theseFiles -- STARTS CHECKING FILES IN SEQUENCE
       set thePromo to item x of theseFiles
       set tracks to the mediainfoFile(thePromo)'s tracks
       
       --WHEN MEDIAINFO READS AN MXF WITH XDCAM HD422 AS THE CODEC THE FIELD IS LABELLED
       --"Commercial_Name". THIS TRY BLOCK CHECKS THE CODEC FIELD OF THE XML
       --TO MAKE SURE THE PROPER CODEC FIELD IS PRESENT
       try
           set PromoCodec to (trackInfo given type:"Video", key:"Commercial_name")
           if the PromoCodec = false then
               set CodecError to 1
           end if
           
           --IF THE PROPER CODEC IS PRESENT THIS IS WHERE THE VARIABLES ARE POPULATED BY THE MEDIAINFOFILE HANDLER
           if CodecError is equal to 0 then
               set PromoBitRate to (trackInfo given type:"Video", key:"Bit_rate")
               set PromoDuration to (trackInfo given type:"Audio", id:2, key:"Duration")
               set PromoFrameRate to (trackInfo given type:"Video", key:"Frame_rate")
               set theDuration to returnNumbersInString(PromoDuration)
               set Duration to SAR(theDuration, ", ", ".")
               set FileName to do shell script "basename " & quoted form of POSIX path of thePromo
               set S4MDuration to the first word of FileName
           end if
       end try
       
       --THIS SECTION IS WHERE THE TRUNCATED FILE NAME IS CREATED
       try
           tell application "Finder"
               set extension hidden of thePromo to false
           end tell
           
           set theName to name of (info for thePromo)
           set thePath to the POSIX path of thePromo
           
           set n to the number of characters in theName
           
           set n to (n - 11)
           
           set JustS4MNumber to (characters n through end of theName) as string
           
           set theNewPath to quoted form of ("/Users/jquimby/Desktop/Proxies/" & JustS4MNumber)
           --THE ABOVE LINE IS WHERE THE FILE WILL BE POSTED IF IT PASSES ALL TECH CHECKS
           
           set theOldpath to quoted form of thePath
           set PromoError to 0
           
       on error
           set PromoError to 1
       end try
       
       --THIS IS THE BEGINNING OF THE TECH CHECKS
       if PromoError is equal to 0 and CodecError is equal to 0 then
           set theS4MNumber to the word -2 of theName --word -2 removes the file extension
           set S4MNumberCheck to the first word of JustS4MNumber
           
           --THIS SECTION CHECKS THAT THE FIRST WORD OF THE FILE NAME IS ACTUALLY A VALID NUMBER
           try
               set DurationCheck to (S4MDuration + 2)
           on error
               set InvalidDuration to 1
           end try
           
           --THIS SECTION ENSURES THE PROMO DURATION IS WITHIN A 2 FRAME RANGE OF THE TARGET DURATION
           if InvalidDuration is equal to 0 then
               set FramesHeavy to (S4MDuration + 0.66)
               set FramesLight to (S4MDuration - 0.66)
               if Duration is greater than FramesLight and Duration is less than FramesHeavy then
                   set DurationError to 0
               else
                   set DurationError to 1
               end if
           end if
           
           --THIS SECTION CHECKS THAT THE S4M NUMBER IS 8 DIGITS AND CONTAINS ONLY NUMBERS
           if the number of characters of theS4MNumber is equal to 8 then
               try
                   set theS4MCalc to (theS4MNumber + 2)
               on error
                   set InvalidS4MNumber to 1
               end try
           else
               set InvalidS4MNumber to 1
           end if
           if the number of characters of S4MNumberCheck is not equal to 8 then
               set InvalidS4MNumber to 1
           end if
           
           --THIS SECTION CHECKS TO ENSURE THE CODEC AND BIT RATE ARE CORRECT
           if PromoCodec is not in theRightFormats and PromoBitRate is not in theRightFormats then
               set CodecError to 1
           else
               set CodecError to 0
           end if
       end if
       
       --THIS SECTION CHECKS ALL THE ERROR COUNTERS, LABELS THE FILES IN FINDER, CREATES THE ERROR LIST, AND IF THE FILE PASSES ALL CHECKS IT WILL PASTE THE FILE INTO THE DESIRED DESTINATION    
       if PromoError is equal to 0 then
           tell application "Finder"
               if CodecError is not equal to 0 then -- CODEC ERROR CHECK
                   set label index of thePromo to 2
                   set TotalCodecErrors to TotalCodecErrors + 1
                   set FilesWithCodecErrors to FilesWithCodecErrors & theName & "" & "    • codec is " & PromoCodec & "
               "

                   set CodecError to 0
               else
                   if InvalidS4MNumber is not equal to 0 then -- BAD S4M NUMBER FORMAT IN FILENAME
                       set label index of thePromo to 4
                       set FilesWithS4MNumberErrors to FilesWithS4MNumberErrors & theName & "
                   "

                       set TotalS4MNumberErrors to TotalS4MNumberErrors + 1
                       set InvalidS4MNumber to 0
                   else
                       if DurationError is not equal to 0 then -- PROMO IS NOT WITHIN THE 2 FRAME BUFFER FOR DURATION
                           set label index of thePromo to 7
                           set TotalDurationErrors to TotalDurationErrors + 1
                           set FilesWithDurationErrors to FilesWithDurationErrors & theName & "
                       "

                           set DurationError to 0
                       else
                           if InvalidDuration is not equal to 0 then -- BAD DURATION FORMAT IN FILENAME
                               set label index of thePromo to 3
                               set TotalFileNameErrors to TotalFileNameErrors + 1
                               set FilesWithFileNameErrors to FilesWithFileNameErrors & theName & "
                   "
& "    • length is " & (round (Duration / 30)) & " seconds
                   "

                               set InvalidDuration to 0
                           else
                               set label index of thePromo to 6
                               do shell script "cp " & theOldpath & " " & theNewPath --THIS IS THE STEP THAT ACTUALLY COPIES THE FILE TO THE NEW LOCATION
                           end if
                       end if
                   end if
               end if
           end tell
           set PromoError to 0
       end if
       if PromoError is not equal to 0 then
           tell application "Finder"
               set label index of thePromo to 5
               set TotalPromoError to TotalPromoError + 1
               set FilesNotProcessed to FilesNotProcessed & (name of (info for thePromo)) & "
               "

           end tell
       end if
   end repeat -- END OF INDIVIDUAL FILE CHECK REPEAT LOOP
   
   --THIS IS WHERE THE BATCH ERROR MESSAGES BEGIN
   
   tell application "Finder"
       if FilesWithCodecErrors is not equal to "" then
           display dialog "..." & TotalCodecErrors & " file(s) are not the proper codec...
"
& FilesWithCodecErrors & "
(Label colour: red)"
buttons "Thanks"
       end if
       if FilesWithS4MNumberErrors is not equal to "" then
           display dialog "..." & TotalS4MNumberErrors & " file(s) do not have a proper S4M number...
   "
& FilesWithS4MNumberErrors & "(Label colour: blue)" buttons "Thanks"
       end if
       if FilesWithDurationErrors is not equal to "" then
           display dialog "..." & TotalDurationErrors & " file(s) were not the proper duration...
   "
& FilesWithDurationErrors & "(Label colour: yellow)" buttons "Thanks"
       end if
       if FilesWithFileNameErrors is not equal to "" then
           display dialog "..." & TotalFileNameErrors & " file(s) had incorrect durations in their file name(s).
   "
& FilesWithFileNameErrors & "(Label colour: purple)" buttons "Thanks"
       end if
       if FilesNotProcessed is not equal to "" then
           display dialog "..." & TotalPromoError & " file(s) were not properly processed.
       "
& FilesNotProcessed & "(Label colour: orange)" buttons "Thanks"
       end if
       if FilesWithCodecErrors is equal to "" and FilesWithS4MNumberErrors is equal to "" and FilesWithDurationErrors is equal to "" and FilesWithFileNameErrors is equal to "" and FilesNotProcessed is equal to "" then
           display dialog "All OK!" & theName & "
       (Label colour: green)"
buttons "Thanks"
       end if
   end tell
end common

--THIS HANDLER READS THE XML DATA:
on trackInfo given type:type as text, id:|id| as text : -1, key:key as text
   local key, |id|, type
   global tracks
   
   tell application "System Events"
       if |id| = -1 then
           set {trackdata} to the |tracks| where ¬
               value of the XML attribute "type" = |type|
       else
           set {trackdata} to the |tracks| where ¬
               value of the XML attribute "type" = |type| and ¬
               value of the XML attribute "streamid" = |id|
       end if
       
       tell (a reference to XML element named key in the trackdata) to ¬
           if it exists then
               return its value
           else
               return false
           end if
   end tell
end trackInfo

--THIS HANDLER GENERATES THE XML DATA
on mediainfoFile(inputstring) -- Only call this once per script run
   set theFile to quoted form of POSIX path of (inputstring)
   set xmltext to do shell script "usr/local/bin/mediainfo " & ¬
       theFile & " --Output=XML"
   
   tell application "System Events"
       set xml to make new XML data with properties {text:xmltext}
       set mediaInfo to XML element "Mediainfo" of xml
       set |file| to XML element "File" of mediaInfo
       
       return {|tracks|:a reference to XML elements of |file|}
   end tell
end mediainfoFile

--THIS HANDLER EXTRACTS NUMBERS FROM A STRING
on returnNumbersInString(inputstring)
   set s to quoted form of inputstring
   do shell script "sed s/[a-zA-Z\\']//g <<< " & s
   set dx to the result
   set numlist to {}
   repeat with i from 1 to count of words in dx
       set this_item to word i of dx
       try
           set this_item to this_item as number
           set the end of numlist to this_item
       end try
   end repeat
   return numlist
end returnNumbersInString

--THIS HANDLER SEARCHES A STRING FOR SPECIFIED CHARACTERS AND REPLACES THEM WITH THE DESIGNATED CHARACTERS
on SAR(main_text, search_text, replace_text)
   set old_delims to AppleScript's text item delimiters
   try
       set AppleScript's text item delimiters to search_text
       considering case
           set parts to every text item of main_text
       end considering
       set AppleScript's text item delimiters to replace_text
       set newText to (parts as string)
   end try
   set AppleScript's text item delimiters to old_delims
   return newText
end SAR

Saved as an application, it may be used as an applet - entry point by on run or as a droplet - entry point by on open.

To be sure that everything was OK, I tried to use it from the script editor which uses the entry : on run.
Alas I got an error which I don't understand.

Here is the event log:

Applescript:

tell application "Script Editor"
   choose file with multiple selections allowed
       --> {alias "SSD 500:Users:**********:Desktop:theXML 1.xml", alias "SSD 500:Users:**********:Desktop:theXML 2.xml"}
end tell
tell current application
   do shell script "usr/local/bin/mediainfo '/Users/**********/Desktop/theXML 1.xml' --Output=XML"
       --> "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<MediaInfo
xmlns=\"https://mediaarea.net/mediainfo\"
xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"
xsi:schemaLocation=\"https://mediaarea.net/mediainfo https://mediaarea.net/mediainfo/mediainfo_2_0.xsd\"
version=\"2.0\">
<creatingLibrary version=\"19.04\" url=\"https://mediaarea.net/MediaInfo\">MediaInfoLib</creatingLibrary>
<media ref=\"/Users/**********/Desktop/theXML 1.xml\">
<track type=\"General\">
<FileExtension>xml</FileExtension>
<FileSize>3034</FileSize>
<StreamSize>3034</StreamSize>
<File_Modified_Date>UTC 2019-04-27 09:16:59</File_Modified_Date>
<File_Modified_Date_Local>2019-04-27 11:16:59</File_Modified_Date_Local>
</track>
</media>
</MediaInfo>
"

end tell
tell application "System Events"
   make new XML data with properties {text:"<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<MediaInfo
xmlns=\"https://mediaarea.net/mediainfo\"
xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"
xsi:schemaLocation=\"https://mediaarea.net/mediainfo https://mediaarea.net/mediainfo/mediainfo_2_0.xsd\"
version=\"2.0\">
<creatingLibrary version=\"19.04\" url=\"https://mediaarea.net/MediaInfo\">MediaInfoLib</creatingLibrary>
<media ref=\"/Users/**********/Desktop/theXML 1.xml\">
<track type=\"General\">
<FileExtension>xml</FileExtension>
<FileSize>3034</FileSize>
<StreamSize>3034</StreamSize>
<File_Modified_Date>UTC 2019-04-27 09:16:59</File_Modified_Date>
<File_Modified_Date_Local>2019-04-27 11:16:59</File_Modified_Date_Local>
</track>
</media>
</MediaInfo>
"
}
       --> XML data id "sans titre 1"
   get XML element "Mediainfo" of XML data id "sans titre 1"
       --> error number -1728 from XML element "Mediainfo" of XML data id "sans titre 1"
Résultat :
error "Erreur dans System Events : Il est impossible d’obtenir XML element \"Mediainfo\" of XML data id \"sans titre 1\"." number -1728 from XML element "Mediainfo" of XML data id "sans titre 1"

The content of the passed xml file is :

<?xml version="1.0" encoding="UTF-8"?>
<Mediainfo version="0.7.60">
<File>
<track type="General">
<Complete_name>/Users/jquimby/Desktop/test.mxf</Complete_name>
<Format>MXF</Format>
<Commercial_name>XDCAM HD422</Commercial_name>
<Format_profile>OP-1a</Format_profile>
<Format_settings>Closed / Complete</Format_settings>
<File_size>31.0 MiB</File_size>
<Duration>5s 5ms</Duration>
<Overall_bit_rate>52.0 Mbps</Overall_bit_rate>
<Encoded_date>2019-04-03 15:32:46.000</Encoded_date>
<Writing_application>Adobe Systems Incorporated Adobe Media Encoder 1.0.0.0.1</Writing_application>
<Writing_library>Adobe Systems Incorporated Adobe Media Encoder 1.0.0.0.1</Writing_library>
</track>

<track type="Video">
<ID>512</ID>
<Format>MPEG Video</Format>
<Commercial_name>XDCAM HD422</Commercial_name>
<Format_version>Version 2</Format_version>
<Format_profile>4:2:2@High</Format_profile>
<Format_settings__BVOP>Yes</Format_settings__BVOP>
<Format_settings__Matrix>Custom</Format_settings__Matrix>
<Format_settings__GOP>M=3, N=15</Format_settings__GOP>
<Format_Settings_Wrapping>Frame</Format_Settings_Wrapping>
<Duration>5s 5ms</Duration>
<Bit_rate>50.0 Mbps</Bit_rate>
<Width>1 920 pixels</Width>
<Height>1 080 pixels</Height>
<Display_aspect_ratio>16:9</Display_aspect_ratio>
<Frame_rate>29.970 fps</Frame_rate>
<Standard>Component</Standard>
<Color_space>YUV</Color_space>
<Chroma_subsampling>4:2:2</Chroma_subsampling>
<Bit_depth>8 bits</Bit_depth>
<Scan_type>Interlaced</Scan_type>
<Scan_order>Top Field First</Scan_order>
<Compression_mode>Lossy</Compression_mode>
<Bits__Pixel_Frame_>0.805</Bits__Pixel_Frame_>
<Stream_size>29.8 MiB (96%)</Stream_size>
<Delay_SDTI>0</Delay_SDTI>
<Color_primaries>BT.709</Color_primaries>
<Transfer_characteristics>BT.709</Transfer_characteristics>
</track>

<track type="Audio" streamid="1">
<ID>768</ID>
<Format>PCM</Format>
<Format_settings__Endianness>Little</Format_settings__Endianness>
<Format_Settings_Wrapping>Frame (AES)</Format_Settings_Wrapping>
<Duration>5s 5ms</Duration>
<Bit_rate_mode>Constant</Bit_rate_mode>
<Bit_rate>1 152 Kbps</Bit_rate>
<Channel_s_>1 channel</Channel_s_>
<Sampling_rate>48.0 KHz</Sampling_rate>
<Bit_depth>24 bits</Bit_depth>
<Stream_size>704 KiB (2%)</Stream_size>
<Delay_SDTI>0</Delay_SDTI>
</track>

<track type="Audio" streamid="2">
<ID>1024</ID>
<Format>PCM</Format>
<Format_settings__Endianness>Little</Format_settings__Endianness>
<Format_Settings_Wrapping>Frame (AES)</Format_Settings_Wrapping>
<Duration>5s 5ms</Duration>
<Bit_rate_mode>Constant</Bit_rate_mode>
<Bit_rate>1 152 Kbps</Bit_rate>
<Channel_s_>1 channel</Channel_s_>
<Sampling_rate>48.0 KHz</Sampling_rate>
<Bit_depth>24 bits</Bit_depth>
<Stream_size>704 KiB (2%)</Stream_size>
<Delay_SDTI>0</Delay_SDTI>
</track>

<track type="Text">
<ID>1280-CC1</ID>
<Format>EIA-608</Format>
<Muxing_mode>Ancillary data / CDP</Muxing_mode>
<Duration>5s 5ms</Duration>
<Bit_rate_mode>Constant</Bit_rate_mode>
<Stream_size>0.00 Byte (0%)</Stream_size>
<Delay_SDTI>0</Delay_SDTI>
</track>

</File>
</Mediainfo>


The Unix file mediainfo is decribed as:

Type: Exécutable Unix
Taille: 13 936176 octets (13,9 Mo sur disque)
Emplacement: SSD 500 - usr - local - bin
Créé: mardi 23 avril 2019 à 16:06
Modifié: mardi 23 avril 2019 à 16:06

What is the wrongdoer ?

Yvan KOENIG running High Sierra 10.13.6 in French (VALLAURIS, France) mardi 14 mai 2019  21:34:02

Offline

 

#35 2019-05-15 03:33:15 am

CK
Member
From:: UK
Registered: 2018-11-04
Posts: 91

Re: Can Applescript read an XML file stored as a variable?

Yvan Koenig wrote:

Here is the event log:
                .
                .
                .
The content of the passed xml file is :
                .
                .
                .

The two XMLs are completely different.  You're taking XML that was previously produced as output from that shell script program, and which you now have saved in a file on your desktop; and you're trying to run that file back through the same shell script again, which produces completely different XML that isn't suitable for this script.

JQ is sourcing his files from some other place, and he needs to run them through the shell script in order to produce the XML he requires.  You and I already have that XML, which JQ provided at the start.  Therefore, you should comment out the first three lines of the mediainfoFile() handler, and declare xmltext like this:

Applescript:

set xmltext to read the inputstring

Offline

 

#36 2019-05-15 05:18:19 am

CK
Member
From:: UK
Registered: 2018-11-04
Posts: 91

Re: Can Applescript read an XML file stored as a variable?

JQ wrote:

▸ If I remove the Try block from the above script it tells me that "tracks" is not defined...

▸ If I add "on run" at the top and "end run" at the bottom (before my handlers) and export as an application it works...

▸ Once I add "on open" it just for some reason will either not read or not generate the XML properly is my only guess...[/applescript]

OK, so this is an issue of variable scope that I mentioned in one of my previous replies when I brought up the notion of global variables.  I may have also mentioned something about an implicit run handler (or, rather, referred to the run handler and put the word "implicitly" in brackets somewhere in the sentence).

Anyway, before I go on, I'll just tell you the solution first, then the explanation can follow.  Keep your script as you have it (no need to declare an explicit run handler); keep your open handler; at the top of the script, add the line:

Applescript:

global tracks

ExplanationThe run handler: Implicit vs. Explicit
Every set of AppleScript commands is contained within a handler, including the ones that don't appear to be so, because they are sitting outside of all the other handler declarations and appear to be unconfined.  Those are the commands that AppleScript executes by default, without needing to call upon a handler yourself, and I previously referred to those lines of code as "the main" part of the script (a misnomer).  In fact, they are contained inside a run handler, even though this can be very unapparent to a layman reading the script in those instances we choose not to declare the run handler explicitly:

tell application "Finder" to activate

(* more code *)


on myHandler()
        
        (* some code *)
        
end myHandler
        .
        .
        .
(* other user-defined handlers *)

Here, though the declaration of the run handler cannot be seen, any command not put inside another handler is, by default, part of the run handler.  It is said to be declared implicitly, and thus referred to as the implicit run handler (its existence is implied, even if not seen).  Adding in the handler declaration:

on run
        tell application "Finder" to stop being so slow
                .
                .
        (* more code *)
                .
                .
end run

on myHandler()
        
        (* some code *)
        
end myHandler
        .
        .
        .
(* other user-defined handlers *)

now makes the run handler explicit.  If you were to try and declare your run handler explicitly, then put command expressions outside of it (and not contained inside other handlers), the script would fail to compile (you can, however, declare properties and uninitialised variables outside the run handler, but variables always get initialised within a handler).

Variable Scope
As I mentioned before, variables exist and are bound inside the scope (I previously also referred to this as the domain) of the handler in which they are declared.  One handler does not ordinarily have access to another handler's variables.  You can grant a handler access to variables in the run handler's domain (also called the top-level of the script object) by declaring a global instance of it inside the handler that wants access (another misnomer, as it remains the same instance of the variable, and it's the handler that gains access to the domain in which the variable lives).  This does not make the variable global in the AppleScript domain (i.e. in the scope of the script as a whole), and the other user-defined handlers won't have access to it unless they also declare a global instance of it themselves.

This is what the situation was for you and I when we were testing the script inside Script Editor where the "main" part of the script was living inside an implicit run handler, which is where the variable tracks lived.

When the changes were made to create an Application script, the lines of code previously existing in the run handler were wrapped inside the open handler, and this meant the tracks variable got bound within the local scope of the open handler and inaccessible to other handlers regardless of attempts to access the global variable domain.

The solution is to declare the tracks variable as global in the AppleScript domain, i.e. outside all handlers, including the run handler.  Now every handler in the script has access to this variable and can change its value.  They don't need to contain an explicit global declaration themselves, although I tend to add one inside any handler that utilises the variable as a way of keeping track of scopes that overlap and which parts of the script are making changes to it.  It's also why I always have explicit declarations for my local variables inside a handler; this isn't necessary, but it helps make it clear and obvious when a local instance of a variable overrides any previous global declaration of a variable using the same identifier.

But, as a general rule, don't declare global variables.  As this lesson has taught us with just a single global variable, it's easy to lose track of where they are and who's doing what to them.  The safer way to pass a value from one domain to another, e.g. from the top-level script object to one of its handlers, is, where possible (which it almost always is), to declare a handler that takes arguments and passing it the value of the variable that's needed.

Last edited by CK (2019-05-15 05:34:09 am)

Offline

 

#37 2019-05-15 05:52:53 am

CK
Member
From:: UK
Registered: 2018-11-04
Posts: 91

Re: Can Applescript read an XML file stored as a variable?

Lastly, I'm going to pick apart your try blocks again.  Ultimately, it is your decision, but I think you're having a tough time seeing how genuinely unnecessary they are in your script, and only causing trouble, as is evident by how it obscured what was happening with the PromoCodec and tracks variables until you physically removed the try statement:

JQ wrote:

Applescript:

--WHEN MEDIAINFO READS AN MXF WITH XDCAM HD422 AS THE CODEC THE FIELD IS LABELLED
--"Commercial_Name". THIS TRY BLOCK CHECKS THE CODEC FIELD OF THE XML
--TO MAKE SURE THE PROPER CODEC FIELD IS PRESENT
try
       set PromoCodec to (trackInfo given type:"Video", key:"Commercial_name")
       if the PromoCodec = false then
               set CodecError to 1
       end if
       
       --IF THE PROPER CODEC IS PRESENT THIS IS WHERE THE VARIABLES ARE POPULATED BY THE MEDIAINFOFILE HANDLER
       if CodecError is equal to 0 then
               set PromoBitRate to (trackInfo given type:"Video", key:"Bit_rate")
               set PromoDuration to (trackInfo given type:"Audio", id:2, key:"Duration")
               set PromoFrameRate to (trackInfo given type:"Video", key:"Frame_rate")
               set theDuration to returnNumbersInString(PromoDuration)
               set Duration to SAR(theDuration, ", ", ".")
               set FileName to do shell script "basename " & quoted form of POSIX path of thePromo
               set S4MDuration to the first word of FileName
       end if
end try



"THIS TRY BLOCK CHECKS THE CODEC FIELD OF THE XML TO MAKE SURE THE PROPER CODEC FIELD Commercial_Name IS PRESENT"

If this were true, you wouldn't need the two if...then conditional blocks checking to determine whether PromoCodec is set to false (which would indicate the Commercial_Name field was absent) and choosing whether to execute the subsequent lines.  You could simply remove those conditional statements, let the error get caught, which would skip the lines of code inside the rest of the try block and continue executing what comes after.

But that is not the way to do it.  Rather, get rid of the try block, and use a single conditional statement that will cater for both Commerical_Name's presence or absence:

Applescript:

set PromoCodec to (trackInfo given type:"Video", key:"Commercial_name")
if PromoCodec ≠ false then
       --IF THE PROPER CODEC IS PRESENT THIS IS WHERE THE VARIABLES ARE POPULATED BY THE MEDIAINFOFILE HANDLER        
       set PromoBitRate to (trackInfo given type:"Video", key:"Bit_rate")
       set PromoDuration to (trackInfo given type:"Audio", id:2, key:"Duration")
       set PromoFrameRate to (trackInfo given type:"Video", key:"Frame_rate")
       set theDuration to returnNumbersInString(PromoDuration)
       set Duration to SAR(theDuration, ", ", ".")
       set FileName to do shell script "basename " & quoted form of POSIX path of thePromo
       set S4MDuration to the first word of FileName
end if

Last edited by CK (2019-05-15 05:54:27 am)

Offline

 

#38 2019-05-15 07:53:40 am

JQ
Member
Registered: 2019-02-04
Posts: 36

Re: Can Applescript read an XML file stored as a variable?

Thank you everyone for your incredible help and patience.  I'm now able to run the script as an application.  I would not have been able to do this without all of your help as this kind of script is way beyond my scope as a script writer.

CK - One question about your note about Try blocks.  The original script was using them to catalog errors and mark files with a flag depending on the issue with the file.  The script will be used to process sometimes as many as 100 files at a time and we use the Try blocks/Error counters to identify any technical issues with an individual file inside the batch being processed.  I see the logic with the alteration of the PromoCodec try block, but I would need to keep the if statements in for the error counters. 

Would altering/removing the Try blocks make the script more efficient (ie. run faster)?

Here is the final script application (that still includes the Try blocks):

Applescript:


on open theseFiles
   global tracks
   
   -- THESE ARE THE ERROR VARIABLES
   set CodecError to 0 --Codec Errors will highlight the file GRAY
   set DurationError to 0 --Duration Errors will highlight the file YELLOW
   set InvalidDuration to 0
   set InvalidS4MNumber to 0
   set TotalCodecErrors to 0 -- COUNTS CODEC ERRORS
   set TotalDurationErrors to 0 -- COUNTS PROMO DURATION ERRORS
   set TotalS4MNumberErrors to 0 -- COUNTS BAD S4M NUMBERS IN FILENAMES
   set TotalFileNameErrors to 0 -- COUNTS DURATION ERRORS OF TOP OF FILENAMES
   set TotalPromoError to 0 -- RESULTS IN "FILE NOT PROPERLY PROCESSED"
   set FilesWithCodecErrors to "" -- CREATES A LIST OF THE PROMOS THAT HAVE CODEC ERRORS
   set FilesWithDurationErrors to "" -- CREATES A LIST OF THE PROMOS THAT HAVE DURATION ERRORS
   set FilesWithFileNameErrors to "" -- CREATES A LIST OF THE PROMOS THAT HAVE FILENAME ERRORS
   set FilesWithS4MNumberErrors to "" -- CREATES A LIST OF THE PROMOS THAT HAVE S4M NUMBER ERRORS
   set FilesNotProcessed to "" -- CREATES A LIST OF PROMOS THAT WERE NOT PROCESSED
   set theRightFormats to {"XDCAM HD422", "50.0 Mbps", "29.970 fps"} as list
   
   repeat with i from 1 to count of theseFiles -- STARTS CHECKING FILES IN SEQUENCE
       set thePromo to item i of theseFiles
       set tracks to the mediainfoFile(thePromo)'s tracks
       
       --WHEN MEDIAINFO READS AN MXF WITH XDCAM HD422 AS THE CODEC THE FIELD IS LABELLED
       --"Commercial_Name". THIS TRY BLOCK CHECKS THE CODEC FIELD OF THE XML
       --TO MAKE SURE THE PROPER CODEC FIELD IS PRESENT
       try
           set PromoCodec to (trackInfo given type:"Video", key:"Commercial_name")
           if the PromoCodec = false then
               set CodecError to 1
           end if
           
           --IF THE PROPER CODEC IS PRESENT THIS IS WHERE THE VARIABLES ARE POPULATED BY THE MEDIAINFOFILE HANDLER
           if CodecError is equal to 0 then
               set PromoBitRate to (trackInfo given type:"Video", key:"Bit_rate")
               set PromoDuration to (trackInfo given type:"Audio", id:2, key:"Duration")
               set PromoFrameRate to (trackInfo given type:"Video", key:"Frame_rate")
               set theDuration to returnNumbersInString(PromoDuration)
               set Duration to SAR(theDuration, ", ", ".")
               set FileName to do shell script "basename " & quoted form of POSIX path of thePromo
               set S4MDuration to the first word of FileName
           end if
       end try
       
       --THIS SECTION IS WHERE THE TRUNCATED FILE NAME IS CREATED
       try
           tell application "Finder"
               set extension hidden of thePromo to false
           end tell
           
           set theName to name of (info for thePromo)
           set thePath to the POSIX path of thePromo
           
           set n to the number of characters in theName
           
           set n to (n - 11)
           
           set JustS4MNumber to (characters n through end of theName) as string
           
           set theNewPath to quoted form of ("/Volumes/Post_SAN_02/Post_SAN_02/GLOBAL/Producers/Jason/Troubleshooting/RunwayTest/" & JustS4MNumber)
           --THE ABOVE LINE IS WHERE THE FILE WILL BE POSTED IF IT PASSES ALL TECH CHECKS
           
           
           set theOldpath to quoted form of thePath
           set PromoError to 0
           
       on error
           set PromoError to 1
       end try
       
       --THIS IS THE BEGINNING OF THE TECH CHECKS
       if PromoError is equal to 0 and CodecError is equal to 0 then
           set theS4MNumber to the word -2 of theName --word -2 removes the file extension
           set S4MNumberCheck to the first word of JustS4MNumber
           
           --THIS SECTION CHECKS THAT THE FIRST WORD OF THE FILE NAME IS ACTUALLY A VALID NUMBER
           try
               set DurationCheck to (S4MDuration + 2)
           on error
               set InvalidDuration to 1
           end try
           
           --THIS SECTION ENSURES THE PROMO DURATION IS WITHIN A 2 FRAME RANGE OF THE TARGET DURATION
           if InvalidDuration is equal to 0 then
               set FramesHeavy to (S4MDuration + 0.66)
               set FramesLight to (S4MDuration - 0.66)
               if Duration is greater than FramesLight and Duration is less than FramesHeavy then
                   set DurationError to 0
               else
                   set DurationError to 1
               end if
           end if
           
           --THIS SECTION CHECKS THAT THE S4M NUMBER IS 8 DIGITS AND CONTAINS ONLY NUMBERS
           if the number of characters of theS4MNumber is equal to 8 then
               try
                   set theS4MCalc to (theS4MNumber + 2)
               on error
                   set InvalidS4MNumber to 1
               end try
           else
               set InvalidS4MNumber to 1
           end if
           if the number of characters of S4MNumberCheck is not equal to 8 then
               set InvalidS4MNumber to 1
           end if
           
           --THIS SECTION CHECKS TO ENSURE THE CODEC AND BIT RATE ARE CORRECT
           if PromoCodec is not in theRightFormats and PromoBitRate is not in theRightFormats then
               set CodecError to 1
           else
               set CodecError to 0
           end if
       end if
       
       --THIS SECTION CHECKS ALL THE ERROR COUNTERS, LABELS THE FILES IN FINDER, CREATES THE ERROR LIST, AND IF THE FILE PASSES ALL CHECKS IT WILL PASTE THE FILE INTO THE DESIRED DESTINATION    
       if PromoError is equal to 0 then
           tell application "Finder"
               if CodecError is not equal to 0 then -- CODEC ERROR CHECK
                   set label index of thePromo to 2
                   set TotalCodecErrors to TotalCodecErrors + 1
                   set FilesWithCodecErrors to FilesWithCodecErrors & theName & "" & "    • codec is " & PromoCodec & return
                   set CodecError to 0
               else
                   if InvalidS4MNumber is not equal to 0 then -- BAD S4M NUMBER FORMAT IN FILENAME
                       set label index of thePromo to 4
                       set FilesWithS4MNumberErrors to FilesWithS4MNumberErrors & theName & return
                       set TotalS4MNumberErrors to TotalS4MNumberErrors + 1
                       set InvalidS4MNumber to 0
                   else
                       if DurationError is not equal to 0 then -- PROMO IS NOT WITHIN THE 2 FRAME BUFFER FOR DURATION
                           set label index of thePromo to 3
                           set TotalDurationErrors to TotalDurationErrors + 1
                           set FilesWithDurationErrors to FilesWithDurationErrors & theName & return
                           set DurationError to 0
                       else
                           if InvalidDuration is not equal to 0 then -- BAD DURATION FORMAT IN FILENAME
                               set label index of thePromo to 6
                               set TotalFileNameErrors to TotalFileNameErrors + 1
                               set FilesWithFileNameErrors to FilesWithFileNameErrors & theName & return
                               set InvalidDuration to 0
                           else
                               set label index of thePromo to 6
                               do shell script "cp " & theOldpath & " " & theNewPath --THIS IS THE STEP THAT ACTUALLY COPIES THE FILE TO THE NEW LOCATION
                           end if
                       end if
                   end if
               end if
           end tell
           set PromoError to 0
       end if
       if PromoError is not equal to 0 then
           tell application "Finder"
               set label index of thePromo to 5
               set TotalPromoError to TotalPromoError + 1
               set FilesNotProcessed to FilesNotProcessed & (name of (info for thePromo)) & "
               "

           end tell
       end if
   end repeat -- END OF INDIVIDUAL FILE CHECK REPEAT LOOP
   
   
   --THIS IS WHERE THE BATCH ERROR MESSAGES BEGIN
   
   tell application "Finder"
       if FilesWithCodecErrors is not equal to "" then
           display dialog ("..." & TotalCodecErrors & " file(s) are not the proper codec..." & return & return & FilesWithCodecErrors as text) & return & "(Label colour: red)" buttons "Thanks"
       end if
       if FilesWithS4MNumberErrors is not equal to "" then
           display dialog ("..." & TotalS4MNumberErrors & " file(s) do not have a proper S4M number..." & return & return & FilesWithS4MNumberErrors as text) & return & "(Label colour: blue)" buttons "Thanks"
       end if
       if FilesWithDurationErrors is not equal to "" then
           display dialog ("..." & TotalDurationErrors & " file(s) were not the proper duration..." & return & return & FilesWithDurationErrors as text) & return & "(Label colour: yellow)" buttons "Thanks"
       end if
       if FilesWithFileNameErrors is not equal to "" then
           display dialog ("..." & TotalFileNameErrors & " file(s) had incorrect durations in their file name(s)." & return & return & FilesWithFileNameErrors as text) & return & "(Label colour: purple)" buttons "Thanks"
       end if
       if FilesNotProcessed is not equal to "" then
           display dialog ("..." & TotalPromoError & " file(s) were not properly processed." & return & return & FilesNotProcessed as text) & return & "(Label colour: orange)" buttons "Thanks"
       end if
       if FilesWithCodecErrors is equal to "" and FilesWithS4MNumberErrors is equal to "" and FilesWithDurationErrors is equal to "" and FilesWithFileNameErrors is equal to "" and FilesNotProcessed is equal to "" then
           display dialog ("All OK!" & return & return & theName as text) & "(Label colour: green)" buttons "Thanks"
       end if
   end tell
end open

--THIS HANDLER READS THE XML DATA:
on trackInfo given type:type as text, id:|id| as text : -1, key:key as text
   local key, |id|, type
   global tracks
   
   tell application "System Events"
       if |id| = -1 then
           set {trackdata} to the |tracks| where ¬
               value of the XML attribute "type" = |type|
       else
           set {trackdata} to the |tracks| where ¬
               value of the XML attribute "type" = |type| and ¬
               value of the XML attribute "streamid" = |id|
       end if
       
       tell (a reference to XML element named key in the trackdata) to ¬
           if it exists then
               return its value
           else
               return false
           end if
   end tell
end trackInfo

--THIS HANDLER GENERATES THE XML DATA
on mediainfoFile(inputstring) -- Only call this once per script run
   set theFile to quoted form of POSIX path of (inputstring)
   set xmltext to do shell script "usr/local/bin/mediainfo " & ¬
       theFile & " --Output=XML"
   
   tell application "System Events"
       set xml to make new XML data with properties {text:xmltext}
       set mediaInfo to XML element "Mediainfo" of xml
       set |file| to XML element "File" of mediaInfo
       
       return {|tracks|:a reference to XML elements of |file|}
   end tell
end mediainfoFile

--THIS HANDLER EXTRACTS NUMBERS FROM A STRING
on returnNumbersInString(inputstring)
   set s to quoted form of inputstring
   do shell script "sed s/[a-zA-Z\\']//g <<< " & s
   set dx to the result
   set numlist to {}
   repeat with i from 1 to count of words in dx
       set this_item to word i of dx
       try
           set this_item to this_item as number
           set the end of numlist to this_item
       end try
   end repeat
   return numlist
end returnNumbersInString

--THIS HANDLER SEARCHES A STRING FOR SPECIFIED CHARACTERS AND REPLACES THEM WITH THE DESIGNATED CHARACTERS
on SAR(main_text, search_text, replace_text)
   set old_delims to AppleScript's text item delimiters
   try
       set AppleScript's text item delimiters to search_text
       considering case
           set parts to every text item of main_text
       end considering
       set AppleScript's text item delimiters to replace_text
       set newText to (parts as string)
   end try
   set AppleScript's text item delimiters to old_delims
   return newText
end SAR

Offline

 

#39 2019-05-15 12:13:30 pm

JQ
Member
Registered: 2019-02-04
Posts: 36

Re: Can Applescript read an XML file stored as a variable?

One more question.  I want to add a line that would modify the file name of all files that passed the through all the error checks.  I want to add a date stamp in the format of mmmdd and add it before the last word of the original file name.  This is the script I wrote to test creating/inserting the date stamp:

Applescript:


set theFile to (choose file)
set theFilename to name of (info for theFile)
set TodaysDate to (current date) as string
set TruncatedDate to word 2 of TodaysDate & word 3 of TodaysDate
set NewFilename to SAR(theFilename, (word -2 of theFilename), TruncatedDate & " " & (word -2 of the theFilename))
tell application "Finder" to set name of theFile to NewFilename

on SAR(main_text, search_text, replace_text)
   set old_delims to AppleScript's text item delimiters
   try
       set AppleScript's text item delimiters to search_text
       considering case
           set parts to every text item of main_text
       end considering
       set AppleScript's text item delimiters to replace_text
       set newText to (parts as string)
   end try
   set AppleScript's text item delimiters to old_delims
   return newText
end SAR

The modifications I've made to the larger script are as follows:

Applescript:


on open theseFiles
   global tracks
   set TodaysDate to (current date) as string --NEW LINE
   set TruncatedDate to word 2 of TodaysDate & word 3 of TodaysDate --NEW LINE
   
   -- THESE ARE THE ERROR VARIABLES    

Applescript:


set theName to name of (info for thePromo)
           set thePath to the POSIX path of thePromo
           
           set n to the number of characters in theName
           
           set n to (n - 11)
           
           set JustS4MNumber to (characters n through end of theName) as string
           
           set theNewPath to quoted form of ("/Volumes/Post_SAN_02/Post_SAN_02/GLOBAL/Producers/Jason/Troubleshooting/RunwayTest/" & JustS4MNumber)
           --THE ABOVE LINE IS WHERE THE FILE WILL BE POSTED IF IT PASSES ALL TECH CHECKS
           
           set NewFilename to SAR(theName, (word -2 of theName), TruncatedDate & " " & (word -2 of the theName)) -- NEW LINE TO CREATE DESIRED NEW FILE NAME
           
           set theOldpath to quoted form of thePath
           set PromoError to 0

and lastly:

Applescript:


if PromoError is equal to 0 then
           tell application "Finder"
               if CodecError is not equal to 0 then -- CODEC ERROR CHECK
                   set label index of thePromo to 2
                   set TotalCodecErrors to TotalCodecErrors + 1
                   set FilesWithCodecErrors to FilesWithCodecErrors & theName & "" & "    • codec is " & PromoCodec & return
                   set CodecError to 0
               else
                   if InvalidS4MNumber is not equal to 0 then -- BAD S4M NUMBER FORMAT IN FILENAME
                       set label index of thePromo to 4
                       set FilesWithS4MNumberErrors to FilesWithS4MNumberErrors & theName & return
                       set TotalS4MNumberErrors to TotalS4MNumberErrors + 1
                       set InvalidS4MNumber to 0
                   else
                       if DurationError is not equal to 0 then -- PROMO IS NOT WITHIN THE 2 FRAME BUFFER FOR DURATION
                           set label index of thePromo to 3
                           set TotalDurationErrors to TotalDurationErrors + 1
                           set FilesWithDurationErrors to FilesWithDurationErrors & theName & return
                           set DurationError to 0
                       else
                           if InvalidDuration is not equal to 0 then -- BAD DURATION FORMAT IN FILENAME
                               set label index of thePromo to 5
                               set TotalFileNameErrors to TotalFileNameErrors + 1
                               set FilesWithFileNameErrors to FilesWithFileNameErrors & theName & return
                               set InvalidDuration to 0
                           else
                               set label index of thePromo to 6
                               set TotalDeliveredFiles to TotalDeliveredFiles + 1
                               set DeliveredFiles to DeliveredFiles & theName & return
                               set name of theName to NewFilename -- NEW LINE TO RENAME FILE THAT HAS PASSED TECH CHECKS
                               do shell script "cp " & theOldpath & " " & theNewPath --THIS IS THE STEP THAT ACTUALLY COPIES THE FILE TO THE NEW LOCATION
                           end if
                       end if
                   end if
               end if
           end tell
           set PromoError to 0
       end if

But I get this error once I try to tell the Finder to rename the file:

Can’t set name of "30 911 AN MON 00773484.mxf" to "30 911 AN MON May15 00773484.mxf". (-10006)

My test script changes the file name with no issue.  Once I add the pieces into the larger script though I get a Finder error. As far as I know, where I've put the line to rename the file should not cause a conflict with the other instances of calling theName as all those steps have been completed.

Offline

 

#40 2019-05-15 12:51:19 pm

Yvan Koenig
Member
Registered: 2006-09-14
Posts: 3471

Re: Can Applescript read an XML file stored as a variable?

JQ wrote:


But I get this error once I try to tell the Finder to rename the file:

Can’t set name of "30 911 AN MON 00773484.mxf" to "30 911 AN MON May15 00773484.mxf". (-10006)

My test script changes the file name with no issue.  Once I add the pieces into the larger script though I get a Finder error. As far as I know, where I've put the line to rename the file should not cause a conflict with the other instances of calling theName as all those steps have been completed.




You try to change the name of a file defined by its name (theName) when you must define it by its entire pathname (thePromo).

Yvan KOENIG running High Sierra 10.13.6 in French (VALLAURIS, France) mercredi 15 mai 2019  20:51:14

Offline

 

#41 2019-05-15 01:55:13 pm

JQ
Member
Registered: 2019-02-04
Posts: 36

Re: Can Applescript read an XML file stored as a variable?

Thank you!

Offline

 

#42 2019-05-16 04:44:24 pm

CK
Member
From:: UK
Registered: 2018-11-04
Posts: 91

Re: Can Applescript read an XML file stored as a variable?

JQ wrote:

Would altering/removing the Try blocks make the script more efficient (ie. run faster)?

In theory, yes.  AppleScript takes time to recover from errors as there's an overhead incurred in retrieving error codes and messages, plus other stuff that happens under the hood.

Offline

 

Board footer

Powered by FluxBB

RSS (new topics) RSS (active topics)