import discord
from discord.ext import commands
import random
from src.discord.giphy import Gif
import json
import sys
import os
import tensorflow as tf
import boto3
import json
import asyncio
import random
import src.models.aesop_gpt2 as gpt2
from transformers import GPT2Model, GPT2Config, GPT2Tokenizer
import pickle
import math
import tensorflow
import tensorflow as tf
import tensorflow_datasets as tfds
import tensorflow_addons as tfa
import json
import os
import time
from ftfy import fix_text
#:os.chdir('../')
import pickle
import numpy as np
import string, os
from gensim.models import KeyedVectors
import gensim.downloader as api
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Dense, Input, Dropout, LSTM, Activation, Bidirectional
from tensorflow.keras.layers import Embedding
from tensorflow.keras.preprocessing import sequence
from tensorflow.keras.initializers import glorot_uniform
from tensorflow.keras.callbacks import LambdaCallback, ModelCheckpoint
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
import tensorflow.keras.utils as ku
from sklearn.model_selection import train_test_split
import random
import sys
from datetime import date
from collections import Counter
import matplotlib.pyplot as plt
from src.features.build import Lyrics
from src.features.transform_data import Transform
from random import shuffle
from tensorflow.python.framework import tensor_shape
from tokenizers import CharBPETokenizer, BertWordPieceTokenizer
from transformers import GPT2Model, GPT2Config, GPT2Tokenizer
# physical_devices = tf.config.list_physical_devices('GPU')
# tf.config.experimental.set_memory_growth(physical_devices[0], enable=True)
# from src.features.build import Provider
# model = inference()
description = '''Bot for aesop rock'''
bot = commands.Bot(command_prefix='?', description=description)
client = discord.Client()
# client.close()

@bot.event
async def on_ready():
    # global model
    # global data_reader
    print('Logged in as')
    print(bot.user.name)
    print(bot.user.id)
    print('------')

@bot.command()
async def add(left : int, right : int):
    """Adds two numbers together."""
    await bot.say(left + right)

@bot.command()
async def roll(dice : str):
    """Rolls a dice in NdN format."""
    try:
        rolls, limit = map(int, dice.split('d'))
    except Exception:
        await bot.say('Format has to be in NdN!')
        return

    result = ', '.join(str(random.randint(1, limit)) for r in range(rolls))
    if len(result) < 2000:
        await bot.say(result)
    else:
        await bot.say('Result is too long. Look it up on wolfram alpha or something Kappa')

@bot.command(description='For when you wanna settle the score some other way')
async def choose(*choices : str):
    """Chooses between multiple choices."""
    await bot.say(random.choice(choices))

@bot.command()
async def repeat(times : int, content='repeating...'):
    """Repeats a message multiple times."""
    for i in range(times):
        await bot.say(content)

@bot.command()
async def joined(member : discord.Member):
    """Says when a member joined."""
    await bot.say('{0.name} joined in {0.joined_at}'.format(member))

@bot.group(pass_context=True)
async def cool(ctx):
    """Says if a user is cool.
    In reality this just checks if a subcommand is being invoked.
    """
    if ctx.invoked_subcommand is None:
        await bot.say('No, {0.subcommand_passed} is not cool'.format(ctx))

@cool.command(name='Pepo-Bot')
async def _bot():
    """Is the bot cool?"""
    await bot.say('Yes, the bot is cool.')

@bot.command()
async def subtract(left : int, right : int):
    """Adds two numbers together."""
    await bot.say(left - right)

@bot.command()
async def randomboi():
    """Posts a random dat boi"""
    boi = Gif('datboi', 50).random()
    await bot.say(boi)

@bot.command()
async def gif(*term: str):
    """Searches for and posts a gif from giphy"""
    term = " ".join(list(term))
    _gif = Gif(term, 50).random()
    await bot.say(_gif)

@bot.command(name='freestyle_topic')
async def freestyle_topic(ctx, context: str, seq_len: int, temperature: float, top_k: int,top_p: float):
    """Aesop Raps about a specific topic"""
    # global data_reader
    # print(term)
    term = "".join(list(context))
    tokenizer = GPT2Tokenizer.from_pretrained('gpt2-xl')
    special_tokens_dict = {'eos_token':'<END>','sep_token':'<NEWLINE>','bos_token':'<START>'}
    num_added_toks = tokenizer.add_special_tokens(special_tokens_dict)

    model = gpt2.Gpt2(6, 768, 8, 768, 128, vocab_size=tokenizer.vocab_size+3, tokenizer=tokenizer, optimizer="adam")#.load_model(filepath='checkpoint')
    model.create_optimizer()
    model.create_checkpoint_manager('checkpoint_longer')
    # model.create_summary_writer('logs')
    # model = model.load_model(filepath='checkpoint')
    # global data_reader
    # print(random.random(data_reader.lyrics))
    sample = model.sample_sequence(seq_len, context=context,temperature=temperature,top_k=top_k,top_p=top_p,nucleus_sampling=True)
    #sample = model.generate(data_reader, priming_text="hip hop ", sample=True, num_out=2000, temperature=.4)
    del model

    await ctx.send(sample)

@bot.command(name='freestyle_random')
async def freestyle_random(ctx, seq_len: int, temperature: float, top_k: int,top_p: float):
    """Aesop Raps: Random Aesop lyrics are fed in to seed the generator"""
    data_dir = 'data/processed/verses.txt'
    with open(data_dir, "rb") as fp:   # Unpickling
        lyrics = pickle.load(fp)
    arr = [' <NEWLINE> '.join([j for j in i.split(' \n ') if len(j) > 1 and '\n\n' != j]) for i in list(np.array(lyrics)) if len(i.split(' \n ')) > 0]#tokenizer = BertWordPieceTokenizer()
    #tokenizer.train(['data/processed/verses_encoded.txt'])
    tokenizer = GPT2Tokenizer.from_pretrained('gpt2-xl')
    special_tokens_dict = {'eos_token':'<END>','sep_token':'<NEWLINE>','bos_token':'<START>'}
    num_added_toks = tokenizer.add_special_tokens(special_tokens_dict)
    print(tokenizer.encode(' <NEWLINE> '))
    tokenizer.save_pretrained('src/data/tokenizers')
    dataset = list()
    for verse in arr:
        tmp = list()
        verse = ' <START> ' + verse + ' <END> '
        verse_split = verse.split(' <NEWLINE> ')
        for line in verse_split:
            tmp = tmp + tokenizer.encode(line + ' <NEWLINE>', add_prefix_space=True)
        if tmp:
            dataset.append(tmp)
    context = random.choice(dataset)[:25]
    model = gpt2.Gpt2(12, 768, 16, 768, 16, vocab_size=tokenizer.vocab_size+3, tokenizer=tokenizer, optimizer="adam")
    model.create_optimizer()
    model.create_checkpoint_manager('checkpoint_long')
    model.create_summary_writer('logs')
    # global data_reader
    # print(random.random(data_reader.lyrics))
    sample = model.sample_sequence(300, context=context,temperature=temperature,top_k=top_k,top_p=top_p,nucleus_sampling=True)
    #sample = model.generate(data_reader, priming_text="hip hop ", sample=True, num_out=2000, temperature=.4)
    del model
    await ctx.send(sample)

