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

カテゴリー: Natural Language Processing

NaturalLanguage.frameworkを用いて日本語テキストの形態素解析を行う

Posted on 4月 10 by Takaaki Naganoya

NSLinguisticTaggerの後継であるNaturalLanguage(NLTokenizer)を用いて、日本語テキストの形態素解析を行なってみました。

この手の頭を使わないプログラミングだとChatGPTに丸投げすれば、(デバッグ作業が必要な)AppleScriptのコードが出てくるので、走らせて直して……で、15分ほどでしょうか。

NLTokenizerの処理結果は、間違ってはいないものの、相変わらず固有名詞を無視しまくるので、実用レベルにあるとはいえません。自分でAppleScriptで書いた簡易日本語パーサー「easyJParse」と処理結果が変わらないので、頑張ってNLTokenizerを使う意義はほとんどないといえます(日本語を処理すると品詞情報を返して来ないので余計に……)。

AppleScript名:NaturalLanguage.frameworkを用いて日本語テキストの形態素解析を行う.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2025/04/10
—
–  Copyright © 2025 Piyomaru Software, All Rights Reserved
—

use AppleScript
use framework "Foundation"
use framework "NaturalLanguage"
use scripting additions

set inputText to current application’s NSMutableString’s stringWithString:"私の名前は長野谷です。"

— NLTokenizerのインスタンスを作成し、単語単位で設定
set tokenizer to current application’s NLTokenizer’s alloc()’s initWithUnit:(current application’s NLTokenUnitWord)
tokenizer’s setString:inputText
tokenizer’s setLanguage:(current application’s NLLanguageJapanese)

— 解析範囲の取得
set textLength to (inputText’s |length|()) as integer
set theRange to current application’s NSMakeRange(0, textLength)

— トークンを格納するリスト
set tokenList to {}

— トークン範囲を1つずつ取得して、文字列を抽出
set currentIndex to tokenizer’s tokenRangeAtIndex:0

repeat while (currentIndex’s location < (textLength))
  set subStr to (inputText’s substringWithRange:currentIndex)
  
copy (subStr as string) to end of tokenList
  
  
— 次のトークン範囲へ進む
  
set nextIndex to (currentIndex’s location) + (currentIndex’s |length|())
  
if nextIndex ≥ textLength then exit repeat
  
set currentIndex to tokenizer’s tokenRangeAtIndex:nextIndex
end repeat

return tokenList
–> {"私", "の", "名前", "は", "長野", "谷", "です"}

★Click Here to Open This Script 

Posted in Natural Language Processing | Tagged 13.0savvy 14.0savvy 15.0savvy NLTokenizer | Leave a comment

指定言語でNLEmbeddingを処理できるかチェック_13_14_15

Posted on 12月 16, 2024 by Takaaki Naganoya

NaturalLanguage.frameworkのごくごく入門的なオブジェクト「NLEmbedding」を利用できるか、各言語でチェックを行ったところ、macOS 13、14で予想外の結果が返ってきた内容をmacOS 15で再確認してみました。

ラテン系言語を中心に中国語がサポートされているあたりがあまりにも特徴的なNaturalLanguage.framework。多くの機能を日本語で利用できないことは分かりきっていたのですが、macOS 14で対応言語が激減。このまま廃止されるのかと驚いていたのですが、macOS 15で復旧していました。

どうしてmacOS 14.x台で復旧していなかったのか。ひたすら不思議です。

AppleScript名:指定言語でNLEmbeddingを処理できるかチェック_13_14_15.scpt
—
–  Created by: Takaaki Naganoya
–  Created on: 2024/03/13
—
–  Copyright © 2024 Piyomaru Software, All Rights Reserved
—

use AppleScript version "2.8"
use framework "Foundation"
use framework "NaturalLanguage"
use scripting additions

–The result is on macOS 13.6.5 / 14.4 / 15.2
set aRes to testNLLanguage("NLLanguageEnglish") of me –> true–> true –true
set aRes to testNLLanguage("NLLanguageFrench") of me –> true–>false (macOS 14)—> true
set aRes to testNLLanguage("NLLanguageGerman") of me –> true–>false (macOS 14)–> true
set aRes to testNLLanguage("NLLanguageItalian") of me –> true–>false (macOS 14)–> true
set aRes to testNLLanguage("NLLanguagePortuguese") of me –> true–>false (macOS 14)–> true
set aRes to testNLLanguage("NLLanguageSimplifiedChinese") of me –> true–>false (macOS 14)–> true
set aRes to testNLLanguage("NLLanguageSpanish") of me –> true–>false (macOS 14)–> true

set aRes to testNLLanguage("NLLanguageUndetermined") of me –> true –>Natural Language framework doesn’t recognize(macOS 14).–> true
–macOS 14.7.2で再確認したところtrueに

set aRes to testNLLanguage("NLLanguageAmharic") of me –> false–> false–> false
set aRes to testNLLanguage("NLLanguageArabic") of me –> false–> false–> false
set aRes to testNLLanguage("NLLanguageArmenian") of me –> false–> false–> false
set aRes to testNLLanguage("NLLanguageBengali") of me –> false–> false–> false
set aRes to testNLLanguage("NLLanguageBulgarian") of me –> false–> false–> false
set aRes to testNLLanguage("NLLanguageBurmese") of me –> false–> false–> false
set aRes to testNLLanguage("NLLanguageCatalan") of me –> false–> false–> false
set aRes to testNLLanguage("NLLanguageCherokee") of me –> false–> false–> false
set aRes to testNLLanguage("NLLanguageCroatian") of me –> false–> false–> false
set aRes to testNLLanguage("NLLanguageCzech") of me –> false–> false–> false
set aRes to testNLLanguage("NLLanguageDanish") of me –> false–> false–> false
set aRes to testNLLanguage("NLLanguageDutch") of me –> false–> false–> false
set aRes to testNLLanguage("NLLanguageFinnish") of me –> false–> false–> false
set aRes to testNLLanguage("NLLanguageGeorgian") of me –> false–> false–> false
set aRes to testNLLanguage("NLLanguageGreek") of me –> false–> false–> false
set aRes to testNLLanguage("NLLanguageGujarati") of me –> false–> false–> false
set aRes to testNLLanguage("NLLanguageHebrew") of me –> false–> false–> false
set aRes to testNLLanguage("NLLanguageHindi") of me –> false–> false–> false
set aRes to testNLLanguage("NLLanguageHungarian") of me –> false–> false–> false
set aRes to testNLLanguage("NLLanguageIcelandic") of me –> false–> false–> false
set aRes to testNLLanguage("NLLanguageIndonesian") of me –> false–> false–> false
set aRes to testNLLanguage("NLLanguageJapanese") of me –> false–> false–> false
set aRes to testNLLanguage("NLLanguageKannada") of me –> false–> false–> false
set aRes to testNLLanguage("NLLanguageKazakh") of me –> false–> false–> false
set aRes to testNLLanguage("NLLanguageKhmer") of me –> false–> false–> false
set aRes to testNLLanguage("NLLanguageKorean") of me –> false–> false–> false
set aRes to testNLLanguage("NLLanguageLao") of me –> false–> false–> false
set aRes to testNLLanguage("NLLanguageMalay") of me –> false–> false–> false
set aRes to testNLLanguage("NLLanguageMalayalam") of me –> false–> false–> false
set aRes to testNLLanguage("NLLanguageMarathi") of me –> false–> false–> false
set aRes to testNLLanguage("NLLanguageMongolian") of me –> false–> false–> false
set aRes to testNLLanguage("NLLanguageNorwegian") of me –> false–> false–> false
set aRes to testNLLanguage("NLLanguageOriya") of me –> false–> false–> false
set aRes to testNLLanguage("NLLanguagePersian") of me –> false–> false–> false
set aRes to testNLLanguage("NLLanguagePolish") of me –> false–> false–> false
set aRes to testNLLanguage("NLLanguagePunjabi") of me –> false–> false–> false
set aRes to testNLLanguage("NLLanguageRomanian") of me –> false–> false–> false
set aRes to testNLLanguage("NLLanguageRussian") of me –> false–> false–> false
set aRes to testNLLanguage("NLLanguageSinhalese") of me –> false–> false–> false
set aRes to testNLLanguage("NLLanguageSlovak") of me –> false–> false–> false
set aRes to testNLLanguage("NLLanguageSwedish") of me –> false–> false–> false
set aRes to testNLLanguage("NLLanguageTamil") of me –> false–> false–> false
set aRes to testNLLanguage("NLLanguageTelugu") of me –> false–> false–> false
set aRes to testNLLanguage("NLLanguageThai") of me –> false–> false–> false
set aRes to testNLLanguage("NLLanguageTibetan") of me –> false–> false–> false
set aRes to testNLLanguage("NLLanguageTraditionalChinese") of me –> false–> false–> false
set aRes to testNLLanguage("NLLanguageTurkish") of me –> false–> false–> false
set aRes to testNLLanguage("NLLanguageUkrainian") of me –> false–> false–> false
set aRes to testNLLanguage("NLLanguageUrdu") of me –> false–> false–> false
set aRes to testNLLanguage("NLLanguageVietnamese") of me –> false–> false–> false

on testNLLanguage(aLangName)
  set aText to "use AppleScript
use framework \"Foundation\"
use framework \"NaturalLanguage\"

  set targLang to (current application’s " & aLangName & ")
  set aEmb to current application’s NLEmbedding’s wordEmbeddingForLanguage:(targLang)
  if aEmb = missing value then return false
  return true
  "

  
return run script aText
end testNLLanguage

★Click Here to Open This Script 

Posted in Natural Language Processing | Tagged 13.0savvy 14.0savvy 15.0savvy NLEmbedding | Leave a comment

Natural Language frameworkで英語で文章同士の距離を測る

Posted on 3月 13, 2024 by Takaaki Naganoya

NaturalLanguage.frameworkを用いて、英語の文章の意味的な距離を測るAppleScriptです。

単語単位の意味的な距離を計算する機能はいまひとつ使い道が限定される感じですが、文単位での意味的な距離の計算には期待してしまうところです。

実際にやってみました。

やってはみたものの、なにかピンと来ないというか、このAPIは1つの文章だけで距離を測るためのものなのか、それとも複数の文の塊で計算するものなのか、、、、

文章のかたまりでも計算できているようです。いろいろサンプル文章をひろってみて距離を計測してみましたが、「なんとなくそんな感じ」の結果が返ってくるだけです。

これは別にAppleが悪いということではなくて、自然言語処理ってこんな感じです。相対的な違いでしかないので、その結果をもって「いい」「わるい」という評価が行えるわけではなく「なんとなくこっち」という判断をするだけです。ただ、間違うこともあるので、その点をあらかじめ知っておくことが重要です。

AppleScript名:英語で文章同士の距離を測る_English.scpt
—
–  Created by: Takaaki Naganoya
–  Created on: 2024/03/13
—
–  Copyright © 2024 Piyomaru Software, All Rights Reserved
—

use AppleScript version "2.8" — Monterey (12.0) or later
use framework "Foundation"
use framework "NaturalLanguage"
use scripting additions

set targLang to current application’s NLLanguageEnglish
set aEmb to current application’s NLEmbedding’s sentenceEmbeddingForLanguage:(targLang)
if aEmb = missing value then return –NLLanguageJapanese is not available here in macOS 13

set aSent to "This is my book."
set bSent to "We the People of the United States, in Order to form a more perfect Union, establish Justice, insure domestic Tranquility, provide for the common defence, promote the general Welfare, and secure the Blessings of Liberty to ourselves and our Posterity, do ordain and establish this Constitution for the United States of America."
set cSent to "Thanks for updating Takaaki! You have almost completed updating AdRotate to version 5.12.9!
To complete the update click the button on the right. This may take a few seconds to complete!
For an overview of what has changed take a look at the development page and usually there is an article on the blog with more information as well."

set dSent to "He says that he like to read something with iPad."

set aDist to (aEmb’s distanceBetweenString:aSent andString:bSent distanceType:(current application’s NLDistanceTypeCosine))
–> 1.350924730301

set bDist to (aEmb’s distanceBetweenString:aSent andString:cSent distanceType:(current application’s NLDistanceTypeCosine))
–> 1.374191045761

set cDist to (aEmb’s distanceBetweenString:aSent andString:dSent distanceType:(current application’s NLDistanceTypeCosine))
–> 1.168848276138

★Click Here to Open This Script 

Posted in Natural Language Processing | Tagged 13.0savvy 14.0savvy | Leave a comment

NaturalLanguage.frameworkでNLEmbeddingの処理が可能な言語をチェック

Posted on 3月 13, 2024 by Takaaki Naganoya

NaturalLanguage.frameworkには各種言語の定義を行なった定数が57ほど定義されているようです。ただし、これらの定義がすべて利用できるわけがありません(Appleのやることなので、必ずミスやもれがあります)。

とりあえず、本当にどのぐらいの言語が使えるのか、チェックしておくことが必要です。

結論からいえば、Appleが何を考えているのかよくわかりません。macOS 13では7言語ほど使えるという結果になりましたが、macOS 14では英語しか使えないという結果になっています。OSがバージョンアップするとOSの機能が低下するという理解不能な挙動を示しています。バグ、、、なのかも????

Appleが用意した新機能は、ひととおり「本当に使えるのか」をチェックする必要があります。だいたいは搭載されて1発目はバグだらけで、OSのメジャーアップデートを経て良くなったり、よくならなかったりします。

この機能はどちらなんでしょう? Shortcutみたいに「救いようがない」のもありますが……

AppleScript名:指定言語でNLEmbeddingを処理できるかチェック_13_14.scpt
—
–  Created by: Takaaki Naganoya
–  Created on: 2024/03/13
—
–  Copyright © 2024 Piyomaru Software, All Rights Reserved
—

use AppleScript version "2.8"
use framework "Foundation"
use framework "NaturalLanguage"
use scripting additions

–The result is on macOS 13.6.5 / 14.4
set aRes to testNLLanguage("NLLanguageEnglish") of me –> true
set aRes to testNLLanguage("NLLanguageFrench") of me –> true–>false (macOS 14)
set aRes to testNLLanguage("NLLanguageGerman") of me –> true–>false (macOS 14)
set aRes to testNLLanguage("NLLanguageItalian") of me –> true–>false (macOS 14)
set aRes to testNLLanguage("NLLanguagePortuguese") of me –> true–>false (macOS 14)
set aRes to testNLLanguage("NLLanguageSimplifiedChinese") of me –> true–>false (macOS 14)
set aRes to testNLLanguage("NLLanguageSpanish") of me –> true–>false (macOS 14)

set aRes to testNLLanguage("NLLanguageUndetermined") of me –> true –Natural Language framework doesn’t recognize.

