Menu

Skip to content
AppleScriptの穴
  • Home
  • Products
  • Books
  • Docs
  • Events
  • Forum
  • About This Blog
  • License
  • 仕事依頼

AppleScriptの穴

Useful & Practical AppleScript archive. Click '★Click Here to Open This Script' Link to download each AppleScript

カテゴリー: Language

与えられた自然言語テキストから言語を推測して、指定の性別で、TTSキャラクタを自動選択して読み上げ

Posted on 2月 5, 2022 by Takaaki Naganoya

自然言語テキストを与えると、記述言語を推測して、その言語コード(jaとか)、性別、Premium(高音質)音声かどうか(true/false)をもとにText to Speechの読み上げ音声キャラクタをしぼりこんで、sayコマンドで音声読み上げするAppleScriptです。

# ScriptのリストについているURL Linkを書き換えました

自然言語から推測される言語コードと、TTS音声キャラクタに振られている言語コードの間に仕様的な食い違いがあるので、中国語の自動判定を行うためには、(若干の)処理を追加する必要があります。

自然言語テキストから取得できるのは「簡体字」「繁体字」のコードである一方で、TTS読み上げキャラクタが持っているのは、China、HongKong、Taiwanと国コードなので、対照表でもつけるか、いっそ全部「zh」でくくってランダム選択するか、、、はたまた、実行マシンの緯度・経度情報から判定するか、テーブルを編集可能なようにしておいて、テーブルのルールを決め打ちで反映するとか、、、、


▲システム環境設定>アクセシビリティ>読み上げコンテンツ>システムの声 のポップアップメニューで、一番下に「カスタマイズ」の項目があり、Text To Speech読み上げキャラクタの追加が行える


▲追加したTTSキャラクタの音声データは自動でダウンロードが行われる。TTS用にSiri音声は指定できないが、「ショートカット」の音声読み上げでは指定できる。このあたり、外部のTTS音声データ提供会社との契約によるものなのか、あるいは管理プログラムが異なるのか?

AppleScript名:与えられた自然言語テキストから言語を推測して、指定の性別で、TTSキャラクタを自動選択して読み上げ v1(簡体字、繁体字 未サポート).scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2022/02/05
—
–  Copyright © 2022 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"

property NSSpeechSynthesizer : a reference to current application’s NSSpeechSynthesizer

set str1 to "こんにちは"

–指定文字列が何語かを推測して、言語コード(Short)を取得
set a1Res to guessLanguageCodeOf(str1) of me

–指定の言語コード(Short)をキーにしてTTS属性情報を取得
set vList to retAvailableTTSbyShortLangCodeAndSexAndPremium(a1Res, "Female", true) of me
if vList = {} then return

–取得したTTS情報リストから、てきとーに項目を取得
set fV to contents of first item of vList

set vName to VoiceName of fV
say str1 using vName

—
on retAvailableTTSbyShortLangCodeAndSexAndPremium(aLangShortCode as string, aSex as string, premiumFlag as boolean)
  set outList to {}
  
  
if aSex is not in {"Male", "Female"} then error "Sex code is wrong"
  
  
set aList to NSSpeechSynthesizer’s availableVoices()
  
set bList to aList as list
  
  
repeat with i in bList
    set j to contents of i
    
set aInfo to (NSSpeechSynthesizer’s attributesForVoice:j)
    
set aInfoRec to aInfo as record
    
    
–読み上げ対象文字データは多すぎるので削除しておく
    
set VoiceIndividuallySpokenCharacters of aInfoRec to {}
    
set VoiceSupportedCharacters of aInfoRec to {}
    
    
set aName to VoiceName of aInfoRec
    
set aLangCode to VoiceLocaleIdentifier of aInfoRec
    
    
set aGender to VoiceGender of aInfoRec
    
set aVID to VoiceIdentifier of aInfoRec
    
    
if (aLangCode starts with aLangShortCode) and (aGender = "VoiceGender" & aSex) then
      if premiumFlag = true then
        if aVID ends with "premium" then
          set the end of outList to aInfoRec
        end if
      else
        set the end of outList to aInfoRec
      end if
    end if
  end repeat
  
  
return outList
end retAvailableTTSbyShortLangCodeAndSexAndPremium

–文字列から言語を推測して言語名を返す
on guessLanguageOf(theString)
  set theTagger to current application’s NSLinguisticTagger’s alloc()’s initWithTagSchemes:{current application’s NSLinguisticTagSchemeLanguage} options:0
  
theTagger’s setString:theString
  
set languageID to theTagger’s tagAtIndex:0 |scheme|:(current application’s NSLinguisticTagSchemeLanguage) tokenRange:(missing value) sentenceRange:(missing value)
  
return ((current application’s NSLocale’s localeWithLocaleIdentifier:"en")’s localizedStringForLanguageCode:languageID) as text
end guessLanguageOf

–文字列から言語を推測して言語コードを返す
on guessLanguageCodeOf(theString)
  set theTagger to current application’s NSLinguisticTagger’s alloc()’s initWithTagSchemes:{current application’s NSLinguisticTagSchemeLanguage} options:0
  
theTagger’s setString:theString
  
set languageID to theTagger’s tagAtIndex:0 |scheme|:(current application’s NSLinguisticTagSchemeLanguage) tokenRange:(missing value) sentenceRange:(missing value)
  
return languageID as text
end guessLanguageCodeOf

★Click Here to Open This Script 

(Visited 123 times, 1 visits today)
Posted in Language Text Text to Speech | Tagged 10.15savvy 11.0savvy 12.0savvy NSLinguisticTagger NSLocale NSSpeechSynthesizer | Leave a comment

指定アプリケーションの各言語のローカライズ名称を取得して、言語名をローカライズしてNumbersに出力

Posted on 2月 4, 2022 by Takaaki Naganoya

指定アプリケーションが対応している各ローカライズ言語におけるアプリケーション名称を取得して、言語名をcurrent localeに合わせて変換しつつCSV出力してNumbersでオープンするAppleScriptです。

アプリケーションバンドルを調査して、ローカライズ対応している言語の一覧を取得するプログラムは組んでありました。そのローカライズを順次調べて、InfoPlist.stringsファイルを読み込み、CFBundleNameのエントリを調べています。

これで、その言語向けにローカライズされた「名称」を調べられます。あとは、言語コードを名称に変換する処理(これも、ありもの)を組み合わせて、2次元配列(2D list)にまとめあげ、CSV書き出しして(ありもの)、Numbersでオープンしただけのものです。

言語名称については、currentLocaleを利用しているため、日本語環境で実行すれば日本語表現で出力されますし、英語環境で実行すれば英語表現で出力されます。

実際に、書籍に掲載する資料用のデータを作成するときに使ってみました。

言語 Code 「地図」アプリのローカライズ名称
ドイツ語 de Karten
ヘブライ語 he מפות
英語(オーストラリア) en_AU Maps
アラビア語 ar الخرائط
ギリシャ語 el Χάρτες
日本語 ja マップ
英語 en Maps
ウクライナ語 uk Карти
スペイン語(ラテンアメリカ) es_419 Mapas
中国語(中国本土) zh_CN 地图
スペイン語 es Mapas
デンマーク語 da Kort
イタリア語 it Mappe
スロバキア語 sk Mapy
ポルトガル語(ポルトガル) pt_PT Mapas
マレー語 ms Peta
スウェーデン語 sv Kartor
チェコ語 cs Mapy
韓国語 ko 지도
広東語(中国本土) yue_CN 地图
ノルウェー語 no Kart
ハンガリー語 hu Térképek
中国語(香港) zh_HK 地圖
トルコ語 tr Harita
ポーランド語 pl Mapy
中国語(台湾) zh_TW 地圖
英語(イギリス) en_GB Maps
ベトナム語 vi Bản đồ
ロシア語 ru Карты
フランス語(カナダ) fr_CA Plans
フランス語 fr Plans
フィンランド語 fi Kartat
インドネシア語 id Peta
オランダ語 nl Kaarten
タイ語 th แผนที่
ポルトガル語 pt Mapas
ルーマニア語 ro Hărți
クロアチア語 hr Karte
ヒンディー語 hi नक़्शा
カタロニア語 ca Mapes
AppleScript名:指定アプリケーションの各言語のローカライズ名称を取得して、言語名をローカライズしてNumbersに出力.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2022/02/04
—
–  Copyright © 2022 Piyomaru Software, All Rights Reserved
—