# @bot.command()
# async def aesop_stats(*term: str):
#     global model
#     # global data_reader
#     stats = dict()
#     stats['model_info'] = model.__dict__
#     stats['iterator_info'] = model.__dict__
#     print(term)
#     if not isinstance(term, tuple):
#         await bot.say("I'm just a dumb bot right now.\nA real normie.\nA real yitbosy fucker.\n.\nsBut....\n...\n....\nI can only hand a single argument.\n\n\n...\n...BRO!")
#     else:
#         if len(term) > 1 and len(term) < 3:
#             if term[0] == 'listparams':
#                 print(list(stats.keys()))
#                 if term[1] == 'model':
#                     await bot.say(stats['model_info'])
#                 elif term[1] == 'iterator':
#                     await bot.say(stats['iterator_info'])
#                 else:
#                     print(list(stats.keys()))
#                     await bot.say("Pick from either {0} or {1}".format(stats.keys()))
#             elif term[0] == "list":
#                 try:
#                     config = stats[term[1]]
#                     await bot.say(config)
#                 except KeyError:
#                     await bot.say("Hey yo thats not a parameter my brain is not familiar with\nYou should try ?listparams")
#         else:
#             await bot.say("Idk man. You're on your own.\nYou do know I have documentaion right?.\nTry ?help")
#

# @bot.command()
# async def speak():
#     try:
#         await bot.say("You should hear some noise.")
#         os.system('afplay sound.mp3')  # Works only on Mac OS, sorry
#         os.remove('sound.mp3')
#     except FileNotFoundError:
#         await bot.say("No audiofile found! Please use the freestyle command to generate text")

with open('configs/config.json','r') as cfgFile:
    cfg = json.load(cfgFile)
    # discord_params = cfg['discord']['token']
# global model
# global data_reader
# tf.reset_default_graph()
# # term = " ".join(list(term))
# data_reader = Provider(cfg["model_params"]["LSTM"]["BATCH_SIZE"],
#                        cfg["model_params"]["LSTM"]["SEQUENCE_LENGTH"])
#
# vocabulary = data_reader.vocabulary
# sess = tf.Session()
# model = RNNModel(sess,
#                  vocabulary=vocabulary,
#                  batch_size=cfg["model_params"]["LSTM"]["BATCH_SIZE"],
#                  sequence_length=cfg["model_params"]["LSTM"]["SEQUENCE_LENGTH"],
#                  hidden_layer_size=cfg["model_params"]["LSTM"]["HIDDEN_LAYER_SIZE"],
#                  cells_size=cfg["model_params"]["LSTM"]["CELLS_SIZE"],
#                  keep_prob=cfg["model_params"]["LSTM"]["TRAIN_KEEP_PROB"],
#                  gradient_clip=cfg["model_params"]["LSTM"]["GRADIENT_CLIP"],
#                  starter_learning_rate=cfg["model_params"]["LSTM"]["STARTER_LEARNING_RATE"],
#                  decay_rate=cfg["model_params"]["LSTM"]["DECAY_RATE"],
#                  training=False
#                  )
#
# saver = tf.train.Saver()
# sess.run(tf.global_variables_initializer())
# _num = str(max([int(i.replace('ckpt-','')) for i in list(set([i.split('.')[1] for i in os.listdir("src/data") if 'aesop.ckpt-' in i]))]))
# saver.restore(sess, "src/data/aesop.ckpt-{}".format(_num))
print('------')
bot.run(cfg['discord']['token'])


import sys
from utils.shading import *

# other modules
import os
import numpy as np

from torch.autograd import Variable
from torchvision.utils import make_grid
import torch
import time
import cv2
from models.dpr.defineHourglass_1024_gray_skip_matchFeature import *

def get_dpr_network():
    modelFolder = 'trained_model/'

    # load model

    my_network_512 = HourglassNet(16)
    my_network = HourglassNet_1024(my_network_512, 16)
    my_network.load_state_dict(torch.load(os.path.join(modelFolder, 'trained_model_1024_03.t7')))
    my_network.cuda()
    my_network.train(False)

    return my_network


from facenet_pytorch import MTCNN, InceptionResnetV1, extract_face
import torch
from torch.utils.data import DataLoader
from torchvision import datasets
import shutil
from PIL import Image, ImageDraw
import numpy as np
import pandas as pd
import os, shutil, json
from Image_upload.models import Photo

