-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathserver.py
43 lines (27 loc) · 1.02 KB
/
server.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
#!/usr/bin/env python
import hug
from hug_middleware_cors import CORSMiddleware
import subprocess
from tempfile import NamedTemporaryFile
api = hug.API(__name__)
api.http.add_middleware(CORSMiddleware(api))
@hug.get('/', output=hug.output_format.file)
def index():
return "index.htm"
@hug.get('/static/{fn}', output=hug.output_format.file)
def static(fn):
return 'static/{}'.format(fn)
@hug.post('/ocr', output=hug.output_format.file)
def ocr(body, response, language: "The language(s) to use for OCR"="eng"):
if not len(body) == 1:
raise Exception("Need exactly one file!")
fn, content = list(body.items()).pop()
f_out = NamedTemporaryFile(suffix='.pdf')
with NamedTemporaryFile(suffix='.pdf', mode="wb") as f_in:
f_in.write(content)
f_in.flush()
proc = subprocess.Popen(['ocrmypdf', '--force-ocr', '-l', language, f_in.name, f_out.name])
code = proc.wait()
response.set_header('X-OCR-Exit-Code', str(code))
print(f_out.name)
return f_out