-
Notifications
You must be signed in to change notification settings - Fork 0
/
image_gen.ts
60 lines (50 loc) · 1.64 KB
/
image_gen.ts
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
import axios from "axios"
import { createWriteStream, existsSync, mkdirSync } from "fs"
import { join } from "path"
import dotenv from "dotenv"
import { QUEUE_NAMES, imageQueue } from "./queue/queue"
dotenv.config()
const isValidImage = (img: string) => {
if (img.includes(".jpg") || img.includes(".jpeg") || img.includes(".png"))
return true
return false
}
const api_key = process.env.SERP_API_KEY as string
export async function GenerateImages(img_prompt: string, count: number) {
const res = await fetch(
`${process.env.SERPAPI_ENDPOINT}&q=${img_prompt}&api_key=${api_key}&gl=in&ijn=1`
)
const data = await res.json()
let imageUrl = ""
for (let idx = 0; idx < data.images_results.length; idx++) {
if (isValidImage(data.images_results[idx].original)) {
imageUrl = data.images_results[idx].original
break
}
}
const saveDirectory = "../images"
if (!existsSync(saveDirectory)) mkdirSync(saveDirectory, { recursive: true })
const fileName = `downloaded_image_${count}.jpg`
const filePath = join(saveDirectory, fileName)
try {
const imgDownloadData = await axios({
method: "get",
url: imageUrl,
responseType: "stream",
})
if (imgDownloadData.status === 200) {
const writer = createWriteStream(filePath)
imgDownloadData.data.pipe(writer)
console.log(`Image downloaded to ${filePath}`)
return new Promise((resolve, reject) => {
writer.on("finish", () => {
imageQueue.add(QUEUE_NAMES.imageQueue, { imageUrl: filePath })
resolve(true)
})
writer.on("error", reject)
})
}
} catch (error) {
console.log(error)
}
}