class Face_recognition :

    def __init__(self,model,folder_name):
        self.model = model      # model object
        self.folder_name = folder_name
        self.names = []     # list of image names
        self.face_num_list = []  # face number of each image

    def face_embedding(self):
        '''
        Recognize face in the model's image and save the embedding to the model.

        :param model: The target model
        :param folder_name: Folder Path of the model image
        :return:
        '''
        BASE_DIR = os.path.join(os.getcwd(), 'media', self.folder_name)
        workers = 0 if os.name == 'nt' else 4
        device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
        print('Running on device: {}'.format(device))

        mtcnn = MTCNN(
            image_size=160, margin=0, min_face_size=20,
            thresholds=[0.6, 0.7, 0.7], factor=0.709, post_process=True,
            device=device, keep_all=True
        )
        resnet = InceptionResnetV1(pretrained='vggface2').eval().to(device)

        def collate_fn(x):
            return x[0]

        dataset = datasets.ImageFolder(BASE_DIR)
        dataset.idx_to_class = {i: c for c, i in dataset.class_to_idx.items()}
        loader = DataLoader(dataset, collate_fn=collate_fn, num_workers=workers)

        aligned = []  # aligned tensor of image, element shape:[3,160,160]

        for x, y in loader:
            face_num = 0
            x_aligned, prob = mtcnn(x, return_prob=True)
            if x_aligned is not None:  # if mtcnn detected face ,adding face tensor of to aligned
                for number in prob:
                    print(f'Face detected with probability: {number}')
                for num in range(x_aligned.shape[0]):
                    aligned.append(x_aligned[num])
                    face_num += 1
            else:  # if no face in the image adding 0 tensor to aligned
                aligned.append(torch.zeros([3, 160, 160]))
                print('no detect')
                face_num += 1
            self.face_num_list.append(face_num)

        names = self.names + self.Load_image_name()  # Get all image name in the folder

        aligned = torch.stack(aligned).to(device)
        embeddings = resnet(aligned).detach().cpu()  # calculate face embedding of each face

        embedding_dict = {}
        now = 0
        for j in self.face_num_list:  # create a dict of {image_name:face_tensor(shape of [face_num,512])}
            embedding_dict[f'{names[now]}'] = embeddings[now:now + j, :]
            now += j

        self.embedding_save(embedding_dict)  # save the embedding tensor to the model

        image_path = os.path.join(BASE_DIR, 'image')
        shutil.rmtree(image_path)  # delete classify image
        os.mkdir(image_path)

        dists = [[(e1 - e2).norm().item() for e2 in embeddings] for e1 in
                 embeddings]  # distance table of this image group
        print(pd.DataFrame(dists, columns=names, index=names))

    def compare_image(self):
        '''

        :param target: target image model
        :param model: whole image model
        :return:
        '''
        target = self.model.objects.filter(tag=True)
        photo = self.model.objects.all()
        for target_image in target:
            print(f'\n{target_image.image} start comparing \n')
            for image in photo:
                target_tensor = torch.tensor(json.loads(target_image.embedding))
                image_tensor = torch.tensor(json.loads(image.embedding))
                for i in range(image_tensor.size(0)):
                    threshold = (image_tensor[i] - target_tensor).norm().item()
                    print(f' {image.image} round "{i}" threshold:', threshold)

                    if threshold <= 1:
                        pic = self.model.objects.get(image=f'{str(image.image)}')
                        pic.target_tag = pic.target_tag + f' {target_image.image}'
                        pic.save()
                        print(f'{image.image} save. tag: {image.target_tag}')
                    else:
                        print(image.image, ' are not target')
        return True

    def load_image_name(self):
        '''
        Get whole image name in file
        :param model_name:
        :return:
        '''
        path = os.path.join(os.getcwd(), 'media', self.folder_name, 'image')
        photo_list = os.listdir(path)
        for i in range(len(photo_list)):
            photo_list[i] = 'image/' + photo_list[i]
        print(photo_list)
        image_list = []
        count = 0
        for num in self.face_num_list:
            for i in range(num):
                image_list.append(photo_list[count])
            count += 1
        return image_list

    def embedding_save(self, embedding_dict):
        photos = self.model.objects.all()
        for image in photos:
            try:
                pic = photos.filter(image=f'{str(image.image)}')
                pic.update(embedding=str(embedding_dict[f'{str(image.image)}'].tolist()))

            except:
                continue

        return True

    def check_new_file(self):
        photos = self.model.objects.all()
        path = os.path.join(os.getcwd(), 'media')

        for image in photos:
            # print(f'image name:{image.image} "{image.embedding}"')
            if image.embedding is "":
                image_name = os.path.join(path, str(image.image))
                shutil.copyfile(image_name, image_name.replace('image', self.folder_name + '/image'))
                print(image_name, 'is new')
        return True

    def return_image(self,target_name):
        target = self.model.objects.filter(target_tag__contains=target_name)
        return target


import os
import torch
from torch.nn import functional as F
import torch.distributions as D
import numpy as np
from agent.model import CategoricalPolicy
from agent.agent_base import AgentBase

class AgentReinforce(AgentBase):
    def __init__(
        self,
        config: dict,
        env: object,
        weight_decay: float = 0.0005
    ) -> None:
        super().__init__(config, env)
        self.agent_learning_config = config['agent'][config['args']['mode']]['learning']

        assert config['args']['agent'] == 'reinforce'
        input_size = self.state_tracker.state_dim
        self.gamma = self.agent_learning_config['gamma']

        # policy
        self.policy = CategoricalPolicy(input_size, self.cv_utils.action_feature_size).to(config['device'])

        # setup loss function and optimizer
        self.optimizer_policy = torch.optim.Adam(self.policy.parameters(), lr=self.agent_learning_config['lr'], weight_decay=weight_decay)

        self.update_networks()
        for net_type, nets in self.networks.items():
            for net_id, net in nets.items():
                if isinstance(net, torch.nn.Module):
                    print('%5s: %-10s' % (net_type, net_id), "<class 'torch.nn.Module'>")
                else:
                    print('%5s: %-10s' % (net_type, net_id), type(net))
        return

    def _get_actions_prob(
        self,
        belief_state: torch.Tensor,
        candidate_action_embed: torch.Tensor,
        illegal: torch.Tensor
    ) -> (torch.Tensor, torch.Tensor, torch.Tensor):
        policy_out = self.policy(belief_state, candidate_action_embed)
        policy_out[illegal] = -float('inf')
        actions_prob = F.softmax(policy_out, dim=1)
        tiny_prob = (actions_prob == 0.0).float() * 1e-8
        actions_log_prob = torch.log(actions_prob + tiny_prob)
        return policy_out, actions_prob, actions_log_prob

    def _get_policy_rl_loss(
        self,
        batch_mem: list
    ) -> torch.Tensor or None:
        belief_state, critic_belief_state, action, intent, candidate_action_feature, reward, cummulative_reward, agent_mask, done = batch_mem

        # get policy loss
        illegal = self.intent_to_mask(intents=intent, find_legal=False)
        logit = self.policy(belief_state, candidate_action_feature)
        logit[illegal] = -float('inf')

        logit = logit[agent_mask]
        action = action[agent_mask].squeeze()

        agent_actions_log_prob = F.cross_entropy(logit, action.clone(), reduction='none').unsqueeze(1)
        agent_cummulative_reward = cummulative_reward[agent_mask]

        assert agent_actions_log_prob.shape == agent_cummulative_reward.shape
        if len(agent_actions_log_prob) > 0:
            policy_rl_loss = agent_cummulative_reward * agent_actions_log_prob
            return policy_rl_loss.mean()
        else:
            return None

    def train(
        self,
        agent_mems: list
    ) -> (np.ndarray, float):
        batch_agent_mem = self._get_batch_mem(agent_mems)
        policy_loss = self._get_policy_rl_loss(batch_agent_mem)
        self._update_param(loss=policy_loss, optimizer=self.optimizer_policy, network=self.policy, clip_grad=1)
        policy_loss_float = self._get_float_loss(policy_loss)
        return np.array([0, 0, policy_loss_float, 0, 0]), 0

    def act(
        self,
        location_infos: list,
        instr_embed: torch.Tensor,
        instr_mask: torch.Tensor,
        last_action_features: torch.Tensor,
        hiddens: torch.Tensor,
        evaluate: bool
    ) -> (np.ndarray, torch.Tensor, torch.Tensor):
        # get belief state
        if evaluate:
            belief_states, _, instr_attn_weight, hiddens = self.get_belief_states(
                vision_features=self.cv_utils.get_vision_features(location_infos),
                abs_pose_features=self.cv_utils.get_abs_pose_features(location_infos).squeeze(0),
                action_features=last_action_features,
                instr_embed=instr_embed,
                instr_mask=instr_mask,
                hiddens=hiddens,
                enable_grad=False
            )
        else:
            belief_states, _, instr_attn_weight, hiddens, _ = self.get_belief_states_with_dist(
                vision_features=self.cv_utils.get_vision_features(location_infos),
                abs_pose_features=self.cv_utils.get_abs_pose_features(location_infos).squeeze(0),
                action_features=last_action_features,
                instr_embed=instr_embed,
                instr_mask=instr_mask,
                hiddens=hiddens,
                enable_grad=False
            )

        with torch.no_grad():
            # get candidate action features
            candidate_action_features = self.cv_utils.get_candidate_action_features(location_infos).squeeze(0)

            # generate actions
            legals = self.intent_to_mask(
                intents=[location_info.action_info.intents for location_info in location_infos],
                find_legal=True
            )
            policy_out = self.policy(belief_states, candidate_action_features)
            illegal = torch.logical_not(torch.tensor(legals, dtype=torch.bool))
            policy_out[illegal] = -float('inf')
            if evaluate:
                # select action by greedy
                actions = torch.argmax(policy_out, dim=1).cpu().view(-1).numpy()
            else:
                # sample action from categorical distribution
                actions_prob = F.softmax(policy_out, dim=1)
                actions_dist = D.Categorical(actions_prob)
                actions = actions_dist.sample().cpu().view(-1).numpy()
        return actions, candidate_action_features, hiddens

    def load_pre_train(
        self,
        load_dir: str
    ) -> None:
        models = {
            'pomdp': [self.config['args']['state_tracker']],
            'obs': ['vision', 'instr'],
            'agent': ['policy']
        }

        for net_type, net_ids in models.items():
            for net_id in net_ids:
                net_dir = os.path.join(load_dir, '%s_%s.pt' % (net_type, net_id))
                self.networks[net_type][net_id].load_state_dict(torch.load(net_dir))
                if net_type != 'agent':
                    self.networks[net_type][net_id].eval()
                    for param in self.networks[net_type][net_id].parameters():
                        param.requires_grad = False
                print('load %s_%s from %s' % (net_type, net_id, net_dir))
        return

