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

カテゴリー: Text

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

Posted on 2月 26 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 

(Visited 18 times, 2 visits today)
Posted in Natural Language Processing REST API Text | Tagged 12.0savvy 13.0savvy ChatGPT | Leave a comment

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

Posted on 2月 26 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 

(Visited 15 times, 1 visits today)
Posted in Natural Language Processing REST API Text | Tagged 12.0savvy 13.0savvy ChatGPT | Leave a comment

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

Posted on 2月 26 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 

(Visited 34 times, 4 visits today)
Posted in Natural Language Processing REST API Text | Tagged 12.0savvy 13.0savvy ChatGPT | Leave a comment

Keynoteの表の選択中のセルのデータをDeepLで翻訳して書き戻す

Posted on 1月 31 by Takaaki Naganoya

Keynoteの最前面の書類中の、現在表示中のスライドの表の選択中のセル中のテキストを取得してDeepLのREST APIを呼び出して指定言語に翻訳し、表のセルに翻訳後のテキストを書き戻すAppleScriptです。

DeepLのREST API呼び出しのためには、DeepL SE社のWebサイトで「DeepL API Free」(無料コース)か「DeepL API Pro」プランにサインアップして、API Keyを取得して、プログラムリスト中に記入したうえで実行してください。


▲実行前。Keynote書類上の表の翻訳対象のセルを選択して実行


▲実行後。Keynote書類上の表の翻訳対象のセルをに翻訳後の内容をストア

実際に使ってみると、けっこう翻訳に時間がかかるのと、一度翻訳した同じフレーズを再度翻訳させるのはコストがかかるため、ローカルに「翻訳キャッシュ」を作って、翻訳ずみの内容を再翻訳しないように工夫する必要がありそうです。

AppleScript名:Keynoteの表の選択中のセルのデータをDeepLで翻訳して書き戻す.scpt
—
–  Created by: Takaaki Naganoya
–  Created on: 2023/01/30
—
–  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 myAPIKey to "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
set myTargLang to "EN" –翻訳ターゲット言語

set aTableDat to returnSelectedTableCellDataOnCurrentSlide() of me
–> {"プロパティ項目", "データ型", "読み/書き", "内容(サンプル)", "説明"}

set nList to {}
repeat with i in aTableDat
  set j to contents of i
  
set tRes to translateWithDeepL(j, myAPIKey, myTargLang) of me
  
set the end of nList to tRes
end repeat

–表に翻訳した内容を書き戻す
storeSelectedTableCellDataOnCurrentSlide(nList) of me

on storeSelectedTableCellDataOnCurrentSlide(sList)
  tell application "Keynote"
    tell front document
      tell current slide
        try
          set theTable to first table whose class of selection range is range
        on error
          return false –何も選択されてなかった場合
        end try
        
        
tell theTable
          set cList to every cell of selection range
          
if (length of cList) is not equal to (length of sList) then error
          
          
set aCount to 1
          
repeat with i in cList
            set j to contents of i
            
tell j
              set value of it to (contents of item aCount of sList)
            end tell
            
set aCount to aCount + 1
          end repeat
        end tell
      end tell
    end tell
  end tell
end storeSelectedTableCellDataOnCurrentSlide

on returnSelectedTableCellDataOnCurrentSlide()
  tell application "Keynote"
    tell front document
      tell current slide
        try
          set theTable to first table whose class of selection range is range
        on error
          return false –何も選択されてなかった場合
        end try
        
        
tell theTable
          set vList to value of every cell of selection range
          
set cCount to count of column of selection range
          
set rCount to count of row of selection range
          
          
–複数行選択されていた場合にはエラーを返すなどの処理の布石
          
return vList
        end tell
      end tell
    end tell
  end tell
end returnSelectedTableCellDataOnCurrentSlide

–DeepLのAPIを呼び出して翻訳する
on translateWithDeepL(myText, myAPIKey, myTargLang)
  set sText to "curl -X POST ’https://api-free.deepl.com/v2/translate’ -H ’Authorization: DeepL-Auth-Key " & myAPIKey & "’ -d ’text=" & myText & "’ -d ’target_lang=" & myTargLang & "’"
  
try
    set sRes to do shell script sText
  on error
    error
  end try
  
  
set jsonString to NSString’s stringWithString:sRes
  
set jsonData to jsonString’s dataUsingEncoding:(NSUTF8StringEncoding)
  
set aJsonDict to NSJSONSerialization’s JSONObjectWithData:jsonData options:0 |error|:(missing value)
  
  
set tRes to aJsonDict’s valueForKeyPath:"translations.text"
  
if tRes = missing value then
    set erMes to (aJsonDict’s valueForKey:"message") as string
    
error erMes
  else
    return contents of first item of (tRes as list)
  end if
end translateWithDeepL

★Click Here to Open This Script 

(Visited 19 times, 1 visits today)
Posted in REST API shell script Text | Tagged 12.0savvy 13.0savvy | Leave a comment

HexDump to BASIC

Posted on 1月 9 by Takaaki Naganoya

これも同じく、8bitコンピュータ時代のクロスアセンブラが出力していたダンプリストを、BASICのPOKE文に展開して出力するという、20〜30年前の仕様のテキスト変換を行うために作ったものです。

CotEditorでオープン中のダンプリストのテキストの変換対象行を選択しておいた状態で実行すると、変換したリストを新規書類に出力します。

AppleScript名:HexDump to BASIC.scpt
—
–  Created by: Takaaki Naganoya
–  Created on: 2023/01/09
—
–  Copyright © 2023 Piyomaru Software, All Rights Reserved
—

tell application "CotEditor"
  tell front document
    set aaSel to paragraphs of contents of selection
  end tell
end tell

set sNum to 100
set allText to ""
repeat with i in aaSel
  set tmpL to ""
  
  
set bList to words of i
  
set aStr to retOnLineBasicPoke(bList) of me
  
set allText to allText & ((sNum as string) & ": ") & aStr & return
  
set sNum to sNum + 1
end repeat

tell application "CotEditor"
  set newDoc to make new document
  
tell newDoc
    set contents of it to allText
  end tell
end tell

on retOnLineBasicPoke(aList)
  set addrStr to first item of aList
  
set aList to rest of aList
  
set aaList to items 1 thru 8 of aList
  
  
set aStr to "POKE #0, &" & addrStr & ", "
  
repeat with i in aaList
    set j to contents of i
    
set aStr to aStr & "&" & j & ", "
  end repeat
  
  
return text 1 thru -3 of aStr
end retOnLineBasicPoke

★Click Here to Open This Script 

(Visited 31 times, 1 visits today)
Posted in Text | Tagged 13.0savvy CotEditor | Leave a comment

Intel Hexa to BASIC

Posted on 1月 9 by Takaaki Naganoya

これ、8bitコンピュータ時代のクロスアセンブラが出力していたIntel Hexaフォーマットのダンプリスト(EPROMライター向けの出力フォーマットらしい)を、BASICのPOKE文に展開して出力するという、20〜30年前の仕様のテキスト変換を行うために作ったものです。

CotEditorでオープン中のIntel Hexaのテキストの変換対象行を選択しておいた状態で実行すると、変換したリストを新規書類に出力します。

汎用性は一切ないのですが、実際にさまざまな本を作る際に、こうした「ちょっとしたツール」を作るのと作らないのとでは生産性が段違いです。

ただ、元データと最終成果物を示すと途中のロジックをプログラム側で考えて出力してくれるといいのに、とは思います。

AppleScript名:Intel Hexa to BASIC.scpt
—
–  Created by: Takaaki Naganoya
–  Created on: 2023/01/09
—
–  Copyright © 2023 Piyomaru Software, All Rights Reserved
—

use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

tell application "CotEditor"
  tell front document
    set aaSel to paragraphs of contents of selection
  end tell
end tell

set sNum to 100
set allText to ""
repeat with i in aaSel
  set tmpL to ""
  
set j to contents of i
  
set {addrStr, hexList} to procOneLine(j) of me
  
set aStr to retOnLineBasicPoke(addrStr, hexList) of me
  
set allText to allText & ((sNum as string) & " ") & aStr & return
  
set sNum to sNum + 1
end repeat

tell application "CotEditor"
  set newDoc to make new document
  
tell newDoc
    set contents of it to allText
  end tell
end tell

on retOnLineBasicPoke(addrStr, aList)
  set aStr to "POKE #0, &" & addrStr & ", "
  
repeat with i in aList
    set j to contents of i
    
set aStr to aStr & "&" & j & ", "
  end repeat
  
  
return text 1 thru -3 of aStr
end retOnLineBasicPoke

on procOneLine(a)
  set fChar to first character of a
  
if fChar is not equal to ":" then error
  
  
set byteC to text 2 thru 3 of a
  
set byteNum to retIntFromHexString(byteC) of me
  
  
set addrStr to text 4 thru 7 of a
  
  
set hList to {}
  
repeat with i from 10 to (10 + (2 * (byteNum – 1))) by 2
    set tmpStr to text i thru (i + 1) of a
    