set aRes to testNLLanguage("NLLanguageAmharic") of me –> false
set aRes to testNLLanguage("NLLanguageArabic") of me –> false
set aRes to testNLLanguage("NLLanguageArmenian") of me –> false
set aRes to testNLLanguage("NLLanguageBengali") of me –> false
set aRes to testNLLanguage("NLLanguageBulgarian") of me –> false
set aRes to testNLLanguage("NLLanguageBurmese") of me –> false
set aRes to testNLLanguage("NLLanguageCatalan") of me –> false
set aRes to testNLLanguage("NLLanguageCherokee") of me –> false
set aRes to testNLLanguage("NLLanguageCroatian") of me –> false
set aRes to testNLLanguage("NLLanguageCzech") of me –> false
set aRes to testNLLanguage("NLLanguageDanish") of me –> false
set aRes to testNLLanguage("NLLanguageDutch") of me –> false
set aRes to testNLLanguage("NLLanguageFinnish") of me –> false
set aRes to testNLLanguage("NLLanguageGeorgian") of me –> false
set aRes to testNLLanguage("NLLanguageGreek") of me –> false
set aRes to testNLLanguage("NLLanguageGujarati") of me –> false
set aRes to testNLLanguage("NLLanguageHebrew") of me –> false
set aRes to testNLLanguage("NLLanguageHindi") of me –> false
set aRes to testNLLanguage("NLLanguageHungarian") of me –> false
set aRes to testNLLanguage("NLLanguageIcelandic") of me –> false
set aRes to testNLLanguage("NLLanguageIndonesian") of me –> false
set aRes to testNLLanguage("NLLanguageJapanese") of me –> false
set aRes to testNLLanguage("NLLanguageKannada") of me –> false
set aRes to testNLLanguage("NLLanguageKazakh") of me –> false
set aRes to testNLLanguage("NLLanguageKhmer") of me –> false
set aRes to testNLLanguage("NLLanguageKorean") of me –> false
set aRes to testNLLanguage("NLLanguageLao") of me –> false
set aRes to testNLLanguage("NLLanguageMalay") of me –> false
set aRes to testNLLanguage("NLLanguageMalayalam") of me –> false
set aRes to testNLLanguage("NLLanguageMarathi") of me –> false
set aRes to testNLLanguage("NLLanguageMongolian") of me –> false
set aRes to testNLLanguage("NLLanguageNorwegian") of me –> false
set aRes to testNLLanguage("NLLanguageOriya") of me –> false
set aRes to testNLLanguage("NLLanguagePersian") of me –> false
set aRes to testNLLanguage("NLLanguagePolish") of me –> false
set aRes to testNLLanguage("NLLanguagePunjabi") of me –> false
set aRes to testNLLanguage("NLLanguageRomanian") of me –> false
set aRes to testNLLanguage("NLLanguageRussian") of me –> false
set aRes to testNLLanguage("NLLanguageSinhalese") of me –> false
set aRes to testNLLanguage("NLLanguageSlovak") of me –> false
set aRes to testNLLanguage("NLLanguageSwedish") of me –> false
set aRes to testNLLanguage("NLLanguageTamil") of me –> false
set aRes to testNLLanguage("NLLanguageTelugu") of me –> false
set aRes to testNLLanguage("NLLanguageThai") of me –> false
set aRes to testNLLanguage("NLLanguageTibetan") of me –> false
set aRes to testNLLanguage("NLLanguageTraditionalChinese") of me –> false
set aRes to testNLLanguage("NLLanguageTurkish") of me –> false
set aRes to testNLLanguage("NLLanguageUkrainian") of me –> false
set aRes to testNLLanguage("NLLanguageUrdu") of me –> false
set aRes to testNLLanguage("NLLanguageVietnamese") of me –> false

on testNLLanguage(aLangName)
  set aText to "use AppleScript
use framework \"Foundation\"
use framework \"NaturalLanguage\"

  set targLang to (current application’s " & aLangName & ")
  set aEmb to current application’s NLEmbedding’s wordEmbeddingForLanguage:(targLang)
  if aEmb = missing value then return false
  return true
  "

  
return run script aText
end testNLLanguage

★Click Here to Open This Script 

Posted in Natural Language Processing Text | Tagged 13.0savvy 14.0savvy | Leave a comment

NaturalLanguage frameworkを使って類語語展開+意味的な距離を計測してソート

Posted on 3月 13, 2024 by Takaaki Naganoya

NaturalLanguage frameworkといえば、macOS 10.14で追加されたものですが、自然言語テキストが「何語」であるかを推測するなどの使い方をAppleScriptから行なってきました。正直、その程度しか「役に立つ機能がない」という認識でした。

日本語のサポートはまだまだですが、日本語でなければ意外と使えることがわかりました。

試しに、NaturalLanguage.frameworkの機能を用いて指定の英単語の類義語を生成して、それぞれの元の単語との意味的な距離を計算してみました。

自然言語処理的にわかりやすい言葉でいえば、類語語のリストをword2vecでベクトル化してコサイン距離を計算する、というところでしょうか。

類義語展開であれば、日本語WordNetを利用して検索するAppleScriptを4年ぐらい前に試作ずみなので、このOS側の類義語展開機能がなくても別に構わないのですが、word2vecやsentence2vecで単語や文章をベクトル化して意味的な距離を計測する演算については、利用したいところです。

ただ、OSの機能が向上するどころか退化しているようなので、この分野ではmacOSの進歩は期待できないのかもしれません。

AppleScript名:指定単語の類義語を展開して元の単語との距離を測る.scpt
—
–  Created by: Takaaki Naganoya
–  Created on: 2024/03/12
—
–  Copyright © 2024 Piyomaru Software, All Rights Reserved
—

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

set targLang to current application’s NLLanguageEnglish
set aEmb to current application’s NLEmbedding’s wordEmbeddingForLanguage:(targLang)
if aEmb = missing value then return –NLLanguageJapanese is not available here in macOS 13

–類義語展開(Max.50)
set aWord to "computer"
set aSym to (aEmb’s neighborsForString:aWord maximumCount:20 distanceType:(current application’s NLDistanceTypeCosine)) as list

–コサイン距離を計測(0.0〜2.0)数字が小さいと近いはず。ちょっとでも意味が遠いと2.0になるという悪癖を持つ
set distList to {}
repeat with i in aSym
  set j to contents of i
  
set aDist to (aEmb’s distanceBetweenString:aWord andString:j distanceType:(current application’s NLDistanceTypeCosine))
  
set the end of distList to {wordName:j, wordDistance:aDist as real}
end repeat

–昇順ソート
set bList to sortRecListByLabel(distList, "wordDistance", true) of me
–> {{wordDistance:0.837697923183, wordName:"workstation"}, {wordDistance:0.875068962574, wordName:"mainframe"}, {wordDistance:0.886509418488, wordName:"laptop"}, {wordDistance:0.901307225227, wordName:"software"}, {wordDistance:0.901674091816, wordName:"computing"}, {wordDistance:0.904342055321, wordName:"palmtop"}, {wordDistance:0.951638877392, wordName:"desktop"}, {wordDistance:0.954249441624, wordName:"intranet"}, {wordDistance:0.958346903324, wordName:"keystroke"}, {wordDistance:0.961381614208, wordName:"notebook"}, {wordDistance:0.964299142361, wordName:"server"}, {wordDistance:0.970234155655, wordName:"hardware"}, {wordDistance:0.974493980408, wordName:"pager"}, {wordDistance:0.981385648251, wordName:"electronic"}, {wordDistance:0.984282553196, wordName:"peripheral"}, {wordDistance:0.993325233459, wordName:"machine"}, {wordDistance:0.996084809303, wordName:"diskette"}, {wordDistance:0.999181330204, wordName:"portable"}, {wordDistance:1.001676082611, wordName:"compatible"}, {wordDistance:1.00532245636, wordName:"programmer"}}

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

★Click Here to Open This Script 

本当は単語ではなく「文章」の距離を計測できないと実用性が低いところです。word2vecではなくsentence2vecの演算を行いたいところ。

自作のAppleScriptによるアイデアプロセッサ「Kamenoko」も、当初から自然言語処理の機能を盛り込むことを企画していました。sentence2vecぐらいの演算を行なって、各ノードに書いてある文章同士の距離を計測して、距離に応じて色を変えるといった機能も検討していました。

ただ、そうした機能を実装するのに割とデータ量が多くなるとか、アプリとしてパッケージングするのに無理があるとか、もういっそWebサーバー側で処理したほうがいいんじゃないの? 的な話になって見送った経緯があります。

このNaturalLanguage.frameworkがもっと使えるように、なったらいいのに。簡体字の中国語に対応しているぐらいなので、日本語への対応も期待したいところですが……macOS 14では対応言語が英語だけになるなど、展開の仕方が謎であります。

Posted in list Natural Language Processing Record | Tagged 13.0savvy 14.0savvy | Leave a comment

可変次元のベクトルに対応したコサイン類似度計算

Posted on 11月 23, 2023 by Takaaki Naganoya

ChatGPTに書かせたAppleScriptを微修正したものです。ベクトルの内積、外積の計算を経てコサイン類似度計算のAppleScriptを書かせました。

もともとは、ChatGPTのAPIを利用して自然言語テキストをベクトル化し、それらの類似度を計算させるための準備で用意しました。自分が試したときには、ChatGPTのREST APIは1536次元のベクトルを返してきました。残念ながら、いま試してみると(全然REST API呼び出しをしていないのに)Quota Exceedのエラーが出てしまって目的の処理はできませんでした。

このあたり、実際にChatGPTのコンソールから利用履歴を確認してみても、全然呼び出していないことが確認できたので、自分の記憶違いではありません。

もともと、日本語テキストを複数の機械翻訳APIを利用して英訳し、再度日本語訳したのちに文章をベクトル化。これらの複数の機械翻訳APIの結果を比較して、もともとの日本語の文章と類似度が高いものを「正確に英訳された文章」として採用してみるといいんじゃないかと思っていました。翻訳文の質を疑似的に評価してみようと思ったわけです。

ChatGPTに出力させたAppleScriptは、「間違ってはいないんだけど、正しくないし、微妙にムカつく(resultを使って計算したりする)」内容で、よくわかっている人間にとっては簡単に修正できるものですが、基礎がわかっていないとどこが間違っているか指摘しにくいし、そもそも間違っているかどうかも指摘しにくいので……より正確な知識が要求されます。

AppleScript名:可変次元のベクトルに対応したコサイン類似度計算.scpt
— ベクトルの例
set vectorA to {1, 2, 3, 4}
set vectorB to {4, 5, 6, 7}

— コサイン類似度を計算
set similarityResult to cosineSimilarity(vectorA, vectorB)

— 結果を表示
return similarityResult
–> 0.975900072949

— ベクトルのノルムを計算する関数
on vectorNorm(aVec)
  set sumSquares to 0
  
repeat with i from 1 to (count of aVec)
    set sumSquares to sumSquares + (item i of aVec) ^ 2
  end repeat
  
return (sumSquares) ^ 0.5
end vectorNorm

— ベクトルのコサイン類似度を計算する関数
on cosineSimilarity(vector1, vector2)
  set dimension1 to count of vector1
  
set dimension2 to count of vector2
  
  
if dimension1 = dimension2 then
    set dotProductResult to dotProduct(vector1, vector2)
    
set norm1 to vectorNorm(vector1)
    
set norm2 to vectorNorm(vector2)
    
set similarity to dotProductResult / (norm1 * norm2)
    
return similarity
  else
    error "ベクトルの次元数が一致していません。"
  end if
end cosineSimilarity

— ベクトルの内積を計算する関数
on dotProduct(vector1, vector2)
  set dimension1 to count of vector1
  
set dimension2 to count of vector2
  
  
if dimension1 = dimension2 then
    set sRes to 0
    
repeat with i from 1 to dimension1
      set sRes to sRes + ((item i of vector1) * (item i of vector2))
    end repeat
    
return sRes
  else
    error "ベクトルの次元数が一致していません。"
  end if
end dotProduct

★Click Here to Open This Script 

Posted in list Natural Language Processing | Tagged 13.0savvy 14.0savvy | Leave a comment

ChatGPTでchatに対する応答文を取得

Posted on 3月 6, 2023 by Takaaki Naganoya

OpenAIが提供しているREST APIを呼び出して、チャットに対する応答を生成するAppleScriptです。実行のためにはOpenAIのWebサイトにサインアップして、実行のためのAPI Keyを取得してください。

ChatGPTなどのサービスを提供しているOpenAIにサインアップして、各種サービスをAppleScriptから利用できます。Freeアカウントでは1分あたりに発行できるクエリー数の上限が低めに設定されていますが、実験を行う程度であれば十分なレベルでしょう。

https://platform.openai.com/docs/introduction

「chat」は、いわゆるChatGPTでよく知られている処理で、チャットに応答するものです。この呼び出し方に対して、さらにroleとして「system」「user」「assistant」などの役割を指定することで、チャットらしいやりとりを生成するようです(Chat completion)。

AppleScript名:Chat.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2023/03/05
—
–  Copyright © 2023 Piyomaru Software, All Rights Reserved
—

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

property NSString : a reference to current application’s NSString
property NSCountedSet : a reference to current application’s NSCountedSet
property NSJSONSerialization : a reference to current application’s NSJSONSerialization
property NSUTF8StringEncoding : a reference to current application’s NSUTF8StringEncoding

set myText to "こんにちは"

set barerKey to "xx-XXXXXXXxXxxxxXxxXXxXXXXxxxXXxxxxXXxxxXXxXXxxXXxx"

set aText to "curl https://api.openai.com/v1/chat/completions -H ’Content-Type: application/json’ -H ’Authorization: Bearer " & barerKey & "’ -d ’{\"model\": \"gpt-3.5-turbo\",\"messages\": [{\"role\": \"user\", \"content\": \"" & myText & "\"}]}’"
set sRes to do shell script aText

set jsonString to NSString’s stringWithString:sRes
set jsonData to jsonString’s dataUsingEncoding:(NSUTF8StringEncoding)
set aRes to NSJSONSerialization’s JSONObjectWithData:jsonData options:0 |error|:(missing value)
set chatRes to (aRes’s valueForKeyPath:"choices.message.content") as list
–>{"こんにちは!こんにちはと言うと、こんにちはと返してくださる方が多いですね。私はAIアシスタントなので、いつでもお話し相手になれます。何かお話を聞かせてください。"}
–> {"、こんにちは! 私はAIアシスタントです。何かお手伝いできることはありますか?"}
–> {"こんにちは!私はAIアシスタントです。何かお手伝いできますか?"}
–> {"、私はAIアシスタントです。何かお手伝いできることはありますか?"}
–> {"こんにちは!こんにちはは、日本語で「こんにちは」と書き、挨拶の一つです。相手と会話をする際に使われる一般的な挨拶の言葉で、おはようございます、こんにちは、こんばんはなどがあります。どうぞよろしくお願いします!"}

★Click Here to Open This Script 

Posted in JSON Natural Language Processing Network REST API | Tagged 12.0savvy 13.0savvy ChatGPT | Leave a comment

ChatGPTで質問に対する回答を生成(Compilations)

Posted on 2月 26, 2023 by Takaaki Naganoya

OpenAIが提供しているREST APIを呼び出して、質問に対する回答を生成するAppleScriptです。実行のためにはOpenAIのWebサイトにサインアップして、実行のためのAPI Keyを取得してください。

ChatGPTなどのサービスを提供しているOpenAIにサインアップして、各種サービスをAppleScriptから利用できます。Freeアカウントでは1分あたりに発行できるクエリー数の上限が低めに設定されていますが、実験を行う程度であれば十分なレベルでしょう。

https://platform.openai.com/docs/introduction

「質問に対する回答を生成」は、いわゆるChatGPTでよく知られている処理で、対話的に質問文に回答するものです。回答内容が正しいかどうかはちょっとアレですが、自然言語処理もこのレベルまで来たのかと感心させられます。

