ingest.py 4.65 KB
Newer Older
Wei Shoulin's avatar
c3  
Wei Shoulin committed
1
2
3
4
5
6
7
8
import os, sys
import argparse
import logging
from astropy.io import fits
import datetime
import shutil

from csst_dfs_api_local.common.db import DBClient
Wei Shoulin's avatar
ifs ver    
Wei Shoulin committed
9
10
from csst_dfs_commons.utils.fits import get_header_value

Wei Shoulin's avatar
c3  
Wei Shoulin committed
11
12
13
log = logging.getLogger('csst-dfs-api-local')

def ingest():
Wei Shoulin's avatar
Wei Shoulin committed
14
    
Wei Shoulin's avatar
c3  
Wei Shoulin committed
15
16
    parser = argparse.ArgumentParser(prog=f"{sys.argv[0]}", description="ingest the local files")
    parser.add_argument('-i','--infile', dest="infile", help="a file or a directory")
Wei Shoulin's avatar
Wei Shoulin committed
17
    parser.add_argument('-m', '--copyfiles', dest="copyfiles", action='store_true', default=False, help="whether copy files after import")
Wei Shoulin's avatar
c3  
Wei Shoulin committed
18
19
20
    args = parser.parse_args(sys.argv[1:])
    
    import_root_dir = args.infile
Wei Shoulin's avatar
Wei Shoulin committed
21
22
23
    if import_root_dir is None or (not os.path.isfile(import_root_dir) and not os.path.isdir(import_root_dir)):
        parser.print_help()
        sys.exit(0)
Wei Shoulin's avatar
c3  
Wei Shoulin committed
24

Wei Shoulin's avatar
Wei Shoulin committed
25
    db = DBClient()
Wei Shoulin's avatar
c3  
Wei Shoulin committed
26
27
    if os.path.isfile(import_root_dir):
        log.info(f"prepare import {import_root_dir}")
Wei Shoulin's avatar
Wei Shoulin committed
28
        ingest_one(import_root_dir, db, args.copyfiles)
Wei Shoulin's avatar
c3  
Wei Shoulin committed
29
30
31
32
33
34
    if os.path.isdir(import_root_dir):
        for (path, _, file_names) in os.walk(import_root_dir):
            for filename in file_names:
                if filename.find(".fits") > 0:
                    file_full_path = os.path.join(path, filename)
                    log.info(f"prepare import {file_full_path}")
Wei Shoulin's avatar
Wei Shoulin committed
35
                    ingest_one(file_full_path, db, args.copyfiles)
Wei Shoulin's avatar
c3  
Wei Shoulin committed
36
37
38

    db.close()

Wei Shoulin's avatar
Wei Shoulin committed
39
def ingest_one(file_path, db, copyfiles):
Wei Shoulin's avatar
c3  
Wei Shoulin committed
40
41
42
    dest_root_dir = os.getenv("CSST_LOCAL_FILE_ROOT", "/opt/temp/csst")

    hdul = fits.open(file_path)
43
44
    fits_header = hdul[0].header
    img_header = hdul[1].header
Wei Shoulin's avatar
c3  
Wei Shoulin committed
45

46
47
48
    obs_id = fits_header["OBSID"]
    exp_start_time = f"{fits_header['DATE-OBS']} {fits_header['TIME-OBS']}"
    exp_time = fits_header['EXPTIME']
Wei Shoulin's avatar
c3  
Wei Shoulin committed
49
    
50
51
    module_id = fits_header["INSTRUME"]
    obs_type = fits_header["FILETYPE"]
Wei Shoulin's avatar
Wei Shoulin committed
52
53
    qc0_status = -1
    prc_status = -1
Wei Shoulin's avatar
c3  
Wei Shoulin committed
54
55
56
57
58
59
    time_now = datetime.datetime.now()
    create_time = time_now.strftime('%Y-%m-%d %H:%M:%S')

    facility_status_id = 0
    module_status_id = 0

Wei Shoulin's avatar
Wei Shoulin committed
60
    existed = db.exists("select * from t_observation where obs_id=?", (obs_id,))
