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

MecabCocoaで形態素解析

Posted on 11月 14, 2018 by Takaaki Naganoya

オープンソースのMecabラッパー「MecabCocoa.framework」を呼び出して、日本語の文字列を形態素解析するAppleScriptです。

単語(形態素)に分割する形態素解析については、動作しているものの、

 partOfSpeechType:品詞
 originalForm:原形

といったあたりの、重要な情報がまともに返ってこないので、単語分割やよみがなの機能しか動作していないように見えるのですが、、、、

AppleScript名:MecabCocoaで形態素解析.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2018/11/13
—
–  Copyright © 2018 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use framework "MecabCocoa" –https://github.com/shinjukunian/MecabCocoa
use scripting additions

set aStr to "私の名前は長野谷です。"
set tokenArray to (current application’s MecabTokenizer’s alloc()’s parseToNodeWithString:aStr withDictionary:2)
set tList to (tokenArray’s surface) as list
–> {"私", "の", "名前", "は", "長野", "谷", "です", "。"}

set fList to (tokenArray’s features) as list
–> {{"watakushi"}, missing value, {"namae"}, missing value, {"nagano"}, {"tani"}, missing value, missing value}

set psList to (tokenArray’s partOfSpeechType) as list
–> {100, 100, 100, 100, 100, 100, 100, 100} –おかしい?

★Click Here to Open This Script 

Posted in Natural Language Processing Text | Tagged 10.11savvy 10.12savvy 10.13savvy 10.14savvy | Leave a comment

NLLanguageRecognizerで自然言語の推定 v4

Posted on 11月 13, 2018 by Takaaki Naganoya

macOS 10.14であらたに搭載されたNaturalLanguage.frameworkにアクセスして、自然言語テキストが「何語」かを推定し、指定数の言語ごとにその推測した確率を求めるAppleScriptです。

NLLanguageRecognizerで、言語推定時に「言語Aと言語Bのみ考慮してね」と指定し、それぞれに数値による重み付け(0.0〜1.0)を指定できます。

ただ、重み付けを指定してもダメな時はダメなようで……日本語の文章に多めにアルファベットが入っている場合にはまったく日本語と判定されません。

AppleScript名:NLLanguageRecognizerで自然言語の推定 v4
— Created 2018-11-13 by Takaaki Naganoya
use AppleScript version "2.7" — Mojave (10.14) or later
use framework "Foundation"
use framework "NaturalLanguage"
use scripting additions

property NLLanguageEnglish : a reference to current application’s NLLanguageEnglish
property NSMutableDictionary : a reference to current application’s NSMutableDictionary
property NLLanguageJapanese : a reference to current application’s NLLanguageJapanese
property NLLanguageRecognizer : a reference to current application’s NLLanguageRecognizer

set aNL to NLLanguageRecognizer’s alloc()’s init()

–言語ごとに可能性の重み付けを行って、言語推定

–言語推定の可能性ヒントデータを指定。日本語が99.9%、英語は0.1%の可能性として指定
set hintDict to NSMutableDictionary’s dictionaryWithObjects:{1.0E-3, 0.999} forKeys:{NLLanguageEnglish, NLLanguageJapanese}
–> (*(NSDictionary) {en:0.01, ja:0.99}*) –recordで作ってScriptingBridge経由でNSDictionaryに自動変換させてもよかったが、recordでは属性ラベルにハイフンなどは使えないのでこれでいいのだ
set hintRes3 to (aNL’s setLanguageHints:hintDict)

aNL’s processString:"AppleScriptで日本語を処理するよ。"
set langRes4 to (aNL’s languageHypothesesWithMaximum:2) as record
–> {en:1.0}– アルファベットの文字量が多いので、英語と判断されたよ! (>_<)

aNL’s processString:"AppleScriptで日本語を処理するぴよ。"
set langRes5 to (aNL’s languageHypothesesWithMaximum:2) as record
–> {ja:1.0}– 「よ」を「ぴよ」に書き換えたら日本語の文字の量が増えて日本語と判定されたよ! (^ー^)

★Click Here to Open This Script 

Posted in Natural Language Processing Record Text | Tagged 10.14savvy NLLanguageRecognizer NSMutableDictionary | Leave a comment

NLLanguageRecognizerで自然言語の推定 v3

Posted on 11月 13, 2018 by Takaaki Naganoya

macOS 10.14であらたに搭載されたNaturalLanguage.frameworkにアクセスして、自然言語テキストが「何語」かを推定し、指定数の言語ごとにその推測した確率を求めるAppleScriptです。

NLLanguageRecognizerも、「最もそれらしいラベル(言語)値」を返すだけでなく、推測候補言語とその確率(0.0〜1.0、1.0が最もそれらしい)をDictionary形式で(AppleScriptでいうところのrecord)出力するメソッドがあります。試しに呼んでみました。

AppleScript名:NLLanguageRecognizerで自然言語の推定 v3
— Created 2018-11-13 by Takaaki Naganoya
use AppleScript version "2.7" — Mojave (10.14) or later
use framework "Foundation"
use framework "NaturalLanguage"
use scripting additions

property NLLanguageRecognizer : a reference to current application’s NLLanguageRecognizer

set aNL to NLLanguageRecognizer’s alloc()’s init()

–言語推定時の各言語の可能性の数値をリストアップ
aNL’s processString:"AppleScriptで日本語を処理。"
set langRes1 to (aNL’s languageHypothesesWithMaximum:10) as record
–> {|is|:0.017804400995, ro:0.02502822876, fr:0.015569564886, de:0.041996311396, |it|:0.017095085233, nl:0.630239665508, sv:0.041430238634, en:0.11029753834, nb:0.025065546855, hu:0.051682028919}
–アルファベットの比率が高まると、日本語として認識される可能性が極端に下がる

aNL’s processString:"「「「「了解です!」」」」" –なろう系小説の複数人物の同時発話表現
set langRes2 to (aNL’s languageHypothesesWithMaximum:5) as record
–> {|zh-hans|:0.251541793346, ja:0.748288214207, |zh-hant|:1.62590833497234E-4}

★Click Here to Open This Script 

Posted in Natural Language Processing Record Text | Tagged 10.14savvy NLLanguageRecognizer | Leave a comment

NLLanguageRecognizerで自然言語の推定 v2

Posted on 11月 13, 2018 by Takaaki Naganoya

macOS 10.14であらたに搭載されたNaturalLanguage.frameworkにアクセスして、自然言語テキストが「何語」かを推定するAppleScriptです。

以前にNSLinguisticTaggerで言語推定を試してみましたが、ネット上のラノベ文書(セリフが多く、人名がカタカナばっかり)を与えてみたら日本語を日本語として判定せず、「使えない機能」だと感じました。

ポンコツで与える文字列の長さや記号文字の登場頻度に極端に演算結果が左右されていたNSLinguisticTaggerとは異なり、このNLLanguageRecognizerは割と使えるようです。「日本語だよ。」という程度の文章で日本語と判定してくれたので、なかなか使えそうな気配がします。

ただし、実際に試してみたところ文中にアルファベットの単語が多く含まれると日本語として判定してくれなくなるという「弱点」があるので、そのあたりは注意を要します。

AppleScript名:NLLanguageRecognizerで自然言語の推定 v2.scptd
— Created 2018-11-13 by Takaaki Naganoya
use AppleScript version "2.7" — Mojave (10.14) or later
use scripting additions
use framework "Foundation"
use framework "NaturalLanguage" –new framework

set str01 to "Ilmatyynyalukseni on täynnä ankeriaita."
set str02 to "Luftputebåten min er full av ål"
set str03 to "私の名前は長野谷です。"
set str04 to "أنشأ فوكوزاوا يوكيتشي (١٨٣٥–١٩٠١) في اكتوبر عام ١٨٥٨ مدرسة للدراسات الهولندية (تحولت بعد ذلك لمدرسة للغة الانكليزية) في ايدو (طوكيو حاليا). يعد فوكوزاوا يوكيتشي من أحد مؤسسي نهضة اليابان الحديثة، فونهتم بمدرستنا بنوع التعليم الذي ينمي القدرات الإبداعية والفنية التي يتطلب توافرها في طلاب الجامعة بحيث لا ينشغل الطلاب باختبار قبول الجامعات ونحترم استقلالية وتفرد كل طالب وذلك في جو دافئ في بيئة طبيعية مليئة بأشجار"
set str05 to "게이오 기주쿠는 어디에나 있는 학교의 하나로 만족하지 않습니다. 게이오 기주쿠는 기주쿠(義塾, 의숙)에서 배우는 학생과 교원이 일본의 ’기품의 원천’ 및 ’지덕의 모범’이 되는 것을 목표로 하는 학숙(學塾)입니다. "
set str06 to "庆应义塾不是仅仅满足于成为常常见到的一般性学校。"
set str07 to "Je suis japonaise."
set str08 to "Buon pomeriggio."
set str09 to "Хороших выходных!"
set str10 to "Möchten Sie Tee oder Kaffee?"