def main():
    return

if __name__ == '__main__':
    main()


import sys
import os
import time
import argparse
import param
import logging
import pickle
import numpy as np

logging.basicConfig(format='%(message)s', level=logging.INFO)
base2num = dict(zip("ACGT",(0, 1, 2, 3)))
num2base = dict(zip((0, 1, 2, 3),"ACGT"))

def Run(args):
    # create a Clairvoyante
    if args.v2 == True:
        import utils_v2 as utils
        if args.slim == True:
            import clairvoyante_v2_slim as cv
        else:
            import clairvoyante_v2 as cv
    elif args.v3 == True:
        import utils_v2 as utils # v3 network is using v2 utils
        if args.slim == True:
            import clairvoyante_v3_slim as cv
        else:
            import clairvoyante_v3 as cv
    utils.SetupEnv()
    m = cv.Clairvoyante()
    m.init()

    if args.bin_fn != None:
        with open(args.bin_fn, "rb") as fh:
            total = pickle.load(fh)
            XArrayCompressed = pickle.load(fh)
            YArrayCompressed = pickle.load(fh)
            posArrayCompressed = pickle.load(fh)
    else:
        total, XArrayCompressed, YArrayCompressed, posArrayCompressed = \
        utils.GetTrainingArray(args.tensor_fn,
                               args.var_fn,
                               args.bed_fn)

    with open(args.chkpnt_list) as fh:
        for row in fh:
            row = row.rstrip()
            logging.info("Working on model: %s" % (row))
            m.restoreParameters(os.path.abspath(row))
            Test(args, m, utils, total, XArrayCompressed, YArrayCompressed, posArrayCompressed)

def Test(args, m, utils, total, XArrayCompressed, YArrayCompressed, posArrayCompressed):
    predictBatchSize = param.predictBatchSize
    predictStart = time.time()
    if args.v2 == True or args.v3 == True:
        datasetPtr = 0
        XBatch, _, _ = utils.DecompressArray(XArrayCompressed, datasetPtr, predictBatchSize, total)
        bases = []; zs = []; ts = []; ls = []
        base, z, t, l = m.predict(XBatch)
        bases.append(base); zs.append(z); ts.append(t); ls.append(l)
        datasetPtr += predictBatchSize
        while datasetPtr < total:
            XBatch, _, endFlag = utils.DecompressArray(XArrayCompressed, datasetPtr, predictBatchSize, total)
            base, z, t, l = m.predict(XBatch)
            bases.append(base); zs.append(z); ts.append(t); ls.append(l)
            datasetPtr += predictBatchSize
            if endFlag != 0:
                break
        bases = np.concatenate(bases[:])
        zs = np.concatenate(zs[:])
        ts = np.concatenate(ts[:])
        ls = np.concatenate(ls[:])
    logging.info("Prediciton time elapsed: %.2f s" % (time.time() - predictStart))

    YArray, _, _ = utils.DecompressArray(YArrayCompressed, 0, total, total)
    if args.v2 == True or args.v3 == True:
        logging.info("Version 2 model, evaluation on base change:")
        allBaseCount = top1Count = top2Count = 0
        for predictV, annotateV in zip(bases, YArray[:,0:4]):
            allBaseCount += 1
            sortPredictV = predictV.argsort()[::-1]
            if np.argmax(annotateV) == sortPredictV[0]:
                top1Count += 1
                top2Count += 1
            elif np.argmax(annotateV) == sortPredictV[1]:
                top2Count += 1
        logging.info("all/top1/top2/top1p/top2p: %d/%d/%d/%.2f/%.2f" % (allBaseCount, top1Count, top2Count, float(top1Count)/allBaseCount*100, float(top2Count)/allBaseCount*100))
        logging.info("Version 2 model, evaluation on Zygosity:")
        ed = np.zeros( (2,2), dtype=np.int )
        for predictV, annotateV in zip(zs, YArray[:,4:6]):
            ed[np.argmax(annotateV)][np.argmax(predictV)] += 1
        for i in range(2):
            logging.info("\t".join([str(ed[i][j]) for j in range(2)]))
        logging.info("Version 2 model, evaluation on variant type:")
        ed = np.zeros( (4,4), dtype=np.int )
        for predictV, annotateV in zip(ts, YArray[:,6:10]):
            ed[np.argmax(annotateV)][np.argmax(predictV)] += 1
        for i in range(4):
            logging.info("\t".join([str(ed[i][j]) for j in range(4)]))
        logging.info("Version 2 model, evaluation on indel length:")
        ed = np.zeros( (6,6), dtype=np.int )
        for predictV, annotateV in zip(ls, YArray[:,10:16]):
            ed[np.argmax(annotateV)][np.argmax(predictV)] += 1
        for i in range(6):
            logging.info("\t".join([str(ed[i][j]) for j in range(6)]))

