text:
from grid_functions import get_grid_index_for_ray_point, get_ray_index_for_grid_point
from math import exp
from scipy.integrate import simps
import numpy as np

def calc_Lambda_star(Lambda_star, n_depth_pts, n_mu_pts, rays, mu_grid):
    inorm_tmp = np.zeros([n_depth_pts, n_mu_pts])
    for l in range(1, n_depth_pts-1):
        inorm_tmp[:, :] = 0
        for j, each_ray in enumerate(rays):
            # get ray index corresponding to physical grid index l
            ray_idx_l   = get_ray_index_for_grid_point(each_ray, l, n_depth_pts)

            # get physical grid indices corresponding to i+1 and i-1 along the ray
            grid_idx_lim1 = get_grid_index_for_ray_point(each_ray, ray_idx_l-1, n_depth_pts)
            grid_idx_lip1 = get_grid_index_for_ray_point(each_ray, ray_idx_l+1, n_depth_pts)

            inorm_tmp[grid_idx_lim1, j] =  each_ray.gamma(ray_idx_l-1)
            inorm_tmp[l,             j] =  each_ray.gamma(ray_idx_l-1) * exp(-each_ray.Delta_tau(ray_idx_l-1)) + each_ray.beta(ray_idx_l)
            inorm_tmp[grid_idx_lip1, j] = (each_ray.gamma(ray_idx_l-1) * exp(-each_ray.Delta_tau(ray_idx_l-1)) + each_ray.beta(ray_idx_l)) * exp(-each_ray.Delta_tau(ray_idx_l)) + each_ray.alpha(ray_idx_l+1)

        # TODO: these +1/-1 offsets are hard-coded, works in 1-D plane parallel,
        # but won't work in more complex geometries
        Lambda_star[l-1, l] = 0.5 * simps(inorm_tmp[l-1, :], x=mu_grid)
        Lambda_star[l  , l] = 0.5 * simps(inorm_tmp[l ,  :], x=mu_grid)
        Lambda_star[l+1, l] = 0.5 * simps(inorm_tmp[l+1, :], x=mu_grid)

    # boundary cases.

    # surface
    l = 0
    inorm_tmp[:, :] = 0
    for j, each_ray in enumerate(rays):
        # at the surface, outgoing rays (those with mu > 0) only have i-1 and i components, no i+1
        if each_ray.mu > 0:
            ray_idx_l = get_ray_index_for_grid_point(each_ray, l, n_depth_pts)

            grid_idx_lim1 = get_grid_index_for_ray_point(each_ray, ray_idx_l-1, n_depth_pts)

            inorm_tmp[grid_idx_lim1, j] = each_ray.gamma(ray_idx_l-1)
            inorm_tmp[l,             j] = each_ray.gamma(ray_idx_l-1) * exp(-each_ray.Delta_tau(ray_idx_l-1)) + each_ray.beta(ray_idx_l)
        else:
            # at the surface we don't have an "i-1" term on incoming rays (those with mu < 0)
            # no illumination from the surface, so incoming rays at the surface have I(surface) = 0
            ray_idx_l = get_ray_index_for_grid_point(each_ray, l, n_depth_pts)

            grid_idx_lip1 = get_grid_index_for_ray_point(each_ray, ray_idx_l+1, n_depth_pts)

            inorm_tmp[l,             j] = 0
            inorm_tmp[grid_idx_lip1, j] = each_ray.alpha(ray_idx_l+1)

    Lambda_star[l,   l] = 0.5 * simps(inorm_tmp[l ,  :], x=mu_grid)
    Lambda_star[l+1, l] = 0.5 * simps(inorm_tmp[l+1, :], x=mu_grid)

    inorm_tmp[:, :] = 0

    # depth
    l = n_depth_pts-1
    for j, each_ray in enumerate(rays):
        # at depth, we don't have an "i-1" term on rays with mu > 0 because they start at depth
        if (each_ray.mu < 0):
            ray_idx_l    = get_ray_index_for_grid_point(each_ray, l, n_depth_pts)

            grid_idx_lim1 = get_grid_index_for_ray_point(each_ray, ray_idx_l-1, n_depth_pts)

            inorm_tmp[grid_idx_lim1, j] = each_ray.gamma(ray_idx_l-1)
            inorm_tmp[l,             j] = each_ray.gamma(ray_idx_l-1) * exp(-each_ray.Delta_tau(ray_idx_l-1)) + each_ray.beta(ray_idx_l)
        else:
            ray_idx_l    = get_ray_index_for_grid_point(each_ray, l, n_depth_pts)

            grid_idx_lip1 = get_grid_index_for_ray_point(each_ray, ray_idx_l+1, n_depth_pts)

            inorm_tmp[l,             j] = 0.0
            inorm_tmp[grid_idx_lip1, j] = each_ray.alpha(ray_idx_l+1)

    Lambda_star[l-1, l] = 0.5 * simps(inorm_tmp[l-1, :], x=mu_grid)
    Lambda_star[l  , l] = 0.5 * simps(inorm_tmp[l  , :], x=mu_grid)

    return(Lambda_star)

max_stars_repo_name: bcfriesen/PyRT

max_issues_repo_name: bcfriesen/PyRT

max_forks_repo_name: bcfriesen/PyRT

reason: import numpy,from scipy


text:
     #  Rotate, scale, and translate and crop to 128 sizes...
     #   Rotate is angle of rotation degrees
     #   Scale is the scale of the image in pixels between [w*cos(45 degrees),w]
     #   Translation is the X and Y translation of the image in pixels of the original image
import cv2
import numpy as np
from random import randrange, randint

def augmentImage(im, rot_angle = -1, scale = -1, tran = -1):
    h, w, c = im.shape
    min_size = 128; # smallest size in the original image for the output image
     # Rotate, Scale and Translate in the same affine rotation.
     #     So translate and crop between buffer of dim and the random scaling, rotate, and random scaling (all at once!)

    if rot_angle < 0:
        rot_angle = randrange(360)

     #print(rot_angle)
    mH, mW = calculateLargestProportionalRect(rot_angle, h,w)
    dim = np.floor(min(mH,mW))
    if scale < 0:
        scale = randrange(min_size,dim)
    elif scale == 0:
        scale = 181 # Max allowed if allowing for any rotation

     # Get rotation and scale matrix
    scale_ratio = 128.0/scale
    M = cv2.getRotationMatrix2D((h/2,w/2),rot_angle,scale_ratio)#randrange(360),1)

      # Find max difference and scale it down and make random

    if tran < 0:
        xshift = scale_ratio*(randint(-(dim-scale),dim-scale)/2.0)
        yshift = scale_ratio*(randint(-(dim-scale),dim-scale)/2.0)
    else:
        xshift = scale_ratio*tran
        yshift = scale_ratio*tran
     #(random.randrange(1,3)*2-3)#
     #xshift = (128.0/rand_scale)*((dim-rand_scale)/2.0)
     #yshift = (128.0/rand_scale)*((dim-rand_scale)/2.0)
    M[0,2] = M[0,2] - (h/2 - 64) - xshift # shift center and add random translation in x
    M[1,2] = M[1,2] - (w/2 - 64) - yshift # shift center and add random translation in y

     #print('Dim: {}\tScale: {}\tRot: {:03d}\txshift: {}\tyshift: {}'.format(dim,scale,rot_angle,xshift,yshift))

     # Apply Transformation in only valid area and use inter_area since downsampling (CV suggestion)
    return cv2.warpAffine(im,M,(128,128),flags=cv2.INTER_LINEAR,borderMode=cv2.BORDER_CONSTANT)

def calculateLargestProportionalRect(angle, origHeight,origWidth):
    angle = np.deg2rad(angle)
    if (origWidth <= origHeight):
        w0 = origWidth
        h0 = origHeight

    else:
        w0 = origHeight
        h0 = origWidth

     # Angle normalization in range [-PI..PI)
    ang = angle - np.floor((angle + np.pi) / (2*np.pi)) * 2*np.pi;
    ang = np.abs(ang);
    if (ang > np.pi / 2):
        ang = np.pi - ang;
    c = w0 / (h0 * np.sin(ang) + w0 * np.cos(ang));
    if (origWidth <= origHeight) :
        w = w0 * c
        h = h0 * c

    else:
        w = h0 * c
        h = w0 * c

    return h,w

ext: py

reason: import numpy


text:
import sys, os, logging
from resnet_heterofl import resnet18
import torch
import torch.nn.functional as F
import numpy as np
import copy
from collections import OrderedDict
sys.path.insert(1, os.path.join(sys.path[0], '../../'))
from argParser import args

def init_model():
    global tokenizer

    logging.info("Initializing the model ...")
    if args.model == 'resnet_heterofl':
        model = resnet18()

    return model

