forked from xenodium/chatgpt-shell
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdall-e-shell.el
270 lines (237 loc) · 10.9 KB
/
dall-e-shell.el
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
;;; dall-e-shell.el --- Interaction mode for DALL-E -*- lexical-binding: t -*-
;; Copyright (C) 2023 Alvaro Ramirez
;; Author: Alvaro Ramirez https://xenodium.com
;; URL: https://github.com/xenodium/chatgpt-shell
;; Version: 0.19.1
;; Package-Requires: ((emacs "27.1") (shell-maker "0.25.1"))
;; This package is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 3, or (at your option)
;; any later version.
;; This package is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;; You should have received a copy of the GNU General Public License
;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
;;; Commentary:
;; `dall-e-shell' is a comint-based DALL-E shell for Emacs.
;;
;; You must set `dall-e-shell-openai-key' to your key before using.
;;
;; Run `dall-e-shell' to get a DALL-E shell.
;;
;; Note: This is young package still. Please report issues or send
;; patches to https://github.com/xenodium/chatgpt-shell
;;
;; Support the work https://github.com/sponsors/xenodium
(require 'shell-maker)
;;; Code:
(defcustom dall-e-shell-openai-key nil
"OpenAI key as a string or a function that loads and returns it."
:type '(choice (function :tag "Function")
(string :tag "String"))
:group 'dall-e-shell)
(defcustom dall-e-shell-image-size nil
"The default size of the requested image as a string.
For example: \"1024x1024\""
:type 'string
:group 'dall-e-shell)
(defcustom dall-e-shell-model-version "image-alpha-001"
"The used DALL-E OpenAI model."
:type 'string
:group 'dall-e-shell)
(defcustom dall-e-shell-request-timeout 60
"How long to wait for a request to time out."
:type 'integer
:group 'dall-e-shell)
(defcustom dall-e-shell-image-output-directory temporary-file-directory
"Output directory for the generated image."
:type 'directory
:group 'dall-e-shell)
(defvaralias 'dall-e-shell-display-function 'shell-maker-display-function)
(defvaralias 'dall-e-shell-read-string-function 'shell-maker-read-string-function)
;; Aliasing enables editing as text in babel.
(defalias 'dall-e-shell-mode #'text-mode)
(defvar dall-e-shell--url "https://api.openai.com/v1/images/generations")
(defvar dall-e-shell--config
(make-shell-maker-config
:name "DALL-E"
:validate-command
(lambda (_command)
(unless dall-e-shell-openai-key
"Variable `dall-e-shell-openai-key' needs to be set to your key.
Try M-x set-variable dall-e-shell-openai-key
or
(setq dall-e-shell-openai-key \"my-key\")"))
:execute-command
(lambda (_command history callback error-callback)
(shell-maker-async-shell-command
(dall-e-shell--make-curl-request-command-list
(dall-e-shell--make-payload history))
nil ;; no streaming
#'dall-e-shell--extract-response
callback
error-callback))))
;;;###autoload
(defun dall-e-shell ()
"Start a DALL-E shell."
(interactive)
(shell-maker-start dall-e-shell--config))
(defun dall-e-shell--make-payload (history)
"Create the request payload from HISTORY."
(let ((request-data `((model . ,dall-e-shell-model-version)
(prompt . ,(car (car (last history)))))))
(when dall-e-shell-image-size
(push `(size . ,dall-e-shell-image-size) request-data))
request-data))
(defun dall-e-shell--extract-response (json &optional no-download)
"Extract DALL-E response from JSON.
Set NO-DOWNLOAD to skip automatic downloading."
(if-let ((parsed (shell-maker--json-parse-string-filtering
json "^curl:.*\n?"))
(buffer (shell-maker-buffer shell-maker-config)))
(if-let* ((url (let-alist parsed
(let-alist (seq-first .data)
.url)))
(created (number-to-string (let-alist parsed
.created)))
(path (expand-file-name (concat created ".png")
dall-e-shell-image-output-directory)))
(if no-download
`((url . ,url)
(created . ,created)
(path . ,path))
(progn
(dall-e-shell--download-image
url path
(lambda (path)
(let* ((loc (dall-e-shell--find-string-in-buffer
buffer
path))
(start (car loc))
(end (cdr loc)))
(with-current-buffer buffer
(remove-text-properties start end '(face nil))
(add-text-properties
start end
`(display ,(create-image path nil nil :width 400)))
(put-text-property start end
'keymap (let ((map (make-sparse-keymap)))
(define-key map (kbd "RET")
(lambda () (interactive)
(find-file path)))
map)))))
(lambda (error)
(when-let* ((loc (dall-e-shell--find-string-in-buffer
buffer
path))
(start (car loc))
(end (cdr loc)))
(with-current-buffer buffer
(remove-text-properties start end '(face nil))
(add-text-properties start end `(display ,error))))))
(propertize path 'display "[downloading...]")))
(let-alist parsed
.error.message))))
(defun dall-e-shell-post-prompt (prompt &optional version image-size)
"Make a single DALL-E request with PROMPT.
Optionally provide model VERSION or IMAGE-SIZE."
(with-temp-buffer
(setq-local shell-maker-config
dall-e-shell--config)
(let* ((api-buffer (current-buffer))
(command
(dall-e-shell--make-curl-request-command-list
(let ((request-data `((model . ,(or version
dall-e-shell-model-version))
(prompt . ,prompt))))
(when (or image-size dall-e-shell-image-size)
(push `(size . ,(or image-size dall-e-shell-image-size))
request-data))
request-data)))
(_status (condition-case err
(apply #'call-process (seq-first command)
nil api-buffer nil (cdr command))
(error
(insert (error-message-string err))
1)))
(response (dall-e-shell--extract-response
(buffer-substring-no-properties
(point-min)
(point-max))
t)))
(if (and (map-elt response 'url)
(map-elt response 'path)
(map-elt response 'created))
(with-temp-buffer
(let* ((download-buffer (current-buffer))
(status (condition-case err
(call-process "curl" nil download-buffer
"curl" "--no-progress-meter"
"-o" (map-elt response 'path)
(map-elt response 'url))
(error
(insert (error-message-string err))
1)))
(output (with-current-buffer download-buffer
(buffer-string))))
(message "outcome: %s" output)
(if (= status 0)
(map-elt response 'path)
output)))
(or response (with-current-buffer api-buffer
(buffer-string)))))))
(defun dall-e-shell--find-string-in-buffer (buffer search-str)
"Find SEARCH-STR in BUFFER and return a cons with start/end.
Return nil if not found."
(with-current-buffer buffer
(save-excursion
(goto-char (point-min))
(when (search-forward search-str nil t)
(cons (match-beginning 0) (match-end 0))))))
(defun dall-e-shell--download-image (url path callback error-callback)
"Download URL to PATH. Invoke CALLBACK on success.
ERROR-CALLBACK otherwise."
;; Ensure sync failures can be handled in next runloop.
(run-with-idle-timer 0 nil
(lambda ()
(let* ((output-buffer (generate-new-buffer " *temp*"))
(request-process
(condition-case err
(start-process "curl" (buffer-name output-buffer)
"curl" "--no-progress-meter"
"-o" path
url)
(error
(funcall error-callback (error-message-string err))
nil)))
(process-connection-type nil))
(when request-process
(set-process-sentinel
request-process
(lambda (process _event)
(let ((output (with-current-buffer (process-buffer process)
(buffer-string))))
(if (= (process-exit-status process) 0)
(funcall callback path)
(funcall error-callback output))
(kill-buffer output-buffer)))))))))
(defun dall-e-shell--make-curl-request-command-list (request-data)
"Build DALL-E curl command list using REQUEST-DATA."
(list "curl" dall-e-shell--url
"--fail-with-body"
"--no-progress-meter"
"-m" (number-to-string dall-e-shell-request-timeout)
"-H" "Content-Type: application/json"
"-H" (format "Authorization: Bearer %s"
(cond ((stringp dall-e-shell-openai-key)
dall-e-shell-openai-key)
((functionp dall-e-shell-openai-key)
(condition-case _err
(funcall dall-e-shell-openai-key)
(error
"KEY-NOT-FOUND")))))
"-d" (shell-maker--json-encode request-data)))
(provide 'dall-e-shell)
;;; dall-e-shell.el ends here