コード例 #1
0
def handler(ctx, data=None, loop=None):
    res = ""
    try:
        if data and len(data) > 0:
            #
            # 1. decode byte stream
            #
            nparr = np.frombuffer(data, np.uint8)
            #
            # 2. decode image
            #
            img_np = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
            #
            # 3. convert image
            #
            edges = cv2.Canny(img_np, 100, 200)
            #
            # 4. write response to byte array
            #
            retval, buf = cv2.imencode('.jpg', edges)
            #
            # 5 Convert buffer to bytes for row response
            res = buf.tobytes()
    except Exception as ex:
        res = "Exception:" + str(ex) + ' at ' + getActiveLine()
        return res
    return response.RawResponse(ctx,
                                response_data=res,
                                headers={
                                    "Content-Type": "application/octet-stream",
                                })
コード例 #2
0
def build_view(context, data=None, loop=None):
    print("entering the function \n", file=sys.stderr, flush=True)
    resp = requests.get(recorder, timeout=200)
    resp.raise_for_status()
    print("stats received\n", file=sys.stderr, flush=True)
    data = resp.json()
    main_emotions = data['main']
    alt_emotions = data['alt']
    main, alt = [], []
    total = sum(list(main_emotions.values()))
    for emotion, count in main_emotions.items():
        main.append(
            dict(emotion=emotion,
                 stat=float("{:.2f}".format(float(count / total) * 100)),
                 times=count))
    for emotion, count in alt_emotions.items():
        alt.append(
            dict(emotion=emotion,
                 stat=float("{:.2f}".format(float(count / total) * 100)),
                 times=count))
    print("final stats assembled\n", file=sys.stderr, flush=True)
    render_context = {
        "main_emotions": main,
        "alt_emotions": alt,
        "total": total
    }
    headers = {
        "Content-Type": "text/html",
    }
    return response.RawResponse(context,
                                status_code=200,
                                headers=headers,
                                response_data=template.render(render_context))
コード例 #3
0
 def response(self):
     resp_headers = headers.GoLikeHeaders({})
     resp_headers.set("content-type", "text/plain; charset=utf-8")
     return response.RawResponse(
         self.context,
         response_data={"error": {
             "message": self.message,
         }},
         headers=resp_headers,
         status_code=self.status)
コード例 #4
0
def encaped_header(ctx, **kwargs):
    httpctx = ctx.HTTPContext()
    hs = httpctx.Headers()
    v = hs.get("custom-header-maybe")
    return response.RawResponse(httpctx,
                                response_data="OK",
                                status_code=200,
                                headers={
                                    "Content-Type": "text/plain",
                                    "custom-header-maybe": v
                                })
コード例 #5
0
def access_request_url(ctx, **kwargs):
    httpctx = ctx.HTTPContext()
    hs = httpctx.Headers()
    method = httpctx.Method()
    request_url = hs.get("Fn-Http-Request-Url")
    return response.RawResponse(httpctx,
                                response_data="OK",
                                headers={
                                    "Response-Request-URL": request_url,
                                    "Request-Method": method,
                                })
コード例 #6
0
ファイル: darknet.py プロジェクト: rstyczynski/Fn
def handler(ctx, data=None, loop=None):
    res = ""
    try:
        if data and len(data) > 0:
            #
            # 1. decode byte stream
            #
            nparr = np.frombuffer(data, np.uint8)
            #
            # 3. convert image
            #
            img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
            #
            net = Detector(bytes("cfg/yolov3.cfg", encoding="utf-8"),
                           bytes("weights/yolov3.weights", encoding="utf-8"),
                           0, bytes("cfg/coco.data", encoding="utf-8"))
            #
            dark_frame = Image(img)
            results = net.detect(dark_frame)
            del dark_frame
            for cat, score, bounds in results:
                x, y, w, h = bounds
                cv2.rectangle(img, (int(x - w / 2), int(y - h / 2)),
                              (int(x + w / 2), int(y + h / 2)), (255, 0, 0))
                cv2.putText(img, str(cat.decode("utf-8")), (int(x), int(y)),
                            cv2.FONT_HERSHEY_COMPLEX, 1, (255, 255, 0))
            #
            # 4. write response to byte array
            #
            retval, buf = cv2.imencode('.jpg', img)
            #
            # 5 Convert buffer to bytes for row response
            res = buf.tobytes()
    except Exception as ex:
        res = "Exception:" + str(ex) + ' at ' + getActiveLine()
        return res
    return response.RawResponse(ctx,
                                response_data=res,
                                headers={
                                    "Content-Type": "application/octet-stream",
                                })
