Spaces:
Sleeping
Sleeping
File size: 5,130 Bytes
a027087 | 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 | """Verify the running FastAPI server with a real HTTP enhancement request."""
from __future__ import annotations
import argparse
import json
import sys
import time
from io import BytesIO
from pathlib import Path
import httpx
from PIL import Image
BACKEND_ROOT = Path(__file__).resolve().parents[1]
DEFAULT_INPUT = BACKEND_ROOT / "tests" / "fixtures" / "0014.jpg"
DEFAULT_OUTPUT = BACKEND_ROOT / "outputs" / "api-0014-enhanced-4x.png"
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--base-url", default="http://127.0.0.1:8000")
parser.add_argument("--input", type=Path, default=DEFAULT_INPUT)
parser.add_argument("--output", type=Path, default=DEFAULT_OUTPUT)
arguments = parser.parse_args()
base_url = arguments.base_url.rstrip("/")
input_bytes = arguments.input.read_bytes()
with Image.open(BytesIO(input_bytes)) as source:
source.load()
source_width, source_height = source.size
timeout = httpx.Timeout(connect=10, read=180, write=30, pool=10)
with httpx.Client(timeout=timeout) as client:
health = client.get(f"{base_url}/health")
health.raise_for_status()
if health.json().get("ready") is not True:
raise RuntimeError("The API health endpoint did not report ready.")
docs = client.get(f"{base_url}/docs")
docs.raise_for_status()
if "swagger-ui" not in docs.text:
raise RuntimeError("Swagger UI was not served at /docs.")
schema_response = client.get(f"{base_url}/openapi.json")
schema_response.raise_for_status()
schema = schema_response.json()
operation = schema["paths"]["/api/enhance"]["post"]
form_schema = operation["requestBody"]["content"]["multipart/form-data"][
"schema"
]
component = form_schema.get("$ref", "").rsplit("/", maxsplit=1)[-1]
fields = sorted(schema["components"]["schemas"][component]["properties"])
if fields != ["file", "output_format", "scale"]:
raise RuntimeError(f"Unexpected multipart fields in OpenAPI: {fields}")
started = time.perf_counter()
response = client.post(
f"{base_url}/api/enhance",
files={"file": (arguments.input.name, input_bytes, "image/jpeg")},
data={"scale": "4", "output_format": "png"},
)
elapsed = time.perf_counter() - started
response.raise_for_status()
expected_size = (source_width * 4, source_height * 4)
required_headers = {
"x-original-width": str(source_width),
"x-original-height": str(source_height),
"x-enhanced-width": str(expected_size[0]),
"x-enhanced-height": str(expected_size[1]),
"x-upscale-factor": "4",
"x-model": "RealESRGAN_x4plus",
}
for name, value in required_headers.items():
if response.headers.get(name) != value:
raise RuntimeError(f"Unexpected {name} response header.")
if (
response.headers.get("content-type", "").split(";", maxsplit=1)[0]
!= "image/png"
):
raise RuntimeError("The API did not return a PNG image.")
if not response.headers.get("content-disposition", "").startswith("attachment;"):
raise RuntimeError("The response did not include a download disposition.")
if response.content == input_bytes:
raise RuntimeError("The API response unexpectedly matches the input bytes.")
with Image.open(BytesIO(response.content)) as output:
output.load()
if output.format != "PNG" or output.size != expected_size:
raise RuntimeError(
f"Unexpected decoded output: {output.format} {output.size}, "
f"expected PNG {expected_size}."
)
arguments.output.parent.mkdir(parents=True, exist_ok=True)
arguments.output.write_bytes(response.content)
print(
json.dumps(
{
"health_status": health.status_code,
"docs_status": docs.status_code,
"openapi_status": schema_response.status_code,
"openapi_multipart_fields": fields,
"enhance_status": response.status_code,
"content_type": response.headers["content-type"],
"response_headers": {
**required_headers,
"content-disposition": response.headers["content-disposition"],
},
"input_dimensions": [source_width, source_height],
"output_dimensions": list(expected_size),
"output_bytes": len(response.content),
"output_path": str(arguments.output.resolve()),
"elapsed_seconds": round(elapsed, 3),
"response_differs_from_input": response.content != input_bytes,
},
indent=2,
)
)
return 0
if __name__ == "__main__":
try:
raise SystemExit(main())
except Exception as error:
print(f"HTTP API smoke test failed: {error}", file=sys.stderr)
raise SystemExit(1) from error
|