""" Minimal example client for the AI-Circle TraCIM expert. Workflow: 1. Request test data for an order key (POST {api}/order/{order_key}/test) 2. Download the sample images listed in the returned XML 3. Detect circles in each image (replace `detect_circles` with your own algorithm!) 4. Upload the results (POST {api}/test/{process_key}) 5. Save the returned test reports (XML + PDF) Usage: python examples/minimal_client.py [--api https://tracim.ptb.de/tracim/api] """ import argparse import base64 import math import os import xml.etree.ElementTree as ET from xml.sax.saxutils import escape import requests from PIL import Image NS = { "tracim": "http://tracim.ptb.de/tracim", "dx": "https://ptb.de/dx", } def detect_circles(image_path: str) -> list[tuple[float, float, float]]: """Returns detected circles as (x, y, radius) tuples in pixel units. This is a placeholder: plug in your own circle detection algorithm here! """ return [] def fetch_test(api: str, order_key: str) -> tuple[str, list[str]]: """Requests a new test and returns the process key and the sample image URLs.""" resp = requests.post(f"{api}/order/{order_key}/test", timeout=20) resp.raise_for_status() root = ET.fromstring(resp.content) process_key = root.findtext(".//tracim:process/tracim:key", namespaces=NS).strip() image_urls = [ el.text.strip() for el in root.iterfind(".//dx:quantity[@dx:refType='aicircle_sample']/dx:noQuantity/dx:content", NS) ] return process_key, image_urls def download(url: str, target_dir: str) -> str: path = os.path.join(target_dir, os.path.basename(url)) resp = requests.get(url, timeout=30) resp.raise_for_status() with open(path, "wb") as f: f.write(resp.content) return path def result_xml(url: str, width: int, height: int, circles: list[tuple[float, float, float]]) -> str: """Builds a single element for one sample image.""" sample_id = os.path.splitext(os.path.basename(url))[0] xs = " ".join(f"{x:.1f}" for x, _, _ in circles) ys = " ".join(f"{y:.1f}" for _, y, _ in circles) rs = " ".join(f"{r:.1f}" for _, _, r in circles) surface_ratio = sum(math.pi * r**2 for _, _, r in circles) / (width * height) return f""" Result {escape(sample_id)} {escape(url)} Count {float(len(circles))} \\one AreaRatio {surface_ratio:.4f} \\one CartesianCoordinates {xs} \\one CartesianCoordinates {ys} \\one Radius {rs} """ def wrap_results(results: list[str]) -> str: return f""" {"".join(results)} """ def upload(api: str, process_key: str, xml: str, target_dir: str): """Uploads the results and stores the returned XML and PDF reports.""" resp = requests.post( f"{api}/test/{process_key}", data=xml.encode("utf-8"), headers={"Content-Type": "application/xml"}, timeout=60, ) resp.raise_for_status() root = ET.fromstring(resp.content) report = root.find(".//tracim:report", NS) if report is not None: content = ET.tostring(report[0], encoding="unicode") if len(report) else report.text or "" with open(os.path.join(target_dir, "report.xml"), "w", encoding="utf-8") as f: f.write(content) pdf = root.findtext(".//tracim:reportPDF", namespaces=NS) if pdf: with open(os.path.join(target_dir, "report.pdf"), "wb") as f: f.write(base64.b64decode(pdf.strip())) def main(): parser = argparse.ArgumentParser(description="Minimal AI-Circle TraCIM client") parser.add_argument("order_key", help="TraCIM order key") parser.add_argument("--api", default="https://tracim.ptb.de/tracim/api", help="TraCIM API base URL") parser.add_argument("--out", default="tracim_output", help="Output directory") args = parser.parse_args() process_key, image_urls = fetch_test(args.api, args.order_key) out_dir = os.path.join(args.out, process_key) os.makedirs(out_dir, exist_ok=True) print(f"Process key: {process_key} ({len(image_urls)} samples)") results = [] for i, url in enumerate(image_urls, 1): path = download(url, out_dir) width, height = Image.open(path).size circles = detect_circles(path) print(f"[{i}/{len(image_urls)}] {os.path.basename(path)}: {len(circles)} circles") results.append(result_xml(url, width, height, circles)) xml = wrap_results(results) with open(os.path.join(out_dir, "results.xml"), "w", encoding="utf-8") as f: f.write(xml) upload(args.api, process_key, xml, out_dir) print(f"Reports saved to {out_dir}") if __name__ == "__main__": main()