def make_param_idx(model, model_rate):
    """
    "HeteroFL: Computation and Communication Efficient Federated Learning for Heterogeneous Clients"
    Enmao Diao, Jie Ding, Vahid Tarokh,
    ICLR 2021
    """
    param_idxi = None
    param_idx = OrderedDict()
    for k, v in model.state_dict().items():
        parameter_type = k.split('.')[-1]
        if 'weight' in parameter_type or 'bias' in parameter_type:
            if parameter_type == 'weight':
                if v.dim() > 1:
                    input_size = v.size(1)
                    output_size = v.size(0)
                    if 'conv1' in k or 'conv2' in k:
                        if param_idxi is None:
                            param_idxi = torch.arange(input_size, device=v.device)
                        input_idx_i = param_idxi
                        scaler_rate = model_rate
                        local_output_size = int(np.ceil(output_size * scaler_rate))
                        output_idx_i = torch.arange(output_size, device=v.device)[:local_output_size]
                        param_idxi = output_idx_i
                    elif 'shortcut' in k:
                        input_idx_i = param_idx[k.replace('shortcut', 'conv1')][1]
                        output_idx_i = param_idxi
                    elif 'linear' in k:
                        input_idx_i = param_idxi
                        output_idx_i = torch.arange(output_size, device=v.device)
                    else:
                        raise ValueError('Not valid k')
                    param_idx[k] = (output_idx_i, input_idx_i)
                else:
                    input_idx_i = param_idxi
                    param_idx[k] = input_idx_i
            else:
                input_size = v.size(0)
                if 'linear' in k:
                    input_idx_i = torch.arange(input_size, device=v.device)
                    param_idx[k] = input_idx_i
                else:
                    input_idx_i = param_idxi
                    param_idx[k] = input_idx_i
        else:
            pass
    return param_idx

def split_model(global_model, model_rate):
    """
    "HeteroFL: Computation and Communication Efficient Federated Learning for Heterogeneous Clients"
    Enmao Diao, Jie Ding, Vahid Tarokh,
    ICLR 2021
    """
    param_idx = make_param_idx(global_model, model_rate)
    local_parameters = OrderedDict()
    # split global model into a sub local model
    for k, v in global_model.state_dict().items():
        parameter_type = k.split('.')[-1]
        if 'weight' in parameter_type or 'bias' in parameter_type:
            if 'weight' in parameter_type:
                if v.dim() > 1:
                    local_parameters[k] = copy.deepcopy(v[torch.meshgrid(param_idx[k])])
                else:
                    local_parameters[k] = copy.deepcopy(v[param_idx[k]])
            else:
                local_parameters[k] = copy.deepcopy(v[param_idx[k]])
        else:
            local_parameters[k] = copy.deepcopy(v)
    return local_parameters

max_stars_repo_name: NCLPhD/FedScale

max_issues_repo_name: NCLPhD/FedScale

max_forks_repo_name: NCLPhD/FedScale


text:
import streamlit as st
import fastai
from fastai.vision import *
from fastai.utils.mem import *
from fastai.vision import open_image, load_learner, image, torch
import numpy as np4
import urllib.request
import PIL.Image
from io import BytesIO
import torchvision.transforms as T
from PIL import Image
import requests
from io import BytesIO
import fastai
from fastai.vision import *
from fastai.utils.mem import *
from fastai.vision import open_image, load_learner, image, torch
import numpy as np
import urllib.request
from urllib.request import urlretrieve
import PIL.Image
from io import BytesIO
import torchvision.transforms as T
import torchvision.transforms as tfms

class FeatureLoss(nn.Module):
    def __init__(self, m_feat, layer_ids, layer_wgts):
        super().__init__()
        self.m_feat = m_feat
        self.loss_features = [self.m_feat[i] for i in layer_ids]
        self.hooks = hook_outputs(self.loss_features, detach=False)
        self.wgts = layer_wgts
        self.metric_names = ['pixel',] + [f'feat_{i}' for i in range(len(layer_ids))
              ] + [f'gram_{i}' for i in range(len(layer_ids))]

    def make_features(self, x, clone=False):
        self.m_feat(x)
        return [(o.clone() if clone else o) for o in self.hooks.stored]

    def forward(self, input, target):
        out_feat = self.make_features(target, clone=True)
        in_feat = self.make_features(input)
        self.feat_losses = [base_loss(input,target)]
        self.feat_losses += [base_loss(f_in, f_out)*w
                             for f_in, f_out, w in zip(in_feat, out_feat, self.wgts)]
        self.feat_losses += [base_loss(gram_matrix(f_in), gram_matrix(f_out))*w**2 * 5e3
                             for f_in, f_out, w in zip(in_feat, out_feat, self.wgts)]
        self.metrics = dict(zip(self.metric_names, self.feat_losses))
        return sum(self.feat_losses)

    def __del__(self): self.hooks.remove()