set the end of hList to tmpStr
  end repeat
  
return {addrStr, hList}
end procOneLine

on retIntFromHexString(aHex as string)
  set {aRes, hexRes} to (current application’s NSScanner’s scannerWithString:aHex)’s scanHexInt:(reference)
  
if aRes = false then
    return "" –エラーの場合
  else
    return hexRes
  end if
end retIntFromHexString

★Click Here to Open This Script 

(Visited 27 times, 1 visits today)
Posted in Text | Tagged 13.0savvy CotEditor | Leave a comment

macOS 13でNSNotFoundバグふたたび

Posted on 12月 1, 2022 by Takaaki Naganoya

また、Appleがやらかしてくれたようです。あの会社はNSNotFoundの定義値を何回間違えたら気が済むんでしょうか。これで通算4回目ぐらいです。macOS 10.12で発生し10.13.1で修正された定義値のミスをまたやったわけで、失敗がまったく生かされていない。大したものです。

今回のバグは、文字列の検索処理を行っているときに発見しました。指定文字列から対象文字列の登場位置と長さをリストで返す処理を行っていたところ、NSRangeからlocationを取得したときに、これ以上見つからない場所まで来たときにNSNotFoundを返すことを期待されるわけですが、そこに前回(macOS 10.12…10.13)と同様のおかしな値を返してきました。

この(↓)AppleScriptをmacOS 13上で実行すると、エラーになります。

追記:macOS 13.1でもエラーになります。

AppleScript名:テキストのキーワード検索(結果をNSRangeのlistで返す).scptd
— Created 2017-08-09 by Takaaki Naganoya
— 2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
–http://piyocast.com/as/archives/4771

property NSString : a reference to current application’s NSString
property NSMutableArray : a reference to current application’s NSMutableArray
property NSLiteralSearch : a reference to current application’s NSLiteralSearch

set aStr to "ATGC ACGT ATGC AGTC
ATGC ACGT ATGC AGTC
ATGC ACGT ATGC AGTC
ATGC ACGT ATGC AGTC
"

set aRes to searchWordRanges(aStr, "ATGC") of me as list
–>  {​​​​​{​​​​​​​location:0, ​​​​​​​length:4​​​​​}, ​​​​​{​​​​​​​location:10, ​​​​​​​length:4​​​​​}, ​​​​​{​​​​​​​location:20, ​​​​​​​length:4​​​​​}, ​​​​​{​​​​​​​location:30, ​​​​​​​length:4​​​​​}, ​​​​​{​​​​​​​location:40, ​​​​​​​length:4​​​​​}, ​​​​​{​​​​​​​location:50, ​​​​​​​length:4​​​​​}, ​​​​​{​​​​​​​location:60, ​​​​​​​length:4​​​​​}, ​​​​​{​​​​​​​location:70, ​​​​​​​length:4​​​​​}​​​}

on searchWordRanges(aTargText as string, aSearchStr as string)
  set aStr to NSString’s stringWithString:aTargText
  
set bStr to NSString’s stringWithString:aSearchStr
  
  
set hitArray to NSMutableArray’s alloc()’s init()
  
set cNum to (aStr’s |length|()) as integer
  
  
set aRange to current application’s NSMakeRange(0, cNum)
  
  
repeat
    set detectedRange to aStr’s rangeOfString:bStr options:(NSLiteralSearch) range:aRange
    
set aLoc to detectedRange’s location
    
log aLoc
    
if (detectedRange’s location) is equal to (current application’s NSNotFound) then exit repeat
    
    
hitArray’s addObject:detectedRange
    
    
set aNum to (detectedRange’s location) as number
    
set bNum to (detectedRange’s |length|) as number
    
    
set aRange to current application’s NSMakeRange(aNum + bNum, cNum – (aNum + bNum))
  end repeat
  
  
return hitArray
end searchWordRanges

★Click Here to Open This Script 

症状も前回とまったく同じなので、対処も前回と同じです。Appleは定期的にNSNotFoundの定義値を間違えるトンでもない会社なので(計測された事実)、NSNotFoundまわりはAppleがバグをやらかすことを前提に書いておくべきなんでしょう。

AppleScript名:テキストのキーワード検索(結果をNSRangeのlistで返す)v2.scptd
— Created 2017-08-09 by Takaaki Naganoya
— Modified 2022-12-01 by Takaaki Naganoya
— 2022 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

property NSString : a reference to current application’s NSString
property NSMutableArray : a reference to current application’s NSMutableArray
property NSLiteralSearch : a reference to current application’s NSLiteralSearch

set aStr to "ATGC ACGT ATGC AGTC
ATGC ACGT ATGC AGTC
ATGC ACGT ATGC AGTC
ATGC ACGT ATGC AGTC
"

set aRes to searchWordRanges(aStr, "ATGC") of me as list
–>  {​​​​​{​​​​​​​location:0, ​​​​​​​length:4​​​​​}, ​​​​​{​​​​​​​location:10, ​​​​​​​length:4​​​​​}, ​​​​​{​​​​​​​location:20, ​​​​​​​length:4​​​​​}, ​​​​​{​​​​​​​location:30, ​​​​​​​length:4​​​​​}, ​​​​​{​​​​​​​location:40, ​​​​​​​length:4​​​​​}, ​​​​​{​​​​​​​location:50, ​​​​​​​length:4​​​​​}, ​​​​​{​​​​​​​location:60, ​​​​​​​length:4​​​​​}, ​​​​​{​​​​​​​location:70, ​​​​​​​length:4​​​​​}​​​}
–> {{location:0, |length|:4}, {location:10, |length|:4}, {location:20, |length|:4}, {location:30, |length|:4}, {location:40, |length|:4}, {location:50, |length|:4}, {location:60, |length|:4}, {location:70, |length|:4}}

on searchWordRanges(aTargText as string, aSearchStr as string)
  set aStr to NSString’s stringWithString:aTargText
  
set bStr to NSString’s stringWithString:aSearchStr
  
  
set hitArray to NSMutableArray’s alloc()’s init()
  
set cNum to (aStr’s |length|()) as integer
  
  
set aRange to current application’s NSMakeRange(0, cNum)
  
  
repeat
    set detectedRange to aStr’s rangeOfString:bStr options:(NSLiteralSearch) range:aRange
    
set aLoc to detectedRange’s location
    
    
–macOS 13でAppleが新たに作ったバグを回避
    
if (aLoc > 9.999999999E+9) or (aLoc = current application’s NSNotFound) then exit repeat
    
    
hitArray’s addObject:detectedRange
    
    
set aNum to (detectedRange’s location) as number
    
set bNum to (detectedRange’s |length|) as number
    
    
set aRange to current application’s NSMakeRange(aNum + bNum, cNum – (aNum + bNum))
  end repeat
  
  
return hitArray
end searchWordRanges

★Click Here to Open This Script 

(Visited 54 times, 2 visits today)
Posted in Bug list Text | Tagged 13.0savvy NSLiteralSearch NSMakeRange NSMutableArray NSNotFound NSRange NSString | Leave a comment

Keynote書類のdefault title item部分に入った改行コードを除去する

Posted on 10月 9, 2022 by Takaaki Naganoya

Keynote v12.1書類の現在のスライドにあるdefault title itemに入っている改行コード(?)を除去するAppleScriptです。

結論から言うと、これが改行コード(LFとかCRとか)ではなく、Unicode特殊文字の「LINE SEPARATOR」(U+2028)であることが、データをhexdumpしてわかりました(AppleScript書いてるだけなのに、hexdumpのお世話になることの多いこと、多いこと)。なので、文字コードをUTF-16(AppleScript側の文字コード)で指定して置換を行なっています。

# AppleScriptのネイティブ文字コードはUTF-16BEです

Keynote書類の各Slideに存在しているdefault title itemから文字列(object text)を取得し、改行コードを除去する処理を行います。

AppleScript名:default title item部分に入った改行コードを除去する.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2022/10/09
—
–  Copyright © 2022 Piyomaru Software, All Rights Reserved
—

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

tell application "Keynote"
  tell front document
    tell current slide
      set jj to object text of default title item
      
      
–https://www.fileformat.info/info/unicode/char/2028/index.htm
      
–Unicode Character ’LINE SEPARATOR’ (U+2028)
      
–UTF-16 (decimal)  8,232
      
set kk to repCharByID(jj, 8232, "") of me
      
log kk
      
    end tell
  end tell
end tell

–文字置換
on repCharByID(origText as string, targCharID as number, repChar as string)
  set targChar to string id targCharID
  
set curDelim to AppleScript’s text item delimiters
  
set AppleScript’s text item delimiters to targChar
  
set tmpList to text items of origText
  
set AppleScript’s text item delimiters to repChar
  
set retText to tmpList as string
  
set AppleScript’s text item delimiters to curDelim
  
return retText
end repCharByID

★Click Here to Open This Script 

(Visited 28 times, 1 visits today)
Posted in Text | Tagged 12.0savvy Keynote | Leave a comment

