Spaces:
Sleeping
Sleeping
| import requests | |
| import json | |
| import random | |
| import os | |
| from datetime import datetime, timedelta | |
| # --- Configuration --- | |
| API_URL = "http://127.0.0.1:8000/measure" | |
| IMAGE_DIR = "test_data" | |
| IMAGE_NAME = "test1_post.png" # The name of the image file you will provide | |
| # --- Pre-defined list of sample metadata --- | |
| METADATA_SAMPLES = [ | |
| { | |
| "ship_id": "IMO9321483", | |
| "timestamp": (datetime.utcnow() - timedelta(hours=2)).isoformat() + "Z", | |
| "latitude": 1.2646, | |
| "longitude": 103.8357, | |
| "camera_id": "CAM-04" | |
| }, | |
| { | |
| "ship_id": "IMO9839272", | |
| "timestamp": (datetime.utcnow() - timedelta(minutes=45)).isoformat() + "Z", | |
| "latitude": 51.9432, | |
| "longitude": 4.1497, | |
| "camera_id": "JETTY-7B" | |
| }, | |
| { | |
| "ship_id": "IMO9450259", | |
| "timestamp": (datetime.utcnow() - timedelta(days=1)).isoformat() + "Z", | |
| "latitude": 31.2244, | |
| "longitude": 121.4737, | |
| "camera_id": "FIXED-PIER-3" | |
| }, | |
| { | |
| "ship_id": "IMO9226788", | |
| "timestamp": datetime.utcnow().isoformat() + "Z", | |
| "latitude": 33.7542, | |
| "longitude": -118.2165, | |
| "camera_id": "DRONE-ALPHA" | |
| } | |
| ] | |
| def run_test(): | |
| """Runs a single integration test against the API.""" | |
| image_path = os.path.join(IMAGE_DIR, IMAGE_NAME) | |
| # 1. Check if the image file exists | |
| if not os.path.exists(image_path): | |
| print(f"Error: Test image not found at '{image_path}'") | |
| print("Please place your test image there before running the script.") | |
| return | |
| # 2. Randomly select a metadata object | |
| metadata = random.choice(METADATA_SAMPLES) | |
| print(f"Selected metadata for this test run:\n{json.dumps(metadata, indent=2)}\n") | |
| # 3. Open the image file and send the request | |
| try: | |
| with open(image_path, "rb") as image_file: | |
| files = {"image": (IMAGE_NAME, image_file, "image/png")} | |
| form_data = {"metadata_json": json.dumps(metadata)} | |
| print(f"Sending request to {API_URL}...") | |
| response = requests.post(API_URL, files=files, data=form_data) | |
| # 4. Print the server's response | |
| print(f"\n--- Server Response ---") | |
| print(f"Status Code: {response.status_code}") | |
| if response.status_code == 200: | |
| print("Response JSON:") | |
| print(response.json()) | |
| else: | |
| print("Error Response Text:") | |
| print(response.text) | |
| print("-----------------------") | |
| except requests.exceptions.ConnectionError as e: | |
| print(f"\nError: Connection to the API server failed.") | |
| print("Please ensure the main application is running (`python main.py`).") | |
| print(f"Details: {e}") | |
| except Exception as e: | |
| print(f"An unexpected error occurred: {e}") | |
| if __name__ == "__main__": | |
| run_test() | |