対話っぽい動作(前回の問い合わせを踏まえた上で回答する)を考えて「user」パラメータを付けて呼び出していますが(ここも自分のユーザーアカウントに書き換えてください)、いまひとつWebブラウザ上で問い合わせを行ったときのような「つながり」を感じられないので、何かまだ指定する必要があるのかもしれません。

AppleScript名:Compilations(質問に対する回答を生成).scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2023/02/24
—
–  Copyright © 2023 Piyomaru Software, All Rights Reserved
—

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

property NSString : a reference to current application’s NSString
property NSCountedSet : a reference to current application’s NSCountedSet
property NSJSONSerialization : a reference to current application’s NSJSONSerialization
property NSUTF8StringEncoding : a reference to current application’s NSUTF8StringEncoding

set myText to "バンダイナムコのアーケードゲーム「戦場の絆1」の初代プロデューサーの名前は、小山順一朗さんです。"

set barerKey to "xx-XXXXXXXxXxxxxXxxXXxXXXXxxxXXxxxxXXxxxXXxXXxxXXxx"

set sRes to (do shell script "curl https://api.openai.com/v1/completions -H ’Content-Type: application/json’ -H ’Authorization: Bearer " & barerKey & "’ -d ’{\"model\": \"text-davinci-003\", \"prompt\": \"" & myText & "\", \"max_tokens\": 200, \"temperature\": 0, \"user\": \"maro_ml@piyocast.com\"}’")

set jsonString to NSString’s stringWithString:sRes
set jsonData to jsonString’s dataUsingEncoding:(NSUTF8StringEncoding)
set aRes to NSJSONSerialization’s JSONObjectWithData:jsonData options:0 |error|:(missing value)
set modelRes to aRes as {anything, record}

–>{|id|:"cmpl-6nMNGJzTFei6eMbn1rnMgMN9ML4qi", object:"text_completion", created:1.677222098E+9, model:"text-davinci-003", choices:{{|index|:0, finish_reason:"stop", logprobs:missing value, |text|:"小山順一朗さんは、バンダイナムコのゲームプロデューサーとして、「戦場の絆1」をはじめとした数々のアーケードゲームをプロデュースしてきました。また、「戦場の絆1」のプロデューサーとして、「戦場の絆2」「戦場の絆3」「戦場の絆4」などのシリーズをプロデュースしています。"}}, usage:{total_tokens:224, completion_tokens:163, prompt_tokens:61}}

★Click Here to Open This Script 

Posted in Natural Language Processing REST API Text | Tagged 12.0savvy 13.0savvy ChatGPT | Leave a comment

ChatGPTで文章の感情検出(Moderations)

Posted on 2月 26, 2023 by Takaaki Naganoya

OpenAIが提供しているREST APIを呼び出して、指定文章の感情検出を行うAppleScriptです。実行のためにはOpenAIのWebサイトにサインアップして、実行のためのAPI Keyを取得してください。

ChatGPTなどのサービスを提供しているOpenAIにサインアップして、各種サービスをAppleScriptから利用できます。Freeアカウントでは1分あたりに発行できるクエリー数の上限が低めに設定されていますが、実験を行う程度であれば十分なレベルでしょう。

https://platform.openai.com/docs/introduction

「文章の感情検出」は、ユーザーサポートなどの現場においてユーザーからの投稿が質問などのものなのか、あるいは感情的な文章なのかといった「当たり」をつけるために用いられているといった印象があります。

ただ、「I want to kill him.」という例文に対して「hate」が検出されないなど、ややその評価内容には疑問の余地が残されているようです。

AppleScript名:Moderations(感情検出).scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2023/02/24
—
–  Copyright © 2023 Piyomaru Software, All Rights Reserved
—

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

property NSString : a reference to current application’s NSString
property NSCountedSet : a reference to current application’s NSCountedSet
property NSJSONSerialization : a reference to current application’s NSJSONSerialization
property NSUTF8StringEncoding : a reference to current application’s NSUTF8StringEncoding

set aSentence to "I want to kill him."

set barerKey to "xx-XXXXXXXxXxxxxXxxXXxXXXXxxxXXxxxxXXxxxXXxXXxxXXxx"
set sRes to (do shell script "curl https://api.openai.com/v1/moderations -H ’Content-Type: application/json’ -H ’Authorization: Bearer " & barerKey & "’ -d ’{\"input\": \"" & aSentence & "\" }’")

set jsonString to NSString’s stringWithString:sRes
set jsonData to jsonString’s dataUsingEncoding:(NSUTF8StringEncoding)
set aRes to NSJSONSerialization’s JSONObjectWithData:jsonData options:0 |error|:(missing value)

set mRes to aRes as {anything, record}
–> {|id|:"modr-6o8PPeHjWYIH5z5Qi79etbe8JaWY8", model:"text-moderation-004", results:{{flagged:true, category_scores:{sexual:3.26660915561661E-6, |sexual/minors|:2.58405265185502E-7, |hate/threatening|:2.28086973947939E-5, hate:0.007466733921, |self-harm|:1.23088886994083E-6, violence:0.794520378113, |violence/graphic|:4.90069034242424E-8}, categories:{sexual:false, |sexual/minors|:false, |hate/threatening|:false, hate:false, |self-harm|:false, violence:true, |violence/graphic|:false}}}}

★Click Here to Open This Script 

Posted in Natural Language Processing REST API Text | Tagged 12.0savvy 13.0savvy ChatGPT | Leave a comment

ChatGPTで文章のベクトル化(Embedding)

Posted on 2月 26, 2023 by Takaaki Naganoya

OpenAIが提供しているREST APIを呼び出して、指定文章のベクトル化を行うAppleScriptです。実行のためにはOpenAIのWebサイトにサインアップして、実行のためのAPI Keyを取得してください。

ChatGPTなどのサービスを提供しているOpenAIにサインアップして、各種サービスをAppleScriptから利用できます。Freeアカウントでは1分あたりに発行できるクエリー数の上限が低めに設定されていますが、実験を行う程度であれば十分なレベルでしょう。

https://platform.openai.com/docs/introduction

「文章のベクトル化」は、大量の候補文を用意しておいてベクトル化し、新たにユーザーが与えた文章との「類似度」を計算するためのものです。

AppleScript名:Embedding(文章のベクトル化).scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2023/02/24
—
–  Copyright © 2023 Piyomaru Software, All Rights Reserved
—

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

property NSString : a reference to current application’s NSString
property NSCountedSet : a reference to current application’s NSCountedSet
property NSJSONSerialization : a reference to current application’s NSJSONSerialization
property NSUTF8StringEncoding : a reference to current application’s NSUTF8StringEncoding

set myText to "今日はいい天気です。"

set barerKey to "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
set sRes to (do shell script "curl https://api.openai.com/v1/embeddings -H ’Content-Type: application/json’ -H ’Authorization: Bearer " & barerKey & "’ -d ’{\"input\": \"" & myText & "\", \"model\":\"text-embedding-ada-002\"}’")