AS関連データの取り扱いを容易にする(はずの)privateDataTypeLib

Posted on 8月 22, 2022 by Takaaki Naganoya

AS関連データの取り扱いを簡単にすることを目的に書き出した、privateDatatypeLibです。

プログラムとデータを分離して、データ記述部分を外部ファイル(設定ファイルなど)に追い出したときに、どのようなデータかを表現するための道具として試作してみました。

macOS上のデータ記述子は、

などのさまざまなデータ識別方法が存在していますが、どれも(自分の)用途には合わなかったので、検討・試作をはじめてみました。Predicatesが一番近いものの、不十分なのでいろんなデータ型や用途に拡張。あくまで自分用なので「public」などの宣言はとくに不必要と考え、縮小して処理を行なっています。

とくに、ファイルパスの処理なんて定型処理しかしないのに、わざわざ何かの表現を行う必要があるのはナンセンスですし、日付関連も割と余計な記述が多いように感じています。

また、緯度/経度のデータや座標データなども、もう少しなんとかならないかと思っています。

AppleScript名:privateDataTypeLib.scptd
—
–  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 aData to "100"
set dType to "@number"
set bData to "" –不要なケース多数。不要な場合にはヌル文字を指定
set mePath to path to me –実際には、呼び出し側で取得して指定。ライブラリ自体のパスを求めているのはテスト実行時のみ
set aRes to getParameterAndCalc(aData, dType, bData, mePath) of me

on getParameterAndCalc(aData, dType, bData, mePath)
  if dType = "@string" then
    return normalizeByNFC(aData) of me
    
  else if dType = "@number" then
    set tmpA to zenToHan(aData) of charConvKit of me –全角→半角変換
    
set a to detectOutNumStr(tmpA) of me –数字+関連・意外の文字を除外
    
return normalizeByNFC(a) of me
    
  else if dType = "@filepath.sub.foldername" then
    set aClass to class of aData –aliasだったらPOSIX pathに変換。file…はどうなんだか
    
if aClass = alias then set aData to POSIX path of aData
    
return aData & bData & "/"
    
  else if dType = "@file.comment" then
    set aStr to getFinderComment(POSIX path of mePath) of me
    
return normalizeByNFC(aStr) of me
    
  else if dType = "@file.name" then
    set aClass to class of aData
    
if aClass = alias then set aData to POSIX path of aData
    
set aStr to (current application’s NSString’s stringWithString:aData)’s lastPathComponent()’s stringByDeletingPathExtension()
    
return normalizeByNFC(aStr as string) of me
    
  else if dType = "@date.month" then
    set curDate to current date
    
set curMonth to month of curDate as number
    
return curMonth as string
    
  else
    return aData
  end if
end getParameterAndCalc

on normalizeByNFC(aStr)
  set aNSStr to current application’s NSString’s stringWithString:aStr
  
set aNFC to aNSStr’s precomposedStringWithCanonicalMapping()
  
return aNFC as string
end normalizeByNFC

–ANK文字列以外のものをそぎ落とす
on detectOutNumStr(testStr)
  set sList to characters of testStr
  
set aStr to ""
  
  
repeat with i in sList
    if detectOutNumChar(i) of me then
      set aStr to aStr & (i as string)
    end if
  end repeat
  
  
return aStr
end detectOutNumStr

on detectOutNumChar(testText)
  –Numeric + Special char
  
set ankChar to {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ".", "-", "+", "E", ","}
  
  
set _testChar to testText as Unicode text
  
  
ignoring case
    repeat with i in _testChar
      set j to contents of i
      
if j is not in ankChar then
        return false
      end if
    end repeat
  end ignoring
  
  
return true
end detectOutNumChar

–Finderコメントを取得
on getFinderComment(aPOSIX)
  set aURL to current application’s |NSURL|’s fileURLWithPath:aPOSIX
  
set aMetaInfo to current application’s NSMetadataItem’s alloc()’s initWithURL:aURL
  
set metaDict to (aMetaInfo’s valuesForAttributes:{"kMDItemFinderComment"}) as record
  
if metaDict = {} then return ""
  
set aComment to kMDItemFinderComment of (metaDict)
  
return aComment
end getFinderComment

script charConvKit
  — Created 2017-09-06 by Shane Stanley
  
— Modified 2017-09-06 by Takaaki Naganoya
  
use AppleScript
  
use framework "Foundation"
  
property parent : AppleScript
  
  
property NSString : a reference to current application’s NSString
  
property NSStringTransformFullwidthToHalfwidth : a reference to current application’s NSStringTransformFullwidthToHalfwidth
  
property NSStringTransformHiraganaToKatakana : a reference to current application’s NSStringTransformHiraganaToKatakana
  
property NSStringTransformLatinToHiragana : a reference to current application’s NSStringTransformLatinToHiragana
  
property NSStringTransformLatinToKatakana : a reference to current application’s NSStringTransformLatinToKatakana
  
property NSStringTransformToUnicodeName : a reference to current application’s NSStringTransformToUnicodeName
  
property NSStringTransformToXMLHex : a reference to current application’s NSStringTransformToXMLHex
  
  
–半角→全角変換
  
on hanToZen(aStr)
    set aString to NSString’s stringWithString:aStr
    
return (aString’s stringByApplyingTransform:(NSStringTransformFullwidthToHalfwidth) |reverse|:true) as string
  end hanToZen
  
  
–全角→半角変換
  
on zenToHan(aStr)
    set aString to NSString’s stringWithString:aStr
    
return (aString’s stringByApplyingTransform:(NSStringTransformFullwidthToHalfwidth) |reverse|:false) as string
  end zenToHan
  
  
–ひらがな→カタカナ変換
  
on hiraganaToKatakana(aStr)
    set aString to NSString’s stringWithString:aStr
    
return (aString’s stringByApplyingTransform:(NSStringTransformHiraganaToKatakana) |reverse|:false) as string
  end hiraganaToKatakana
  
  
–カタカナ→ひらがな変換
  
on katakanaToHiraganaTo(aStr)
    set aString to NSString’s stringWithString:aStr
    
return (aString’s stringByApplyingTransform:(NSStringTransformHiraganaToKatakana) |reverse|:true) as string
  end katakanaToHiraganaTo
  
  
–ローマ字→ひらがな変換
  
on alphabetToHiragana(aStr)
    set aString to NSString’s stringWithString:aStr
    
return (aString’s stringByApplyingTransform:(NSStringTransformLatinToHiragana) |reverse|:false) as string
  end alphabetToHiragana
  
  
–ひらがな→ローマ字変換
  
on hiraganaToalphabet(aStr)
    set aString to NSString’s stringWithString:aStr
    
return (aString’s stringByApplyingTransform:(NSStringTransformLatinToHiragana) |reverse|:true) as string
  end hiraganaToalphabet
  
  
–ローマ字→カタカナ変換
  
on alphabetToKatakana(aStr)
    set aString to NSString’s stringWithString:aStr
    
return (aString’s stringByApplyingTransform:(NSStringTransformLatinToKatakana) |reverse|:false) as string
  end alphabetToKatakana
  
  
–カタカナ→ローマ字変換
  
on katakanaToAlphabet(aStr)
    set aString to NSString’s stringWithString:aStr
    
return (aString’s stringByApplyingTransform:(NSStringTransformLatinToKatakana) |reverse|:true) as string
  end katakanaToAlphabet
  
  
–文字→Unicode Name変換
  
on characterToUnicodeName(aStr)
    set aString to NSString’s stringWithString:aStr
    
return (aString’s stringByApplyingTransform:(NSStringTransformToUnicodeName) |reverse|:false) as string
  end characterToUnicodeName
  
  
–Unicode Name→文字変換
  
on unicodeNameToCharacter(aStr)
    set aString to NSString’s stringWithString:aStr
    
return (aString’s stringByApplyingTransform:(NSStringTransformToUnicodeName) |reverse|:true) as string
  end unicodeNameToCharacter
  
  
–文字→XML Hex変換
  
on stringToXMLHex(aStr)
    set aString to NSString’s stringWithString:aStr
    
return (aString’s stringByApplyingTransform:(NSStringTransformToXMLHex) |reverse|:false) as string
  end stringToXMLHex
  
  
–XML Hex→文字変換
  
on xmlHexTostring(aStr)
    set aString to NSString’s stringWithString:aStr
    
return (aString’s stringByApplyingTransform:(NSStringTransformToXMLHex) |reverse|:true) as string
  end xmlHexTostring
end script

★Click Here to Open This Script 

(Visited 63 times, 1 visits today)
Posted in Calendar file File path folder Library Number Text URL | Tagged 10.14savvy 10.15savvy 11.0savvy 12.0savvy | 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 

(Visited 30 times, 1 visits today)
Posted in Natural Language Processing Text | Tagged 10.15savvy 11.0savvy 12.0savvy | Leave a comment

Keynoteの表で選択中のセルの文字列長さを一覧表で表示

Posted on 7月 4, 2022 by Takaaki Naganoya