def main():
    parser = argparse.ArgumentParser(
            description="Evaluate trained Clairvoyante model" )

    parser.add_argument('--bin_fn', type=str, default = None,
            help="Binary tensor input generated by tensor2Bin.py, tensor_fn, var_fn and bed_fn will be ignored")

    parser.add_argument('--tensor_fn', type=str, default = "vartensors",
            help="Tensor input")

    parser.add_argument('--var_fn', type=str, default = "truthvars",
            help="Truth variants list input")

    parser.add_argument('--bed_fn', type=str, default = None,
            help="High confident genome regions input in the BED format")

    parser.add_argument('--chkpnt_list', type=str, default = None,
            help="Input a list of checkpoints for testing")

    parser.add_argument('--v3', type=param.str2bool, nargs='?', const=True, default = True,
            help="Use Clairvoyante version 3")

    parser.add_argument('--v2', type=param.str2bool, nargs='?', const=True, default = False,
            help="Use Clairvoyante version 2")

    parser.add_argument('--slim', type=param.str2bool, nargs='?', const=True, default = False,
            help="Train using the slim version of Clairvoyante, optional")

    args = parser.parse_args()

    if len(sys.argv[1:]) == 0:
        parser.print_help()
        sys.exit(1)

    Run(args)

if __name__ == "__main__":
    main()


import cv2
import os
import time
import numpy as np
from net.mtcnn import mtcnn
import utils.utils as utils
from net.inception import InceptionResNetV1
import RPi.GPIO as GPIO
import signal
import atexit
import threading

# 初始化舵机
atexit.register(GPIO.cleanup)
servopin = 17
GPIO.setmode(GPIO.BCM)
GPIO.setup(servopin, GPIO.OUT, initial=False)
pwm = GPIO.PWM(servopin, 50)  # 50HZ
pwm.start(0)
# 利用Event类模拟信号量
event = threading.Event()

def ControlMotor(angle):
    # 舵机的频率为50HZ，占空比为2.5%-12.5%，线性对应舵机转动角度的0-180度
    pwm.ChangeDutyCycle(2.5 + angle / 360 * 20)

def lock_wait():
    while True:
        event.wait()
        print("\33[42;1mdetected face! unlocking...\033[0m")
        ControlMotor(180)
        time.sleep(5)
        ControlMotor(0)
        time.sleep(10)  # 10s 内不再次开锁
        event.clear()

class face_rec:
    def __init__(self):
        # 创建 mtcnn 对象
        # 检测图片中的人脸
        self.mtcnn_model = mtcnn()
        # 门限函数
        self.threshold = [0.5, 0.8, 0.9]

        # 载入 facenet
        # 将检测到的人脸转化为128维的向量
        self.facenet_model = InceptionResNetV1()
        # model.summary()
        # 加载模型权重只需要15s 而加载图像文件夹则需30s以上
        model_path = './model_data/facenet_keras.h5'
        self.facenet_model.load_weights(model_path)

        time2 = time.time()
        # ----------------------------------------------- #
        #   对数据库中的人脸进行编码
        #   known_face_encodings中存储的是编码后的人脸
        #   known_face_names为人脸的名字
        # ----------------------------------------------- #
        face_list = os.listdir("face_dataset")

        self.known_face_encodings = []

        self.known_face_names = []

        for face in face_list:
            name = face.split(".")[0]

            img = cv2.imread("./face_dataset/"+face)
            img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

            # 检测人脸
            rectangles = self.mtcnn_model.detectFace(img, self.threshold)

            # 转化成正方形
            rectangles = utils.rect2square(np.array(rectangles))
            # facenet要传入一个160x160的图片
            rectangle = rectangles[0]
            # 记下他们的landmark
            landmark = (np.reshape(rectangle[5:15],(5,2)) - np.array([int(rectangle[0]),int(rectangle[1])]))/(rectangle[3]-rectangle[1])*160

            crop_img = img[int(rectangle[1]):int(rectangle[3]), int(rectangle[0]):int(rectangle[2])]
            crop_img = cv2.resize(crop_img,(160,160))

            new_img,_ = utils.Alignment_1(crop_img,landmark)

            new_img = np.expand_dims(new_img,0)
            # 将检测到的人脸传入到facenet的模型中，实现128维特征向量的提取
            face_encoding = utils.calc_128_vec(self.facenet_model,new_img)

            self.known_face_encodings.append(face_encoding)
            self.known_face_names.append(name)

        time3 = time.time()
        print('init faceDataSet use: ', end='')
        print("{:.2f}".format(time3-time2))

    def recognize(self, draw):
        # -----------------------------------------------#
        #   人脸识别
        #   先定位，再进行数据库匹配
        # -----------------------------------------------#
        height, width, _ = np.shape(draw)
        draw_rgb = cv2.cvtColor(draw, cv2.COLOR_BGR2RGB)

        # 检测人脸
        rectangles = self.mtcnn_model.detectFace(draw_rgb, self.threshold)

        if len(rectangles) == 0:
            return

        # 转化成正方形
        rectangles = utils.rect2square(np.array(rectangles, dtype=np.int32))
        rectangles[:, 0] = np.clip(rectangles[:, 0], 0, width)
        rectangles[:, 1] = np.clip(rectangles[:, 1], 0, height)
        rectangles[:, 2] = np.clip(rectangles[:, 2], 0, width)
        rectangles[:, 3] = np.clip(rectangles[:, 3], 0, height)
        # -----------------------------------------------#
        #   对检测到的人脸进行编码
        # -----------------------------------------------#
        face_encodings = []
        for rectangle in rectangles:
            landmark = (np.reshape(rectangle[5:15], (5, 2)) - np.array([int(rectangle[0]), int(rectangle[1])])) / (
                        rectangle[3] - rectangle[1]) * 160

            crop_img = draw_rgb[int(rectangle[1]):int(rectangle[3]), int(rectangle[0]):int(rectangle[2])]
            crop_img = cv2.resize(crop_img, (160, 160))

            new_img, _ = utils.Alignment_1(crop_img, landmark)
            new_img = np.expand_dims(new_img, 0)

            face_encoding = utils.calc_128_vec(self.facenet_model, new_img)
            face_encodings.append(face_encoding)

        face_names = []
        distances = []
        for face_encoding in face_encodings:
            # 取出一张脸并与数据库中所有的人脸进行对比，计算得分
            matches = utils.compare_faces(self.known_face_encodings, face_encoding, tolerance=0.7)
            name = "Unknown"
            # 找出距离最近的人脸
            face_distances = utils.face_distance(self.known_face_encodings, face_encoding)
            # 取出这个最近人脸的评分
            best_match_index = np.argmin(face_distances)
            dis = face_distances[best_match_index]
            if matches[best_match_index]:
                name = self.known_face_names[best_match_index]
                print(name+" ---> "+str(dis))

                event.set()  # 设置信号量，异步调用开锁函数

            face_names.append(name)
            distances.append(dis)

        rectangles = rectangles[:, 0:4]
        # -----------------------------------------------#
        #   画框~!~
        # -----------------------------------------------#
        for (left, top, right, bottom), name, dis in zip(rectangles, face_names, distances):
            cv2.rectangle(draw, (left, top), (right, bottom), (0, 0, 255), 2)

            font = cv2.FONT_HERSHEY_SIMPLEX
            cv2.putText(draw, name, (left, bottom - 15), font, 0.75, (255, 255, 255), 2)
            cv2.putText(draw, str(dis), (right, bottom - 15), font, 0.75, (0, 0, 255), 2)
        return draw