set jsonString to NSString’s stringWithString:sRes
set jsonData to jsonString’s dataUsingEncoding:(NSUTF8StringEncoding)
set aRes to NSJSONSerialization’s JSONObjectWithData:jsonData options:0 |error|:(missing value)
set modelRes to aRes as {anything, record}
–> {object:"list", |data|:{{|index|:0, object:"embedding", embedding:{0.0024673557, 0.0037366515, -0.005702117, -0.025023261, 0.010659494, -0.0024349757, 0.0038791234, -0.031266123, 0.005248797, -0.023909388, -0.0052941293, 0.008710219, -0.0028316306, -0.019039437, -0.013780926, -0.009519719, 0.01660446, -0.020762052, 0.019881317, -0.025748573, 0.037897546, 0.025981707, -0.006569901, -0.01387159, -0.023209982, 0.0051743235, 0.014182438, -0.018974677, 0.031032987, -0.026655212, 0.029919116, -0.00975933, -0.007019983, 0.022381052, 0.010186747, -0.032120954, -0.023054557, 0.01536107, -0.0049476633, 0.005919063, 0.01542583, -0.019363238, 0.015335166, -0.0029741025, -0.02567086, 0.008626031, -0.008295755, 0.0018116607, -0.004814905, 0.028546205, 0.011533754, -0.006395049, -0.040876508, -0.038855996, -5.7595916E-4, 0.006106867, -0.014078822, -1.681736E-4, -0.005365365, -0.01260877, -0.0025499247, -0.013949302, -0.009280107, 0.01925962, 0.007266071, -0.01451919, -0.020917477, -0.0051937513, -0.018197557, 0.009701047, 0.008813835, -0.0028105837, -4.6546242E-4, -0.035669804, 0.008813835, 0.0023507876, -0.013003807, -0.010562355, -0.0016028098, 0.008904499, 0.015995719, -0.03269084, -0.0109638665, -0.006909891, 0.0061554373, 0.0031861917, -0.014117678, 0.019440949, -1.770781E-4, -0.017057782, 0.011592038, 0.0014376718, 0.023171125, -0.0041090213, -0.006637899, 0.0035877035, 0.01633247, 0.031136604, 0.011158146, -0.026784733, -0.0041122595, -0.0016950928, 2.7664658E-4, 0.0033416154, -0.051367626, -0.0082892785, 0.027173292, -0.008082047, 0.02120242, -0.038234297, -0.015179742, -0.006909891, 4.5251043E-4, -0.039918058, -0.024518132, 0.008962783, 0.004562341, 0.0014311958, -0.012168402, -3.0922896E-4, 0.018624973, 0.010070179, -0.0012701054, -0.004737193, 0.006450095, 0.01150785, -0.02890886, -0.016228853, -0.011650322, 8.2771364E-4, 0.01426015, 0.005112801, 0.0041187354, 0.007466827, 0.0037139854, 0.012984378, -0.025632005, 0.0197777, -0.010756634, 0.018093942, 0.006236387, 0.035177626, -0.019699989, -0.018236414, -0.013107422, 0.012401538, 0.008600127, -0.019415045, 0.01354779, -0.017562909, 0.020787956, -0.012511631, 0.029349228, 0.017472245, 0.023313597, 0.026784733, 9.843518E-4, 0.017239109, -0.0036265594, -0.013573694, 0.028934764, -0.0132045625, 0.03590294, 0.007725867, 8.362134E-4, 0.02644798, 0.009739903, 0.0050577554, 0.007000555, -2.8352733E-4, -0.0048537613, 0.023184076, -0.030307677, 0.0038305535, -0.010251506, 0.034115564, 0.016280662, 0.005864017, -0.0049185213, -0.017485198, -0.038985513, -8.707183E-5, 0.014558046, -0.005430125, 0.0011486803, -0.011630895, 0.024453372, 0.0055110753, -0.009849994, -0.026422076, 0.0330535, 0.038027067, 0.013405318, -0.013884542, -0.6204525, -0.027976315, -0.0013024854, -0.0033578055, 0.03079985, 0.0029174376, 0.014506238, 0.018132798, -0.01905239, 0.016643317, -0.01290019, 0.009973039, -0.015827341, -0.0017614717, 0.0027199197, -0.016461989, -0.009824091, -0.0061845793, -0.025852188, 0.01796442, -0.016410181, 0.01562011, -0.022186773, -0.018236414, 0.014337862, -0.016215902, -0.009571526, -0.027276909, -0.019997885, 0.041705433, -0.036576442, 0.03901142, 0.014998414, -0.014117678, 0.048181433, -0.0039438833, -0.029789595, 0.050564602, 0.019415045, 0.026046468, -0.024220238, -0.017148446, 0.015827341, -0.0099082785, 0.011112815, -0.006961699, 0.024025956, -0.015153838, 0.01801623, 0.0025628766, -0.0042353035, -0.0033707574, 0.0029384845, -0.0015914767, -0.012731814, 0.016695125, 0.039063226, -0.030748043, -0.01163737, 0.0014692423, -0.006589329, 0.009383723, -0.013949302, -0.010950915, -0.016449038, 0.01562011, -0.007492731, 0.005987061, 0.020723198, 0.0031068607, -0.0051095635, 0.0049347114, 0.014609854, 0.018093942, 0.011125767, 0.013729118, 0.037742123, -0.0028915335, -0.020956334, 0.014311958, 0.011695654, -0.019712942, -0.018948773, 0.0023313598, 0.006877511, -0.012569915, -0.038674667, -0.01822346, 0.021435557, -0.0042968253, 0.010769586, 0.02028283, 0.024090717, 0.0019444188, 0.008263375, 0.018327078, -0.008470607, -0.024803076, 0.0041640676, 0.014570998, -0.0054625054, 0.011061006, 0.016669221, 0.008412323, 0.007201311, 0.009552099, -0.026681116, -0.006521331, -0.0035650374, -0.01840479, 0.018003277, -0.01510203, -0.01796442, 0.0025207826, 0.024272045, -0.032898076, 0.016837597, 0.012550486, 0.00843175, 0.008412323, 0.0090987785, 0.0060971533, 0.019712942, -0.008502987, -0.021590982, 0.029375132, -0.007486255, -0.012971426, -0.0032282856, 0.007421495, -0.010633591, 0.0019897507, 0.016034573, -0.019894268, 0.03033358, -0.031551067, 0.008308707, -0.0126411505, 0.04802601, -0.011876983, -0.027017869, -0.014221294, -0.010491119, 0.017718334, -0.0026762066, -0.016449038, -0.01490775, -0.005760401, -0.026914252, 0.013340558, 0.007123599, 0.004520247, -0.007745295, 0.022925036, -0.018871062, -0.0026389696, 0.007777675, -0.008898023, -0.008308707, 3.936193E-5, 0.009072875, 0.0013850543, -0.01464871, 0.006006489, -0.005925539, -0.01866383, -0.033727, 0.016733982, -0.006246101, -0.023054557, -0.016695125, -0.0042061615, -0.009610383, 0.011203478, 0.0089109745, -0.016759885, 0.0016837597, -0.005423649, 0.0045688176, -0.016539702, -0.009985991, -0.027147388, -0.015335166, 0.0021548886, -0.0032590465, -0.007058839, 0.029711884, 0.04025481, -0.006621709, 0.021629836, -0.008295755, 0.025165733, -0.008107951, 0.008127379, 0.036343306, -0.025204588, 0.0011932028, 0.02735462, 0.015982766, 0.017537005, 0.012323827, 0.009215347, 0.014104726, -0.0120777385, -4.7841444E-4, -0.021318989, 0.007240167, -0.01231735, 0.0020010837, 0.01098977, 0.0010321124, -0.022044301, -0.019427998, 0.0024592606, -0.01315923, 0.019130101, 0.0025304966, -6.358622E-4, 0.008107951, -0.018521357, 0.007272547, 0.016733982, -0.0016934738, -0.04686033, -0.029064285, -0.014493286, 0.012272018, 0.03131793, 0.0130167585, -0.007687011, -0.024712412, -0.014855942, -0.02249762, 0.025632005, 0.004209399, -0.060459927, 0.0032234285, -0.018599069, 0.054553818, 0.03800116, 0.007557491, -0.0014789563, 0.006760943, -0.030773947, 2.950627E-4, 0.016837597, 0.04349281, 0.008703743, 0.0018148988, 0.0038273155, -0.015995719, -0.036187883, -0.013275798, -0.00911173, 0.007207787, -0.058491223, 0.0019071817, -0.014039966, 0.01516679, 0.044891626, 0.012680006, 0.04551332, -0.0021111758, -0.0027927747, 0.020256925, 0.0024997357, 0.016513798, -0.03279446, -0.007706439, 0.0010264459, -0.0021678407, 0.005261749, 0.0023783108, -0.009170014, 0.007168931, -0.02054187, -0.008211567, -0.0029433416, 0.0051516574, 0.015089078, 6.973841E-4, -0.037534893, -0.010037798, 0.01222021, -0.0021937448, -0.013832734, -0.012945523, -0.034452315, -0.022653045, 0.018003277, 0.015581254, 0.028028125, -0.012809526, 8.872119E-4, 0.012123071, -0.009681619, 0.038855996, -0.0032655227, -0.059475575, -0.027898604, 0.029064285, -0.014078822, 0.022665996, -0.035643898, 0.005067469, 4.998662E-4, -0.008230994, -0.0024284997, 2.5215923E-4, 0.011779842, -0.0052747014, -0.016941214, -0.019635228, -0.017226158, -0.0037431275, 0.0037269376, -0.0046627196, -0.013923398, 0.029375132, -0.013534838, -0.019272573, -0.0034355174, -0.0044490113, 0.012725338, 0.035151724, 0.0014061013, 0.018132798, 0.029867308, 0.019971982, 6.2210066E-4, -0.016358374, -0.02008855, 3.7161106E-5, -0.014596902, 0.014208342, 0.0022034587, 0.009571526, -0.011222906, 0.007188359, -0.009927707, -0.016112287, -0.0036168455, -0.0020367017, -0.013379415, -0.013923398, 0.01445443, -5.3872215E-4, 0.015309262, 0.009519719, 0.0013340558, -0.006100391, 0.031991437, 0.020153308, -0.007589871, -0.007065315, 0.01464871, -0.010374551, -0.008373467, -0.010562355, 0.01951866, -0.0097204745, 0.025450677, -0.013379415, -0.013431222, -0.0042871116, 0.032716747, 0.014804134, 0.013314654, -0.009694571, 0.0020707007, -0.01471347, 0.014959558, -0.010303315, -0.007797103, 0.019946078, 0.016487895, -0.0285203, -0.03105889, -0.008923926, 0.040954217, -0.0272251, -0.009843519, -0.009144111, 0.013340558, -0.011462518, -0.021603933, -0.007725867, 8.535165E-5, -0.0140140625, -0.03144745, -0.008075571, -0.01691531, -0.0063497173, -0.020153308, -0.0015145743, -0.005925539, -0.033675194, 9.414484E-4, 0.025049165, 0.02994502, 0.007622251, -0.017018925, -0.009273631, 0.024712412, -0.008800883, -0.005248797, 0.020438254, -0.020256925, -0.014182438, 0.0013648168, 0.006832179, -2.2463621E-4, 0.006683231, 0.01257639, 0.018832205, 0.020658437, 0.01458395, 0.018573165, -0.011630895, -0.0097204745, 0.008820311, 0.0119611705, -0.026046468, -0.0018278507, 0.027769083, -0.01626771, -0.016461989, -5.9133966E-4, -7.4878737E-4, 0.03136974, 0.016461989, -8.305469E-4, 0.007732343, 0.0041414015, 0.029271515, -0.010011895, 0.037612602, -2.3637396E-4, -0.0039762636, 0.02327474, 0.006550473, 0.007823007, 0.0058963974, -0.035825226, 0.010510546, -0.01730387, 0.038286105, -0.009053446, 0.025761524, -0.008690791, -0.01821051, -0.028235355, -0.01406587, 0.0115855625, -0.010089607, 0.027769083, -0.0050868974, -0.027717276, -0.013910446, -0.023404261, -0.0039730254, 0.036783677, -0.01613819, -0.030229963, -0.030022731, -0.010018371, 0.01413063, -0.015840294, 0.006871035, -0.02534706, -0.012744767, -8.1455924E-5, 0.016423134, 0.022860277, -0.009001639, -0.005990299, -0.02994502, -5.6786416E-4, 0.013431222, -0.0291679, -0.0035035156, -0.014570998, -0.0010402073, 0.0029190567, 0.021940686, 0.017316822, 0.0049476633, -0.011443091, -0.009539147, -0.0034419936, 0.0045526274, -6.1521993E-4, -0.025852188, 0.0053394614, 0.009118207, -0.0016384277, -0.008936878, -0.015697822, -0.012492202, 0.0027361095, -7.131694E-4, -0.007039411, -0.007654631, -0.033856522, 0.0022892656, -0.014480334, -0.019065341, 0.005048041, 0.043363288, 0.007356735, 0.008082047, -1.9427997E-4, 0.026214844, -0.010478167, 0.02146146, -0.009701047, -0.0010499214, -0.017057782, -0.01069835, -0.0030793375, 0.022640092, -0.0076934868, 0.008891547, 0.010290363, 0.02243286, 0.020140357, -0.01150785, 0.0053977454, -0.01137833, 0.015982766, -0.013884542, 0.0036362736, 0.010575307, -0.018391838, -0.0045105335, -0.0032979026, -0.020917477, -0.026603404, 0.022601238, -2.0983754E-5, -0.0041932096, 0.006087439, -0.026072372, -0.019156005, -0.016721029, -0.008321659, 0.0050156615, -0.02547658, 0.04447716, 0.057714105, 0.0050286134, -0.024712412, -0.05911292, -0.020503012, -0.0016181903, -0.0036589394, 0.010750159, 0.013534838, -0.014480334, -0.007874815, 0.03800116, -0.0048408094, -5.1241345E-4, 0.027017869, 0.023481973, -0.01659151, 0.0027749657, 0.01769243, -0.019207813, 0.018689733, 0.010303315, -0.015646014, -0.0343487, -0.013858638, -0.006242863, 0.021616885, -0.025813332, 0.022769613, 0.023987101, 0.0034743736, 0.015866198, -0.021629836, -0.015089078, -0.0020723196, -0.0026082087, 0.02573562, -0.018508404, 0.017316822, -0.008237471, 0.030022731, 0.0050771832, 0.0011041579, -0.018430693, 0.0427934, 2.0824384E-4, -0.020386444, -0.009066399, 0.014881846, 0.014221294, -0.006252577, 0.00962981, 0.014350814, -0.025916949, -0.013703214, 0.013431222, 0.0037139854, -7.7023916E-4, -0.012304398, -0.015050222, -0.02513983, -0.0014125773, -0.026603404, -0.008425275, -0.0049994714, -0.015542398, 0.016798742, -0.028779339, 0.028882956, 0.028727531, -0.0031748586, -0.012563438, 0.03131793, -0.04064337, 0.013975206, -0.01898763, 0.0022083158, 0.008444703, -0.012654102, 5.2779395E-4, -0.0037334135, 0.0054042214, 0.020490061, -8.2690414E-4, -0.0226919, 0.010096082, 0.011501375, -0.0043518716, -0.006488951, 0.022147916, 0.014959558, 0.0033189496, -0.012647626, -0.04569465, 0.020373493, -0.0010296839, 0.011164622, 0.007531587, -0.0262537, 0.009247727, 0.0013874829, 0.007674059, -0.017679477, -0.021772308, -0.015063174, -0.0028818196, 0.009947134, -0.012783622, -0.0051354673, 0.007097695, -0.012686483, -2.7361096E-4, 0.0048051914, -0.007596347, 0.014402622, 0.028623916, 0.03864876, -0.0051710852, 0.0021613648, -0.01231735, -0.025204588, 0.0033319015, -0.02191478, -0.032509517, -0.021694597, 4.6141492E-4, 0.025230492, 4.658672E-4, -0.014350814, -0.03592884, -0.0022552668, -0.043026537, -0.0013559123, -0.016954165, 0.024790125, 0.0056049773, -0.0040442613, -0.0028283927, 0.04038433, 0.0022504097, -0.0052293693, -0.022458766, -0.007615775, -0.028675724, -0.0035779895, 0.0038791234, -0.004491105, -0.021422604, -0.03320892, 0.0055564074, -0.005734497, 0.009655715, 0.035695706, 0.0041381633, 0.0023847867, -0.011048054, -0.0265775, -0.005371841, 0.009118207, -0.009221823, -0.020231022, -0.014739374, 0.0027522997, 0.008677838, 0.004801953, 0.01581439, 0.005579073, 0.0051160394, 0.01082787, -0.029530555, -0.016565606, -0.020723198, -0.043984987, -0.009616858, -0.011261762, 0.0052455594, 0.02067139, 0.010944438, -0.025049165, -0.01536107, 0.01626771, -0.009882375, -0.010866727, 0.0033642815, -0.007376163, 5.3710316E-4, 0.0027474426, 0.01299733, -0.011229383, -0.020399397, 0.025541341, -0.021772308, -0.039503593, 0.0015623348, 0.010005418, -0.03390833, -0.009934182, 0.011533754, -0.030877564, 0.0027296336, -0.027043773, 0.03364929, -0.03351977, 0.018301174, -8.001906E-4, -0.01822346, -0.0013599598, 0.013599598, 0.009927707, -0.017925566, 0.019453902, 0.2832861, -0.01374207, -0.009221823, 0.038027067, 0.0122072585, 0.019130101, 0.011941742, -0.0066314233, 0.010368074, 0.014545094, -0.019389141, -0.010232079, -0.0017987087, 0.008651935, 0.018547261, -0.016902357, -0.020010836, -0.012246114, -0.03105889, -0.013178658, 0.011935267, 0.0020399396, 0.008684315, 0.0028138217, 0.0011745844, 0.017070733, -0.007350259, 0.021565078, 0.014376718, -0.0010669208, -0.0125828665, -0.011579086, 0.010096082, -0.0066897073, -0.010005418, -0.03390833, 0.039115034, -0.014311958, 0.022678949, 4.5655793E-4, 0.0032460946, -0.0107760625, 0.017770141, -0.010633591, 0.006362669, 0.023313597, -8.4187987E-4, -0.009610383, -0.009448483, 0.024142524, -0.01290019, -0.0034711354, 0.03351977, 0.04090241, 0.009707523, -0.017239109, 0.03460774, -0.012259066, 0.019855414, -0.030773947, 0.01536107, 0.035177626, -0.022912085, 0.022653045, -0.0051937513, 0.015723726, -0.024466325, 0.007551015, 0.025437724, -0.007188359, 0.018754493, 0.007777675, 0.0058737313, 0.0037010335, -0.025269348, -0.0054851715, 0.03287217, 0.01134595, 3.9017893E-4, 0.0021208897, -0.014661662, 0.022290388, 0.006618471, -0.0058510653, -0.016371327, -0.033364348, 0.02300275, 0.0028899147, 0.01254401, -0.01562011, 0.0011276334, 0.0032169526, 0.010406931, -0.010866727, -0.013962254, -0.0014490047, -0.020904524, 0.0052585113, -0.01814575, 0.02274371, 0.006420953, -0.045746457, 0.009804662, 0.027691372, 0.004591483, -0.0020982237, 0.018948773, -0.0013842448, 0.0011494899, -0.017770141, 0.0028931526, -0.019427998, 0.015697822, -0.0023928815, -0.009675142, 0.023171125, 0.0115855625, 0.007071791, -0.010905582, -0.0025612577, 0.026137132, -0.007920147, -0.028598012, 0.023481973, 0.026046468, -0.019997885, -0.010251506, 0.0017274728, 0.01846955, -0.053310424, 0.041394588, -6.7795615E-4, 0.014687566, 0.008062619, -0.0016084763, 0.006093915, 0.017537005, 0.0100248465, 0.0021484126, 0.011190526, -5.120087E-4, -0.024336804, -0.01406587, -0.018301174, 0.0037981735, -0.0036297976, -0.0013372938, -0.032820363, -0.007738819, 0.015594206, -0.029996827, -0.02839078, -0.007842435, -0.007013507, 0.02191478, 0.0023086937, -0.04616092, -0.029711884, 0.0014668138, 0.04310425, -0.020062646, 7.7023916E-4, 0.026486836, -0.033467963, -0.01581439, -0.0010361598, -0.16371326, 0.014855942, -0.0023653586, -0.020800909, 0.010147891, 0.0042288275, 0.009318963, 0.0025774476, -0.014558046, -0.008328135, 0.021228325, 0.027199196, -0.021059949, 0.021098806, 0.005060993, 0.021888876, -0.027173292, 0.0019444188, 0.034452315, 0.0052520353, 0.026396172, -0.016837597, 4.7598593E-4, 5.715069E-4, 0.03007454, 0.0034193275, -0.03680958, 0.012459822, 0.006793323, -0.008094999, -0.009694571, 0.006974651, 0.044632584, 0.009862946, 0.0051581333, 4.8974744E-4, 0.0013227228, 0.005154895, -0.01516679, 0.0044587255, 0.0030275297, 0.0036233214, 0.015969813, 0.008606602, -0.028546205, 0.020632533, 0.016449038, 0.012310875, -0.024751268, -0.015658965, 0.016824646, -0.01348303, 0.012757719, 0.006650851, 0.024207285, 0.023805773, -0.01361255, 0.022588285, 0.01270591, -0.011915838, -0.0010094463, -0.03124022, -0.008587175, 0.0048472853, 0.0027976315, 0.019065341, -0.01957047, 0.01685055, 1.2081786E-4, 0.006702659, 0.015594206, -0.03541076, -0.009655715, -0.021694597, 0.0048278575, -0.0063497173, -0.027069677, 0.0020674628, 0.005235845, -0.011935267, -0.017213205, 0.047300696, -0.0031003845, -0.0010515404, -0.008632507, 0.007751771, 0.01286781, -0.004678909, -0.034581836, -0.007952527, 0.03007454, -0.040099386, 0.0017371868, -0.02300275, -0.010517023, 0.0019217527, 0.012984378, 0.022963893, -0.011974122, -0.019194862, -0.010614162, -0.0033286635, -0.01393635, 0.012971426, -0.016474942, 0.02410367, 0.0078553865, 0.011838126, 0.02515278, 0.0060680113, 0.008133855, -0.01299733, 0.012589342, 0.0036880814, 0.019855414, 0.013962254, -0.008185663, -0.010653019, 0.02670702, -0.031680588, -0.017666526, -0.026279604, -0.0043648235, 0.030877564, -0.0055207894, -0.0022617427, -0.05709241, 0.013327606, -0.006420953, 0.026124181, 0.01608638, 0.03784574, 0.015063174, 0.024790125, -0.01060121, -0.013139802, 3.3776383E-4, 0.0015145743, -0.030126348, -0.014091774, 0.021629836, -0.026784733, -0.006340003, -0.019596374, -0.013625502, -7.1114564E-4, -0.0041543534, -0.0040151193, -0.016889406, -0.029271515, -0.02683654, 0.007279023, -0.02112471, 0.058750264, 0.01821051, 0.005747449, 0.030126348, -0.014027014, 0.0029676266, -0.019816557, -0.013457126, -0.013081518, -0.024751268, -0.010931486, 0.0027943936, -0.026292557, 0.019687038, -0.0037981735, 4.4967717E-4, -0.02359854, -0.026862444, 0.0052326075, -0.0018391837, 0.014441478, 0.0025531626, -0.0053394614, -0.03201734, -0.0013105803, -0.028468492, -0.024660604, 0.018637925, -0.0024835456, 0.0042612073, 0.01853431, -0.021940686, 0.009390199, -0.0036395115, 0.0025029737, -0.0053459373, 0.046394058, 0.009785235, 0.023715109, -0.008561271, -0.010368074, 0.013366462, 0.0035585614, 0.005067469, 0.034478217, -0.010251506, 0.032613132, -0.018573165, -0.022122012, -0.038286105, -0.037534893, 0.01704483, -0.013793878, -0.006767419, -0.0213967, 0.007551015, -0.0084770825, 0.009798187, 0.017135493, -9.6816185E-4, 0.0049120453, 0.016500846, 0.017990325, 0.008846215, 7.8076264E-4, 0.026888348, -0.01341827, -0.009785235, -0.013923398, -0.007894243, -0.014337862, 0.013819782, -0.005647071, 0.00885269, -0.032302283, -0.07242757, 0.01510203, 0.007117123, 0.0040474995, -0.009053446, -0.0029935306, -0.007466827, -0.009053446, -0.0032460946, -0.006877511, -0.020800909, 0.011753938, 0.006903415, -3.2076432E-4, -0.03054081, -8.297374E-4, 0.03201734, 0.015309262, 0.01134595, 0.009079351, -0.0011608228, 0.010504071, -0.005964395, 0.018197557, -0.007835959, 0.025580196, -1.9225622E-4, 0.019013533, -0.007680535, -0.018637925, -4.002977E-4, -0.033364348, 0.017977374, 0.023507876, -0.012045358, -0.022122012, -0.0044878675, 0.014817086, 0.01523155, 0.009461435, -0.020166261, -0.03608427, 0.044192217, 0.012854858, -0.025852188, -0.010096082, -0.024919644, 0.011728034, 0.02067139, -0.0045299614, 0.01432491, 0.014208342, 0.006139247, 0.0039503593, 0.0027037296, -0.020166261, 0.014441478, 0.010607687, 0.019130101, -0.012291446, 0.02326179, 0.021293085, 0.024207285, 0.0053815553, 0.01141071, 0.012893714, -0.0013996253, -0.008755551, 0.010808443, -0.01222021, -0.015801437, 0.020567773, -0.0055045993, 0.029245611, 0.015658965, -0.0016724268, 0.018935822, -0.021785261, -0.019453902, 0.03797526, 0.0039665494, 0.017187301, -0.010374551, 0.014622806, 0.01247925, 0.007188359, -0.021888876, -0.014985462, -0.028960668, 0.019440949, -0.031913724, -0.0024252618, 0.019168958, 0.020425301, 0.021824118, 0.015633062, 0.017575862, -0.014674614, 0.02385758, 0.02839078, -0.0052941293, 0.009811139, -0.01652675, -0.0037496034, -0.0054268874, -0.0014376718, -0.0153869735, -0.020826813, 0.0060032513, 0.010866727, -0.008120903, 0.013495982, -0.02469946, 0.028079933, -0.011061006, -0.0024803076, -0.0020755576, -0.025826285, -0.017498149, 0.02508802, 2.102676E-4, 0.006994079, 0.013845686, -0.0184825, 0.005355651, -0.006670279, -0.01150785, -0.006722087, 0.019220766, 0.0024155476, 0.0061554373, -0.0030663856, -0.008561271, -0.007525111, -0.016980069, 0.022381052, 0.009824091, 0.02436271, -0.039374076, 0.037042715, 0.0049541392, -0.0042773974, 0.027017869, -0.019298477, -0.0011405853, 0.014506238, 0.010063702, 0.006420953, -0.0041932096, -0.006087439, 0.004338919, -0.008885071, -0.016358374, -0.030281771, -0.022601238, -0.005300605, 0.021733453, -0.03020406, -0.0013170564, 0.034840874, -0.006812751, 0.014830038, 0.010232079, -0.021603933, -0.02774318, 0.023430165, -0.0032250476, -0.0017274728, -0.022963893, -0.0034873255, 0.012757719, 0.011689179, -0.0037722695, -0.009066399, -0.0035715136, -0.006760943, 0.013703214, 0.0011090148, 0.026227796, 8.9044985E-4, 0.006272005, -0.02515278, -0.005857541, 0.025981707, -0.006194293, -0.0065375213, 0.0109638665, -0.0057150694}}}, model:"text-embedding-ada-002-v2", usage:{total_tokens:9, prompt_tokens:9}}

