comparison omero_get_value.py @ 3:6ae415d8821c draft default tip

planemo upload for repository https://github.com/Helmholtz-UFZ/galaxy-tools/tree/main/tools/omero commit 233f0e70cb20a02ec8530dbcfd5c7e70eef74476
author ufz
date Mon, 26 Jan 2026 15:04:30 +0000
parents 86428b102388
children
comparison
equal deleted inserted replaced
2:ad8ca0f76aaf 3:6ae415d8821c
1 import argparse 1 import argparse
2 import csv 2 import csv
3 import json
4 import os 3 import os
5 import sys 4 import sys
5 from typing import Optional
6 6
7 import ezomero as ez 7 import ezomero as ez
8 import pandas as pd 8 import pandas as pd
9 from connect_omero import establish_connection
10
11 # Import environmental variables
12 usr = os.getenv("OMERO_USER")
13 psw = os.getenv("OMERO_PASSWORD")
14 uuid_key = os.getenv("UUID_SESSION_KEY")
9 15
10 16
11 def get_object_ezo(user, pws, host, port, obj_type, ids, out_dir): 17 def get_object_ezo(
18 host: str,
19 port: int,
20 obj_type: str,
21 ids: list,
22 out_dir: str,
23 uuid_key: Optional[str] = None,
24 ses_close: Optional[bool] = True
25 ) -> str | dict:
26
27 """
28 Fetch OMERO objects (Annotation, Table and Key-Value Pairs list) and save them as TSV based on object type.
29
30 Parameters
31 ----------
32 host : str
33 OMERO server host (i.e. OMERO address or domain name)"
34 port : int
35 OMERO server port (default:4064)
36 obj_type : str
37 Type of object to fetch ID: Project, Dataset, Image, Annotation, Tag, ROI, or Table.
38 ids : list
39 IDs of the OMERO objects.
40 out_dir : str
41 Output path of the file
42 uuid_key : str, optional
43 OMERO UUID session key to connect without password
44 ses_close : bool
45 Decide if close or not the section after executing the script. Defaulf value is true, useful when connecting with the UUID session key.
46 Returns
47 -------
48 csv.writer
49 A CSV writer object configured to write TSV data.
50 """
51
52 conn = establish_connection(uuid_key, usr, psw, host, port)
53
12 # Function to write tabular file from the ezomero output 54 # Function to write tabular file from the ezomero output
13 def write_values_to_tsv(data, header): 55 def write_values_to_tsv(data, header):
14 with open("output.tsv", 'w', newline='') as f: 56 with open("output.tsv", 'w', newline='') as f:
15 writer = csv.writer(f, delimiter='\t') 57 writer = csv.writer(f, delimiter='\t')
16 writer.writerow([header]) # Write the header 58 writer.writerow([header]) # Write the header
29 def write_table_to_tsv(data, id): 71 def write_table_to_tsv(data, id):
30 with open(f"./output/ID_{id}_table.tsv", 'w') as f: 72 with open(f"./output/ID_{id}_table.tsv", 'w') as f:
31 for row in data: 73 for row in data:
32 f.write('\t'.join([str(val) for val in row]) + '\n') 74 f.write('\t'.join([str(val) for val in row]) + '\n')
33 75
34 with ez.connect(user, pws, "", host, port, secure=True) as conn: 76 try:
77 # Fetch different object according to the user input
35 if obj_type == "Annotation": 78 if obj_type == "Annotation":
36 ma_dict = {} 79 ma_dict = {}
37 for maid in ids: 80 for maid in ids:
38 current_ma_dict = ez.get_map_annotation(conn, maid) 81 current_ma_dict = ez.get_map_annotation(conn, maid)
39 ma_dict = {**ma_dict, **current_ma_dict} 82 ma_dict = {**ma_dict, **current_ma_dict}
59 df.to_csv(f"./output/ID_{id}_{base_name}", sep='\t', index=False) 102 df.to_csv(f"./output/ID_{id}_{base_name}", sep='\t', index=False)
60 os.remove(attch_path) 103 os.remove(attch_path)
61 else: 104 else:
62 sys.exit(f"Unsupported object type: {filter}") 105 sys.exit(f"Unsupported object type: {filter}")
63 106
107 finally:
108 if ses_close:
109 conn.close()
64 110
65 # Argument parsing 111
66 if __name__ == "__main__": 112 if __name__ == "__main__":
67 parser = argparse.ArgumentParser(description="Fetch and save data as TSV based on object type.") 113 parser = argparse.ArgumentParser(description="Fetch and save data as TSV based on object type.")
68 parser.add_argument("--credential-file", dest="credential_file", type=str, 114 parser.add_argument('--host', required=True, help="OMERO server host (i.e. OMERO address or domain name)")
69 required=True, help="Credential file (JSON file with username and password for OMERO)") 115 parser.add_argument('--port', required=True, type=int, help="OMERO server port (default:4064)")
70 parser.add_argument('--host', required=True, 116 parser.add_argument('--obj_type', required=True, help="Type of object to fetch: Annotation, Table or Tag.")
71 help="Host server address.")
72 parser.add_argument('--port', required=True, type=int,
73 help='OMERO port')
74 parser.add_argument('--obj_type', required=True,
75 help="Type of object to fetch: Annotation, Table or Tag.")
76 group = parser.add_mutually_exclusive_group() 117 group = parser.add_mutually_exclusive_group()
77 group.add_argument('--ids', nargs='+', type=int, 118 group.add_argument('--ids', nargs='+', type=int, help="IDs of the OMERO objects.")
78 help="IDs of the OMERO objects.") 119 group.add_argument('--ids_path', help="File with IDs of the OMERO objects (one per line).")
79 group.add_argument('--ids_path', 120 parser.add_argument('--session_close', required=False, help='Namespace or title for the annotation')
80 help="File with IDs of the OMERO objects (one per line).") 121 parser.add_argument('--out_dir', required=True, help="Output path.")
81 parser.add_argument('--out_dir', required=True, 122
82 help="Output path.")
83 args = parser.parse_args() 123 args = parser.parse_args()
84 124
85 if args.ids_path: 125 if args.ids_path:
86 args.ids = [] 126 args.ids = []
87 with open(args.ids_path, 'r') as f: 127 with open(args.ids_path, 'r') as f:
91 except ValueError: 131 except ValueError:
92 print(f"{line.strip()} is not a valid ID.") 132 print(f"{line.strip()} is not a valid ID.")
93 if len(args.ids) == 0: 133 if len(args.ids) == 0:
94 raise ValueError("Cound not find a single ID in the file.") 134 raise ValueError("Cound not find a single ID in the file.")
95 135
96 with open(args.credential_file, 'r') as f:
97 crds = json.load(f)
98
99 # Call the main function to get the object and save it as a TSV 136 # Call the main function to get the object and save it as a TSV
100 get_object_ezo(user=crds['username'], pws=crds['password'], host=args.host, 137 get_object_ezo(host=args.host,
101 port=args.port, 138 port=args.port,
102 obj_type=args.obj_type, 139 obj_type=args.obj_type,
103 ids=args.ids, 140 ids=args.ids,
141 ses_close=args.session_close,
104 out_dir=args.out_dir) 142 out_dir=args.out_dir)