File size: 8,423 Bytes
54ba1c5
 
79f7ac0
3fded0a
 
 
79f7ac0
eb06d6c
54ba1c5
4a797ab
 
 
 
 
 
 
 
 
 
 
 
 
 
54ba1c5
 
7fe37cd
54ba1c5
 
 
 
79f7ac0
fa762df
 
52f6b1b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f8d826
7541db3
 
 
fa762df
5433c0e
 
 
 
 
 
 
 
 
 
 
 
 
7541db3
 
45130a6
7541db3
d82c975
e5fe435
d82c975
997a698
e5fe435
d82c975
5e11386
 
 
 
 
3474a0b
91cb296
5e11386
862d774
 
7fe37cd
 
 
 
54ba1c5
 
d82c975
d07388b
54ba1c5
 
 
d4d4332
79f7ac0
c28b31a
997a698
79f7ac0
 
 
 
 
1681ad8
2a14a22
79f7ac0
 
 
 
3fdf66a
79f7ac0
 
 
 
 
3fded0a
f035308
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
290493f
79f7ac0
f035308
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0abf878
f035308
 
 
 
 
 
 
4a797ab
 
 
 
f035308
 
 
4a797ab
 
 
 
f035308
 
 
 
4a797ab
 
 
 
 
f035308
52f6b1b
79f7ac0
4a797ab
 
79f7ac0
4a797ab
 
 
 
79f7ac0
4a797ab
 
 
 
 
 
 
f035308
79f7ac0
4a797ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79f7ac0
4a797ab
d4d4332
 
c941955
 
 
 
 
 
 
 
 
 
 
 
 
 
0abf878
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0da58fc
 
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
279
280
281
282
283
284
285
286
287
288
289
290
import { Hono } from '@hono/hono';
import { logger } from '@hono/hono/logger';
import { serveStatic } from '@hono/hono/deno';
import { generateImage as fluxGenerateImage } from './gradio-api/flux.ts';
import { parseResolution } from './utils/string.ts';
import OpenAI from '@openai/openai';
import { encodeBase64 } from '@std/encoding/base64';
import { ensureDir } from '@std/fs';

interface Payload {
  model: string;
  inputs: string;
  parameters?: {
    guidance_scale?: number;
    negative_prompt?: string;
    num_inference_steps?: number;
    width?: number;
    height?: number;
    scheduler?: string;
    seed?: number;
  };
}

// https://api-inference.huggingface.co/v1
const HF_API_URL = 'https://api-inference.huggingface.co';
const JINA_API_URL = 'https://deepsearch.jina.ai';

const app = new Hono();

app.use(logger());

app.get('/', (c) => c.text('Hello Hono!'));

// In-memory storage for images
const imageCache = new Map<string, { data: Uint8Array; contentType: string }>();

// Modified route to serve from in-memory cache instead of filesystem
app.get('/tmp/:id', async (c) => {
  const id = c.req.param('id');
  const cachedImage = imageCache.get(id);

  if (!cachedImage) {
    return c.text('Image not found', 404);
  }

  return new Response(cachedImage.data, {
    headers: {
      'Content-Type': cachedImage.contentType,
    },
  });
});

// LM Studio
app.get('/v1/models', (c) => {
  return c.json({
    object: 'list',
    data: [
      {
        'id': 'meta-llama/Llama-3.2-11B-Vision-Instruct',
        'object': 'model',
        'type': 'vlm',
        'publisher': 'lmstudio-community',
        'arch': 'llama',
        'compatibility_type': 'gguf',
        'quantization': 'Q4_K_M',
        'state': 'not-loaded',
        'max_context_length': 131072,
      },
    ],
  });
});

app.post('/v1/chat/completions', async (c) => {
  const headers = new Headers(c.req.raw.headers);
  // headers.delete('Host');
  headers.delete('Authorization');
  headers.has('x-use-cache') || headers.set('x-use-cache', 'false');
  console.log('headers:', Object.fromEntries(headers));

  // const clonedRequest = await c.req.raw.clone();
  // const body = await clonedRequest.json();
  // body.max_tokens = 33554432;

  const body = await c.req.json();
  // body.max_tokens = 33554432;
  delete body.max_tokens;

  console.log('body:', body);

  const { pathname, search } = new URL(c.req.url);
  const targetUrl = `${body.model === 'jina-deepsearch-v1' ? JINA_API_URL : HF_API_URL}${pathname}${search}`;
  // console.log(targetUrl);

  return await fetch(targetUrl, {
    method: 'POST',
    headers: headers,
    body: JSON.stringify(body),
  });
});