Keynoteの最前面の書類で表示中のスライド中の表で、選択中の各セルの内容の文字列の長さを表インタフェースで一覧表示するAppleScriptです。

こんなKeynote書類上の表があったとして、その選択中の各セルに入っている文字列の長さを、AppleScriptライブラリ「display table by list」を用いて一覧表示します。実行には同ライブラリのインストールが必要です。

実行の前提として、Keynoteで書類をオープンしてあり、書類上の表の集計対象のセルを選択しておくことが必要です。

文字列長と元の文字列を一覧表示します。

AppleScript名:Keynoteの表で選択中のセルの文字列長さを一覧表で表示.scpt
—
–  Created by: Takaaki Naganoya
–  Created on: 2022/07/04
—
–  Copyright © 2022 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.5" — El Capitan (10.11) or later
use framework "Foundation"
use scripting additions
use easyTable : script "display table by list"

tell application "Keynote"
  tell front document
    tell current slide
      try
        set theTable to first table whose class of selection range is range
      on error
        display notification "Numbers: There is no selection"
        
return
      end try
      
      
tell theTable
        set aRes to value of cells of selection range
      end tell
    end tell
  end tell
end tell

set fLabels to {"文字列長", "文字列"}

set newList to {}
repeat with i in aRes
  set j to contents of i
  
if j is not equal to missing value then
    set aLen to length of j
    
set the end of newList to {aLen, j}
  end if
end repeat

tell current application
  set aRes to (display table by list newList main message "テキストの文字列長" sub message "Keynoteの表で選択中のテキストの各セルの文字列長" size {800, 400} labels fLabels icon "")
end tell

★Click Here to Open This Script 

(Visited 44 times, 1 visits today)
Posted in list Text | Tagged 10.15savvy 11.0savvy 12.0savvy Keynote | 1 Comment

Keynoteの最前面の書類で表示中のスライドで選択中の表の指定行のテキストのセルの文字列長の分布を計算

Posted on 7月 4, 2022 by Takaaki Naganoya

Keynoteの最前面の書類で表示中のスライド(ページ)で選択中の表の、指定行のテキストのセルの文字列長の分布をグラフ出力するAppleScriptです。

# Blogの英訳本の企画を動かしていますが、たしかに日本語のタイトルを(日本人が)見てもけっこうわかりにくいのかも?
# タイトルをGoogle翻訳に突っ込むと、それなりに「そんな感じじゃね?」という英語が出てきますが、、、

こういう、電子書籍の紹介文を掲載しているページがあって、そこに書いてある紹介文の長さの分布を計算してみるために、ありものの部品を組み合わせて作ったものです。

「だいたい3行ぐらい」というふんわりとしたルールのもとに18冊分ほど書いてきましたが、本の冊数が増えてページを追加するにあたって、文字列長の分布を計算してみようと思い立ってScriptを書いてみました。

043 #
044 ##
045 
046 ###
047 
048 ##
049 ###
050 #
051 #
052 #
053 
054 #
055 
056 #
057 #
058 
059 
060 
061 
062 
063 
064 
065 
066 
067 
068 #

分布はわかりましたが、似たような処理を行うことが多いので、何か簡単なGUIをつけておいたほうがいいような気がするような、、、

AppleScript名:選択中の表のデータを取得して、特定の行のデータの文字列長を集計.scpt
—
–  Created by: Takaaki Naganoya
–  Created on: 2022/07/04
—
–  Copyright © 2022 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"

property NSMutableArray : a reference to current application’s NSMutableArray

set aList to get2DListFromKeynoteTableSelection() of me
if aList = "" then return false

–取得した各セルの文字列長をすべて取得する
set aLen to length of aList
set aaLen to length of item 1 of aList

set nList to {}
repeat with i from 3 to (aLen) by 3
  repeat with ii from 1 to aaLen
    set the end of nList to length of (contents of item ii of item i of aList)
  end repeat
end repeat

–文字列長の度数分布を計算
set minRes to calcMin(nList) of me
set maxRes to calcMax(nList) of me

set itemCount to maxRes – minRes
set n2List to makeBlankListByItem(itemCount + 1, 0) of me

repeat with i in nList
  set j to contents of i
  
set tmpNum to contents of item (j – minRes + 1) of n2List
  
set tmpNum to tmpNum + 1
  
set item (j – minRes + 1) of n2List to tmpNum
end repeat

–文字列長の度数分布のグラフを文字出力
set tList to {}
set aCount to minRes

repeat with i in n2List
  set gText to returnRepeatedText(i, "#") of me
  
set tNumStr to makeFN(aCount, 3) of me
  
set totalText to tNumStr & " " & gText
  
set the end of tList to totalText
  
set aCount to aCount + 1
end repeat

return retArrowText(tList, return) of me

–リストを任意のデリミタ付きでテキストに
on retArrowText(aList, aDelim)
  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 retArrowText

on returnRepeatedText(aNum, aChar)
  set aText to ""
  
repeat aNum times
    set aText to aText & aChar
  end repeat
  
return aText
end returnRepeatedText

on makeBlankListByItem(itemNum, blankItem)
  set tmpList to {}
  
repeat itemNum times
    set the end of tmpList to blankItem
  end repeat
  
return tmpList
end makeBlankListByItem

on calcMin(aList as list)
  set tmpFItem to first item of aList
  
set aClass to class of tmpFItem
  
  
set nArray to (NSMutableArray’s arrayWithArray:aList)
  
if aClass = real then
    set maxRes to (nArray’s valueForKeyPath:"@min.self")’s doubeValue()
  else
    set maxRes to (nArray’s valueForKeyPath:"@min.self")’s intValue()
  end if
  
  
return maxRes
end calcMin

on calcMax(aList as list)
  set tmpFItem to first item of aList
  
set aClass to class of tmpFItem
  
  
set nArray to (NSMutableArray’s arrayWithArray:aList)
  
if aClass = real then
    set maxRes to (nArray’s valueForKeyPath:"@max.self")’s doubeValue()
  else
    set maxRes to (nArray’s valueForKeyPath:"@max.self")’s intValue()
  end if
  
  
return maxRes
end calcMax

on makeFN(aNum, aDigit)
  set aText to "00000000000" & (aNum as text)
  
set aLen to length of aText
  
set aRes to text (aLen – aDigit + 1) thru -1 of aText
  
return aRes
end makeFN

–Keynoteで選択中の表のすべてのセルのデータを2Dで返す
on get2DListFromKeynoteTableSelection()
  tell application "Keynote"
    tell front document
      tell current slide
        try
          set theTable to first table whose class of selection range is range
        on error
          return "" –何も選択されてなかった場合
        end try
        
        
tell theTable
          set selList to value of every cell –すべてののデータを取得
          
set selHeight to count every row
          
set selWidth to count every column
          
        end tell
      end tell
    end tell
  end tell
  
  
set aLen to length of selList
  
set aaLen to selHeight
  
  
set bList to {}
  
repeat with i from 1 to aaLen
    set aHoriList to {}
    
    
repeat with ii from 1 to selWidth
      set j1 to ii + (i – 1) * selWidth
      
set tmpCon to contents of item j1 of selList
      
      
set aClass to class of tmpCon
      
if aClass = number or aClass = integer or aClass = real then
        set tmpCon to tmpCon as integer
      end if
      
      
set the end of aHoriList to tmpCon
    end repeat
    
    
set the end of bList to aHoriList
  end repeat
  
  
return bList
end get2DListFromKeynoteTableSelection

–テキストを指定デリミタでリスト化
on parseByDelim(aData, aDelim)
  set aText to current application’s NSString’s stringWithString:aData
  
set aList to aText’s componentsSeparatedByString:aDelim
  
return aList as list
end parseByDelim

–1D/2D Listのユニーク化
on uniquifyList(aList as list)
  set aArray to current application’s NSArray’s arrayWithArray:aList
  
set bArray to aArray’s valueForKeyPath:"@distinctUnionOfObjects.self"
  
return bArray as list
end uniquifyList

★Click Here to Open This Script 

(Visited 34 times, 1 visits today)
Posted in Text | Tagged 10.15savvy 11.0savvy 12.0savvy Keynote | Leave a comment

相対パスを計算で求める

Posted on 6月 14, 2022 by Takaaki Naganoya

指定のPOSIX pathを元に相対パスを計算するAppleScriptです。

Unix shellであれば、相対パスについては「../../../」などと表現できるわけですが、シェルを介さずに計算する方法が見つからなかったので、必要に迫られて作っておきました。

AppleScript名:上位パスを相対的に求める.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2022/06/14
—
–  Copyright © 2022 Piyomaru Software, All Rights Reserved
—

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

set aFile to "/Users/me/Documents/1/2/3"

set aNum to 1
set bFile to getUpperDir(aFile, aNum) of me

–> "/Users/me/Documents/1/2"

set aNum to 2
set cFile to getUpperDir(aFile, aNum) of me
–>"/Users/me/Documents/1"

