File size: 2,917 Bytes
597b5d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
568802f
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
const fetch = require('node-fetch');
const FormData = require('form-data');
const path = require('path');

module.exports = {
  path: '/deepseek-ocr',
  method: ['GET', 'POST'], // Mendukung dua metode
  description: 'OCR DeepSeek: Kirim URL via GET (?image=) atau File via POST.',
  handler: async (request, reply) => {
    const WORKER_PREFIX = "https://proxy2.auriel.workers.dev/?u=";
    const HF_DOMAIN = "https://merterbak-deepseek-ocr-demo.hf.space";
    const API_BASE = `${WORKER_PREFIX}${encodeURIComponent(HF_DOMAIN + "/gradio_api")}`;
    const session_hash = Math.random().toString(36).substring(2);

    try {
      let fileData;
      let fileName;

      if (request.method === 'POST') {
        const data = await request.file(); // Membutuhkan @fastify/multipart
        if (!data) throw new Error("No file uploaded");
        fileData = await data.toBuffer();
        fileName = data.filename;
      } else {
        const { image } = request.query;
        if (!image) throw new Error("Query 'image' (URL) diperlukan");
        const res = await fetch(image);
        fileData = await res.buffer();
        fileName = "url_upload.png";
      }

      // 1. Upload ke Gradio
      const form = new FormData();
      form.append('files', fileData, { filename: fileName });

      const uploadRes = await fetch(`${API_BASE}/upload?upload_id=${session_hash}`, {
        method: "POST",
        body: form,
        headers: form.getHeaders()
      });

      const uploadData = await uploadRes.json();
      const remotePath = uploadData[0];

      // 2. Join Antrean
      const payload = {
        "data": [null, {
          "path": remotePath,
          "url": `${HF_DOMAIN}/gradio_api/file=${remotePath}`,
          "orig_name": fileName,
          "size": fileData.length,
          "mime_type": "image/png",
          "meta": { "_type": "gradio.FileData" }
        }, "📋 Markdown", null, 1],
        "fn_index": 6,
        "session_hash": session_hash
      };

      await fetch(`${API_BASE}/queue/join`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload)
      });

      // 3. Stream Response
      return new Promise((resolve, reject) => {
        const streamUrl = `${API_BASE}/queue/data?session_hash=${session_hash}`;
        fetch(streamUrl).then(res => {
          res.body.on('data', (chunk) => {
            const lines = chunk.toString().split("\n");
            for (let line of lines) {
              if (line.includes('"process_completed"')) {
                const json = JSON.parse(line.replace("data: ", ""));
                resolve({ status: "success", result: json.output.data[0] });
              }
            }
          });
        });
        setTimeout(() => reject(new Error("Timeout")), 60000);
      });

    } catch (err) {
      return { status: "error", message: err.message };
    }
  }
};