-
Notifications
You must be signed in to change notification settings - Fork 0
/
recognize-text.js
48 lines (41 loc) · 1.26 KB
/
recognize-text.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
/*
* Recognize text on a selected image via OCR API
* and create a sticker with recognized text
*/
const apiUrl = 'https://api.ocr.space/parse/imageurl'
const ocrSpaceApiKey = '<your-api-key-here>'
const image = (await miro.board.selection.get())[0]
if (!image || image.type !== 'IMAGE') {
await miro.showErrorNotification('Please select an image')
return
}
let recognizedText
try {
recognizedText = await recognizeImage(image.url)
} catch (error) {
await miro.showErrorNotification(error.message)
return
}
const created = await miro.board.widgets
.create({type: 'TEXT', text: recognizedText})
await miro.board.viewport.zoomToObject(created[0])
async function recognizeImage(imageUrl) {
const urlParams = new URLSearchParams(
Object.entries({
url: imageUrl,
apiKey: ocrSpaceApiKey,
OCREngine: 2,
fileType: 'PNG'
})
)
const resp = await fetch(`${apiUrl}?${urlParams}`, { mode: 'no-cors' })
if (!resp.ok) {
throw new Error('Could not process image')
}
const result = await resp.json()
const text = (result.ParsedResults) ? result.ParsedResults[0].ParsedText : null
if (!text) {
throw new Error('Could not recognize text')
}
return text
}