use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use framework "AppKit"
use scripting additions

set targFile to "InfoPlist.strings"
set targKey to "CFBundleName"

set aLocale to (current application’s NSLocale’s currentLocale())

set aLoc to path to applications folder
set anApp to POSIX path of (choose file of type {"com.apple.application-bundle"} default location aLoc)

set aBundle to getBundleFromPath(anApp) of me
set aName to aBundle’s objectForInfoDictionaryKey:(current application’s kCFBundleNameKey)

set aLocList to getSpecifiedAppFilesLocalizationListWithDuplication(aBundle) of me

set hitList to {}

repeat with i in aLocList
  set j to contents of i
  
  
if j is not equal to "Base" then
    set allPath to anApp & "/Contents/Resources/" & j & ".lproj/" & targFile
    
set aDict to (current application’s NSDictionary’s alloc()’s initWithContentsOfFile:allPath)
    
    
if aDict is not equal to missing value then
      set aVal to (aDict’s valueForKeyPath:(targKey))
      
if aVal is not equal to missing value then
        set aLang to getLangNameWithLocale(j, aLocale) of me
        
set the end of hitList to {aLang, j, aVal as string}
      end if
    else
      log {"Error in ", j}
    end if
  end if
end repeat

–一時ファイルをCSV形式でデスクトップに書き出し
set aPath to (path to desktop as string) & (do shell script "uuidgen") & ".csv"
saveAsCSV(hitList, aPath) of me

–書き出したCSVファイルをNumbersでオープン
tell application "Numbers"
  open (aPath as alias)
end tell

–Application path –> Bundle
on getBundleFromPath(aPOSIXpath)
  set aURL to current application’s |NSURL|’s fileURLWithPath:aPOSIXpath
  
set aWorkspace to current application’s NSWorkspace’s sharedWorkspace()
  
set appURL to aWorkspace’s URLForApplicationToOpenURL:aURL
  
set aBundle to current application’s NSBundle’s bundleWithURL:appURL
  
return aBundle
end getBundleFromPath

–指定Bundleのローカライズ言語リストを求める。重複を許容
on getSpecifiedAppFilesLocalizationListWithDuplication(aBundle)
  set locList to aBundle’s localizations()
  
return locList as list
end getSpecifiedAppFilesLocalizationListWithDuplication

on getLangNameWithLocale(langCode, aLocale)
  set aLangName to (aLocale’s displayNameForKey:(current application’s NSLocaleIdentifier) value:langCode) as string
  
return aLangName
end getLangNameWithLocale

–2D List to CSV file
on saveAsCSV(aList, aPath)
  –set crlfChar to (ASCII character 13) & (ASCII character 10)
  
set crlfChar to (string id 13) & (string id 10)
  
set LF to (string id 10)
  
set wholeText to ""
  
  
repeat with i in aList
    set newLine to {}
    
    
–Sanitize (Double Quote)
    
repeat with ii in i
      set jj to ii as text
      
set kk to repChar(jj, string id 34, (string id 34) & (string id 34)) of me –Escape Double Quote
      
set the end of newLine to kk
    end repeat
    
    
–Change Delimiter
    
set aLineText to ""
    
set curDelim to AppleScript’s text item delimiters
    
set AppleScript’s text item delimiters to "\",\""
    
set aLineList to newLine as text
    
set AppleScript’s text item delimiters to curDelim
    
    
set aLineText to repChar(aLineList, return, "") of me –delete return
    
set aLineText to repChar(aLineText, LF, "") of me –delete lf
    
    
set wholeText to wholeText & "\"" & aLineText & "\"" & crlfChar –line terminator: CR+LF
  end repeat
  
  
if (aPath as string) does not end with ".csv" then
    set bPath to aPath & ".csv" as Unicode text
  else
    set bPath to aPath as Unicode text
  end if
  
  
writeToFileAsUTF8(wholeText, bPath, false) of me
  
end saveAsCSV

on writeToFileAsUTF8(this_data, target_file, append_data)
  tell current application
    try
      set the target_file to the target_file as text
      
set the open_target_file to open for access file target_file with write permission
      
if append_data is false then set eof of the open_target_file to 0
      
write this_data as «class utf8» to the open_target_file starting at eof
      
close access the open_target_file
      
return true
    on error error_message
      try
        close access file target_file
      end try
      
return error_message
    end try
  end tell
end writeToFileAsUTF8

on repChar(origText as text, targChar as text, repChar as text)
  set curDelim to AppleScript’s text item delimiters
  
set AppleScript’s text item delimiters to targChar
  
set tmpList to text items of origText
  
set AppleScript’s text item delimiters to repChar
  
set retText to tmpList as string
  
set AppleScript’s text item delimiters to curDelim
  
return retText
end repChar

★Click Here to Open This Script 

(Visited 45 times, 1 visits today)
Posted in Language Locale Record | Tagged 10.15savvy 11.0savvy 12.0savvy NSBundle NSDictionary NSLocale NSURL NSWorkspace Numbers | Leave a comment

最前面のKeynote書類のテキストアイテムの英語化率を求める

Posted on 1月 28, 2021 by Takaaki Naganoya

Keynote書類内のテキストアイテムのうち、どの程度が英語で書かれているかを計算するAppleScriptです。macOS 10.14以降で動作します。

日本語で書いた本を英語に翻訳しているわけですが、進捗を確認するのに自分でページを見ながら確認する作業が地味に大変です。そこで、この大変な作業をAppleScriptで自動処理することにしました。最終的なチェックは目視で行う必要がありますが、翻訳済みのテキストがどの程度あるかをテキストアイテムの個数ベースで(文章の長さは考慮せず)自動計算します。

AppleScriptでKeynote書類中のテキストアイテム中のテキストをすべて取得し、言語を自動判定して英語化率(≒英訳作業の進捗率)を計算してみました。


▲Script Debugger v8で実行したところ。Dark Modeへの対応が嬉しいが、全体的に動作が重い

日本語と英語以外にいろいろ意図しない言語判定されているテキストアイテムが存在していますが、そんな言語は書いていないのでおおよそ英語ブロックでしょう。

いま英語化率は80%と出ていますが、誤判定もあるはずなので、最後の最後は目視判定が必要と思われます。あとは、日本語フォントが指定されている箇所をクリーニングして、英語フォントに指定し直す作業も必要です。

開発マシンでmacOS 10.14.6+Keynote 10.1の環境で、139ページある「FileMaker Pro Scripting Book」の全テキスト判定に3.9秒ほどかかります。速度面でとくに不満はありませんが、こういう処理をM1 Macで行うとどの程度の速度になるのかには興味があります。

FileMaker選手権に応募した作品が入賞すれば、開発マシンの更新も可能かもしれませんが……勝負は時の運ということで。


▲英語への翻訳が完了したページ(表紙)


▲まだ日本語の文章がまだらに残っているページ。ただ、オリジナルの日本語版をもとに日本語の本のルールでページ順を設定しているので、「本当にこれでいいのか?」(奥付が最終ページにある日本スタイルそのまま、とか)とは思っています

AppleScript名:最前面のKeynote書類のテキストアイテムの英語化率を求める.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2021/01/27
—
–  Copyright © 2021 Piyomaru Software, All Rights Reserved
—

use AppleScript version "2.7" — High Sierra (10.13) or later
use framework "Foundation"
use framework "NaturalLanguage" –Mojave (10.14) or later
use scripting additions

tell application "Keynote"
  set dCount to count every document
  
if dCount = 0 then
    display notification "There is no Keynote document"
    
return {}
  end if
end tell

set tOut to {}
set erOut to {}

tell application "Keynote"
  tell front document
    set sCount to count every slide
    
repeat with i from 1 to sCount
      tell slide i
        set tList to every text item
        
        
