Im, using an Applescript to bashconvert a whole bunch of mv4 files to 640x480 using Handbrake CLI. I have a applescript I found somewhere changed to my parameters, and it works great. But to save time, I want the script to skip files that are already 640x480, since not all files need conversion. How would I go about that?
Here´s the script:
--on adding folder items to this_folder after receiving these_items
with timeout of (720 * 60) seconds
tell application "Finder"
--Get all m4v files that have no label color yet, meaning it hasn’t been processed
set allFiles to every file of entire contents of ("FIRSTHD:Users:jerry:Desktop:Omkodning" as alias) whose ((name extension is "m4v") and label index is 0)
--Repeat for all files in above folder
repeat with i from 1 to number of items in allFiles
set currentFile to (item i of allFiles)
try
--Set to gray label to indicate processing
set label index of currentFile to 7
--Assemble original and new file paths
set origFilepath to quoted form of POSIX path of (currentFile as alias)
set newFilepath to (characters 1 thru -5 of origFilepath as string) & "mp4'"
--Start the conversion
set shellCommand to "nice /Applications/HandBrakeCLI -i " & origFilepath & " -o " & newFilepath & " -e ffmpeg4 -b 1200 -a 1 -E faac -B 160 -R 29.97 -f mp4 –crop 0:0:0:0 crf 24 -w 640 -l 480 ;"
do shell script shellCommand
--Set the label to green in case file deletion fails
set label index of currentFile to 6
--Remove the old file
set shellCommand to "rm -f " & origFilepath
do shell script shellCommand
on error errmsg
--Set the label to red to indicate failure
set label index of currentFile to 2
end try
end repeat
end tell
end timeout
--end adding folder items to
Edited for clarity....
Since HandBreakCLI doesn't have any options to tell it not to convert if the resolution is 640x480, you have to handle that bit of logic in your script. It is easily done.
So all your script needs to do is...
get the video file resolution
If file is not at desired resolution then
convert the file
else
skip it
end if
So, as discussed here, you can use the freely available mediainfo command line tool to get the video resolution.
Here is some applescript code which you can copy/paste and run to see how it works...
set filterStr to " | grep pixels | tr -d [:alpha:][:blank:][:punct:]"
set allFiles to (choose file with multiple selections allowed)
repeat with i from 1 to number of items in allFiles
set currentFile to (item i of allFiles)
set cmdStr to "/usr/local/bin/mediainfo " & ¬
quoted form of POSIX path of currentFile & filterStr
set h to 0
set w to 0
try
set fileInfo to do shell script (cmdStr)
set {w, h} to every paragraph of fileInfo
end try
if w is not 640 and h is not 480 then
log w & " x " & h
# Convert to desired resolution....
end if
end repeat
Hope that helped.
Related
I'm trying to write a small gpx file conversion script. The conversion part is done but I can't fix the naming of the converted file. I want the filename of the converted file like this:
originalfilename.2.gpx
This is the code I have so far:
-- begin script
-- For converting from one format to another. Preset to convert from GPX to KML. Tailor as needed. Read the documentation for your version
--Based on the script by Robert Nixon, http://www.gpsbabel.org/os/OSX_oneclick.html
-- This is set up for gpsbabel installed using DarwinPorts. See <http://www.gpsbabel.org/osnotes.html> for details
-- This script is not being actively supported, but you may get some help from the gpsbabel discussion group: <http://www.gpsbabel.org/lists.html>
--start script
-- HINT a '~/' is your home folder and of course the double hyphen is a comment. Remove to make active.
-- setting path for gpsbabel. Reset as needed
--set gpsBabelLocation to "/opt/local/var/db/dports/software/gpsbabel/1.2.7_0/opt/local/bin/" -- DarwinPorts Default for Tiger, Feb. 2006
set gpsBabelLocation to "/Applications/GPSBabelFE.app/Contents/MacOS/" -- Normal MacGPSBabel location
--set gpsBabelLocation to ""
set inputTYPE to "gpx" -- set the input file type to whatever you want
set outputTYPE to "gpx" --set the output file type to whatever you want
set strPath to POSIX file "/Users/someusername/downloads/" --set the default path for file input dialog
--set inputPATH to "~/Desktop/route.gpx" --set the path to where your input file is
-- comment out the following line if you want to use the line above
set inputPATHalias to (choose file with prompt "Select a GPX file to convert to " & outputTYPE & ":" default location strPath)
-- set inputPATH to quoted form of POSIX path of inputPATHalias -- got error, but two step below works.
set inputfilename to (inputPATHalias as text)
set inputPATH to POSIX path of inputPATHalias
set inputPATH to quoted form of inputPATH -- needed to pass to shell script
--set outputPATH to "~/Desktop/yournewfile.wpt" --set the path to where your output file will be
set outputFileName to "converted." & inputTYPE & ".2." & outputTYPE
--set outputFileName to outputFileName & ".2." & outputTYPE
set outputFolderalias to choose folder with prompt "Select a folder for converted file:"
set outputPATH to fileCheckName(outputFolderalias, outputFileName)
-- See the Documentation for normal usage. http://www.gpsbabel.org/readme.html#d0e1388
-- Using the Position filter to correct a Garmin error. When the Garmin loses sight of the sattiletes, when it reconects, it puts in poitns with a lat-long equal to the last good point, but current time and elevation (mine has a barometer). Garmin: remove extraneous points recorded when out of range that have same lat and long as last good point (altitude is ignored in this filter).
set filterSetting to "" -- use this one if you don't want any Position filtering. You can leave in uncommented and any below will override it.
-- set filterSetting to " -x position " -- Default, distance=0
-- set filterSetting to " -x position,distance=1f " -- 1 foot and leave one
-- set filterSetting to " -x position,distance=1m " -- 1 meter and leave one
-- set filterSetting to " -x position,all" -- remove all duplicates
-- set filterSetting to " -x simplify,count=1000"
-- set filterSetting to " -x simplify,error=1k" -- doesnt' work, but then it's not in the manual
-- set filterSetting to ""
tell application "System Events"
activate
do shell script gpsBabelLocation & "gpsbabel " & filterSetting & "-i " & inputTYPE & " -f " & inputPATH & " -x transform,trk=rte " & " -o " & outputTYPE & " -F " & outputPATH
end tell
--Handlers. Only used once, but I've used them elsewhere
on fileCheckName(outputFolderalias, outputFileName)
set outputFolder to POSIX path of outputFolderalias
set outputPATHnoQuote to outputFolder & "/" & outputFileName -- may need to change this if the extension isn't the same as the outputType, The Desktop is a common location
set outputPATH to quoted form of outputPATHnoQuote -- needed to pass to shell script
--check if file already exist and if we want to overwrite it
set outputFolderaliasText to outputFolderalias as text
set outputPATHcolon to outputFolderaliasText & outputFileName
tell application "Finder" -- trying to get handler to work
if file outputPATHcolon exists then display dialog "The file " & outputFileName & " already exists. Do you want to overwrite it?"
end tell
return outputPATH
end fileCheckName
--end script
I'm unable to find Applescript code that translates the filename from a prompt into a variable.
I recommend to not use the Finder.app at all for this task. Especially, checking file existence with the Posix file coercion inside the tell block is a big mistake. The Finder is also not needed to get the file basename. For this task, with the help of other experienced users, I developed a high-speed handler, provided here.
In general, I recommend using the Finder only when absolutely necessary, because it is often busy in the background with other time-consuming tasks.
set gpsBabelLocation to "/Applications/GPSBabelFE.app/Contents/MacOS/" -- Normal MacGPSBabel location
set inputType to "gpx" -- the input file type extension
set outputType to "gpx" -- the output file type extension
set defaultPath to (path to downloads folder)
set inputPath to (choose file of type inputType with prompt "Select a " & inputType & " file to convert to " & outputType & ":" default location defaultPath) -- remove 'of type inputType' to select any file
set outputFileName to getBaseName(POSIX path of inputPath) & ".2." & outputType -- the converted name
set outputFolder to choose folder with prompt "Select a folder for the converted file:"
set outputPath to fileCheckName(outputFolder, outputFileName)
set filterSetting to ""
set inputPath to quoted form of (POSIX path of inputPath)
set command to gpsBabelLocation & "gpsbabel " & filterSetting & "-i " & inputType & " -f " & inputPath & " -x transform,trk=rte " & " -o " & outputType & " -F " & outputPath
log command
if gpsBabelLocation is not "" then
do shell script command
log result
end if
on getBaseName(posixPath)
set {ATID, AppleScript's text item delimiters} to {AppleScript's text item delimiters, "/"}
if (posixPath ends with "/") then
set baseName to text item -2 of posixPath
else
set baseName to text item -1 of posixPath
end if
if (baseName contains ".") then
set AppleScript's text item delimiters to "."
set baseName to text 1 thru text item -2 of baseName
end if
set AppleScript's text item delimiters to ATID
return baseName
end getBaseName
on fileCheckName(outputFolder, outputFileName) -- check if file exists
try
alias (outputFolder & outputFileName)
display alert quoted form of outputFileName & " already exists. Do you want to replace it?" message "A file or folder with the same name already exists at " & quoted form of POSIX path of outputFolder & ". Replacing it will overwrite its current contents." buttons {"OK", "Cancel"}
if button returned of the result is "Cancel" then error number -128 -- alert doesn't automatically cancel
end try
return quoted form of ((POSIX path of outputFolder) & outputFileName) -- quote for the shell script
end fileCheckName
Finder or System Events can be used to get file names, you just need to be a little careful when using the Finder, since it doesn't know that much about POSIX paths. With the various quoting for the shell, you also need to manipulate the various name pieces before quoting. Shortened and cleaned up a bit, your script would be something like:
--Based on the script by Robert Nixon, http://www.gpsbabel.org/os/OSX_oneclick.html
-- set path for gpsbabel as needed:
-- set gpsBabelLocation to "/opt/local/var/db/dports/software/gpsbabel/1.2.7_0/opt/local/bin/" -- DarwinPorts Default for Tiger, Feb. 2006
set gpsBabelLocation to "/Applications/GPSBabelFE.app/Contents/MacOS/" -- Normal MacGPSBabel location
-- set gpsBabelLocation to "" -- testing, etc
set inputType to "gpx" -- the input file type extension
set outputType to "gpx" -- the output file type extension
set defaultPath to (path to downloads folder)
set inputPath to (choose file of type inputType with prompt "Select a " & inputType & " file to convert to " & outputType & ":" default location defaultPath) -- remove 'of type inputType' to select any file
tell application "Finder" to set {inputName, inputExt} to {name, name extension} of inputPath
if inputExt is not "" then set inputName to text 1 thru -((count inputExt) + 2) of inputName -- just the name part
set inputPath to quoted form of POSIX path of inputPath -- quote for the shell script
set outputFileName to inputName & ".2." & outputType -- the converted name
set outputFolder to choose folder with prompt "Select a folder for the converted file:"
set outputPath to fileCheckName(outputFolder, outputFileName)
-- See the Documentation for normal usage. http://www.gpsbabel.org/readme.html#d0e1388
set filterSetting to "" -- uncomment any below to override no position filtering
-- set filterSetting to " -x position " -- Default, distance=0
-- set filterSetting to " -x position,distance=1f " -- 1 foot and leave one
-- set filterSetting to " -x position,distance=1m " -- 1 meter and leave one
-- set filterSetting to " -x position,all" -- remove all duplicates
-- set filterSetting to " -x simplify,count=1000"
set command to gpsBabelLocation & "gpsbabel " & filterSetting & "-i " & inputType & " -f " & inputPath & " -x transform,trk=rte " & " -o " & outputType & " -F " & outputPath
log command
if gpsBabelLocation is not "" then
do shell script command
log result
end if
on fileCheckName(outputFolder, outputFileName) -- check if file exists
set outputPath to (POSIX path of outputFolder) & outputFileName
tell application "Finder" to if (outputPath as POSIX file) exists then -- match the save alert
display alert quoted form of outputFileName & " already exists. Do you want to replace it?" message "A file or folder with the same name already exists at " & quoted form of POSIX path of outputFolder & ". Replacing it will overwrite its current contents." buttons {"OK", "Cancel"}
if button returned of the result is "Cancel" then error number -128 -- alert doesn't automatically cancel
end if
return quoted form of outputPath -- quote for the shell script
end fileCheckName
Essentially i'm looking for an applescript that allow me to order the massive 50.000 files by creating folders that have just the first word of the files, ignoring the rest of the filename after the first space.
For eaxmple the 50.000 files are named like this:
- amazingfrog -shootingbase.jpg
- frog 2sHDn1_9fFs12s.jpg
- frog 29adjjdd39939.mov
- Horse IUS39aosdja.mov
- horse 282131888.jpg
- HORSE.jpg
And so on.....
- I would like to be like this:
- amazingfrog
-amazingfrog -shootingbase.jpg
- frog
-frog 2sHDn1_9fFs12s.jpg
-frog 29adjjdd39939.mov
- horse
-horse IUS39aosdja.mov
-horse 282131888.jpg
-horse.gif
And so on....
On the internet i came across with the following script:
set chosenFolder to (choose folder)
tell application "Finder" to set fileList to files of chosenFolder
repeat with aFile in fileList
set {name:Nm, name extension:Ex} to info for (aFile as alias)
if Ex is missing value then set Ex to ""
if Ex is not "" then set Nm to text 1 thru ((count Nm) - (count Ex) - 1) of Nm
set dateFolder to text 1 thru 15 of Nm
set sourceFile to quoted form of POSIX path of (aFile as text)
set destinationFile to quoted form of (POSIX path of chosenFolder & dateFolder & "/" & name of aFile)
do shell script "ditto " & sourceFile & space & destinationFile
do shell script "rm " & sourceFile
end repeat
The only problem is that i have to choose in the "text 1 thru" the numbers of the letters i want to keep. And unfortunately the first word of the filenames have different length...
Could be possible to modify this script to my needed? or do you have any other suggestions?
Thanks in advance for any reply!!
I recommend to use text item delimiters to extract the first part of the file name
set chosenFolder to (choose folder)
tell application "Finder" to set fileList to files of chosenFolder
set TID to text item delimiters
set text item delimiters to space
repeat with aFile in fileList
set fileName to name of aFile
set textItems to text items of fileName
if (count textItems) = 1 then
set fileExtension to name extension of aFile
set folderName to text 1 thru ((get offset of "." & fileExtension in fileName) - 1) of fileName
else
set folderName to first item of textItems
end if
set sourceFile to quoted form of POSIX path of (aFile as text)
set destinationFile to quoted form of (POSIX path of chosenFolder & folderName & "/" & fileName)
do shell script "ditto " & sourceFile & space & destinationFile
do shell script "rm " & sourceFile
end repeat
set text item delimiters to TID
I currently have an Applescript that lets you type in a song and play it.
Here it is:
set userInput to text returned of (display dialog "Type something" default answer "")
if userInput contains "Play " then
set {TID, text item delimiters} to {text item delimiters, {"Play "}}
if length of userInput is greater than or equal to 2 then set resultString to text item 2 of userInput
set text item delimiters to TID
set playSong to (resultString as string)
tell application "iTunes"
set mySongs to every track of library playlist 1 whose name is playSong
repeat with aSong in mySongs
play aSong
end repeat
if (count of mySongs) = 0 then
say "Song not found"
end if
end tell
end if
Basically, I need to get the path to the main iTunes library and play a song from it. Currently, to search for songs, iTunes has to open. And if it can't find the song, it just stays open. I want to search the actual iTunes directory to make it so if iTunes cannot find a song, it doesn't open
I have no idea how to do this.
Thanks
Here is the script to search in the "iTunes Library.xml" file.
set XMLFile to my get_iTunes_Library_xml()
set userInput to text returned of (display dialog "Type something" default answer "Play ")
if userInput begins with "Play " and length of userInput > 5 then
set playSong to text 6 thru -1 of userInput
set searchString to "<key>Name<\\/key><string>" & playSong & "<\\/string>" -- to match exact name
if (my searchTrackName(searchString, XMLFile)) is not "" then
tell application "iTunes" to play (tracks whose name is playSong)
else
say "Song not found"
end if
end if
on searchTrackName(t, f) -- search in iTunes Library.xml file
if "&" is in t then set t to do shell script "sed \"s/&/&/g\" <<<" & quoted form of t -- to replace "&" by "&"
try -- return a count of matching lines
return do shell script "grep -c -m1 -i " & (quoted form of t) & " " & f -- "-i" equal case insensitive, "-m 1" to exit at first match
end try
return ""
end searchTrackName
on get_iTunes_Library_xml() -- get the path
do shell script "defaults read com.apple.iApps iTunesRecentDatabases | sed -En 's:^ *\"(.*)\"$:\\1:p' |/usr/bin/perl -MURI -e 'print URI->new(<>)->file;'"
return quoted form of the result
end get_iTunes_Library_xml
The "com.apple.iApps.plist" file contains the path to yours iTunes libraries (if you have more than one), the script get the path of the "iTunes Library.xml" file of the current library.
Not a finished solution, but perhaps a starting point.
I didn't find a way to get automatically the path to the iTunes library.
With the StandardAdditions you can get the path to the main music folder in the home folder via
set searchPath to POSIX path of music folder
You can set the path manual, like this:
set searchPath to quoted form of "/Users/USERNAME/Music/iTunes/iTunes Music/"
To search for the music files without iTunes, i use the shell command "mdfind"
do shell script "mdfind -count -onlyin PATH SEARCHSTRING"
With the count-Flag we get the total numbers of matches. If you like to see what mdfind finds, omit the count-Flag.
tell application "System Events"
set userInput to text returned of (display dialog "Search for music" default answer "madonna")
set searchPath to POSIX path of music folder
end tell
set shellCommand to "mdfind -count -onlyin " & searchPath & " " & quoted form of userInput
set searchResult to (do shell script shellCommand) as number
if searchResult = 0 then
say "Song not found"
else if searchResult >= 1 then
say "Found some songs"
end if
With mdfind you can search in the metadata, for example you can search for only MP3-Files:
mdfind "kMDItemContentType=='public.mp3'"
This script works as mentioned on a previous question to add #2x to all files in a folder, BUT how do I make or change this apple script to remove the #2x.
set appendable to "#2x"
set theFolder to choose folder
tell application "Finder"
set theFiles to (files of entire contents of theFolder) as alias list
repeat with theFile in theFiles
set FileExtension to theFile's name extension as string
set FileName to theFile's name as string
set FileBaseName to text 1 thru ((offset of "." in FileName) - 1) of FileName
set theFile's name to FileBaseName & appendable & "." & FileExtension
end repeat
end tell
tell application "Finder"
repeat with f in (files of entire contents of (choose folder) as alias list)
set n to name of f
set x to name extension of f
if n does not end with "#2x." & x then next
set name of f to text 1 thru (-5 - (count x)) of n & "." & x
end repeat
end tell
It would be easier to do it in a shell: IFS=$'\n'; for f in $(find ~/Desktop -name '*#2x*'); do mv "$f" "${f//#2x/}"; done.
In the past I had created an applescript for datedspace but which is not running anymore.
I would like to create an applescript that would look inside a folder ~/Documents/pool/ or ~/Downloads.
Let's say we are on February 7, 2011.
Check if the ~/Documents/2011/02/07/ exists
If not create ~/Documents/2011/02/07/
Move the files and/or folders inside ~/Documents/pool/ to ~/Documents/2011/02/07/
Bonus
Create a text file in ~/Documents/2011/ with the name index.mdown and containing the following format
# Index 2011
## January
[…]
## February
* 2011-02-07: Foo.jpeg
* 2011-02-07: Bar/
Lead or incomplete solutions are welcome.
Previous script
-- Script to automaticaly save documents in a date space.
-- Karl Dubost - http://www.la-grange.net/ - <karl#*******> - 2001 ©
-- Feel free to distribute it and modify it
-- Feel free to send me improvements
-- ********************************************************
-- Version 1.1 2001-03-30
-- Add control on existence of folders year and month
-- Make it more general based on Startup Disk
-- Version 1.0 2001-03-29
-- Creation of the code
-- Thanks to Bill Briggs
-- http://maccentral.macworld.com/columns/briggs.shtml
-- ********************************************************
on adding folder items to this_folder after receiving added_items
tell application "Finder"
set yourDisk to name of startup disk as string
end tell
set todaysDate to (current date)
set {d, m, y} to {day, month, year} of todaysDate
set monthList to {January, February, March, April, May, June, ¬
July, August, September, October, November, December}
repeat with i from 1 to 12
if m = (item i of monthList) then
set monthString to text -2 thru -1 of ("0" & i)
exit repeat
end if
end repeat
set y to y as string
set dayString to text -2 thru -1 of ("0" & d)
set dayString to dayString as string
set datedFolder to yourDisk & ":Documents:" & y & ":" & monthString & ":" & dayString & ":" as string
set monthFolder to yourDisk & ":Documents:" & y & ":" & monthString & ":" as string
set yearFolder to yourDisk & ":Documents:" & y & ":" as string
set rootFolder to yourDisk & ":Documents:" as string
tell application "Finder"
if (folder datedFolder exists) then
repeat with oneFile in added_items
move oneFile to folder datedFolder
end repeat
else if not (folder yearFolder exists) then
make new folder at folder rootFolder with properties {name:y}
else if not (folder monthFolder exists) then
make new folder at folder yearFolder with properties {name:monthString}
else
make new folder at folder monthFolder with properties {name:dayString}
repeat with oneFile in added_items
move oneFile to folder datedFolder
end repeat
end if
end tell
end adding folder items to
I hope this will be good enough :-) :
With the help of some basic command line applications it creates subfolders in your ~/Documents folder (mkdir -p: it will not overwrite existing directories!), moves files there (mv -n: not overwriting files with the same name), then creates monthly logfiles containing the names of addedItems and finally a index.mdown file with all monthly logfiles which should look like this:
2011/01/03: testfile9
2011/02/01: testfile10
2011/02/07: testfile11
Now go ahead and attach it to your folder, give it a try! (maybe uncomment baseFolder and change it to /tmp/test or something, or to POSIX path of thisFolder, if you want it to clean up the folder it´s attached to.)
property dateFormatForFolder : "+%Y/%m/%d"
property dateFormatForMonthlyLog : "+%Y/%m/"
property dateFormatForYearlyLog : "+%Y/"
on adding folder items to thisFolder after receiving addedItems
set baseFolder to POSIX path of (path to documents folder)
set todaysFolder to do shell script "/bin/date '" & dateFormatForFolder & "'"
set monthsFolder to do shell script "/bin/date '" & dateFormatForMonthlyLog & "'"
set yearsFolder to do shell script "/bin/date '" & dateFormatForYearlyLog & "'"
set fullPath to baseFolder & todaysFolder
createFolder(fullPath)
repeat with i from 1 to number of items in addedItems
set oneItemsPath to (quoted form of POSIX path of item i of addedItems)
try
moveToFolder(fullPath, oneItemsPath)
end try
set fileName to name of (info for item i of addedItems)
set logThis to todaysFolder & ": " & fileName
do shell script "echo " & logThis & " >> " & baseFolder & monthsFolder & "log.txt"
end repeat
do shell script "find " & baseFolder & yearsFolder & " -type f -name 'log.txt' -print0 | xargs -0 cat > " & baseFolder & yearsFolder & "index.mdown"
end adding folder items to
on createFolder(fullPath)
do shell script "/bin/mkdir -p " & quoted form of fullPath
end createFolder
on moveToFolder(fullPath, oneItemsPath)
do shell script "/bin/mv -n " & oneItemsPath & " " & fullPath
end moveToFolder