app.post('/v1/images/generations', async (c) => {
  const headers = new Headers(c.req.raw.headers);
  headers.delete('Authorization');
  headers.has('x-use-cache') || headers.set('x-use-cache', 'false');
  console.log('headers:', Object.fromEntries(headers));

  const params = await c.req.json<OpenAI.ImageGenerateParams>();
  console.log('request body:', params);

  const targetUrl = `${HF_API_URL}/models/${params.model}`;
  console.log(targetUrl);

  const { width = 1024, height = 1024 } = parseResolution(params.size as string);

  const requestBody: any = {
    inputs: params.prompt,
    parameters: {
      width,
      height,
    },
  };

  if (headers.has('guidance_scale')) {
    requestBody.parameters.guidance_scale = parseFloat(headers.get('guidance_scale')!);
    headers.delete('guidance_scale');
  }
  if (headers.has('negative_prompt')) {
    requestBody.parameters.negative_prompt = headers.get('negative_prompt');
    headers.delete('negative_prompt');
  }
  if (headers.has('num_inference_steps')) {
    requestBody.parameters.num_inference_steps = parseInt(headers.get('num_inference_steps')!);
    headers.delete('num_inference_steps');
  }
  if (headers.has('scheduler')) {
    requestBody.parameters.scheduler = headers.get('scheduler');
    headers.delete('scheduler');
  }
  if (headers.has('seed')) {
    requestBody.parameters.seed = parseInt(headers.get('seed')!);
    headers.delete('seed');
  }
  console.log('new body:', requestBody);

  // Determine how many images to generate (default to 1)
  const numImages = params.n || 1;

  // Create an array of promises for parallel execution
  const imagePromises = Array.from({ length: numImages }, async (_, i) => {
    // Clone the request body to avoid race conditions
    const currentRequestBody = structuredClone(requestBody);

    // If a seed was provided, increment it for each image to ensure variety
    if (currentRequestBody.parameters.seed !== undefined && i > 0) {
      currentRequestBody.parameters.seed += i; // Add index to ensure unique seeds
    }

    // Create a copy of headers for each request
    const currentHeaders = new Headers(headers);

    try {
      const response = await fetch(targetUrl, {
        method: 'POST',
        headers: currentHeaders,
        body: JSON.stringify(currentRequestBody),
      });

      if (!response.ok) {
        throw new Error(`Request failed with status ${response.status}: ${await response.text()}`);
      }

      const contentType = response.headers.get('content-type')!;
      const imageArrayBuffer = await response.arrayBuffer();
      const imageData = new Uint8Array(imageArrayBuffer);

      // Generate a unique ID without the file extension
      const fileId = crypto.randomUUID();

      // Store in our in-memory cache instead of writing to disk
      imageCache.set(fileId, {
        data: imageData,
        contentType: contentType,
      });

      const host = 'https://' + Deno.env.get('SPACE_HOST');
      const url = `${host}/tmp/${fileId}`;

      console.log(`Generated image ${i + 1}/${numImages}: ${url}`);

      // Create the appropriate data format based on the response_format
      if (params.response_format === 'b64_json') {
        return {
          success: true,
          data: {
            b64_json: encodeBase64(imageArrayBuffer),
          },
        };
      } else {
        return {
          success: true,
          data: {
            url,
          },
        };
      }
    } catch (error) {
      console.error(`Error generating image ${i + 1}:`, error);
      // Return failure object instead of throwing
      return {
        success: false,
        error: error instanceof Error ? error.message : 'Unknown error',
      };
    }
  });

  // Wait for all image generation attempts to complete (regardless of success/failure)
  const results = await Promise.all(imagePromises);

  // Filter out the successful results
  const successfulImages = results
    .filter((result) => result.success)
    .map((result) => result.data);

  // Collect errors for logging/reporting
  const errors = results
    .filter((result) => !result.success)
    .map((result) => result.error);

  if (errors.length > 0) {
    console.warn(`${errors.length} of ${numImages} images failed to generate:`, errors);
  }

  // Return successful images even if some failed
  const responseBody = {
    created: Math.floor(Date.now() / 1000),
    data: successfulImages,
    // Include error information if any images failed
    ...(errors.length > 0
      ? {
        partial_failure: true,
        error_count: errors.length,
        success_count: successfulImages.length,
      }
      : {}),
  };

  // If all images failed, return 500 status
  if (successfulImages.length === 0) {
    return c.json({
      error: 'Failed to generate any images',
      errors: errors,
    }, 500);
  }

  return c.json(responseBody);
});

// Google Translate TTS
app.get('/translate_tts', async (c) => {
  const params = {
    client: 'tw-ob',
    ie: 'UTF-8',
    tl: c.req.query('tl') || 'en',
    q: c.req.query('q') || '',
  };

  const url = 'https://translate.google.com/translate_tts?' + new URLSearchParams(params);

  return await fetch(url);
});

app.post('*', async (c) => {
  const headers = new Headers(c.req.raw.headers);
  headers.delete('Authorization');
  headers.has('x-use-cache') || headers.set('x-use-cache', 'false');
  console.log('headers:', Object.fromEntries(headers));

  const { pathname, search } = new URL(c.req.url);
  const targetUrl = `${HF_API_URL}${pathname}${search}`;

  return await fetch(targetUrl, {
    method: 'POST',
    headers: headers,
    body: c.req.raw.body,
  });
});

// Deno.serve({ port: 7860 }, app.fetch);
export default app.fetch;