repeat with i in tList
          set aTmpStr to object text of i
          
if aTmpStr is not equal to "" then
            set b1Res to guessLanguageCodeOf(aTmpStr) of me
            
set the end of tOut to b1Res
            
(*
            if b1Res is not equal to "en" then
              set the end of erOut to aTmpStr
            else
              set the end of tOut to b1Res
            end if
            *)

          end if
        end repeat
      end tell
    end repeat
  end tell
end tell

set tPercent to calcOneItemsPercent(tOut, "en") of me

on guessLanguageCodeOf(theString as string)
  set aNL to current application’s NLLanguageRecognizer’s alloc()’s init()
  
aNL’s processString:theString
  
set langRes to (aNL’s dominantLanguage()) as string
  
return langRes
end guessLanguageCodeOf

–true/falseで構成されるlistのうち、指定要素が占める割合を%で計算。小数点以下を四捨五入
on calcOneItemsPercent(aList, targItem)
  set aLen to length of aList
  
set theCountedSet to current application’s NSCountedSet’s alloc()’s initWithArray:aList
  
set tRes to (theCountedSet’s countForObject:targItem)
  
if tRes < 1 then return 0
  
set pRes to (tRes / aLen) * 100
  
return (round pRes rounding as taught in school)
end calcOneItemsPercent

★Click Here to Open This Script 

(Visited 159 times, 1 visits today)
Posted in Language Text | Tagged 10.14savvy 10.15savvy 11.0savvy Keynote | 1 Comment

指定の言語コードを、指定のLocaleの表現で、言語名称に

Posted on 8月 14, 2020 by Takaaki Naganoya

配列に入れた言語コードに対して、指定のLocaleの言語による表現で、言語名称を求めるAppleScriptです。

AppleScript名:指定の言語コードを、指定のLocaleの表現で、言語名称に.scpt
—
–  Created by: Takaaki Naganoya
–  Created on: 2020/08/14
—
–  Copyright © 2020 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set langList to {"en", "ru", "ja"}
set aList to getLocalizedLangNameList(langList, "ja_JP") of me
–> {"英語", "ロシア語", "日本語"}

set aList to getLocalizedLangNameList(langList, "en_US") of me
–> {"English", "Russian", "Japanese"}

set aList to getLocalizedLangNameList(langList, "zh-Hans") of me
—> {"英文", "俄文", "日文"}

on getLocalizedLangNameList(langList, aLocaleID)
  set aLocale to (current application’s NSLocale’s localeWithLocaleIdentifier:aLocaleID)
  
set langLocalizedList to {}
  
repeat with i in langList
    set aLang to getLangNameWithLocale(i, aLocale) of me
    
set the end of langLocalizedList to aLang
  end repeat
  
  
return langLocalizedList
end getLocalizedLangNameList

on getLangNameWithLocale(langCode, aLocale)
  set aLangName to (aLocale’s displayNameForKey:(current application’s NSLocaleIdentifier) value:langCode) as string
  
return aLangName
end getLangNameWithLocale

★Click Here to Open This Script 

(Visited 31 times, 1 visits today)
Posted in Language list Locale | Tagged 10.13savvy 10.14savvy 10.15savvy 11.0savvy | Leave a comment

指定の言語コードを、デフォルトのLocaleの表現で、言語名称に

Posted on 8月 14, 2020 by Takaaki Naganoya

配列変数に入れた言語コードを、デフォルトのLocaleの言語による表現で、言語名称を求めるAppleScriptです。

AppleScript名:指定の言語コードを、デフォルトのLocaleの表現で、言語名称に.scpt
—
–  Created by: Takaaki Naganoya
–  Created on: 2020/08/14
—
–  Copyright © 2020 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set langList to {"en", "ru", "ja"}
set aList to getLocalizedLangNameList(langList) of me
–> {"英語", "ロシア語", "日本語"}

on getLocalizedLangNameList(langList)
  set aLocale to (current application’s NSLocale’s currentLocale())
  
set langLocalizedList to {}
  
repeat with i in langList
    set aLang to getLangNameWithLocale(i, aLocale) of me
    
set the end of langLocalizedList to aLang
  end repeat
  
  
return langLocalizedList
end getLocalizedLangNameList

on getLangNameWithLocale(langCode, aLocale)
  set aLangName to (aLocale’s displayNameForKey:(current application’s NSLocaleIdentifier) value:langCode) as string
  
return aLangName
end getLangNameWithLocale

★Click Here to Open This Script 

(Visited 51 times, 1 visits today)
Posted in Language list Locale | Tagged 10.13savvy 10.14savvy 10.15savvy 11.0savvy | Leave a comment

クリップボード内のテキストをSayコマンドで読み上げて音声ファイル化

Posted on 5月 27, 2020 by Takaaki Naganoya

読み上げ対象のテキストをコピーした状態で実行するAppleScriptです。クリップボード内のテキストをSayコマンドで読み上げて、音声ファイルにレンダリングします。出力後、読み上げ所要時間を出力ファイルから求めてダイアログ表示します。

音声レンダリング処理は実際の音声読み上げ処理よりも短い時間で完了します。

–> Downlad Script With library within its bundle

掲載のリストを実行しても、スライダー入力ライブラリが含まれていないため、そのままでは実行できません。↑のScriptをまるごとダウンロードして展開すると、ライブラリ入りのScriptになります。実行にはダウンロードしたScriptをご利用ください。プログラムリスト掲載は参考のために行なっているものです。


▲ステップ1:念のために、読み上げ対象テキストをダイアログ表示


▲ステップ2:読み上げ時の速度をスライダーで選択


▲ステップ3:読み上げ音声を選択


▲ステップ4:読み上げ所要時間をダイアログ表示


▲ステップ5:音声レンダリングしたファイルをQuickTime Playerでオープン

AppleScript名:クリップボード内のテキストをSayコマンドで読み上げて音声ファイル化.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2020/05/27
—
–  Copyright © 2020 Piyomaru Software, All Rights Reserved
—

use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use framework "AppKit"
use framework "AVFoundation"
use scripting additions
use slLib : script "sliderLib"

property |NSURL| : a reference to current application’s |NSURL|
property NSDate : a reference to current application’s NSDate
property NSUUID : a reference to current application’s NSUUID
property NSFileManager : a reference to current application’s NSFileManager
property AVAudioPlayer : a reference to current application’s AVAudioPlayer
property NSDateFormatter : a reference to current application’s NSDateFormatter
property NSSpeechSynthesizer : a reference to current application’s NSSpeechSynthesizer

set aInfo to clipboard info
set uCount to (clipboard info for Unicode text)
if uCount = {} then
  display dialog "There is no text information in the clipboard" with title "Terminate information" buttons {"OK"} default button 1 with icon 2
  
return
end if

set totalCount to item 2 of item 1 of uCount

set aStr to the clipboard as text

–読み上げ内容の確認
display dialog aStr with title "Text length:" & (uCount as string) & " chars."

–読み上げ速度をSliderで入力
set rRes to slLib’s chooseBySlider(180, 220, "Select TTS reading pitch (small number:slow)")

–読み上げTTSキャラクタの選択
set aLoc to (current application’s NSLocale’s currentLocale()’s identifier()) as string –>  "ja_JP"
set vList to getTTSVoiceNameWithLanguage(aLoc) of me
set vRes to choose from list vList with prompt ("Select TTS Voice in your language :" & aLoc) without empty selection allowed
if vRes = false then return

set vCharacter to contents of first item of vRes

–音声ファイルの作成先パスを求める
set aUUID to NSUUID’s UUID()’s UUIDString() as string
set aPath to (((path to movies folder) as string) & aUUID & ".aif")
set aPOSIX to POSIX path of aPath

–音声レンダリング
tell current application
  say aStr using vCharacter saving to (aPOSIX) speaking rate rRes without waiting until completion
end tell

–レンダリングした音声の読み上げ所要時間を計算
set aDur to getDuration(aPath as alias) of me

–レンダリングした音声ファイルをオープン
tell application "QuickTime Player"
  open aPath
end tell

–完了報告
display dialog "読み上げ所要時間:" & my formatHMS(aDur)

