-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathgenerateImage.js
More file actions
93 lines (76 loc) · 2.65 KB
/
generateImage.js
File metadata and controls
93 lines (76 loc) · 2.65 KB
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
const { Configuration, OpenAIApi } = require("openai");
const fs = require("fs");
const path = require("path");
const API_KEY = "that ur problem";
const DEFAULT_MODEL = "image-alpha-001";
const AVAILABLE_MODELS = [
"image-alpha-001",
"image-alpha-002",
"image-alpha-003",
"image-dall-E-002",
"image-curie-001",
"image-curie-002",
"image-babbage-001",
"image-jukebox-001",
];
const RATE_LIMIT_COUNT = 100;
const usageDataPath = path.join(__dirname, "usageData.json");
const configuration = new Configuration({
apiKey: API_KEY,
});
const openai = new OpenAIApi(configuration);
let usageData = {};
// Load the usage data from the file
try {
const rawData = fs.readFileSync(usageDataPath);
usageData = JSON.parse(rawData);
} catch (error) {
console.error("Failed to load usage data from file", error);
}
// Save the usage data to the file
function saveUsageData() {
fs.writeFileSync(usageDataPath, JSON.stringify(usageData));
}
async function ask(prompt, message, model = DEFAULT_MODEL) {
let userId = null;
if (message && message.author_id) {
userId = message.author_id;
}
if (!AVAILABLE_MODELS.includes(model)) {
throw new Error(`Error: The model "${model}" is not available. Please choose from: ${AVAILABLE_MODELS.join(", ")}`);
}
const now = Date.now();
const userUsage = usageData[userId] || { count: 0, resetTime: 0 };
// Check if the user has exceeded the usage limit
if (userUsage.count >= RATE_LIMIT_COUNT && now < userUsage.resetTime) {
const timeLeft = Math.ceil((userUsage.resetTime - now) / 100);
throw new Error(`Usage limit reached for user ${userId}. Try again in ${timeLeft} seconds.`);
}
userUsage.count++;
// Check if the user has used the API 100 times
if (userUsage.count === 100) {
userUsage.limitReached = true;
}
// Save the updated usage data to the file
usageData[userId] = userUsage;
saveUsageData();
if (userUsage.limitReached) {
return { success: false, error: "User" + `<@${userId}>` + "has reached 100 API uses. want more [support](rvlt.gg/qvJEsmPt) us [images](https://autumn.revolt.chat/attachments/0s377fGbuwcX4AA0aa3b1k-HC2VDJv2YJIGScAKyeB/image.png)" };
}
try {
const response = await openai.createImage({
prompt,
model,
n: 1,
size: "512x512"
});
const imageUrls = response?.data?.data?.map(({ url }) => url);
return { success: true, imageUrls };
} catch (error) {
console.error(error);
return { success: false, error: error.message + " or bad prompt [maybe](<https://status.openai.com/>)" };
}
}
module.exports = {
ask,
};