20260518

[AppleScript]Apple Intelligenceに質問をする(swift経由)

[AppleScript]Apple Intelligenceに質問をする(swift経由)

NOTE記事一覧ですnote.com

【スクリプトエディタで開く】 |

Apple Intelligenceに質問する.scpt.scpt
ソース
001#!/usr/bin/env osascript
002#coding: utf-8
003----+----1----+----2----+----3----+----4----+----5----+----6----+----7--
004(*
005
006Apple Intelligenceに質問するスクリプト
007なんですが
008Apple Intelligenceがアレすぎるので、全く使い物になりません
009ダメダメな解答ばかり戻します。
010
011質問は理解しているようですが
012解答の精度が悪すぎる
013
014v1 初回作成
015
016
017com.cocolog-nifty.quicktimer.icefloe *)
018----+----1----+----2----+----3----+----4----+----5----+----6----+----7--
019use AppleScript version "2.8"
020use framework "Foundation"
021use framework "AppKit"
022use framework "UniformTypeIdentifiers"
023use scripting additions
024
025property refMe : a reference to current application
026
027
028################
029#インテリジェンスが利用可能かチェック
030set boolDone to doChkIntelligence()
031if boolDone is false then
032   tell application "SystemUIServer"
033      activate
034      display alert "インテリジェンスが停止中です"
035   end tell
036   set boolDone to doOpenPrefPane()
037   return boolDone
038end if
039
040################
041#ペーストボード
042set ocidPasteboard to refMe's NSPasteboard's generalPasteboard()
043set ocidClassesArray to refMe's NSMutableArray's alloc()'s init()
044ocidClassesArray's addObject:(refMe's NSString)
045set ocidPasteboardArray to ocidPasteboard's readObjectsForClasses:(ocidClassesArray) options:(missing value)
046set numCntArray to ocidPasteboardArray's |count|()
047if numCntArray = 0 then
048   set strDefaultAnswer to ("質問を入力してください") as text
049else
050   set strDefaultAnswer to ocidPasteboardArray's firstObject() as text
051end if
052set strDefaultAnswer to ("回答は日本語のMarkdownフォーマット" & return & return & strDefaultAnswer & " ") as text
053########################
054# 開始ダイアログ
055set strTitle to ("入力してください か 戻り値") as text
056set strMsg to ("Apple Intelligenceに質問をどうぞ") as text
057set strSaveAs to ("テキストファイルに保存する") as text
058set strCopy to ("クリップボードにコピーする") as text
059set strQuit to ("中断・終了") as text
060set strOK to ("OK") as text
061set strCancel to ("キャンセル") as text
062set listButtons to {strOK, strCancel} as list
063set strIconFilePath to ("/System/Applications/Image Playground.app/Contents/Resources/AppIcon.icns") as text
064set aliasIconFilePath to (POSIX file strIconFilePath) as alias
065try
066   tell application "System Events"
067      activate
068      set recordResponse to (display dialog strMsg with title strTitle default answer strDefaultAnswer buttons listButtons default button strOK cancel button strCancel with icon aliasIconFilePath giving up after 360 without hidden answer) as record
069   end tell
070on error strErrorMes number numErrorNO
071   log strErrorMes & numErrorNO
072   return false
073end try
074set boolGaveUP to (gave up of recordResponse) as boolean
075if boolGaveUP is true then
076   log "時間切れ終了"
077   return false
078end if
079set strButtonReturned to (button returned of recordResponse) as text
080set strResponse to (text returned of recordResponse) as text
081set ocidResponseString to (refMe's NSString's stringWithString:(strResponse))
082
083########################
084# エスケープ不要にするためにBASE64エンコードする
085set ocidArgData to ocidResponseString's dataUsingEncoding:(refMe's NSUTF8StringEncoding)
086set ocidOption to (refMe's NSDataBase64EncodingEndLineWithLineFeed)
087set ocidBase64EncodedString to ocidArgData's base64EncodedStringWithOptions:(ocidOption)
088set strBase64string to ocidBase64EncodedString as string
089
090##############################
091#SWIFT
092set strSwiftCode to ("#!/usr/bin/env swift\nimport AppKit\nimport Foundation\nimport FoundationModels\nlet argString = \"" & strBase64string & "\"\nlet cleaned = argString\n.components(separatedBy: .newlines)\n.joined()\nguard let dataBase64String = Data(base64Encoded: cleaned),\nlet decodedString = String(data: dataBase64String, encoding: .utf8) else {\nprint(\"Base64デコード失敗\")\nexit(1)\n}\nlet inputText = decodedString\nTask {\nlet appSession = LanguageModelSession {\n\"\"\"\n時間がかかっても良いので確実な回答をしてください\n参照したサイトがある場合はURLを併記すること\n出力はMarkdownフォーマットにすること\n\n\"\"\"\n}\nlet responseString = try await appSession.respond(to: inputText)\nprint(responseString.content)\nexit(0)\n}\nRunLoop.main.run()\n") as text
093try
094   with timeout of 60 seconds
095      set strStdOut to (do shell script ("/bin/echo '" & strSwiftCode & "' | /usr/bin/swift -")) as text
096   end timeout
097end try
098set strDefaultAnswer to strStdOut as text
099
100##############################
101#終了ダイアログ
102set strIconFilePath to ("/System/Applications/Image Playground.app/Contents/Resources/AppIcon.icns") as text
103set aliasIconFilePath to (POSIX file strIconFilePath) as alias
104set strMsg to ("テキストの戻り値です" & return & "コピーできます") as text
105set strTitle to ("処理の戻り値です") as text
106set strOK to ("ファイルに保存する") as text
107set strCancel to ("キャンセル") as text
108set strCopyToClipboard to ("クリップボードにコピー") as text
109set listBotton to {strCopyToClipboard, strCancel, strOK} as list
110try
111   tell application "System Events"
112      activate
113      set recordResult to (display dialog strMsg with title strTitle default answer strDefaultAnswer buttons listBotton default button strCopyToClipboard cancel button strCancel with icon aliasIconFilePath giving up after 20 without hidden answer) as record
114   end tell
115on error strErrMsg number numErrNo
116   log strErrMsg & numErrNo
117   return false
118end try
119
120set strResponseButton to (button returned of recordResult) as text
121set boolGaveUP to (gave up of recordResult) as boolean
122if boolGaveUP is true then
123   log "時間切れ"
124   return false
125end if
126set strResponseText to (text returned of recordResult) as text
127if strResponseButton is strOK then
128   set appFileManager to refMe's NSFileManager's defaultManager()
129   set ocidURLsArray to (appFileManager's URLsForDirectory:(refMe's NSDesktopDirectory) inDomains:(refMe's NSUserDomainMask))
130   set ocidDesktopDirPathURL to ocidURLsArray's firstObject()
131   set aliasDesktopDirPath to (ocidDesktopDirPathURL's absoluteURL()) as alias
132   set strIconFilePath to ("/System/Library/UserNotifications/Bundles/com.apple.identityservicesd.firewall.bundle/Contents/Resources/Apple Care_Mac.icns") as text
133   set aliasIconFilePath to (POSIX file strIconFilePath) as alias
134   #
135   set strBaseFileName to ("IntelligenceResponse") as text
136   set strSaveExtension to ("md") as text
137   set strDefaultFileName to ("" & strBaseFileName & "." & strSaveExtension & "") as text
138   set strMsg to ("名前を決めてください" & return & "拡張子は" & strSaveExtension & "です") as text
139   set strPromptText to "名前を決めてください" as text
140   #ファイル名 ダイアログ
141   tell application "SystemUIServer"
142      activate
143      set aliasSaveFilePath to (choose file name strMsg default location aliasDesktopDirPath default name strDefaultFileName with prompt strPromptText) as «class furl»
144   end tell
145   #出力パス
146   set strSaveFilePath to (POSIX path of aliasSaveFilePath) as text
147   set ocidSaveFilePathStr to refMe's NSString's stringWithString:(strSaveFilePath)
148   set ocidSaveFilePath to ocidSaveFilePathStr's stringByStandardizingPath()
149   set ocidSaveFilePathURL to (refMe's NSURL's alloc()'s initFileURLWithPath:(ocidSaveFilePath) isDirectory:false)
150   set ocidContainerDirPathURL to ocidSaveFilePathURL's URLByDeletingLastPathComponent()
151   #拡張子
152   set strExtension to (ocidSaveFilePathURL's pathExtension()) as text
153   #最後のアイテムがファイル名
154   set strFileName to (ocidSaveFilePathURL's lastPathComponent()) as text
155   #拡張子のつけ忘れ対策
156   if strFileName does not contain strSaveExtension then
157      set strFileName to (strFileName & "." & strSaveExtension) as text
158      set ocidSaveFilePathURL to ocidContainerDirPathURL's URLByAppendingPathComponent:(strFileName)
159   end if
160   #保存処理
161   set ocidSaveString to refMe's NSMutableString's stringWithString:(strResponseText)
162   set ocidSaveString to (ocidSaveString's stringByReplacingOccurrencesOfString:(return & linefeed) withString:(linefeed))
163   set ocidSaveString to (ocidSaveString's stringByReplacingOccurrencesOfString:(return) withString:(linefeed))
164   set ocidSaveString to (ocidSaveString's stringByReplacingOccurrencesOfString:(linefeed & linefeed) withString:(linefeed))
165   set listDone to ocidSaveString's writeToURL:(ocidSaveFilePathURL) atomically:(true) encoding:(refMe's NSUTF8StringEncoding) |error|:(reference)
166   return (first item of listDone)
167else if strResponseButton is strCopyToClipboard then
168   #ペーストボードに格納する
169   set appPasteboard to refMe's NSPasteboard's generalPasteboard()
170   set ocidText to (refMe's NSString's stringWithString:(strResponseText))
171   appPasteboard's clearContents()
172   set boolDone to appPasteboard's setString:(ocidText) forType:(refMe's NSPasteboardTypeString)
173   return boolDone
174end if
175
176return 0
177
178####################
179#doChkIntelligence
180on doChkIntelligence()
181   
182   set strSwiftCode to ("#!/usr/bin/env swift\n//coding: utf-8\nimport Foundation\nimport FoundationModels\nlet appModel = SystemLanguageModel.default\nswitch appModel.availability {\ncase .available:\nprint(\"TRUE\")\ncase .unavailable(.appleIntelligenceNotEnabled):\nprint(\"FALSE\")\ncase .unavailable(.deviceNotEligible):\nprint(\"FALSE\")\ncase .unavailable(.modelNotReady):\nprint(\"FALSE\")\ncase .unavailable(_):\nprint(\"FALSE\")\n}\n") as text
183   
184   set boolDone to (do shell script ("/bin/echo '" & strSwiftCode & "' | /usr/bin/swift -")) as boolean
185   return boolDone
186   
187end doChkIntelligence
188
189
190
191####################
192#
193on doOpenPrefPane()
194   
195   set strBundleID to ("com.apple.systempreferences") as text
196   ###URLにする
197   set ocidURLComponents to refMe's NSURLComponents's alloc()'s init()
198   ###スキーム
199   ocidURLComponents's setScheme:("x-apple.systempreferences")
200   ###パネルIDをパスにセット
201   ocidURLComponents's setPath:("com.apple.Siri-Settings.extension*siri-sae")
202   ###アンカーをクエリーとして追加
203   ocidURLComponents's setQuery:("GenerativeAssistantSettingsView")
204   set ocidOpenAppURL to ocidURLComponents's |URL|
205   set strOpenAppURL to ocidOpenAppURL's absoluteString() as text
206   ###ワークスペースで開く
207   set appShardWorkspace to refMe's NSWorkspace's sharedWorkspace()
208   set boolDone to appShardWorkspace's openURL:(ocidOpenAppURL)
209   log boolDone
210   if boolDone is false then
211      tell application id "com.apple.systempreferences"
212         activate
213         set miniaturized of the settings window to false
214      end tell
215      tell application id "com.apple.finder"
216         open location "x-apple.systempreferences:com.apple.Siri-Settings.extension*siri-sae?GenerativeAssistantSettingsView"
217      end tell
218      tell application id "com.apple.systempreferences"
219         reveal anchor "GenerativeAssistantSettingsView" of pane id "com.apple.Siri-Settings.extension*siri-sae"
220      end tell
221      tell application id "com.apple.systempreferences" to activate
222   end if
223   ###開くのを待つ
224   repeat 10 times
225      tell application id "com.apple.systempreferences"
226         set boolFrontMost to frontmost as boolean
227      end tell
228      if boolFrontMost is true then
229         delay 1
230         exit repeat
231      else
232         tell application id "com.apple.systempreferences" to activate
233         delay 0.5
234      end if
235   end repeat
236   ###パネルを確認して
237   repeat 10 times
238      tell application id "com.apple.systempreferences"
239         activate
240         tell current pane
241            set strPaneID to id
242         end tell
243      end tell
244      if strPaneID is "com.apple.systempreferences.GeneralSettings" then
245         delay 0.5
246      else if strPaneID is "com.apple.Siri-Settings.extension*siri-sae" then
247         exit repeat
248      end if
249   end repeat
250   ###アンカーを再指定
251   tell application "System Settings"
252      tell pane id "com.apple.Siri-Settings.extension*siri-sae"
253         tell anchor "GenerativeAssistantSettingsView"
254            try
255               reveal
256            end try
257            
258         end tell
259      end tell
260   end tell
261   return true
262   
263end doOpenPrefPane
AppleScriptで生成しました