on getTTSVoiceNameWithLanguage(voiceLang)
  set outArray to current application’s NSMutableArray’s new()
  
  
set aList to NSSpeechSynthesizer’s availableVoices()
  
set bList to aList as list
  
  
repeat with i in bList
    set j to contents of i
    
set aDIc to (NSSpeechSynthesizer’s attributesForVoice:j)
    (
outArray’s addObject:aDIc)
  end repeat
  
  
set aPredicate to current application’s NSPredicate’s predicateWithFormat_("VoiceLocaleIdentifier == %@", voiceLang)
  
set filteredArray to outArray’s filteredArrayUsingPredicate:aPredicate
  
set aResList to (filteredArray’s valueForKey:"VoiceName") as list
  
  
return aResList
end getTTSVoiceNameWithLanguage

on getDuration(aFile)
  set aURL to |NSURL|’s fileURLWithPath:(POSIX path of aFile)
  
  
repeat 1000 times
    set aAudioPlayer to AVAudioPlayer’s alloc()’s initWithContentsOfURL:aURL |error|:(missing value)
    
set aRes to aAudioPlayer’s prepareToPlay()
    
if aRes as boolean = true then exit repeat
    
delay 0.5
  end repeat
  
  
set channelCount to aAudioPlayer’s numberOfChannels()
  
set aDuration to aAudioPlayer’s duration()
  
return aDuration as real
end getDuration

on retAvailableTTSnames()
  set outList to {}
  
  
set aList to NSSpeechSynthesizer’s availableVoices()
  
set bList to aList as list
  
  
repeat with i in bList
    set j to contents of i
    
set aInfo to (NSSpeechSynthesizer’s attributesForVoice:j)
    
set aInfoRec to aInfo as record
    
set aName to VoiceName of aInfoRec
    
set the end of outList to aName
  end repeat
  
  
return outList
end retAvailableTTSnames

on formatHMS(aTime)
  set aDate to NSDate’s dateWithTimeIntervalSince1970:aTime
  
set aFormatter to NSDateFormatter’s alloc()’s init()
  
  
—This formatter text is localized in Japanese.
  
if aTime < hours then
    aFormatter’s setDateFormat:"mm分ss秒"
  else if aTime < days then
    aFormatter’s setDateFormat:"HH時間mm分ss秒"
  else
    aFormatter’s setDateFormat:"DD日HH時間mm分ss秒"
  end if
  
  
set timeStr to (aFormatter’s stringFromDate:aDate) as string
  
return timeStr
end formatHMS

★Click Here to Open This Script 

(Visited 153 times, 1 visits today)
Posted in dialog file Language Locale Text | Tagged 10.13savvy 10.14savvy 10.15savvy AVAudioPlayer NSDate NSDateFormatter NSFileManager NSMutableArray NSPredicate NSSpeechSynthesizer NSURL NSUUID | Leave a comment

指定アプリケーションを指定言語環境で再起動

Posted on 4月 30, 2020 by Takaaki Naganoya

指定アプリケーションを、現在のユーザーアカウントで指定可能な言語環境を指定して再起動するAppleScriptです。

Xcodeにこのような機能があり、そのような処理を行える可能性について思い至っていました。shell commandについてはEdama2さんから教えていただきました。あー、やっぱりこういう感じなんですね。

次に、言語コードを求める方法ですが、調べても全言語の言語コードを求める方法が見当たらなかったので(これは、探し方が足りないだけ)、現在のユーザーアカウントで指定可能な言語コードを求める方法に落ち着きました。

本Scriptを実行すると、指定アプリケーションを起動する言語コードを選択。

処理するアプリケーションを選択。choose applicationコマンドが活躍するのはとても珍しいケースです。

英語(English)を指定した場合。

フランス語(French)を指定した場合。

日本語(Japanese)を指定した場合。

個人的には、英語環境でアプリケーションを動かしつつ、執筆用のアプリケーション(Keynote)だけ日本語環境で動かすことができて、些細なコマンドの呼称を確認する必要がなくていい感じです。あれ? 日本語環境でターゲットのアプリケーションだけ英語環境を指定して起動すればいいんじゃ????

AppleScript名:指定アプリケーションを指定言語環境で再起動
—
–  Created by: Takaaki Naganoya
–  Created on: 2020/04/30
–  Special Thanks to : Edama2
–  Copyright © 2020 Piyomaru Software, All Rights Reserved
–  
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"
use framework "AppKit"

set aLocList to (current application’s NSLocale’s preferredLanguages()) as list

set targLanguage to choose from list aLocList
set anApp to choose application

set apFile to POSIX path of (path to anApp)
tell anApp to quit

set sText to "open -n -a " & quoted form of apFile & " –args -AppleLanguages ’(\"" & targLanguage & "\")’"
do shell script sText

★Click Here to Open This Script 

(Visited 60 times, 1 visits today)
Posted in Language Locale shell script | Tagged 10.13savvy 10.14savvy 10.15savvy | 3 Comments

Wikipedia経由で2つの単語の共通要素を計算するcommon elements Lib Script Library

Posted on 2月 28, 2020 by Takaaki Naganoya

現在作成中のアプリケーションの副産物として生まれた「common elements Lib」AppleScript Libraryです。2つの単語の共通要素を計算して返します。

# v1.1にアップデートしました(ダウンロード先URLはかわらず)。ページ下部のテンプレート部分の余計なリンクを拾わないように改善したため、テンプレート部分のリンクが多い項目に対して大きな効果を発揮します

–> Download archive

アーカイブをダウンロードして展開し、~/Library/Script Librariesフォルダに「common elements Lib.scptd」を入れるとAppleScriptから呼び出せるようになります。

macOS 10.10以降で動作するはずですが、開発は10.14上で、動作確認は10.13/10.14/10/15上でのみ行なっています。

この、2つのキーワードの共通要素を求める処理は「マッキー演算」と呼んでおり、男性アイドルグループ「SMAP」と、男性シンガーソングライター「槇原敬之」(マッキー)氏の共通要素を演算で求めることを目的として企画されました。「SMAP」はWikipedia上でも最大級の要素数を持つ項目であり、1,400項目以上のリンク要素を擁しています。

Wikipedia REST APIの仕様ではリンク要素を500項目までしか一度に取得できません。SMAPを処理するためには、複数ページにまたがるリンク取得の処理をこなすことが必要であり、「マッキー演算」は言葉のバカっぽさとは裏腹に、それなりの技術力が要求される、そこそこむずかしい処理なのです。

本ライブラリを用いて、WikipeidaにREST API経由で検索司令を出すわけですが、英語のスペルの単語を受け付けるWikipediaもあれば、日本語やアラビア語Wikipediaなどのようにその言語向けの書き換えを行ったデータで検索するものもあり、割とまちまちであることがわかりました。そのあたりは、sdefに書いておいたサンプルScriptを見ていただくのがよいでしょう。

本ライブラリでは、演算対象とする単語はWikipediaに掲載されているものに限られています。実際に、日本語環境で「スティーブ・ジョブズ」と「ラリー・テスラー」の共通項目を計算すると、

--> {"パロアルト研究所", "Smalltalk", "アメリカ合衆国", "Lisa (コンピュータ)", "アップル・ニュートン", "Macintosh", "アップル (企業)", "Macworld", "スタンフォード大学"}

「スティーブ・ジョブズ」と「ロス・ペロー」の共通項目を計算すると、

--> {"NeXT", "アル・ゴア", "統合典拠ファイル", "実業家", "IBM", "ゼネラルモーターズ", "SNAC", "アメリカ合衆国", "国際標準名称識別子", "孫正義", "ソフトバンク", "国立国会図書館", "フランス国立図書館", "アメリカ議会図書館管理番号", "CiNii", "バーチャル国際典拠ファイル"}

のような結果を返してきます。

冒頭で述べた「SMAP」と「槇原敬之」の共通項目を計算すると、