★Click Here to Open This Script 

Posted in Natural Language Processing REST API Text | Tagged 12.0savvy 13.0savvy ChatGPT | 1 Comment

カギカッコのペア検出+エラーチェック

Posted on 8月 22, 2022 by Takaaki Naganoya

短い日本語の文章で、カギカッコ(「」)のペアがそろっているか、順番がきちんとしているか、個数が合っているかなどを検出するテスト用のAppleScriptです。

何回も同じようなScriptを書いてきたような気がします。

AppleScript名:カギカッコのペア検出+エラーチェック.scpt
—
–  Created by: Takaaki Naganoya
–  Created on: 2022/08/22
—
–  Copyright © 2022 Piyomaru Software, All Rights Reserved
—

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

set aStr to "「モーニング娘。」を表示した。「藤岡弘。」を表示。「藤岡弘。」。「藤岡弘。」"
–set aStr to "「モーニング娘。」を表示した。「藤岡弘。」を表示「。「藤岡弘。」。」「藤岡弘。」"

set kagikakkoList to {"「", "」"} –カギカッコ 開始文字、終了文字ペア。英語で言うところのダブルクォート(「“」, 「”」)
set aRes to pairKagikakkoCheckAndReturnPositionPairts(aStr, kagikakkoList) of me
–> {{1, 9}, {16, 21}, {26, 31}, {33, 38}}–正常な場合
–> false –カッコの対応についてエラーがある場合

on pairKagikakkoCheckAndReturnPositionPairts(aStr as string, kagikakkoList as list)
  set aList to {}
  
  
–カギカッコの開始文字、終了文字の位置をシーケンシャルにピックアップする
  
repeat with i in kagikakkoList
    set j to contents of i
    
set aRes to scanStrMultiple(aStr, j) of me
    
set the end of aList to aRes
  end repeat
  
–> {{1, 16, 26, 33}, {9, 21, 31, 38}}
  
  
–カギカッコの個数が合っていないかどうかチェック
  
if length of aList is not equal to length of kagikakkoList then error "Separator number error"
  
  
  
–ペアリスト作成前に、カギカッコの開始、修了の文字の個数が合っているかをチェック
  
set startLen to length of first item of aList
  
set endLen to length of second item of aList
  
if startLen is not equal to endLen then error "Separator pair number is not same"
  
  
  
–ペアリストを作成
  
set pairList to {}
  
repeat with i from 1 to (length of first item of aList)
    set item1Dat to contents of item i of (first item of aList)
    
set item2Dat to contents of item i of (second item of aList)
    
set the end of pairList to {item1Dat, item2Dat}
  end repeat
  
–> {{1, 9}, {16, 21}, {25, 32}, {27, 34}, {35, 40}}
  
  
  
–ペアリストのクロスチェック
  
repeat with i from 1 to ((length of pairList) – 1)
    set {itemA1, itemA2} to contents of item i of pairList
    
set {itemB1, itemB2} to contents of item (i + 1) of pairList
    
    
if itemA1 > itemA2 then return false
    
if itemA1 > itemB1 then return false
    
if itemA2 > itemB1 then return false
  end repeat
  
  
return pairList
end pairKagikakkoCheckAndReturnPositionPairts

on scanStrMultiple(aStr, targStr)
  set aStrLen to length of aStr
  
set tLen to (length of targStr)
  
set posOffset to 0
  
  
copy aStr to bStr
  
set aList to {}
  
  
repeat
    set aRes to offset of targStr in bStr
    
if aRes = 0 then exit repeat
    
    
if aRes is not in aList then
      set the end of aList to (aRes + posOffset)
      
set posOffset to posOffset + aRes
    end if
    
    
if posOffset ≥ aStrLen then exit repeat
    
    
set tPos to (aRes + tLen)
    
if tPos > length of bStr then
      set tPos to length of bStr
    end if
    
    
if (length of bStr) ≤ tLen then exit repeat
    
    
set bStr to text tPos thru -1 of bStr
  end repeat
  
  
return aList
end scanStrMultiple

–offset命令の実行を横取りする
on offset of searchStr in str
  set aRes to getOffset(str, searchStr) of me
  
return aRes
end offset

on getOffset(str, searchStr)
  set d to divideBy(str, searchStr)
  
if (count d) is less than 2 then return 0
  
return (length of item 1 of d) + 1
end getOffset

on divideBy(str, separator)
  set delSave to AppleScript’s text item delimiters
  
set the AppleScript’s text item delimiters to separator
  
set strItems to every text item of str
  
set the AppleScript’s text item delimiters to delSave
  
return strItems
end divideBy

★Click Here to Open This Script 

Posted in Natural Language Processing Text | Tagged 10.15savvy 11.0savvy 12.0savvy | Leave a comment

日本語簡易パーサーeasyJParse v5

Posted on 12月 31, 2020 by Takaaki Naganoya

簡易日本語パーサー「easyJParse」のバージョンアップ版です。AppleScriptライブラリ「BridgePlus」を利用しないように改めました。

簡易日本語パーサーというのは、日本語の文を単語に分解するプログラムですが、品詞情報や係り受けの情報が得られるわけではなく、単に単語に分解するだけのもので、用途を日本語コマンド解釈などに限定した簡易版の形態素解析器もどきソフトウェアです。特定の人名など区切られて困る単語についてはカギ括弧などで括ることで(例:「ぴよまるソフトウェア」)まとまった単語として出力する機能を持たせています。

→ easyJParse v3
→ easyJParse v4

前バージョンまではBridgePlus Script Libraryを利用していましたが、同ライブラリがFrameworkを含んでいるために、確実に動かせるように設定するには技量(理解と慣れ)が必要です。自分の手元では動かせていますが、ユーザーによってはBridgePlusをmacOS 10.15以降のMacで利用できないケースも見られ(たぶん、操作間違い)、BridgePlusへの依存がマイナスポイントになりつつあるように感じられます。

本ScriptでBridgePlusから利用しているメソッドは2つ。どちらも既存のAppleScriptのルーチンの組み合わせで再現できる程度の簡単なもの。これらをすべて既存のルーチンの組み合わせで置き換えました。BridgePlus内蔵の機能を書き換える際に、扱うデータサイズはあまり大きくないものであることを前提に最適化しました。あまり巨大なデータを扱うのには向いていませんが、小さなデータを高速に処理できるようにしてあります。

MacBookPro10,1,  macOS Version 10.14.6 (Build 18G8005),  100 iterations
         First Run   Total Time    Average     Median    Maximum    Minimum   Std.Dev.
First       0.6685       0.6236     0.0062     0.0059     0.0083     0.0054     0.0008

正直なところ、この程度の極小データサイズだとCocoaの機能を利用するメリットがあまりないので、Cocoaを使わないように書き換えると高速化できます。高速化は必要に応じて行う程度でしょう。

外部ライブラリに依存しなくなったため、たとえばCotEditorのメニューから呼び出すScriptや、FileMaker Pro Scriptの中にまるごと日本語パーサーを突っ込むといった真似ができます。

AppleScript名:easyJParse v5.scptd
— Created 2018-09-26 by Takaaki Naganoya
— Modified 2020-12-31 by Takaaki Naganoya
— 2020 Piyomaru Software
use AppleScript version "2.5" — El Capitan (10.11) or later
use framework "Foundation"
use scripting additions

property NSArray : a reference to current application’s NSArray
property NSSortDescriptor : a reference to current application’s NSSortDescriptor

set aTargName to "Finderで選択中のAI書類上の「製品名」レイヤーから抜き出したコードをもとにスペック情報をGoogle Spreadsheet「製品コード表」から展開して保存。"
set aList to parseJ(aTargName, true) of me
–> {"Finder", "で", "選択", "中", "の", "AI", "書類", "上", "の", "「", "製品名", "」", "レイヤー", "から", "抜き出し", "た", "コード", "を", "もと", "に", "スペック", "情報", "を", "Google", " ", "Spreadsheet", "「", "製品コード表", "」", "から", "展開", "し", "て", "保存", "。"}–v4
–> {"Finder", "で", "選択", "中", "の", "AI", "書類", "上", "の", "「", "製品名", "」", "レイヤー", "から", "抜き出し", "た", "コード", "を", "もと", "に", "スペック", "情報", "を", "Google", " ", "Spreadsheet", "「", "製品コード表", "」", "から", "展開", "し", "て", "保存", "。"}–v5

return aList

set aTargName to "私の名前は「長野谷」です。"
set aList to parseJ(aTargName, true) of me
–> {"私", "の", "名前", "は", "「", "長野谷", "」", "です", "。"}–v4
–> {"私", "の", "名前", "は", "「", "長野谷", "」", "です", "。"}–v5

–カッコのネスティングとクロス(エラー)については、処理せずにそのまま出力
on parseJ(aTargStr as string, pickupPhraseByBracketPair as boolean)
  copy aTargStr to tStr
  
  
set cList to characters of tStr
  
set wList to words of tStr
  
  
set cLen to length of cList
  
  
set w2List to {}
  
set w3List to {}
  
set aCount to 0
  
  
set lastPos to 0
  
  
repeat with i in wList
    set j to contents of i
    
    
using terms from scripting additions
      set anOffset to offset of j in tStr
    end using terms from
    
    
if anOffset is not equal to 1 then
      set aChar to character (lastPos + 1) of aTargStr
      
      
set the end of w3List to {wordList:aChar, characterList:{aChar}, startPos:(lastPos + 1), endPos:(lastPos + 1)}
    end if
    
    
set aLen to length of j
    
    
set w2List to w2List & (characters of j)
    
set startPointer to (anOffset + aCount)
    
set endPointer to (anOffset + aCount + aLen – 1)
    
    
set the end of w3List to {wordList:j, characterList:(characters of j), startPos:startPointer, endPos:endPointer}
    
    
set trimStart to (anOffset + aLen)
    
    
if trimStart > (length of tStr) then
      set trimStart to 1
    end if
    
    
set tStr to text trimStart thru -1 of tStr
    
    
set aCount to aCount + anOffset + aLen – 1
    
copy endPointer to lastPos
  end repeat
  
  
–句読点など。文末の処理
  
if endPointer is not equal to cLen then
    set the end of w3List to {wordList:tStr, characterList:(characters of tStr), startPos:(lastPos + aCount), endPos:aLen}
  end if
  
  
set bArray to sortRecListByLabel((w3List), "startPos", true) of me
  
set cArray to (bArray’s valueForKeyPath:"wordList") as list
  
  
–カッコでくくった範囲を1つの塊として連結する
  
set bracketList to {"「", "」", "『", "』", "【", "】", "《", "》", "〈", "〉", "(", ")"}
  
set bList to jointItemsBetweenBrackets(cArray, bracketList) of me
  
  
return bList
end parseJ

–リストに入れたレコードを、指定の属性ラベルの値でソート
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 arrayWithObject:sortDesc
  