st.set_page_config(layout="wide")
#st.image(os.path.join('Images','2.jpg'), use_column_width  = True)
st.markdown("
Get deinked!!
", unsafe_allow_html=True)
Image = st.file_uploader('Upload your picture here',type=['jpg','jpeg','png'])
if Image is not None:
  col1, col2 = st.beta_columns(2)
  img = PIL.Image.open(Image).convert("RGB")
  #Image = Image.read()
  #Image = tf.image.decode_image(Image, channels=3).numpy()
  #Image = adjust_gamma(Image, gamma=gamma)
  Image1 = np.array(img)
  with col1:
        st.image(Image1,width = 400, use_column_width=400)
  #imageLocation = st.empty()
  #imageLocation.image(img, width = 400)
  MODEL_URL = "https://www.dropbox.com/s/vxgw0s7ktpla4dk/SkinDeep2.pkl?dl=1"
  urlretrieve(MODEL_URL, "SkinDeep2.pkl")
  path = Path(".")
  learn=load_learner(path, 'SkinDeep2.pkl')
  im1 = img.save("test.jpg")
  img_fast = open_image("test.jpg")
  #img_t = T.ToTensor()(img)
  #img_fast = Image(img_t)
  _, img_hr, _ = learn.predict(img_fast)
  img_np=image2np(img_hr)
  with col2:
    st.image(img_np, width=400,clamp=True)

max_stars_repo_name: Tiamat-Tech/SkinDeep

max_issues_repo_name: Tiamat-Tech/SkinDeep

max_forks_repo_name: Tiamat-Tech/SkinDeep


text:
import shutil
import os,sys
import json,json5
import argparse
import traceback
import numpy as np
from pprint import pprint
from datetime import datetime
from docker.tool import yellow

def base_args():
    parser = argparse.ArgumentParser(description='PyTorch Training')
    parser.add_argument("cfg_file", help="config file", type=str)
    parser.add_argument('-epoch', nargs='?', type=str, default=None,
                        help="Start epoch, Default -1 (Train: Begin a new training; Test: Test at the last epoch)")
    parser.add_argument('-time', nargs='?', type=str, default=None,
                        help="Timestap of the checkpoint you want to load (Train: Load and continue to train; Test: Test at here)")
    parser.add_argument('-remark', nargs='?', type=str, default=None,
                        help="Input the remark you want to write at the name of experiment floder")
    parser.add_argument('-no_opt', action='store_true',
                        help='If you do not want to load the weight of optimizer or etc. choose it.')
    # parser.add_argument('-target_code', action='store_true',
    #                     help='use history code')
    return parser

class Configuration(object):
    def __init__(self,parser, mode):
        super(Configuration,self).__init__()
        self.mode = mode
        args, extras = parser.parse_known_args()
        self.visual = args.visual if 'visual' in args else False
        self.save = args.save if 'save' in args else False
        self.with_tqdm = not args.no_tqdm if 'no_tqdm' in args else True

        with open('RootPath.json') as f:
            self.root = json5.load(f)
        if mode == 'train' and args.epoch is None:
            load_path, result_dir = None, None
        else:
            load_path, result_dir = self.__ensure_load_path(args)
        # if args.target_code:
        #     base = sys.path.pop(0)
        #     sys.path.append(os.path.join(result_dir,'code'))

        cfg_path = './config/{}.jsonc'.format(args.cfg_file)
        assert os.path.exists(cfg_path), 'Config file not exist!'
        with open(cfg_path) as f:
            dic = json5.load(f)
        if args.remark is not None:
            dic['system']['remark'] = args.remark.replace('\r','').replace('\n','')
        dic = self.__cfgChange(dic,extras)
        if mode == 'train':
            timestamp = datetime.now().strftime('%m%d_%H%M')
            if len(dic['system']['remark'])>0: timestamp += '_'+dic['system']['remark']
            result_dir = os.path.join(self.root[r'%RESULT%'], args.cfg_file, timestamp)
            self.__copy(args.cfg_file,dic,result_dir)

        self.system = dic['system']
        self.system['result_dir'] = result_dir
        self.system['load_path'] = load_path

        self.optimizer = dic['optimizer']
        self.optimizer['no_opt'] = args.no_opt

        self.dataset = dic['dataset']
        for key,val in dic['dataset'].items():
            if key in ('train','test'): continue
            self.dataset['train'][key] = val
            self.dataset['test'][key] = val

        for key in ('train', 'test'):
            if self.dataset[key]['direction'][0] == '%DATA%':
                self.dataset[key]['direction'][0] = self.root['%DATA%']
            self.dataset[key]['direction'] = os.path.join(*self.dataset[key]['direction'])

    def __cfgChange(self,dic,extras):
        extraParser = argparse.ArgumentParser()
        for arg in extras:
            if arg.startswith(("-", "--")):
                extraParser.add_argument(arg)
        chgDic = vars(extraParser.parse_args(extras))
        for arg_chain,val in chgDic.items():
            arg_list = arg_chain.split('.')
            change_flag = False
            for CLS in ('system','optimizer','dataset'):
                change_parent = dic[CLS]
                for arg in arg_list[:-1]:
                    if arg not in change_parent: break
                    change_parent = change_parent[arg]
                else:
                    try: tmp = eval(val)
                    except:
                        tmp = val
                        if val.lower() in ['null','none']: tmp = None
                        elif val.lower() == 'true': tmp = True
                        elif val.lower() == 'false': tmp = False
                    if arg_list[-1] in change_parent:
                        change_parent[arg_list[-1]] = tmp
                        change_flag = True
            if not change_flag:
                print(yellow("Input q/Q to exist, any key to continue."))
                sys.stdout.flush()
                ins = input('#### {} do not exist, please check again ####'.format(yellow(CLS+'.'+arg_chain)))
                assert ins!='q' and ins!='Q'

        pprint(dic)
        return dic

    def __copy(self, cfg_name, cfg, result_dir):
        try:
            code_dir = os.path.join(result_dir,'code')
            os.makedirs(os.path.join(result_dir,'ckp'))
            os.makedirs(os.path.join(result_dir,'save'))
            os.makedirs(code_dir)

            tar_config_path = os.path.join(code_dir,'config')
            tar_model_path  = os.path.join(code_dir,'model')
            tar_data_path = os.path.join(code_dir,'dataset')
            os.makedirs(tar_config_path)
            os.makedirs(tar_model_path)
            os.makedirs(tar_data_path)

            with open(os.path.join(tar_config_path,cfg_name+'.jsonc'),'w') as f:
                json.dump(cfg,f)
            shutil.copy('RootPath.json',code_dir)
            shutil.copy('train.py',code_dir)
            shutil.copy('test.py',code_dir)
            shutil.copy(os.path.join('model',cfg['system']['net'][0]+'.py'),tar_model_path)
            shutil.copy(os.path.join('dataset',cfg['dataset']['file_name']+'.py'),tar_data_path)
            shutil.copytree('docker',os.path.join(code_dir,'docker'))
        except:
            key = input(yellow('\nDo you want to reserve this train(Default No)? y/n: '))
            if key == 'n' and os.path.exists(result_dir):
                shutil.rmtree(result_dir)
            traceback.print_exc()
            sys.stdout.flush()

    def __ensure_load_path(self, args):
        direct = os.path.join(self.root[r'%RESULT%'], args.cfg_file)
        assert os.path.exists(direct), 'Net {} not exist'.format(args.cfg_file)

        target_timestap_list = os.listdir(direct)
        target_timestap = args.time
        if target_timestap is None:
            target_timestap_list.sort(key=lambda date: date[:9])
            target_timestap = target_timestap_list[-1]
        else:
            for item in target_timestap_list:
                if args.time == item[:len(args.time)]:
                    target_timestap = item
                    break
        direct = os.path.join(direct,target_timestap,'ckp')
        assert os.path.exists(direct), 'Timestamp {} not exist'.format(target_timestap)

        if args.epoch is None:
            epoches = os.listdir(direct)
            if 'best' in epoches:
                args.epoch = 'best'
            else:
                assert len(epoches) != 0, 'Epoch not exist'
                epoches = np.array(epoches, dtype=int)
                args.epoch = str(epoches.max())
        direct = os.path.join(direct, args.epoch)
        assert os.path.exists(direct), 'Epoch {} not exist'.format(args.epoch)

        return direct, os.path.join(self.root[r'%RESULT%'], args.cfg_file, target_timestap)

if __name__ == "__main__":
    args = base_args()
    cfg = Configuration(args,'train')


text:
from app.service.filterService import FilterService
from app.service.fourierService import FourierService
import numpy as np
import uuid
from PIL import Image
import base64
from io import BytesIO

def readb64(uri):
   encoded_data = uri.split(',')[1]
   nparr = np.fromstring(base64.b64decode(encoded_data), np.uint8)
   buf = BytesIO(nparr)
   img = Image.open(buf)
   return img

class ImageObject:
    key = None
    label = None
    image = None

    def __init__(self, label, image):
        self.key = uuid.uuid4()
        self.label = label
        self.image = Image.fromarray(image)

class ImageProcess:
    image = None
    gray_image = None
    mask_filter = None
    scale_value = None
    image_shape = (1, 1)
    filterService = FilterService()
    fourierService = FourierService()
    def __init__(self, image, scale_value=30):

        self.scale_value = int(image.size[0]/3)
        self.image = np.asarray(image.convert('RGB'))
        self.gray_image = np.array(image.convert("L"))
        self.image_shape = self.gray_image.shape
        # import filter service
        self.mask_filter = self.filterService.idealHP(
            scale_value, self.image_shape)

    # setup filter
    def set_filter(self, mask_type="IDEAL", filter_type="HIGH", scale_out=30, scale_in=20, n=20):
        if mask_type == "IDEAL":
            if filter_type == "HIGH":
                self.mask_filter = self.filterService.idealHP(
                    scale_out, self.image_shape)
            elif filter_type == "LOW":
                self.mask_filter = self.filterService.idealLP(
                    scale_out, self.image_shape)
            elif filter_type == "BAND":
                self.mask_filter = self.filterService.idealBP(
                    scale_in, scale_out, self.image_shape)
        elif mask_type == "BUTTERWORTH":
            if filter_type == "HIGH":
                self.mask_filter = self.filterService.butterworthHP(
                    scale_out, self.image_shape, n)
            elif filter_type == "LOW":
                self.mask_filter = self.filterService.butterworthLP(
                    scale_out, self.image_shape, n)
        elif mask_type == "GAUSSIAN":
            if filter_type == "HIGH":
                self.mask_filter = self.filterService.gaussianHP(
                    scale_out, self.image_shape)
            elif filter_type == "LOW":
                self.mask_filter = self.filterService.gaussianLP(
                    scale_out, self.image_shape)

    def bit_8_image_edge(self):
        # convert image to gray image
        converted_image_gray = self.fourierService.convertImageColor(
            self.image)
        saved_image_gray = ImageObject("Gray image", self.convertToRGB(converted_image_gray,"GRAY"))

        # make fourier spectrum
        gray_spectrum = self.fourierService.ImageToFFT(converted_image_gray)
        saved_spectrum = ImageObject(
            "Fourier spectrum", self.convertToRGB(self.fourierService.toImage(gray_spectrum),"GRAY"))

        # make convert fourier spectrum out to center
        center_gray_spectrum = self.fourierService.centerSpectrum(
            gray_spectrum)
        saved_center_spectrum = ImageObject(
            "Fourier center spectrum", self.convertToRGB(self.fourierService.toImage(center_gray_spectrum),"GRAY"))
        # multiple center fourier spectrum  with filter : y(x,y) = f(x,y)*h(x,y) => h is filter
        filtered_spectrum = center_gray_spectrum * self.mask_filter
        filtered_spectrum_image = ImageObject(
            "Fourier spectrum with mask", self.convertToRGB(self.fourierService.toImage(filtered_spectrum),"GRAY"))

        # convert filter image => inverse center filtered spectrum to outer filtered spectrum and use log to cover value to real image
        filtered_image = self.fourierService.fftToImage(
            self.fourierService.inverseSpectrum(filtered_spectrum))
        converted_image = ImageObject(
            "Filtered Image", self.convertToRGB(self.fourierService.toImage(filtered_image),"GRAY"))

        # # concatenate image to create image and save
        # concatenate_image = self.fourierService.toImage(np.dstack((filtered_image, filtered_image, filtered_image)))
        # final_image = ImageObject(
        #     "Final image", self.convertToRGB(concatenate_image,"RGB"))

            # result
        returnObject = [
                        [saved_image_gray],
                        [saved_spectrum],
                        [saved_center_spectrum],
                        [filtered_spectrum_image],
                        [converted_image]
                    ]
        return returnObject

    def bit_24_image_edge(self):

        #convert section
        # convert image to red image to filter channel red
        converted_image_red = self.fourierService.convertImageColor(
            self.image, "RED")
        saved_image_red = ImageObject(
            "Red image", self.convertToRGB(converted_image_red, "RED"))
        # convert image to green image to filter channel green
        converted_image_green = self.fourierService.convertImageColor(
            self.image, "GREEN")
        saved_image_green = ImageObject(
            "Green image", self.convertToRGB(converted_image_green, "GREEN"))
        # convert image to blue image to filter channel blue
        converted_image_blue = self.fourierService.convertImageColor(
            self.image, "BLUE")
        saved_image_blue = ImageObject(
            "Blue image", self.convertToRGB(converted_image_blue, "BLUE"))
        #end convert section

        #convert to fourier spectrum
        red_spectrum = self.fourierService.ImageToFFT(converted_image_red)
        saved_red_spectrum = ImageObject(
            "Fourier red spectrum", self.convertToRGB(self.fourierService.toImage(red_spectrum), "RED"))

        green_spectrum = self.fourierService.ImageToFFT(converted_image_green)
        saved_green_spectrum = ImageObject(
            "Fourier green spectrum", self.convertToRGB(self.fourierService.toImage(green_spectrum), "GREEN"))

        blue_spectrum = self.fourierService.ImageToFFT(converted_image_blue)
        saved_blue_spectrum = ImageObject(
            "Fourier blue spectrum", self.convertToRGB(self.fourierService.toImage(blue_spectrum), "BLUE"))
        #end convert to fourier spectrum

        #convert to center fourier spectrum
        center_red_spectrum = self.fourierService.centerSpectrum(red_spectrum)
        saved_center_red_spectrum = ImageObject("Fourier centered red spectrum",
                                                self.convertToRGB(self.fourierService.toImage(center_red_spectrum), "RED"))
        center_green_spectrum = self.fourierService.centerSpectrum(
            green_spectrum)
        saved_center_green_spectrum = ImageObject("Fourier centered green spectrum",
                                                  self.convertToRGB(self.fourierService.toImage(center_green_spectrum), "GREEN"))

        center_blue_spectrum = self.fourierService.centerSpectrum(
            blue_spectrum)
        saved_center_blue_spectrum = ImageObject("Fourier centered blue spectrum",
                                                 self.convertToRGB(self.fourierService.toImage(center_blue_spectrum), "BLUE"))
        #end convert to center fourier spectrum

        # multiple center fourier spectrum  with filter : y(x,y) = f(x,y)*h(x,y) => h is filter
        mask_red = center_red_spectrum * self.mask_filter
        masked_red_spectrum = ImageObject("Masked red spectrum",
                                          self.convertToRGB(self.fourierService.toImage(mask_red), "RED"))

        mask_green = center_green_spectrum * self.mask_filter
        masked_green_spectrum = ImageObject("Masked green spectrum",
                                            self.convertToRGB(self.fourierService.toImage(mask_green), "GREEN"))

        mask_blue = center_blue_spectrum * self.mask_filter
        masked_blue_spectrum = ImageObject("Masked blue spectrum",
                                           self.convertToRGB(self.fourierService.toImage(mask_blue), "BLUE"))
        # end multiple

        # convert to image when filtered per channel
        red_image = self.fourierService.fftToImage(
            self.fourierService.inverseSpectrum(mask_red))
        filtered_red_image = ImageObject("Filtered Red Image",
                                         self.convertToRGB(self.fourierService.toImage(red_image), "RED"))

        green_image = self.fourierService.fftToImage(
            self.fourierService.inverseSpectrum(mask_green))
        filtered_green_image = ImageObject("Filtered Green Image",
                                           self.convertToRGB(self.fourierService.toImage(green_image), "GREEN"))

        blue_image = self.fourierService.fftToImage(
            self.fourierService.inverseSpectrum(mask_blue))
        filtered_blue_image = ImageObject("Filtered Blue Image",
                                          self.convertToRGB(self.fourierService.toImage(blue_image), "BLUE"))
        #end convert to image when filtered per channel

        # concatenate and map color image with each channel
        concatenate_image = np.dstack((red_image, green_image, blue_image))
        concatenate_image = self.fourierService.toImage(concatenate_image)

        saved_image = ImageObject(
            "Final image", self.convertToRGB(concatenate_image, "RGB"))

        # result
        returnObject = [
            [saved_image_red, saved_image_green, saved_image_blue],
            [saved_red_spectrum, saved_green_spectrum, saved_blue_spectrum],
            [saved_center_red_spectrum, saved_center_green_spectrum,
                saved_center_blue_spectrum],
            [masked_red_spectrum, masked_green_spectrum, masked_blue_spectrum],
            [filtered_red_image, filtered_green_image, filtered_blue_image],
            [saved_image]
        ]
        return returnObject

    def convertToRGB(self, array, type_convert):
        tempImage = np.zeros(self.image.shape, "uint8")
        divide_factor = (int(256 / (np.amax(array) + 1))) # divide_factor is number to convert [0..1] or [0..10] to [0..256] color code

        if type_convert == "RED":
            tempImage[:, :, 0] = (array*divide_factor).astype(int)
        elif type_convert == "GREEN":
            tempImage[:, :, 1] = (array*divide_factor).astype(int)
        elif type_convert == "BLUE":
            tempImage[:, :, 2] = (array*divide_factor).astype(int)
        elif type_convert == "GRAY":
            tempImage = np.zeros(self.gray_image.shape, "uint8")
            putArr = (array*divide_factor).astype(int)
            tempImage[:,:] = putArr
        elif type_convert == "RGB":
            array = (array * 255).astype(np.uint8)
            if len(array.shape) == len(self.image.shape):
                tempImage = array
        return tempImage

class MainService:
    def bit_8_image(self,filter_image,filter_mask_type="IDEAL",filter_mask_filter_type="HIGH",filter_scale_out=100,filter_scale_in=50,n = 20):
        image = readb64(filter_image)
        imageprocess = ImageProcess(image)
        imageprocess.set_filter(mask_type=filter_mask_type,filter_type=filter_mask_filter_type, scale_out=filter_scale_out,scale_in=filter_scale_in)
        listReturn = imageprocess.bit_8_image_edge()
        return listReturn
    def bit_24_image(self,filter_image,filter_mask_type="IDEAL",filter_mask_filter_type="HIGH",filter_scale_out=100,filter_scale_in=50,n = 20):
        image = readb64(filter_image)
        imageprocess = ImageProcess(image)
        imageprocess.set_filter(mask_type=filter_mask_type,filter_type=filter_mask_filter_type, scale_out=filter_scale_out,scale_in=filter_scale_in)
        listReturn = imageprocess.bit_24_image_edge()
        return listReturn


text:
# Licensed under a 3-clause BSD style license - see PYFITS.rst

import re
import warnings

import numpy as np

from .util import _str_to_num, _is_int, translate, _words_group
from .verify import _Verify, _ErrList, VerifyError, VerifyWarning

from . import conf
from astropy.utils.exceptions import AstropyUserWarning

__all__ = ['Card', 'Undefined']

FIX_FP_TABLE = str.maketrans('de', 'DE')
FIX_FP_TABLE2 = str.maketrans('dD', 'eE')

CARD_LENGTH = 80
BLANK_CARD = ' ' * CARD_LENGTH
KEYWORD_LENGTH = 8  # The max length for FITS-standard keywords

VALUE_INDICATOR = '= '  # The standard FITS value indicator
VALUE_INDICATOR_LEN = len(VALUE_INDICATOR)
HIERARCH_VALUE_INDICATOR = '='  # HIERARCH cards may use a shortened indicator

class Undefined:
    """Undefined value."""

    def __init__(self):
        # This __init__ is required to be here for Sphinx documentation
        pass

UNDEFINED = Undefined()

class Card(_Verify):

    length = CARD_LENGTH
    """The length of a Card image; should always be 80 for valid FITS files."""

    # String for a FITS standard compliant (FSC) keyword.
    _keywd_FSC_RE = re.compile(r'^[A-Z0-9_-]{0,%d}$' % KEYWORD_LENGTH)
    # This will match any printable ASCII character excluding '='
    _keywd_hierarch_RE = re.compile(r'^(?:HIERARCH +)?(?:^[ -<>-~]+ ?)+$',
                                    re.I)

    # A number sub-string, either an integer or a float in fixed or
    # scientific notation.  One for FSC and one for non-FSC (NFSC) format:
    # NFSC allows lower case of DE for exponent, allows space between sign,
    # digits, exponent sign, and exponents
    _digits_FSC = r'(\.\d+|\d+(\.\d*)?)([DE][+-]?\d+)?'
    _digits_NFSC = r'(\.\d+|\d+(\.\d*)?) *([deDE] *[+-]? *\d+)?'
    _numr_FSC = r'[+-]?' + _digits_FSC
    _numr_NFSC = r'[+-]? *' + _digits_NFSC

    # This regex helps delete leading zeros from numbers, otherwise
    # Python might evaluate them as octal values (this is not-greedy, however,
    # so it may not strip leading zeros from a float, which is fine)
    _number_FSC_RE = re.compile(rf'(?P<sign>[+-])?0*?(?P<digt>{_digits_FSC})')
    _number_NFSC_RE = \
            re.compile(rf'(?P<sign>[+-])? *0*?(?P<digt>{_digits_NFSC})')

    # Used in cards using the CONTINUE convention which expect a string
    # followed by an optional comment
    _strg = r'\'(?P<strg>([ -~]+?|\'\'|) *?)\'(?=$|/| )'
    _comm_field = r'(?P<comm_field>(?P<sepr>/ *)(?P<comm>(.|\n)*))'
    _strg_comment_RE = re.compile(f'({_strg})? *{_comm_field}?')

    # FSC commentary card string which must contain printable ASCII characters.
    # Note: \Z matches the end of the string without allowing newlines
    _ascii_text_re = re.compile(r'[ -~]*\Z')

    # Checks for a valid value/comment string.  It returns a match object
    # for a valid value/comment string.
    # The valu group will return a match if a FITS string, boolean,
    # number, or complex value is found, otherwise it will return
    # None, meaning the keyword is undefined.  The comment field will
    # return a match if the comment separator is found, though the
    # comment maybe an empty string.
    _value_FSC_RE = re.compile(
        r'(?P<valu_field> *'
            r'(?P<valu>'

                #  The <strg> regex is not correct for all cases, but
                #  it comes pretty darn close.  It appears to find the
                #  end of a string rather well, but will accept
                #  strings with an odd number of single quotes,
                #  instead of issuing an error.  The FITS standard
                #  appears vague on this issue and only states that a
                #  string should not end with two single quotes,
                #  whereas it should not end with an even number of
                #  quotes to be precise.
                #
                #  Note that a non-greedy match is done for a string,
                #  since a greedy match will find a single-quote after
                #  the comment separator resulting in an incorrect
                #  match.
                rf'{_strg}|'
                r'(?P<bool>[FT])|'
                r'(?P<numr>' + _numr_FSC + r')|'
                r'(?P<cplx>\( *'
                    r'(?P<real>' + _numr_FSC + r') *, *'
                    r'(?P<imag>' + _numr_FSC + r') *\))'
            r')? *)'
        r'(?P<comm_field>'
            r'(?P<sepr>/ *)'
            r'(?P<comm>[!-~][ -~]*)?'
        r')?$')

    _value_NFSC_RE = re.compile(
        r'(?P<valu_field> *'
            r'(?P<valu>'
                rf'{_strg}|'
                r'(?P<bool>[FT])|'
                r'(?P<numr>' + _numr_NFSC + r')|'
                r'(?P<cplx>\( *'
                    r'(?P<real>' + _numr_NFSC + r') *, *'
                    r'(?P<imag>' + _numr_NFSC + r') *\))'
            fr')? *){_comm_field}?$')

    _rvkc_identifier = r'[a-zA-Z_]\w*'
    _rvkc_field = _rvkc_identifier + r'(\.\d+)?'
    _rvkc_field_specifier_s = fr'{_rvkc_field}(\.{_rvkc_field})*'
    _rvkc_field_specifier_val = (r'(?P<keyword>{}): +(?P<val>{})'.format(
            _rvkc_field_specifier_s, _numr_FSC))
    _rvkc_keyword_val = fr'\'(?P<rawval>{_rvkc_field_specifier_val})\''
    _rvkc_keyword_val_comm = (r' *{} *(/ *(?P<comm>[ -~]*))?$'.format(
            _rvkc_keyword_val))

    _rvkc_field_specifier_val_RE = re.compile(_rvkc_field_specifier_val + '$')

    # regular expression to extract the key and the field specifier from a
    # string that is being used to index into a card list that contains
    # record value keyword cards (ex. 'DP1.AXIS.1')
    _rvkc_keyword_name_RE = (
        re.compile(r'(?P<keyword>{})\.(?P<field_specifier>{})$'.format(
                _rvkc_identifier, _rvkc_field_specifier_s)))

    # regular expression to extract the field specifier and value and comment
    # from the string value of a record value keyword card
    # (ex "'AXIS.1: 1' / a comment")
    _rvkc_keyword_val_comm_RE = re.compile(_rvkc_keyword_val_comm)

    _commentary_keywords = {'', 'COMMENT', 'HISTORY', 'END'}
    _special_keywords = _commentary_keywords.union(['CONTINUE'])

    # The default value indicator; may be changed if required by a convention
    # (namely HIERARCH cards)
    _value_indicator = VALUE_INDICATOR

    def __init__(self, keyword=None, value=None, comment=None, **kwargs):
        # For backwards compatibility, support the 'key' keyword argument:
        if keyword is None and 'key' in kwargs:
            keyword = kwargs['key']

        self._keyword = None
        self._value = None
        self._comment = None
        self._valuestring = None
        self._image = None

        # This attribute is set to False when creating the card from a card
        # image to ensure that the contents of the image get verified at some
        # point
        self._verified = True

        # A flag to conveniently mark whether or not this was a valid HIERARCH
        # card
        self._hierarch = False

        # If the card could not be parsed according the the FITS standard or
        # any recognized non-standard conventions, this will be True
        self._invalid = False

        self._field_specifier = None

        # These are used primarily only by RVKCs
        self._rawkeyword = None
        self._rawvalue = None

        if not (keyword is not None and value is not None and
                self._check_if_rvkc(keyword, value)):
            # If _check_if_rvkc passes, it will handle setting the keyword and
            # value
            if keyword is not None:
                self.keyword = keyword
            if value is not None:
                self.value = value

        if comment is not None:
            self.comment = comment

        self._modified = False
        self._valuemodified = False

    def __repr__(self):
        return repr((self.keyword, self.value, self.comment))

    def __str__(self):
        return self.image

    def __len__(self):
        return 3

    def __getitem__(self, index):
        return (self.keyword, self.value, self.comment)[index]

    @property
    def keyword(self):
        """Returns the keyword name parsed from the card image."""
        if self._keyword is not None:
            return self._keyword
        elif self._image:
            self._keyword = self._parse_keyword()
            return self._keyword
        else:
            self.keyword = ''
            return ''

    @keyword.setter
    def keyword(self, keyword):
        """Set the key attribute; once set it cannot be modified."""
        if self._keyword is not None:
            raise AttributeError(
                'Once set, the Card keyword may not be modified')
        elif isinstance(keyword, str):
            # Be nice and remove trailing whitespace--some FITS code always
            # pads keywords out with spaces; leading whitespace, however,
            # should be strictly disallowed.
            keyword = keyword.rstrip()
            keyword_upper = keyword.upper()
            if (len(keyword) <= KEYWORD_LENGTH and
                    self._keywd_FSC_RE.match(keyword_upper)):
                # For keywords with length > 8 they will be HIERARCH cards,
                # and can have arbitrary case keywords
                if keyword_upper == 'END':
                    raise ValueError("Keyword 'END' not allowed.")
                keyword = keyword_upper
            elif self._keywd_hierarch_RE.match(keyword):
                # In prior versions of PyFITS (*) HIERARCH cards would only be
                # created if the user-supplied keyword explicitly started with
                # 'HIERARCH '.  Now we will create them automatically for long
                # keywords, but we still want to support the old behavior too;
                # the old behavior makes it possible to create HIERARCH cards
                # that would otherwise be recognized as RVKCs
                # (*) This has never affected Astropy, because it was changed
                # before PyFITS was merged into Astropy!
                self._hierarch = True
                self._value_indicator = HIERARCH_VALUE_INDICATOR

                if keyword_upper[:9] == 'HIERARCH ':
                    # The user explicitly asked for a HIERARCH card, so don't
                    # bug them about it...
                    keyword = keyword[9:].strip()
                else:
                    # We'll gladly create a HIERARCH card, but a warning is
                    # also displayed
                    warnings.warn(
                        'Keyword name {!r} is greater than 8 characters or '
                        'contains characters not allowed by the FITS '
                        'standard; a HIERARCH card will be created.'.format(
                            keyword), VerifyWarning)
            else:
                raise ValueError(f'Illegal keyword name: {keyword!r}.')
            self._keyword = keyword
            self._modified = True
        else:
            raise ValueError(f'Keyword name {keyword!r} is not a string.')

    @property
    def value(self):
        """The value associated with the keyword stored in this card."""

        if self.field_specifier:
            return float(self._value)

        if self._value is not None:
            value = self._value
        elif self._valuestring is not None or self._image:
            value = self._value = self._parse_value()
        else:
            if self._keyword == '':
                self._value = value = ''
            else:
                self._value = value = UNDEFINED

        if conf.strip_header_whitespace and isinstance(value, str):
            value = value.rstrip()

        return value

    @value.setter
    def value(self, value):
        if self._invalid:
            raise ValueError(
                'The value of invalid/unparsable cards cannot set.  Either '
                'delete this card from the header or replace it.')

        if value is None:
            value = UNDEFINED

        try:
            oldvalue = self.value
        except VerifyError:
            # probably a parsing error, falling back to the internal _value
            # which should be None. This may happen while calling _fix_value.
            oldvalue = self._value

        if oldvalue is None:
            oldvalue = UNDEFINED

        if not isinstance(value,
                          (str, int, float, complex, bool, Undefined,
                           np.floating, np.integer, np.complexfloating,
                           np.bool_)):
            raise ValueError(f'Illegal value: {value!r}.')

        if isinstance(value, (float, np.float32)) and (np.isnan(value) or
                                                       np.isinf(value)):
            # value is checked for both float and np.float32 instances
            # since np.float32 is not considered a Python float.
            raise ValueError("Floating point {!r} values are not allowed "
                             "in FITS headers.".format(value))

        elif isinstance(value, str):
            m = self._ascii_text_re.match(value)
            if not m:
                raise ValueError(
                    'FITS header values must contain standard printable ASCII '
                    'characters; {!r} contains characters not representable in '
                    'ASCII or non-printable characters.'.format(value))
        elif isinstance(value, np.bool_):
            value = bool(value)

        if (conf.strip_header_whitespace and
                (isinstance(oldvalue, str) and isinstance(value, str))):
            # Ignore extra whitespace when comparing the new value to the old
            different = oldvalue.rstrip() != value.rstrip()
        elif isinstance(oldvalue, bool) or isinstance(value, bool):
            different = oldvalue is not value
        else:
            different = (oldvalue != value or
                         not isinstance(value, type(oldvalue)))

        if different:
            self._value = value
            self._rawvalue = None
            self._modified = True
            self._valuestring = None
            self._valuemodified = True
            if self.field_specifier:
                try:
                    self._value = _int_or_float(self._value)
                except ValueError:
                    raise ValueError(f'value {self._value} is not a float')

    @value.deleter
    def value(self):
        if self._invalid:
            raise ValueError(
                'The value of invalid/unparsable cards cannot deleted.  '
                'Either delete this card from the header or replace it.')

        if not self.field_specifier:
            self.value = ''
        else:
            raise AttributeError('Values cannot be deleted from record-valued '
                                 'keyword cards')

    @property
    def rawkeyword(self):
        """On record-valued keyword cards this is the name of the standard <= 8
        character FITS keyword that this RVKC is stored in.  Otherwise it is
        the card's normal keyword.
        """

        if self._rawkeyword is not None:
            return self._rawkeyword
        elif self.field_specifier is not None:
            self._rawkeyword = self.keyword.split('.', 1)[0]
            return self._rawkeyword
        else:
            return self.keyword

    @property
    def rawvalue(self):
        """On record-valued keyword cards this is the raw string value in
        the ``<field-specifier>: <value>`` format stored in the card in order
        to represent a RVKC.  Otherwise it is the card's normal value.
        """

        if self._rawvalue is not None:
            return self._rawvalue
        elif self.field_specifier is not None:
            self._rawvalue = f'{self.field_specifier}: {self.value}'
            return self._rawvalue
        else:
            return self.value

    @property
    def comment(self):
        """Get the comment attribute from the card image if not already set."""

        if self._comment is not None:
            return self._comment
        elif self._image:
            self._comment = self._parse_comment()
            return self._comment
        else:
            self._comment = ''
            return ''

    @comment.setter
    def comment(self, comment):
        if self._invalid:
            raise ValueError(
                'The comment of invalid/unparsable cards cannot set.  Either '
                'delete this card from the header or replace it.')

        if comment is None:
            comment = ''

        if isinstance(comment, str):
            m = self._ascii_text_re.match(comment)
            if not m:
                raise ValueError(
                    'FITS header comments must contain standard printable '
                    'ASCII characters; {!r} contains characters not '
                    'representable in ASCII or non-printable characters.'
                    .format(comment))

        try:
            oldcomment = self.comment
        except VerifyError:
            # probably a parsing error, falling back to the internal _comment
            # which should be None.
            oldcomment = self._comment

        if oldcomment is None:
            oldcomment = ''
        if comment != oldcomment:
            self._comment = comment
            self._modified = True

    @comment.deleter
    def comment(self):
        if self._invalid:
            raise ValueError(
                'The comment of invalid/unparsable cards cannot deleted.  '
                'Either delete this card from the header or replace it.')

        self.comment = ''

    @property
    def field_specifier(self):
        """
        The field-specifier of record-valued keyword cards; always `None` on
        normal cards.
        """

        # Ensure that the keyword exists and has been parsed--the will set the
        # internal _field_specifier attribute if this is a RVKC.
        if self.keyword:
            return self._field_specifier
        else:
            return None

    @field_specifier.setter
    def field_specifier(self, field_specifier):
        if not field_specifier:
            raise ValueError('The field-specifier may not be blank in '
                             'record-valued keyword cards.')
        elif not self.field_specifier:
            raise AttributeError('Cannot coerce cards to be record-valued '
                                 'keyword cards by setting the '
                                 'field_specifier attribute')
        elif field_specifier != self.field_specifier:
            self._field_specifier = field_specifier
            # The keyword need also be updated
            keyword = self._keyword.split('.', 1)[0]
            self._keyword = '.'.join([keyword, field_specifier])
            self._modified = True

    @field_specifier.deleter
    def field_specifier(self):
        raise AttributeError('The field_specifier attribute may not be '
                             'deleted from record-valued keyword cards.')

    @property
    def image(self):
        """
        The card "image", that is, the 80 byte character string that represents
        this card in an actual FITS header.
        """

        if self._image and not self._verified:
            self.verify('fix+warn')
        if self._image is None or self._modified:
            self._image = self._format_image()
        return self._image

    @property
    def is_blank(self):
        """
        `True` if the card is completely blank--that is, it has no keyword,
        value, or comment.  It appears in the header as 80 spaces.

        Returns `False` otherwise.
        """

        if not self._verified:
            # The card image has not been parsed yet; compare directly with the
            # string representation of a blank card
            return self._image == BLANK_CARD

        # If the keyword, value, and comment are all empty (for self.value
        # explicitly check that it is a string value, since a blank value is
        # returned as '')
        return (not self.keyword and
                (isinstance(self.value, str) and not self.value) and
                not self.comment)

    @classmethod
    def fromstring(cls, image):
        """
        Construct a `Card` object from a (raw) string. It will pad the string
        if it is not the length of a card image (80 columns).  If the card
        image is longer than 80 columns, assume it contains ``CONTINUE``
        card(s).
        """

        card = cls()
        if isinstance(image, bytes):
            # FITS supports only ASCII, but decode as latin1 and just take all
            # bytes for now; if it results in mojibake due to e.g. UTF-8
            # encoded data in a FITS header that's OK because it shouldn't be
            # there in the first place
            image = image.decode('latin1')

        card._image = _pad(image)
        card._verified = False
        return card

    @classmethod
    def normalize_keyword(cls, keyword):
        """
        `classmethod` to convert a keyword value that may contain a
        field-specifier to uppercase.  The effect is to raise the key to
        uppercase and leave the field specifier in its original case.

        Parameters
        ----------
        keyword : or str
            A keyword value or a ``keyword.field-specifier`` value
        """

        # Test first for the most common case: a standard FITS keyword provided
        # in standard all-caps
        if (len(keyword) <= KEYWORD_LENGTH and
                cls._keywd_FSC_RE.match(keyword)):
            return keyword

        # Test if this is a record-valued keyword
        match = cls._rvkc_keyword_name_RE.match(keyword)

        if match:
            return '.'.join((match.group('keyword').strip().upper(),
                             match.group('field_specifier')))
        elif len(keyword) > 9 and keyword[:9].upper() == 'HIERARCH ':
            # Remove 'HIERARCH' from HIERARCH keywords; this could lead to
            # ambiguity if there is actually a keyword card containing
            # "HIERARCH HIERARCH", but shame on you if you do that.
            return keyword[9:].strip().upper()
        else:
            # A normal FITS keyword, but provided in non-standard case
            return keyword.strip().upper()

    def _check_if_rvkc(self, *args):
        """
        Determine whether or not the card is a record-valued keyword card.

        If one argument is given, that argument is treated as a full card image
        and parsed as such.  If two arguments are given, the first is treated
        as the card keyword (including the field-specifier if the card is
        intended as a RVKC), and the second as the card value OR the first value
        can be the base keyword, and the second value the 'field-specifier:
        value' string.

        If the check passes the ._keyword, ._value, and .field_specifier
        keywords are set.

        Examples
        --------
        ::

            self._check_if_rvkc('DP1', 'AXIS.1: 2')
            self._check_if_rvkc('DP1.AXIS.1', 2)
            self._check_if_rvkc('DP1     = AXIS.1: 2')
        """

        if not conf.enable_record_valued_keyword_cards:
            return False

        if len(args) == 1:
            return self._check_if_rvkc_image(*args)
        elif len(args) == 2:
            keyword, value = args
            if not isinstance(keyword, str):
                return False
            if keyword in self._commentary_keywords:
                return False
            match = self._rvkc_keyword_name_RE.match(keyword)
            if match and isinstance(value, (int, float)):
                self._init_rvkc(match.group('keyword'),
                                match.group('field_specifier'), None, value)
                return True

            # Testing for ': ' is a quick way to avoid running the full regular
            # expression, speeding this up for the majority of cases
            if isinstance(value, str) and value.find(': ') > 0:
                match = self._rvkc_field_specifier_val_RE.match(value)
                if match and self._keywd_FSC_RE.match(keyword):
                    self._init_rvkc(keyword, match.group('keyword'), value,
                                    match.group('val'))
                    return True

    def _check_if_rvkc_image(self, *args):
        """
        Implements `Card._check_if_rvkc` for the case of an unparsed card
        image.  If given one argument this is the full intact image.  If given
        two arguments the card has already been split between keyword and
        value+comment at the standard value indicator '= '.
        """

        if len(args) == 1:
            image = args[0]
            eq_idx = image.find(VALUE_INDICATOR)
            if eq_idx < 0 or eq_idx > 9:
                return False
            keyword = image[:eq_idx]
            rest = image[eq_idx + VALUE_INDICATOR_LEN:]
        else:
            keyword, rest = args

        rest = rest.lstrip()

        # This test allows us to skip running the full regular expression for
        # the majority of cards that do not contain strings or that definitely
        # do not contain RVKC field-specifiers; it's very much a
        # micro-optimization but it does make a measurable difference
        if not rest or rest[0] != "'" or rest.find(': ') < 2:
            return False

        match = self._rvkc_keyword_val_comm_RE.match(rest)
        if match:
            self._init_rvkc(keyword, match.group('keyword'),
                            match.group('rawval'), match.group('val'))
            return True

    def _init_rvkc(self, keyword, field_specifier, field, value):
        """
        Sort of addendum to Card.__init__ to set the appropriate internal
        attributes if the card was determined to be a RVKC.
        """

        keyword_upper = keyword.upper()
        self._keyword = '.'.join((keyword_upper, field_specifier))
        self._rawkeyword = keyword_upper
        self._field_specifier = field_specifier
        self._value = _int_or_float(value)
        self._rawvalue = field

    def _parse_keyword(self):
        keyword = self._image[:KEYWORD_LENGTH].strip()
        keyword_upper = keyword.upper()

        if keyword_upper in self._special_keywords:
            return keyword_upper
        elif (keyword_upper == 'HIERARCH' and self._image[8] == ' ' and
              HIERARCH_VALUE_INDICATOR in self._image):
            # This is valid HIERARCH card as described by the HIERARCH keyword
            # convention:
            # http://fits.gsfc.nasa.gov/registry/hierarch_keyword.html
            self._hierarch = True
            self._value_indicator = HIERARCH_VALUE_INDICATOR
            keyword = self._image.split(HIERARCH_VALUE_INDICATOR, 1)[0][9:]
            return keyword.strip()
        else:
            val_ind_idx = self._image.find(VALUE_INDICATOR)
            if 0 <= val_ind_idx <= KEYWORD_LENGTH:
                # The value indicator should appear in byte 8, but we are
                # flexible and allow this to be fixed
                if val_ind_idx < KEYWORD_LENGTH:
                    keyword = keyword[:val_ind_idx]
                    keyword_upper = keyword_upper[:val_ind_idx]

                rest = self._image[val_ind_idx + VALUE_INDICATOR_LEN:]

                # So far this looks like a standard FITS keyword; check whether
                # the value represents a RVKC; if so then we pass things off to
                # the RVKC parser
                if self._check_if_rvkc_image(keyword, rest):
                    return self._keyword

                return keyword_upper
            else:
                warnings.warn(
                    'The following header keyword is invalid or follows an '
                    'unrecognized non-standard convention:\n{}'
                    .format(self._image), AstropyUserWarning)
                self._invalid = True
                return keyword

    def _parse_value(self):
        """Extract the keyword value from the card image."""

        # for commentary cards, no need to parse further
        # Likewise for invalid cards
        if self.keyword.upper() in self._commentary_keywords or self._invalid:
            return self._image[KEYWORD_LENGTH:].rstrip()

        if self._check_if_rvkc(self._image):
            return self._value

        m = self._value_NFSC_RE.match(self._split()[1])

        if m is None:
            raise VerifyError("Unparsable card ({}), fix it first with "
                              ".verify('fix').".format(self.keyword))

        if m.group('bool') is not None:
            value = m.group('bool') == 'T'
        elif m.group('strg') is not None:
            value = re.sub("''", "'", m.group('strg'))
        elif m.group('numr') is not None:
            #  Check for numbers with leading 0s.
            numr = self._number_NFSC_RE.match(m.group('numr'))
            digt = translate(numr.group('digt'), FIX_FP_TABLE2, ' ')
            if numr.group('sign') is None:
                sign = ''
            else:
                sign = numr.group('sign')
            value = _str_to_num(sign + digt)

        elif m.group('cplx') is not None:
            #  Check for numbers with leading 0s.
            real = self._number_NFSC_RE.match(m.group('real'))
            rdigt = translate(real.group('digt'), FIX_FP_TABLE2, ' ')
            if real.group('sign') is None:
                rsign = ''
            else:
                rsign = real.group('sign')
            value = _str_to_num(rsign + rdigt)
            imag = self._number_NFSC_RE.match(m.group('imag'))
            idigt = translate(imag.group('digt'), FIX_FP_TABLE2, ' ')
            if imag.group('sign') is None:
                isign = ''
            else:
                isign = imag.group('sign')
            value += _str_to_num(isign + idigt) * 1j
        else:
            value = UNDEFINED

        if not self._valuestring:
            self._valuestring = m.group('valu')
        return value

    def _parse_comment(self):
        """Extract the keyword value from the card image."""

        # for commentary cards, no need to parse further
        # likewise for invalid/unparsable cards
        if self.keyword in Card._commentary_keywords or self._invalid:
            return ''

        valuecomment = self._split()[1]
        m = self._value_NFSC_RE.match(valuecomment)
        comment = ''
        if m is not None:
            # Don't combine this if statement with the one above, because
            # we only want the elif case to run if this was not a valid
            # card at all
            if m.group('comm'):
                comment = m.group('comm').rstrip()
        elif '/' in valuecomment:
            # The value in this FITS file was not in a valid/known format.  In
            # this case the best we can do is guess that everything after the
            # first / was meant to be the comment
            comment = valuecomment.split('/', 1)[1].strip()

        return comment

    def _split(self):
        """
        Split the card image between the keyword and the rest of the card.
        """

        if self._image is not None:
            # If we already have a card image, don't try to rebuild a new card
            # image, which self.image would do
            image = self._image
        else:
            image = self.image

        # Split cards with CONTINUE cards or commentary keywords with long
        # values
        if len(self._image) > self.length:
            values = []
            comments = []
            keyword = None
            for card in self._itersubcards():
                kw, vc = card._split()
                if keyword is None:
                    keyword = kw

                if keyword in self._commentary_keywords:
                    values.append(vc)
                    continue

                # Should match a string followed by a comment; if not it
                # might be an invalid Card, so we just take it verbatim
                m = self._strg_comment_RE.match(vc)
                if not m:
                    return kw, vc

                value = m.group('strg') or ''
                value = value.rstrip().replace("''", "'")
                if value and value[-1] == '&':
                    value = value[:-1]
                values.append(value)
                comment = m.group('comm')
                if comment:
                    comments.append(comment.rstrip())

            if keyword in self._commentary_keywords:
                valuecomment = ''.join(values)
            else:
                # CONTINUE card
                valuecomment = f"'{''.join(values)}' / {' '.join(comments)}"
            return keyword, valuecomment

        if self.keyword in self._special_keywords:
            keyword, valuecomment = image.split(' ', 1)
        else:
            try:
                delim_index = image.index(self._value_indicator)
            except ValueError:
                delim_index = None

            # The equal sign may not be any higher than column 10; anything
            # past that must be considered part of the card value
            if delim_index is None:
                keyword = image[:KEYWORD_LENGTH]
                valuecomment = image[KEYWORD_LENGTH:]
            elif delim_index > 10 and image[:9] != 'HIERARCH ':
                keyword = image[:8]
                valuecomment = image[8:]
            else:
                keyword, valuecomment = image.split(self._value_indicator, 1)
        return keyword.strip(), valuecomment.strip()

    def _fix_keyword(self):
        if self.field_specifier:
            keyword, field_specifier = self._keyword.split('.', 1)
            self._keyword = '.'.join([keyword.upper(), field_specifier])
        else:
            self._keyword = self._keyword.upper()
        self._modified = True

    def _fix_value(self):
        """Fix the card image for fixable non-standard compliance."""

        value = None
        keyword, valuecomment = self._split()
        m = self._value_NFSC_RE.match(valuecomment)

        # for the unparsable case
        if m is None:
            try:
                value, comment = valuecomment.split('/', 1)
                self.value = value.strip()
                self.comment = comment.strip()
            except (ValueError, IndexError):
                self.value = valuecomment
            self._valuestring = self._value
            return
        elif m.group('numr') is not None:
            numr = self._number_NFSC_RE.match(m.group('numr'))
            value = translate(numr.group('digt'), FIX_FP_TABLE, ' ')
            if numr.group('sign') is not None:
                value = numr.group('sign') + value

        elif m.group('cplx') is not None:
            real = self._number_NFSC_RE.match(m.group('real'))
            rdigt = translate(real.group('digt'), FIX_FP_TABLE, ' ')
            if real.group('sign') is not None:
                rdigt = real.group('sign') + rdigt

            imag = self._number_NFSC_RE.match(m.group('imag'))
            idigt = translate(imag.group('digt'), FIX_FP_TABLE, ' ')
            if imag.group('sign') is not None:
                idigt = imag.group('sign') + idigt
            value = f'({rdigt}, {idigt})'
        self._valuestring = value
        # The value itself has not been modified, but its serialized
        # representation (as stored in self._valuestring) has been changed, so
        # still set this card as having been modified (see ticket #137)
        self._modified = True

    def _format_keyword(self):
        if self.keyword:
            if self.field_specifier:
                return '{:{len}}'.format(self.keyword.split('.', 1)[0],
                                         len=KEYWORD_LENGTH)
            elif self._hierarch:
                return f'HIERARCH {self.keyword} '
            else:
                return '{:{len}}'.format(self.keyword, len=KEYWORD_LENGTH)
        else:
            return ' ' * KEYWORD_LENGTH

    def _format_value(self):
        # value string
        float_types = (float, np.floating, complex, np.complexfloating)

        # Force the value to be parsed out first
        value = self.value
        # But work with the underlying raw value instead (to preserve
        # whitespace, for now...)
        value = self._value

        if self.keyword in self._commentary_keywords:
            # The value of a commentary card must be just a raw unprocessed
            # string
            value = str(value)
        elif (self._valuestring and not self._valuemodified and
              isinstance(self.value, float_types)):
            # Keep the existing formatting for float/complex numbers
            value = f'{self._valuestring:>20}'
        elif self.field_specifier:
            value = _format_value(self._value).strip()
            value = f"'{self.field_specifier}: {value}'"
        else:
            value = _format_value(value)

        # For HIERARCH cards the value should be shortened to conserve space
        if not self.field_specifier and len(self.keyword) > KEYWORD_LENGTH:
            value = value.strip()

        return value

    def _format_comment(self):
        if not self.comment:
            return ''
        else:
            return f' / {self._comment}'

    def _format_image(self):
        keyword = self._format_keyword()

        value = self._format_value()
        is_commentary = keyword.strip() in self._commentary_keywords
        if is_commentary:
            comment = ''
        else:
            comment = self._format_comment()

        # equal sign string
        # by default use the standard value indicator even for HIERARCH cards;
        # later we may abbreviate it if necessary
        delimiter = VALUE_INDICATOR
        if is_commentary:
            delimiter = ''

        # put all parts together
        output = ''.join([keyword, delimiter, value, comment])

        # For HIERARCH cards we can save a bit of space if necessary by
        # removing the space between the keyword and the equals sign; I'm
        # guessing this is part of the HIEARCH card specification
        keywordvalue_length = len(keyword) + len(delimiter) + len(value)
        if (keywordvalue_length > self.length and
                keyword.startswith('HIERARCH')):
            if (keywordvalue_length == self.length + 1 and keyword[-1] == ' '):
                output = ''.join([keyword[:-1], delimiter, value, comment])
            else:
                # I guess the HIERARCH card spec is incompatible with CONTINUE
                # cards
                raise ValueError('The header keyword {!r} with its value is '
                                 'too long'.format(self.keyword))

        if len(output) <= self.length:
            output = f'{output:80}'
        else:
            # longstring case (CONTINUE card)
            # try not to use CONTINUE if the string value can fit in one line.
            # Instead, just truncate the comment
            if (isinstance(self.value, str) and
                    len(value) > (self.length - 10)):
                output = self._format_long_image()
            else:
                warnings.warn('Card is too long, comment will be truncated.',
                              VerifyWarning)
                output = output[:Card.length]
        return output

    def _format_long_image(self):
        """
        Break up long string value/comment into ``CONTINUE`` cards.
        This is a primitive implementation: it will put the value
        string in one block and the comment string in another.  Also,
        it does not break at the blank space between words.  So it may
        not look pretty.
        """

        if self.keyword in Card._commentary_keywords:
            return self._format_long_commentary_image()

        value_length = 67
        comment_length = 64
        output = []

        # do the value string
        value = self._value.replace("'", "''")
        words = _words_group(value, value_length)
        for idx, word in enumerate(words):
            if idx == 0:
                headstr = '{:{len}}= '.format(self.keyword, len=KEYWORD_LENGTH)
            else:
                headstr = 'CONTINUE  '

            # If this is the final CONTINUE remove the '&'
            if not self.comment and idx == len(words) - 1:
                value_format = "'{}'"
            else:
                value_format = "'{}&'"

            value = value_format.format(word)

            output.append(f'{headstr + value:80}')

        # do the comment string
        comment_format = "{}"

        if self.comment:
            words = _words_group(self.comment, comment_length)
            for idx, word in enumerate(words):
                # If this is the final CONTINUE remove the '&'
                if idx == len(words) - 1:
                    headstr = "CONTINUE  '' / "
                else:
                    headstr = "CONTINUE  '&' / "

                comment = headstr + comment_format.format(word)
                output.append(f'{comment:80}')

        return ''.join(output)

    def _format_long_commentary_image(self):
        """
        If a commentary card's value is too long to fit on a single card, this
        will render the card as multiple consecutive commentary card of the
        same type.
        """

        maxlen = Card.length - KEYWORD_LENGTH
        value = self._format_value()
        output = []
        idx = 0
        while idx < len(value):
            output.append(str(Card(self.keyword, value[idx:idx + maxlen])))
            idx += maxlen
        return ''.join(output)

    def _verify(self, option='warn'):
        errs = []
        fix_text = f'Fixed {self.keyword!r} card to meet the FITS standard.'

        # Don't try to verify cards that already don't meet any recognizable
        # standard
        if self._invalid:
            return _ErrList(errs)

        # verify the equal sign position
        if (self.keyword not in self._commentary_keywords and
            (self._image and self._image[:9].upper() != 'HIERARCH ' and
             self._image.find('=') != 8)):
            errs.append(dict(
                err_text='Card {!r} is not FITS standard (equal sign not '
                         'at column 8).'.format(self.keyword),
                fix_text=fix_text,
                fix=self._fix_value))

        # verify the key, it is never fixable
        # always fix silently the case where "=" is before column 9,
        # since there is no way to communicate back to the _keys.
        if ((self._image and self._image[:8].upper() == 'HIERARCH') or
                self._hierarch):
            pass
        else:
            if self._image:
                # PyFITS will auto-uppercase any standard keyword, so lowercase
                # keywords can only occur if they came from the wild
                keyword = self._split()[0]
                if keyword != keyword.upper():
                    # Keyword should be uppercase unless it's a HIERARCH card
                    errs.append(dict(
                        err_text=f'Card keyword {keyword!r} is not upper case.',
                        fix_text=fix_text,
                        fix=self._fix_keyword))

            keyword = self.keyword
            if self.field_specifier:
                keyword = keyword.split('.', 1)[0]

            if not self._keywd_FSC_RE.match(keyword):
                errs.append(dict(
                    err_text=f'Illegal keyword name {keyword!r}',
                    fixable=False))

        # verify the value, it may be fixable
        keyword, valuecomment = self._split()
        if self.keyword in self._commentary_keywords:
            # For commentary keywords all that needs to be ensured is that it
            # contains only printable ASCII characters
            if not self._ascii_text_re.match(valuecomment):
                errs.append(dict(
                    err_text='Unprintable string {!r}; commentary cards may '
                             'only contain printable ASCII characters'.format(
                             valuecomment),
                    fixable=False))
        else:
            if not self._valuemodified:
                m = self._value_FSC_RE.match(valuecomment)
                # If the value of a card was replaced before the card was ever
                # even verified, the new value can be considered valid, so we
                # don't bother verifying the old value.  See
                # https://github.com/astropy/astropy/issues/5408
                if m is None:
                    errs.append(dict(
                        err_text=f'Card {self.keyword!r} is not FITS standard '
                                 f'(invalid value string: {valuecomment!r}).',
                        fix_text=fix_text,
                        fix=self._fix_value))

        # verify the comment (string), it is never fixable
        m = self._value_NFSC_RE.match(valuecomment)
        if m is not None:
            comment = m.group('comm')
            if comment is not None:
                if not self._ascii_text_re.match(comment):
                    errs.append(dict(
                        err_text=f'Unprintable string {comment!r}; header '
                                  'comments may only contain printable '
                                  'ASCII characters',
                        fixable=False))

        errs = _ErrList([self.run_option(option, **err) for err in errs])
        self._verified = True
        return errs

    def _itersubcards(self):
        """
        If the card image is greater than 80 characters, it should consist of a
        normal card followed by one or more CONTINUE card.  This method returns
        the subcards that make up this logical card.

        This can also support the case where a HISTORY or COMMENT card has a
        long value that is stored internally as multiple concatenated card
        images.
        """

        ncards = len(self._image) // Card.length

        for idx in range(0, Card.length * ncards, Card.length):
            card = Card.fromstring(self._image[idx:idx + Card.length])
            if idx > 0 and card.keyword.upper() not in self._special_keywords:
                raise VerifyError(
                        'Long card images must have CONTINUE cards after '
                        'the first card or have commentary keywords like '
                        'HISTORY or COMMENT.')

            if not isinstance(card.value, str):
                raise VerifyError('CONTINUE cards must have string values.')

            yield card

def _int_or_float(s):
    """
    Converts an a string to an int if possible, or to a float.

    If the string is neither a string or a float a value error is raised.
    """

    if isinstance(s, float):
        # Already a float so just pass through
        return s

    try:
        return int(s)
    except (ValueError, TypeError):
        try:
            return float(s)
        except (ValueError, TypeError) as e:
            raise ValueError(str(e))

def _format_value(value):
    """
    Converts a card value to its appropriate string representation as
    defined by the FITS format.
    """

    # string value should occupies at least 8 columns, unless it is
    # a null string
    if isinstance(value, str):
        if value == '':
            return "''"
        else:
            exp_val_str = value.replace("'", "''")
            val_str = f"'{exp_val_str:8}'"
            return f'{val_str:20}'

    # must be before int checking since bool is also int
    elif isinstance(value, (bool, np.bool_)):
        return f'{repr(value)[0]:>20}'  # T or F

    elif _is_int(value):
        return f'{value:>20d}'

    elif isinstance(value, (float, np.floating)):
        return f'{_format_float(value):>20}'

    elif isinstance(value, (complex, np.complexfloating)):
        val_str = f'({_format_float(value.real)}, {_format_float(value.imag)})'
        return f'{val_str:>20}'

    elif isinstance(value, Undefined):
        return ''
    else:
        return ''

def _format_float(value):
    """Format a floating number to make sure it gets the decimal point."""

    value_str = f'{value:.16G}'
    if '.' not in value_str and 'E' not in value_str:
        value_str += '.0'
    elif 'E' in value_str:
        # On some Windows builds of Python (and possibly other platforms?) the
        # exponent is zero-padded out to, it seems, three digits.  Normalize
        # the format to pad only to two digits.
        significand, exponent = value_str.split('E')
        if exponent[0] in ('+', '-'):
            sign = exponent[0]
            exponent = exponent[1:]
        else:
            sign = ''
        value_str = f'{significand}E{sign}{int(exponent):02d}'

    # Limit the value string to at most 20 characters.
    str_len = len(value_str)

    if str_len > 20:
        idx = value_str.find('E')

        if idx < 0:
            value_str = value_str[:20]
        else:
            value_str = value_str[:20 - (str_len - idx)] + value_str[idx:]

    return value_str

def _pad(input):
    """Pad blank space to the input string to be multiple of 80."""

    _len = len(input)
    if _len == Card.length:
        return input
    elif _len > Card.length:
        strlen = _len % Card.length
        if strlen == 0:
            return input
        else:
            return input + ' ' * (Card.length - strlen)

    # minimum length is 80
    else:
        strlen = _len % Card.length
        return input + ' ' * (Card.length - strlen)

max_stars_repo_name: emirkmo/astropy

max_issues_repo_name: emirkmo/astropy

max_forks_repo_name: emirkmo/astropy

reason: import numpy,from astropy