--> {"スポーツニッポン", "ABO式血液型", "テレビ朝日", "東京都", "社長", "エフエム東京", "ミュージックステーション", "J-POP", "第42回NHK紅白歌合戦", "大阪城ホール", "日本", "We are SMAP!", "ミリオンセラー", "小倉博和", "インターネットアーカイブ", "日本武道館", "ニッポン放送", "リクルートホールディングス", "日刊スポーツ", "第58回NHK紅白歌合戦", "フジテレビジョン", "世界に一つだけの花"}

のようになります。

おおよその主要言語に対応していますが、ロシア語をはじめとするキリル文字の言語を指定すると、なぜか結果が返ってきません。これが、キリル文字のエンコーディングに関する(こちら側の実装がまずい)問題なのか、サーバー側がREST APIをサポートしていないのか(Wikipediaサーバー側の問題)はわかりません。
→ ロシア語のクエリーも処理できることを確認しました

ここでは、だいたいの「いい感じのキーワード」を例として出していますが「George Lucas」と「Steven Spielberg」などの近い単語を指定すると結果が400個以上返ってきます。
→ v1.1における改良により、400個以上のリンクを66個まで減少させました(不要なフッター部分のリンクを拾わないようにした)

膨大な項目から必要な要素を選択するInterfaceをみつくろってテストをしてはいるのですが、iOS上でよさそうに見えてもMac上で動かすといまひとつだったり、なかなか合うものが見つかりません(超多項目選択UI)。

–> Watch Demo

こうした計算結果をもっと減らす方法や、これらの多項目の計算結果からGUI上で項目選択する方法などが自分たちでは見つからなかったので、ライブラリとして公開して広く意見やアイデアを募ろうと考えました。多言語のWikipediaへの問い合わせを行ったり、問題点を洗い出すことも目的の1つです。前述のとおり、ロシア語系のWikipediaに対するアクセスに問題がある点については調査が必要です。

余談ですが、Steve JobsとLarry Teslerの関連項目演算を行おうとしても、Larry Teslerの項目がなかったり、Xerox PARCへのリンクがないために演算結果にこれが含まれない言語のWikipediaがいくつか見られました。コンピュータ史上重要な偉人への敬意をこめ、ぜひ追記していただきたいと考えるものです(という話を日本語で書いても意味がない?)。

AppleScript name:sample.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2020/02/28
—
–  Copyright © 2020 Piyomaru Software, All Rights Reserved
— http://www.piyocast.com

use comLib : script "common elements Lib"

–English
set aWord to "Steve Jobs"
set bWord to "Larry Tesler"
set commonResEN to list up common elements with {aWord, bWord} with language "en"
–> {"The New York Times", "Computer History Museum", "Alan Kay", "International Standard Book Number", "California", "Steve Jobs", "Computer mouse", "John Markoff", "Ethernet", "Stanford University", "Counterculture of the 1960s", "Fortune (magazine)", "Tablet computer", "Apple Lisa", "Apple Inc.", "Associated Press", "Graphical user interface", "International Standard Serial Number", "Apple Computer", "Macintosh 128K", "Xerox Alto"}

–日本語(Japanese)
set aWord to "スティーブ・ジョブズ" –Steve Jobs
set bWord to "ラリー・テスラー" –Larry Tesler
set commonResJP to list up common elements with {aWord, bWord} with language "jp"
–> {"パロアルト研究所", "Smalltalk", "アメリカ合衆国", "Lisa (コンピュータ)", "アップル・ニュートン", "Macintosh", "アップル (企業)", "Macworld", "スタンフォード大学"}

–中文(Simplified Chinese)
set aWord to "史蒂夫·乔布斯" –Steve Jobs
set bWord to "拉里·泰斯勒" –Larry Tesler
set commonResZH to list up common elements with {aWord, bWord} with language "zh"
–> {"母校", "美國", "帕羅奧多研究中心"}

—한국어(Korean)
set aWord to "스티브 잡스" –Steve Jobs
set bWord to "빌 게이츠" –Bill Gates
set commonResKO to list up common elements with {aWord, bWord} with language "ko"
—> {"가상 국제 전거 파일", "위키인용집", "게마인자메 노름다타이", "네덜란드 왕립도서관", "국제 표준 도서 번호", "IBM", "SNAC", "CiNii", "개인용 컴퓨터", "BIBSYS", "영어", "국제 표준 명칭 식별자", "오스트레일리아 국립도서관", "LIBRIS", "체코 국립도서관", "미국", "스페인 국립도서관", "뮤직브레인즈", "프랑스 국립도서관", "이스라엘 국립도서관", "일본 국립국회도서관", "미국 의회도서관 제어 번호", "전거 통제", "국립중앙도서관", "WorldCat Identities", "실리콘 밸리의 신화", "프랑스 대학도서관 종합목록", "위키미디어 공용"}

–svenska
set aWord to "Steve Jobs"
set bWord to "Ross Perot"
set commonResSV to list up common elements with {aWord, bWord} with language "sv"
–> {"USA", "IBM", "Forbes", "Entreprenör", "Libris (bibliotekskatalog)"}

–Deutsch
set aWord to "Steve Jobs"
set bWord to "Larry Tesler"
set commonResDE to list up common elements with {aWord, bWord} with language "de"
–> {"Objektorientierte Programmierung", "Apple", "Apple Macintosh", "Xerox PARC", "Virtual International Authority File", "The New York Times", "Kalifornien", "Apple Lisa"}

–français
set aWord to "Steve Jobs"
set bWord to "Larry Tesler"
set commonResFR to list up common elements with {aWord, bWord} with language "fr"
–> {"The New York Times", "Palo Alto Research Center", "Informaticien", "Californie", "Apple", "États-Unis", "Autorité (sciences de l’information)"}

–Nederlands
set aWord to "Steve Jobs"
set bWord to "Larry Tesler"
set commonResNL to list up common elements with {aWord, bWord} with language "nl"
–> {"Verenigde Staten (hoofdbetekenis)", "Palo Alto Research Center", "Apple Macintosh", "Xerox", "Apple Inc.", "Apple Lisa", "Apple Newton"}

–italiano
set aWord to "Steve Jobs"
set bWord to "Larry Tesler"
set commonResIT to list up common elements with {aWord, bWord} with language "it"
–>{"Apple", "Stati Uniti d’America", "Xerox Palo Alto Research Center", "Informatico"}

–español
set aWord to "Steve Jobs"
set bWord to "Ross Perot"
set commonResES to list up common elements with {aWord, bWord} with language "es"
–> {"Emprendedor", "Library of Congress Control Number", "Wikidata", "IBM", "Enciclopedia Británica", "Wikimedia Commons", "Empresario", "CiNii", "National Diet Library", "Estados Unidos", "National Library of the Czech Republic", "Virtual International Authority File", "Bibliothèque nationale de France", "International Standard Name Identifier", "Integrated Authority File", "Système universitaire de documentation", "ISBN"}

–polski
set aWord to "Steve Jobs"
set bWord to "Larry Tesler"
set commonResPL to list up common elements with {aWord, bWord} with language "pl"
–> {"Apple Inc.", "Virtual International Authority File", "Xerox PARC"}

–Tiếng Việt
set aWord to "Steve Jobs"
set bWord to "Larry Tesler"
set commonResVI to list up common elements with {aWord, bWord} with language "vi"
–> {"Hoa Kỳ", "Apple Lisa", "California", "Apple Inc."}

–Arabic
set aWord to "ستيف جوبز"
set bWord to "روس بيرو"
set commonResAR to list up common elements with {aWord, bWord} with language "ar"
–> {"مكتبة البرلمان الوطني", "رقم الضبط في مكتبة الكونغرس", "رائد أعمال", "المكتبة الوطنية لجمهورية التشيك", "ملف استنادي متكامل", "ملف استنادي دولي افتراضي", "المكتبة الوطنية الفرنسية", "سايني", "ديل", "آي بي إم", "لغة إنجليزية", "ضبط استنادي", "حزب سياسي", "مهنة", "مدرسة أم", "واي باك مشين", "الولايات المتحدة", "المحدد المعياري الدولي للأسماء", "دولار أمريكي"}