コード例 #7
0
ファイル: func.py プロジェクト: paulfelix/fdk-python
def handler(context, data=None):
    """
    General purpose Python3 function processor

    Why general purpose?

     - It supports any call from Fn-powered Python applications
       that utilizes corresponding API to run
       distributed Python functions

    How is it different from other Python FDK functions?

     - This function works with serialized Python callable objects via wire.
       Each function supplied with set of external dependencies that are
       represented as serialized functions, no matter if they are module-level,
       class-level Python objects

    :param context: request context
    :type context: fdk.context.RequestContext
    :param data: request data
    :type data: dict
    :return: resulting object of distributed function
    :rtype: object
    """
    payload = ujson.loads(data)
    (self_in_bytes,
     action_in_bytes, action_args, action_kwargs) = (
        payload['self'],
        payload['action'],
        payload['args'],
        payload['kwargs'])

    print("Got {} bytes of class instance".format(len(self_in_bytes)),
          file=sys.stderr, flush=True)
    print("Got {} bytes of function".format(len(action_in_bytes)),
          file=sys.stderr, flush=True)

    print("string class instance unpickling",
          file=sys.stderr, flush=True)
    self = dill.loads(bytes(self_in_bytes))
    print("class instance unpickled, type: ", type(self),
          file=sys.stderr, flush=True)
    print("string class instance function unpickling",
          file=sys.stderr, flush=True)
    action = dill.loads(bytes(action_in_bytes))
    print("class instance function unpickled, type: ",
          type(action), file=sys.stderr, flush=True)

    action_args.insert(0, self)

    dependencies = action_kwargs.get("dependencies", {})
    print("cached external methods found: ", len(dependencies) > 0,
          file=sys.stderr, flush=True)
    for name, method_in_bytes in dependencies.items():
        dependencies[name] = dill.loads(bytes(method_in_bytes))

    action_kwargs["dependencies"] = dependencies

    print("cached dependencies unpickled", file=sys.stderr, flush=True)

    try:
        res = action(*action_args, **action_kwargs)
    except Exception as ex:
        print("call failed", file=sys.stderr, flush=True)
        return response.RawResponse(
            context,
            status_code=500,
            response_data=str(ex))

    print("call result: {}".format(res), file=sys.stderr, flush=True)

    return response.RawResponse(
        context,
        status_code=200,
        response_data=res)
コード例 #8
0
ファイル: funcs.py プロジェクト: paulfelix/fdk-python
def custom_response(ctx, data=None):
    return response.RawResponse(ctx,
                                response_data=dummy_func(ctx, data=data),
                                status_code=201)
コード例 #9
0
ファイル: funcs.py プロジェクト: paulfelix/fdk-python
def content_type(ctx, data=None):
    return response.RawResponse(ctx,
                                response_data="OK",
                                status_code=200,
                                headers={"content-type": "application/xml"})
コード例 #10
0
ファイル: func.py プロジェクト: paulfelix/fdk-python
def handler(ctx, data=None):
    return response.RawResponse(ctx,
                                response_data="OK",
                                status_code=200,
                                headers={"content-type": "application/json"})
コード例 #11
0
def invalid_xml(ctx, **kwargs):
    return response.RawResponse(ctx,
                                response_data=ujson.dumps(xml),
                                headers={
                                    "Content-Type": "application/xml",
                                })
コード例 #12
0
def valid_xml(ctx, **kwargs):
    return response.RawResponse(ctx,
                                response_data=xml,
                                headers={
                                    "Content-Type": "application/xml",
                                })
コード例 #13
0
def content_type(ctx, data=None):
    return response.RawResponse(ctx,
                                response_data="OK",
                                status_code=200,
                                headers={"Content-Type": "text/plain"})
コード例 #14
0
def verify_request_headers(ctx, **kwargs):
    return response.RawResponse(ctx,
                                response_data=ujson.dumps(xml),
                                headers=ctx.Headers())