set aNum to 3
set dFile to getUpperDir(aFile, aNum) of me
–> "/Users/me/Documents"

–与えられたパスから指定階層「上」のパスを求める
on getUpperDir(aPOSIXpath as string, aNum as integer)
  if aNum < 1 then return aPOSIXpath
  
set pathString to current application’s NSString’s stringWithString:aPOSIXpath
  
repeat aNum times
    set pathString to pathString’s stringByDeletingLastPathComponent()
  end repeat
  
return pathString as string
end getUpperDir

★Click Here to Open This Script 

AppleScript名:下位パスを配列で追加して求める.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2022/06/14
—
–  Copyright © 2022 Piyomaru Software, All Rights Reserved
—

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

set aPOSIXpath to "/Users/me/Documents/" –AppleScriptのPOSIX path表現(フォルダを表現するさい、末尾に「/」)
set catDirList to {"1", "2", "3"}
set bPath to getChildPathByAppendingDirsByArray(aPOSIXpath, catDirList) of me
–> /Users/me/Documents/1/2/3

set aPOSIXpath to "/Users/me/Documents" –CocoaのPOSIX path表現(フォルダを表現する場合でも、末尾に「/」入らず)
set catDirList to {"3", "2", "1"}
set cPath to getChildPathByAppendingDirsByArray(aPOSIXpath, catDirList) of me
–> "/Users/me/Documents/3/2/1"

on getChildPathByAppendingDirsByArray(aPOSIXpath, catDirList)
  set pathString to current application’s NSString’s stringWithString:aPOSIXpath
  
set aList to (pathString’s pathComponents()) as list
  
set aList to aList & catDirList
  
  
set bPath to current application’s NSString’s pathWithComponents:aList
  
return bPath as string
end getChildPathByAppendingDirsByArray

★Click Here to Open This Script 

(Visited 48 times, 1 visits today)
Posted in File path list Text | Tagged 10.13savvy 10.14savvy 10.15savvy 11.0savvy 12.0savvy | Leave a comment

Safariで表示中のYouTubeムービーのサムネイル画像を取得

Posted on 5月 9, 2022 by Takaaki Naganoya

Safariで表示中のYouTubeムービーのサムネール画像を取得、保存、表示するAppleScriptです。

YouTubeのムービーのサムネール画像の取得方法を確認し、動作確認用にダイアログ表示+画像保存の機能を追加したものです。Script Debugger上で動かしている分には、NSImageの内容を結果表示ビューワで自動表示されますが、ない人向けに付けた機能です。

画像自体は、「ピクチャ」フォルダにUUIDつきでPNG形式で保存します。

–> Download Script bundle with Library

掲載リストには、画像表示ライブラリが含まれていないため、そのままでは実行できません。上記のScript Bundleをダウンロードして実行する必要があります。

AppleScript名:Safariで表示中のYouTubeムービーのサムネイル画像を取得.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2022/05/09
—
–  Copyright © 2022 Piyomaru Software, All Rights Reserved
—

use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"
use imgLib : script "imageDisplayLib"

property NSUUID : a reference to current application’s NSUUID
property |NSURL| : a reference to current application’s |NSURL|
property NSString : a reference to current application’s NSString
property NSImage : a reference to current application’s NSImage
property NSPNGFileType : a reference to current application’s NSPNGFileType
property NSURLComponents : a reference to current application’s NSURLComponents
property NSBitmapImageRep : a reference to current application’s NSBitmapImageRep
property NSMutableDictionary : a reference to current application’s NSMutableDictionary

tell application "Safari"
  tell front document
    try
      set aURL to URL
    on error
      set aURL to "https://www.youtube.com/watch?v=_fmDtIV9vvI"
    end try
  end tell
end tell

if aURL does not start with "https://www.youtube.com/watch?" then return

set urlDict to parseURLParamsAsDict(aURL) of me
set aParam to urlDict’s valueForKey:"v"
if aParam = missing value then return

set imgURL to "https://i1.ytimg.com/vi/" & (aParam as string) & "/mqdefault.jpg"
set newURL to |NSURL|’s URLWithString:imgURL
set aImg to NSImage’s alloc()’s initWithContentsOfURL:newURL

set imgPath to (POSIX path of (path to pictures folder) & ((aParam as string) & "_") & (NSUUID’s UUID()’s UUIDString()) as string) & ".png"

–Save
saveNSImageAtPathAsPNG(aImg, imgPath) of me

–Display
dispImage(aImg, "YouTube thumbnail") of imgLib

on parseURLParamsAsDict(aURL)
  set components to NSURLComponents’s alloc()’s initWithString:aURL
  
set qList to (components’s query())’s componentsSeparatedByString:"&"
  
  
set paramRec to NSMutableDictionary’s dictionary()
  
  
repeat with i in qList
    set keyAndValues to (i’s componentsSeparatedByString:"=")
    (
paramRec’s setObject:(keyAndValues’s objectAtIndex:1) forKey:(keyAndValues’s objectAtIndex:0))
  end repeat
  
  
return paramRec
end parseURLParamsAsDict

–NSImageを指定パスにPNG形式で保存
on saveNSImageAtPathAsPNG(anImage, outPath)
  set imageRep to anImage’s TIFFRepresentation()
  
set aRawimg to NSBitmapImageRep’s imageRepWithData:imageRep
  
  
set pathString to NSString’s stringWithString:outPath
  
set newPath to pathString’s stringByExpandingTildeInPath()
  
  
set myNewImageData to (aRawimg’s representationUsingType:(NSPNGFileType) |properties|:(missing value))
  
set aRes to (myNewImageData’s writeToFile:newPath atomically:true) as boolean
  
  
return aRes –成功ならtrue、失敗ならfalseが返る
end saveNSImageAtPathAsPNG

★Click Here to Open This Script 

(Visited 99 times, 1 visits today)
Posted in Image Record Text URL | Tagged 10.14savvy 10.15savvy 11.0savvy 12.0savvy Safari | Leave a comment

Keynoteのタイトル内の強制改行コードを置換….できない?

Posted on 5月 3, 2022 by Takaaki Naganoya

Keynote v12のスライド(ページ)内のタイトル(default title item)内のテキスト(object text)の強制改行を置換(削除)できないという件についての試行錯誤です。

もともと、v12以前のバージョンのKeynoteでは、LF+LFを削除することで、タイトル内のテキストの改行削除は行えていました。

ただ、同様の処理では強制改行を削除し切れないようで….

