dream
86 строк · 2.2 Кб
1import logging2import time3from functools import wraps4
5from fastapi import FastAPI6import uvicorn7
8import sentry_sdk9from sentry_sdk.integrations.asgi import SentryAsgiMiddleware10from sentry_sdk.integrations.logging import ignore_logger11
12from comet_commonsense.interface import COMeTFactory13from comet_commonsense.config import settings14import test_server15
16ignore_logger("root")17
18sentry_sdk.init(dsn=settings.SENTRY_DSN)19
20app = FastAPI()21
22logging.basicConfig(format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO)23logger = logging.getLogger(__name__)24
25comet_engine = COMeTFactory(settings.GRAPH)(settings.PRETRAINED_MODEL, settings.DECODING_ALGO)26
27
28def timing(f):29@wraps(f)30def wrap(*args, **kw):31ts = time.time()32result = f(*args, **kw)33total_time = time.time() - ts34logger.info(f"{settings.SERVICE_NAME} exec time = {total_time:.3f}s")35return result36
37return wrap38
39
40@timing
41def handler(data):42try:43return comet_engine.process_request(data)44except Exception as exc:45sentry_sdk.capture_exception(exc)46logger.exception(exc)47raise exc48
49
50@timing
51def annotator_handler(data):52try:53return comet_engine.annotator(data)54except Exception as exc:55sentry_sdk.capture_exception(exc)56logger.exception(exc)57raise exc58
59
60@app.post("/comet", response_model=comet_engine.response_model)61async def comet_base_handler(input_event: comet_engine.input_event_model):62result = handler(input_event.dict())63return result64
65
66@app.post("/comet_annotator", response_model=comet_engine.annotator_response_model)67async def comet_annotator_handler(input_event: comet_engine.annotator_input_model):68result = annotator_handler(input_event.dict())69logger.info(f"comet_annotator result: {result}")70return result71
72
73app = SentryAsgiMiddleware(app)74
75try:76test_server.run_test(handler)77logger.info("test query processed")78except Exception as exc:79sentry_sdk.capture_exception(exc)80logger.exception(exc)81raise exc82
83logger.info(f"{settings.SERVICE_NAME} is loaded and ready")84
85if __name__ == "__main__":86uvicorn.run(app, host="0.0.0.0", port=settings.SERVICE_PORT, log_level="info")87