Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save veggiesaurus/b7a641fc29b0b0bb5caf45631e1bdcad to your computer and use it in GitHub Desktop.

Select an option

Save veggiesaurus/b7a641fc29b0b0bb5caf45631e1bdcad to your computer and use it in GitHub Desktop.
jordan_script.py
#!/usr/bin/env python3
import argparse,webbrowser,os
from carta.session import Session
from carta.protocol import Protocol
from carta.token import ControllerToken,BackendToken
from carta.util import CartaRequestFailed,CartaBadToken,CartaActionFailed
from carta.browser import Chrome
chromeOptions = ['--force-device-scale-factor=4', '--window-size=1200,800']
def parse_args():
"""Parse arguments into this script.
Returns:
--------
args : class ``argparse.ArgumentParser``
Known and validated arguments."""
parser = argparse.ArgumentParser(description='Run CARTA via a desktop application or server/controller instance.')
instance_args = parser.add_mutually_exclusive_group(required=True)
instance_args.add_argument("-S","--server", action='store_true', required=False, default=False, help="Use CARTA server/controller given by [-U --URL]")
instance_args.add_argument("-D","--desktop", action='store_true', required=False, default=False, help="Use CARTA Desktop Application given by [-e --executable]")
sesh = parser.add_argument_group('Session Arguments')
sesh.add_argument("-s","--sessionID", metavar="ID", required=True, type=int, help="Session ID (use 0 to launch new instance)")
sesh.add_argument("-U","--URL", metavar="URL", default="https://carta.idia.ac.za", required=False, type=str, help="URL of server version to interact with")
sesh.add_argument("-T","--token", metavar="path", required=False, default='~/carta-token', type=str, help="Path to token (existing, or to be created)")
sesh.add_argument("-N","--username", metavar="username", required=False, type=str, default='jcollier', help="Username for CARTA server/controller hosted at [-U --URL]")
sesh.add_argument("-E","--executable", metavar="Local path", required=False, type=str, default='/Applications/CARTA.app/Contents/Resources/app/carta-backend/bin/carta.sh', help='Path to local CARTA executable (desktop)')
sesh.add_argument("-H","--headless", action='store_true', required=False, default=False, help="Run headless browser")
sesh.add_argument("-C","--close", action='store_true', required=False, default=False, help="Close new session (i.e. [-s --sessionID] 0) automatically (without pressing return)")
img = parser.add_argument_group('Image Operations')
img.add_argument("-I","--images", metavar="paths", action='append', required=False, type=str, help="Paths of images to open (append further images with additional call of [-I --images])")
img.add_argument("-i","--index", metavar="image", required=False, type=int, help="Image index to apply an image operation toward, with 1 as the first index (use 0 for all images). Default is active frame.")
img.add_argument("-P","--percentile", metavar="rank", required=False, type=float, help="Percentile rank") # default=99.9,
img.add_argument("-z","--zoom", metavar="Zoom level", required=False, type=float, help='Set Zoom level')
img.add_argument("-c","--contrast", metavar="Bias and contrast level", nargs=2, required=False, type=float, help='Set bias and contrast')
img.add_argument("-e","--exportPath", metavar="Local path", required=False, type=str, help="Save current/final view to this local path")
img.add_argument("-R","--lockRaster", action='store_true', required=False, default=False, help="Lock raster scaling")
img.add_argument("-W","--lockWCS", action='store_true', required=False, default=False, help="Lock WCS")
img.add_argument("-F","--lockFreq", action='store_true', required=False, default=False, help="Lock frequency")
args, unknown = parser.parse_known_args()
if len(unknown) > 0:
parser.error('Unknown input argument(s) present - {0}'.format(unknown))
return args
def server_session(URL, username, token, sessionID, headless):
try:
if sessionID == 0:
session = Session.create(Chrome(headless=headless,options=chromeOptions), URL, ControllerToken.from_file(token))
else:
session = Session.interact(URL, sessionID, ControllerToken.from_file(token))
except (CartaBadToken,CartaRequestFailed):
Protocol.request_refresh_token(URL, username, token)
session = server_session(URL, username, token, sessionID, headless)
return session
def desktop_session(URL, executable, token, sessionID, headless):
if sessionID == 0:
session = Session.start_and_create(Chrome(headless=headless,options=chromeOptions), executable)
else:
if '?token=' in URL:
session = Session.interact(URL, sessionID)
else:
session = Session.interact(URL, sessionID, BackendToken(token))
return session
def run_carta(server, desktop, headless, executable, URL, username, token, sessionID, images, lockRaster, lockWCS, lockFreq, percentile, zoom, contrast, exportPath, close, index):
if 'https://' not in URL and 'http://' not in URL:
URL = 'https://' + URL
if '~' in token:
token = os.path.expanduser(token)
if server:
session = server_session(URL, username, token, sessionID, headless)
elif desktop:
session = desktop_session(URL, executable, token, sessionID, headless)
if sessionID == 0:
print('Started session with ID: {0}'.format(session.session_id))
if images:
for i,image in enumerate(images):
try:
session.append_image(image)
except CartaRequestFailed as err:
if str(sessionID) in str(err):
print(err)
webbrowser.get('chrome').open(URL)
session.close()
sessionID = int(input('Enter session ID (right-click --> Inspect --> Console): '))
run_carta(server, desktop, headless, executable, URL, username, token, sessionID, images, lockRaster, lockWCS, lockFreq, percentile, zoom, contrast, exportPath, close, index)
return
else:
raise CartaRequestFailed(err)
imgs = session.image_list()
if index is None:
img = session.active_frame()
image_operations(img,percentile,zoom,lockRaster,lockWCS,lockFreq,contrast)
elif index > 0:
if index > len(imgs) + 1:
print("Index {0} out of bounds. Only {1} frames present.".format(index,len(imgs)))
else:
img = imgs[index-1]
image_operations(img,percentile,zoom,lockRaster,lockWCS,lockFreq,contrast)
elif index == 0:
for img in imgs:
image_operations(img,percentile,zoom,lockRaster,lockWCS,lockFreq,contrast)
if exportPath:
session.save_rendered_view(exportPath)
if not close and not headless:
input('Press return to close session: ')
if sessionID != 0:
session.close()
def image_operations(img,percentile,zoom,lockRaster,lockWCS,lockFreq,contrast):
if percentile:
img.set_percentile_rank(percentile)
if zoom:
img.set_zoom(zoom)
if lockRaster:
img.set_raster_scaling_matching(True)
if lockWCS:
img.set_spatial_matching(True)
if lockFreq:
img.set_spectral_matching(True)
if contrast:
bias,contrast = contrast
img.set_colormap('inferno',bias=bias,contrast=contrast) #TODO: get actual colormap
def main():
args=parse_args()
kwargs=vars(args)
run_carta(**kwargs)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment