-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathchatGPTSheet.gs
86 lines (79 loc) · 2.55 KB
/
chatGPTSheet.gs
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
function onOpen() {
SpreadsheetApp.getUi().createMenu("OpenAI")
.addItem("Generate Text", "generateText")
.addItem("Generate Images", "generateImages")
.addToUi();
}
function generateText(){
var sh = SpreadsheetApp.getActiveSheet()
var data = sh.getDataRange().getValues()
var apiKey = "YOUR API KEY";
var model = "text-davinci-003"
temperature= 0
maxTokens = 2500
var textData=[]
for (var i =1; i<data.length; i++){
var prompt = data[i][0]
const requestBody = {
"model": model,
"prompt": prompt,
"temperature": temperature,
"max_tokens": maxTokens,
};
const requestOptions = {
"method": "POST",
"headers": {
"Content-Type": "application/json",
"Authorization": "Bearer "+apiKey
},
"payload": JSON.stringify(requestBody)
}
// Call the OpenAI API
const response = UrlFetchApp.fetch("https://api.openai.com/v1/completions", requestOptions);
var responseText = response.getContentText();
var json = JSON.parse(responseText);
textData.push ([json['choices'][0]['text']])
}
sh.getRange(2,2,textData.length,1).setValues(textData)
}
function generateImages(){
var sh = SpreadsheetApp.getActiveSheet()
var data = sh.getDataRange().getValues()
var apiKey = "YOUR API KEY";
temperature= 0
maxTokens = 2500
var imageLinks=[]
for (var i =1; i<data.length; i++){
var prompt = data[i][0]
const requestBody2 = {
"prompt": prompt,
"n": 2,
"size": "512x512"
};
const requestOptions2 = {
"method": "POST",
"headers": {
"Content-Type": "application/json",
"Authorization": "Bearer "+apiKey
},
"payload": JSON.stringify(requestBody2)
}
const response = UrlFetchApp.fetch("https://api.openai.com/v1/images/generations", requestOptions2);
// Parse the response and get the generated text
var responseText = response.getContentText();
var json = JSON.parse(responseText);
var url1=json['data'][0]['url']
var url2=json['data'][1]['url']
var im1=UrlFetchApp.fetch(url1).getContent()
var blob1 = Utilities.newBlob(im1, 'image/png', data[i][0]+'-Image1');
var save1 = DriveApp.createFile(blob1);
var imgUrl1 = save1.getUrl();
var im2=UrlFetchApp.fetch(url2).getContent()
var blob2 = Utilities.newBlob(im2, 'image/png', data[i][0]+'-Image2');
var save2 = DriveApp.createFile(blob2);
var imgUrl2 = save2.getUrl();
imageLinks.push([imgUrl1,imgUrl2])
}
Logger.log(imageLinks)
sh.getRange(2,3,imageLinks.length,2).setValues(imageLinks)
}