set sortedArray to aArray’s sortedArrayUsingDescriptors:sortDescArray
  
return sortedArray
end sortRecListByLabel

on offset of bArg in anArg
  set aClass to class of anArg
  
set bClass to class of bArg
  
  
if {aClass, bClass} = {text, text} then –case 1
    return getOffset(anArg, bArg) of me
  else if {aClass, bClass} = {list, list} then –case 2 (The target case)
    return execOffsetList(bArg, anArg) of me
  else if {aClass, bClass} = {text, list} then –case 3 (Illegular case)
    return execOffsetList(bArg, {anArg}) of me
  else if {aClass, bClass} = {list, text} then –case 4 (Illegular case)
    return execOffsetList({bArg}, anArg) of me
  end if
end offset

–1D List同士のoffset演算を行うルーチンの本体
on execOffsetList(aList as list, bList as list)
  set resList to {}
  
repeat with i in aList
    set j to contents of i
    
set aCount to 1
    
    
repeat with ii in bList
      set jj to contents of ii
      
if jj = j then
        set the end of resList to aCount
        
exit repeat
      end if
      
set aCount to aCount + 1
    end repeat
  end repeat
  
  
–見つかったItem No.が連続値かどうかチェック
  
set sRes to chkSequential(resList) of me
  
if sRes = true then
    return contents of first item of resList
  else
    return false
  end if
end execOffsetList

–与えられた1D Listが連続値かどうかをチェックする
on chkSequential(aList)
  if length of aList = 1 then return true
  
if aList = {} then return false
  
  
set aFirst to first item of aList
  
set aList to rest of aList
  
  
repeat with i in aList
    set j to contents of i
    
if j is not equal to (aFirst + 1) then
      return false
    end if
    
copy j to aFirst
  end repeat
  
  
return true
end chkSequential

–テキスト同士のoffset ofを(2.5x fasterで)実行する
on getOffset(str, searchStr)
  set d to divideBy(str, searchStr)
  
if (count d) is less than 2 then return 0
  
return (length of item 1 of d) + 1
end getOffset

on divideBy(str, separator)
  set delSave to AppleScript’s text item delimiters
  
set the AppleScript’s text item delimiters to separator
  
set strItems to every text item of str
  
set the AppleScript’s text item delimiters to delSave
  
return strItems
end divideBy

–カッコでくくった範囲を1つの塊として連結する
on jointItemsBetweenBrackets(aList as list, bracketList as list)
  
  
  
–リスト内のブラケット位置の検出
  
set aRes to (my indexesOfItems:bracketList inArray:aList base:0) as list
  
–> {9, 12, 15, 18, 22, 25, 27, 29}–0 based
  
  
if aRes = {} then return aList
  
  
–位置情報リストを開始位置, 終了位置のペアの2D Listに変換する
  
set cList to my subarraysFrom:(aRes) groupedBy:2
  
–> {{9, 12}, {15, 18}, {22, 25}, {27, 29}}–0 based
  
  
–カッコの位置がクロスしていないかチェック(入れ子状態はエラーになる)
  
set dRes to checkCrossRange(cList) of me
  
if dRes = false then return aList
  
  
set ccList to reverse of cList –順次、ブラケットに囲まれた要素を連結していくので、アイテム数が随時変化する。アイテム番号が狂わないよう後方から処理する必要がある。そのために、リストの要素を逆順に組み替える
  
–> {{27, 29}, {22, 25}, {15, 18}, {9, 12}}–0 based
  
  
—
  
copy aList to aaList
  
  
repeat with i in ccList
    copy i to {s2Dat, e2Dat}
    
    
set s2Dat to s2Dat + 1 –Array index conversion from 0 to 1 based
    
set e2Dat to e2Dat + 1 –Array index conversion from 0 to 1 based
    
    
set tmp1 to items 1 thru s2Dat of aaList
    
set tmp2 to (items (s2Dat + 1) thru (e2Dat – 1) of aaList) as string
    
set tmp3 to items e2Dat thru -1 of aaList
    
    
set aaList to tmp1 & tmp2 & tmp3
  end repeat
  
  
return aaList
end jointItemsBetweenBrackets

–{始点, 終点}のペアの2D Listが違いにクロスしていないかチェック
on checkCrossRange(aList as list)
  set rList to {}
  
repeat with i in aList
    copy i to {sRange, eRange}
    
set tmpRange to current application’s NSMakeRange(sRange, eRange – sRange + 1)
    
set the end of rList to tmpRange
  end repeat
  
  
repeat with ii in rList
    set jj to contents of ii
    
repeat with i in rList
      set j to contents of i
      
      
if jj is not equal to j then
        set aRes to current application’s NSIntersectionRange(jj, j)
        
        
if aRes is not equal to {location:0, |length|:0} then
          return false
        end if
      end if
      
    end repeat
  end repeat
  
  
return true
end checkCrossRange

–BridgePlus内の命令を展開
on indexesOfItems:(iList as list) inArray:(aList as list) base:(baseNum as integer)
  return retIndexesOfNumInArray(iList, aList, baseNum) of me
end indexesOfItems:inArray:base:

–1Dリスト中のシーケンシャルサーチ(複数)
on retIndexesOfNumInArray(aTargetList, aList, baseNum)
  script obj
    property list : aList
    
property resList : {}
  end script
  
  
if baseNum is not in {0, 1} then return false
  
  
–set obj’s list to aList
  
set (resList of obj) to {}
  
set aCount to baseNum
  
set hitF to false
  
  
repeat with i in obj’s list
    set j to contents of i
    
if j is in aTargetList then
      set the end of (resList of obj) to aCount
    end if
    
    
set aCount to aCount + 1
  end repeat
  
  
return (resList of obj)
end retIndexesOfNumInArray

on subarraysFrom:(aList as list) groupedBy:(gNum as integer)
  script spdObj
    property list : aList
    
property bList : {}
  end script
  
  
  
–Group Num check
  
if gNum = 0 then return false
  
if length of aList < gNum then return false
  
  
if (length of aList) mod gNum is not equal to 0 then return
  
  
set (bList of spdObj) to {}
  
  
set tmpList to {}
  
set aCount to 1
  
  
repeat with i in aList
    set j to contents of i
    
set the end of tmpList to j
    
set aCount to aCount + 1
    
    
if aCount > gNum then
      set the end of (bList of spdObj) to tmpList
      
set tmpList to {}
      
set aCount to 1
    end if
  end repeat
  
  
return (bList of spdObj)
end subarraysFrom:groupedBy:

★Click Here to Open This Script 

Posted in Natural Language Processing Text | Tagged 10.13savvy 10.14savvy 10.15savvy 11.0savvy | Leave a comment

common elements Libをロシア語などのクエリーで呼び出す

Posted on 3月 3, 2020 by Takaaki Naganoya

WikipediaのREST APIを呼び出して、2つの単語の共通項を計算する「common elements Lib」を作って実際にいろいろ評価していますが、ロシア語を指定したときに結果が得られないという現象に直面していました。

ロシア語を記述するキリル文字のエンコーディング指定がよくなかったのか、Wikipediaのロシア語サーバーの問題なのか、どこに問題点があるのかよくわかっていませんでした(そういう問題のあぶり出しのためにリリースしてみた事情があります)。

とりあえず人名をGoogle翻訳でロシア語+キリル文字に翻訳してロシア語Wikipediaに突っ込んでみても結果が得られず首をひねっていましたが、ロシア語の人名表記が、

First name Family name

ではなく、

Family name, First name

のフォーマットであることに気づきました。この語順で人名を突っ込んでみたところ、無事結果が得られることを確認しました。

AppleScript名:sample_russian
—
–  Created by: Takaaki Naganoya
–  Created on: 2020/03/03
—
–  Copyright © 2020 Piyomaru Software, All Rights Reserved
—

use comLib : script "common elements Lib"

–"Family Name, First Name" in Russian Language

–"George Lucas" and "Steven Spielberg"
set cRes to list up common elements with {"Лукас, Джордж", "Спилберг, Стивен"} with language "ru"
–> {"Награда имени Ирвинга Тальберга", "Индиана Джонс", "Кинофантастика", "Золотой глобус", "Монтажёр", "Industrial Light & Magic", "Форд, Харрисон", "DreamWorks", "Премия «Сатурн» за лучший сценарий", "Сиквел", "Продюсер", "Кинорежиссёр", "Калифорния", "Сценарист", "Премия «Сатурн» за лучшую режиссуру", "Оскар (кинопремия)"}

–"Larry Tesler" and "Steve Jobs"
set dRes to list up common elements with {"Теслер, Ларри ", "Джобс, Стив"} with language "ru"
–> {"Apple Computer", "Xerox PARC", "Smalltalk", "Стэнфордский университет"}

★Click Here to Open This Script 

ウクライナ語の人名は、

First name Family name

となっているので、そのように書けば結果が得られます。登録記事数がそれほど多くないので、かなり検索語句を選ぶ印象ではあります。

AppleScript名:sample_Ukrainian
–Українська (Ukrainian)
use comLib : script "common elements Lib"

–"Bill Gates" and "Steve Jobs"
set dRes to list up common elements with {"Білл Гейтс", "Стів Джобс"} with language "uk"
–> {"США", "IBM", "Долар США", "Майкрософт", "Головний виконавчий директор", "Стенфордський університет", "Персональний комп’ютер"}

★Click Here to Open This Script 

Posted in Natural Language Processing REST API Script Libraries | Tagged 10.10savvy 10.12savvy 10.13savvy 10.14savvy 10.15savvy | 1 Comment

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 

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

自然言語テキストから複数の日付情報を抽出

Posted on 1月 21, 2020 by Takaaki Naganoya

自然言語テキストから日付の情報(複数可)を抽出するAppleScriptです。

URLやメールアドレスの抽出では、複数のデータをNSDataDetectorで抽出するAppleScriptは書いてありましたが、日付情報の抽出を行うものはなかったので、書いておきました。

AppleScript名:自然言語テキストから複数の日付情報(複数)を抽出して日付のリストを返す.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2020/01/21
—
–  Copyright © 2020 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use scripting additions

set theDate to getDatesIn("本テキストには次の火曜日という日付情報を含んでいる。明日かもしれない。次の木曜日もそうだ。") of me
–> {date "2020年1月28日 火曜日 12:00:00", date "2020年1月22日 水曜日 12:00:00", date "2020年1月23日 木曜日 12:00:00"}

set theDate to getDatesIn("This text contains next Tuesday. The date may be tomorrow. Next Wednesday happen.") of me
–> {date "2020年1月28日 火曜日 12:00:00", date "2020年1月22日 水曜日 12:00:00", date "2020年1月29日 水曜日 12:00:00"}

on getDatesIn(aString)
  set anNSString to current application’s NSString’s stringWithString:aString
  
set theDetector to current application’s NSDataDetector’s dataDetectorWithTypes:(current application’s NSTextCheckingTypeDate) |error|:(missing value)
  
set theMatchs to theDetector’s matchesInString:anNSString options:0 range:{0, anNSString’s |length|()}
  
if theMatchs = missing value then error "No date found with String:" & aString
  
set dRes to theMatchs’s valueForKeyPath:"date"
  
return dRes as list
end getDatesIn

★Click Here to Open This Script 

AppleScript名:自然言語テキストから複数の日付情報(複数)を抽出して日付と当該箇所のリストを返す v2.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2020/01/21
—
–  Copyright © 2020 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4" — Yosemite (10.10) or later
use framework "Foundation"
use scripting additions

set theDate to getDatesAndOrigStringsIn("本テキストには次の火曜日という日付情報を含んでいる。明日かもしれない。次の木曜日もそうだ。") of me
–> {{originalStr:"次の火曜日", detectDate:date "2020年1月28日 火曜日 12:00:00"}, {originalStr:"明日", detectDate:date "2020年1月22日 水曜日 12:00:00"}, {originalStr:"次の木曜日", detectDate:date "2020年1月23日 木曜日 12:00:00"}}

set theDate to getDatesAndOrigStringsIn("This text contains next Tuesday. The date may be tomorrow. Next Wednesday happen.") of me
–> {{originalStr:"next Tuesday", detectDate:date "2020年1月28日 火曜日 12:00:00"}, {originalStr:"tomorrow", detectDate:date "2020年1月22日 水曜日 12:00:00"}, {originalStr:"Next Wednesday", detectDate:date "2020年1月29日 水曜日 12:00:00"}}

on getDatesAndOrigStringsIn(aString)
  set anNSString to current application’s NSString’s stringWithString:aString
  
set theDetector to current application’s NSDataDetector’s dataDetectorWithTypes:(current application’s NSTextCheckingTypeDate) |error|:(missing value)
  
set theMatchs to theDetector’s matchesInString:anNSString options:0 range:{0, anNSString’s |length|()}
  
if theMatchs = missing value then error "No date found with String:" & aString
  
set dRes to (theMatchs’s valueForKeyPath:"date") as list
  
set rRes to (theMatchs’s valueForKeyPath:"range") as list
  
  
set allRes to {}
  
set aLen to length of dRes
  
repeat with i from 1 to aLen
    set aSubStr to (anNSString’s substringWithRange:(item i of rRes))
    
set dDate to contents of item i of dRes
    
set the end of allRes to {originalStr:aSubStr as string, detectDate:dDate}
  end repeat
  
  
return allRes
end getDatesAndOrigStringsIn

★Click Here to Open This Script 

Posted in Calendar Natural Language Processing | Tagged 10.12savvy 10.13savvy 10.14savvy 10.15savvy NSDataDetector NSString | Leave a comment

CotEditorの最前面のドキュメントの選択範囲を伏せ字に

Posted on 10月 22, 2019 by Takaaki Naganoya

CotEditorの最前面のドキュメントの選択範囲を、簡易形態素解析ルーチンeasyJparseを用いて、いい感じに伏せ字にするAppleScriptです。

–> Download makeSelectionToFuseji(Code-Signed AppleScript applet with libraries in its bundle, co-work with CotEditor)

easyJparseは日本語のコマンド解析用にでっちあげた作った超簡易形態素解析プログラムです。単語(形態素)ごとに分割しますが、品詞まではわかりません。コマンド解釈用ではあるものの、少し他の用途にも使えないかと思い、このような用途に使ってみました。

# 本Scriptは、CotEditor用のScript Pack v2.0に収録されています


▲CotEditorの選択範囲を伏せ字にする。形態素解析して単語化して、単語単位で伏せ字にするかの判断を実行

テキストエディタ上で伏せ字処理というのは、個人的によく使います。たいていは、オリジナルの文章に対して同様の分量の文章を作らなくてはならないようなケースで、文字数の感覚をつかむために使います。一種のダミーレイアウトのようなものです。

本スクリプトのような伏せ字処理については、ニーズがあるんだかないんだか不明なものですが、とりあえず掲載してみました。自分で使ってみたところ、たしかに面白いものの、実用性については未知数という印象です。

(minusList of parseSPD) に入れている語群は、どこかからか拾ってきたもののようではあるものの、すでに何か方向性を見失っているような気がしないではありません。

AppleScript名:選択範囲を伏せ字に(簡易形態素解析でそれっぽく).scptd
— Created 2018-09-26 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.5" — El Capitan (10.11) or later
use framework "Foundation"
use scripting additions
use jParser : script "easyJParse"

