/
index.js
195 lines (168 loc) · 5.32 KB
/
index.js
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
import { nanoid } from 'nanoid';
import { Ai } from '@cloudflare/ai';
import OpenAI from 'openai';
function _logWithCfInfo(method, request, ...args) {
const { city, region, continent, asOrganization } = request.cf;
return console[method](`[${request.headers.get('x-real-ip')} / ${city}, ${region}, ${continent} / ${asOrganization}]`, ...args);
}
const logWithCfInfo = _logWithCfInfo.bind(null, 'log');
const warnWithCfInfo = _logWithCfInfo.bind(null, 'warn');
async function _text(ai, userText, threshold, thresholdMod) {
const inputs = { text: userText };
let response = await ai.run('@cf/huggingface/distilbert-sst-2-int8', inputs);
if (thresholdMod) {
threshold += thresholdMod / 10.0;
}
const negative = response.find(({ label }) => label === 'NEGATIVE').score;
const positive = response.find(({ label }) => label === 'POSITIVE').score;
return {
negative,
positive,
good: positive - negative > threshold,
};
}
function _promptFromSentences(sentences, condFunc) {
return sentences
.filter(({ sentiment: { good } }) => condFunc(good))
.map(({ sentence }) => sentence)
.join('. ');
}
async function imageAnalysisAndPrompts(requestId, request, env, ai, headers, url) {
let openaiKey = request.headers.get('X-Yinyang-OpenAI-Key');
const allowBuiltIns = JSON.parse(env.USE_BUILTIN_OPENAI_KEY);
if (allowBuiltIns.includes(openaiKey)) {
logWithCfInfo(request, `Request using builtin OpenAI key!`);
openaiKey = env.OPENAI_KEY;
}
if (!openaiKey) {
return new Response(null, { status: 401 });
}
const openai = new OpenAI({ apiKey: openaiKey });
const prompt = await env.ConfigKVStore.get('prompt');
const detailLevel = await env.ConfigKVStore.get('detail');
let response;
try {
response = await openai.chat.completions.create({
model: 'gpt-4-vision-preview',
max_tokens: 4096,
messages: [
{
role: 'user',
content: [
{ type: 'text', text: prompt },
{
type: 'image_url',
image_url: {
url,
detail: detailLevel,
},
},
],
},
],
});
} catch (e) {
const estr = `OpenAI failed: ${e}`;
console.error(estr);
return new Response(estr, { headers, status: 500 });
}
const { content } = response.choices[0].message;
if (!content) {
return new Response(null, { headers, status: 418 });
}
const threshold = Number.parseFloat(await env.ConfigKVStore.get('goodThreshold'));
let thresholdMod;
if (request.headers.has('X-Yinyang-Threshold-Mod')) {
thresholdMod = Number.parseFloat(request.headers.get('X-Yinyang-Threshold-Mod'));
}
const sentences = await Promise.all(
content
.replaceAll(/\n/g, ' ')
.replaceAll(/[^\w\d\.,\- ]/g, '')
.split('. ')
.map(async (sentence) => ({
sentence,
sentiment: await _text(ai, sentence, threshold, thresholdMod),
})),
);
const goodPrompt = _promptFromSentences(sentences, (good) => good);
const badPrompt = _promptFromSentences(sentences, (good) => !good);
const results = {
good: {
prompt: goodPrompt,
imageBucketId: null,
},
bad: {
prompt: badPrompt,
imageBucketId: null,
},
};
const {
model,
usage: { total_tokens },
} = response;
const responseObj = {
input: {
url,
threshold,
thresholdMod,
},
createdTimeUnixMs: +new Date(),
requestorIp: request.headers.get('x-real-ip'),
requestId,
response: content,
sentences,
results,
meta: {
openai_tokens_used: total_tokens,
openai_full_model_used: model,
openai_prompt: prompt,
},
};
await env.RequestsKVStore.put(
requestId,
JSON.stringify({
...responseObj,
status: 'pending',
}),
);
await env.GENIMG_REQ_QUEUE.send({ requestId });
logWithCfInfo(request, `Posted image generation request for ${requestId}`);
return Response.json(responseObj, { headers });
}
export default {
async fetch(request, env) {
const allowedHosts = JSON.parse(await env.CommonKVStore.get('allowedHostsJSON'));
const origin = request.headers.get('origin');
if (!allowedHosts.includes(origin)) {
warnWithCfInfo(request, `Disallowed origin: ${origin}`);
return new Response(null, { status: 405 });
}
const headers = new Headers();
headers.set('Access-Control-Allow-Origin', origin);
if (!['GET', 'POST', 'OPTIONS'].includes(request.method)) {
warnWithCfInfo(request, `Bad method: ${request.method} ${request.url}`);
return new Response(null, { headers, status: 405 });
}
if (request.method === 'OPTIONS') {
headers.set('Access-Control-Allow-Headers', 'X-Yinyang-OpenAI-Key,X-Yinyang-Threshold-Mod');
return new Response(null, { status: 200, headers });
} else if (request.method === 'GET') {
const checkReqId = new URL(request.url).pathname?.slice(1);
if (!checkReqId) {
return new Response(null, { headers, status: 404 });
}
// no need to deal with eventual consistency here: just let the client try again later!
const reqObj = JSON.parse(await env.RequestsKVStore.get(checkReqId));
if (!reqObj || reqObj.status === 'pending') {
return new Response(null, { headers, status: 202 });
}
return Response.json(reqObj, { headers });
} else if (request.method === 'POST') {
const newReqId = nanoid(Number.parseInt(await env.ConfigKVStore.get('requestIdLengthBytes')));
const body = await request.text();
logWithCfInfo(request, `imageUrl: ${body}`);
return imageAnalysisAndPrompts(newReqId, request, env, new Ai(env.AI), headers, body);
}
},
};