Ripped off another, better repo and implemented my own changes

This commit is contained in:
Max Gialanella 2023-11-02 03:17:49 -07:00
parent 3b579a5a28
commit 01bea44307
3 changed files with 618 additions and 0 deletions

View File

@ -0,0 +1,405 @@
#Requires AutoHotkey v2.0.2
#SingleInstance
#Include "_jxon.ahk"
/*
====================================================
Script Tray Menu
====================================================
*/
TraySetIcon("Icon.ico")
A_TrayMenu.Delete
A_TrayMenu.Add("&Debug", Debug)
A_TrayMenu.Add("&Reload Script", ReloadScript)
A_TrayMenu.Add("E&xit", Exit)
A_IconTip := "ChatGPT AutoHotkey Utility"
ReloadScript(*) {
Reload
}
Debug(*) {
ListLines
}
Exit(*) {
ExitApp
}
/*
====================================================
Dark mode menu
====================================================
*/
Class DarkMode {
Static __New(Mode := 1) => ( ; Mode: Dark = 1, Default (Light) = 0
DllCall(DllCall("GetProcAddress", "ptr", DllCall("GetModuleHandle", "str", "uxtheme", "ptr"), "ptr", 135, "ptr"), "int", mode),
DllCall(DllCall("GetProcAddress", "ptr", DllCall("GetModuleHandle", "str", "uxtheme", "ptr"), "ptr", 136, "ptr"))
)
}
/*
====================================================
Variables
====================================================
*/
API_Key := "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"
API_URL := "https://api.openai.com/v1/chat/completions"
Status_Message := ""
Response_Window_Status := "Closed"
Retry_Status := ""
Last_Api_Response := ""
/*
====================================================
Menus and ChatGPT prompts
====================================================
*/
MenuPopup := Menu()
MenuPopup.Add("&1 - Rephrase", Rephrase)
MenuPopup.Add("&2 - Summarize", Summarize)
MenuPopup.Add("&3 - Explain", Explain)
MenuPopup.Add("&4 - Expand", Expand)
MenuPopup.Add()
MenuPopup.Add("&5 - Generate reply", GenerateReply)
MenuPopup.Add("&6 - Find action items", FindActionItems)
MenuPopup.Add("&7 - Translate to English", TranslateToEnglish)
MenuPopup.Add("&8 - JS Code Snippet", Snippet)
Snippet(*) {
ChatGPT_Prompt := "Use the following input to create a code snippet. Only output ES6 Javascript no additional details or explanations, only code. No other output, only JS code. Create a clear, concise output with readable camel case variable names. Make sure the code is clear, understandable and maintainable. If its necessary use existing variable names with the output. The input is:"
Status_Message := "Snippetizing..."
API_Model := "gpt-4"
CodeResquestProcess(ChatGPT_Prompt, Status_Message, API_Model, Retry_Status)
}
Rephrase(*) {
ChatGPT_Prompt := "Rephrase the following text or paragraph to ensure clarity, conciseness, and a natural flow. The revision should preserve the tone, style, and formatting of the original text. Additionally, correct any grammar and spelling errors you come across:"
Status_Message := "Rephrasing..."
API_Model := "gpt-4"
ProcessRequest(ChatGPT_Prompt, Status_Message, API_Model, Retry_Status)
}
Summarize(*) {
ChatGPT_Prompt := "Summarize the following:"
Status_Message := "Summarizing..."
API_Model := "gpt-4"
ProcessRequest(ChatGPT_Prompt, Status_Message, API_Model, Retry_Status)
}
Explain(*) {
ChatGPT_Prompt := "Explain the following:"
Status_Message := "Explaining..."
API_Model := "gpt-3.5-turbo"
ProcessRequest(ChatGPT_Prompt, Status_Message, API_Model, Retry_Status)
}
Expand(*) {
ChatGPT_Prompt := "Considering the original tone, style, and formatting, please help me express the following idea in a clearer and more articulate way. The style of the message could be formal, informal, casual, empathetic, assertive, or persuasive, depending on the context of the original message. The text should be divided into paragraphs for readability. No specific language complexities need to be avoided and the focus should be equally distributed throughout the message. There's no set minimum or maximum length. Here's what I'm trying to say:"
Status_Message := "Expanding..."
API_Model := "gpt-4"
ProcessRequest(ChatGPT_Prompt, Status_Message, API_Model, Retry_Status)
}
GenerateReply(*) {
ChatGPT_Prompt := "Craft a response to any given message. The response should adhere to the original sender's tone, style, formatting, and cultural or regional context. Maintain the same level of formality and emotional tone as the original message. Responses may be of any length, provided they effectively communicate the response to the original sender:"
Status_Message := "Generating reply..."
API_Model := "gpt-4"
ProcessRequest(ChatGPT_Prompt, Status_Message, API_Model, Retry_Status)
}
FindActionItems(*) {
ChatGPT_Prompt := "Find action items that needs to be done and present them in a list:"
Status_Message := "Finding action items..."
API_Model := "gpt-3.5-turbo"
ProcessRequest(ChatGPT_Prompt, Status_Message, API_Model, Retry_Status)
}
TranslateToEnglish(*) {
ChatGPT_Prompt := "Generate an English translation for the following text or paragraph, ensuring the translation accurately conveys the intended meaning or idea without excessive deviation. The translation should preserve the tone, style, and formatting of the original text:"
Status_Message := "Translating to English..."
API_Model := "gpt-4"
ProcessRequest(ChatGPT_Prompt, Status_Message, API_Model, Retry_Status)
}
/*
====================================================
Create Response Window
====================================================
*/
Response_Window := Gui("-Caption", "Response")
Response_Window.BackColor := "0x333333"
Response_Window.SetFont("s13 cWhite", "Georgia")
Response := Response_Window.Add("Edit", "r20 ReadOnly w600 Wrap Background333333", Status_Message)
RetryButton := Response_Window.Add("Button", "x190 Disabled", "Retry")
RetryButton.OnEvent("Click", Retry)
CopyButton := Response_Window.Add("Button", "x+30 w80 Disabled", "Copy")
CopyButton.OnEvent("Click", Copy)
Response_Window.Add("Button", "x+30", "Close").OnEvent("Click", Close)
Response_Window.Add("Button", "Default x+30", "Looks Good").OnEvent("Click", Confirm)
Response_Window.OnEvent("Escape", Confirm)
/*
====================================================
Buttons
====================================================
*/
Retry(*) {
Retry_Status := "Retry"
RetryButton.Enabled := 0
CopyButton.Enabled := 0
CopyButton.Text := "Copy"
ProcessRequest(Previous_ChatGPT_Prompt, Previous_Status_Message, Previous_API_Model, Retry_Status)
}
Copy(*) {
A_Clipboard := Response.Value
CopyButton.Enabled := 0
CopyButton.Text := "Copied!"
DllCall("SetFocus", "Ptr", 0)
Sleep 2000
CopyButton.Enabled := 1
CopyButton.Text := "Copy"
}
Confirm(*) {
Global Last_Api_Response
Close()
DllCall("SetFocus", "Ptr", 0)
; Move cursor to start, then comment out line
SendInput("{Home}// ")
SendInput("{End} `r")
; clean up chat GPT output for editor
Last_Api_Response := StrReplace(Last_Api_Response, "``````Javascript", "")
Last_Api_Response := StrReplace(Last_Api_Response, "``````", "")
Last_Api_Response := Trim(Last_Api_Response, "`r`n`t ")
; push output to clipboard then paste
A_Clipboard := Last_Api_Response
Sleep 100
Send("^v`r") ; paste and return
Sleep 1000
Last_Api_Response := ""
}
Close(*) {
HTTP_Request.Abort
Response_Window.Hide
global Response_Window_Status := "Closed"
}
/*
====================================================
Connect to ChatGPT API and process request
====================================================
*/
ProcessRequest(ChatGPT_Prompt, Status_Message, API_Model, Retry_Status) {
if (Retry_Status != "Retry") {
A_Clipboard := ""
Send "^c"
if !ClipWait(2) {
MsgBox "The attempt to copy text onto the clipboard failed."
return
}
CopiedText := A_Clipboard
ChatGPT_Prompt := ChatGPT_Prompt "`n`n" CopiedText
ChatGPT_Prompt := RegExReplace(ChatGPT_Prompt, '(\\|")+', '\$1') ; Clean back spaces and quotes
ChatGPT_Prompt := RegExReplace(ChatGPT_Prompt, "`n", "\n") ; Clean newlines
ChatGPT_Prompt := RegExReplace(ChatGPT_Prompt, "`r", "") ; Remove carriage returns
global Previous_ChatGPT_Prompt := ChatGPT_Prompt
global Previous_Status_Message := Status_Message
global Previous_API_Model := API_Model
global Response_Window_Status
}
OnMessage 0x200, WM_MOUSEHOVER
Response.Value := Status_Message
if (Response_Window_Status = "Closed") {
Response_Window.Show("AutoSize Center")
Response_Window_Status := "Open"
RetryButton.Enabled := 0
CopyButton.Enabled := 0
}
DllCall("SetFocus", "Ptr", 0)
global HTTP_Request := ComObject("WinHttp.WinHttpRequest.5.1")
HTTP_Request.open("POST", API_URL, true)
HTTP_Request.SetRequestHeader("Content-Type", "application/json")
HTTP_Request.SetRequestHeader("Authorization", "Bearer " API_Key)
Messages := '{ "role": "user", "content": "' ChatGPT_Prompt '" }'
JSON_Request := '{ "model": "' API_Model '", "messages": [' Messages '] }'
HTTP_Request.SetTimeouts(60000, 60000, 60000, 60000)
HTTP_Request.Send(JSON_Request)
SetTimer LoadingCursor, 1
if WinExist("Response") {
WinActivate "Response"
}
HTTP_Request.WaitForResponse
try {
if (HTTP_Request.status == 200) {
SafeArray := HTTP_Request.responseBody
pData := NumGet(ComObjValue(SafeArray) + 8 + A_PtrSize, 'Ptr')
length := SafeArray.MaxIndex() + 1
JSON_Response := StrGet(pData, length, 'UTF-8')
var := Jxon_Load(&JSON_Response)
JSON_Response := var.Get("choices")[1].Get("message").Get("content")
RetryButton.Enabled := 1
CopyButton.Enabled := 1
Response.Value := JSON_Response
SetTimer LoadingCursor, 0
OnMessage 0x200, WM_MOUSEHOVER, 0
Cursor := DllCall("LoadCursor", "uint", 0, "uint", 32512) ; Arrow cursor
DllCall("SetCursor", "UPtr", Cursor)
Response_Window.Flash()
DllCall("SetFocus", "Ptr", 0)
} else {
RetryButton.Enabled := 1
CopyButton.Enabled := 1
Response.Value := "Status " HTTP_Request.status " " HTTP_Request.responseText
SetTimer LoadingCursor, 0
OnMessage 0x200, WM_MOUSEHOVER, 0
Cursor := DllCall("LoadCursor", "uint", 0, "uint", 32512) ; Arrow cursor
DllCall("SetCursor", "UPtr", Cursor)
Response_Window.Flash()
DllCall("SetFocus", "Ptr", 0)
}
}
}
CodeResquestProcess(ChatGPT_Prompt, Status_Message, API_Model, Retry_Status) {
Global Last_Api_Response
Global Response_Window
if (Retry_Status != "Retry") {
A_Clipboard := ""
Send "^c"
if !ClipWait(2) {
MsgBox "The attempt to copy text onto the clipboard failed."
return
}
CopiedText := A_Clipboard
ChatGPT_Prompt := ChatGPT_Prompt "`n`n" CopiedText
ChatGPT_Prompt := RegExReplace(ChatGPT_Prompt, '(\\|")+', '\$1') ; Clean back spaces and quotes
ChatGPT_Prompt := RegExReplace(ChatGPT_Prompt, "`n", "\n") ; Clean newlines
ChatGPT_Prompt := RegExReplace(ChatGPT_Prompt, "`r", "") ; Remove carriage returns
global Previous_ChatGPT_Prompt := ChatGPT_Prompt
global Previous_Status_Message := Status_Message
global Previous_API_Model := API_Model
global Response_Window_Status
}
; OnMessage 0x200, WM_MOUSEHOVER
Response.Value := Status_Message
if (Response_Window_Status = "Closed") {
Response_Window.Show("AutoSize Center")
Response_Window_Status := "Open"
RetryButton.Enabled := 0
CopyButton.Enabled := 0
}
; DllCall("SetFocus", "Ptr", 0)
global HTTP_Request := ComObject("WinHttp.WinHttpRequest.5.1")
HTTP_Request.open("POST", API_URL, true)
HTTP_Request.SetRequestHeader("Content-Type", "application/json")
HTTP_Request.SetRequestHeader("Authorization", "Bearer " API_Key)
Messages := '{ "role": "user", "content": "' ChatGPT_Prompt '" }'
JSON_Request := '{ "model": "' API_Model '", "messages": [' Messages '] }'
HTTP_Request.SetTimeouts(6000, 6000, 6000, 6000)
HTTP_Request.Send(JSON_Request)
; SetTimer LoadingCursor, 1
if WinExist("Response") {
WinActivate "Response"
}
HTTP_Request.WaitForResponse
try {
if (HTTP_Request.status == 200) {
SafeArray := HTTP_Request.responseBody
pData := NumGet(ComObjValue(SafeArray) + 8 + A_PtrSize, 'Ptr')
length := SafeArray.MaxIndex() + 1
JSON_Response := StrGet(pData, length, 'UTF-8')
var := Jxon_Load(&JSON_Response)
JSON_Response := var.Get("choices")[1].Get("message").Get("content")
RetryButton.Enabled := 1
CopyButton.Enabled := 1
Response.Value := JSON_Response
Last_Api_Response := JSON_Response
Response_Window.Focus()
; SetTimer LoadingCursor, 0
; OnMessage 0x200, WM_MOUSEHOVER, 0
; Cursor := DllCall("LoadCursor", "uint", 0, "uint", 32512) ; Arrow cursor
; DllCall("SetCursor", "UPtr", Cursor)
; Response_Window.Flash()
; DllCall("SetFocus", "Ptr", 0)
} else {
RetryButton.Enabled := 1
CopyButton.Enabled := 1
Response.Value := "Status " HTTP_Request.status " " HTTP_Request.responseText
; SetTimer LoadingCursor, 0
; OnMessage 0x200, WM_MOUSEHOVER, 0
; Cursor := DllCall("LoadCursor", "uint", 0, "uint", 32512) ; Arrow cursor
; DllCall("SetCursor", "UPtr", Cursor)
; Response_Window.Flash()
; DllCall("SetFocus", "Ptr", 0)
}
}
}
/*
====================================================
Cursors
====================================================
*/
WM_MOUSEHOVER(*) {
Cursor := DllCall("LoadCursor", "uint", 0, "uint", 32648) ; Unavailable cursor
MouseGetPos ,,, &MousePosition
if (CopyButton.Enabled = 0) & (MousePosition = "Button2") {
DllCall("SetCursor", "UPtr", Cursor)
} else if (RetryButton.Enabled = 0) & (MousePosition = "Button1") | (MousePosition = "Button2") {
DllCall("SetCursor", "UPtr", Cursor)
}
}
LoadingCursor() {
MouseGetPos ,,, &MousePosition
if (MousePosition = "Edit1") {
Cursor := DllCall("LoadCursor", "uint", 0, "uint", 32514) ; Loading cursor
DllCall("SetCursor", "UPtr", Cursor)
}
}
/*
====================================================
Hotkey
====================================================
*/
;`::MenuPopup.Show()
~::Snippet()

BIN
Icon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 112 KiB

213
_jxon.ahk Normal file
View File

@ -0,0 +1,213 @@
;;;; AHK v2 - https://github.com/TheArkive/JXON_ahk2
;MIT License
;Copyright (c) 2021 TheArkive
;Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
;The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
;THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
;
; Example ===================================================================================
; ===========================================================================================
; Msgbox "The idea here is to create several nested arrays, save to text with jxon_dump(), and then reload the array with jxon_load(). The resulting array should be the same.`r`n`r`nThis is what this example shows."
; a := Map(), b := Map(), c := Map(), d := Map(), e := Map(), f := Map() ; Object() is more technically correct than {} but both will work.
; d["g"] := 1, d["h"] := 2, d["i"] := ["purple","pink","pippy red"]
; e["g"] := 1, e["h"] := 2, e["i"] := Map("1","test1","2","test2","3","test3")
; f["g"] := 1, f["h"] := 2, f["i"] := [1,2,Map("a",1.0009,"b",2.0003,"c",3.0001)]
; a["test1"] := "test11", a["d"] := d
; b["test3"] := "test33", b["e"] := e
; c["test5"] := "test55", c["f"] := f
; myObj := Map()
; myObj["a"] := a, myObj["b"] := b, myObj["c"] := c, myObj["test7"] := "test77", myObj["test8"] := "test88"
; g := ["blue","green","red"], myObj["h"] := g ; add linear array for testing
; q := Chr(34)
; textData2 := Jxon_dump(myObj,4) ; ===> convert array to JSON
; msgbox "JSON output text:`r`n===========================================`r`n(Should match second output.)`r`n`r`n" textData2
; newObj := Jxon_load(&textData2) ; ===> convert json back to array
; textData3 := Jxon_dump(newObj,4) ; ===> break down array into 2D layout again, should be identical
; msgbox "Second output text:`r`n===========================================`r`n(should be identical to first output)`r`n`r`n" textData3
; msgbox "textData2 = textData3: " ((textData2=textData3) ? "true" : "false")
; ===========================================================================================
; End Example ; =============================================================================
; ===========================================================================================
; originally posted by user coco on AutoHotkey.com
; https://github.com/cocobelgica/AutoHotkey-JSON
Jxon_Load(&src, args*) {
key := "", is_key := false
stack := [ tree := [] ]
next := '"{[01234567890-tfn'
pos := 0
while ( (ch := SubStr(src, ++pos, 1)) != "" ) {
if InStr(" `t`n`r", ch)
continue
if !InStr(next, ch, true) {
testArr := StrSplit(SubStr(src, 1, pos), "`n")
ln := testArr.Length
col := pos - InStr(src, "`n",, -(StrLen(src)-pos+1))
msg := Format("{}: line {} col {} (char {})"
, (next == "") ? ["Extra data", ch := SubStr(src, pos)][1]
: (next == "'") ? "Unterminated string starting at"
: (next == "\") ? "Invalid \escape"
: (next == ":") ? "Expecting ':' delimiter"
: (next == '"') ? "Expecting object key enclosed in double quotes"
: (next == '"}') ? "Expecting object key enclosed in double quotes or object closing '}'"
: (next == ",}") ? "Expecting ',' delimiter or object closing '}'"
: (next == ",]") ? "Expecting ',' delimiter or array closing ']'"
: [ "Expecting JSON value(string, number, [true, false, null], object or array)"
, ch := SubStr(src, pos, (SubStr(src, pos)~="[\]\},\s]|$")-1) ][1]
, ln, col, pos)
throw Error(msg, -1, ch)
}
obj := stack[1]
is_array := (obj is Array)
if i := InStr("{[", ch) { ; start new object / map?
val := (i = 1) ? Map() : Array() ; ahk v2
is_array ? obj.Push(val) : obj[key] := val
stack.InsertAt(1,val)
next := '"' ((is_key := (ch == "{")) ? "}" : "{[]0123456789-tfn")
} else if InStr("}]", ch) {
stack.RemoveAt(1)
next := (stack[1]==tree) ? "" : (stack[1] is Array) ? ",]" : ",}"
} else if InStr(",:", ch) {
is_key := (!is_array && ch == ",")
next := is_key ? '"' : '"{[0123456789-tfn'
} else { ; string | number | true | false | null
if (ch == '"') { ; string
i := pos
while i := InStr(src, '"',, i+1) {
val := StrReplace(SubStr(src, pos+1, i-pos-1), "\\", "\u005C")
if (SubStr(val, -1) != "\")
break
}
if !i ? (pos--, next := "'") : 0
continue
pos := i ; update pos
val := StrReplace(val, "\/", "/")
val := StrReplace(val, '\"', '"')
, val := StrReplace(val, "\b", "`b")
, val := StrReplace(val, "\f", "`f")
, val := StrReplace(val, "\n", "`n")
, val := StrReplace(val, "\r", "`r")
, val := StrReplace(val, "\t", "`t")
i := 0
while i := InStr(val, "\",, i+1) {
if (SubStr(val, i+1, 1) != "u") ? (pos -= StrLen(SubStr(val, i)), next := "\") : 0
continue 2
xxxx := Abs("0x" . SubStr(val, i+2, 4)) ; \uXXXX - JSON unicode escape sequence
if (xxxx < 0x100)
val := SubStr(val, 1, i-1) . Chr(xxxx) . SubStr(val, i+6)
}
if is_key {
key := val, next := ":"
continue
}
} else { ; number | true | false | null
val := SubStr(src, pos, i := RegExMatch(src, "[\]\},\s]|$",, pos)-pos)
if IsInteger(val)
val += 0
else if IsFloat(val)
val += 0
else if (val == "true" || val == "false")
val := (val == "true")
else if (val == "null")
val := ""
else if is_key {
pos--, next := "#"
continue
}
pos += i-1
}
is_array ? obj.Push(val) : obj[key] := val
next := obj == tree ? "" : is_array ? ",]" : ",}"
}
}
return tree[1]
}
Jxon_Dump(obj, indent:="", lvl:=1) {
if IsObject(obj) {
If !(obj is Array || obj is Map || obj is String || obj is Number)
throw Error("Object type not supported.", -1, Format("<Object at 0x{:p}>", ObjPtr(obj)))
if IsInteger(indent)
{
if (indent < 0)
throw Error("Indent parameter must be a postive integer.", -1, indent)
spaces := indent, indent := ""
Loop spaces ; ===> changed
indent .= " "
}
indt := ""
Loop indent ? lvl : 0
indt .= indent
is_array := (obj is Array)
lvl += 1, out := "" ; Make #Warn happy
for k, v in obj {
if IsObject(k) || (k == "")
throw Error("Invalid object key.", -1, k ? Format("<Object at 0x{:p}>", ObjPtr(obj)) : "<blank>")
if !is_array ;// key ; ObjGetCapacity([k], 1)
out .= (ObjGetCapacity([k]) ? Jxon_Dump(k) : escape_str(k)) (indent ? ": " : ":") ; token + padding
out .= Jxon_Dump(v, indent, lvl) ; value
. ( indent ? ",`n" . indt : "," ) ; token + indent
}
if (out != "") {
out := Trim(out, ",`n" . indent)
if (indent != "")
out := "`n" . indt . out . "`n" . SubStr(indt, StrLen(indent)+1)
}
return is_array ? "[" . out . "]" : "{" . out . "}"
} Else If (obj is Number)
return obj
Else ; String
return escape_str(obj)
escape_str(obj) {
obj := StrReplace(obj,"\","\\")
obj := StrReplace(obj,"`t","\t")
obj := StrReplace(obj,"`r","\r")
obj := StrReplace(obj,"`n","\n")
obj := StrReplace(obj,"`b","\b")
obj := StrReplace(obj,"`f","\f")
obj := StrReplace(obj,"/","\/")
obj := StrReplace(obj,'"','\"')
return '"' obj '"'
}
}