Python

C#の標準出力
Pythonの標準入力
communication_main.py
    ├─ カメラ番号などを読み取る
    ├─ PNG/JPEGバイト列を読み取る
    └─ PIL.Image.Imageへ復元
inference_processor.py
    process_image(image, camera_number)
    list[dict]を返す
communication_main.py
    ├─ PIL画像をPNGバイト列へ変換
    ├─ JSONメタデータを作成
    └─ 標準出力でC#へ返す

通信仕様

C#からPythonへの1要求は、次の順番です。

1
2
3
4
8 bytes   JSONメタデータ長
可変長    JSONメタデータ
8 bytes   入力PNG長
可変長    入力PNG

JSON例です。

1
2
3
4
5
{
  "command": "process",
  "request_id": 1001,
  "camera_number": 2
}
PythonからC#への応答です。
1
2
3
4
5
6
7
8 bytes   結果JSON長
可変長    結果JSON
8 bytes   結果画像枚数

画像枚数分繰り返し:
    8 bytes   PNG長
    可変長    PNG本体
整数はすべて、符号なし64bit・リトルエンディアンです。

※stdoutには絶対に通常のprint()を出さないでください

ログは必ずstderrです。

1
2
3
4
5
print(
    "推論開始",
    file=sys.stderr,
    flush=True,
)

  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
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
    # response_converter.py

    from __future__ import annotations

    import json
    from io import BytesIO
    from typing import Any

    from PIL import Image


    def pil_image_to_png_bytes(
        image: Image.Image,
        compress_level: int = 3,
    ) -> bytes:
        """
        PIL.Image.ImageをPNGファイル形式のbytesへ変換する。

        Parameters
        ----------
        image:
            PNGへ変換するPIL画像。

        compress_level:
            PNG圧縮レベル。0~9。
            0は圧縮なしで高速・大容量。
            9は高圧縮だが低速。
            連続処理では1~3程度から試すのがおすすめ。

        Returns
        -------
        bytes:
            PNGファイル全体のバイト列。
        """

        if not isinstance(image, Image.Image):
            raise TypeError(
                "imageはPIL.Image.Imageである必要があります。"
                f" actual={type(image)}"
            )

        if not isinstance(compress_level, int):
            raise TypeError(
                "compress_levelはintである必要があります。"
            )

        if not 0 <= compress_level <= 9:
            raise ValueError(
                "compress_levelは0~9の範囲で指定してください。"
            )

        buffer = BytesIO()

        image.save(
            buffer,
            format="PNG",
            compress_level=compress_level,
        )

        return buffer.getvalue()


    def create_response_data(
        inference_results: list[dict[str, Any]],
        request_id: int | str | None,
        compress_level: int = 3,
    ) -> tuple[bytes, list[bytes]]:
        """
        inference_processor.pyから返されたlist[dict]を、
        C#送信用のJSONメタデータとPNGバイト列へ変換する。

        想定する入力要素
        ----------------
        {
            "image": PIL.Image.Image,
            "class_name": str,
            "score": float,
            "camera_number": int,
            "result_index": int,
            "request_id": int | str | None
        }

        Returns
        -------
        tuple[bytes, list[bytes]]:
            1. UTF-8のJSONバイト列
            2. PNG画像バイト列のリスト
        """

        if not isinstance(inference_results, list):
            raise TypeError(
                "inference_resultsはlistである必要があります。"
                f" actual={type(inference_results)}"
            )

        metadata_results: list[dict[str, Any]] = []
        png_images: list[bytes] = []

        for list_index, result in enumerate(inference_results):
            if not isinstance(result, dict):
                raise TypeError(
                    "inference_resultsの各要素はdictである必要があります。"
                    f" index={list_index}, actual={type(result)}"
                )

            image = _get_required_value(
                result,
                key="image",
                expected_type=Image.Image,
                result_index=list_index,
            )

            class_name = _get_required_value(
                result,
                key="class_name",
                expected_type=str,
                result_index=list_index,
            )

            score_value = _get_required_numeric_value(
                result,
                key="score",
                result_index=list_index,
            )

            # dictにresult_indexがなければリスト位置を使用
            result_index = int(
                result.get(
                    "result_index",
                    list_index,
                )
            )

            camera_number_value = result.get(
                "camera_number",
                None,
            )

            camera_number = (
                int(camera_number_value)
                if camera_number_value is not None
                else None
            )

            png_bytes = pil_image_to_png_bytes(
                image=image,
                compress_level=compress_level,
            )

            png_images.append(png_bytes)

            metadata_results.append(
                {
                    "result_index": result_index,
                    "class_name": class_name,
                    "score": float(score_value),
                    "camera_number": camera_number,

                    # PNGバイナリ自体はJSONへ入れない
                    "image_index": list_index,
                    "image_format": "png",
                    "image_length": len(png_bytes),

                    # 参考情報。PNG内部にもサイズ情報は含まれる
                    "image_width": int(image.width),
                    "image_height": int(image.height),
                    "image_mode": str(image.mode),
                }
            )

        metadata = {
            "success": True,
            "request_id": request_id,
            "result_count": len(metadata_results),
            "results": metadata_results,
            "error": None,
        }

        json_bytes = json.dumps(
            metadata,
            ensure_ascii=False,
            separators=(",", ":"),
        ).encode("utf-8")

        return json_bytes, png_images


    def create_error_response_data(
        request_id: int | str | None,
        error_code: str,
        error_message: str,
    ) -> tuple[bytes, list[bytes]]:
        """
        C#へ返すエラー応答を作成する。

        エラー時は画像数0で返す。
        """

        metadata = {
            "success": False,
            "request_id": request_id,
            "result_count": 0,
            "results": [],
            "error": {
                "code": str(error_code),
                "message": str(error_message),
            },
        }

        json_bytes = json.dumps(
            metadata,
            ensure_ascii=False,
            separators=(",", ":"),
        ).encode("utf-8")

        return json_bytes, []


    def _get_required_value(
        source: dict[str, Any],
        key: str,
        expected_type: type,
        result_index: int,
    ) -> Any:
        """
        dictから必須値を取得し、型を確認する。
        """

        if key not in source:
            raise KeyError(
                f"推論結果に必須キー'{key}'がありません。"
                f" result_index={result_index}"
            )

        value = source[key]

        if not isinstance(value, expected_type):
            raise TypeError(
                f"推論結果の'{key}'の型が不正です。"
                f" result_index={result_index},"
                f" expected={expected_type},"
                f" actual={type(value)}"
            )

        return value


    def _get_required_numeric_value(
        source: dict[str, Any],
        key: str,
        result_index: int,
    ) -> float:
        """
        intまたはfloatの必須値を取得する。

        NumPyのfloat32などが入る可能性がある場合でも、
        float()で変換可能なら受け付ける。
        """

        if key not in source:
            raise KeyError(
                f"推論結果に必須キー'{key}'がありません。"
                f" result_index={result_index}"
            )

        value = source[key]

        try:
            return float(value)
        except (TypeError, ValueError) as exception:
            raise TypeError(
                f"推論結果の'{key}'をfloatへ変換できません。"
                f" result_index={result_index},"
                f" actual={type(value)}"
            ) from exception



    # communication_main.py

    from __future__ import annotations

    import json
    import struct
    import sys
    import traceback
    from io import BytesIO
    from pathlib import Path
    from typing import Any, BinaryIO

    from PIL import Image, UnidentifiedImageError

    from inference_processor import ImageInferenceProcessor
    from response_converter import (
        create_error_response_data,
        create_response_data,
    )


    # 1つの受信画像に許可する最大サイズ。
    # 異常値で巨大メモリを確保しないための上限。
    MAX_INPUT_IMAGE_BYTES = 512 * 1024 * 1024

    # JSONメタデータの最大サイズ。
    MAX_JSON_BYTES = 10 * 1024 * 1024

    # C#へ返すPNGの圧縮レベル。
    # 連続処理ではまず1~3を推奨。
    PNG_COMPRESS_LEVEL = 3


    class EndOfInputError(Exception):
        """
        C#側が標準入力を閉じた場合に使用する例外。
        """


    class ProtocolError(Exception):
        """
        通信プロトコルが不正な場合に使用する例外。
        """


    def log(
        message: str,
    ) -> None:
        """
        ログはstdoutではなくstderrへ出力する。

        stdoutはC#とのバイナリ通信専用なので、
        print()を通常どおり使ってはいけない。
        """

        print(
            message,
            file=sys.stderr,
            flush=True,
        )


    def read_exact(
        stream: BinaryIO,
        byte_count: int,
    ) -> bytes:
        """
        streamから指定されたバイト数を必ず読み取る。

        read()は要求数より少ないデータを返す可能性があるため、
        必要数に達するまで繰り返す。
        """

        if byte_count < 0:
            raise ValueError(
                "byte_countは0以上である必要があります。"
            )

        if byte_count == 0:
            return b""

        buffer = bytearray()

        while len(buffer) < byte_count:
            chunk = stream.read(
                byte_count - len(buffer)
            )

            if not chunk:
                if len(buffer) == 0:
                    raise EndOfInputError(
                        "標準入力が閉じられました。"
                    )

                raise EOFError(
                    "要求されたデータの途中で標準入力が閉じられました。"
                    f" expected={byte_count}, actual={len(buffer)}"
                )

            buffer.extend(chunk)

        return bytes(buffer)


    def read_uint64(
        stream: BinaryIO,
    ) -> int:
        """
        リトルエンディアンの符号なし64bit整数を読み取る。
        """

        raw_bytes = read_exact(
            stream,
            8,
        )

        return struct.unpack(
            "<Q",
            raw_bytes,
        )[0]


    def write_uint64(
        stream: BinaryIO,
        value: int,
    ) -> None:
        """
        リトルエンディアンの符号なし64bit整数を書き込む。
        """

        if value < 0:
            raise ValueError(
                "valueは0以上である必要があります。"
            )

        stream.write(
            struct.pack(
                "<Q",
                value,
            )
        )


    def read_request() -> tuple[dict[str, Any], Image.Image | None]:
        """
        C#から1要求を読み取る。

        受信形式
        --------
        8 bytes : JSON長
        N bytes : JSON本体
        8 bytes : 入力画像長
        M bytes : 入力画像本体

        shutdown要求では画像長を0にできる。

        Returns
        -------
        tuple:
            request_metadata, PIL画像またはNone
        """

        input_stream = sys.stdin.buffer

        json_length = read_uint64(
            input_stream
        )

        if json_length == 0:
            raise ProtocolError(
                "JSON長が0です。"
            )

        if json_length > MAX_JSON_BYTES:
            raise ProtocolError(
                "JSONメタデータが上限を超えています。"
                f" length={json_length},"
                f" max={MAX_JSON_BYTES}"
            )

        json_bytes = read_exact(
            input_stream,
            json_length,
        )

        try:
            metadata = json.loads(
                json_bytes.decode("utf-8")
            )
        except UnicodeDecodeError as exception:
            raise ProtocolError(
                "JSONメタデータをUTF-8として読み込めません。"
            ) from exception
        except json.JSONDecodeError as exception:
            raise ProtocolError(
                "JSONメタデータの形式が不正です。"
            ) from exception

        if not isinstance(metadata, dict):
            raise ProtocolError(
                "要求JSONのルートはobjectである必要があります。"
            )

        image_length = read_uint64(
            input_stream
        )

        if image_length > MAX_INPUT_IMAGE_BYTES:
            raise ProtocolError(
                "入力画像が上限サイズを超えています。"
                f" length={image_length},"
                f" max={MAX_INPUT_IMAGE_BYTES}"
            )

        command = str(
            metadata.get(
                "command",
                "process",
            )
        ).lower()

        if command == "shutdown":
            # shutdown時は画像データを破棄する。
            # 通常はimage_length=0を想定。
            if image_length > 0:
                read_exact(
                    input_stream,
                    image_length,
                )

            return metadata, None

        if image_length == 0:
            raise ProtocolError(
                "process要求ですが入力画像長が0です。"
            )

        image_bytes = read_exact(
            input_stream,
            image_length,
        )

        try:
            # BytesIOが閉じられても利用できるよう、
            # load()後にcopy()して独立した画像にする。
            with Image.open(
                BytesIO(image_bytes)
            ) as opened_image:
                opened_image.load()
                input_image = opened_image.copy()

        except UnidentifiedImageError as exception:
            raise ProtocolError(
                "受信データを画像として認識できません。"
            ) from exception
        except OSError as exception:
            raise ProtocolError(
                "受信画像のデコードに失敗しました。"
            ) from exception

        return metadata, input_image


    def write_response(
        json_bytes: bytes,
        png_images: list[bytes],
    ) -> None:
        """
        JSONメタデータと複数のPNGをC#へ送信する。

        送信形式
        --------
        8 bytes : JSON長
        N bytes : JSON本体

        8 bytes : 画像枚数

        画像枚数分:
            8 bytes : PNG長
            M bytes : PNG本体
        """

        output_stream = sys.stdout.buffer

        write_uint64(
            output_stream,
            len(json_bytes),
        )

        output_stream.write(
            json_bytes
        )

        write_uint64(
            output_stream,
            len(png_images),
        )

        for png_bytes in png_images:
            write_uint64(
                output_stream,
                len(png_bytes),
            )

            output_stream.write(
                png_bytes
            )

        # C#側へすぐ届くよう必ずflushする
        output_stream.flush()


    def get_request_id(
        metadata: dict[str, Any],
    ) -> int | str | None:
        """
        request_idを取得する。

        数値でも文字列でも許可する。
        """

        return metadata.get(
            "request_id",
            None,
        )


    def get_camera_number(
        metadata: dict[str, Any],
    ) -> int:
        """
        JSONメタデータからcamera_numberを取得する。
        """

        if "camera_number" not in metadata:
            raise ProtocolError(
                "要求JSONにcamera_numberがありません。"
            )

        camera_number_value = metadata["camera_number"]

        # boolはintの派生型なので明示的に拒否する
        if isinstance(camera_number_value, bool):
            raise ProtocolError(
                "camera_numberにboolは指定できません。"
            )

        try:
            camera_number = int(
                camera_number_value
            )
        except (TypeError, ValueError) as exception:
            raise ProtocolError(
                "camera_numberをintへ変換できません。"
            ) from exception

        if camera_number < 0:
            raise ProtocolError(
                "camera_numberは0以上である必要があります。"
            )

        return camera_number


    def run_server(
        processor: ImageInferenceProcessor,
    ) -> None:
        """
        C#からの要求を繰り返し処理する常駐ループ。
        """

        log(
            "Python画像推論プロセスの待受を開始しました。"
        )

        while True:
            request_metadata: dict[str, Any] = {}
            request_id: int | str | None = None

            try:
                request_metadata, input_image = (
                    read_request()
                )

                request_id = get_request_id(
                    request_metadata
                )

                command = str(
                    request_metadata.get(
                        "command",
                        "process",
                    )
                ).lower()

                if command == "shutdown":
                    log(
                        "C#からshutdown要求を受信しました。"
                    )

                    shutdown_json = json.dumps(
                        {
                            "success": True,
                            "request_id": request_id,
                            "result_count": 0,
                            "results": [],
                            "shutdown": True,
                            "error": None,
                        },
                        ensure_ascii=False,
                        separators=(",", ":"),
                    ).encode("utf-8")

                    write_response(
                        json_bytes=shutdown_json,
                        png_images=[],
                    )

                    break

                if command != "process":
                    raise ProtocolError(
                        f"未対応のcommandです: {command}"
                    )

                if input_image is None:
                    raise ProtocolError(
                        "process要求ですが画像がありません。"
                    )

                camera_number = get_camera_number(
                    request_metadata
                )

                log(
                    "推論要求を受信しました。"
                    f" request_id={request_id},"
                    f" camera_number={camera_number},"
                    f" image_size={input_image.size},"
                    f" image_mode={input_image.mode}"
                )

                # inference_processor.pyの処理を呼び出す
                inference_results = processor.process_image(
                    image=input_image,
                    camera_number=camera_number,
                    request_id=request_id,
                )

                # PIL.Image.ImageをPNGへ変換し、
                # JSONメタデータと分離する
                json_bytes, png_images = (
                    create_response_data(
                        inference_results=inference_results,
                        request_id=request_id,
                        compress_level=PNG_COMPRESS_LEVEL,
                    )
                )

                write_response(
                    json_bytes=json_bytes,
                    png_images=png_images,
                )

                log(
                    "推論結果を送信しました。"
                    f" request_id={request_id},"
                    f" result_count={len(png_images)}"
                )

            except EndOfInputError:
                # C#が終了してstdinが閉じられた場合
                log(
                    "標準入力が閉じられたため終了します。"
                )
                break

            except Exception as exception:
                # 詳細ログはstderrへ出す
                traceback.print_exc(
                    file=sys.stderr
                )
                sys.stderr.flush()

                error_code = (
                    "PROTOCOL_ERROR"
                    if isinstance(exception, ProtocolError)
                    else "PROCESSING_ERROR"
                )

                error_json, no_images = (
                    create_error_response_data(
                        request_id=request_id,
                        error_code=error_code,
                        error_message=str(exception),
                    )
                )

                try:
                    write_response(
                        json_bytes=error_json,
                        png_images=no_images,
                    )
                except Exception:
                    # stdout自体が壊れている場合は継続できない
                    traceback.print_exc(
                        file=sys.stderr
                    )
                    sys.stderr.flush()
                    break


    def main() -> int:
        """
        Pythonプロセスのエントリーポイント。
        """

        try:
            script_directory = Path(
                __file__
            ).resolve().parent

            model_path = (
                script_directory
                / "models"
                / "classifier.onnx"
            )

            log(
                f"ONNXモデルを読み込みます: {model_path}"
            )

            # この時点でONNXモデルを1回だけ読み込む
            processor = ImageInferenceProcessor(
                model_path=model_path
            )

            log(
                "ONNXモデルの読み込みが完了しました。"
            )

            run_server(
                processor
            )

            log(
                "Python画像推論プロセスを終了します。"
            )

            return 0

        except Exception:
            traceback.print_exc(
                file=sys.stderr
            )
            sys.stderr.flush()

            return 1


    if __name__ == "__main__":
        raise SystemExit(
            main()
        )