set a1Res to guessLanguageCodeOf(str01) of me –>  "fi"
set a2Res to guessLanguageCodeOf(str02) of me –>  "sv"
set a3Res to guessLanguageCodeOf(str03) of me –>  "ja"
set a4Res to guessLanguageCodeOf(str04) of me –>  "ar"
set a5Res to guessLanguageCodeOf(str05) of me –>  "ko"
set a6Res to guessLanguageCodeOf(str06) of me –>  "zh-Hans"
set a7Res to guessLanguageCodeOf(str07) of me –>  "fr"
set a8Res to guessLanguageCodeOf(str08) of me –>  "it"
set a9Res to guessLanguageCodeOf(str09) of me –>  "ru"
set a10Res to guessLanguageCodeOf(str10) of me –> "de"

return {a1Res, a2Res, a3Res, a4Res, a5Res, a6Res, a7Res, a8Res, a9Res, a10Res}
–> {"fi", "nb", "ja", "ar", "ko", "zh-Hans", "fr", "it", "ru", "de"}

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

★Click Here to Open This Script 

Posted in Natural Language Processing Text | Tagged 10.14savvy NLLanguageRecognizer | Leave a comment

Bayes推定による文章仕分け(Classifier)

Posted on 11月 12, 2018 by Takaaki Naganoya

ベイズ推定を計算するオープンソースのプログラム「Bayes」をCocoaフレームワーク化した「BayesKit」を呼び出してベイズ推定の計算を行うAppleScriptです。

–> Download BayesKit.framework (To ~/Library/Frameworks)

macOS 10.14以外はスクリプトエディタ/Script Debugger上で実行可能で、10.14のみScript Debugger上での実行を必要とします(この仕様、いい加減かったるいので戻してほしい)。

スパムメール選別用途御用達のベイズ推定の演算を行なってみました。プログラムに添付されていたサンプルは英語の文章を処理するようにできていましたが、予想どおり日本語の文章をそのまま与えると単語切り分けが行えずに計算がうまく行きません。

そこで、掲載サンプルScriptのように単語ごとに手動で半角スペースを入れてみました。

本来であれば、形態素解析辞書を使って単語ごとに切り分け、さらに単語の活用形をどうにかする必要があるはずですが、そこまで神経質にならずに簡易日本語パーサーで単語に分解し、助詞などを削除しデータとして与えることでそこそこの実用性は確保できるのではないかと思われます(これだと固有名詞がバラバラになる可能性は否定できませんが)。

NSLinguisticTagger+macOS 10.14で日本語文章の形態素解析+品詞解析は行えることを期待したいですが、未確認です。ただ、できた場合でも固有名詞への配慮がどの程度あるかは不明です。

AppleScript名:Bayes推定による文章仕分け(Classifier).scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2018/11/12
—
–  Copyright © 2018 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.5" — El Capitan(10.11) or later
use framework "Foundation"
use framework "BayesKit" –https://github.com/kevincobain2000/Bayes
use scripting additions

property Bayes : a reference to current application’s Bayes
property FeaturesVector : a reference to current application’s FeaturesVector
property NSMutableArray : a reference to current application’s NSMutableArray

–set positiveStr to "word word good good"
–set negativeStr to "thiss word bad bad"
set positiveStr to "良い 良い 良い 良い 。"
set negativeStr to "悪 悪 悪 悪 悪 。"

set classifierObj to Bayes’s alloc()’s init()
set featuresVec to FeaturesVector’s alloc()’s init()

set featuresArray to NSMutableArray’s arrayWithArray:{"tokens"}

featuresVec’s appendFeatures:positiveStr forFeatures:featuresArray
classifierObj’s train:(featuresVec’s features) forlabel:"positive"

featuresVec’s appendFeatures:negativeStr forFeatures:featuresArray
classifierObj’s train:(featuresVec’s features) forlabel:"negative"

–set toGuess to "word"
set toGuess to "良い 。"

featuresVec’s appendFeatures:toGuess forFeatures:featuresArray
classifierObj’s guessNaiveBayes:(featuresVec’s features)

set vRes to (classifierObj’s probabilities) as record
–> {positive:0.6400000453, negative:0.32000002265}–English Sample Words OK
–> {positive:1.0, negative:0.0}–Japanese Sample Words OK

★Click Here to Open This Script 

Posted in Machine Learning Record Text | Tagged 10.11savvy 10.12savvy 10.13savvy 10.14savvy NSMutableArray | Leave a comment

squeezeNetで画像のオブジェクト認識を行い、結果をCSV出力してNumbersでオープン

Posted on 11月 12, 2018 by Takaaki Naganoya

Core MLモデル「squeezeNet.mlmodel」を用いて画像のオブジェクト認識を行い、結果をデスクトップにCSV形式でデータ書き出しを行い、NumbersでオープンするAppleScriptです。

–> Download squeezeNetKit.framework (To ~/Library/Frameworks)

macOS 10.13上ではスクリプトエディタ、Script Debugger上で、macOS 10.14上ではScript Debugger上で動作します(AppleScript Appletでも動作)。

さまざまなCore MLモデルを用いて画像認識を行わせてはみたものの、最もスコアの高いもののラベルだけを返させても、結果がまったく内容にそぐわないケースが多く見られます。


▲機械学習の評価値が1.0に近いものは確度が高く、0.0に近いものは判断に迷った末に消極的に出した値。経験則でいえば、最高スコアの項目が0.7以上のスコアでないといまひとつのようです(0.7以上でもダメな時はダメなわけで、、、)

画像認識については、結果があまりに的外れで「なんじゃこら?」というケースが多いので、確認のためにCSVデータ出力させてNumbers上で確認させてみることにしてみました。そのためにありあわせのサブルーチンを組み合わせて作ったものです。

スコアが高い順に結果を並べて確認してみると、最も高いスコアの値であっても0.0に近い評価値であることがあり、「何も考えずに最高スコアのラベルだけ取ってくるのはものすごく危険」なことがよくわかります。


▲squeezeNet.mlmodelをNetronでビジュアライズしたところ(一部抜粋)

AppleScript名:SqueezeNetでオブジェクト判定して結果をCSV書き出ししてNumbersでオープン.scpt
–  Created by: Takaaki Naganoya
–  Created on: 2018/11/11
–  Copyright © 2018 Piyomaru Software, All Rights Reserved
use AppleScript version "2.7" — High Sierra (10.13) or later
use framework "Foundation"
use framework "AppKit"
use framework "squeezeNetKit"
use scripting additions

property NSUUID : a reference to current application’s NSUUID
property NSArray : a reference to current application’s NSArray
property NSImage : a reference to current application’s NSImage
property NSMutableArray : a reference to current application’s NSMutableArray
property NSSortDescriptor : a reference to current application’s NSSortDescriptor

set aFile to POSIX path of (choose file of type {"public.image"})
set aImage to NSImage’s alloc()’s initWithContentsOfFile:aFile
set resDict to (current application’s imageClassifier’s alloc()’s init()’s ImageClassifierWithImageAndRetDict:aImage)

set kArray to (resDict’s allKeys())
set vArray to (resDict’s allValues())
set aLen to kArray’s |count|()

set anArray to NSMutableArray’s new()

repeat with i from 0 to (aLen – 1)
  set tmpKey to (kArray’s objectAtIndex:i) as string
  
set tmpVal to (vArray’s objectAtIndex:i) as real
  (
anArray’s addObject:{aKey:tmpKey, aVal:tmpVal})
end repeat

–Sort by value
set bList to sortRecListByLabel(anArray, "aVal", false) of me

–record in list –> 2D list
set cList to convRecInListTo2DList(bList) of me

–デスクトップにCSVファイルを書き出してNumbersでオープン
set aPath to (((path to desktop) as string) & (NSUUID’s UUID()’s UUIDString()) as string) & ".csv"
set fRes to saveAsCSV(cList, aPath) of me
tell application "Numbers"
  open (aPath as alias)
