a b/examples/remote_ark.py
1
#!/usr/bin/env python
2
3
__doc__ = """
4
This example shows how to use a client to access a 
5
remote Sybil server (running Ark) to predict risk scores for a set of DICOM files.
6
7
The server must be started separately.
8
9
https://github.com/reginabarzilaygroup/Sybil/wiki
10
https://github.com/reginabarzilaygroup/ark/wiki
11
"""
12
import json
13
import os
14
15
import numpy as np
16
import requests
17
18
import sybil.utils.visualization
19
20
from utils import get_demo_data
21
22
if __name__ == "__main__":
23
24
    dicom_files = get_demo_data()
25
    serie = sybil.Serie(dicom_files)
26
27
    # Set the URL of the remote Sybil server
28
    ark_hostname = "localhost"
29
    ark_port = 5000
30
31
    # Set the URL of the remote Sybil server
32
    ark_host = f"http://{ark_hostname}:{ark_port}"
33
34
    data_dict = {"return_attentions": True}
35
    payload = {"data": json.dumps(data_dict)}
36
37
    # Check if the server is running and reachable
38
    resp = requests.get(f"{ark_host}/info")
39
    if resp.status_code != 200:
40
        raise ValueError(f"Failed to connect to ARK server. Status code: {resp.status_code}")
41
42
    info_data = resp.json()["data"]
43
    assert info_data["modelName"].lower() == "sybil", "The ARK server is not running Sybil"
44
    print(f"ARK server info: {info_data}")
45
46
    # Submit prediction to ARK server.
47
    files = [('dicom', open(file_path, 'rb')) for file_path in dicom_files]
48
    r = requests.post(f"{ark_host}/dicom/files", files=files, data=payload)
49
    _ = [f[1].close() for f in files]
50
    if r.status_code != 200:
51
        raise ValueError(f"Error occurred processing DICOM files. Status code: {r.status_code}.\n{r.text}")
52
53
    r_json = r.json()
54
    predictions = r_json["data"]["predictions"]
55
56
    scores = predictions[0]
57
    print(f"Risk scores: {scores}")
58
59
    attentions = predictions[1]
60
    attentions = np.array(attentions)
61
    print(f"Ark received attention shape: {attentions.shape}")
62
63
    # Visualize attention maps
64
    save_directory = "remote_ark_sybil_attention_output"
65
66
    print(f"Writing attention images to {save_directory}")
67
68
    images = serie.get_raw_images()
69
    overlayed_images = sybil.utils.visualization.build_overlayed_images(images, attentions, gain=3)
70
71
    if save_directory is not None:
72
        serie_idx = 0
73
        save_path = os.path.join(save_directory, f"serie_{serie_idx}")
74
        sybil.utils.visualization.save_images(overlayed_images, save_path, f"serie_{serie_idx}")
75
76
    print(f"Finished writing attention images to {save_directory}")
77