-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLorem-Chatum-v2.idjs
253 lines (212 loc) · 8.21 KB
/
Lorem-Chatum-v2.idjs
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
// Lorem Chatum v2.0 for Adobe InDesign 2023 and newer
// Copyright (c) 2023 by Adam Twardoch
// https://github.com/twardoch/lorem-chatum-for-indesign
// Licensed under the Apache 2.0 License
// Create a new OpenAI API secret key at https://platform.openai.com/account/api-keys
// and paste it below
const OPENAI_API_KEY = "sk-";
let TEXT_COLOR;
if (app.generalPreferences.uiBrightnessPreference <= 0.5) {
TEXT_COLOR = "white";
} else {
TEXT_COLOR = "black";
}
async function alert(msg) {
return new Promise((resolve) => {
const dialog = document.createElement("dialog");
dialog.innerHTML = `
<form method="dialog" style="display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 8px 14px; color: inherit;">
<sp-body size="S" style="color: ${TEXT_COLOR};">
<sp-text id="alert-message">${msg}</sp-text>
</sp-body>
<sp-footer>
<sp-button id="ok-button" variant="cta">OK</sp-button>
</sp-footer>
</form>
`;
const okButton = dialog.querySelector("#ok-button");
okButton.addEventListener("click", () => {
dialog.close();
resolve();
});
document.body.appendChild(dialog);
dialog.showModal();
});
}
async function showProgress() {
const dialog = document.createElement("dialog");
dialog.innerHTML = `
<form method="dialog" style="padding: 8px 14px;">
<sp-body size="S" style="color: ${TEXT_COLOR};">
<sp-text>Lorem Chatum dolor...</sp-text>
</sp-body>
</form>
`;
document.body.appendChild(dialog);
const progressBar = dialog.querySelector("#progress-bar");
dialog.showModal();
return { dialog, progressBar };
}
async function openAIApi(apiKey, prompt, lang, maxTokens) {
let requestBody = JSON.stringify({
model: 'gpt-3.5-turbo',
messages: [
{
role: 'system',
content:
'Write an essay in ' + lang + ', to the max length, by continuing the prompt. Do not ask anything, do not add anything that is not requested.',
},
{ role: 'user', content: prompt },
],
temperature: 1,
max_tokens: maxTokens,
top_p: 1,
n: 1,
frequency_penalty: 0,
presence_penalty: 0,
});
let response = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + apiKey,
},
body: requestBody
});
if (!response.ok) {
if (response.statusText == 'unauthorized') {
throw new Error(`<a href="https://platform.openai.com/account/api-keys">Click here to create an OpenAI API secret key,</a> then paste it at the beginning of this script, and run again.`);
} else {
throw new Error(`Error connecting to OpenAI API: ${response.statusText}.`);
}
}
let responseData = await response.json();
let completion = responseData.choices[0].message.content;
return completion;
}
/// Rest of the script
async function getText(textFrame) {
var text = "";
var words = textFrame.words;
if (words != null) {
for (var i = 0; i < words.length; i++) {
var word = words.item(i);
var wordContent = word.contents;
if (typeof wordContent === 'string') {
text += wordContent + " ";
}
}
}
return text;
}
async function getContext(textFrame) {
var context = await getText(textFrame);
if (context.length === 0) {
context = await collectPageText(textFrame);
}
return context;
}
async function collectPageText(textFrame) {
var currentPage = textFrame.parentPage;
var pages = [];
pages.push(currentPage);
var combinedText = '';
var maxWords = 500;
for (var i = 0; i < pages.length; i++) {
combinedText += await getTextFromPage(pages[i]);
if (wordCount(combinedText) >= maxWords) {
combinedText = await capTextAtWords(combinedText, maxWords);
break;
}
}
return combinedText;
}
async function getTextFromPage(page) {
var textFrames = page.textFrames;
var combinedText = '';
for (var i = 0; i < textFrames.length; i++) {
var textFrame = textFrames.item(i);
combinedText += await getText(textFrame);
}
return combinedText;
}
async function wordCount(text) {
var words = text.replace(/^\s+|\s+$/g, '').split(/\s+/);
return words.length;
}
async function capTextAtWords(text, wordLimit) {
var words = text.replace(/^\s+|\s+$/g, '').split(/\s+/);
var cappedWords = words.slice(0, wordLimit);
return cappedWords.join(' ');
}
async function estimateTokens(textFrame) {
var frameWidth = textFrame.geometricBounds[3] - textFrame.geometricBounds[1];
var frameHeight = textFrame.geometricBounds[2] - textFrame.geometricBounds[0];
var fontSize = textFrame.texts.item(0).pointSize;
var lineHeight = fontSize * 1.2;
var avgCharWidth = fontSize * 0.6;
var charsPerLine = Math.floor(frameWidth / avgCharWidth);
var lines = Math.floor(frameHeight / lineHeight);
var estimatedChars = charsPerLine * lines;
console.warn(" frameHeight: " + frameHeight);
console.warn(" frameWidth: " + frameWidth);
console.warn(" lineHeight: " + lineHeight);
console.warn(" fontSize: " + fontSize);
console.warn(" Lines: " + lines);
console.warn(" Chars per line: " + charsPerLine);
console.warn(" Chars: " + estimatedChars);
var estimatedTokens = Math.min(Math.ceil(estimatedChars), 4095);
return estimatedTokens;
}
async function getOpenAIApiKey() {
return OPENAI_API_KEY;
}
async function getOpenAICompletion(context, lang, estimatedTokens) {
var apiKey = await getOpenAIApiKey();
var prompt = context.replace(/[\r\n]+/g, ' ') + ' ';
var completion = '';
try {
completion = await openAIApi(apiKey, prompt, lang, estimatedTokens);
} catch (error) {
await alert('OpenAI error: ' + error.message);
}
return ' ' + completion.replace(/^\n/, '');
}
async function completeSelectedFrameText() {
if (
app.documents.length === 0 ||
app.selection.length !== 1 ||
app.selection[0].constructorName !== 'TextFrame'
) {
await alert('Please select a text frame, and set the Character language to the desired language.');
return;
}
doc = app.activeDocument;
const horizontalMeasurementUnits = doc.viewPreferences.horizontalMeasurementUnits;
doc.viewPreferences.horizontalMeasurementUnits = MeasurementUnits.points;
const verticalMeasurementUnits = doc.viewPreferences.verticalMeasurementUnits;
doc.viewPreferences.verticalMeasurementUnits = MeasurementUnits.points;
const typographicMeasurementUnits = doc.viewPreferences.typographicMeasurementUnits;
doc.viewPreferences.typographicMeasurementUnits = MeasurementUnits.points;
const textSizeMeasurementUnits = doc.viewPreferences.textSizeMeasurementUnits;
doc.viewPreferences.textSizeMeasurementUnits = MeasurementUnits.points;
const { dialog: progressDialog } = await showProgress();
try {
var textFrame = app.selection[0];
var context = await getContext(textFrame);
var lang = textFrame.texts.item(0).appliedLanguage.name.split(":")[0];
console.warn("CONTEXT: " + context);
var estimatedTokens = await estimateTokens(textFrame);
console.warn("TOKENS: " + estimatedTokens + " LANG: " + lang);
var completion = await getOpenAICompletion(context, lang, estimatedTokens);
console.warn("COMPLETION: " + completion);
textFrame.contents += completion;
} finally {
progressDialog.close();
}
doc.viewPreferences.horizontalMeasurementUnits = horizontalMeasurementUnits;
doc.viewPreferences.verticalMeasurementUnits = verticalMeasurementUnits;
doc.viewPreferences.typographicMeasurementUnits = typographicMeasurementUnits;
doc.viewPreferences.textSizeMeasurementUnits = textSizeMeasurementUnits;
}
await completeSelectedFrameText();