end tell

–リストに入れたレコードを、指定の属性ラベルの値でソート
on sortRecListByLabel(aRecList as list, aLabelStr as string, ascendF as boolean)
  set aArray to NSArray’s arrayWithArray:aRecList
  
set sortDesc to NSSortDescriptor’s alloc()’s initWithKey:aLabelStr ascending:ascendF
  
set sortDescArray to NSArray’s arrayWithObjects:sortDesc
  
set sortedArray to aArray’s sortedArrayUsingDescriptors:sortDescArray
  
set bList to (sortedArray) as anything
  
return bList
end sortRecListByLabel

on convRecInListTo2DList(aList)
  set anArray to NSMutableArray’s arrayWithArray:aList
  
set fItem to anArray’s objectAtIndex:0
  
set keyList to fItem’s allKeys() as list
  
set aCount to anArray’s |count|()
  
  
set allArray to NSMutableArray’s new()
  
  
repeat with i from 1 to aCount
    set anItem to (anArray’s objectAtIndex:(i – 1))
    
set tmpItem to {}
    
    
repeat with ii in keyList
      set tmpDat to (anItem’s valueForKeyPath:(contents of ii))
      
if tmpDat is not equal to missing value then
        set the end of tmpItem to tmpDat
      else
        set the end of tmpItem to ""
      end if
    end repeat
    (
allArray’s addObject:tmpItem)
  end repeat
  
  
set allList to allArray as list
  
set the beginning of allList to keyList
  
return allList
end convRecInListTo2DList

–CSV Kit

–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
  
  
write_to_file(wholeText, bPath, false) of me
  
end saveAsCSV

