forked from MISP/misp-modules
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ocr_enrich.py
64 lines (53 loc) · 1.68 KB
/
ocr_enrich.py
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
import json
import binascii
import cv2
import np
import pytesseract
misperrors = {'error': 'Error'}
mispattributes = {'input': ['attachment'],
'output': ['freetext']}
moduleinfo = {'version': '0.2', 'author': 'Sascha Rommelfangen',
'description': 'OCR decoder',
'module-type': ['expansion']}
moduleconfig = []
def filter_decoded(decoded):
for line in decoded.split('\n'):
decoded_line = line.strip('\t\x0b\x0c\r ')
if decoded_line:
yield decoded_line
def handler(q=False):
if q is False:
return False
q = json.loads(q)
filename = q['attachment']
try:
img_array = np.frombuffer(binascii.a2b_base64(q['data']), np.uint8)
except Exception as e:
print(e)
err = "Couldn't fetch attachment (JSON 'data' is empty). Are you using the 'Query enrichment' action?"
misperrors['error'] = err
print(err)
return misperrors
image = img_array
image = cv2.imdecode(img_array, cv2.IMREAD_COLOR)
try:
decoded = pytesseract.image_to_string(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
return {
'results': [
{
'types': ['freetext'],
'values': list(filter_decoded(decoded)),
'comment': f"OCR from file {filename}"
}
]
}
except Exception as e:
print(e)
err = "Couldn't analyze file type. Only images are supported right now."
misperrors['error'] = err
return misperrors
def introspection():
return mispattributes
def version():
moduleinfo['config'] = moduleconfig
return moduleinfo