Skip to content

Commit 0435ff2

Browse files
authored
Merge pull request #5 from TatraDev/use_case
Use case added
2 parents f31e76d + d5717f2 commit 0435ff2

20 files changed

+963
-46
lines changed

main.py

Lines changed: 44 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,50 @@
1-
from piper.services import TestMessageAdder, StringValue
2-
from piper.envs import CurrentEnv
3-
1+
from piper.services import TestMessageAdder, StringValue, TesseractRecognizer, SpacyNER
2+
from piper.envs import CurrentEnv, DockerEnv
3+
from piper.configurations import get_configuration
4+
import time
45
import asyncio
6+
import sys
7+
from piper.utils import tesrct_utils as tu
8+
59
from loguru import logger
6-
logger.add("file.log", level="INFO")
10+
logger.add("file.log", level="INFO", backtrace=True, diagnose=True, rotation='5 MB')
711

812
if __name__ == '__main__':
13+
# cfg = get_configuration()
14+
# loop = asyncio.get_event_loop()
15+
# with CurrentEnv() as env:
16+
# x = StringValue(value="hello, world")
17+
# adder = TestMessageAdder(appender="!", port=cfg.docker_app_port)
18+
# result = loop.run_until_complete(adder(x))
19+
# print(result)
20+
21+
# x = StringValue(value="hello, world")
22+
# adder = TestMessageAdder(appender="!", port=cfg.docker_app_port)
23+
# result = loop.run_until_complete(adder(x))
24+
# print(result)
25+
# adder.rm_container()
26+
27+
logger.info(f'main here {time.time()}')
28+
cfg = get_configuration()
929
loop = asyncio.get_event_loop()
10-
with CurrentEnv() as env:
11-
x = StringValue(value="hello, world")
12-
adder = TestMessageAdder(appender="!", port=8788)
13-
result = loop.run_until_complete(adder(x))
14-
print(result)
30+
with DockerEnv() as env:
31+
# object created
32+
recognizer = TesseractRecognizer(port=cfg.docker_app_port)
33+
34+
result = loop.run_until_complete(recognizer())
35+
logger.info(f'result of recognition is {result}')
36+
37+
# sys.exit()
1538

16-
x = StringValue(value="hello, world")
17-
adder = TestMessageAdder(appender="!", port=8788)
18-
result = loop.run_until_complete(adder(x))
19-
print(result)
20-
adder.rm_container()
39+
# sn = SpacyNER()
40+
# txt = 'The Alraigo Incident occurred on 6th June 1983, when a lost British Royal Navy Sea Harrier fighter aircraft landed on the deck of a Spanish container ship.[1][2] Its pilot, Sub-lieutenant Ian Watson, was a junior Royal Navy Pilot undertaking his first NATO exercise from HMS Illustrious, which was operating off the coast of Portugal. Watson was launched in a pair of aircraft tasked with locating a French aircraft carrier under combat conditions including radio-silence and radar switched off.'
41+
# # switch models
42+
# for avalable_model in sn.available_models:
43+
# logger.info(f'current model is {avalable_model}')
44+
# sn.set_model(avalable_model)
45+
# result1 = sn.extract_named_ents(txt)
46+
# if result1:
47+
# result1_str = "\n".join(str(x) for x in result1)
48+
# logger.info(f'result of NER for model {avalable_model} is {result1_str}')
49+
# else:
50+
# logger.info(f'module didn`t get NER data')
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
import time
2+
3+
from fastapi import FastAPI, Request, status, File, UploadFile, HTTPException
4+
from piper.envs import CurrentEnv
5+
from loguru import logger
6+
from pathlib import Path
7+
#logger = logging.getLogger(__name__)
8+
9+
#logger.add("file.log", level="INFO", backtrace=True, diagnose=True, rotation='5 MB')
10+
11+
{% for script_name in scripts.keys() %}
12+
from {{ script_name }} import *
13+
{% endfor %}
14+
15+
app = FastAPI(debug=True)
16+
app.logger = logger
17+
logger.info(f'main here {time.time()}')
18+
logger.info(f'Tesseract executor')
19+
20+
@app.post('/health_check', status_code=status.HTTP_200_OK)
21+
async def health_check():
22+
logger.info('health_check request')
23+
return {"message": "health check"}
24+
25+
with CurrentEnv():
26+
logger.info(f'CurrentEnv')
27+
service = {{ service_class }}( {% for k, v in service_kwargs.items() %} {{ k }}={{ v }}, {% endfor %} )
28+
logger.info(f'service {service}')
29+
30+
sn = SpacyNER()
31+
logger.info(f'SpacyNER created {sn}')
32+
33+
@app.post('/{{ function_name }}')
34+
async def {{ function_name }}(file: UploadFile = File(...)):
35+
try:
36+
suf = Path(file.filename).suffix[1:].lower()
37+
logger.info(f'recived file {file.filename}, suffix is {suf}')
38+
content = await file.read()
39+
result = await service.{{ function_name }}(content, suf)
40+
return result
41+
except Exception as e:
42+
logger.error(f'error while parsing File object {e}')
43+
44+
45+
@app.post('/set_config')
46+
async def set_config(request: Request):
47+
conf = await request.json()
48+
logger.info(f'recived config dict {conf}')
49+
try:
50+
result = await service.sconfig(conf)
51+
return result
52+
except Exception as e:
53+
logger.error(f'error while set config {e}')
54+
55+
@app.get('/get_ner_models')
56+
async def get_ner_models():
57+
return {'available_models': sn.available_models}
58+
59+
@app.post('/set_ner_model')
60+
async def set_ner_model(request: Request):
61+
model_name = await request.json()
62+
try:
63+
model_name = model_name.get('model_name')
64+
sn.set_model(model_name)
65+
return {'message': f'spacy ner model is {model_name} now'}
66+
67+
except ValueError as ve:
68+
raise HTTPException(status_code = 400, detail=f'Exception is {ve}')
69+
70+
except Exception as e:
71+
logger.error(f'error while set config {e}')
72+
logger.error('return HTTPException object')
73+
raise HTTPException(status_code = 500, detail=f'Exception is {e}')
74+
75+
@app.get('/extract_named_ents')
76+
async def extract_named_ents(request: Request):
77+
txt = await request.json()
78+
try:
79+
txt = txt.get('txt')
80+
result = sn.extract_named_ents(txt)
81+
return {'result': result}
82+
83+
except Exception as e:
84+
logger.error(f'error while set config {e}')

