comparison omero_metadata_upload.py @ 0:1ae349b83c08 draft

planemo upload for repository https://github.com/Helmholtz-UFZ/galaxy-tools/tree/main/tools/omero commit 19d84fd5a372f1428e3e5670144881a56e8af8b2
author ufz
date Tue, 22 Oct 2024 11:52:46 +0000
parents
children 5513b999c56e
comparison
equal deleted inserted replaced
-1:000000000000 0:1ae349b83c08
1 import argparse
2 import json
3 from datetime import datetime
4
5 import ezomero as ez
6 import pandas as pd
7
8
9 def metadata_import_ezo(user, pws, host, port, obj_type, did=None, ann_type="table", ann_file=None, an_name=None,
10 log_file='metadata_import_log.txt'):
11 def upload_metadata(conn, obj_type, did, data_dict, df, ann_type, an_name):
12 try:
13 if ann_type == "KV":
14 id_map_ann = ez.post_map_annotation(conn, obj_type, object_id=int(did), kv_dict=data_dict, ns=an_name)
15 ma_dict = ez.get_map_annotation(conn, id_map_ann)
16 return ma_dict
17 elif ann_type == "table":
18 id_tb_ann = ez.post_table(conn, df, object_type=obj_type, object_id=int(did), title=an_name,
19 headers=True)
20 tb_dict = ez.get_table(conn, id_tb_ann)
21 return tb_dict
22 except Exception as e:
23 log_error(f"Error uploading metadata for {obj_type} with ID {did}: {str(e)}")
24 return None
25
26 def log_error(message):
27 with open(log_file, 'w') as f:
28 f.write(f"ERROR: {message}\n")
29
30 def log_success(message):
31 with open(log_file, 'w') as f:
32 f.write(f"SUCCESS: {message}\n")
33
34 try:
35 df = pd.read_csv(ann_file, delimiter='\t')
36 except FileNotFoundError as e:
37 log_error(f"Annotation file not found: {str(e)}")
38 return
39
40 if ann_type == "table":
41 data_dict = df.to_dict(orient='records')
42 elif ann_type == "KV":
43 data_dict = {col: df[col].iloc[0] for col in df.columns}
44
45 try:
46 with ez.connect(user, pws, "", host, port, secure=True) as conn:
47 if obj_type == "project":
48 if did is None:
49 did = ez.post_project(conn, project_name=str(datetime.now()))
50 result = upload_metadata(conn, "Project", did, data_dict, df, ann_type, an_name)
51 elif obj_type == "screen":
52 if did is None:
53 did = ez.post_screen(conn, screen_name=str(datetime.now()))
54 result = upload_metadata(conn, "Screen", did, data_dict, df, ann_type, an_name)
55 elif obj_type == "dataset":
56 if did is None:
57 did = ez.post_dataset(conn, dataset_name=str(datetime.now()))
58 result = upload_metadata(conn, "Dataset", did, data_dict, df, ann_type, an_name)
59 elif obj_type == "image":
60 result = upload_metadata(conn, "Image", did, data_dict, df, ann_type, an_name)
61 else:
62 raise ValueError("Unsupported object type provided: {}".format(obj_type))
63
64 if result is not None:
65 log_success(f"Successfully uploaded metadata for {obj_type} with ID {did}. Result: {result}")
66 else:
67 log_error(f"Failed to upload metadata for {obj_type} with ID {did}.")
68
69 conn.close()
70
71 except Exception as e:
72 log_error(f"Connection error: {str(e)}")
73
74
75 if __name__ == "__main__":
76 parser = argparse.ArgumentParser(description='Import metadata into OMERO.')
77 parser.add_argument("--credential-file", dest="credential_file", type=str, required=True, help="Credential file (JSON file with username and password for OMERO)")
78 parser.add_argument('--host', required=True, help='OMERO host')
79 parser.add_argument('--port', required=True, type=int, help='OMERO port')
80 parser.add_argument('--obj_type', required=True, choices=['project', 'screen', 'dataset', 'image'],
81 help='Type of OMERO object')
82 parser.add_argument('--did', type=int, help='ID of the object (if it exists)')
83 parser.add_argument('--ann_type', required=True, choices=['table', 'KV'], help='Annotation type')
84 parser.add_argument('--ann_file', required=True, help='Path to the annotation file')
85 parser.add_argument('--an_name', required=True, help='Namespace or title for the annotation')
86 parser.add_argument('--log_file', default='metadata_import_log.txt', help='Path to the log file')
87
88 args = parser.parse_args()
89
90 with open(args.credential_file, 'r') as f:
91 crds = json.load(f)
92
93 metadata_import_ezo(user=crds['username'], pws=crds['password'], host=args.host, port=args.port,
94 obj_type=args.obj_type, did=args.did, ann_type=args.ann_type,
95 ann_file=args.ann_file, an_name=args.an_name, log_file=args.log_file)