add generate.py

This commit is contained in:
adienakhmad 2025-11-17 10:45:36 +00:00
parent b54728dcda
commit f6b28fc2ca

65
generate.py Normal file
View file

@ -0,0 +1,65 @@
# /// script
# requires-python = ">=3.12"
# dependencies = ["requests<3"]
# ///
import json
import os
import requests
MANIFEST_URL = "https://null.formulatrix.dev/Contest/stitch-a-ton-answer/raw/branch/main/answer.json"
API_ENDPOINT_URL = os.getenv("CONTEST_HOST")+ os.getenv("CONTEST_ENDPOINT")
DOWNLOAD_DIR = os.getenv("CONTEST_OUTPUT")
def fetch_manifest(url):
print(f"fetching manifest from {url}...")
try:
response = requests.get(url)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
print(f" ERROR: Could not fetch manifest. Reason: {e}")
except json.JSONDecodeError:
print(" ERROR: Failed to parse JSON from manifest. The content may not be valid JSON.")
return None
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
with open(filepath, 'wb') as f:
for chunk in response.iter_content(chunk_size=8192):
f.write(chunk)
print(f" SUCCESS: Saved '{os.path.basename(filepath)}'")
except requests.exceptions.HTTPError as e:
print(f" ERROR: HTTP error for '{os.path.basename(filepath)}': {e.response.status_code} {e.response.reason}")
except requests.exceptions.RequestException as e:
print(f" ERROR: Could not download '{os.path.basename(filepath)}'. Reason: {e}")
def main():
os.makedirs(DOWNLOAD_DIR, exist_ok=True)
manifest_data = fetch_manifest(MANIFEST_URL)
if not manifest_data:
return
for test_case in manifest_data.get("tests", []):
filename = test_case.get("name")
request_payload = test_case.get("request")
if not filename or not request_payload:
print(f"Skipping invalid test case: {test_case}")
continue
print(f"Requesting '{filename}'...")
output_filepath = os.path.join(DOWNLOAD_DIR, filename)
download_image(API_ENDPOINT_URL, request_payload, output_filepath)
if __name__ == "__main__":
main()