–português
set aWord to "Steve Jobs"
set bWord to "Larry Tesler"
set commonResPT to list up common elements with {aWord, bWord} with language "pt"
–> {"Macintosh", "Alan Kay", "Apple Newton", "Povo dos Estados Unidos", "Língua inglesa", "Estados Unidos", "Ciência da computação", "Apple", "Califórnia", "Base Virtual Internacional de Autoridade"}

–Català
set aWord to "Steve Jobs"
set bWord to "Larry Tesler"
set commonResCA to list up common elements with {aWord, bWord} with language "ca"
–> {"Control d’autoritats", "Virtual International Authority File", "Apple Macintosh", "Apple Inc", "Interfície gràfica d’usuari"}

–Bahasa Indonesia
set aWord to "Steve Jobs"
set bWord to "Larry Tesler"
set commonResNO to list up common elements with {aWord, bWord} with language "id"
–> {"California", "Biografi", "Amerika Serikat"}

–magyar
set aWord to "Steve Jobs"
set bWord to "Larry Tesler"
set commonResHU to list up common elements with {aWord, bWord} with language "hu"
–> {"Amerikai Egyesült Államok", "Informatikus", "Wikimédia Commons", "Stanford Egyetem", "Nemzetközi Virtuális Katalógustár"}

–euskara
set aWord to "Steve Jobs"
set bWord to "Larry Tesler"
set commonResEU to list up common elements with {aWord, bWord} with language "eu"
–> {"Xerox", "Informatikari", "Ingeles", "Apple Inc.", "Ameriketako Estatu Batuak", "Wikidata", "Smalltalk", "Virtual International Authority File", "Stanford Unibertsitatea", "Wikimedia Commons"}

–Türkçe
set aWord to "Steve Jobs"
set bWord to "Larry Tesler"
set commonResTR to list up common elements with {aWord, bWord} with language "tr"
–> {"The New York Times", "Apple", "Amerika Birleşik Devletleri", "Kaliforniya"}

★Click Here to Open This Script 

AppleScript name:sample2
—
–  Created by: Takaaki Naganoya
–  Created on: 2020/02/28
—
–  Copyright © 2020 Piyomaru Software, All Rights Reserved
— http://www.piyocast.com

use comLib : script "common elements Lib"

set sList to supported lang codes
–> {"en", "ceb", "sv", "de", "fr", "nl", "ru", "it", "es", "pl", "war", "vi", "jp", "zh", "ar", "pt", "uk", "fa", "ca", "sr", "no", "id", "ko", "fi", "hu", "sh", "cs", "ro", "eu", "tr", "ms", "eo", "hy", "bg", "he", "da", "ce", "zh-min-nan", "sk", "kk", "min", "hr", "et", "lt", "be", "el", "azb", "sl", "gl", "az", "simple", "ur", "nn", "hi", "th", "ka", "uz", "la", "ta", "vo", "arz", "cy", "mk", "tg", "lv", "ast", "mg", "tt", "af", "oc", "bs", "bn", "ky", "sq", "zh-yue", "tl", "new", "te", "be-tarask", "br", "ml", "pms", "nds", "su", "ht", "lb", "jv", "sco", "mr", "sw", "pnb", "ga", "szl", "ba", "is", "my", "fy", "cv", "lmo", "an", "ne", "pa", "yo", "bar", "io", "gu", "wuu", "als", "ku", "scn", "kn", "ckb", "bpy", "ia", "qu", "mn", "bat-smg", "vec", "wa", "si", "or", "cdo", "gd", "yi", "am", "nap", "ilo", "bug", "xmf", "mai", "hsb", "map-bms", "fo", "diq", "mzn", "sd", "li", "eml", "sah", "nv", "os", "sa", "ps", "ace", "mrj", "frr", "zh-classical", "mhr"}

–"ru", "uk", "sh", "bg" seems not to work… "ms" or later codes seems not to work (depends on Wikipedia Server spec)….

★Click Here to Open This Script 

(Visited 108 times, 1 visits today)
Posted in Internet Language Natural Language Processing REST API Script Libraries sdef | Tagged 10.10savvy 10.11savvy 10.12savvy 10.13savvy 10.14savvy 10.15savvy | 1 Comment

指定Bundle IDのstringsファイル中における指定タイトルの指定言語のローカライズ版を求める

Posted on 2月 24, 2020 by Takaaki Naganoya

/Applicationsフォルダ以下のすべてのアプリケーションのバンドル中のstringsファイル中を走査して、指定の言語における指定キーワード(”Quit”など)の指定言語におけるローカライズした文字列を取得するAppleScriptです。

自分でアプリケーションのローカライズを行う際に、既存のmacOS用のアプリケーションのバンドル内にあるstringsファイルを参考にするためのツールです。

もともとは、Shane StanleyがLate Night Softwareのフォーラムに投稿したプログラムですが、自分もいろいろ試していたように、アプリケーション側のローカライズのされ方(言語別のフォルダ名の名称指定)に「ゆらぎ」があるため、そのあたりは総当たりでテストしているようです。

オリジナルではデータが存在しない場合にはエラーにしていましたが、このようにすべてのアプリケーションに対してループで処理を行うような場合にはエラーで止まっては困るので、そのあたりを書き換えています。

/Applicationsフォルダ以下のSpotlight検索によるアプリケーションの取得についてはMetadata Libを用いています。自分の開発環境で1キーワード(x バンドル内のすべてのstringsファイル x すべてのアプリケーション)の問い合わせに3.6〜5秒程度かかっています。HDDの環境ではこれより大幅に長くかかるはずなので、ちょっと考えたくありません。

また、Stringsファイルで供給されるローカライズ情報については探すことができますが、OS側が強制的に供給するWindowメニューなどの内容については本Scriptで調査することはできません。ねんのため。

AppleScript名:指定Bundle IDのstringsファイル中における指定タイトルの指定言語のローカライズ版を求める.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2020/02/24
—
–  Copyright © 2020 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.5" — El Capitan (10.11) or later
use framework "Foundation"
use framework "AppKit"
use scripting additions
use mdLib : script "Metadata Lib" version "2.0.0" –https://macosxautomation.com/applescript/apps/Script_Libs.html

property NSWorkspace : a reference to current application’s NSWorkspace

set targStr to "Performance"
set origLang to "en" –From
set targLang to "hu" –To

set tList to {}

set origPath to POSIX path of (path to applications folder)
set aResList to mdLib’s searchFolders:{origPath} searchString:("kMDItemContentType == %@") searchArgs:{"com.apple.application-bundle"}
repeat with i in aResList
  set aTitleRes to getAppGUITitleWithCurrentLocale(i, targStr, origLang, targLang) of me
  
if aTitleRes is not equal to missing value and aTitleRes is not in tList then
    set the end of tList to aTitleRes
  end if
end repeat

return tList
–> {"Előadás", "Teljesítmény"}

–指定Bundle IDのstringsファイル中における指定タイトルの現在実行中のロケールのローカライズ版を求める
on getAppGUITitleWithCurrentLocale(aPath, aTargetTitle, origLang, targLang)
  return my localizedStringFor:aTargetTitle inBundle:aPath destLang:targLang sourceLang:origLang
end getAppGUITitleWithCurrentLocale

–Bundle IDからアプリケーションのPathを返す
on retAppAbusolutePathFromBundleID(aBundleID)
  set appPath to NSWorkspace’s sharedWorkspace()’s absolutePathForAppBundleWithIdentifier:aBundleID
  
if appPath = missing value then return false
  
return appPath as string
end retAppAbusolutePathFromBundleID

–Original By Shane Stanley@Late Night Software
–Modified By Takaaki Naganoya
–https://forum.latenightsw.com/t/localizing-gui-scripts/2246
on localizedStringFor:baseString inBundle:aPOSIX destLang:destLangCode sourceLang:sourceLangCode
  set anURL to current application’s |NSURL|’s fileURLWithPath:aPOSIX
  
set theBundle to current application’s NSBundle’s bundleWithURL:anURL
  
if theBundle = missing value then return missing value
  
  
set sourceLangString to current application’s NSString’s stringWithString:sourceLangCode
  
set destLangString to current application’s NSString’s stringWithString:destLangCode
  
  
— get source strings values
  