property NSArray : a reference to current application’s NSArray
property NSMutableSet : a reference to current application’s NSMutableSet
property NSSortDescriptor : a reference to current application’s NSSortDescriptor

property fuesejiChar : "□"

script parseSPD
  property pList : {}
  
property p2List : {}
  
property oneLine : {}
  
property outStr : ""
  
property minusList : {}
end script

–伏せ字化しない助詞などの単語リスト。名詞だけを残すように整備。単語(形態素)単位で照合する
set (minusList of parseSPD) to {"", " ", "ー", "あ", "で", "も", "に", "と", "の", "は", "へ", "さ", "が", "せ", "か", "た", "だ", "だっ", "ば", "つ", "な", "い", "き", "お", "ら", "る", "れ", "なっ", "それ", "これ", "あれ", "どれ", "この", "どの", "あの", "その", "まで", "こと", "もの", "いつ", "いく", "たち", "ただ", "たい", "そう", "いる", "よう", "れる", "ない", "なら", "なる", "なけれ", "から", "する", "たら", "たり", "だけ", "って", "られ", "的", "化", "いくら", "そんな", "どんな", "あんな", "者", "陰", "時", "事", "こんな", "つれ", "けど", "ああ", "ある", "あっ", "あり", "しかし", "きっと", "すっかり", "例えば", "たとえば", "さっぱり", "たとえ", "だろう", "かつ", "ところ", "まるで", "だが", "全て", "すべて", "なり", "いい", "つれ", "つけ", "ながら", "せいぜい", "そうそう", "さらに", "もっと", "まだ", "なく", "し", "を", "て", "いけ", "行く", "また", "まま", "まぁ", "『", "』", "、", "。", "。。", "……。", "【", "】", "「", "」", "(", ")", "最近", "今度", "中", "チカチカ", "グラグラ", "ふわふわ", "少し", "ついで", "より", "っぽい", "ぐらい", "何", "とき", "ため", "そっくり", "そして", "やがて", "じきに", "すぐ", "今", "次", "できる", "出来る", "いや", "そう", "おそらく", "いえ", "らしい", "とも", "ほぼ", "つい", "もう", "きっかけ", "ころ", "頃", "早々", "そこ", "どこ", "なんか", "じゃ", "くれ", "ください", "こそ", "あいつ", "だれ", "誰", "おぼしき", "らしき", "らしい", "しか", "でき", "よっ", "確か", "どう", "こう", "そう", "ああ", "くる", "ざま", "ごとく", "きれ", "はず", "さらに", "さらなる", "更なる", "など", "ごと", "とても", "たく", "いう", "とっ", "いっ", "えっ", "おっ", "ここ", "そこ", "どこ", "なかっ", "ごく", "やる", "ゆい", "ふと", "たび", "ほど", "もた", "よし", "ぜひ", "いら", "よい", "ま", "み", "む", "め", "も", "や", "けれど", "だけど", "したがっ", "すごく", "そもそも", "ほしい", "なれる", "すぎ", "もふもふ", "モフモフ", "さん", "おと", "とー", "えっと", "け", "っけ", "なん", "よ", "ね", "しっくり", "くれる", "くれた", "なぜ", "まあ", "まぁ", "ん", "なんて", "!」"}

set (pList of parseSPD) to {}
set (p2List of parseSPD) to {}
set (oneLine of parseSPD) to {}
set (outStr of parseSPD) to {}

tell application "CotEditor"
  tell front document
    –選択部分が存在しているかどうかチェック
    
set aCon to contents of selection
    
if aCon = "" then return
    
    
set (pList of parseSPD) to paragraphs of aCon
  end tell
end tell

–伏せ字にする対象単語を、助詞などを消し込むことでピックアップ
repeat with i in (pList of parseSPD)
  if length of i > 1 then
    –簡易形態素解析
    
set tempList to parseJ(i) of jParser
    
    
–簡易形態素解析したリストと助詞などのリストの差分を計算
    
set cList to clacListDiff(tempList, (minusList of parseSPD)) of me
    
    
set (oneLine of parseSPD) to {}
    
repeat with ii in tempList
      set aLen to length of ii
      
if ii is in cList then
        –伏せ字化する場合
        
set bCon to multipleChar(fuesejiChar, aLen) of me
        
      else
        –そのまま出力する場合
        
set bCon to contents of ii
      end if
      
set the end of (oneLine of parseSPD) to bCon
    end repeat
    
    
–1つの文章ぶんの単語を連結
    
set cStr to retDelimedText((oneLine of parseSPD), "") of me
  else
    set cStr to ""
  end if
  
  
set the end of (p2List of parseSPD) to cStr
  
end repeat

–すべての文章を連結して配列からテキストに
set (outStr of parseSPD) to retDelimedText((p2List of parseSPD), return) of me

tell application "CotEditor"
  tell front document
    set contents of selection to (outStr of parseSPD)
  end tell
end tell

–指定文字を指定回数繰り返して連結して出力
on multipleChar(aChar as string, aLen as integer)
  set aList to {}
  
repeat aLen times
    set the end of aList to aChar
  end repeat
  
  
return retDelimedText(aList, "") of me
end multipleChar

–1D Listを要素間に指定デリミタをはさんで文字列化
on retDelimedText(aList as list, aDelim as string)
  set aText to ""
  
set curDelim to AppleScript’s text item delimiters
  
set AppleScript’s text item delimiters to aDelim
  
set aText to aList as text
  
set AppleScript’s text item delimiters to curDelim
  
return aText
end retDelimedText

–2つの1D Listの差分を計算
on clacListDiff(aList as list, bList as list)
  set aSet to NSMutableSet’s setWithArray:aList
  
set bSet to NSMutableSet’s setWithArray:bList
  
  
aSet’s minusSet:bSet –補集合
  
set aRes to aSet’s allObjects() as list
  
  
return aRes
end clacListDiff

★Click Here to Open This Script 

Posted in list Natural Language Processing Text | Tagged 10.12savvy 10.13savvy 10.14savvy 10.15savvy CotEditor NSArray NSMutableSet NSSortDescriptor | 1 Comment

頭のいいタイマー割り込み実行

Posted on 3月 27, 2019 by Takaaki Naganoya

頭のいいタイマー割り込み(on idle)実行のAppleScriptを追求してみました。

AppleScript開闢(かいびゃく)以来、すでに20年以上の時間が経過しているので、on idleによるタイマー割り込み処理なんて、探せばサンプルが山のように出てくるものです。

AppleScript名:timer interrupt
property targetTime : "9:37:00"
property timerInterval : 30

on run
  set timerInterval to 30
end run

on idle
  set curTime to current date
  
set cString to time string of curTime
  
  
if cString ≥ targetTime then
    display dialog "It’s time to take off!" buttons {"OK"} default button 1 giving up after 30
    
quit
  end if
  
  
return timerInterval
end idle

★Click Here to Open This Script 

これが基礎的な内容で、このScriptをScript Editor上でアプリケーション(アプレット)形式で、「ハンドラの実行後に終了しない」をオンにして書き出すとタイマー実行アプレットが出来上がります(3分間クッキング)。

ただ、実行時刻のパラメータがプログラム内に直打ちなのが気になります。知能レベルが低い感じがします。

そこで、実行時刻のパラメータの外部供給ということを考え出すわけですが、

 (1)設定ファイルから読み込み
 (2)アプレット自身のコメント(File Comment)から読み込み
 (3)ファイル名自体から読み込み
 (4)コマンドラインから実行し、実行時にパラメータ(argv)を指定

などの方法を考えつきます(20世紀にすでにさんざんやった内容)。ただし、全角数字を半角に変換したり、ファイル名の場合には時刻セパレータの「:」がmacOS上ではファイル名に使えない文字(ディレクトリ・セパレータ)だったり、Finderが管理しているファイル名はUnicodeのNormalize方式が異なる(処理しやすいようにNormalizeし直さないとダメ)など割と頭の痛い問題がいろいろあります。

そこで利用したいのが、CocoaのDataFormatter。自然言語風に書かれた「10時41分」(全角数字入り)といった文字列から日時データをピックアップします。

そうして書いたのがこれ(↓)です。

ファイル名に書かれた時刻から実行時刻を拾ってタイマー実行します。けっこう頭がいい感じがします。

実際に、こうした処理の延長線上にTanzakuで行なっているファイル名から取得した文字列に対する形態素解析&コマンドピックアップの処理があります。

AppleScript名:10時42分
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"

property targTime : missing value
property timerInterval : 1

on run
  set timerInterval to 1
  
  
–Get filename from this applet
  
set myPath to path to current application
  
tell application "System Events"
    set myName to name of myPath
  end tell
  
  
–Validate filename as a natural language format date by using NSDataDetector
  
set dList to getDatesIn(myName) of me
  
repeat while dList = {}
    set myName to text returned of (display dialog "There is no time elements in my filename. Input the target time in x時xx分" default answer "午後5時45分")
    
set dList to getDatesIn(myName) of me
  end repeat
  
  
set targDate to first item of dList
  
set targTime to time string of targDate
  
display notification targTime
end run

on idle
  set curTime to current date
  
set curTimeStr to time string of curTime
  
  
if curTimeStr ≥ targTime then
    activate
    
display dialog "It’s time to take off!" buttons {"OK"} default button 1 giving up after 30
    
quit
  end if
  
  
return timerInterval
end idle

on getDatesIn(aString)
  set anNSString to current application’s NSString’s stringWithString:aString
  
set {theDetector, theError} to current application’s NSDataDetector’s dataDetectorWithTypes:(current application’s NSTextCheckingTypeDate) |error|:(reference)
  
set theMatches to theDetector’s matchesInString:anNSString options:0 range:{0, anNSString’s |length|()}
  
set theResults to theMatches’s valueForKey:"date"
  
return theResults as list
end getDatesIn

★Click Here to Open This Script 

Posted in File path Natural Language Processing | Tagged 10.11savvy 10.12savvy 10.13savvy 10.14savvy NSDataDetector NSString | Leave a comment

住所録から苗字を抽出して1文字以上の苗字をリスト出力

Posted on 12月 20, 2018 by Takaaki Naganoya

固有名詞を抽出するために、住所録から苗字を抽出して1文字以上の長さの苗字をリスト出力するAppleScriptです。

簡易形態素解析を行うさいに、みのまわりの人物の苗字を認識してくれないと知性を感じられないため(例:”長野”,”谷”)、逆に住所録に登録があるぐらい身の回りの人物の苗字を固有名詞として認識してくれるよう、住所録から苗字を抽出させてみました。

抽出した苗字は、missing valueが返ってきたものを除去し、重複を排除し、文字列長でソートして長いものから短いものへと並べ替え。

さらに、文字種別を判定して漢字のみで構成されているものを抽出。さらに、1文字の苗字を排除。

こうして得られたリストの先頭に自分の苗字を入れて、真っ先に自分の名前が認識されるようにしてみました。

住所録へのアクセスは、macOS標準装備の「連絡先.app」にアクセスしてみました。最近はmacOS標準装備のFrameworkにアクセスしてこの手のデータを取得していたりしましたが、その際に利用していたAddressBook.frameworkが廃止になる見込みであるため、新設されたContacts.frameworkを使ったほうが好ましいところです。

ただ、Contacts.frameworkの各種メソッドはObjective-CのBlocks構文の記述を必要とするため、AppleScriptからそのまま呼び出すことができません。

そのため、連絡先.app(Contacts.app)にアクセスすることになった次第です。

固有名詞抽出については、簡易形態素解析を実行するたびに実行するのではなく、1日に1回ぐらいの頻度で実行すればよいと考えています。

AppleScript名:住所録から苗字を抽出して1文字以上の苗字をリスト出力
—
–  Created by: Takaaki Naganoya
–  Created on: 2018/12/20
—
–  Copyright © 2018 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use bPlus : script "BridgePlus"

property NSString : a reference to current application’s NSString
property NSScanner : a reference to current application’s NSScanner
property NSNumber : a reference to current application’s NSNumber
property NSDictionary : a reference to current application’s NSDictionary
property NSCountedSet : a reference to current application’s NSCountedSet
property NSCharacterSet : a reference to current application’s NSCharacterSet
property NSMutableArray : a reference to current application’s NSMutableArray
property NSNumberFormatter : a reference to current application’s NSNumberFormatter
property NSMutableCharacterSet : a reference to current application’s NSMutableCharacterSet
property NSRegularExpressionSearch : a reference to current application’s NSRegularExpressionSearch
property NSNumberFormatterRoundUp : a reference to current application’s NSNumberFormatterRoundUp
property NSStringTransformFullwidthToHalfwidth : a reference to current application’s NSStringTransformFullwidthToHalfwidth

tell application "Contacts"
  set lastNames to last name of every person
  
set myName to last name of my card
end tell

load framework

–Remove missing value (Cleaning)
set aList to (current application’s SMSForder’s arrayByDeletingBlanksIn:(lastNames)) as list

–重複部分の削除
set bList to makeUniqueListFrom(aList) of me

–文字列長でソート。長い文字列→短い文字列
set cList to sort1DListByStringLength(bList, false) of me –降順

–文字種別を判定して漢字のみから構成されるものを抽出し、1文字のものを除外
set dList to {}
repeat with i in cList
  set j to contents of i
  
set tmpPat to retAtrPatternFromStr(j) of me
  
if tmpPat is equal to "漢" then
    –1文字以上の苗字のみ出力
    
if length of j > 1 then
      set the end of dList to j
    end if
  end if
end repeat

set the beginning of dList to myName
return dList
–> {"長野谷", "久保田", "三津田", "小笠原", "上田平", "大久保", "長谷川", "長野谷", "伊賀", "伊勢","伊東", "伊藤", "井上", "稲葉" …}

–Objective-Cライクなパラメータ記述
on makeUniqueListOf:theList
  set theSet to current application’s NSOrderedSet’s orderedSetWithArray:theList
  
return (theSet’s array()) as list
end makeUniqueListOf:

–Pure AS風のパラメータ記述
on makeUniqueListFrom(theList)
  set aList to my makeUniqueListOf:theList
  
return aList
end makeUniqueListFrom

–1D Listを文字列長でソート v2
on sort1DListByStringLength(aList as list, sortOrder as boolean)
  set aArray to current application’s NSArray’s arrayWithArray:aList
  
set desc1 to current application’s NSSortDescriptor’s sortDescriptorWithKey:"length" ascending:sortOrder
  
set desc2 to current application’s NSSortDescriptor’s sortDescriptorWithKey:"self" ascending:true selector:"localizedCaseInsensitiveCompare:"
  
set bArray to aArray’s sortedArrayUsingDescriptors:{desc1, desc2}
  
return bArray as list of string or string
end sort1DListByStringLength

–文字種別の判定
on retAtrPatternFromStr(aText)
  set a1List to {"100000", "010000", "001000", "000100", "000010", "000001"}
  
set b1List to {"9", "A", "$", "漢", "あ", "ア"} –数字、アルファベット、記号、全角漢字、全角ひらがな、全角カタカナ
  
set aDict to NSDictionary’s dictionaryWithObjects:b1List forKeys:a1List
  
  
set aStr to NSString’s stringWithString:aText
  
set bStr to aStr’s stringByDeletingPathExtension()
  
set cStr to zenToHan(bStr) of me
  
  
set outList to {}
  