Wei Shoulin's avatar
c3  
Wei Shoulin committed
61
62
    if not existed:
        db.execute("insert into t_observation \
Wei Shoulin's avatar
Wei Shoulin committed
63
            (obs_id,obs_time,exp_time,module_id,obs_type,facility_status_id, module_status_id, qc0_status, prc_status,create_time) \
Wei Shoulin's avatar
c3  
Wei Shoulin committed
64
65
            values (?,?,?,?,?,?,?,?,?,?)",
        (obs_id,exp_start_time,exp_time,module_id,obs_type,facility_status_id,module_status_id,qc0_status, prc_status,create_time))
Wei Shoulin's avatar
Wei Shoulin committed
66
        db.end()
Wei Shoulin's avatar
c3  
Wei Shoulin committed
67
    #level0
68
69
    detector = fits_header["DETECTOR"]
    filename = get_header_value("FILENAME", fits_header, os.path.basename(file_path))
Wei Shoulin's avatar
c3  
Wei Shoulin committed
70
71
    
    existed = db.exists(
Wei Shoulin's avatar
bugs    
Wei Shoulin committed
72
            "select * from msc_level0_data where filename=?",
Wei Shoulin's avatar
c3  
Wei Shoulin committed
73
74
75
76
77
78
79
80
81
82
83
84
            (filename,)
        )
    if existed:
        log.warning('%s has already been imported' %(file_path, ))
        db.end()
        return    

    detector_status_id = 0

    file_full_path = file_path

    if copyfiles:
85
        file_dir = f"{dest_root_dir}/{module_id}/{obs_type.upper()}/{fits_header['EXPSTART']}/{obs_id}/MS"
Wei Shoulin's avatar
c3  
Wei Shoulin committed
86
87
        if not os.path.exists(file_dir):
            os.makedirs(file_dir)
Wei Shoulin's avatar
Wei Shoulin committed
88
89
90
        file_full_path = f"{file_dir}/{filename}.fits"

    level0_id = f"{obs_id}{detector}"  
Wei Shoulin's avatar
c3  
Wei Shoulin committed
91

Wei Shoulin's avatar
Wei Shoulin committed
92
    c = db.execute("insert into msc_level0_data \
Wei Shoulin's avatar
Wei Shoulin committed
93
94
95
        (level0_id, obs_id, detector_no, obs_type, obs_time, exp_time,detector_status_id, filename, file_path,qc0_status, prc_status,create_time) \
        values (?,?,?,?,?,?,?,?,?,?,?,?)",
        (level0_id, obs_id, detector, obs_type, exp_start_time, exp_time, detector_status_id, filename, file_full_path, qc0_status, prc_status,create_time))
Wei Shoulin's avatar
c3  
Wei Shoulin committed
96
    db.end()
Wei Shoulin's avatar
Wei Shoulin committed
97
    level0_id_id = db.last_row_id()
Wei Shoulin's avatar
c3  
Wei Shoulin committed
98
    #level0-header
99
100
101
102
103
104
105
106
107
108
109
110
    ra_obj = fits_header["RA_OBJ"]
    dec_obj = fits_header["DEC_OBJ"]
    crpix1 = img_header["CRPIX1"]
    crpix2 = img_header["CRPIX2"]
    crval1 = img_header["CRVAL1"]
    crval1 = img_header["CRVAL2"]
    ctype1 = img_header["CTYPE1"]
    ctype2 = img_header["CTYPE2"]
    cd1_1 = img_header["CD1_1"]
    cd1_2 = img_header["CD1_2"]
    cd2_1 = img_header["CD2_1"]
    cd2_2 = img_header["CD2_2"]
Wei Shoulin's avatar
Wei Shoulin committed
111
112
    db.execute("delete from msc_level0_header where id=?",(level0_id_id,))    
    db.execute("insert into msc_level0_header \
113
114
115
116
        (id, ra_obj, dec_obj, crpix1, crpix2, crval1, crval1, \
        ctype1, ctype2, cd1_1, cd1_2, cd2_1, cd2_2, create_time) \
        values (?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
        (level0_id_id, ra_obj, dec_obj, crpix1, crpix2, crval1, crval1, ctype1, ctype2, cd1_1, cd1_2, cd2_1, cd2_2, create_time))
Wei Shoulin's avatar
c3  
Wei Shoulin committed
117
118
119
120
121
122
123
124
125
126
127
    
    if copyfiles:
        #copy files
        shutil.copyfile(file_path, file_full_path)

    db.end()

    print(f"{file_path} imported")

if __name__ == "__main__":
    ingest()