set theURLs to theBundle’s URLsForResourcesWithExtension:"strings" subdirectory:"" localization:sourceLangString
  
if theURLs = missing value then return missing value
  
if theURLs’s |count|() < 2 and (sourceLangString’s containsString:"_") as boolean then
    — try stripping off country-specific part
    
set sourceLangString to sourceLangString’s substringToIndex:2
    
set theURLs to theBundle’s URLsForResourcesWithExtension:"strings" subdirectory:"" localization:sourceLangString
  end if
  
  
if theURLs’s |count|() < 2 then
    — try long name for localization
    
set sourceLangString to (current application’s NSLocale’s localeWithLocaleIdentifier:"en")’s localizedStringForLocaleIdentifier:sourceLangString
    
set theURLs to theBundle’s URLsForResourcesWithExtension:"strings" subdirectory:"" localization:sourceLangString
  end if
  
  
if theURLs’s |count|() < 2 then return missing value –error "No " & sourceLangCode & " localization found"
  
  
repeat with sourceURL in theURLs
    — skip unlocalized file
    
if not (sourceURL’s URLByDeletingLastPathComponent()’s lastPathComponent()’s isEqualToString:"Resources") as boolean then
      set theData to (current application’s NSData’s alloc()’s initWithContentsOfURL:sourceURL)
      
      
if theData is missing value then return — error "No " & sourceLangCode & " localization found"
      
set sourceDict to (current application’s NSPropertyListSerialization’s propertyListWithData:theData options:0 format:0 |error|:(missing value))
      
if sourceDict = missing value then return missing value
      
      
set theKey to (sourceDict’s allKeysForObject:baseString)’s firstObject()
      
      
if theKey is not missing value then
        set stringsFileName to sourceURL’s lastPathComponent()’s stringByDeletingPathExtension()
        
set localURL to (theBundle’s URLForResource:stringsFileName withExtension:"strings" subdirectory:"" localization:destLangString)
        
        
if localURL is missing value and (destLangString’s containsString:"_") as boolean then
          — try stripping off country-specific part
          
set destLangString to (destLangString’s substringToIndex:2)
          
set localURL to (theBundle’s URLForResource:stringsFileName withExtension:"strings" subdirectory:"" localization:destLangString)
        end if
        
        
if localURL is missing value then
          — try long name for localization
          
set destLangString to ((current application’s NSLocale’s localeWithLocaleIdentifier:"en")’s localizedStringForLocaleIdentifier:destLangString)
          
set localURL to (theBundle’s URLForResource:stringsFileName withExtension:"strings" subdirectory:"" localization:destLangString)
        end if
        
        
if localURL is missing value then return missing value — "No " & destLangCode & " localization found"
        
        
set theData to (current application’s NSData’s alloc()’s initWithContentsOfURL:localURL)
        
if theData is missing value then missing value — "No " & destLangCode & " localization found"
        
set destDict to (current application’s NSPropertyListSerialization’s propertyListWithData:theData options:0 format:0 |error|:(missing value))
        
set destValue to (destDict’s objectForKey:theKey)
        
        
–if destValue is not missing value then return {destValue as text, stringsFileName as text}
        
if destValue is not missing value then return destValue as text
        
return missing value
      end if
    end if
  end repeat
  
return missing value
end localizedStringFor:inBundle:destLang:sourceLang:

★Click Here to Open This Script 

(Visited 42 times, 1 visits today)
Posted in file File path Language Locale Text | Tagged 10.14savvy 10.15savvy NSBundle NSData NSLocale NSPropertyListSerialization NSString NSURL NSWorkspace | Leave a comment

ISOコードから国名を取得

Posted on 12月 30, 2019 by Takaaki Naganoya

ISOコード(ISO 3166-1 Alpha-2 code)で示した国の名称を取得するAppleScriptです。

現在のロケールでローカライズして取得するもの(retCountryNameInCurrentLocale)と、指定ロケールでローカライズするもの(retCountryNameInSpecifiedLocale)を用意しておきました。

Mac App Storeに出したDouble PDF v2.0(30言語以上ローカライズした)の審査は年越し確実で、審査に1か月以上かかるという、自分の知っている範囲での最長記録を更新しつつあります(AppleがOSに作ったバグを回避する以外の追加機能はわずかなのに)。

そんな中、各国語で国名を表記する方法を調べておきました。ヒンディー語、タイ語、ギリシア語あたりは文字が見慣れないながらもギリギリ文字単位での識別が可能で、非日常感があって(日本語の表記範囲で出てこない文字なので)クールな感じがします(個人の見解です)。アラビア語やヘブライ語になってしまうと、コンピュータの挙動が変わってしまうので(表記が右→左)、ちょっとシャレにならない感じであります。

AppleScript名:ISOコードから国名を取得.scpt
—
–  Created by: Takaaki Naganoya
–  Created on: 2019/12/30
—
–  Copyright © 2019 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use scripting additions

set aCountryName to retCountryNameInCurrentLocale("GE") of me
–> "ジョージア" —In Japanese (Current Locale, diffenret in each user)

set bCountryName to retCountryNameInSpecifiedLocale("GE", "en_US") of me
–> "Georgia" –In English
set cCountryName to retCountryNameInSpecifiedLocale("GE", "fr") of me
–> "Géorgie"–In French
set dCountryName to retCountryNameInSpecifiedLocale("GE", "ru") of me
–> "Грузия"–In Russian
set eCountryName to retCountryNameInSpecifiedLocale("GE", "zh") of me
–>"格鲁吉亚"–In Chinese
set fCountryName to retCountryNameInSpecifiedLocale("GE", "ko_KR") of me
–> "조지아"–In Korean
set gCountryName to retCountryNameInSpecifiedLocale("GE", "hi") of me
–> "जॉर्जिया" –In Hindi
set hCountryName to retCountryNameInSpecifiedLocale("GE", "th") of me
–> "จอร์เจีย"-In Thai
set iCountryName to retCountryNameInSpecifiedLocale("GE", "el_GR") of me
–> "Γεωργία"–In Greek

–指定の国名コードから国名を現在のロケールでローカライズして返す
on retCountryNameInCurrentLocale(isoCode as string)
  set curLocale to current application’s NSLocale’s currentLocale()
  
set aLocLangCode to (curLocale’s objectForKey:(current application’s NSLocaleLanguageCode)) as string
  
set aCountry to curLocale’s displayNameForKey:(current application’s NSLocaleCountryCode) value:isoCode
  
return aCountry as string
end retCountryNameInCurrentLocale

–指定の国名コードから国名を指定のロケールでローカライズして返す
on retCountryNameInSpecifiedLocale(isoCode as string, targLocale as string)
  set curLocale to current application’s NSLocale’s localeWithLocaleIdentifier:targLocale
  
set aLocLangCode to (curLocale’s objectForKey:(current application’s NSLocaleLanguageCode)) as string
  
set aCountry to curLocale’s displayNameForKey:(current application’s NSLocaleCountryCode) value:isoCode
  
return aCountry as string
end retCountryNameInSpecifiedLocale

★Click Here to Open This Script 

(Visited 48 times, 1 visits today)
Posted in Language Locale | Tagged 10.12savvy 10.13savvy 10.14savvy 10.15savvy NSLocale NSLocaleCountryCode NSLocaleLanguageCode | Leave a comment

InputManagerでIMを切り換える v2

Posted on 12月 20, 2018 by Takaaki Naganoya

InputManager.frameworkを呼び出して、日本語入力Input Methodの入力文字の切り替えを行うAppleScriptです。

–> Demo Movie

macOS標準装備のスクリプトエディタ上ではControl-Command-Rで実行できましたが、Script Debugger上で動かなかった(メインスレッド上で強制実行する必要があった)ので、切り替えメソッドを強制的にメインスレッド上で実行するように変更してみました。

–> InputManager.framework (To ~/Library/Frameworks)

macOS 10.14上で実行する場合には、(フレームワーク呼び出しの都合上)Script Debugger上で実行してください。

AppleScript名:InputManagerでIMを切り換える v2
— Created 2017-01-22 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "InputManager" –https://github.com/jensnockert/input-manager