set cList to characters of cStr
  
  
repeat with i in cList
    set j to contents of i
    
set chk1 to ((my chkNumeric:j) as integer) as string
    
set chk2 to ((my chkAlphabet:j) as integer) as string
    
set chk3 to ((my chkSymbol:j) as integer) as string
    
set chk4 to ((my chkKanji:j) as integer) as string
    
set chk5 to ((my chkHiragana:j) as integer) as string
    
set chk6 to ((my chkKatakana:j) as integer) as string
    
    
set allKey to (chk1 & chk2 & chk3 & chk4 & chk5 & chk6) as string
    
set aVal to (aDict’s valueForKeyPath:allKey) as string
    
    
if aVal is not in outList then
      set the end of outList to aVal
    end if
  end repeat
  
  
return outList as string
end retAtrPatternFromStr

–全角→半角変換
on zenToHan(aStr)
  set aString to NSString’s stringWithString:aStr
  
return (aString’s stringByApplyingTransform:(NSStringTransformFullwidthToHalfwidth) |reverse|:false) as string
end zenToHan

–数字か
on chkNumeric:checkString
  set digitCharSet to NSCharacterSet’s characterSetWithCharactersInString:"0123456789"
  
set ret to my chkCompareString:checkString baseString:digitCharSet
  
return ret as boolean
end chkNumeric:

–記号か
on chkSymbol:checkString
  set muCharSet to NSCharacterSet’s alloc()’s init()
  
muCharSet’s addCharactersInString:"$\"!~&=#[]._-+`|{}?%^*/’@-/:;(),"
  
set ret to my chkCompareString:checkString baseString:muCharSet
  
return ret as boolean
end chkSymbol:

–漢字か
on chkKanji:aChar
  return detectCharKind(aChar, "[一-龠]") of me
end chkKanji:

–ひらがなか
on chkHiragana:aChar
  return detectCharKind(aChar, "[ぁ-ん]") of me
end chkHiragana:

–カタカナか
on chkKatakana:aChar
  return detectCharKind(aChar, "[ァ-ヶ]") of me
end chkKatakana:

–半角スペースか
on chkSpace:checkString
  set muCharSet to NSCharacterSet’s alloc()’s init()
  
muCharSet’s addCharactersInString:" " –半角スペース(20h)
  
set ret to my chkCompareString:checkString baseString:muCharSet
  
return ret as boolean
end chkSpace:

— アルファベットか
on chkAlphabet:checkString
  set aStr to NSString’s stringWithString:checkString
  
set allCharSet to NSMutableCharacterSet’s alloc()’s init()
  
allCharSet’s addCharactersInRange:(current application’s NSMakeRange(id of "a", 26))
  
allCharSet’s addCharactersInRange:(current application’s NSMakeRange(id of "A", 26))
  
set aBool to my chkCompareString:aStr baseString:allCharSet
  
return aBool as boolean
end chkAlphabet:

on chkCompareString:checkString baseString:baseString
  set aScanner to NSScanner’s localizedScannerWithString:checkString
  
aScanner’s setCharactersToBeSkipped:(missing value)
  
aScanner’s scanCharactersFromSet:baseString intoString:(missing value)
  
return (aScanner’s isAtEnd()) as boolean
end chkCompareString:baseString:

on detectCharKind(aChar, aPattern)
  set aChar to NSString’s stringWithString:aChar
  
set searchStr to NSString’s stringWithString:aPattern
  
set matchRes to aChar’s rangeOfString:searchStr options:(NSRegularExpressionSearch)
  
if matchRes’s location() = (current application’s NSNotFound) or (matchRes’s location() as number) > 9.99999999E+8 then
    return false
  else
    return true
  end if
end detectCharKind

★Click Here to Open This Script 

Posted in list Natural Language Processing Record Sort | Tagged 10.11savvy 10.12savvy 10.13savvy 10.14savvy Contacts | Leave a comment

easyJParse v4

Posted on 12月 14, 2018 by Takaaki Naganoya

簡易的な日本語テキストのParse(辞書なし)を行うAppleScriptです。

詳細な説明はこちら。

本バージョンでは、かっこ( “「”, “」”, “『”, “』”, “【”, “】”, “《”, “》”, “〈”, “〉”, “(”, “))で区切られた文字列を区分けしないで1かたまりで出力させたものです。

コマンド解釈用に作成した本Script、パラメーターとして区分けしてほしくない情報(フィールド情報やデータベース名など)をかたまりのまま出力する必要があって、そのように処理させてみました。

かっこがクロスしたりネスティング(入れ子)していることは検出していますが、そのまま連結せずに出力しています。

このプログラムを作ったことにより、固有名詞への対応のメドが立ちました。

前処理で何かの記号で固有名詞を囲えばいいんじゃないか、などと思っています。何を固有名詞とするか、ということになりますが、とりあえず住所録(Contacts.app)から人名(Last Name)や会社名をすべて出力させるのがよいだろうか、といったところです。

AppleScript名:easyJParse v4(かぎかっこ内の単語を1つの単語としてみなす)
— Created 2018-09-26 by Takaaki Naganoya
— Modified 2018-12-14 by Takaaki Naganoya
— 2018 Piyomaru Software
use AppleScript version "2.5" — El Capitan (10.11) or later
use framework "Foundation"
use scripting additions
use bPlus : script "BridgePlus" –https://www.macosxautomation.com/applescript/apps/BridgePlus.html

property NSArray : a reference to current application’s NSArray
property NSSortDescriptor : a reference to current application’s NSSortDescriptor

load framework
set aTargName to "曲のアーティスト名を変更"
–set aTargName to "<満喜子>さんの実家から半径300メートル以内にあるコンビニを取得"
–set aTargName to "Finderで選択中のAI書類上の「製品名」レイヤーから抜き出したコードをもとにスペック情報をGoogle Spreadsheet「製品コード表」から展開して保存。"
set aList to parseJ(aTargName, true) of me
–> {"Finder", "で", "選択", "中", "の", "AI", "書類", "上", "の", "「", "製品名", "」", "レイヤー", "から", "抜き出し", "た", "コード", "を", "もと", "に", "スペック", "情報", "を", "Google", " ", "Spreadsheet", "「", "製品コード表", "」", "から", "展開", "し", "て", "保存", "。"}
return aList

set aTargName to "私の名前は「長野谷」です。"
set aList to parseJ(aTargName, true) of me
–> {"私", "の", "名前", "は", "「", "長野谷", "」", "です", "。"}

–カッコのネスティングとクロス(エラー)については、処理せずにそのまま出力
on parseJ(aTargStr as string, pickupPhraseByBracketPair as boolean)
  copy aTargStr to tStr
  
  
set cList to characters of tStr
  
set wList to words of tStr
  
  
set cLen to length of cList
  
  
set w2List to {}
  
set w3List to {}
  
set aCount to 0
  
  
set lastPos to 0
  
  
repeat with i in wList
    set j to contents of i
    
    
using terms from scripting additions
      set anOffset to offset of j in tStr
    end using terms from
    
    
if anOffset is not equal to 1 then
      set aChar to character (lastPos + 1) of aTargStr
      
      
set the end of w3List to {wordList:aChar, characterList:{aChar}, startPos:(lastPos + 1), endPos:(lastPos + 1)}
    end if
    
    
set aLen to length of j
    
    
set w2List to w2List & (characters of j)
    
set startPointer to (anOffset + aCount)
    
set endPointer to (anOffset + aCount + aLen – 1)
    
    
set the end of w3List to {wordList:j, characterList:(characters of j), startPos:startPointer, endPos:endPointer}
    
    
set trimStart to (anOffset + aLen)
    
    
if trimStart > (length of tStr) then
      set trimStart to 1
    end if
    
    
set tStr to text trimStart thru -1 of tStr
    
    
set aCount to aCount + anOffset + aLen – 1
    
copy endPointer to lastPos
  end repeat
  
  
–句読点など。文末の処理
  
if endPointer is not equal to cLen then
    set the end of w3List to {wordList:tStr, characterList:(characters of tStr), startPos:(lastPos + aCount), endPos:aLen}
  end if
  
  
set bArray to sortRecListByLabel((w3List), "startPos", true) of me
  
set cArray to (bArray’s valueForKeyPath:"wordList") as list
  
  
–カッコでくくった範囲を1つの塊として連結する
  
set bracketList to {"「", "」", "『", "』", "【", "】", "《", "》", "〈", "〉", "(", ")"}
  
set bList to jointItemsBetweenBrackets(cArray, bracketList) of me
  
  
return bList
end parseJ

–リストに入れたレコードを、指定の属性ラベルの値でソート
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 arrayWithObject:sortDesc
  
set sortedArray to aArray’s sortedArrayUsingDescriptors:sortDescArray
  
return sortedArray
end sortRecListByLabel

on offset of bArg in anArg
  set aClass to class of anArg
  
set bClass to class of bArg
  
  
if {aClass, bClass} = {text, text} then –case 1
    return getOffset(anArg, bArg) of me
  else if {aClass, bClass} = {list, list} then –case 2 (The target case)
    return execOffsetList(bArg, anArg) of me
  else if {aClass, bClass} = {text, list} then –case 3 (Illegular case)
    return execOffsetList(bArg, {anArg}) of me
  else if {aClass, bClass} = {list, text} then –case 4 (Illegular case)
    return execOffsetList({bArg}, anArg) of me
  end if
end offset

–1D List同士のoffset演算を行うルーチンの本体
on execOffsetList(aList as list, bList as list)
  set resList to {}
  
repeat with i in aList
    set j to contents of i
    
set aCount to 1
    
    
repeat with ii in bList
      set jj to contents of ii
      
if jj = j then
        set the end of resList to aCount
        
exit repeat
      end if
      
set aCount to aCount + 1
    end repeat
  end repeat
  
  
–見つかったItem No.が連続値かどうかチェック
  
set sRes to chkSequential(resList) of me
  
if sRes = true then
    return contents of first item of resList
  else
    return false
  end if
end execOffsetList

–与えられた1D Listが連続値かどうかをチェックする
on chkSequential(aList)
  if length of aList = 1 then return true
  
if aList = {} then return false
  
  
set aFirst to first item of aList
  
set aList to rest of aList
  
  
repeat with i in aList
    set j to contents of i
    
if j is not equal to (aFirst + 1) then
      return false
    end if
    
copy j to aFirst
  end repeat
  
  
return true
end chkSequential

–テキスト同士のoffset ofを(2.5x fasterで)実行する
on getOffset(str, searchStr)
  set d to divideBy(str, searchStr)
  
if (count d) is less than 2 then return 0
  
return (length of item 1 of d) + 1
end getOffset

on divideBy(str, separator)
  set delSave to AppleScript’s text item delimiters
  
set the AppleScript’s text item delimiters to separator
  
set strItems to every text item of str
  
set the AppleScript’s text item delimiters to delSave
  
return strItems
end divideBy

–カッコでくくった範囲を1つの塊として連結する
on jointItemsBetweenBrackets(aList as list, bracketList as list)
  load framework
  
  
–リスト内のブラケット位置の検出
  
set aRes to (current application’s SMSForder’s indexesOfItems:bracketList inArray:aList inverting:false) as list
  
–> {9, 12, 15, 18, 22, 25, 27, 29}–0 based
  
  
if aRes = {} then return aList
  
  
–位置情報リストを開始位置, 終了位置のペアの2D Listに変換する
  
set cList to (current application’s SMSForder’s subarraysFrom:(aRes) groupedBy:2 |error|:(missing value)) as list
  
–> {{9, 12}, {15, 18}, {22, 25}, {27, 29}}–0 based
  
  
–カッコの位置がクロスしていないかチェック(入れ子状態はエラーになる)
  
set dRes to checkCrossRange(cList) of me
  
if dRes = false then return aList
  
  
set ccList to reverse of cList –順次、ブラケットに囲まれた要素を連結していくので、アイテム数が随時変化する。アイテム番号が狂わないよう後方から処理する必要がある。そのために、リストの要素を逆順に組み替える
  
–> {{27, 29}, {22, 25}, {15, 18}, {9, 12}}–0 based
  
  
—
  
copy aList to aaList
  
  
repeat with i in ccList
    copy i to {s2Dat, e2Dat}
    
    
set s2Dat to s2Dat + 1 –Array index conversion from 0 to 1 based
    
set e2Dat to e2Dat + 1 –Array index conversion from 0 to 1 based
    
    
set tmp1 to items 1 thru s2Dat of aaList
    
set tmp2 to (items (s2Dat + 1) thru (e2Dat – 1) of aaList) as string
    
set tmp3 to items e2Dat thru -1 of aaList
    
    
set aaList to tmp1 & tmp2 & tmp3
  end repeat
  
  
return aaList
end jointItemsBetweenBrackets

–{始点, 終点}のペアの2D Listが違いにクロスしていないかチェック
on checkCrossRange(aList as list)
  set rList to {}
  
repeat with i in aList
    copy i to {sRange, eRange}
    
set tmpRange to current application’s NSMakeRange(sRange, eRange – sRange + 1)
    
set the end of rList to tmpRange
  end repeat
  
  
repeat with ii in rList
    set jj to contents of ii
    
repeat with i in rList
      set j to contents of i
      
      
if jj is not equal to j then
        set aRes to current application’s NSIntersectionRange(jj, j)
        
        
if aRes is not equal to {location:0, |length|:0} then
          return false
        end if
      end if
      
    end repeat
  end repeat
  
  
return true
end checkCrossRange

★Click Here to Open This Script 

Posted in list Natural Language Processing Text | Tagged 10.11savvy 10.12savvy 10.13savvy 10.14savvy 10.15savvy 11.0savvy | 1 Comment

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

Post navigation

  • Older posts

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

Google Search

Popular posts

  • 開発機としてM2 Mac miniが来たのでガチレビュー
  • CotEditorで2つの書類の行単位での差分検出
  • macOS 15, Sequoia
  • 指定のWordファイルをPDFに書き出す
  • Pages本執筆中に、2つの書類モード切り替えに気がついた
  • Numbersで選択範囲のセルの前後の空白を削除
  • メキシカンハットの描画
  • Pixelmator Pro v3.6.4でAppleScriptからの操作時の挙動に違和感が
  • AdobeがInDesign v19.4からPOSIX pathを採用
  • AppleScriptによる並列処理
  • Safariで「プロファイル」機能を使うとAppleScriptの処理に影響
  • Cocoa Scripting Course 続刊計画
  • macOS 14.xでScript Menuの実行速度が大幅に下がるバグ
  • AppleScript入門③AppleScriptを使った「自動化」とは?
  • NaturalLanguage.frameworkでNLEmbeddingの処理が可能な言語をチェック
  • Keynote/Pagesで選択中の表カラムの幅を均等割
  • Keynote、Pages、Numbers Ver.14.0が登場
  • macOS 15 リモートApple Eventsにバグ?
  • デフォルトインストールされたフォント名を取得するAppleScript
  • AppleScript入門① AppleScriptってなんだろう?

Tags

10.11savvy (1101) 10.12savvy (1242) 10.13savvy (1391) 10.14savvy (587) 10.15savvy (438) 11.0savvy (283) 12.0savvy (212) 13.0savvy (193) 14.0savvy (145) 15.0savvy (127) CotEditor (66) Finder (51) iTunes (19) Keynote (116) 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 (54) 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年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