Commit 6a8855a6 authored by Manuel Luis Alcazar Laynez's avatar Manuel Luis Alcazar Laynez
Browse files

Merge branch 'clickable-image' into 9-get_images_sdss-update-the-csv-with-the-img-path

parents d35e5a90 70feffd3
Loading
Loading
Loading
Loading
+1 −1
Original line number Diff line number Diff line
MIT License

Copyright (c) 2024 <copyright holders>
Copyright (c) 2024, GALAssify contributors

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

+2 −1
Original line number Diff line number Diff line
@@ -52,7 +52,8 @@ dependencies = [
  'matplotlib>=3.7',
  'astropy>=5.3',
  'requests>=2.31',
  'Pillow>=9.5'
  'Pillow>=9.5',
  'PyConsoleMenu>=1.0'
]

[project.optional-dependencies]
+26 −3
Original line number Diff line number Diff line
@@ -5,6 +5,7 @@
#######################################################

import sys
import os
from PyQt5 import QtWidgets
from . import utils
from . import gui
@@ -13,12 +14,32 @@ VERSION = '0.1.4'

def main():
    args = utils.getOptions(VERSION)
    selectedFiles, selectedGroups = utils.getFiles()
    if not len(sys.argv) > 1:
        if utils.exist_basic_files():
            run_gui(args)
        else:    
            selec = utils.load_menu()
            if selec == 0:
                utils.init_flag()            
            elif selec == 10:
                utils.example_flag('basic')
            elif selec == 11:
                utils.example_flag('fits')
    else:
        if args.init:
            utils.init_flag()
        elif args.example != '':
            print(f"INFO:\t Create the {args.example} example files")
            utils.example_flag(args.example)
        else:
            run_gui(args)


def run_gui(args):
    selectedFiles, selectedGroups = utils.getFiles()
    if len(selectedFiles) > 0:
        if args.list:
            print(selectedFiles.filename)

        else:
            print(f"INFO:\t {str(len(selectedFiles))} galaxies found in selected group(s).")
            df = selectedFiles # utils.expand_df(selectedFiles)
@@ -26,7 +47,9 @@ def main():
            window = gui.Ui(df, selectedGroups)
            app.exec_()
    else:
        print('ERROR: No files found with the arguments given.')
        print('ERROR:\tNo files found with the arguments given.')
        print('HINT:\tDid you populate your .csv file?')


if __name__ == '__main__':
    sys.exit(main())
 No newline at end of file
+110 −6
Original line number Diff line number Diff line
import os
import re
import sys
import glob
import argparse
from pathlib import Path
import pandas as pd
import pkg_resources
from PyConsoleMenu import SelectorMenu