--> {"AppleSript+NSImageでよく使う

基礎的な処理一覧", "画像ファイル
変換処理", "画像回転処理", "画像ファイルからの

情報取得処理", "画像リサイズ処理", "画像フィルタ処理"}

いまひとつすっきりしません。

Keynoteのタイトル文字列をコピーして、CotEditor(文字コードをAppleScriptと同じUTF16BEに変更)の書類上にペーストすると0Ahと表示するのですが、どうもKeynote上では異なるようで困ります。

AppleScript名:Keynote v12上の選択中のスライドのタイトルをテキスト化(改行削除)(未遂).scpt
—
–  Created by: Takaaki Naganoya
–  Created on: 2022/05/03
—
–  Copyright © 2022 Piyomaru Software, All Rights Reserved
—
use AppleScript version "2.5"
use scripting additions
use framework "Foundation"

set repTargList to {string id 10 & string id 10, string id 10, string id 11, string id 13} –LF,CR,VTab一括置換

tell application "Keynote"
  tell front document
    set aSel to selection
    
set aList to {}
    
    
repeat with i in aSel
      set tmpClass to class of i
      
if tmpClass = slide then
        set tmpStr0 to object text of default title item of i
        
set hexList to retHexDumpedStr(tmpStr0) of me
        
set tmpStr1 to (paragraphs of tmpStr0) –パラグラフごとにlistにしてみた
        
log tmpStr1
        
set tmpStr2 to replaceTextMultiple(tmpStr1 as string, repTargList, "") of me as string
        
set the end of aList to tmpStr2
      end if
    end repeat
  end tell
end tell

return aList

–文字列の前後の改行と空白文字を除去
on cleanUpText(someText)
  set theString to current application’s NSString’s stringWithString:someText
  
set theString to theString’s stringByReplacingOccurrencesOfString:" +" withString:" " options:(current application’s NSRegularExpressionSearch) range:{location:0, |length|:length of someText}
  
set theWhiteSet to current application’s NSCharacterSet’s whitespaceAndNewlineCharacterSet()
  
set theString to theString’s stringByTrimmingCharactersInSet:theWhiteSet
  
return theString as text
end cleanUpText

–指定文字列からCRLFを除去
on cleanUpCRLF(aStr)
  set aString to current application’s NSString’s stringWithString:aStr
  
set bString to aString’s stringByReplacingOccurrencesOfString:(string id 10) withString:"" –remove LF
  
set cString to bString’s stringByReplacingOccurrencesOfString:(string id 13) withString:"" –remove CR
  
set dString to cString as string
  
return dString
end cleanUpCRLF

–文字置換ルーチン
on repChar(origText as string, targStr as string, repStr as string)
  set {txdl, AppleScript’s text item delimiters} to {AppleScript’s text item delimiters, targStr}
  
set temp to text items of origText
  
set AppleScript’s text item delimiters to repStr
  
set res to temp as text
  
set AppleScript’s text item delimiters to txdl
  
return res
end repChar

–任意のデータから特定の文字列を複数パターン一括置換
on replaceTextMultiple(origData as string, origTexts as list, repText as string)
  set curDelim to AppleScript’s text item delimiters
  
set AppleScript’s text item delimiters to origTexts
  
set origData to text items of origData
  
set AppleScript’s text item delimiters to {repText}
  
set origData to origData as text
  
set AppleScript’s text item delimiters to curDelim
  
return origData
end replaceTextMultiple

on hexDumpString(aStr as string)
  set theNSString to current application’s NSString’s stringWithString:aStr
  
set theNSData to theNSString’s dataUsingEncoding:(current application’s NSUTF8StringEncoding)
  
set theString to (theNSData’s |debugDescription|()’s uppercaseString())
  
  
–Remove "<" ">" characters in head and tail
  
set tLength to (theString’s |length|()) – 2
  
set aRange to current application’s NSMakeRange(1, tLength)
  
set theString2 to theString’s substringWithRange:aRange
  
  
–Replace Space Characters
  
set aString to current application’s NSString’s stringWithString:theString2
  
set bString to aString’s stringByReplacingOccurrencesOfString:" " withString:""
  
  
set aResList to splitString(bString, 2)
  
–> {​​​​​"E3", ​​​​​"81", ​​​​​"82", ​​​​​"E3", ​​​​​"81", ​​​​​"84", ​​​​​"E3", ​​​​​"81", ​​​​​"86", ​​​​​"E3", ​​​​​"81", ​​​​​"88", ​​​​​"E3", ​​​​​"81", ​​​​​"8A"​​​}
  
  
return aResList
end hexDumpString

–Split NSString in specified aNum characters
on splitString(aText, aNum)
  set aStr to current application’s NSString’s stringWithString:aText
  
if aStr’s |length|() ≤ aNum then return aText
  
  
set anArray to current application’s NSMutableArray’s new()
  
set mStr to current application’s NSMutableString’s stringWithString:aStr
  
  
set aRange to current application’s NSMakeRange(0, aNum)
  
  
repeat while (mStr’s |length|()) > 0
    if (mStr’s |length|()) < aNum then
      anArray’s addObject:(current application’s NSString’s stringWithString:mStr)
      
mStr’s deleteCharactersInRange:(current application’s NSMakeRange(0, mStr’s |length|()))
    else
      anArray’s addObject:(mStr’s substringWithRange:aRange)
      
mStr’s deleteCharactersInRange:aRange
    end if
  end repeat
  
  
return (current application’s NSArray’s arrayWithArray:anArray) as list
end splitString

–与えられたデータ内容をhexdumpして返す
on retHexDumpedStr(aStr)
  set aRes to do shell script "echo " & quoted form of aStr & " | hexdump -v "
  
return aRes
end retHexDumpedStr

★Click Here to Open This Script 

(Visited 41 times, 1 visits today)
Posted in Object control Text | Tagged 10.15savvy 11.0savvy 12.0savvy Keynote | Leave a comment

NSCharacterSetの使い方を間違えた

Posted on 3月 30, 2022 by Takaaki Naganoya

これまでに、NSMutableCharacterSetを使うべきところにNSCharacterSetを指定していたAppleScriptがあって、これは自分のミスだったのですが……これまで、この書き方で動いてしまって気が付かなかったものでした(Thanks Shane!)

このところ、AppleScriptの処理系やmacOS自体のバグが続いたので、不可思議な問題を見つけると「これどーなの?」と関係筋に確認をとっています。Appleにレポートする前に複数のScripterに確認をとって、「本当にそうなのか?」「再現性のあるトラブルか?」という話をしています。そんな中で、これは自分のミスでした。

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:

それが、macOS 12.3で急に厳密に動かなくなり….逆にいえば、「なんでこれまでは動いていたんだろう?」というところではあるのですが、割と文字種別の判定はいろんなScriptで行なっているので影響が大きいところです。

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

Cocoa Scripting Course #1 NSStringの付録サンプルScriptに該当するものがあるため、バグ情報を掲載しています。
また、差し替えたものをダウンロードできるように購入ページ上のアーカイブを更新いたします。

(Visited 71 times, 1 visits today)
Posted in Text | Tagged 12.0savvy NSCharacterSet NSMutableCharacterSet | Leave a comment

指定のPDFの本文テキストの文字数をカウント

Posted on 3月 9, 2022 by Takaaki Naganoya

指定のPDFの本文テキストを取り出し、文字数をカウントするAppleScriptです。


▲「AppleScriptによるWebブラウザ自動操縦ガイド」の文字数をカウントしようとした

300ページを超える、わりと大きな本のPDFデータから文字を取り出したので、それなりの文字数になりました。つまり、Cocoaの有効活用を考えないとデータサイズ的につらそうなデータ量になることが予想されました。

当初、(文字処理については)Cocoaの機能をあまり活用しないv2を作ったものの、処理にM1 Mac miniで30秒ほどかかりました。すべてNSStringのまま(AppleScriptのstringに型変換せずに)処理してみたら、案の定、大幅に処理が高速化され6秒あまりで完了。

ただし、両者でカウントした文字数が1万文字ぐらい違っていたので、(PDFから取得した文字の)Unicode文字のNormalize方式を変更したところ、両者で同じ結果になりました。また、処理速度に改変前から大幅な変化はありませんでした。

文字数を数えるという処理だとさすがにデータ数が膨大になるため、NSStringで処理したほうがメリットが大きいようです。

# あれ? 5文字ぐらい違う、、、、絵文字の部分か?

AppleScript名:指定のPDFの本文テキストの文字数を数える v2
use AppleScript version "2.8" –macOS 12 or later
use framework "Foundation"
use framework "PDFKit" –Comment Out under macOS 11
–use framework "Quartz"–Uncomment under macOS 11
use scripting additions

script spd
  property cRes : ""
  
property cList : {}
end script

set (cRes of spd) to ""
set (cList of spd) to {}

set (cRes of spd) to getTextFromPDF(POSIX path of (choose file of type {"pdf"})) of me
set (cList of spd) to current application’s NSArray’s arrayWithArray:(characters of (cRes of spd))
set cLen to (cList of spd)’s |count|()
return cLen
–> 256137 (24.763sec)

on getTextFromPDF(posixPath)
  set theURL to current application’s |NSURL|’s fileURLWithPath:posixPath
  
set thePDF to current application’s PDFDocument’s alloc()’s initWithURL:theURL
  
return (thePDF’s |string|()’s precomposedStringWithCompatibilityMapping()) as text
end getTextFromPDF

★Click Here to Open This Script 

AppleScript名:指定のPDFの本文テキストの文字数を数える v3
use AppleScript version "2.8" –macOS 12 or later
use framework "Foundation"
use framework "PDFKit" –Comment Out under macOS 11
–use framework "Quartz"–Uncomment under macOS 11
use scripting additions

script spd
  property cRes : ""
  
property cList : {}
end script

set (cRes of spd) to ""
set (cList of spd) to {}

set (cRes of spd) to getTextFromPDF(POSIX path of (choose file of type {"pdf"})) of me
set cLen to (cRes of spd)’s |length|
return cLen as anything
–> 256142 (6.28 sec)

on getTextFromPDF(posixPath)
  set theURL to current application’s |NSURL|’s fileURLWithPath:posixPath
  
set thePDF to current application’s PDFDocument’s alloc()’s initWithURL:theURL
  
return (thePDF’s |string|()’s precomposedStringWithCompatibilityMapping())
end getTextFromPDF

★Click Here to Open This Script 

わずかとはいえ、違いが出ていることは確かなので、1つのPDFに対して2つの処理方法でテキストを取り出して、それを配列に入れて集合演算して差分をとってみました。M1でも処理に1分少々かかりました。こういう処理は、M1 MaxでもM1 Ultraでも所要時間は変わらないことでしょう(逆にM1の方が処理時間が短い可能性まである)。

どうやら改行コードの解釈で文字数カウント結果に違いが出たようです。

AppleScript名:テキストの抽出方法による文字数の相違チェック.scptd
use AppleScript version "2.8" –macOS 12 or later
use framework "Foundation"
use framework "PDFKit" –Comment Out under macOS 11
–use framework "Quartz"–Uncomment under macOS 11
use scripting additions

script spd
  property cRes : ""
  
property cList : {}
end script

set (cRes of spd) to ""
set (cList of spd) to {}

set docPath to POSIX path of (choose file of type {"pdf"})

set (cRes of spd) to getTextFromPDF1(docPath) of me
set (cList of spd) to characters of (cRes of spd)
set anArray to current application’s NSArray’s arrayWithArray:(cList of spd)

set bStr to getTextFromPDF2(docPath) of me
set bArray to current application’s NSMutableArray’s new()
set bLen to (bStr’s |length|) as anything
repeat with i from 0 to (bLen – 1)
  set tmpStr to (bStr’s substringWithRange:(current application’s NSMakeRange(i, 1)))
  (
bArray’s addObject:(tmpStr))
end repeat

set aRes to diffLists(anArray, bArray) of me
set bRes to diffLists(bArray, anArray) of me
return {aRes, bRes}

on getTextFromPDF1(posixPath)
  set theURL to current application’s |NSURL|’s fileURLWithPath:posixPath
  
set thePDF to current application’s PDFDocument’s alloc()’s initWithURL:theURL
  
return (thePDF’s |string|()’s precomposedStringWithCompatibilityMapping()) as text
end getTextFromPDF1

on getTextFromPDF2(posixPath)
  set theURL to current application’s |NSURL|’s fileURLWithPath:posixPath
  
set thePDF to current application’s PDFDocument’s alloc()’s initWithURL:theURL
  
return (thePDF’s |string|()’s precomposedStringWithCompatibilityMapping())
end getTextFromPDF2

–1D List同士のdiffを計算する
on diffLists(aList, bList)
  set aSet to current application’s NSMutableSet’s setWithArray:aList
  
set bSet to current application’s NSMutableSet’s setWithArray:bList
  
set aRes to calcSetDifference(aSet, bSet) of me
  
return aRes
end diffLists

–2つのNSMutableSetの補集合を求める
on calcSetDifference(aSet, bSet)
  aSet’s minusSet:bSet –補集合
  
set aRes to aSet’s allObjects() as list
  
return aRes
end calcSetDifference

★Click Here to Open This Script 

(Visited 62 times, 1 visits today)
Posted in PDF Text | Tagged 12.0savvy NSURL PDFDocument | Leave a comment

書籍フォルダの階層をさかのぼって、ツメに掲載する最大チャプターを推測 v2

Posted on 3月 4, 2022 by Takaaki Naganoya

電子書籍を作るのにPagesやKeynoteを使っており、「AppleScriptによるWebブラウザ自動操縦ガイド」(以下、Webブラウザガイド)も全ページPagesで作っています。

PagesやKeynoteでは書籍作成用としては機能が素朴すぎて、足りない点はAppleScriptでツールを作って、作業の手間を減らしています。それらの補助Scriptは、各種パラメータをその本に合わせて固定して使用しています。

Webブラウザガイドは全14章で構成されているため、ページの左右につけている「ツメ」(Index)は1から14までの数字が入っています。

今後もツメチェックAppleScript(座標、塗りつぶし色と非選択色の自動判別、ファイル名からの該当章の自動ピックアップ)を他の書籍用にも運用していくつもりですが、この「全14章」という仕様は固定なので、章構成が異なる他の本のプロジェクトでは、自動で章の数をかぞえてくれるとよさそうだと考えました。

だいたい電子書籍のファイルについては、フォルダ分けして2階層ぐらいで管理しているので、その階層数については決め打ちでDoc rootフォルダを計算(parent of parent of….)するようにしました。そして、全フォルダのフォルダ名称を取得。

ダイアログで最終章を選択させると、そこから章番号を自動抽出して(「XX章」と書かれていることが前提)、その番号を返します。

こういう用途を考えると、階層構造をそのまま選択できるNSOutlineViewを選択用の部品に使えると便利で……これまでにもedama2さんと意見交換しつつNSOutlineViewをNSAlertダイアログ上に表示するといった試作も何回か検討してきたのですが、スクリプトエディタ/Script Debugger上で記述するAppleScriptObjCではこの部品を扱うのがとても難しいんですね。

ならば、Xcode上で記述するAppleScriptObjCにAppleScript用語辞書を持たせて、階層ファイル構造を選択させる専用の補助アプリケーションを作ってもいいのかも? ただ、Xcode 13.x系が壊れて使えないままの環境であるため、いまXcodeでビルドするわけにもいかないのでした。

choose fileコマンドやchoose folderコマンドに「icon view」「list view」「column view」といった初期表示状態を指定できる機能があれば、それで済むような気もしますが、どうせAppleに要望出してもこういうのは通らないので、自分で作ったほうが確実で早いですわー。

にしても、この通常ウィンドウと見分けがつかないファイル選択ダイアログ、macOS 11で最初に見たときには「正気か?!」と、腰を抜かしました。あいかわらず、この決定を下した責任者は●●だと思いますが、せめてもう少し視覚的に見分けがつくようにできなかったもんでしょうか。

AppleScript名:書籍フォルダの階層をさかのぼって、ツメに掲載する最大チャプターを推測 v2.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2022/02/26
—
–  Copyright © 2022 Piyomaru Software, All Rights Reserved
—

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

tell application "Pages"
  tell front document
    set filePath to (file of it) as alias
  end tell
end tell

tell application "Finder"
  set parentFol to (parent of parent of filePath)
  
tell parentFol
    set fNames to name of every folder
  end tell
end tell

set folName to contents of (choose from list fNames with prompt "書籍のツメに載せる最終章のフォルダを選択")
set cNum to retChapter(folName as string) of me
–> 14

–ファイル名から「章」情報を抽出
on retChapter(aStr)
  set wList to words of aStr
  
set aCount to 1
  
repeat with ii in wList
    set jj to contents of ii
    
if jj = "章" then
      return contents of item (aCount – 1) of wList
    end if
    
set aCount to aCount + 1
  end repeat
  
return 0 –Illeagal file name
end retChapter

★Click Here to Open This Script 

(Visited 40 times, 1 visits today)
Posted in Books file File path Text | Tagged 12.0savvy Finder Pages | 1 Comment

CotEditor v4.1.2でAppleScript系の機能を追加

Posted on 2月 22, 2022 by Takaaki Naganoya

オープンソース開発されているフリーのテキストエディタ「CotEditor」v4.1.2において、AppleScript系の機能が追加されています。

・DocumentオブジェクトのhasBOM属性

has BOM (boolean, r/o) : Is the file encoding of the document has BOM (byte order mark)?

・convertコマンドのBOMオプション

convert v : Convert the document text to new encoding.
convert document : The document to convert encoding.
[lossy boolean] : Allows lossy conversion?
[BOM boolean] : Has the new encoding a BOM (byte order mark)?
to text : The new encoding, either in localized encoding name or an IANA charset name.
→ boolean : Did the convertion succeed?

・新設のjumpコマンド

jump v : Move the caret to the specified location. At least, either one of a parameter is required.
jump document : The document to move.
to line integer : The number of the line to go. If a negative value is provided, the line is counted from the end of the document.
[column integer] : The location in the line to jump. If a negative value is provided, the column is counted from the end of the line.

こんなサンプル書類があったとして、

AppleScriptのdocumentオブジェクトの文字データを取得してダンプしてみても、

--No BOM
{"E3", "81", "B4", "E3", "82", "88", "E3", "81", "BE", "E3", "82", "8B", "E3", "82", "BD", "E3", "83", "95", "E3", "83", "88", "E3", "82", "A6", "E3", "82", "A7", "E3", "82", "A2", "0A", "61", "62", "63", "64", "E9", "AB", "98", "E5", "B3", "B6", "E5", "B1", "8B", "65", "66", "67", "68", "69", "0A", "0A"}

--with BOM
{"E3", "81", "B4", "E3", "82", "88", "E3", "81", "BE", "E3", "82", "8B", "E3", "82", "BD", "E3", "83", "95", "E3", "83", "88", "E3", "82", "A6", "E3", "82", "A7", "E3", "82", "A2", "0A", "61", "62", "63", "64", "E9", "AB", "98", "E5", "B3", "B6", "E5", "B1", "8B", "65", "66", "67", "68", "69", "0A", "0A"}

この状態ではhasBOM属性値で差があっても、内部データでは差が出ません。これをファイルに書き込んで、ファイル内容についてチェックを行うと、

--No BOM
0000000 81e3 e3b4 8882 81e3 e3be 8b82 82e3 e3bd
0000010 9583 83e3 e388 a682 82e3 e3a7 a282 610a
0000020 6362 e964 98ab b3e5 e5b6 8bb1 6665 6867
0000030 0a69 000a                              
0000033

--With BOM
0000000 bbef e3bf b481 82e3 e388 be81 82e3 e38b
0000010 bd82 83e3 e395 8883 82e3 e3a6 a782 82e3
0000020 0aa2 6261 6463 abe9 e598 b6b3 b1e5 658b
0000030 6766 6968 0a0a                         
0000036

のように、差を検出できます。

(Visited 85 times, 1 visits today)
Posted in news Object control Text | Tagged 10.15savvy 11.0savvy 12.0savvy CotEditor | Leave a comment

リストに入れたテキストで、冒頭に入ったマルつき数字をリナンバーする

Posted on 2月 12, 2022 by Takaaki Naganoya

日本語環境限定かもしれませんが、マルつき数字(①②③④⑤⑥⑦⑧⑨….)をさまざまな場所でよく使います。

データにマルつき数字を入れると、順番がわかりやすくてよいのですが、データそのものを入れ替えたときに番号をふり直すという手間がかかってしまいます。これがけっこうな手間になっています(地味に大変)。

そこで、

 {"③AAAAAA", "②BBBBB", "①CCCCC", "⑬DDDDDD", "⑫EEEE", "④FFFF", "⑤GGGG", "⑥HHHH", "⑲IIIII", "⑧JJJJ"}

というデータを本Scriptによって、

{"①AAAAAA", "②BBBBB", "③CCCCC", "④DDDDDD", "⑤EEEE", "⑥FFFF", "⑦GGGG", "⑧HHHH", "⑨IIIII", "⑩JJJJ"}

と、リナンバー処理します。

本処理は、絵文字の削除Scriptの副産物として生まれたもので、マル文字を削除したのちに番号をふり直して付加したところ、たいへん有用性を感じられました。

Keynote、Numbers、Pages…と、同じことができるようにScriptを整備し、CotEditor用にあったほうが便利だろうと考えて、CotEditor用にかきかえた際に、

–> Watch Demo Movie

「ほかのアプリケーションでも使えたほうが便利なので、再利用しやすいように部品化しておこう」

と、Script文でラッピングしてみたものがこれです。

AppleScript名:リストに入れたテキストで、冒頭に入ったマルつき数字をリナンバーする.scptd
—
–  Created by: Takaaki Naganoya
–  Created on: 2022/02/12
—
–  Copyright © 2022 Piyomaru Software, All Rights Reserved
—

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

set aOffset to 0

set aSelList to {"③AAAAAA", "②BBBBB", "①CCCCC", "⑬DDDDDD", "⑫EEEE", "④FFFF", "⑤GGGG", "⑥HHHH", "⑲IIIII", "⑧JJJJ"}

—データ中に丸つき数字が存在した場合には、最小のものを取得
set aOffset to (getMinimumNumFromNumberWithSign(aSelList) of maruNumKit)

–ユーザーに対して「本当に初期値がこれでいいのか?」をダイアログなどで確認したほうがいい

–Keynoteの表のセルから取得したデータから丸つき数字を除去する
set cList to removeNumberWithSignFromList(aSelList) of maruNumKit

–list中の各アイテムの冒頭に順次丸つき数字を追加する
set dList to {}
set aCount to 0

repeat with i in cList
  set j to convNumToNumWithSign(aCount + aOffset) of maruNumKit
  
set jj to contents of i
  
  
set the end of dList to (j & jj)
  
  
set aCount to aCount + 1
end repeat

return dList
–> {"①AAAAAA", "②BBBBB", "③CCCCC", "④DDDDDD", "⑤EEEE", "⑥FFFF", "⑦GGGG", "⑧HHHH", "⑨IIIII", "⑩JJJJ"}

–1D Arrayを改行コードをデリミタに指定しつつテキスト化
–set outStr to retDelimedText(dList, return) of maruNumKit

–丸つき数字を扱うキット
script maruNumKit
  
  
use AppleScript
  
use framework "Foundation"
  
use scripting additions
  
property parent : AppleScript
  
  
–1~50の範囲の数値を丸つき数字に変換して返す
  
on convNumToNumWithSign(aNum as number)
    if (aNum ≤ 0) or (aNum > 50) then return ""
    
set aStr to "①②③④⑤⑥⑦⑧⑨⑩⑪⑫⑬⑭⑮⑯⑰⑱⑲⑳㉑㉒㉓㉔㉕㉖㉗㉘㉙㉚㉛㉜㉝㉞㉟㊱㊲㊳㊴㊵㊶㊷㊸㊹㊺㊻㊼㊽㊾㊿"
    
set bChar to character aNum of aStr
    
return bChar
  end convNumToNumWithSign
  
  
  
–1D List上で指定データを検索してヒットしたアイテム番号を返す
  
on search1DList(aList, aTarg)
    set anArray to current application’s NSMutableArray’s arrayWithArray:aList
    
set anIndex to anArray’s indexOfObject:aTarg
    
if (anIndex = current application’s NSNotFound) or (anIndex > 9.99999999E+8) then
      return false
    end if
    
return (anIndex as integer) + 1 –convert index base (0 based to 1 based)
  end search1DList
  
  
  
–1D listのクリーニング
  
on cleanUp1DList(aList as list, cleanUpItems as list)
    set bList to {}
    
repeat with i in aList
      set j to contents of i
      
if j is not in cleanUpItems then
        set the end of bList to j
      else
        set the end of bList to ""
      end if
    end repeat
    
return bList
  end cleanUp1DList
  
  
  
–text in listから丸つき数字を除去する
  
on removeNumberWithSignFromList(aList as list)
    set bList to {}
    
repeat with i in aList
      set j to contents of i
      
set j2 to removeNumberWithSign(j) of me
      
set the end of bList to j2
    end repeat
    
return bList
  end removeNumberWithSignFromList
  
  
  
–文字列から丸つき数字を除去する
  
on removeNumberWithSign(aStr as text)
    set aNSString to current application’s NSString’s stringWithString:aStr
    
return (aNSString’s stringByReplacingOccurrencesOfString:"[\\U000024EA-\\U000024EA\\U00002460-\\U00002473\\U00003251-\\U000032BF\\U000024FF-\\U000024FF\\U00002776-\\U0000277F\\U000024EB-\\U000024F4\\U00002780-\\U00002789\\U0000278A-\\U00002793\\U000024F5-\\U000024FE]" withString:"" options:(current application’s NSRegularExpressionSearch) range:{0, aNSString’s |length|()}) as text
  end removeNumberWithSign
  
  
  
–1D Listに入っているテキストから丸つき数字を抽出して数値化し、最小のものを求める
  
on getMinimumNumFromNumberWithSign(aList)
    set nList to {}
    
    
repeat with i in aList
      set j to contents of i
      
–与えられたテキストのうち、丸つき数字(白)の
      
set j2 to holdNumberWithSignOnly(j) of me
      
set n2List to characters of j2 –複数の丸つき数字が入っている場合に対処
      
      
repeat with ii in n2List
        set jj to contents of ii
        
set tmpNum to decodeNumFromNumWithSign(jj) of me
        
set the end of nList to tmpNum
      end repeat
      
    end repeat
    
    
set anArray to current application’s NSArray’s arrayWithArray:nList
    
set cRes to (anArray’s valueForKeyPath:"@min.self") as integer
    
return cRes
  end getMinimumNumFromNumberWithSign
  
  
  
–指定文字列から丸つき数字のみ抽出する
  
on holdNumberWithSignOnly(aStr as text)
    set aNSString to current application’s NSString’s stringWithString:aStr
    
return (aNSString’s stringByReplacingOccurrencesOfString:"[^\\U000024EA-\\U000024EA\\U00002460-\\U00002473\\U00003251-\\U000032BF\\U000024FF-\\U000024FF\\U00002776-\\U0000277F\\U000024EB-\\U000024F4\\U00002780-\\U00002789\\U0000278A-\\U00002793\\U000024F5-\\U000024FE]" withString:"" options:(current application’s NSRegularExpressionSearch) range:{0, aNSString’s |length|()}) as text
  end holdNumberWithSignOnly
  
  
  
–丸つき数字を数値にデコードする v2
  
on decodeNumFromNumWithSign(aStr as string)
    set numStr1 to "①②③④⑤⑥⑦⑧⑨⑩⑪⑫⑬⑭⑮⑯⑰⑱⑲⑳㉑㉒㉓㉔㉕㉖㉗㉘㉙㉚㉛㉜㉝㉞㉟㊱㊲㊳㊴㊵㊶㊷㊸㊹㊺㊻㊼㊽㊾㊿"
    
set numStr2 to "❶❷❸❹❺❻❼❽❾❿⓫⓬⓭⓮⓯⓰⓱⓲⓳⓴"
    
set numStr3 to "➀➁➂➃➄➅➆➇➈➉"
    
set numStr4 to "➊➋➌➍➎➏➐➑➒➓"
    
set numStr5 to "⓵⓶⓷⓸⓹⓺⓻⓼⓽⓾"
    
    
set nList to {numStr1, numStr2, numStr3, numStr4, numStr5}
    
    
repeat with i in nList
      set numTemp to contents of i
      
if numTemp contains aStr then
        using terms from scripting additions
          set bNum to offset of aStr in numTemp
        end using terms from
        
return bNum
      end if
    end repeat
    
return false
  end decodeNumFromNumWithSign
  
  
–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
end script

★Click Here to Open This Script 

(Visited 55 times, 1 visits today)
Posted in list Text | Tagged 10.15savvy 11.0savvy 12.0savvy | 1 Comment

Post navigation

  • Older posts

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

Google Search

Popular posts

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

Tags

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

カテゴリー

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

アーカイブ

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

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

メタ情報

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

Forum Posts

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

メタ情報

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