aboutsummaryrefslogtreecommitdiff
path: root/src/server/ApiManagers/FireflyManager.ts
blob: a41492745e5ab8d9cd4191860f77b0bcc8bc46ba (plain)
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
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
import { Dropbox } from 'dropbox';
import * as fs from 'fs';
import * as multipart from 'parse-multipart-data';
import * as path from 'path';
import { DashUploadUtils } from '../DashUploadUtils';
import { _error, _invalid, _success, Method } from '../RouteManager';
import { Directory, filesDirectory } from '../SocketData';
import ApiManager, { Registration } from './ApiManager';

export default class FireflyManager extends ApiManager {
    getBearerToken = () =>
        fetch('https://ims-na1.adobelogin.com/ims/token/v3', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: `grant_type=client_credentials&client_id=${process.env._CLIENT_FIREFLY_CLIENT_ID}&client_secret=${process.env._CLIENT_FIREFLY_SECRET}&scope=openid,AdobeID,session,additional_info,read_organizations,firefly_api,ff_apis`,
        }).catch(error => {
            console.error('Error:', error);
            return undefined;
        });

    generateImageFromStructure = (prompt: string = 'a realistic illustration of a cat coding', structureUrl: string, strength: number) =>
        this.getBearerToken().then(response =>
            response?.json().then((data: { access_token: string }) =>
                fetch('https://firefly-api.adobe.io/v3/images/generate', {
                    method: 'POST',
                    headers: [
                        ['Content-Type', 'application/json'],
                        ['Accept', 'application/json'],
                        ['x-api-key', process.env._CLIENT_FIREFLY_CLIENT_ID ?? ''],
                        ['Authorization', `Bearer ${data.access_token}`],
                    ],
                    body: JSON.stringify({
                        prompt,
                        structure: !structureUrl
                            ? undefined
                            : {
                                  strength,
                                  imageReference: {
                                      source: { url: structureUrl },
                                  },
                              },
                    }),
                })
                    .then(response2 => response2.json().then(json => JSON.stringify((json.outputs?.[0] as { image: { url: string } })?.image)))
                    .catch(error => {
                        console.error('Error:', error);
                        return '';
                    })
            )
        );

    uploadImageToDropbox = (fileUrl: string, dbx = new Dropbox({ accessToken: process.env.DROPBOX_TOKEN })) =>
        new Promise<string>((res, rej) =>
            fs.readFile(path.join(filesDirectory, `${Directory.images}/${path.basename(fileUrl)}`), undefined, (err, contents) => {
                if (err) {
                    console.log('Error: ', err);
                    rej();
                } else {
                    dbx.filesUpload({ path: `/Apps/browndash/${path.basename(fileUrl)}`, contents }).then(response => {
                        dbx.filesGetTemporaryLink({ path: response.result.path_display ?? '' }).then(link => res(link.result.link));
                    });
                }
            })
        );

    generateImage = (prompt: string = 'a realistic illustration of a cat coding', width: number = 2048, height: number = 2048, seed?: number) => {
        console.log('DIMENSIONS', width, height);
        let body = `{  "prompt": "${prompt}", "size": { "width": ${width}, "height": ${height}} }`;
        if (seed) {
            console.log('RECEIVED SEED', seed);
            body = `{  "prompt": "${prompt}", "size": { "width": ${width}, "height": ${height}}, "seeds": [${seed}]}`;
        }
        const fetched = this.getBearerToken().then(response =>
            response?.json().then((data: { access_token: string }) =>
                fetch('https://firefly-api.adobe.io/v3/images/generate', {
                    method: 'POST',
                    headers: [
                        ['Content-Type', 'application/json'],
                        ['Accept', 'application/json'],
                        ['x-api-key', process.env._CLIENT_FIREFLY_CLIENT_ID ?? ''],
                        ['Authorization', `Bearer ${data.access_token}`],
                    ],
                    body: body,
                })
                    .then(response2 =>
                        response2.json().then(json => {
                            const seed = json.outputs?.[0]?.seed;
                            const url = json.outputs?.[0]?.image?.url;
                            return { seed, url };
                        })
                    )
                    .catch(error => {
                        console.error('Error:', error);
                        return undefined;
                    })
            )
        );
        return fetched;
    };
    expandImage = (imgUrl: string, prompt?: string) => {
        const dropboxImgUrl = imgUrl;
        const fetched = this.getBearerToken().then(response =>
            response
                ?.json()
                .then((data: { access_token: string }) => {
                    return fetch('https://firefly-api.adobe.io/v3/images/expand', {
                        method: 'POST',
                        headers: [
                            ['Content-Type', 'application/json'],
                            ['Accept', 'application/json'],
                            ['x-api-key', process.env._CLIENT_FIREFLY_CLIENT_ID ?? ''],
                            ['Authorization', `Bearer ${data.access_token}`],
                        ],
                        body: JSON.stringify({
                            image: {
                                source: {
                                    url: dropboxImgUrl,
                                },
                            },
                            numVariations: 1,
                            seeds: [0],
                            size: {
                                width: 3048,
                                height: 2048,
                            },
                            prompt: prompt ?? 'cloudy skies',
                            placement: {
                                inset: {
                                    left: 0,
                                    top: 0,
                                    right: 0,
                                    bottom: 0,
                                },
                                alignment: {
                                    horizontal: 'center',
                                    vertical: 'center',
                                },
                            },
                        }),
                    });
                })
                .then(resp => resp.json())
        );
        return fetched;
    };
    getImageText = (imageBlob: Blob) => {
        const inputFileVarName = 'infile';
        const outputVarName = 'result';
        const fetched = this.getBearerToken().then(response =>
            response?.json().then((data: { access_token: string }) => {
                return fetch('https://sensei.adobe.io/services/v2/predict', {
                    method: 'POST',
                    headers: [
                        ['Prefer', 'respond-async, wait=59'],
                        ['x-api-key', process.env._CLIENT_FIREFLY_CLIENT_ID ?? ''],
                        // ['content-type', 'multipart/form-data'], // bcz: Don't set this!! content-type will get set automatically including the Boundary string
                        ['Authorization', `Bearer ${data.access_token}`],
                    ],
                    body: ((form: FormData) => {
                        form.set(inputFileVarName, imageBlob);
                        form.set(
                            'contentAnalyzerRequests',
                            JSON.stringify({
                                'sensei:name': 'Feature:cintel-object-detection:Service-b9ace8b348b6433e9e7d82371aa16690',
                                'sensei:invocation_mode': 'asynchronous',
                                'sensei:invocation_batch': false,
                                'sensei:engines': [
                                    {
                                        'sensei:execution_info': {
                                            'sensei:engine': 'Feature:cintel-object-detection:Service-b9ace8b348b6433e9e7d82371aa16690',
                                        },
                                        'sensei:inputs': {
                                            documents: [
                                                {
                                                    'sensei:multipart_field_name': inputFileVarName,
                                                    'dc:format': 'image/png',
                                                },
                                            ],
                                        },
                                        'sensei:params': {
                                            correct_with_dictionary: true,
                                        },
                                        'sensei:outputs': {
                                            result: {
                                                'sensei:multipart_field_name': outputVarName,
                                                'dc:format': 'application/json',
                                            },
                                        },
                                    },
                                ],
                            })
                        );
                        return form;
                    })(new FormData()),
                }).then(response2 => {
                    const contentType = response2.headers.get('content-type') ?? '';
                    if (contentType.includes('application/json')) {
                        return response2.json().then((json: object) => JSON.stringify(json));
                    }
                    if (contentType.includes('multipart')) {
                        return response2
                            .arrayBuffer()
                            .then(arrayBuffer =>
                                multipart
                                    .parse(Buffer.from(arrayBuffer), 'Boundary' + (response2.headers.get('content-type')?.match(/=Boundary(.*);/)?.[1] ?? ''))
                                    .filter(part => part.name === outputVarName)
                                    .map(part => JSON.parse(part.data.toString())[0])
                                    .reduce((text, json) => text + (json?.is_text_present ? json.tags.map((tag: { text: string }) => tag.text).join(' ') : ''), '')
                            )
                            .catch(error => {
                                console.error('Error:', error);
                                return '';
                            });
                    }
                    return response2.text();
                });
            })
        );
        return fetched;
    };
    protected initialize(register: Registration): void {
        register({
            method: Method.POST,
            subscription: '/queryFireflyImageFromStructure',
            secureHandler: async ({ req, res }) =>
                this.uploadImageToDropbox(req.body.structureUrl).then(uploadUrl =>
                    this.generateImageFromStructure(req.body.prompt, uploadUrl, req.body.strength).then(fire =>
                        DashUploadUtils.UploadImage(JSON.parse(fire ?? '').url).then(info => {
                            if (info instanceof Error) _invalid(res, info.message);
                            else _success(res, info);
                        })
                    )
                ),
        });
        register({
            method: Method.POST,
            subscription: '/queryFireflyImage',
            secureHandler: ({ req, res }) =>
                this.generateImage(req.body.prompt, req.body.width, req.body.height, req.body.seed).then(img =>
                    DashUploadUtils.UploadImage(img?.url ?? '', undefined, img?.seed).then(info => {
                        if (info instanceof Error) _invalid(res, info.message);
                        else _success(res, info);
                    })
                ),
        });

        register({
            method: Method.POST,
            subscription: '/queryFireflyImageText',
            // eslint-disable-next-line @typescript-eslint/no-unused-vars
            secureHandler: ({ req, res }) =>
                fetch(req.body.file).then(json =>
                    json.blob().then(file =>
                        this.getImageText(file).then(text => {
                            _success(res, text);
                        })
                    )
                ),
        });
        register({
            method: Method.POST,
            subscription: '/expandImage',
            secureHandler: ({ req, res }) =>
                this.uploadImageToDropbox(req.body.file).then(uploadUrl =>
                    this.expandImage(uploadUrl, req.body.prompt).then(text => {
                        if (text.error_code) _error(res, text.message);
                        else
                            DashUploadUtils.UploadImage(text.outputs[0].image.url).then(info => {
                                if (info instanceof Error) _invalid(res, info.message);
                                else _success(res, info);
                            });
                    })
                ),
        });
    }
}