piper/base/backend/templates/fast-api.j2

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ from {{ script_name }} import *
1010
app = FastAPI(debug=True)
1111

1212
@app.post('/health_check', status_code = status.HTTP_200_OK)
13-
async def hl():
13+
async def health_check():
1414
return {"message": "health check"}
1515

1616
with CurrentEnv():

piper/base/backend/utils.py

Lines changed: 23 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,27 @@ def render_fast_api_backend(**kwargs):
66
"""
77
Render backend template to app.py
88
"""
9-
print(os.path.dirname(__file__))
10-
template_dir = os.path.join(os.path.dirname(__file__), 'templates/')
11-
jinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader(template_dir),
12-
trim_blocks=True,
13-
lstrip_blocks=True)
14-
print(jinja_env.list_templates())
15-
template = jinja_env.get_template('fast-api.j2')
9+
template = get_backend_template('fast-api.j2')
10+
return template.render(**kwargs)
11+
12+
13+
def render_fast_api_tsrct_backend(**kwargs):
14+
"""
15+
Render backend tesseract template to app.py
16+
"""
17+
template = get_backend_template('fast-api-tsrct.j2')
1618
return template.render(**kwargs)
19+
20+
21+
def get_backend_template(template_fn):
22+
"""
23+
Returns template data for j2 file
24+
"""
25+
template_dir = os.path.join(os.path.dirname(__file__), 'templates/')
26+
jinja_env = jinja2.Environment(
27+
loader=jinja2.FileSystemLoader(template_dir),
28+
trim_blocks=True,
29+
lstrip_blocks=True
30+
)
31+
template = jinja_env.get_template(template_fn)
32+
return template

piper/base/docker/__init__.py

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,13 @@
44

55
class PythonImage:
66

7-
def __init__(self, tag, python_docker_version, cmd):
7+
def __init__(self, tag, python_docker_version, cmd, template_file, run_rows, post_install_lines):
88
self.tag = tag
99
self.python_docker_version = python_docker_version
1010
self.cmd = cmd
11+
self.template_file = template_file
12+
self.run_rows = run_rows
13+
self.post_install_lines = post_install_lines
1114

1215
def render(self):
1316
"""
@@ -17,5 +20,25 @@ def render(self):
1720
jinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader(template_dir),
1821
trim_blocks=True,
1922
lstrip_blocks=True)
20-
template = jinja_env.get_template('default-python.j2')
21-
return template.render(cmd=self.cmd, python_docker_version=self.python_docker_version)
23+
template = jinja_env.get_template(self.template_file)
24+
return template.render(cmd=self.cmd, python_docker_version=self.python_docker_version, run_command_lines=self.run_rows, post_install_lines=self.post_install_lines)
25+
26+
27+
# class PythonTesseractImage:
28+
29+
# def __init__(self, tag, python_docker_version, cmd):
30+
# self.tag = tag
31+
# self.python_docker_version = python_docker_version
32+
# self.cmd = cmd
33+
34+
35+
# def render(self):
36+
# """
37+
# Render docker template
38+
# """
39+
# template_dir = os.path.join(os.path.dirname(__file__), 'images')
40+
# jinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader(template_dir),
41+
# trim_blocks=True,
42+
# lstrip_blocks=True)
43+
# template = jinja_env.get_template('python-tesrct.j2')
44+
# return template.render(cmd=self.cmd, python_docker_version=self.python_docker_version, run_command_lines=self.run_command_lines)

piper/base/docker/images/default-python.j2

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,14 @@
11
FROM python:{{ python_docker_version }}
22

3+
{{ run_command_lines }}
4+
35
WORKDIR /app
46

57
COPY requirements.txt ./requirements.txt
68
RUN pip3 install -r requirements.txt
79

10+
{{ post_install_lines }}
11+
812
COPY ./ ./
913
RUN chmod +x ./run.sh
1014

0 commit comments

Comments
 (0)