def run():
    diudiudiu = face_rec()
    video_capture = cv2.VideoCapture(0)

    num_frames = 0
    since = time.time()
    while True:
        time.sleep(0.5)
        ret, draw = video_capture.read()
        diudiudiu.recognize(draw)
        # put the text into video
        num_frames += 1
        # cv2.putText(draw, f'FPS{num_frames / (time.time() - since):.2f}', (50, 50), cv2.FONT_HERSHEY_SIMPLEX, 1.2,
        #             (0, 0, 255), 2)
        fps = num_frames / (time.time() - since)
        print('FPS: ', end='')
        print('%.2f' % fps)
        # cv2.imshow('Video', draw)
        if cv2.waitKey(20) & 0xFF == ord('q'):
            break

    video_capture.release()
    cv2.destroyAllWindows()

if __name__ == "__main__":
    # 多线程调用
    run = threading.Thread(target=run)
    run.start()
    lock_wait = threading.Thread(target=lock_wait)
    lock_wait.start()


import numpy as np
import cv2
import utils
import argparse
from time import sleep
from imutils.video import FPS
from datetime import datetime
# from multiprocessing import Process, Queue
from threading import Thread
from queue import Queue
from detector.yolo.yolo import NCSYolo, yolo_get_candidate_objects, YoloObjectDetector
from mvnc import mvncapi as mvnc

class MvncsDetector(NCSYolo):
    """ """
    def __init__(self, model, win_name='', use_threads=True):
        super().__init__(model)
        self.graph.SetGraphOption(mvnc.GraphOption.DONT_BLOCK, 1)
        self.net_out    = None
        self.bboxes     = None
        self.in_frame   = None
        self.prev_frame = None
        self.preproc    = None
        self.started    = False
        self.win_name   = win_name
        self.use_threads = use_threads
        cv2.namedWindow(self.win_name, cv2.WINDOW_NORMAL)
        if use_threads is True:
            self.inp_q   = Queue(7)
            self.stopped = False
            Thread(target=self.det_process).start()

    def det_process(self):
        while True:
            frame, preproc = self.inp_q.get()
            self.inp_q.task_done()
            if self.started is False:
                self.fps = FPS().start()
                self.started = True
            if frame is None: break
            if self.stopped is True: break
            self.process_frame(frame, preproc)
        print ('Thread Exits')

    def process_frame(self, frame, preproc):
        self.graph.LoadTensor(preproc, 'frame')

        # Process output of the previous frame
        if self.net_out is not None:
            out_shape = self.net_out.shape
            if self.model['out_size'] is not None:
                out_size = self.model['out_size']
                self.net_out = self.net_out.reshape(out_size)
                self.net_out = np.transpose(self.net_out, [2, 0, 1])
            self.net_out = self.net_out.astype(np.float32)
            self.bboxes = yolo_get_candidate_objects(self.net_out, self.prev_frame.shape)
            utils.draw_detections(self.prev_frame, self.bboxes)
            cv2.imshow(self.win_name, self.prev_frame)
            cv2.waitKey(10)
            self.fps.update()

        # Set the next input frame
        self.prev_frame = frame

        # Run network on the current frame
        self.net_out = None
        while self.net_out is None:
            self.net_out, obj = self.graph.GetResult()

    def call_th(self, frame):
        stop = False
        if utils.Esc_key_pressed():
            stop = True
            self.fps.stop()
            print("Elapsed = {:.2f}".format(self.fps.elapsed()))
            print("FPS     = {:.2f}".format(self.fps.fps()))
            preproc = None
            frame   = None
            self.stopped = True
        else:
            preproc = self.preprocess(frame)

        self.inp_q.put((frame, preproc))
        return stop

    def call_noth(self, frame):
        print('Time = ', datetime.now() - self.last_call)
        stop = False
        if utils.Esc_key_pressed():
            stop = True
            self.fps.stop()
            print("Elapsed = {:.2f}".format(self.fps.elapsed()))
            print("FPS     = {:.2f}".format(self.fps.fps()))

        # Preprocess Current frame
        if self.started is True:
            self.graph.LoadTensor(self.preproc, 'image')

        # Process output of the previous frame
        if self.net_out is not None:
            out_shape = self.net_out.shape
            if self.model['out_size'] is not None:
                out_size = self.model['out_size']
                self.net_out = self.net_out.reshape(out_size)
                self.net_out = np.transpose(self.net_out, [2, 0, 1])
            self.net_out = self.net_out.astype(np.float32)
            self.bboxes = yolo_get_candidate_objects(self.net_out, self.in_frame.shape)
            utils.draw_detections(self.prev_frame, self.bboxes)
            cv2.imshow(self.win_name, self.prev_frame)
            self.fps.update()

        # Set the nest input frame
        t1 = datetime.now()
        self.prev_frame = self.in_frame
        self.in_frame   = frame
        self.preproc    = self.preprocess(self.in_frame)
        print('pre_proc = ', datetime.now() - t1)

        # Run network on the current frame
        self.net_out = None
        if self.started is True:
            while self.net_out is None:
                self.net_out, obj = self.graph.GetResult()
        else:
            self.started = True
            self.fps = FPS().start()

        self.last_call  = datetime.now()
        return stop

    def __call__(self, frame):
        return self.call_th(frame)

def main():

    parser = argparse.ArgumentParser()
    parser.add_argument('-v', '--video', default='')
    parser.add_argument('-m', '--model', default='')
    args = parser.parse_args()
    cam_id = args.video if args.video else 0
    model  = args.model
    print ("PROFILING Model :  ", model)
    pi_cam = utils.get_default_cam(cam_id=cam_id,
                                    win_name='Pi Camera Object Detection',
                                    resolution=(640, 480))
    mvnc_det = MvncsDetector(model, pi_cam.name)
    pi_cam.start_video_capture(capture_cb=mvnc_det)
    mvnc_det.close()
    print ('END')

if __name__ == "__main__":
    main()


import os
import glob
import time
import numpy
import warnings
import progressbar

from lwa352_pipeline_control import Lwa352PipelineControl
from casacore import tables

import astropy.units as u
from astropy.time import Time, TimeDelta
from astropy.coordinates import SkyCoord, EarthLocation, AltAz
from astropy.coordinates import solar_system_ephemeris, get_body
from astropy.constants import c as speedOfLight
speedOfLight = speedOfLight.to('m/ns').value

from common import NPIPELINE, chan_to_freq
from station import ovro

NCHAN_PIPELINE = 96
NPIPELINE_SUBBAND = 2
NPIPELINE_SERVER = 4

