Files
2026-04-08 14:21:18 +08:00

62 lines
1.5 KiB
Python

import argparse
import base64
import json
from pathlib import Path
from urllib import error, request
def parse_args():
parser = argparse.ArgumentParser(
description="Send an image classification request to the local server."
)
parser.add_argument(
"--url",
default="http://127.0.0.1:8000/v1/classify",
help="Classify endpoint URL.",
)
parser.add_argument(
"--image",
default="cats_image.jpeg",
help="Image path to upload.",
)
return parser.parse_args()
def main():
args = parse_args()
image_path = Path(args.image)
if not image_path.exists():
raise FileNotFoundError(f"image not found: {image_path}")
payload = {
"image": base64.b64encode(image_path.read_bytes()).decode("utf-8"),
"image_name": image_path.name,
}
data = json.dumps(payload).encode("utf-8")
req = request.Request(
args.url,
data=data,
headers={"Content-Type": "application/json"},
method="POST",
)
try:
with request.urlopen(req) as resp:
body = resp.read().decode("utf-8")
print(f"status_code: {resp.status}")
print("response:")
print(body)
except error.HTTPError as exc:
body = exc.read().decode("utf-8", errors="replace")
print(f"status_code: {exc.code}")
print("response:")
print(body)
raise
except error.URLError as exc:
raise RuntimeError(f"request failed: {exc}") from exc
if __name__ == "__main__":
main()