ilhamdev commited on
Commit
9dc1f9e
·
verified ·
1 Parent(s): 4be4aaf

Delete bimg.js

Browse files
Files changed (1) hide show
  1. bimg.js +0 -169
bimg.js DELETED
@@ -1,169 +0,0 @@
1
- import axios from "axios";
2
- import fs from "node:fs";
3
- import path from "path";
4
- import "dotenv/config"
5
- import querystring from "querystring";
6
- import { performance } from "perf_hooks";
7
- const BING_URL = "https://cn.bing.com";
8
- const Config = {
9
- bingImageCookie: process.env.BING_IMAGE_COOKIE,
10
- tempDir: process.env.TEMP_DIR || "/tmp",
11
- };
12
- const createSession = (authCookie) => {
13
- const session = axios.create({
14
- headers: {
15
- accept: "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
16
- "accept-encoding": "gzip, deflate, br",
17
- "accept-language": "en-US,en;q=0.9,zh-CN;q=0.8,zh-TW;q=0.7,zh;q=0.6",
18
- "cache-control": "max-age=0",
19
- "content-type": "application/x-www-form-urlencoded",
20
- "Referrer-Policy": "origin-when-cross-origin",
21
- referrer: "https://www.bing.com/images/create/",
22
- origin: "https://www.bing.com",
23
- "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36 Edg/111.0.1661.54",
24
- cookie: `_U=${authCookie}`,
25
- "sec-ch-ua": `"Microsoft Edge";v="111", "Not(A:Brand";v="8", "Chromium";v="111"`,
26
- "sec-ch-ua-mobile": "?0",
27
- "sec-fetch-dest": "document",
28
- "sec-fetch-mode": "navigate",
29
- "sec-fetch-site": "same-origin",
30
- "sec-fetch-user": "?1",
31
- "upgrade-insecure-requests": "1",
32
- },
33
- });
34
- return session;
35
- };
36
- const getImages = async (session, prompt) => {
37
- console.log("Sending request...");
38
- const urlEncodedPrompt = querystring.escape(prompt);
39
- const url = `${BING_URL}/images/create?q=${urlEncodedPrompt}&rt=3&FORM=GENCRE`; // force use rt=3
40
- console.log(url);
41
- const response = await session.post(url, {
42
- maxRedirects: 0,
43
- validateStatus: function (status) {
44
- return status >= 200 && status < 303;
45
- },
46
- timeout: 200000,
47
- });
48
- let redirectUrl;
49
- // toHTMLfile(response, "example.html");
50
- if (response.status == 200) {
51
- redirectUrl = response.request.res.responseUrl.replace("&nfy=1", "");
52
- }
53
- else if (response.status !== 302) {
54
- console.error(`ERROR: the status is ${response.status} instead of 302 or 200`);
55
- throw new Error("Redirect failed");
56
- }
57
- console.log("Redirected to", redirectUrl);
58
- const requestId = redirectUrl.split("id=")[1];
59
- await session.get(redirectUrl);
60
- const pollingUrl = `${BING_URL}/images/create/async/results/${requestId}?q=${urlEncodedPrompt}`;
61
- console.log("Waiting for results...");
62
- const startWait = performance.now();
63
- let imagesResponse;
64
- while (true) {
65
- if (performance.now() - startWait > 300000) {
66
- throw new Error("Timeout error");
67
- }
68
- console.log(".", { end: "", flush: true });
69
- imagesResponse = await session.get(pollingUrl);
70
- if (imagesResponse.status !== 200) {
71
- throw new Error("Could not get results");
72
- }
73
- if (imagesResponse.data === "") {
74
- await new Promise((resolve) => setTimeout(resolve, 1000));
75
- continue;
76
- }
77
- else {
78
- break;
79
- }
80
- }
81
- if (imagesResponse.data.errorMessage === "Pending") {
82
- throw new Error("This prompt has been blocked by Bing. Bing's system flagged this prompt because it may conflict with their content policy. More policy violations may lead to automatic suspension of your access.");
83
- }
84
- else if (imagesResponse.data.errorMessage) {
85
- throw new Error("Bing returned an error: " + imagesResponse.data.errorMessage);
86
- }
87
- const imageLinks = imagesResponse.data
88
- .match(/src="([^"]+)"/g)
89
- .map((src) => src.slice(5, -1));
90
- const normalImageLinks = Array.from(new Set(imageLinks.map((link) => link.split("?w=")[0])));
91
- const badImages = [
92
- "https://r.bing.com/rp/in-2zU3AJUdkgFe7ZKv19yPBHVs.png",
93
- "https://r.bing.com/rp/TX9QuO3WzcCJz1uaaSwQAz39Kb0.jpg",
94
- ];
95
- for (const im of normalImageLinks) {
96
- if (badImages.includes(im)) {
97
- throw new Error("Bad images");
98
- }
99
- }
100
- if (normalImageLinks.length === 0) {
101
- throw new Error("No images");
102
- }
103
- return normalImageLinks;
104
- };
105
- const saveImages = async (session, links, outputDir) => {
106
- console.log("\nDownloading images...");
107
- try {
108
- fs.mkdirSync(outputDir, { recursive: true });
109
- }
110
- catch (err) {
111
- if (err.code !== "EEXIST")
112
- throw err;
113
- }
114
- let imageNum = 0;
115
- for (const link of links) {
116
- try {
117
- const response = await session.get(link, { responseType: "stream" });
118
- const outputPath = path.join(outputDir, `${imageNum}.jpeg`);
119
- const writer = fs.createWriteStream(outputPath);
120
- response.data.pipe(writer);
121
- await new Promise((resolve, reject) => {
122
- writer.on("finish", resolve);
123
- writer.on("error", reject);
124
- });
125
- imageNum += 1;
126
- }
127
- catch (err) {
128
- if (err instanceof axios.AxiosError) {
129
- throw new Error("Inappropriate contents found in the generated images. Please try again or try another prompt.");
130
- }
131
- else {
132
- throw err.message;
133
- }
134
- }
135
- }
136
- };
137
- export const generateImagesLinks = async (prompt) => {
138
- const authCookie = Config.bingImageCookie;
139
- const outputDir = `${Config.tempDir}/${prompt}`;
140
- if (!authCookie || !prompt) {
141
- throw new Error("Missing parameters");
142
- }
143
- // Create image generator session
144
- const session = createSession(authCookie);
145
- const imageLinks = await getImages(session, prompt);
146
- return imageLinks;
147
- };
148
- export const generateImageFiles = async (prompt) => {
149
- const authCookie = Config.bingImageCookie;
150
- const outputDir = `${Config.tempDir}/${prompt}`;
151
- if (!authCookie || !prompt) {
152
- throw new Error("Missing parameters");
153
- }
154
- // Create image generator session
155
- const session = createSession(authCookie);
156
- const imageLinks = await getImages(session, prompt);
157
- await saveImages(session, imageLinks, outputDir);
158
- // Read saved images from the output directory
159
- const imageFiles = fs.readdirSync(outputDir);
160
- const images = imageFiles.map((filename) => {
161
- const filePath = path.join(outputDir, filename);
162
- const fileData = fs.readFileSync(filePath);
163
- return {
164
- filename,
165
- data: fileData.toString("base64"),
166
- };
167
- });
168
- return images;
169
- };