NSUBBAND = NPIPELINE // NPIPELINE_SUBBAND
NSERVER = NPIPELINE // NPIPELINE_SERVER

NSTAND = 352
NPOL = 2

class AllowedPipelineFailure(object):
    """
    Context manager to ignore failures while controlling the pipelines.
    """

    def __init__(self, pipeline):
        self.pipeline = pipeline

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc_value, exc_traceback):
        if exc_type:
            warnings.warn(f"Failed to command {self.pipeline.host} (pipeline {self.pipeline.pipeline_id})")
        return True

class BeamPointingControl(object):
    """
    Class to provide high level control over beam 1 (and only beam 1 right now).
    """

    def __init__(self, servers=None, nserver=8, npipeline_per_server=4, station=ovro):
        # Validate
        assert(nserver <= NSERVER)
        assert(nserver*npipeline_per_server <= NPIPELINE)
        if servers is not None:
            assert(len(servers) <= NSERVER)

        # Save the station so that we know where to point from
        self.station = station

        # Figure out the servers to control
        if servers is None:
            servers = []
            for s in range(nserver):
                servers.append(f"lxdlwagpu{s+1:02d}")

        # Contect to the pipelines
        self.pipelines = []
        for hostname in servers:
            for i in range(npipeline_per_server):
                p = Lwa352PipelineControl(hostname, i, etcdhost='etcdv3service')
                self.pipelines.append(p)

        # Query the pipelines to figure out the frequency ranges they are sending
        self.freqs = []
        for p in self.pipelines:
            metadata = p.beamform.get_bifrost_status()
            freq = chan_to_freq(metadata['chan0'] + numpy.arange(metadata['nchan']))
            self.freqs.append(freq)

        # Make a variable to track the per-pipeline calibration state
        self._cal_set = [False for p in self.pipelines]

        # Make a variable to keep track of a "gain"
        self._gain = 1.0

    @property
    def cal_set(self):
        """
        Boolean as to whether or not all pipelines have had a calibration set.
        """

        return all(self._cal_set)

    def set_beam1_dest(self, addr='10.41.0.25', port=20001):
        """
        Set the destination IP address and UDP port for the beam data.  Defaults
        to what is currently used by the "dr-beam-1" service on lxdlwagpu09.
        """

        for p in self.pipelines:
            with AllowedPipelineFailure(p):
                p.beamform_output.set_destination([addr] + ['0.0.0.0']*15, [port])

    def set_beam1_vlbi_dest(self, addr='10.41.0.25', port=21001):
        """
        Set the destination IP address and UDP port for the VLBI version of the
        beam data.  Defaults to 10.41.0.25, port 21001 (on lxdlwagpu09).
        """

        for p in self.pipelines:
            with AllowedPipelineFailure(p):
                p.beamform_vlbi_output.set_destination(addr, port)

    def _freq_to_pipeline(self, freq_to_find):
        """
        Given a frequency in Hz, return the pipeline index where that frequency
        can be found in the data.  Raises a ValueError if there does not appear
        to be a corresponding pipeline.
        """

        for i,freq in enumerate(self.freqs):
            if freq_to_find >= freq[0] and freq_to_find <= freq[-1]:
                return i
        raise ValueError(f"Cannot associate {freq_to_find/1e6:.3f} MHz with any pipeline currently under control")

    def set_beam1_calibration(self, caltable, verbose=True):
        """
        Given a a CASA measurement set containing a bandpass calibration, load
        the bandpass calibration into the appropriate pipeline(s).
        """

        # Validate
        assert(os.path.exists(caltable))
        assert(os.path.isdir(caltable))
        assert(os.path.exists(os.path.join(caltable, 'SPECTRAL_WINDOW')))
        assert(os.path.isdir(os.path.join(caltable, 'SPECTRAL_WINDOW')))

        # Load in the calibration data and normalize it
        tab = tables.table(caltable, ack=False)
        caldata = tab.getcol('CPARAM')[...]
        caldata /= numpy.abs(caldata)
        tab.close()

        # Load in the frequency information for the calibration
        tab = tables.table(os.path.join(caltable, 'SPECTRAL_WINDOW'), ack=False)
        calfreq = tab.getcol('CHAN_FREQ')[...]
        calfreq = calfreq.ravel()
        tab.close()

        if verbose:
            print(f"Loaded {caldata.shape[0]} by {caldata.shape[1]} by {caldata.shape[2]} complex gains covering {calfreq[0]/1e6:.3f} to {calfreq[-1]/1e6:.3f} MHz")

        # Validate the calibration data structure
        assert(caldata.shape[0] == NSTAND)
        assert(caldata.shape[1] == NCHAN_PIPELINE*NPIPELINE_SUBBAND)
        assert(caldata.shape[2] == NPOL)

        # Find the pipelines that should correspond to the specified subband
        # TODO: Use the freuqency information to figure this out for the user
        subband_pipelines = []
        for i in range(NPIPELINE_SUBBAND):
            ## Get the frequency range for the pipeline in the subband and pull
            ## out the middle
            center_freq = calfreq[i*NCHAN_PIPELINE:(i+1)*NCHAN_PIPELINE]
            center_freq = center_freq[center_freq.size//2]

            ## Try to map that frequency to a pipeline.  If it works, save the
            ## pipeline to subband_pipelines.
            try:
                j = self._freq_to_pipeline(center_freq)
                subband_pipelines.append(self.pipelines[j])
                if verbose:
                    print(f"Found pipeline {j} covering {self.freqs[j][0]/1e6:.3f} to {self.freqs[j][-1]/1e6:.3f} MHz")
            except ValueError:
                pass

        # Issue a warning if we don't seem to have the right number of pipelines
        # for the subband
        if len(subband_pipelines) != NPIPELINE_SUBBAND:
            warnings.warn(f"Found {len(subband_pipelines)} pipelines associated with these data instead of the expected {NPIPELINE_SUBBAND}")

        # Set the coefficients - this is slow
        pb = progressbar.ProgressBar(redirect_stdout=True)
        pb.start(max_value=len(subband_pipelines)*NSTAND)
        for i,p in enumerate(subband_pipelines):
            for j in range(NSTAND):
                for pol in range(NPOL):
                    cal = 1./caldata[j,i*NCHAN_PIPELINE:(i+1)*NCHAN_PIPELINE,pol].ravel()
                    with AllowedPipelineFailure(p):
                        p.beamform.update_calibration_gains(pol, NPOL*j+pol, cal)
                pb += 1
            self._cal_set[i] = True
        pb.finish()

    def set_beam1_gain(self, gain):
        """
        Set the "gain" for beam 1 - this is a multiplicative scalar used during
        beamforming.

        .. note:: A change to the gain can only activated by an update to the
                  pointing direction.
        """

        assert(gain >= 0)
        self._gain = float(gain)

    def set_beam1_delays(self, delays, pol=0):
        """
        Set the beamformer delays to the specified values in ns for the given
        polarization.
        """

        # Validate
        assert(delays.size == NSTAND*NPOL)

        # Make up some dummy amplitudes
        amps = numpy.zeros(NSTAND*NPOL, dtype=numpy.float32)
        amps[pol::NPOL] = self._gain
        # TODO: Remove this when we are done with it
        amps[64:] *= 0

        # Set the delays and amplitudes
        pb = progressbar.ProgressBar(redirect_stdout=True)
        pb.start(max_value=len(self.pipelines))
        for p in self.pipelines:
            with AllowedPipelineFailure(p):
                p.beamform.update_delays(pol, delays, amps)
            pb += 1
        pb.finish()

    def set_beam1_pointing(self, az, alt, degrees=True):
        """
        Given a topocentric pointing in azimuth and altitude (elevation), point
        the beam in that direction.  The `degrees` keyword determines if the
        coordinates are interpreted in degrees (True) or radians (False).
        """

        # Issue a warning if it doesn't look like we've been calibrated
        if not self.cal_set:
            warnings.warn("Calibration is not set, your results may be suspect")

        # Convertion from degrees -> radians, plus a validation
        if degrees:
            az *= numpy.pi/180.0
            alt *= numpy.pi/180.0
        assert(az >= 0 and az < 2*numpy.pi)
        assert(alt >= 0 and alt <= numpy.pi/2)

        # Figure out what the delays to zenith are
        # TODO: Is this needed?
        zen = numpy.array([0, 0, 1])
        zen_delay = [numpy.dot(zen, ant.enz)/speedOfLight for ant in self.station.antennas]

        # Figure out what the delays to the pointing direction are
        dir = numpy.array([numpy.cos(alt)*numpy.sin(az),
                           numpy.cos(alt)*numpy.cos(az),
                           numpy.sin(alt)])
        dir_delay = [numpy.dot(dir, ant.enz)/speedOfLight for ant in self.station.antennas]

        # Subtract what we need from what we have from the calibration
        # TODO: Is this correct?
        delays = numpy.array(dir_delay) - numpy.array(zen_delay)
        delays = numpy.repeat(delays, NPOL)
        delays = delays.max() - delays

        # Apply
        for pol in range(NPOL):
            self.set_beam1_delays(delays, pol)

    def set_beam1_target(self, target, verbose=True):
        """
        Given the name of an astronomical target, 'sun', or 'zenith', compute the
        current topocentric position of the body and point the beam at it.
        """

        # Figure out what to do with the name
        if target.lower() in ('z', 'zen', 'zenith'):
            ## Zenith is easy
            az, alt = 0.0, 90.0
        else:
            ## Load in where we are
            obs = EarthLocation.from_geocentric(*self.station.ecef, unit=u.m)

            ## Resolve the name into coordinates
            if target.lower() in solar_system_ephemeris.bodies:
                if target.lower().startswith('earth'):
                    raise ValueError(f"Invalid target: '{target}'")

                sc = get_body(target.lower(), Time.now(), location=obs)
                if verbose:
                    print(f"Resolved '{target}' to {target.lower()}")
            else:
                sc = SkyCoord.from_name(target)
                if verbose:
                    print(f"Resolved '{target}' to RA {sc.ra}, Dec. {sc.dec}")

            ## Figure out where it is right now
            aa = sc.transform_to(AltAz(obstime=Time.now(), location=obs))
            az = aa.az.deg
            alt = aa.alt.deg
            if verbose:
                print(f"Currently at azimuth {aa.az}, altitude {aa.alt}")

        # Point the beam
        self.set_beam1_pointing(az, alt, degrees=True)

class BeamTracker(object):
    """
    Simple class to track a target using a fully calibrated BeamPointingControl
    instance.
    """

    def __init__(self, control_instance, update_interval=30):
        self.control_instance = control_instance
        self.update_interval = update_interval

    def track(self, target, duration=0, verbose=True):
        """
        Given a target name and a tracking duration in seconds, start tracking
        the source.  If the duration is less than or equal to zero the default
        of 12 hours is used.

        .. note:: The tracking can be canceled at any time with a control-C.
        """

        # Load in where we are
        obs = EarthLocation.from_geocentric(*self.control_instance.station.ecef, unit=u.m)

        # Resolve the name into coordinates
        if target.lower() in solar_system_ephemeris.bodies:
            if target.lower().startswith('earth'):
                raise ValueError(f"Invalid target: '{target}'")

            sc = get_body(target.lower(), Time.now(), location=obs)
            if verbose:
                print(f"Resolved '{target}' to {target.lower()}")
        else:
            sc = SkyCoord.from_name(target)
            if verbose:
                print(f"Resolved '{target}' to RA {sc.ra}, Dec. {sc.dec}")

        # Figure out the duration of the tracking
        if duration <= 0:
            duration = 86400.0/2

        # Set the pointing update time offset - this is half the update interval
        # so that we should end up with a nice scalloped pattern
        puto = TimeDelta(self.update_interval/2.0, format='sec')

        # Set the tracking stop time
        t_stop = time.time() + duration

        try:
            # Go!
            t = time.time()
            while t < t_stop:
                ## Get a time marker so that we can account for how long the
                ## update takes
                t_mark = time.time()

                ## Figure out where the target will be in puto seconds
                aa = sc.transform_to(AltAz(obstime=Time.now()+puto, location=obs))
                az = aa.az.deg
                alt = aa.alt.deg
                if verbose:
                    print(f"At {time.time():.1f}, moving to azimuth {aa.az}, altitude {aa.alt}")

                ## Point
                self.control_instance.set_beam1_pointing(az, alt, degrees=True)

                ## Find how much time we used and when we should sleep until
                t_used = time.time() - t_mark
                t_sleep_until = t + self.update_interval - t_used

                ## Sleep to wait it out in increments of 0.5 s so that a control-C
                ## doesn't take forever to register
                while t < t_sleep_until:
                    time.sleep(0.5)
                    t = time.time()

        except KeyboardInterrupt:
            # We gave up, end it now
            pass

def create_and_calibrate(servers=None, nserver=8, npipeline_per_server=4, cal_directory='/home/ubuntu/mmanders'):
    """
    Wraper to create a new BeamPointingControl instance and load bandpass
    calibration data from a directory.
    """

    # Create the instance
    control_instance = BeamPointingControl(servers=servers,
                                           nserver=nserver,
                                           npipeline_per_server=npipeline_per_server,
                                           station=ovro)

    # Find the calibration files
    calfiles = glob.glob(os.path.join(cal_directory, '*.bcal'))
    calfiles.sort()
    if len(calfiles) == 0:
        warnings.warn(f"No calibration data found in '{cal_directory}'")

    # Load the calibration data, if found
    for calfile in calfiles:
        control_instance.set_beam1_calibration(calfile)

    # Start up the data flow
    control_instance.set_beam1_dest()
    control_instance.set_beam1_vlbi_dest()

    # Done
    return control_instance

import numpy,import astropy,from astropy