stitch-a-ton-answer/action.py

67 lines
1.8 KiB
Python
Raw Normal View History

2025-11-17 10:45:36 +00:00
# /// script
2025-11-19 07:21:17 +00:00
# requires-python = ">=3.14"
2025-11-17 10:45:36 +00:00
# dependencies = ["requests<3"]
# ///
import json
import os
2025-11-19 07:21:17 +00:00
import sys
2025-11-19 04:33:49 +00:00
2025-11-17 10:45:36 +00:00
import requests
def download_image(url, payload, filepath):
try:
# Use a session for potential connection pooling
with requests.Session() as s:
with s.post(url, json=payload, stream=True) as response:
response.raise_for_status()
# Write the content to the file in chunks
2025-11-19 04:33:49 +00:00
with open(filepath, "wb") as f:
2025-11-17 10:45:36 +00:00
for chunk in response.iter_content(chunk_size=8192):
f.write(chunk)
2025-11-19 04:33:49 +00:00
2025-11-17 10:45:36 +00:00
print(f" SUCCESS: Saved '{os.path.basename(filepath)}'")
except requests.exceptions.HTTPError as e:
2025-11-19 04:33:49 +00:00
print(
f" ERROR: HTTP error for '{os.path.basename(filepath)}': {e.response.status_code} {e.response.reason}"
)
2025-11-17 10:45:36 +00:00
except requests.exceptions.RequestException as e:
2025-11-19 04:33:49 +00:00
print(
f" ERROR: Could not download '{os.path.basename(filepath)}'. Reason: {e}"
)
2025-11-17 10:45:36 +00:00
def main():
2025-11-19 07:21:17 +00:00
host = os.getenv("CONTEST_HOST")
endpoint = os.getenv("CONTEST_API")
if host is None or endpoint is None:
print("env variable is not set")
return -1
API_ENDPOINT_URL = host + endpoint
2025-11-19 04:33:49 +00:00
with open("answer.json", "r") as file:
2025-11-19 07:21:17 +00:00
answers = json.load(file)
2025-11-17 10:45:36 +00:00
2025-11-19 07:21:17 +00:00
if not answers:
return -1
2025-11-17 10:45:36 +00:00
2025-11-19 07:21:17 +00:00
for test in answers.get("tests", []):
filename = test.get("name")
request_payload = test.get("request")
2025-11-17 10:45:36 +00:00
if not filename or not request_payload:
2025-11-19 07:21:17 +00:00
print(f"Skipping invalid test case: {test}")
2025-11-17 10:45:36 +00:00
continue
print(f"Requesting '{filename}'...")
2025-11-19 04:33:49 +00:00
download_image(API_ENDPOINT_URL, request_payload, filename)
2025-11-17 10:45:36 +00:00
if __name__ == "__main__":
2025-11-19 07:21:17 +00:00
sys.exit(main())