on write_to_file(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 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 write_to_file

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 

Posted in file Image list Machine Learning Record Sort | Tagged 10.13savvy 10.14savvy NSArray NSImage NSMutableArray NSSortDescriptor NSUUID Numbers | Leave a comment

機械学習モデルをもとに画像のシーン判定

Posted on 11月 6, 2018 by Takaaki Naganoya

Appleが配布しているCoreML Model「Places205-GoogLeNet」を用いて、指定画像のシーン判定を行うAppleScriptです。

Appleが公式に配布している6つのCoreML Modelのうち、「Places205-GoogLeNet」を組み込んだFrameworkを作成して、これをAppleScriptから呼び出しています。

sceneDetection.frameworkをインストールしたうえで、macOS 10.13上ではスクリプトエディタ/Script Debuggerから、macOS 10.14ではScript Debuggerから本Scriptを実行します(AppleScriptアプレットでも動作します)。

「Places205-GoogLeNet」は、

Detects the scene of an image from 205 categories such as an airport terminal, bedroom, forest, coast, and more.

と、画像の内容から、画面やシーン、場所について「だいたいこんなところ」と判定してくれるModelのようです。ただ、日本国内の景色を渡してみると、得られる判定結果にはいまひとつ「ちょっと違う」と感じるものであります。


▲左:crosswalk(横断歩道)実際には自動車販売店と道路(Car shop & road)、右:desert/sand(砂漠、砂)実際にはAirport


▲左:river(川)実際には海、右:bridge(橋) 実際には橋ではありません

–> Download sceneDetection.framework (To ~/Library/Frameworks)


▲GoogLeNetPlaces.mlmodelをNetronでビジュアライズしたところ

AppleScript名:GoogLeNetPlacesでシーン判定.scpt
use AppleScript version "2.7" — High Sierra (10.13) or later
use framework "Foundation"
use framework "AppKit"
use framework "sceneDetection"
use scripting additions

set aFile to POSIX path of (choose file of type {"public.image"})
set aImage to current application’s NSImage’s alloc()’s initWithContentsOfFile:aFile
set msDict to (current application’s sceneDetector’s alloc()’s init()’s GoogLeNetPlacesWithImage:aImage) as string
–> "crosswalk"

★Click Here to Open This Script 

Posted in file Image Machine Learning | Tagged 10.13savvy 10.14savvy NSImage | Leave a comment

CreateMLで機械学習したモデルを利用して、MS画像の連邦、ジオン軍判定

Posted on 11月 6, 2018 by Takaaki Naganoya

「戦場の絆」のホームページからダウンロードしたMSの画像を学習させた機械学習モデルを使用して、指定のMS画像が地球連邦軍(EFSF)かジオン軍(zeon)かを判定するAppleScriptです。


■©創通・サンライズ 学習時に299×299ピクセルに縮小されるので、モノアイとかそういう部分が特徴量として検出されることはないもよう

両軍合わせて180機体ほどの画像を学習させただけなので、正直なところ判定間違いが多いですが、増やしていくとけっこう簡単に判定できそうです(数万ファイルぐらい画像を学習させるともっと明確な傾向が出てくるかも?)。


▲学習させたMS画像データ。efsf、efsf_stole(鹵獲機体)、zeon、zeon_stole(鹵獲機体)に分けてみた。CoreMLで任意のMS画像がこれらのどのグループに所属する可能性が最も高いかをフォルダ名で返してくることになる

macOS 10.14上のスクリプトエディタは野良Frameworkを認識してくれないので、macOS 10.14.x+Script Debugger上で実行する必要があります。あと、AppleScriptアプレットに書き出して実行すると野良Frameworkを認識して実行するので、アプレットに書き出して実行するとScript DebuggerのないmacOS 10.14環境でも動作確認できます。

Xcode上でSwift Playgroundを用いて認識していた時よりも認識精度が下がっているように見えます。結局画像は299×299ピクセルぐらいに縮小されて判定されるので、判定前に画像余白部分をトリミングしておくと認識精度が上がりそうな気もします。

299×299ピクセルに縮小されると、さすがにモノアイが特徴量として認識される可能性も低く、色とかポーズとか構図とかで識別されているのでしょう。


▲作成したmodelをNetronでビジュアライズしたところ

CreateMLで機械学習モデルを作るのがとても簡単であることがわかり、機械学習モデルを呼び出すためのAppleScriptのコードがとてもシンプルなことがわかり、さらに学習モデルを用いた画像分類が短い時間で行えることを確認できました。

現在のところ、1つの機械学習モデル(.mlmodel)を使うためにそのモデルを組み込んだFrameworkを必要としている状態ですが、機械学習モデル自体も外部からパスで指定して柔軟に指定できるようにしたいところです。

これで調子に乗って手書き文字画像データ(Mnist)をCreateMLで機械学習して、手書き文字の画像をスキャナから読み取って手軽に手書き文字認識できるかも?! と、鼻息荒くテストしてみましたが、期待したような精度では判定されないことを思い知らされたのでした。

–> Download msDetector.framework (To ~/Library/Frameworks)

AppleScript名:機械学習で学習したMSの画像の連邦軍、ジオン軍判定.scpt
use AppleScript version "2.7" — Mojave (10.14) or later
use framework "Foundation"
use framework "AppKit"
use framework "msDetector"
use scripting additions

set aFile to POSIX path of (choose file of type {"public.image"})
set aImage to current application’s NSImage’s alloc()’s initWithContentsOfFile:aFile
set msRes to current application’s msClassify’s alloc()’s init()’s ImageClassifierWithImage:aImage
–> "efsf" / "zeon"

★Click Here to Open This Script 

Posted in file Image Machine Learning | Tagged 10.14savvy NSImage | Leave a comment

Table 1の全セルを選択する v3

Posted on 11月 5, 2018 by Takaaki Naganoya

Numbersで選択中のセルがなければ、最前面の書類の選択中のワークシートのうちのTable 1を全選択するAppleScriptです。

選択部分からデータを取得する処理はよく行いますが、プログラム側から選択部分を作成するというのはやっていなかったので、試行錯誤してみました。

AppleScript名:Table 1の全セルを選択する v3.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2018/11/05
—
–  Copyright © 2018 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use scripting additions

tell application "Numbers"
  tell front document
    tell active sheet
      try
        –選択セルがある場合
        
set theTable to first table whose class of selection range is range
      on error
        –選択セルがない場合はTable 1を全選択
        
set tCount to count every table
        
if tCount = 0 then error "There is no table in active sheet"
        
        
tell table 1
          set selection range to cell range
        end tell
        
      end try
    end tell
  end tell
end tell

★Click Here to Open This Script 

Posted in How To | Tagged 10.11savvy 10.12savvy 10.13savvy 10.14savvy Numbers | Leave a comment

電子書籍2冊のリンク切れの対処データが完成

Posted on 11月 4, 2018 by Takaaki Naganoya

2018年1月末の本Blog消失に伴い、電子書籍「AppleScript最新リファレンス」「AppleScript 10大最新技術」本文中からリンクしていた本Blog上のURLの変更先情報補完、および抜けていた記事のBlogへの補充作業がほぼ終了しました。

抜けた記事の再作成&更新作業は割としんどいものでした(ーー;;; 

2つの電子書籍のサポートページ上にURLの対応表を掲載いたしましたので、ご参照ください。

→ 「AppleScript最新リファレンス」サポートページ

→ 「AppleScript 10大最新技術」サポートページ

Posted in Release | Leave a comment

MIKMIDIでデバイス一覧を取得 v2

Posted on 11月 4, 2018 by Takaaki Naganoya

オープンソースのフレームワーク「MIKMIDI」を用いてMIDIデバイス情報を取得するAppleScriptです。

Objective-Cのプログラムもいろいろ読んできましたが、その中でもこれは難易度が高く、高尚であるために読んでもさっぱりわかりません。

–> Download MIKMIDI.framework(To ~/Library/Frameworks/)

AppleScript名:MIKMIDIでデバイス一覧を取得 v2
— Created 2015-11-13 by Takaaki Naganoya
— 2015 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "MIKMIDI" –https://github.com/mixedinkey-opensource/MIKMIDI

property midiDeviceManager : missing value

set midiDeviceManager to current application’s MIKMIDIDeviceManager’s sharedDeviceManager()’s availableDevices()
set aRes to midiDeviceManager’s mutableCopy()

set endpointsInDevs to current application’s NSMutableSet’s |set|()
repeat with i in (midiDeviceManager as list)
  set aSrcList to (current application’s NSSet’s setWithArray:(i’s entities()’s valueForKeyPath:"sources"))
  
set aDstList to (current application’s NSSet’s setWithArray:(i’s entities()’s valueForKeyPath:"destinations"))
  (
endpointsInDevs’s unionSet:aSrcList)
  (
endpointsInDevs’s unionSet:aDstList)
end repeat

endpointsInDevs’s |description|()
–>  (NSSet) {{(MIKMIDISourceEndpoint) <MIKMIDISourceEndpoint: 0x7f8a61d47950> 新しい外部装置}, {(MIKMIDISourceEndpoint) <MIKMIDISourceEndpoint: 0x7f8a63a65610> IAC Driver GarageBand}, {(MIKMIDIDestinationEndpoint) <MIKMIDIDestinationEndpoint: 0x7f8a61bbc130> IAC Driver GarageBand}, {(MIKMIDIDestinationEndpoint) <MIKMIDIDestinationEndpoint: 0x7f8a5ecadcf0> 新しい外部装置}}

–midiDeviceManager’s virtualSources() –Real MIDI I/Fがつながっていないとエラーになる
–set devicelessSources to current application’s NSMutableSet’s setWithWrray:(midiDeviceManager’s virtualSources())

★Click Here to Open This Script 

Posted in MIDI System | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

指定URLをロード_WKWebView版 v2

Posted on 11月 4, 2018 by Takaaki Naganoya

指定のURLを読み込んでページのタイトルを取得するAppleScriptです。

オリジナルはControl+Command+Rの操作が必要でしたが、本バージョンでは必要ありません。ただ、Script Debuggerとの相性はよろしくないようで。

AppleScript名:指定URLをロード_WKWebView版 v2
— Created 2015-09-16 by Takaaki Naganoya
— 2015 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "WebKit"

property theWebView : missing value

set aURL to "http://www.apple.com/jp/shop/browse/home/specialdeals/mac"

my performSelectorOnMainThread:"getPage:" withObject:(aURL) waitUntilDone:true

set aTitle to (theWebView)’s title()
return aTitle as text
–>  "Mac整備済製品 – Apple(日本)"

–Download the URL page to WkWebView
on getPage:aURL
  set thisURL to current application’s |NSURL|’s URLWithString:aURL
  
set theRequest to current application’s NSURLRequest’s requestWithURL:thisURL
  
  
set aConf to current application’s WKWebViewConfiguration’s alloc()’s init()
  
  
set (my theWebView) to current application’s WKWebView’s alloc()’s initWithFrame:(current application’s NSMakeRect(0, 0, 800, 600)) configuration:aConf –フレームの大きさは根拠レス
  (
my theWebView)’s setNavigationDelegate:me
  (
my theWebView)’s loadRequest:theRequest
  
  
set waitLoop to 100 * 60 –60 seconds
  
  
set hitF to false
  
repeat waitLoop times
    set aLoadF to ((my theWebView)’s estimatedProgress()) as number
    
if aLoadF = 1.0 then
      set hitF to true
      
exit repeat
    end if
    
current application’s NSThread’s sleepForTimeInterval:(0.01)
    
–delay 0.1
  end repeat
  
  
return hitF
end getPage:

★Click Here to Open This Script 

Posted in URL | Tagged 10.11savvy 10.12savvy 10.13savvy NSThread NSURL NSURLRequest WKWebView WKWebViewConfiguration | Leave a comment

QuartzComoserでグラフ表示てすと v6

Posted on 11月 4, 2018 by Takaaki Naganoya

QuartzComposerのグラフに任意のデータを指定してウィンドウ表示するAppleScriptです。

スクリプトバンドル内の「Chart.qtz」を読み出して表示しているため、QuartzComposer入りのスクリプトバンドルを用意しておきましたので、ダウンロードしてお試しください。

–> Download qtc_disp_v6

オリジナルはControl+Command+Rで実行する必要がありましたが、本Scriptではその必要がありません。ちなみに、一般的なQuartzComposerのようにマウスでグリグリ回せるとかいうことはありません。パラメータを反映して静止画として表示されるだけです(Xcode上で作成したAppleScriptのGUIアプリケーションであれば、普通に回せます)。

macOS 10.14上で実行してみたところ、スクリプトエディタではCompositionが表示されませんでしたが、Script Debugger上で実行したかぎりでは実行されました。Framework宣言で足りないものがあるのでしょうか?

備考:QuartzComposerはmacOS 10.15でDeprecated扱いになりました

AppleScript名:QuartzComoserでグラフ表示てすと v6
— Created 2015-11-03 by Takaaki Naganoya
— Modified 2018-11-04 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "Quartz"
use framework "AppKit"

property NSColor : a reference to current application’s NSColor
property QCView : a reference to current application’s QCView
property NSString : a reference to current application’s NSString
property NSScreen : a reference to current application’s NSScreen
property NSWindow : a reference to current application’s NSWindow
property NSNumber : a reference to current application’s NSNumber
property NSPredicate : a reference to current application’s NSPredicate
property NSDictionary : a reference to current application’s NSDictionary
property NSMutableArray : a reference to current application’s NSMutableArray
property NSWindowController : a reference to current application’s NSWindowController
property NSMutableDictionary : a reference to current application’s NSMutableDictionary
property NSTitledWindowMask : a reference to current application’s NSTitledWindowMask
property NSWindowCloseButton : a reference to current application’s NSWindowCloseButton
property NSNormalWindowLevel : a reference to current application’s NSNormalWindowLevel
property NSBackingStoreBuffered : a reference to current application’s NSBackingStoreBuffered

set chartData to NSMutableArray’s new()
chartData’s addObject:(my recWithLabels:{"label", "value"} andValues:{"練馬区", 3})
chartData’s addObject:(my recWithLabels:{"label", "value"} andValues:{"青梅市", 1})
chartData’s addObject:(my recWithLabels:{"label", "value"} andValues:{"中野区", 2})

my performSelectorOnMainThread:"dispQuartzComposerWindow:" withObject:(chartData) waitUntilDone:true

on dispQuartzComposerWindow:chartData
  –上記データの最大値を求める
  
set aMaxRec to chartData’s filteredArrayUsingPredicate:(NSPredicate’s predicateWithFormat_("SELF.value == %@.@max.value", chartData))
  
set aMax to value of aMaxRec
  
set aMaxVal to (first item of aMax) as integer
  
  
–Scalingの最大値を求める
  
if aMaxVal ≥ 10 then
    set aScaleMax to (10 div aMaxVal)
    
set aScaleMin to aScaleMax div 10
  else
    set aScaleMax to (10 / aMaxVal)
    
set aScaleMin to 1
  end if
  
  
try
    set aPath to path to resource "Chart.qtz"
  on error
    return
  end try
  
  
set qtPath to NSString’s stringWithString:(POSIX path of aPath)
  
  
set aView to QCView’s alloc()’s init()
  
set qtRes to (aView’s loadCompositionFromFile:qtPath)
  
  
aView’s setValue:chartData forInputKey:"Data"
  
aView’s setValue:(NSNumber’s numberWithFloat:(0.5)) forInputKey:"Scale"
  
aView’s setValue:(NSNumber’s numberWithFloat:(0.2)) forInputKey:"Spacing"
  
aView’s setAutostartsRendering:true
  
  
set maXFrameRate to aView’s maxRenderingFrameRate()
  
  (
aView’s setValue:(NSNumber’s numberWithFloat:aScaleMax / 10) forInputKey:"Scale")
  
  
set aWin to (my makeWinWithView(aView, 800, 600, "AppleScript Composition Test"))
  
  
set wController to NSWindowController’s alloc()
  
wController’s initWithWindow:aWin
  
aWin’s makeFirstResponder:aView
  
wController’s showWindow:me
  
  
aWin’s makeKeyAndOrderFront:me
  
  
delay 5
  
  
my closeWin:aWin
  
aView’s stopRendering() –レンダリング停止
  
end dispQuartzComposerWindow:

–make Window for Display
on makeWinWithView(aView, aWinWidth, aWinHeight, aTitle)
  set aScreen to NSScreen’s mainScreen()
  
set aFrame to {{0, 0}, {aWinWidth, aWinHeight}}
  
  
set aBacking to NSTitledWindowMask
  
  
set aDefer to NSBackingStoreBuffered
  
  
— Window
  
set aWin to NSWindow’s alloc()
  (
aWin’s initWithContentRect:aFrame styleMask:aBacking backing:aDefer defer:false screen:aScreen)
  
aWin’s setBackgroundColor:(NSColor’s whiteColor())
  
  
aWin’s setTitle:aTitle
  
aWin’s setDelegate:me
  
aWin’s setDisplaysWhenScreenProfileChanges:true
  
aWin’s setHasShadow:true
  
aWin’s setIgnoresMouseEvents:false
  
aWin’s setLevel:(NSNormalWindowLevel)
  
aWin’s setOpaque:false
  
aWin’s setReleasedWhenClosed:true
  
aWin’s |center|()
  
aWin’s makeKeyAndOrderFront:(me)
  
–aWin’s movableByWindowBackground:true
  
  
— Set Custom View
  
aWin’s setContentView:aView
  
  
–Set Close Button  
  
set closeButton to NSWindow’s standardWindowButton:(NSWindowCloseButton) forStyleMask:(NSTitledWindowMask)
  
  
return aWin
end makeWinWithView

–close win
on closeWin:aWindow
  repeat with n from 10 to 1 by -1
    (aWindow’s setAlphaValue:n / 10)
    
delay 0.01
  end repeat
  
aWindow’s |close|()
end closeWin:

on recWithLabels:theKeys andValues:theValues
  return (NSDictionary’s dictionaryWithObjects:theValues forKeys:theKeys) as record
end recWithLabels:andValues:

★Click Here to Open This Script 

Posted in GUI Image | Tagged 10.11savvy 10.12savvy 10.13savvy 10.14savvy NSColor NSDictionary NSMutableArray NSMutableDictionary NSNumber NSPredicate NSScreen NSString NSWindow NSWindowController QCView | Leave a comment

テキストをMarkdown形式として解釈してHTMLを出力

Posted on 11月 3, 2018 by Takaaki Naganoya

オープンソースのフレームワーク「MMMarkdown」を利用してMarkdownのテキストをHTMLに変換して出力するAppleScriptです。

ただし、解釈できるMarkdownタグは限定的で、表などは解釈できません。

–> Download MMMarkdown.framework (To ~/Library/Frameworks/)

AppleScript名:テキストをMarkdown形式と解釈してHTMLを出力
— Created 2016-05-12 by Takaaki Naganoya
— 2016 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "MMMarkdown" –https://github.com/mdiep/MMMarkdown

set markdown to "# Example
What a library!"

set htmlString to (current application’s MMMarkdown’s HTMLStringWithMarkdown:markdown |error|:(missing value)) as string
–>
(*
"<h1>Example</h1>
<p>What a library!</p>
"
*)

★Click Here to Open This Script 

Posted in Markdown Text | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

ftpKitのじっけん ftpサーバーからファイル一覧を取得

Posted on 11月 3, 2018 by Takaaki Naganoya

オープンソースのFTPManagerをフレームワーク化したftpKitを利用して、指定サーバー上の指定ディレクトリ内のファイル一覧を取得するAppleScriptです。

sftp接続が必要な場合にはTransmitをAppleScriptからコントロールすることになるわけですが、セキュリティ的にあまり問題にならない用途であればFTP経由でファイル転送することもあるでしょう。

AppleScript名:ftpKitでファイル一覧を取得
— Created 2016-03-01by Takaaki Naganoya
— 2016 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "ftpKit" –https://github.com/nkreipke/FTPManager

set serverURL to "ftp://www.piyocast.com/xxxxx/public_html/private"
set serverUser to "xxxxx@piyocast.com"
set serverPassword to text returned of (display dialog "Input FTP Password" default answer "" with hidden answer)

set aFtpManager to current application’s FTPManager’s alloc()’s init()
set successF to false

set srv to current application’s FMServer’s serverWithDestination:serverURL username:serverUser |password|:serverPassword
srv’s setPort:21

set aResList to aFtpManager’s contentsOfServer:srv

set fileNameList to {}
set fileCount to aResList’s |count|()

repeat with i from 0 to (fileCount – 1)
  set anItem to (aResList’s objectAtIndex:i)
  
  
set aFileName to (anItem’s valueForKeyPath:"kCFFTPResourceName") as string
  
set the end of fileNameList to aFileName
end repeat

fileNameList
–>  {".", "..", "xls1a.png", "xls3.png"}

★Click Here to Open This Script 

Posted in file Network | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

度量衡の変換

Posted on 11月 3, 2018 by Takaaki Naganoya

オープンソースの「DDUnitConverter」(By Dave DeLong)を用いて、度量衡(measurement unit)の変換を行うAppleScriptです。AppleScriptから呼び出すために、DDUnitConverterをフレームワーク化した「ddUnitConversionKit」を作成しています。

もともと、AppleScriptには内蔵の度量衡変換機能があり、

AppleScript名:インチからセンチへの変換
set a to 1
set a to a as inches
–> inches 1.0

set b to a as centimeters
–> centimeters 2.54

set c to a as meters
–> meters 0.0254

set d to a as kilometers
–> kilometers 2.54E-5

★Click Here to Open This Script 

とか、

AppleScript名:液体の容積の単位変換
–液体の容積の単位変換
set a to 10 as liters
–> liters 10.0

set b to a as gallons
–> gallons 2.641720372842

set c to a as quarts
–> quarts 10.566881491367

★Click Here to Open This Script 

ぐらいは簡単にできます。AppleScriptがサポートしている度量衡は、長さ、重さ、温度、液体の容積です。

ただ、mmの下のμmとか、オングストロームとか、そういう単位には対応していませんし、重量でいえばKgに対応していてもt(トン)の単位はサポートしていなかったりと、日常的な度量衡の単位の世界でも不十分な感じが否めません(数値の有効桁数が10桁と小さいことも影響?)。

Cocoaの世界で度量衡変換機能について調べてみたところ、km→m→cm→mmといった変換はしてくれるものの、他の単位への変換は行ってくれていなかったりして、標準機能だけではいまひとつな印象です。

AppleScript名:NSLengthFormatterのじっけん
— Created 2015-11-18 by Takaaki Naganoya
— 2015 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
–http://dev.classmethod.jp/references/ios8-new-formatter/

set aLengthFormatter to current application’s NSLengthFormatter’s alloc()’s init()
set aMeters to 5000
set aRes to (aLengthFormatter’s stringFromMeters:aMeters) as text
–>  "5 km"
set bRes to (aLengthFormatter’s stringFromMeters:500) as text
–>  "500 m"
set cRes to (aLengthFormatter’s stringFromMeters:0.5) as text
–>  "50 cm"
set dRes to (aLengthFormatter’s stringFromMeters:0.005) as text
–>  "5 mm"
set eRes to (aLengthFormatter’s stringFromMeters:("0.000005" as real)) as text
–>  "0.005 mm"

set res2 to aLengthFormatter’s getObjectValue:(missing value) forString:aRes errorDescription:(missing value)
–>  false

set res3 to (aLengthFormatter’s stringFromValue:aMeters unit:(current application’s NSLengthFormatterUnitMillimeter)) as text
–>  "5,000 mm"
set res4 to (aLengthFormatter’s stringFromValue:aMeters unit:(current application’s NSLengthFormatterUnitCentimeter)) as text
–>  "5,000 cm"
set res5 to (aLengthFormatter’s stringFromValue:aMeters unit:(current application’s NSLengthFormatterUnitMeter)) as text
–>  "5,000 m"
set res6 to (aLengthFormatter’s stringFromValue:aMeters unit:(current application’s NSLengthFormatterUnitKilometer)) as text
–>  "5,000 km"
set res7 to (aLengthFormatter’s stringFromValue:aMeters unit:(current application’s NSLengthFormatterUnitInch)) as text
–>  "5,000 in"
set res8 to (aLengthFormatter’s stringFromValue:aMeters unit:(current application’s NSLengthFormatterUnitFoot)) as text
–>  "5,000 ft"
set res9 to (aLengthFormatter’s stringFromValue:aMeters unit:(current application’s NSLengthFormatterUnitYard)) as text
–>  "5,000 yd"
set res10 to (aLengthFormatter’s stringFromValue:aMeters unit:(current application’s NSLengthFormatterUnitMile)) as text
–>  "5,000 mi"

★Click Here to Open This Script 

AppleScript名:NSMassFormatterのじっけん
— Created 2015-11-18 by Takaaki Naganoya
— 2015 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
–http://dev.classmethod.jp/references/ios8-new-formatter/

set aMasFormatter to current application’s NSMassFormatter’s alloc()’s init()
set aKilloGrams to 60.0
set aRes to (aMasFormatter’s stringFromKilograms:aKilloGrams) as text
–>  "60 kg"
set a2Res to (aMasFormatter’s stringFromKilograms:(0.5)) as text
–>  "500 g"
set a3Res to (aMasFormatter’s stringFromKilograms:(5000000)) as text
–>  "5,000,000 kg"
set a4Res to (aMasFormatter’s stringFromKilograms:("0.0005" as real)) as text
–>  "0.5 g"

set bRes to (aMasFormatter’s stringFromValue:aKilloGrams unit:(current application’s NSMassFormatterUnitGram)) as text
–>  "60 g"
set cRes to (aMasFormatter’s stringFromValue:aKilloGrams unit:(current application’s NSMassFormatterUnitKilogram)) as text
–>  "60 kg"
set dRes to (aMasFormatter’s stringFromValue:aKilloGrams unit:(current application’s NSMassFormatterUnitOunce)) as text
–>  "60 oz"
set eRes to (aMasFormatter’s stringFromValue:aKilloGrams unit:(current application’s NSMassFormatterUnitPound)) as text
–>  "60 lb"
set fRes to (aMasFormatter’s stringFromValue:aKilloGrams unit:(current application’s NSMassFormatterUnitStone)) as text
–>  "60 st"

set gRes to (aMasFormatter’s unitStringFromValue:aKilloGrams unit:(current application’s NSMassFormatterUnitGram)) as text
–>  "g"
set hRes to (aMasFormatter’s unitStringFromValue:aKilloGrams unit:(current application’s NSMassFormatterUnitKilogram)) as text
–>  "kg"
set iRes to (aMasFormatter’s unitStringFromValue:aKilloGrams unit:(current application’s NSMassFormatterUnitOunce)) as text
–>  "oz"
set jRes to (aMasFormatter’s unitStringFromValue:aKilloGrams unit:(current application’s NSMassFormatterUnitPound)) as text
–>  "lb"
set kRes to (aMasFormatter’s unitStringFromValue:aKilloGrams unit:(current application’s NSMassFormatterUnitStone)) as text
–>  "st"

set res01 to aMasFormatter’s getObjectValue:(missing value) forString:fRes errorDescription:(missing value)
–>  false

set res02 to (aMasFormatter’s stringFromKilograms:80) as text
–>  "80 kg"

set res03 to aMasFormatter’s unitStyle()
–>  2 = NSFormattingUnitStyleMedium

★Click Here to Open This Script 

そこで、冒頭に紹介したようにDDUnitConverterを導入してみたわけですが、これはこれで問題がないわけでもありません。本来、通貨同士の変換をサポートしており、通貨レートの更新機能を持っているのですが、実際に呼び出してみると更新されていない雰囲気が濃厚です(呼び出し方を間違っているのか?)。

なので、「通貨レート以外」の度量衡変換にのみ用いるのが安全な使い方なのかもしれない、というところです。

例によって、OS X 10.10以降用にビルドしたバイナリを用意しておきましたので、興味のある方はアーカイブを展開したあとで、~/Library/Frameworksに入れておためしください。

–> Download ddUnitConversionKit.framework(To ~/Library/Frameworks/)

AppleScript名:DDUnitConverterのじっけん1
— Created 2015-11-19 by Takaaki Naganoya
— 2015 Piyomaru Software
use AppleScript version “2.4”
use scripting additions
use framework “Foundation”
use framework “ddUnitConversionKit” –davedelong/DDUnitConverter
–https://github.com/davedelong/DDUnitConverter

–enums in DDVelocityUnitConverter.h
property DDVelocityUnitCentimetersPerHour : 0
property DDVelocityUnitCentimetersPerMinute : 1
property DDVelocityUnitCentimetersPerSecond : 2
property DDVelocityUnitFeetPerHour : 3
property DDVelocityUnitFeetPerMinute : 4
property DDVelocityUnitFeetPerSecond : 5
property DDVelocityUnitInchesPerHour : 6
property DDVelocityUnitInchesPerMinute : 7
property DDVelocityUnitInchesPerSecond : 8
property DDVelocityUnitKilometersPerHour : 9
property DDVelocityUnitKilometersPerMinute : 10
property DDVelocityUnitKilometersPerSecond : 11
property DDVelocityUnitKnots : 12
property DDVelocityUnitLight : 13
property DDVelocityUnitMach : 14
property DDVelocityUnitMetersPerHour : 15
property DDVelocityUnitMetersPerMinute : 16
property DDVelocityUnitMetersPerSecond : 17
property DDVelocityUnitMilesPerHour : 18
property DDVelocityUnitMilesPerMinute : 19
property DDVelocityUnitMilesPerSecond : 20
property DDVelocityUnitFurlongsPerFortnight : 21

–時速100kmを秒速kmに変換
set aVal to ((current application’s DDUnitConverter’s velocityUnitConverter())’s convertNumber:100 fromUnit:(DDVelocityUnitKilometersPerHour) toUnit:(DDVelocityUnitKilometersPerSecond)) as real
–>  0.027777777778

★Click Here to Open This Script 

AppleScript名:DDCurrencyUnitConverterのじっけん
— Created 2015-11-19 by Takaaki Naganoya
— 2015 Piyomaru Software
use AppleScript version “2.4”
use scripting additions
use framework “Foundation”
use framework “ddUnitConversionKit” –davedelong/DDUnitConverter
–https://github.com/davedelong/DDUnitConverter

–enums in DDCurrencyUnitConverter.h
property DDCurrencyUnitEuro : 0
property DDCurrencyUnitJapaneseYen : 1
property DDCurrencyUnitUKPoundSterling : 2
property DDCurrencyUnitUSDollar : 3
property DDCurrencyUnitAlgerianDinar : 4
property DDCurrencyUnitArgentinePeso : 5
property DDCurrencyUnitAustralianDollar : 6
property DDCurrencyUnitBahrainDinar : 7
property DDCurrencyUnitBotswanaPula : 8
property DDCurrencyUnitBrazilianReal : 9
property DDCurrencyUnitBruneiDollar : 10
property DDCurrencyUnitCanadianDollar : 11
property DDCurrencyUnitChileanPeso : 12
property DDCurrencyUnitChineseYuan : 13
property DDCurrencyUnitColombianPeso : 14
property DDCurrencyUnitCzechKoruna : 15
property DDCurrencyUnitDanishKrone : 16
property DDCurrencyUnitHungarianForint : 17
property DDCurrencyUnitIcelandicKrona : 18
property DDCurrencyUnitIndianRupee : 19
property DDCurrencyUnitIndonesianRupiah : 20
property DDCurrencyUnitIranianRial : 21
property DDCurrencyUnitIsraeliNewSheqel : 22
property DDCurrencyUnitKazakhstaniTenge : 23
property DDCurrencyUnitKoreanWon : 24
property DDCurrencyUnitKuwaitiDinar : 25
property DDCurrencyUnitLibyanDinar : 26
property DDCurrencyUnitMalaysianRinggit : 27
property DDCurrencyUnitMauritianRupee : 28
property DDCurrencyUnitMexicanPeso : 29
property DDCurrencyUnitNepaleseRupee : 30
property DDCurrencyUnitNewZealandDollar : 31
property DDCurrencyUnitNorwegianKrone : 32
property DDCurrencyUnitRialOmani : 33
property DDCurrencyUnitPakistaniRupee : 34
property DDCurrencyUnitNuevoSol : 35
property DDCurrencyUnitPhilippinePeso : 36
property DDCurrencyUnitPolishZloty : 37
property DDCurrencyUnitQatarRiyal : 38
property DDCurrencyUnitRussianRuble : 39
property DDCurrencyUnitSaudiArabianRiyal : 40
property DDCurrencyUnitSingaporeDollar : 41
property DDCurrencyUnitSouthAfricanRand : 42
property DDCurrencyUnitSriLankaRupee : 43
property DDCurrencyUnitSwedishKrona : 44
property DDCurrencyUnitSwissFranc : 45
property DDCurrencyUnitThaiBaht : 46
property DDCurrencyUnitTrinidadAndTobagoDollar : 47
property DDCurrencyUnitTunisianDinar : 48
property DDCurrencyUnitUAEDirham : 49
property DDCurrencyUnitPesoUruguayo : 50
property DDCurrencyUnitBolivarFuerte : 51
property DDCurrencyUnitSDR : 52

–最初に通貨レートの更新を行う必要があるが、実行しても変わらないのはなぜ????
set aConv to current application’s DDUnitConverter’s currencyUnitConverter()
aConv’s refreshExchangeRates()
set aVal to (aConv’s convertNumber:100 fromUnit:(DDCurrencyUnitUSDollar) toUnit:(DDCurrencyUnitJapaneseYen))
–>  (NSNumber) 1.006839721743

★Click Here to Open This Script 

Posted in Number | Tagged 10.11savvy 10.12savvy 10.13savvy NSLengthFormatter NSMassFormatter | Leave a comment

シリアルコードの生成と検証

Posted on 11月 3, 2018 by Takaaki Naganoya

オープンソースのフレームワーク「SerialKeyGenerator」を用いてシリアルコードを生成、検証するAppleScriptです。

シリアルコードについて

シリアルコードは、日本では「レジストコード」「プロダクトコード」などと呼ばれるもので、ソフトウェアの販売時にこのコードを発行し、ソフトウェアのシリアルコード入力ダイアログに入力してもらうことで、完全版として機能させるというものです。

Mac App StoreではApple IDとひもづけることでシリアルコードを使用しないソフトウェア販売とライセンシングを行なっていますが、Mac App Store外で販売する場合にはシリアルコードのことを考える必要が出てきます。

コードの文字数を増やすと、仮にキーボードから入力する場合の難易度が上がってしまいます。適度な長さの文字列になることが望ましいところです。

シリアルコードが仮に流出した場合に備え、どの購入者のコードが流出したかを特定する必要があります。そのため、シリアルコードにはその名のとおり、購入者の番号を含めてあるのが普通です。

SerialKeyGeneratorの使い方について

SerialKeyGeneratorでは、シークレットキーワード、ユーザー番号をもとにシリアルコードが生成されます。日時を考慮してシリアルコードを計算するため、同じシリアルコードを生成させても日時が変われば結果は異なります。

ただ、おおもとのシークレットキーワードが判明してしまうと、第三者がシリアルコードを勝手に発行してソフトウェアの不正使用ができてしまうため、アプリケーション内に格納するシークレットキーワードは文字ダンプされても判明しないようにしておくのが普通です。

–> Download serialKeyGenKit.framework(To ~/Library/Frameworks/)

AppleScript名:SerialKeyGeneratorサンプル1
— Created 2015-10-24 by Takaaki Naganoya
— 2015 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "serialKeyGenKit" –https://github.com/danielvy/SerialKeyGenerator

–Generate Serial Code with secret Keyword
set aGen to current application’s SerialKeyGenerator’s alloc()’s initWithSecret:"Piyomaru"
–>  (SerialKeyGenerator) <SerialKeyGenerator: 0x7f8b5b5fa200>

set aList to {}
repeat with i from 1 to 10
  set aRes to (aGen’s generateSerialWithSequence:i |data|:i)
  
set the end of aList to (aRes as text)
end repeat

aList
–>  {​​​​​"1CHH8-BJY89-TR9Z9-AKSTL-70JZF", ​​​​​"4KXCF-LS6P5-7BKYN-CUMPY-NM072", ​​​​​"41GO2-OGZ3T-83YP9-2LS4J-9W3MI", ​​​​​"CA3WV-C7FU7-PSPJ3-LNGT7-N6AJT", ​​​​​"3OG0B-MCFUM-7YKHT-EE533-LNJEJ", ​​​​​"4SKWQ-9G8XE-ZCE6K-APSAL-R0T8S", ​​​​​"CTEZT-H4AQQ-BM15H-FH2DG-P7K7O", ​​​​​"4BZ1X-2OHKF-5FWND-7SZVA-EBR89", ​​​​​"BDKRI-9JU7T-G6N20-YPU9K-6FXQW", ​​​​​"9EWW5-O3FMV-SDEZA-77JZE-OY8FL"​​​}

–Decode Serial with secret Keyword
set rList to {}
set bGen to current application’s SerialKeyGenerator’s alloc()’s initWithSecret:"Piyomaru"
–> (SerialKeyGenerator) <SerialKeyGenerator: 0x7fb6992b8400>

repeat with i in aList
  set bRes to (bGen’s decodeSerial:(contents of i))
  
  
set aDate to bRes’s |date| as date
  
set aSeq to bRes’s sequence as integer
  
set aData to bRes’s |data| as integer
  
  
set the end of rList to {aData, aSeq, aDate}
end repeat
return rList
–> {{1, 1, date "2018年11月3日土曜日 16:44:57"}, {2, 2, date "2018年11月3日土曜日 16:44:57"}, {3, 3, date "2018年11月3日土曜日 16:44:57"}, {4, 4, date "2018年11月3日土曜日 16:44:57"}, {5, 5, date "2018年11月3日土曜日 16:44:57"}, {6, 6, date "2018年11月3日土曜日 16:44:57"}, {7, 7, date "2018年11月3日土曜日 16:44:57"}, {8, 8, date "2018年11月3日土曜日 16:44:57"}, {9, 9, date "2018年11月3日土曜日 16:44:57"}, {10, 10, date "2018年11月3日土曜日 16:44:57"}}

★Click Here to Open This Script 

Posted in How To | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

Excelデータを組み立てて書き出し(フォント指定、カラー指定)

Posted on 11月 3, 2018 by Takaaki Naganoya

オープンソースのフレームワーク「JXLS」を用いてExcelデータを組み立てるAppleScriptです。

フォント名と色を指定してみました。実際に案件で使用したことがないので、徹底的に活用した………という経験がないので、いまのところ何か風景画像をExcel書類に変換して「実はExcelで作りました」とかフカすぐらいしか用途がなさそうです。

–> Download JXLS(To ~/Library/Frameworks/)

AppleScript名:ASOCでExcelファイル生成テスト v2
— Created 2015-10-08 by Takaaki Naganoya
— 2015 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "JXLS" –https://github.com/JanX2/JXLS

set aFile to POSIX path of (choose file name)
set filePath to current application’s NSString’s stringWithString:aFile

set workBook to current application’s JXLSWorkBook’s new()
set workSheet to workBook’s workSheetWithName:"ぴよぴよシート"
workSheet’s setWidth:1000 forColumn:0 defaultFormat:(missing value)

repeat with i from 0 to 64
  set aCell to (workSheet’s setCellAtRow:i column:0 toString:(current application’s NSString’s stringWithString:("ぴよまる " & (i as text))))
  (
aCell’s setFontName:"HiraKakuStd-W8")
  (
aCell’s setFontHeight:320) –this is point * 20
  (
aCell’s setFontColorIndex:i)
  (
aCell’s setForegroundFillColorIndex:13)
end repeat

workBook’s writeToFile:filePath

★Click Here to Open This Script 

Posted in How To | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

Excelデータを組み立てて書き出し

Posted on 11月 3, 2018 by Takaaki Naganoya

オープンソースの「JXLS.framework」を用いて指定のExcelデータを組み立てて書き出すAppleScriptです。

アプリケーションにメッセージを送ってアプリケーションに仕事をしてもらうのがAppleScriptの流儀ですが、macOS 10.10以降でCocoaの機能が呼べるようになったため、こうしたオープンソースのフレームワークを呼び出して処理できるようになりました。

AppleScriptが自前で行なっていないことには変わらないのですが、Excelデータを(Excelなしで)組み立てられるわけで、出力データとしてExcel書類が求められる用途において、Excelなしで処理が行えます(開発中はExcelでどのように表示されるか確認する必要があるので、開発中は必要です)。

また、本物のExcelをコントロールする方法ではできなかった「並列処理で大量にデータを作成する」という処理も可能になるわけでけっこうなことです(ただ、そういう要求をされたことは皆無なのですが、、、、)。

–> Download JXLS(To ~/Library/Frameworks/)

AppleScript名:ASOCでExcelファイル生成テスト
— Created 2015-10-08 by Takaaki Naganoya
— 2015 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "JXLS" –https://github.com/JanX2/JXLS

set aFile to POSIX path of (choose file name)
set filePath to current application’s NSString’s stringWithString:aFile

set workBook to current application’s JXLSWorkBook’s new()

set workSheet to workBook’s workSheetWithName:"ぴよぴよシート"
workSheet’s setWidth:1000 forColumn:0 defaultFormat:(missing value)

repeat with i from 0 to 10
  set aCell to (workSheet’s setCellAtRow:i column:0 toString:(current application’s NSString’s stringWithFormat_("ぴよまる %@", i + 1)))
  (
aCell’s setHorizontalAlignment:1) —-HALIGN_LEFT
  (
aCell’s setIndentation:(0 + i)) —– INDENT_0
end repeat

workBook’s writeToFile:filePath

★Click Here to Open This Script 

Posted in Release | Tagged 10.11savvy 10.12savvy 10.13savvy NSString | Leave a comment

ASOCでXML-RPCのテスト v3

Posted on 11月 3, 2018 by Takaaki Naganoya

オープンソースのXMLRPC.frameworkを用いてXMLRPCを実行するAppleScriptです。

XMLRPCといえば、WordPressか郵便専門ネットかというほど用途が限定されていますが、本Blog(Powered By WordPress)の年初の再構築など、使えないと大変な思いをすることがあるので、定期的に調査しています。

初回掲載時は郵便専門ネットのXMLRPCはバージョン番号を”15.09a”と返してきましたが、再掲載時に実行してみたら”18.10a”を返してきました。

–> Download XMLRPC.framework (To ~/Library/Frameworks/)

AppleScript名:ASOCでXML-RPCのテスト v3
— Created 2015-10-06 by Takaaki Naganoya
— 2015 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"
use framework "XMLRPC"
–XMLRPC.framework
–https://cocoapods.org/pods/xmlrpc
–Cocoa XML-RPC Framework © 2011 Divisible by Zero
–v2.3.4

set aRes to (callXMLRPC("http://yubin.senmon.net/service/xmlrpc/", "yubin.getMaxFetchCount", missing value)) as integer
–>  100

set bRes to (callXMLRPC("http://yubin.senmon.net/service/xmlrpc/", "yubin.getVersion", missing value)) as text
–> "15.09a"

on callXMLRPC(paramURL, aMethod, aParamList)
  
  
set aURL to current application’s |NSURL|’s URLWithString:paramURL
  
set aReq to current application’s XMLRPCRequest’s alloc()’s initWithURL:aURL
  
aReq’s setMethod:aMethod withParameter:aParamList
  
set aRes to current application’s XMLRPCConnection’s sendSynchronousXMLRPCRequest:aReq |error|:(missing value)
  
  
set errF to (aRes’s isFault()) as boolean
  
  
if errF = true then
    set xmlRPCres to faultCode of aRes
    
–set xmlRPCbody to faultString of aRes
  else
    set xmlRPCres to aRes’s object()
    
–set xmlRPCbody to aRes’s body()
  end if
  
  
return xmlRPCres
  
end callXMLRPC

★Click Here to Open This Script 

Posted in XML-RPC | Tagged 10.11savvy 10.12savvy 10.13savvy | Leave a comment

Post navigation

  • Older posts
  • Newer posts

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

Google Search

Popular posts

  • 開発機としてM2 Mac miniが来たのでガチレビュー
  • macOS 15, Sequoia
  • 指定のWordファイルをPDFに書き出す
  • Pages本執筆中に、2つの書類モード切り替えに気がついた
  • Numbersで選択範囲のセルの前後の空白を削除
  • メキシカンハットの描画
  • Pixelmator Pro v3.6.4でAppleScriptからの操作時の挙動に違和感が
  • AdobeがInDesign v19.4からPOSIX pathを採用
  • AppleScriptによる並列処理
  • Safariで「プロファイル」機能を使うとAppleScriptの処理に影響
  • macOS 14.xでScript Menuの実行速度が大幅に下がるバグ
  • AppleScript入門③AppleScriptを使った「自動化」とは?
  • macOS 15でも変化したText to Speech環境
  • Keynote/Pagesで選択中の表カラムの幅を均等割
  • デフォルトインストールされたフォント名を取得するAppleScript
  • macOS 15 リモートApple Eventsにバグ?
  • AppleScript入門① AppleScriptってなんだろう?
  • macOS 14で変更になったOSバージョン取得APIの返り値
  • Script Debuggerの開発と販売が2025年に終了
  • Keynoteで2階層のスライドのタイトルをまとめてテキスト化

Tags

10.11savvy (1101) 10.12savvy (1242) 10.13savvy (1391) 10.14savvy (587) 10.15savvy (438) 11.0savvy (283) 12.0savvy (212) 13.0savvy (194) 14.0savvy (147) 15.0savvy (132) CotEditor (66) Finder (51) iTunes (19) Keynote (117) NSAlert (61) NSArray (51) NSBitmapImageRep (20) NSBundle (20) NSButton (34) NSColor (53) NSDictionary (28) NSFileManager (23) NSFont (21) NSImage (41) NSJSONSerialization (21) NSMutableArray (63) NSMutableDictionary (22) NSPredicate (36) NSRunningApplication (56) NSScreen (30) NSScrollView (22) NSString (119) NSURL (98) NSURLRequest (23) NSUTF8StringEncoding (30) NSView (33) NSWorkspace (20) Numbers (76) Pages (55) Safari (44) Script Editor (27) WKUserContentController (21) WKUserScript (20) WKWebView (23) WKWebViewConfiguration (22)

カテゴリー

  • 2D Bin Packing
  • 3D
  • AirDrop
  • AirPlay
  • Animation
  • AppleScript Application on Xcode
  • Beginner
  • Benchmark
  • beta
  • Bluetooth
  • Books
  • boolean
  • bounds
  • Bug
  • Calendar
  • call by reference
  • check sum
  • Clipboard
  • Cocoa-AppleScript Applet
  • Code Sign
  • Color
  • Custom Class
  • date
  • dialog
  • diff
  • drive
  • Droplet
  • 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
  • Localize
  • Machine Learning
  • Map
  • Markdown
  • Menu
  • Metadata
  • MIDI
  • MIME
  • Natural Language Processing
  • Network
  • news
  • Noification
  • Notarization
  • Number
  • Object control
  • OCR
  • OSA
  • parallel processing
  • PDF
  • Peripheral
  • PRODUCTS
  • QR Code
  • Raw AppleEvent Code
  • Record
  • rectangle
  • 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)
  • 未分類

アーカイブ

  • 2025年5月
  • 2025年4月
  • 2025年3月
  • 2025年2月
  • 2025年1月
  • 2024年12月
  • 2024年11月
  • 2024年10月
  • 2024年9月
  • 2024年8月
  • 2024年7月
  • 2024年6月
  • 2024年5月
  • 2024年4月
  • 2024年3月
  • 2024年2月
  • 2024年1月
  • 2023年12月
  • 2023年11月
  • 2023年10月
  • 2023年9月
  • 2023年8月
  • 2023年7月
  • 2023年6月
  • 2023年5月
  • 2023年4月
  • 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