Skip to content

Commit cc25927

Browse files
author
Khadijeh Alibabaei
committed
some parts were removed by mistake
1 parent ad66de6 commit cc25927

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

api/responses.py

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,76 @@ def json_response(results, **options):
7676
logger.warning("Error converting result to JSON: %s", err)
7777
raise RuntimeError("Unsupported response type") from err
7878

79+
def pdf_response(results, **options):
80+
"""Converts the prediction or training results into pdf return format.
81+
82+
Arguments:
83+
result -- Result value from call, expected dict
84+
options -- Not used, added for illustration purpose.
85+
86+
Raises:
87+
RuntimeError: Unsupported response type.
88+
89+
Returns:
90+
Converted result into pdf buffer format.
91+
"""
92+
logger.debug("Response result type: %d", type(results))
93+
logger.debug("Response result: %d", results)
94+
logger.debug("Response options: %d", options)
95+
96+
try:
97+
merger = PdfFileMerger()
98+
for element in results[0]:
99+
# result.append(element.plot())
100+
im = Image.fromarray(
101+
element.plot(
102+
labels=options["show_labels"],
103+
conf=options["show_conf"],
104+
boxes=options["show_boxes"],
105+
)
106+
)
107+
im = im.convert("RGB")
108+
buffer = BytesIO()
109+
buffer.name = "output.pdf"
110+
im.save(buffer)
111+
merger.append(buffer)
112+
buffer.seek(0)
113+
buffer_out = BytesIO()
114+
merger.write(buffer_out)
115+
buffer_out.name = "output.pdf"
116+
buffer_out.seek(0)
117+
return buffer_out
118+
except Exception as err: # TODO: Fix to specific exception
119+
logger.warning("Error converting result to pdf: %s", err)
120+
raise RuntimeError("Unsupported response type") from err
121+
122+
123+
def png_response(results, **options):
124+
logger.debug("Response result type: %d", type(results))
125+
logger.debug("Response result: %d", results)
126+
logger.debug("Response options: %d", options)
127+
try:
128+
for result in results[0]:
129+
# this will return a numpy array with the labels
130+
result = result.plot(
131+
labels=options["show_labels"],
132+
conf=options["show_conf"],
133+
boxes=options["show_boxes"],
134+
font_size=6.0,
135+
)
136+
success, buffer = cv2.imencode(".png", result)
137+
if not success:
138+
return "Error encoding image", 500
139+
140+
# Create a BytesIO object and write the buffer into it
141+
image_buffer = BytesIO(buffer)
142+
143+
return image_buffer
144+
except Exception as err: # TODO: Fix to specific exception
145+
logger.warning("Error converting result to png: %s", err)
146+
raise RuntimeError("Unsupported response type") from err
147+
148+
79149
def create_video_in_buffer(frame_arrays, output_format="mp4"):
80150
height, width, _ = frame_arrays[0].shape
81151
fourcc = cv2.VideoWriter_fourcc(*"mp4v")

0 commit comments

Comments
 (0)