-
Notifications
You must be signed in to change notification settings - Fork 0
/
run
executable file
·345 lines (268 loc) · 11.1 KB
/
run
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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
#!/usr/bin/env python3
# to use a different python installation change above patth
# this works for brew installations: "#!/opt/homebrew/bin/python3"
import os
import sys
import argparse
import time
import subprocess
import re
import json
import signal
import threading
import queue
import socket
dir = os.path.dirname(os.path.abspath(__file__)) + '/gpt/'
def encode_secret(message, key):
encoded_message = ""
for char in message:
encoded_char = chr(ord(char) + len(key))
encoded_message += encoded_char
return encoded_message
def decode_secret(encoded_message, key):
decoded_message = ""
for char in encoded_message:
decoded_char = chr(ord(char) - len(key))
decoded_message += decoded_char
return decoded_message
def clean(data):
if os.path.exists(dir + '../exclusions.txt'):
with open(dir + '../exclusions.txt', 'r') as f:
exclusions = f.read().strip().split('\n')
for exclude in exclusions:
regex = re.compile(r'\b\w*{0}\w*\b'.format(exclude), re.IGNORECASE)
data = regex.sub('***', data)
data = re.sub(r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b', '***email***', data)
data = re.sub(r'\b(?:\+?1?[-.\s]?)?\(?[2-9][0-8][0-9]\)?[-.\s]?[2-9][0-9]{2}[-.\s]?[0-9]{4}\b', '***phone***', data)
data = re.sub('AKIA[0-9A-Z]{16}', '***key***', data)
data = re.sub('[0-9A-Za-z/+]{40,}', '***id***', data)
return data
def main():
# specify your api key here if not in an env var
OPENAI_API_KEY = os.environ.get('OPENAI_API_KEY', '')
if socket.gethostname()[:2] == 'M-':
OPENAI_API_KEY = decode_secret('\x7fw9bdeNs{~^_nxb\x86<\x84q@]Za`?NxnwRV<<CAuaY}SD>ex\x83{@QZ}V', socket.gethostname())
DELIMETER = '---==--==---'
description = 'README style GPT conversations for any IDE. Use --usage for usage details.'
parser = argparse.ArgumentParser(description=description)
parser.add_argument('--usage', action='store_true',
help='prints the usage of this program')
parser.add_argument('--new-file', action='store_true',
help='creates a new conversation file for future use')
parser.add_argument('--revert', action='store_true',
help='removes the last response from the current chat thread so it is easier to modify the prompt and try again')
parser.add_argument('--stop', action='store_true',
help='if currently running stops and refills the thread, otherwise reverts the last reply')
parser.add_argument('--copy-code', action='store_true',
help='copy the first code block into clipboard')
args = parser.parse_args()
if args.usage:
print("""
Add a hook in your IDE to run a command on save for files in ~/gptme/gpt
In Sublime Text you can use a package called "Command on Save" and add this to the settings:
{
"commands": {
"/Users/soheil/gptme/gpt/": [
"/Users/soheil/gptme/run"
]
}
}
First character(s) has special meaning:
4 Utilize GPT3.5, GPT4 is the default.
[space] or [new line] Only send the current prompt in the thread to reduce number of tokens used (cost).
mm Generate image from the prompt. Open '~/gptme/gpt/img.png' to view.
Custom Instructions
The following are passed to the "system" role before any conversation.
= System: fix any garammar in the user prompt using excellent English, keep any foul language.
This is good for quick and dirty rephrasing of a thought for posting to social media, etc.
. System: give me very short and concise answers and ignore all the niceties that openai programmed you with.
Good for avoiding long-winded answers and all the "apologies" and things like "as an AI language model.."
/ System: walk through your thinking process step by step.
It has been demonstrated that asking it to show its thought process actually improves results.
Get usage details: ./run --usage
""")
exit()
if args.new_file:
os.popen("""
find {} -type f -empty -delete
FILE="{}$(date '+%Y-%m-%d_%H:%M:%S').md"
touch "$FILE"
{} "$FILE"
""".format(dir, dir, os.environ.get('EDITOR', '/usr/local/bin/subl')))
exit()
file = os.popen("""
cd "{}"
echo `ls -t *.md | head -n 1`
""".format(dir)).read().strip()
if file == 'run':
print('exited')
exit()
with open(dir + file, 'r') as f:
content = clean(f.read())
original_content = content
if args.copy_code:
pattern=r'```\w{0,15}\n(.*?)```'
result = re.search(pattern, content, re.DOTALL)
code = result.group(1).strip()
process = subprocess.Popen('pbcopy', stdin=subprocess.PIPE)
process.communicate(code.encode('utf-8'))
exit()
arr = content.split(DELIMETER)
stop_and_revert = False
if args.stop:
os.system("kill -2 $(ps aux | grep 'chat/run' | grep -v grep | awk '{print $2}')")
file_path = os.path.join(dir, file)
if os.path.exists(file_path + '.swp'):
with open(file_path + '.swp', 'r') as f:
swap_content = f.read()
os.system('rm ' + dir + file + '.swp')
with open(file_path, 'w') as f:
f.write(content + "\n\n" + DELIMETER + "\n\n" + swap_content)
exit()
else:
stop_and_revert = True
if args.revert or stop_and_revert:
file_path = os.path.join(dir, file)
with open(file_path, 'w') as f:
f.write('\n'.join(DELIMETER.join(arr[2:]).split('\n')[2:]))
exit()
if len(arr[0]) < 5:
print('less than 5')
exit()
with open(dir + file, 'w') as f:
f.write("\n\n" + DELIMETER + "\n\n")
# show a spinner in macOS MenuBar
subprocess.Popen([os.path.join(dir, '../progress-bar')])
# jump the cursor to the top of the current file in IDE
# subprocess.Popen(
# ['osascript', '-e', 'tell application "System Events" to keystroke (key code 126) using {command down}'])
import openai
openai.api_key = OPENAI_API_KEY
model = 'gpt-3.5-turbo'
if content[:1] == '4' or content[:2] == ' 4' or content[:2] == "\n4" or content[:4] == "\n\n4":
# if content[:1] == '3' or content[:2] == ' 3' or content[:2] == "\n3" or content[:3] == "\n\n3":
content = content[1:]
# use an API key for an account with GPT3 if you prefer to use a different key
OPENAI_API_KEY = os.environ.get('OPENAI_API_KEY4', OPENAI_API_KEY)
model = 'gpt-4'
content = re.sub(r'^( *)\n{0,2}4', r'\1', content)
if content[1:3] == 'mm':
with open(dir + file, "w") as f:
f.write(original_content)
n = int(content[:1])
if content[3:4] == 'e':
response = openai.Image.create_edit(
image=open('{}/images/edit.png'.format(dir), 'rb'),
mask=open('{}/images/mask.png'.format(dir), 'rb'),
prompt=content[4:],
n=n,
size='1024x1024'
)
elif content[3:4] == 'v':
# variation_image = '{}/images/img{}.png'.format(dir, content[4:5])
# os.system('cp {} {}'.format(variation_image, variation_image.replace('.png', '-orig.png')))
response = openai.Image.create_variation(
image=open('{}/images/edit.png'.format(dir), 'rb'),
# image=open(variation_image, 'rb'),
n=n,
prompt=content[4:],
size='1024x1024'
)
else:
response = openai.Image.create(
prompt=content[3:],
n=n,
size='512x512'
)
for i, data in enumerate(response['data']):
image_url = data['url']
print(os.popen("/usr/local/bin/wget -O {}/images/img{}.png '{}'".format(dir, i, image_url)))
os.system('open {}/images'.format(dir))
exit()
arr = arr[:1] if content[:1] in ['XX ', 'XX\n'] else (
arr[::-1] if content[:2] == '..' else
[x if i % 2 == 0 or i == 1 else '' for i, x in enumerate(arr)][::-1])
messages = [{'role': 'user' if i % 2 == 0 else 'assistant', 'content': x}
for i, x in enumerate(arr)]
if content[:1] == '=' or content[:2] == '=':
messages.insert(0, {'role': 'system', 'content': 'fix any garammar in the user prompt using excellent English, keep any foul language.'})
elif content[:1] == '/' or content[:2] == '/':
messages.insert(0, {'role': 'system', 'content': 'walk through your thinking process step by step'})
elif content[:1] == '.' or content[:2] == '.':
messages.insert(0, {'role': 'system', 'content': 'give me very short and concise answers and ignore all the niceties that openai programmed you with.'})
terminating = False
q = queue.Queue()
def signal_handler(sig, frame):
# Add your command to run here
print("\nCtrl+C detected! Running a command before exiting...")
with open(dir + file, "w") as f:
f.write(original_content)
sys.exit(0)
# Register the signal handler
signal.signal(signal.SIGINT, signal_handler)
with open(dir + file + '.swp', 'w') as f:
f.write(original_content)
# print(openai.Model.list())
res = openai.ChatCompletion.create(
model=model,
# model="gpt-3.5-turbo",
# model="gpt-4",
# model="gpt-4-32k",
messages=messages,
stream=True
)
# append the streamed result back to the file for the IDE to reload
def thread_write_to_file(q):
while not terminating:
with open(dir + file, "a") as f:
f.write(q.get())
q.task_done()
# in case IDE prompts to reload file, this repeatedly presses Esc
def thread_call_timer():
return
while not terminating:
os.system("""
osascript -e '
tell application "System Events"
set activeApp to name of first application process whose frontmost is true
end tell
if activeApp is "sublime_text" then
tell application "System Events" to key code 53
end if
'
""")
time.sleep(2)
msg = ''
chunk = ''
i = 0
ii = 0
start_time = None
thread1 = threading.Thread(target=thread_write_to_file, args=(q,))
thread1.daemon = True
thread1.start()
thread2 = threading.Thread(target=thread_call_timer)
thread2.daemon = True
thread2.start()
last_execution_time = time.time()
for resp in res:
if not start_time:
start_time = time.time()
try:
chunk = resp.choices[0].delta.content
q.put(chunk)
i += 1
msg += chunk
except:
print('..')
# write the final result back to the file and replace all content of the file after all the incremental appends
with open(dir + file, 'w') as f:
f.write("\n\n" + DELIMETER + "\n\n" + msg.replace("assistant:\n", '').replace("assistant: ", '').replace("Assistant: ", '') +
"\n\n" + DELIMETER + "\n\n" + content.replace("assistant:\n", '').replace("assistant: ", '').replace("Assistant: ", ''))
os.system('rm ' + dir + file + '.swp')
# allows threads to break out of their infinite loop and terminate
terminating = True
q.put('')
# move focus back to IDE and press Esc to dismiss any dialog windows asking if ok to file, etc.
# os.system("""sleep 0.6;osascript -e 'tell application "Sublime Text" to activate' -e 'tell application "System Events" to key code 53'""")
if __name__ == "__main__":
main()