-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
executable file
·69 lines (60 loc) · 2.01 KB
/
index.js
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
#!/usr/bin/env node
// Example of using API4AI OCR text recognition.
const fs = require('fs')
const path = require('path')
const axios = require('axios').default
const FormData = require('form-data')
// Use 'demo' mode just to try api4ai for free. Free demo is rate limited.
// For more details visit:
// https://api4.ai
// Use 'rapidapi' if you want to try api4ai via RapidAPI marketplace.
// For more details visit:
// https://rapidapi.com/api4ai-api4ai-default/api/ocr43/details
const MODE = 'demo'
// Your RapidAPI key. Fill this variable with the proper value if you want
// to try api4ai via RapidAPI marketplace.
const RAPIDAPI_KEY = ''
const OPTIONS = {
demo: {
url: 'https://demo.api4ai.cloud/ocr/v1/results',
headers: { 'A4A-CLIENT-APP-ID': 'sample' }
},
rapidapi: {
url: 'https://ocr43.p.rapidapi.com/v1/results',
headers: { 'X-RapidAPI-Key': RAPIDAPI_KEY }
}
}
// Parse args: path or URL to image.
const image = process.argv[2] || 'https://storage.googleapis.com/api4ai-static/samples/ocr-1.png'
// Preapare request: form.
const form = new FormData()
if (image.includes('://')) {
// Data from image URL.
form.append('url', image)
} else {
// Data from local image file.
const fileName = path.basename(image)
form.append('image', fs.readFileSync(image), fileName)
}
// Preapare request: headers.
const headers = {
...OPTIONS[MODE].headers,
...form.getHeaders(),
'Content-Length': form.getLengthSync()
}
// Make request.
axios.post(OPTIONS[MODE].url, form, { headers })
.then(function (response) {
// Print raw response.
console.log(`💬 Raw response:\n${JSON.stringify(response.data)}\n`)
// Parse response and print recognized text.
for (const i in response.data.results) {
const result = response.data.results[i]
let pageTip = ''
if (Object.hasOwn(result, 'page')) {
pageTip = ` on page ${result.page}`
}
const text = result.entities[0].objects[0].entities[0].text
console.log(`💬 Recognized text${pageTip}:\n${text}\n`)
}
})