File size: 6,087 Bytes
fe5be0d
 
 
7c363b0
fe5be0d
7c363b0
fe5be0d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7c363b0
fe5be0d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7c363b0
fe5be0d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7c363b0
fe5be0d
 
 
 
f22362c
 
 
 
fe5be0d
ea8383b
 
 
 
 
 
 
 
 
fe5be0d
7c363b0
fe5be0d
 
 
 
 
ea8383b
 
 
fe5be0d
 
 
 
 
 
 
 
 
7c363b0
fe5be0d
 
 
ea8383b
fe5be0d
 
 
 
 
 
 
ea8383b
fe5be0d
 
 
 
7c363b0
 
 
 
fe5be0d
7c363b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe5be0d
 
 
7c363b0
 
fe5be0d
7c363b0
 
 
fe5be0d
7c363b0
 
fe5be0d
7c363b0
 
 
fe5be0d
 
 
 
7c363b0
 
 
 
 
fe5be0d
 
 
 
7c363b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea8383b
7c363b0
 
fe5be0d
 
7c363b0
 
 
fe5be0d
7c363b0
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
const { fromBuffer } = require('file-type');
const FormData = require("form-data");
const crypto = require("node:crypto");
const axios = require("axios");
const Jimp = require("jimp");

class GridPlus {
  constructor() {
    this.ins = axios.create({
      baseURL: 'https://api.grid.plus/v1',
      headers: {
        'user-agent': 'Mozilla/5.0 (Android 15; Mobile; SM-F958; rv:130.0) Gecko/130.0 Firefox/130.0',
        'X-AppID': '808645',
        'X-Platform': 'h5',
        'X-Version': '8.9.7',
        'X-SessionToken': '',
        'X-UniqueID': this.uid(),
        'X-GhostID': this.uid(),
        'X-DeviceID': this.uid(),
        'X-MCC': 'id-ID',
        sig: `XX${this.uid()+this.uid()}`
      }
    })
  }
  
  uid() {
    return crypto.randomUUID().replace(/-/g, '')
  }
  
  form(dt) {
    const form = new FormData();
    Object.entries(dt).forEach(([key, value]) => {
      form.append(key, String(value));
    });
    return form
  }
  
  async upload(buff, method) {
    try {
      if (!Buffer.isBuffer(buff)) throw 'data is not buffer!';
      const { mime, ext } = (await fromBuffer(buff)) || {};
      const d = await this.ins.post('/ai/web/nologin/getuploadurl', this.form({
        ext, method
      })).then(i => i.data);
      await axios.put(d.data.upload_url, buff, {
        headers: {
          'content-type': mime
        }
      });
      return d.data.img_url;
    } catch(e) {
      throw new Error('An error occurred while uploading the image');
    }
  }
  
  async task({ path, data, sl = () => false }) {
    const [start, interval, timeout] = [
      Date.now(), 3000, 60000
    ];
    return new Promise(async (resolve, reject) => {
      const check = async () => {
        if (Date.now() - start > timeout) {
          return reject(new Error(`Polling timed out for task`));
        };
        try {
          const dt = await this.ins({
            url: path,
            method: data ? 'POST' : 'GET',
            ...(data ? { data } : {})
          });
          if (!!dt.data.errmsg?.trim()) {
            reject(new Error(`Something a error with message: ${dt.data.errmsg}`));
          };
          if (!!sl(dt.data)) {
            return resolve(dt.data);
          };
          setTimeout(check, interval);
        } catch (error) {
          reject(error);
        }
      };
      check();
    });
  }
  
  async edit(buff, prompt) {
    try {
      const up = await this.upload(buff, 'wn_aistyle_nano');
      const dn = await this.ins.post('/ai/nano/upload', this.form({
        prompt, url: up
      })).then(i => i.data);
      if (!dn.task_id) throw 'taskId not found on request';
      const res = await this.task({
        path: `/ai/nano/get_result/${dn.task_id}`,
        sl: (dt) => dt.code === 0 && !!dt.image_url,
      });
      return res.image_url
    } catch(e) {
      throw new Error('Something error, message: ' + e.message);
    }
  }
}

async function createGrid(imageUrls) {
  const imageBuffers = await Promise.all(
    imageUrls.map(url => axios.get(url, { responseType: 'arraybuffer' }).then(r => Buffer.from(r.data)))
  );

  const images = await Promise.all(
    imageBuffers.map(async buffer => {
      const img = await Jimp.default ? Jimp.default.read(buffer) : new Promise((resolve, reject) => {
        new Jimp(buffer, (err, image) => {
          if (err) reject(err);
          else resolve(image);
        });
      });
      return img;
    })
  );

  const count = images.length;
  const targetSize = 1024;
  
  let cols, rows;
  if (count === 1) {
    const img = images[0];
    await img.resize(targetSize, targetSize);
    return await img.getBufferAsync(Jimp.MIME_JPEG);
  } else if (count === 2) {
    cols = 2;
    rows = 1;
  } else if (count === 3) {
    cols = 2;
    rows = 2;
  } else {
    cols = 2;
    rows = 2;
  }

  const cellSize = Math.floor(targetSize / cols);
  const gridHeight = cellSize * rows;
  const grid = await new Jimp(targetSize, gridHeight, 0xFFFFFFFF);

  for (let i = 0; i < count && i < 4; i++) {
    const col = i % cols;
    const row = Math.floor(i / cols);
    const x = col * cellSize;
    const y = row * cellSize;
    
    const resized = await images[i].cover(cellSize, cellSize);
    grid.composite(resized, x, y);
  }

  return await grid.getBufferAsync(Jimp.MIME_JPEG);
}

const handler = async (req, res) => {
  try {
    const { prompt, img_url1, img_url2, img_url3, img_url4, key } = req.query;

    if (!key) {
      return res.status(400).json({
        success: false,
        error: 'Missing required parameter: key'
      });
    }

    if (!prompt) {
      return res.status(400).json({
        success: false,
        error: 'Missing required parameter: prompt'
      });
    }

    const imageUrls = [img_url1, img_url2, img_url3, img_url4].filter(Boolean);

    if (imageUrls.length === 0) {
      return res.status(400).json({
        success: false,
        error: 'At least one image URL is required (img_url1)'
      });
    }

    if (imageUrls.length > 4) {
      return res.status(400).json({
        success: false,
        error: 'Maximum 4 images allowed'
      });
    }

    const imageBuffer = await createGrid(imageUrls);
    
    const gridPlus = new GridPlus();
    const result = await gridPlus.edit(imageBuffer, prompt);

    return res.json({
      author: "Herza",
      success: true,
      data: {
        prompt: prompt,
        image_url: result,
        original_urls: imageUrls,
        image_count: imageUrls.length
      },
      timestamp: new Date().toISOString()
    });

  } catch (error) {
    res.status(500).json({
      success: false,
      error: error.message,
      timestamp: new Date().toISOString()
    });
  }
};

module.exports = {
  name: 'Nano Banana',
  description: 'AI Image Editing using Grid Plus - Edit 1-4 images with text prompts',
  type: 'GET',
  routes: ['api/AI/nanobanana'],
  tags: ['ai', 'image', 'editing', 'nanobanana', 'multi-image'],
  parameters: ['prompt', 'img_url1', 'img_url2', 'img_url3', 'img_url4', 'key'],
  limit: 5,
  enabled: true,
  main: ['AI'],
  handler
};