–Caution: This script runs on only Japanese language environment

set cList to current application’s CSInputSource’s all()
set dList to (cList’s valueForKey:"localizedName")
set aRes to ((dList’s indexOfObject:"ひらがな") as integer) –"Hiragana" in Japanese
set bRes to ((dList’s indexOfObject:"英字") as integer) –"English Letters" in Japanese

set hiraKey to cList’s objectAtIndex:aRes
set engKey to cList’s objectAtIndex:bRes

repeat 3 times
  my performSelectorOnMainThread:"selectInputCharMode:" withObject:(hiraKey) waitUntilDone:true
  
delay 1
  
my performSelectorOnMainThread:"selectInputCharMode:" withObject:(engKey) waitUntilDone:true
  
delay 1
end repeat

–Force execute on Main Thread
on selectInputCharMode:aModeObj
  aModeObj’s |select|()
end selectInputCharMode:

★Click Here to Open This Script 

(Visited 71 times, 1 visits today)
Posted in Input Method Language | Tagged 10.11savvy 10.12savvy 10.13savvy 10.14savvy | 1 Comment

言語コードから言語名を取得する

Posted on 2月 6, 2018 by Takaaki Naganoya
AppleScript名:言語コードから言語名を取得する
— Created 2015-12-21 13:13:24 +0900 by Takaaki Naganoya
— 2015 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

set countryCode to "en"

set ident to current application’s NSLocale’s preferredLanguages()’s firstObject()
–>  (NSArray) {​​​​​"ja", ​​​​​"en-US", ​​​​​"en-GB", ​​​​​"en", ​​​​​"fr"​​​}
set aLocale to current application’s NSLocale’s alloc()’s initWithLocaleIdentifier:ident
set aCountryName to aLocale’s displayNameForKey:(current application’s NSLocaleIdentifier) value:countryCode
–>  (NSString) "英語 (アメリカ合衆国)"

★Click Here to Open This Script 

(Visited 27 times, 1 visits today)
Posted in Language System | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

電子書籍(PDF)をオンラインストアで販売中!

Google Search

Popular posts

  • AppleScriptによるWebブラウザ自動操縦ガイド
  • macOS 13, Ventura(継続更新)
  • ドラッグ&ドロップ機能の未来?
  • macOS 12.x上のAppleScriptのトラブルまとめ
  • PFiddlesoft UI Browserが製品終了に
  • macOS 12.3 beta 5、ASの障害が解消される(?)
  • SF Symbolsを名称で指定してPNG画像化
  • 新刊発売:AppleScriptによるWebブラウザ自動操縦ガイド
  • macOS 12.3上でFinder上で選択中のファイルをそのままオープンできない件
  • Pixelmator Pro v2.4.1で新機能追加+AppleScriptコマンド追加
  • Safariで表示中のYouTubeムービーのサムネイル画像を取得
  • macOS 12のスクリプトエディタで、Context Menu機能にバグ
  • 人類史上初、魔導書の観点から書かれたAppleScript入門書「7つの宝珠」シリーズ開始?!
  • UI Browserがgithub上でソース公開され、オープンソースに
  • macOS 12.5(21G72)がリリースされた!
  • Pages v12に謎のバグ。書類上に11枚しか画像を配置できない→解決
  • 新発売:AppleScriptからSiriを呼び出そう!
  • iWork 12.2がリリースされた
  • macOS 13 TTS Voice環境に変更
  • NSCharacterSetの使い方を間違えた

Tags

10.11savvy (1102) 10.12savvy (1243) 10.13savvy (1391) 10.14savvy (586) 10.15savvy (434) 11.0savvy (274) 12.0savvy (174) 13.0savvy (34) CotEditor (60) Finder (47) iTunes (19) Keynote (97) NSAlert (60) NSArray (51) NSBezierPath (18) NSBitmapImageRep (21) NSBundle (20) NSButton (34) NSColor (51) NSDictionary (27) NSFileManager (23) NSFont (18) NSImage (42) NSJSONSerialization (21) NSMutableArray (62) NSMutableDictionary (21) NSPredicate (36) NSRunningApplication (56) NSScreen (30) NSScrollView (22) NSString (118) NSURL (97) NSURLRequest (23) NSUTF8StringEncoding (30) NSUUID (18) NSView (33) NSWorkspace (20) Numbers (55) Pages (36) Safari (41) Script Editor (20) WKUserContentController (21) WKUserScript (20) WKWebView (23) WKWebViewConfiguration (22)

カテゴリー

  • 2D Bin Packing
  • 3D
  • AirDrop
  • AirPlay
  • Animation
  • AppleScript Application on Xcode
  • beta
  • Bluetooth
  • Books
  • boolean
  • bounds
  • Bug
  • Calendar
  • call by reference
  • Clipboard
  • Code Sign
  • Color
  • Custom Class
  • dialog
  • drive
  • exif
  • file
  • File path
  • filter
  • folder
  • Font
  • Font
  • GAME
  • geolocation
  • GUI
  • GUI Scripting
  • Hex
  • History
  • How To
  • iCloud
  • Icon
  • Image
  • Input Method
  • Internet
  • iOS App
  • JavaScript
  • JSON
  • JXA
  • Keychain
  • Keychain
  • Language
  • Library
  • list
  • Locale
  • Machine Learning
  • Map
  • Markdown
  • Menu
  • Metadata
  • MIDI
  • MIME
  • Natural Language Processing
  • Network
  • news
  • Noification
  • Notarization
  • Number
  • Object control
  • OCR
  • OSA
  • PDF
  • Peripheral
  • PRODUCTS
  • QR Code
  • Raw AppleEvent Code
  • Record
  • recursive call
  • regexp
  • Release
  • Remote Control
  • Require Control-Command-R to run
  • REST API
  • Review
  • RTF
  • Sandbox
  • Screen Saver
  • Script Libraries
  • sdef
  • search
  • Security
  • selection
  • shell script
  • Shortcuts Workflow
  • Sort
  • Sound
  • Spellchecker
  • Spotlight
  • SVG
  • System
  • Tag
  • Telephony
  • Text
  • Text to Speech
  • timezone
  • Tools
  • Update
  • URL
  • UTI
  • Web Contents Control
  • WiFi
  • XML
  • XML-RPC
  • イベント(Event)
  • 未分類

アーカイブ

  • 2023年3月
  • 2023年2月
  • 2023年1月
  • 2022年12月
  • 2022年11月
  • 2022年10月
  • 2022年9月
  • 2022年8月
  • 2022年7月
  • 2022年6月
  • 2022年5月
  • 2022年4月
  • 2022年3月
  • 2022年2月
  • 2022年1月
  • 2021年12月
  • 2021年11月
  • 2021年10月
  • 2021年9月
  • 2021年8月
  • 2021年7月
  • 2021年6月
  • 2021年5月
  • 2021年4月
  • 2021年3月
  • 2021年2月
  • 2021年1月
  • 2020年12月
  • 2020年11月
  • 2020年10月
  • 2020年9月
  • 2020年8月
  • 2020年7月
  • 2020年6月
  • 2020年5月
  • 2020年4月
  • 2020年3月
  • 2020年2月
  • 2020年1月
  • 2019年12月
  • 2019年11月
  • 2019年10月
  • 2019年9月
  • 2019年8月
  • 2019年7月
  • 2019年6月
  • 2019年5月
  • 2019年4月
  • 2019年3月
  • 2019年2月
  • 2019年1月
  • 2018年12月
  • 2018年11月
  • 2018年10月
  • 2018年9月
  • 2018年8月
  • 2018年7月
  • 2018年6月
  • 2018年5月
  • 2018年4月
  • 2018年3月
  • 2018年2月

https://piyomarusoft.booth.pm/items/301502

メタ情報

  • 登録
  • ログイン
  • 投稿フィード
  • コメントフィード
  • WordPress.org

Forum Posts

  • 人気のトピック
  • 返信がないトピック

メタ情報

  • 登録
  • ログイン
  • 投稿フィード
  • コメントフィード
  • WordPress.org
Proudly powered by WordPress
Theme: Flint by Star Verte LLC