import warnings
from typing import Union
@@ -21,28 +24,37 @@ def getOptions(version):
    global VERSION

    parser = argparse.ArgumentParser(prog='GALAssify', description="GALAssify: Tool to manually classify galaxies.")

    parser.add_argument('--version', action='version', version='%(prog)s ' + version,
                        help="Prints software version and exit.\n")
    parser.add_argument('-p', '--path', type=dir_path, default='img',

    parser.add_argument('--init',action='store_true',help='Generate a basic config file, and the basic folder structure.')

    parser.add_argument('--example', type=example_type, default='', help='Run a galassify (basic or fits) example.')
    
    parser.add_argument('-p', '--path', type=dir_path, default='img/',
                        help="Path to image files.\n")
    
    parser.add_argument('-c', '--config', type=dir_file, default='config',
                        help="Config json file to load.\n")
    
    #parser.add_argument('-f', '--filename', nargs='+',
    #                    required=not('-p' in sys.argv
    #                    or '--path' in sys.argv
    #                    or '--version' in sys.argv), type=dir_file,
    #                    help="Image or list to classify. Not required if path or path + group are given.\n")

    parser.add_argument('-s', '--savefile',
                        #required=not('--version' in sys.argv),
                        default='output.csv',
                        help="CSV file to load and export changes. If does not exists, a new one is created.\n")
    parser.add_argument("-l", "--list", action="store_true",
                        help="List selected files only and exit.\n")
    parser.add_argument('-i', '--inputfile', default='galaxies.csv', type=dir_file,
    
    parser.add_argument('-i', '--inputfile', type=dir_file, default='files/galaxies.csv',
                        help="""Galaxy database file in *.csv format.
                        Minimum required columns: ['galaxy'].
                        Recomended columns: ['group', 'galaxy', 'ra', 'dec',  'filename' and/or 'fits']""")
    
    parser.add_argument('group', metavar='GROUP', nargs='*',
                        help="Group number. Selects images with name format: img_<group>_*.png\n")

@@ -50,6 +62,84 @@ def getOptions(version):
    VERSION = version
    return args

def exist_basic_files():
    files = ['files/','img/','config']
    test_files = True
    for file in files:
        if not Path(file).exists():
            test_files = False
    if not Path('files/galaxies.csv').exists:
        test_files = False
    return test_files

def load_menu():    
    
    global select_option
    select_option = 3

    options = ["INIT (--init):\t Generate a basic config file, and the basic folder structure.", 
                "EXAMPLE (--example):\t Generate a files whit a galassify example", 
                "EXIT"]
    menu = SelectorMenu(options, title='GALAssify: A tool to manually classify galaxies.')
    ans = menu.input()
    if ans.index==0:
        select_option = 0
        #return(0)
    elif ans.index==1:
        options_2 = ["BASIC (--example basic):\t Load the images example", 
                    "FITS (--example fits):\t Load the images fits example", 
                    "BACK"]
        menu_2 = SelectorMenu(options_2, title='GALAssify Example: Generate a files whit a galassify example')
        ans_2 = menu_2.input()
        if (ans_2.index==0):
            select_option = 10
            #return(10)
        elif (ans_2.index==1):
            select_option = 11
            #return(11)
        else:
            load_menu()
    return select_option

def init_flag():
    print(f"INFO:\t Generating the necessary files...")
    try:
        os.system(f"cp '{getPackageResource('config')}' config")
        os.system("mkdir -p files img/fits")
        os.system('echo "group,galaxy,ra,dec,filename,fits" >> files/galaxies.csv')
        print(f"INFO:\t The necessary files were created. \nINFO:\t Now, complete de input files and open GALAssify with: galassify -i files/galaxies.csv -s files/output.csv -p img/ ")
    except:
        pass

def example_flag(type_example):
    print(f"INFO:\t Generating the necessary files...")
    try:
        # Copy common files
        os.system(f"cp '{getPackageResource('config')}' config")
        os.system("mkdir -p files img")

        # Copy and create example-specific files
        if type_example == 'basic':
            os.system(f"cp '{getPackageResource('files/galaxies.csv')}' files/galaxies.csv")
            content = glob.glob(f"{getPackageResource('img/')}")
            content = [f for f in os.listdir(f"{getPackageResource('img/')}") if re.match(r'.*\.jpeg', f)]
            for element in content:
                elemet_dir = getPackageResource('img/'+element)
                os.system(f"cp '{elemet_dir}' img/{element}")

        else:
            os.system(f"cp '{getPackageResource('files/galaxies_fits.csv')}' files/galaxies.csv")
            os.system("mkdir -p img/fits")
            content=glob.glob(f"{getPackageResource('img/fits/')}")
            content = [f for f in os.listdir(f"{getPackageResource('img/fits/')}") if re.match(r'.*\.fits', f)]
            for element in content:
                elemet_dir = getPackageResource('img/fits/'+element)
                os.system(f"cp '{elemet_dir}' img/fits/{element}")

        print(f"INFO:\t The necessary files were created. \nINFO:\t Now, open GALAssify with: galassify -i files/galaxies.csv -s files/output.csv -p img/ ")
        print(f"INFO:\t If needed, you can download catalogue images by executing: get_images_sdss -i files/galaxies.csv -p img/ ")
    except Exception as e:
        print(f"ERROR: Error while creating the necessary files: {e}")

def getVersion():
    global VERSION
@@ -74,7 +164,8 @@ def getFiles():
    
    if imgpath:
        fname = args.inputfile
        if Path(fname).is_file():
        file = Path(fname)
        if file.is_file():
            groups = readInputFile(fname)
        else:
            groups = createInputFile(imgpath, fname)
@@ -116,16 +207,29 @@ def getFiles():
    #    files = []
    return selectedFiles, selectedGroups

def example_type(type_text):
    if type_text == 'basic':
        return(type_text)
    elif type_text == 'fits':
        return(type_text)
    elif type_text == '':
        return(type_text)
    else:
        raise argparse.ArgumentTypeError(f"readable_example_type: {type_text} is not a valid example type.")

def dir_path(path):
    d = Path(path)
    if not d.is_dir():
    if path == 'img/':
        return path
    elif not d.is_dir():
        raise argparse.ArgumentTypeError(f"readable_dir: {path} is not a valid path.")
    return path

def dir_file(file):
    d = Path(file)
    if not d.is_file():
    if file == 'config' or file == 'files/galaxies.csv':
        return file
    elif not d.is_file():
        raise argparse.ArgumentTypeError(f"readable_file: {file} is not a valid file.")
    return file