import streamlit as st

def main():
    st.title('웹 대시보드')

    name = '홍길동'
    print('제 이름은 {} 입니다.'.format(name))
    # 문자열포멧팅
    # print는 터미널에만 출력된다.

    st.text('제 이름은 {} 입니다.'.format(name))
    # st.를 써야 앱에 뜸

    st.header('이 영역은 헤더 영역')
    st.subheader('이 영역은 서브 헤더')

    st.success('성공했을때 나타내고 싶은 문장')
    st.warning('경고하고싶을때 나타내고 싶은 문장')

    st.info('알림을 주고 싶을 때')
    st.error('문제가 발생했음을 알려주고싶을때')

    st.help(range) # 설명을 보여주고 싶을 때

if __name__ == '__main__':
    main()


from flask import Blueprint

from app import models
from app.utils import send_result

api = Blueprint('categories', __name__)

# categories = [
#     {'id': 1, 'name': "birthday cake",
#      'subcategory':
#          [
#              {
#                  "sub_id": 1,
#                  "sub_name": "chiffon cake"
#              },
#              {
#                  "sub_id": 2,
#                  "sub_name": "pound cake"
#              },
#              {
#                  "sub_id": 3,
#                  "sub_name": "fruit cake"
#              }
#          ]
#      }
# ]

@api.route('', methods=['GET'])
def get_all():
    t = [x.json() for x in models.Category.query.all()]
    for i in t:
        i["subcategory"] = [x.json() for x in models.Subcategory.get_by_id_category(i['id'])]
    return send_result(t)


import torch
import torch.nn as nn

from typing import Optional

from .attention_block import CrossAttentionBlock

class PerceiverDecoder(nn.Module):

    def __init__(
        self,
        latent_dim: int,
        q_dim: int,
        heads: int = 4,
        qk_out_dim: Optional[int] = None,
        v_out_dim: Optional[int] = None,
        projection_dim: Optional[int] = None,
        cross_attn_widening_factor: int = 1,
        dropout: float = 0.0
        ):

        super().__init__()
        self.cross_attn = CrossAttentionBlock(
            q_dim=q_dim,
            kv_dim=latent_dim,
            qk_out_dim=qk_out_dim,
            v_out_dim=v_out_dim,
            heads=heads,
            widening_factor=cross_attn_widening_factor,
            dropout=dropout
        )

        if projection_dim is not None:
            self.projection = nn.Linear(q_dim, projection_dim)
        else:
            self.projection = nn.Identity()

    def forward(self, x_q: torch.Tensor, latents: torch.Tensor, query_mask: Optional[torch.Tensor] = None):

        output = self.cross_attn(
            x_q=x_q,
            x_kv=latents,
            attention_mask=query_mask
        )

        return self.projection(output)


import torch

from torch.nn import BCELoss
from vegans.utils import WassersteinLoss
from vegans.utils.networks import Generator, Adversary, Encoder
from vegans.models.unconditional.AbstractGenerativeModel import AbstractGenerativeModel

class AbstractGANGAE(AbstractGenerativeModel):
    """ Abstract class for GAN with structure of one generator, one discriminator / critic and
    one encoder. Examples are the `LRGAN`, `VAEGAN` and `BicycleGAN`.

    Parameters
    ----------
    generator: nn.Module
        Generator architecture. Produces output in the real space.
    adversary: nn.Module
        Adversary architecture. Produces predictions for real and fake samples to differentiate them.
    encoder : nn.Module
        Encoder architecture. Produces predictions in the latent space.
    x_dim : list, tuple
        Number of the output dimensions of the generator and input dimension of the discriminator / critic.
        In the case of images this will be [nr_channels, nr_height_pixels, nr_width_pixels].
    z_dim : int, list, tuple
        Number of the latent dimensions for the generator input. Might have dimensions of an image.
    optim : dict or torch.optim
        Optimizer used for each network. Could be either an optimizer from torch.optim or a dictionary with network
        name keys and torch.optim as value, i.e. {"Generator": torch.optim.Adam}.
    optim_kwargs : dict
        Optimizer keyword arguments used for each network. Must be a dictionary with network
        name keys and dictionary with keyword arguments as value, i.e. {"Generator": {"lr": 0.0001}}.
    feature_layer : torch.nn.*
        Output layer used to compute the feature loss. Should be from either the discriminator or critic.
        If `feature_layer` is not None, the original generator loss is replaced by a feature loss, introduced
        [here](https://arxiv.org/abs/1606.03498v1).
    fixed_noise_size : int
        Number of images shown when logging. The fixed noise is used to produce the images in the folder/images
        subdirectory, the tensorboard images tab and the samples in get_training_results().
    lambda_grad: float
        Weight for the reconstruction loss of the gradients. Pushes the norm of the gradients to 1.
    device : string
        Device used while training the model. Either "cpu" or "cuda".
    ngpu : int
        Number of gpus used during training if device == "cuda".
    folder : string
        Creates a folder in the current working directory with this name. All relevant files like summary, images, models and
        tensorboard output are written there. Existing folders are never overwritten or deleted. If a folder with the same name
        already exists a time stamp is appended to make it unique.
    """

    #########################################################################
    # Actions before training
    #########################################################################
    def __init__(
            self,
            generator,
            adversary,
            encoder,
            x_dim,
            z_dim,
            optim=None,
            optim_kwargs=None,
            adv_type="Discriminator",
            feature_layer=None,
            fixed_noise_size=32,
            device=None,
            folder=None,
            ngpu=0,
            secure=True,
            _called_from_conditional=False):

        self.adv_type = adv_type
        self.generator = Generator(generator, input_size=z_dim, device=device, ngpu=ngpu, secure=secure)
        self.adversary = Adversary(adversary, input_size=x_dim, adv_type=adv_type, device=device, ngpu=ngpu, secure=secure)
        self.encoder = Encoder(encoder, input_size=x_dim, device=device, ngpu=ngpu, secure=secure)
        self.neural_nets = {
            "Generator": self.generator, "Adversary": self.adversary, "Encoder": self.encoder
        }

        super().__init__(
            x_dim=x_dim, z_dim=z_dim, optim=optim, optim_kwargs=optim_kwargs, feature_layer=feature_layer,
            fixed_noise_size=fixed_noise_size, device=device, ngpu=ngpu, folder=folder, secure=secure
        )
        self.hyperparameters["adv_type"] = adv_type
        if not _called_from_conditional and self.secure:
            assert self.generator.output_size == self.x_dim, (
                "Generator output shape must be equal to x_dim. {} vs. {}.".format(self.generator.output_size, self.x_dim)
            )

    def _define_loss(self):
        if self.adv_type == "Discriminator":
            loss_functions = {"Generator": BCELoss(), "Adversary": BCELoss()}
        elif self.adv_type == "Critic":
            loss_functions = {"Generator": WassersteinLoss(), "Adversary": WassersteinLoss()}
        else:
            raise NotImplementedError("'adv_type' must be one of Discriminator or Critic.")
        return loss_functions

    #########################################################################
    # Actions during training
    #########################################################################
    def calculate_losses(self, X_batch, Z_batch, who=None):
        """ Calculates the losses for GANs using a 1v1 architecture.

        This method is called within the `AbstractGenerativeModel` main `fit()` loop.

        Parameters
        ----------
        X_batch : torch.Tensor
            Current x batch.
        Z_batch : torch.Tensor
            Current z batch.
        who : None, optional
            Name of the network that should be trained.
        """
        if who == "Generator":
            losses = self._calculate_generator_loss(X_batch=X_batch, Z_batch=Z_batch)
        elif who == "Adversary":
            losses = self._calculate_adversary_loss(X_batch=X_batch, Z_batch=Z_batch)
        elif who == "Encoder":
            losses = self._calculate_encoder_loss(X_batch=X_batch, Z_batch=Z_batch)
        else:
            losses = self._calculate_generator_loss(X_batch=X_batch, Z_batch=Z_batch)
            losses.update(self._calculate_adversary_loss(X_batch=X_batch, Z_batch=Z_batch))
            losses.update(self._calculate_encoder_loss(X_batch=X_batch, Z_batch=Z_batch))
        return losses

    def _step(self, who=None):
        if who is not None:
            self.optimizers[who].step()
            if who == "Adversary":
                if self.adv_type == "Critic":
                    for p in self.adversary.parameters():
                        p.data.clamp_(-0.01, 0.01)
        else:
            [optimizer.step() for _, optimizer in self.optimizers.items()]

    #########################################################################
    # Utility functions
    #########################################################################
    def encode(self, x):
        return self.encoder(x)


from __future__ import division

import operator
import string

import nltk

from chester.util import ReportCollector, REPORT_PATH

def isPunct(word):
    return len(word) == 1 and word in string.punctuation

def isNumeric(word):
    try:
        float(word) if '.' in word else int(word)
        return True
    except:
        return False

class RakeKeywordExtractor:

    def __init__(self):
        self.stopwords = set(nltk.corpus.stopwords.words())
        self.top_fraction = 1  # consider top third candidate keywords by score

    def _generate_candidate_keywords(self, sentences):
        phrase_list = []
        for sentence in sentences:
            words = map(lambda x: "|" if x in self.stopwords else x,
                        nltk.word_tokenize(sentence.lower()))
            phrase = []
            for word in words:
                if word == "|" or isPunct(word):
                    if len(phrase) > 0:
                        phrase_list.append(phrase)
                        phrase = []
                else:
                    phrase.append(word)
        return phrase_list

    def _calculate_word_scores(self, phrase_list):
        word_freq = nltk.FreqDist()
        word_degree = nltk.FreqDist()
        for phrase in phrase_list:
            degree = len(list(filter(lambda x: not isNumeric(x), phrase))) - 1
            for word in phrase:
                word_freq.update([word])
                word_degree.update([word])
                # word_degree.inc(word, degree)  # other words
        for word in word_freq.keys():
            word_degree[word] = word_degree[word] + word_freq[word]  # itself
        # word score = deg(w) / freq(w)
        word_scores = {}
        for word in word_freq.keys():
            word_scores[word] = word_degree[word] / word_freq[word]
        return word_scores

    def _calculate_phrase_scores(self, phrase_list, word_scores):
        phrase_scores = {}
        for phrase in phrase_list:
            phrase_score = 0
            for word in phrase:
                phrase_score += word_scores[word]
            phrase_scores[" ".join(phrase)] = phrase_score
        return phrase_scores

    def extract(self, text, max_words=7, top_words=10):
        rc = ReportCollector(REPORT_PATH)

        sentences = nltk.sent_tokenize(text)
        phrase_list = self._generate_candidate_keywords(sentences)
        word_scores = self._calculate_word_scores(phrase_list)
        phrase_scores = self._calculate_phrase_scores(
            phrase_list, word_scores)
        sorted_phrase_scores = sorted(phrase_scores.items(), key=operator.itemgetter(1), reverse=True)
        n_phrases = len(sorted_phrase_scores)
        return_list = truncate_and_limit_keywords(sorted_phrase_scores, max_words, top_words)
        rc.save_object(obj=return_list, text="popular terms extraction:")
        return return_list

def truncate_and_limit_keywords(keywords_list, max_words, top_words):
    truncated_keywords = []
    for keyword in keywords_list[:top_words]:
        text = trim_repeated_words(keyword[0], 1)
        score = keyword[1]
        truncated_text = " ".join(text.split()[:max_words])
        truncated_keywords.append((truncated_text, score))
    return truncated_keywords

def trim_repeated_words(text, max_repeated_words):
    words = text.split()
    new_words = []
    word_count = {}
    for word in words:
        if word in word_count:
            word_count[word] += 1
            if word_count[word] <= max_repeated_words:
                new_words.append(word)
        else:
            word_count[word] = 1
            new_words.append(word)
    return ' '.join(new_words)


import sqlite3
from db_builder import exec, execmany
import sys
import random
from datetime import datetime
from datetime import timedelta
from flask import flash

#==========================general data retrieval functions===========================

# returns user info in a list given an osis
def getUserInfo(osis):
    q = "SELECT * from user_tbl WHERE osis=?"
    inputs = (osis,)
    data = execmany(q, inputs).fetchone()
    info = [data[0],data[1],data[2],data[3],data[4],data[5],data[6]]
    return info

# returns locker info in a list given an osis and locker
def getLockerInfo(locker,osis):
    q = "SELECT * from locker_tbl WHERE locker=? AND owner = ?"
    inputs = (locker,osis)
    data = execmany(q, inputs).fetchone()
    info=[]
    if data is not None:
        for value in data:
            info.append(value)
    return info

# returns transaction info in a list given an osis
def getTransactionInfo(osis):
    q = "SELECT * from transaction_tbl WHERE sender=?"
    inputs = (osis,)
    data = execmany(q, inputs).fetchall()
    info = []
    if(data is None):
        return info
    for value in data:
        if len(value)>0 and value[3] == 1:
            info.append([value[0],value[1],value[2],value[3],value[4],value[5]])
    return info

# returns a list of all info from a desired column of a desired table
def getColumnInfo(column, table):
    q = "SELECT " + column + " FROM " + table + "_tbl"
    rawData = exec(q).fetchall()
    info = []
    for entry in rawData:
        info.append(entry[0])
    return info

# returns a list of info from a desired column of a desired table given specific requirements
def getColumnInfo_Specific(column, table, requirement):
    q = "SELECT " + column + " FROM " + table + "_tbl WHERE " + requirement
    rawData = exec(q).fetchall()
    info = []
    for entry in rawData:
        info.append(entry[0])
    return info

# finds a specific osis from user_tbl and returns True if it exists
def findOsis(osis):
    q = "SELECT * FROM user_tbl WHERE osis = ?"
    inputs=(osis,)
    data=execmany(q,inputs).fetchall()
    if len(data) != 0:
        return True
    return False

# creates dict of transaction/locker data given list of tuples
def getTransLock(data,osis):
    dataDict = {}
    for i in data:
        lock = getLockerInfo(i[0],osis)
        dataDict[i] = lock
    return dataDict

# returns a list of all people who the user received a transaction request from
def getTransactionFrom(osis):
    q="SELECT recipient FROM transaction_tbl WHERE sender=? AND status = ?"
    inputs = (osis,1)
    data = execmany(q,inputs).fetchall()
    info=[]
    if data is None:
        return info
    for value in data:
        info.append(value[0])
    filtered = [x for x in info if x != '']
    return filtered

# returns a list of all people who the user sent a transaction request to
def getTransactionTo(osis):
    q="SELECT sender FROM transaction_tbl WHERE recipient=? AND status=?"
    inputs = (osis,1)
    data = execmany(q,inputs).fetchall()
    info=[]
    if data is None:
        return info
    for value in data:
        info.append(value[0])
    return info

#==========================user profile functions===========================

# checks to see if the user/password combination is valid
def userValid(osis,password):
    q = "SELECT password from user_tbl WHERE osis=?"
    inputs = (osis,)
    data = execmany(q, inputs).fetchone()
    if (data is not None):
        if (data[0] == password):
            return True
        else:
            flash("Incorrect OSIS and password combination.", 'danger')
            return False
    flash("OSIS does not exist. Please sign up for an account.", 'danger')
    return False

# adds user info to user_tbl and locker info to locker_tbl
def addUser(osis, password, grade, buddy, linfo, locker, gender):
    q = "SELECT * FROM user_tbl WHERE osis=?"
    inputs = (osis,)
    data = execmany(q, inputs).fetchone()
    if (data is None):
        if (locker != ""):
            q = "SELECT * FROM locker_tbl WHERE locker='" + locker + "' AND floor='" + linfo[1] + "'"
            data = exec(q).fetchone()
        if(data is None or locker==""):
            q = "INSERT INTO user_tbl VALUES(?, ?, ?, ?, ?, ?, ?)"
            inputs = (osis, password, locker, grade, buddy, "", gender)
            execmany(q, inputs)
            q = "INSERT INTO locker_tbl VALUES(?, ?, ?, ?, ?, ?, ?)"
            inputs = (locker, osis, linfo[0], linfo[1], linfo[2], linfo[3], linfo[4])
            execmany(q, inputs)
            return "done"
        else:
            return "locker"
    return "user"

#==========================editing functions===========================

# updates the survey column of user_tbl given an osis and the proper info
def updateSurvey(osis, info):
    q = "UPDATE user_tbl SET survey=? WHERE osis=?"
    inputs = (info, osis)
    execmany(q, inputs)

# edits user_tbl given an osis, the desired column to be changed, and the new info
def editUserTbl(osis,fxn,new):
    new = "\"" + new + "\""
    q = "UPDATE user_tbl SET " + fxn + "=" + new + " WHERE osis=?"
    inputs = (osis,)
    data = execmany(q,inputs)
    return True

# edits transaction_tbl given an osis, the desired column to be changed, and the new info
def editTransTbl(osis,fxn,new):
    if fxn == "locker":
        q="UPDATE transaction_tbl SET locker = ? WHERE recipient = ?"
        inputs = (new,osis)
        execmany(q,inputs)
    else:
        q = "UPDATE transaction_tbl SET sender = ? WHERE sender = ?"
        inputs = (new, osis)
        execmany(q,inputs)
        q = "UPDATE transaction_tbl SET recipient = ? WHERE recipient = ?"
        inputs = (new, osis)
        execmany(q,inputs)
    return True

# edits locker_tbl given an osis, the locker, the desired column to be changed, and the new info
def editLockerTbl(locker,fxn,new, osis):
    if fxn == "locker" or fxn == "floor":
        q="SELECT locker, floor FROM locker_tbl WHERE locker = ?"
        inputs=(locker,)
        old = execmany(q,inputs).fetchone()
        if fxn == "locker":
            q = "SELECT locker, floor FROM locker_tbl WHERE locker = ?"
            inputs=(new,)
            data = execmany(q,inputs).fetchall()
        else:
            q = "SELECT locker, floor FROM locker_tbl WHERE floor = ?"
            inputs=(new,)
            data = execmany(q,inputs).fetchall()
        if data is not None:
            for value in data:
                if value[0] == old[0] and value[1] == old[1]:
                    return False
    new = "\"" + new + "\""
    q = "UPDATE locker_tbl SET " + fxn + "=" + new + " WHERE owner=?"
    inputs = (osis,)
    d= execmany(q, inputs)
    q= "SELECT floor FROM locker_tbl WHERE owner = ? AND locker = ?"
    inputs = (osis, locker)
    d= execmany(q,inputs).fetchone()
    if d is not None:
        q = "UPDATE transaction_tbl SET floor = ? WHERE locker=? AND floor = ?"
        inputs = (new, locker, d[0])
        data = execmany(q,inputs)
    else:
        q = "UPDATE transaction_tbl SET floor = ? WHERE locker=?"
        inputs = (new, locker)
        data = execmany(q,inputs)
    return True

# edits user/locker/transaction_tbl depending on the new information provided by the user
def editUser(oldosis, osis, oldpassword, password, grade, locker, gender, combo, floor, level, type):
    bool = True
    if(userValid(oldosis,oldpassword)):
        if (password != ""): editUserTbl(oldosis,"password",password)
        if (grade != ""): editUserTbl(oldosis,"grade", grade)
        if (gender != ""): editUserTbl(oldosis,"gender", gender)
        q = "SELECT locker FROM user_tbl WHERE osis=?"
        inputs = (oldosis,)
        oldlocker = execmany(q,inputs).fetchone()[0]
        if (combo != ""): editLockerTbl(oldlocker,"combo", combo, oldosis)
        if (floor != ""): bool = bool and editLockerTbl(oldlocker,"floor", floor, oldosis)
        if (level != ""): editLockerTbl(oldlocker,"level", level, oldosis)
        if (type != ""): editLockerTbl(oldlocker,"location", type, oldosis)
        # if the user wants to change their owned locker
        if (locker != ""):
            if(editLockerTbl(oldlocker, "locker", locker, oldosis)):
                editUserTbl(oldosis, "locker", locker)
                editTransTbl(oldosis, "locker", locker)
            else:
                bool = False
        # if the user wants to change their osis
        if (osis != ""):
            if not (findOsis(osis)):
                editTransTbl(oldosis,"notifs",osis)
                q = "UPDATE locker_tbl SET owner=? WHERE owner=?"
                inputs = (osis,oldosis)
                data = execmany(q, inputs)
                editUserTbl(oldosis,"osis",osis)
            else:
                bool = False
    return bool

# deletes an entry from transaction_tbl given the user, recipient, and type of request
def deleteTrans(user, recipient, type):
    # if the user wants to take their locker off the market
    if (recipient == "" and type == 'L'):
        q = "UPDATE locker_tbl SET status='OWNED' WHERE owner=" + user
        exec(q)
    q = "DELETE FROM transaction_tbl WHERE sender=? AND recipient=? AND request=?"
    inputs=(user,recipient,type)
    execmany(q,inputs)
    return True

#==========================locker trading functions===========================

# returns a dict of transaction_tbl tuples and locker_tbl lists of all available lockers
def tradeableLockers():
    q = "SELECT * FROM transaction_tbl WHERE status=1 AND request='L' AND recipient=''"
    data = exec(q).fetchall()
    dataDict = {}
    for i in data:
        q = "SELECT * from locker_tbl WHERE locker=? AND status='TRADING'"
        inputs = (i[0],)
        data = execmany(q, inputs).fetchone()
        info=[]
        for value in data:
            info.append(value)
        dataDict[i] = info
    return dataDict

# returns a dict of transaction_tbl tuple and locker_tbl list of searched locker
def searchLocker(searchBy, query):
    if (searchBy == "Locker Number"):
        if (len(query) != 5):
            return False
        head,space,tail = query.partition("-")
        q = "SELECT * FROM transaction_tbl WHERE recipient='' AND locker=" + tail + " AND floor=" + head
        data = exec(q).fetchall()
        dataDict = {}
        for i in data:
            q = "SELECT * from locker_tbl WHERE locker=? AND floor=?"
            inputs = (tail,head)
            data = execmany(q, inputs).fetchone()
            info=[]
            if data is not None:
                for value in data:
                    info.append(value)
            dataDict[i] = info
        return dataDict
    else:
        if (len(query) != 9):
            return False
        q = "SELECT * FROM transaction_tbl WHERE recipient='' AND sender=" + query
        data = exec(q).fetchall()
        return getTransLock(data,query)

# searches for all lockers that meet the given criteria with possible searches in floor, level, and location of locker
def filterLocker(floor,level,location):
    # filters based on owner
    q = "SELECT owner FROM locker_tbl WHERE status='TRADING'"
    if (floor != ""):
        q += " AND floor=" + floor
    if (level != ""):
        q += " AND level='" + level + "'"
    if (location != ""):
        q += " AND location='" + location + "'"
    data = exec(q).fetchall()
    dictRes = {}
    for i in data:
        # searches for those specific owners and their lockers
        dictRes.update(searchLocker("Owner", i[0]))
    return dictRes

# adds a locker to transaction_tbl and updates its status
def putOnMarket(locker,osis):
    linfo = getLockerInfo(locker,osis)
    q = "INSERT INTO transaction_tbl VALUES (?,?,?,?,?,?)"
    inputs = (locker,"",linfo[1],1,'L',linfo[3])
    execmany(q,inputs)
    q = "UPDATE locker_tbl SET status='TRADING' WHERE locker=" + str(locker) + " AND owner=" + str(osis)
    exec(q)

# adds a locker request to transaction_tbl given two people
def lockerRequest(to,sender):
    owner = getUserInfo(to)
    locker = getLockerInfo(owner[2],to)
    q = "INSERT INTO transaction_tbl VALUES (?,?,?,?,?,?)"
    inputs=(owner[2],to, sender, 1, "L", locker[3])
    execmany(q,inputs)

# updates the user/locker/transaction_tbl to switch two lockers for two people
def acceptLocker(me,you):
    owner = getUserInfo(me)
    ownerL = getLockerInfo(owner[2],me)
    recipient = getUserInfo(you)
    recipientL = getLockerInfo(recipient[2],you)
    q = "UPDATE user_tbl SET locker=" + str(recipient[2]) + " WHERE osis=" + str(me)
    exec(q)
    q = "UPDATE user_tbl SET locker=" + str(owner[2]) + " WHERE osis=" + str(you)
    exec(q)
    q = "UPDATE locker_tbl SET status='OWNED',locker=" + str(recipientL[0]) + ",combo=" + str(recipientL[2]) + ",floor=" + str(recipientL[3]) + ",level='" + str(recipientL[4]) + "',location='" + str(recipientL[5]) + "' WHERE owner=" + str(me)
    exec(q)
    q = "UPDATE locker_tbl SET status='OWNED',locker=" + str(ownerL[0]) + ",combo=" + str(ownerL[2]) + ",floor=" + str(ownerL[3]) + ",level='" + str(ownerL[4]) + "',location='" + str(ownerL[5]) + "' WHERE owner=" + str(you)
    exec(q)
    q = "UPDATE transaction_tbl SET status=0 WHERE recipient=" + str(me) + " AND sender=" + str(you)
    exec(q)
    deleteTrans(me,"","L")
    deleteTrans(you,"","L")
    return True

#==========================buddy matching functions===========================

# returns survey info from user_tbl in a list given an osis
def getSurveyInfo(osis):
    q = "SELECT survey from user_tbl WHERE osis=?"
    inputs = (osis,)
    data = execmany(q, inputs).fetchone()
    info = []
    if(data[0] != ""):
        info = data[0].split("|")
    return info

# filters the buddy search by using the filterUser and filterLock helper functions, returns a list of osis
def filter(query,osis):
    info1=filterUser(query, osis)
    info2=filterLock(query, osis)
    info=[]
    # intersects the two data sets
    for value in info1:
        if value in info2:
            info.append(value)
    return info

# returns a list of all people who fit query criteria found in user_tbl
def filterUser(query,osis):
    q="SELECT osis FROM user_tbl WHERE osis != " + osis
    q+= " AND BUDDY = ''"
    info=[]
    if query[0] != "":
        q+=" AND osis = '" + query[0]+"'"
    if query[1] != "":
        q+=" AND locker = '" + query[1]+"'"
    if query[2] != "" and  query[2] != "None":
        q+=" AND survey LIKE '%" + query[2] +"%'"
    if query[3] != "" and  query[3] != "None":
        q+=" AND survey LIKE '%" + query[3] +"%'"
    if query[4] != "" and  query[4] != "None":
        q+=" AND grade = '" + query[4]+"'"
    if query[5] != "" and  query[5] != "None":
        q+=" AND gender = '" + query[5]+"'"
        q+=";"
    data=exec(q).fetchall()
    for value in data:
        info.append(str(value[0]))
    return info

# returns a list of all people who fit query criteria found in locker_tbl
def filterLock(query,osis):
    info=[]
    q="SELECT owner FROM locker_tbl WHERE owner != " + osis
    if query[6] != "" and  query[6] != "None":
        q+=" AND floor = '" + query[6]+"'"
    if query[7] != "" and  query[7] != "None":
        q+=" AND location = '" + query[7]+"'"
    if query[8] != "" and  query[8] != "None":
        q+=" AND level = '" + query[8]+"'"
    q+=";"
    data=exec(q).fetchall()
    for value in data:
        info.append(str(value[0]))
    return info

# adds a buddy request to transaction_tbl
def buddyRequest(to, sender):
    locker = getUserInfo(to)
    if locker == '':
        locker = getUserInfo(sender)[2]
    q = "INSERT INTO transaction_tbl VALUES (?,?,?,?,?,?)"
    inputs=(locker[2],to, sender, 1, "B", getLockerInfo(locker[2],to)[3])
    execmany(q,inputs)
    return True

# confirms a buddy request by updating user_tbl buddy columns for both people
def confirmB(user, recipient):
    q="UPDATE transaction_tbl SET status = 0 WHERE request = ? AND (sender=? OR recipient = ? OR sender = ? OR recipient = ?)"
    inputs=("B",user,user,recipient,recipient)
    execmany(q,inputs)
    q="UPDATE user_tbl SET buddy = ? WHERE osis = ?"
    inputs=(user, recipient)
    execmany(q,inputs)
    q="UPDATE user_tbl SET buddy = ? WHERE osis = ?"
    inputs=(recipient, user)
    execmany(q,inputs)
    return True

# returns a list of senders who want to dissolve a buddy pair with a given user
def getDissolveInfo(user):
    q = "SELECT sender FROM transaction_tbl WHERE recipient=?"
    inputs=(user,)
    data=execmany(q,inputs).fetchall()
    info=[]
    for value in data:
        info.append(value[0])
    return info

# updates user_tbl by removing the buddy pair of two people
def dissolveBuddy(user, sender):
    q = "UPDATE transaction_tbl SET status = ? WHERE (sender = ? OR recipient = ?) AND request = ?"
    inputs=(0,user,user,"D")
    execmany(q,inputs)
    q = "UPDATE user_tbl SET buddy = ? WHERE osis = ?"
    inputs=("",user)
    execmany(q,inputs)
    inputs=("",sender)
    execmany(q,inputs)
    return True

# adds a dissolve buddy request to transaction_tbl
def breakB(user, recipient):
    q = "INSERT INTO transaction_tbl VALUES (?,?,?,?,?,?)"
    inputs=("" , recipient, user, 1, "D", "")
    execmany(q,inputs)
    return True

# searches transaction_tbl to see if a user wants to dissolve a buddy pair
def ifDissolve(user):
    q = "SELECT * FROM transaction_tbl WHERE (recipient=? OR sender=?) AND status = ? AND request = ?"
    inputs=(user,user,1,"D")
    data=execmany(q,inputs).fetchall()
    if len(data)!=0:
        return True
    return False

#==========================notifications functions===========================

# returns a list of transaction requests sent to the user to be displayed as messages
def getMess(osis,num):
    q="SELECT * FROM transaction_tbl WHERE recipient=? AND status = ?"
    inputs = (osis,num)
    data = execmany(q,inputs).fetchall()
    info=[]
    temp=[]
    if data is None:
        return info
    for value in data:
        for cell in value:
            temp.append(cell)
        info.append(temp)
        temp=[]
    return info

# returns a list of all notifications the user was sent
def getAllNotifs(osis):
    q="SELECT * FROM transaction_tbl WHERE recipient=?"
    inputs = (osis,)
    data = execmany(q,inputs).fetchall()
    info=[]
    temp=[]
    if data is None:
        return info
    for value in data:
        for cell in value:
            temp.append(cell)
        info.append(temp)
        temp=[]
    return info


# importing required libraries
import tensorflow as tf
import numpy as np
import streamlit as st

def remove_digit(text):
    """
    Removes numbers from text
    """
    return "".join(word for word in text if not word.isdigit())

# preprocess and make prediction with the model
def preprocess(text):
    """
    Makes predictions on given text and returns whether it is a real news or not
    """

    # preprocess text
    text = np.array(text)
    custom_text_modified = []
    for i in range(len(text)):
        custom_text_modified.append(remove_digit(text[i]))

    # loading model
    model = tf.keras.models.load_model("final_model_GRU")

    # making predictions
    preds = model.predict(custom_text_modified)

    # rounding off the predictions
    preds = int(np.round(preds))

    # returning the predictions
    if preds == 0:
        return "Real News"

    return "Fake News"

def main():
    with st.sidebar:
        st.title("About:")
        st.markdown(
        "- Predicts whether the Entered News Article is Fake or not.\n"
        "- This helps the people to be aware of the Fake News articles that are being spread by Non-standard News sites."
        )
        st.title("Other Projects:")
        st.markdown("💰 [US Health Insurance Cost Prediction](https://health-insurance-cost-predictor-k19.streamlit.app/)\n\n"\
                    "🪶 [Birds Classifier](https://huggingface.co/spaces/Kathir0011/Birds_Classification)\n\n"\
                    "🧑💻 [YouTube Video Assistant](https://huggingface.co/spaces/Kathir0011/YouTube_Video_Assistant)")

    st.title("Fake News Detector")
    text = st.text_area("Enter the News you saw:", placeholder="Copy & Paste the News here...",
                        help="Provide the News Article description you want to verify", height=350, max_chars=10000)

    if st.button("Submit"):
        st.snow()
        if text == "":
            st.warning(" Please Enter some News to verify...", icon="⚠")

        elif len(text) < 100:
            st.warning(" Please provide more information...", icon="⚠")

        else:
            result = preprocess([text])
            if result == "Real News":
                st.success(result, icon="✅")
            else:
                st.error("Probably a Fake Article, Please verify with other News sites", icon="❌")

    st.info("This Detector helps you to be aware of the fake news articles that are being published.", icon="ℹ")

if __name__ == "__main__":
    # call main function
    main()


print('''
            10.11 – Número favorito: Escreva um programa que pergunte qual é o número
            favorito de um usuário. Use json.dump() para armazenar esse número em um
            arquivo. Escreva um programa separado que leia esse valor e apresente a
            mensagem “Eu sei qual é o seu número favorito! É _____.”.
''')

import json

def get_numero_favorito():

    filename = 'numero_favorito.json'
    try:
        with open(filename) as f_obj:
            number = json.load(f_obj)
    except FileNotFoundError:
        username = input("Qual é o seu número favorito? ")
        with open(filename, 'w') as f_obj:
            json.dump(username, f_obj)
            print(f"O seu número favorito é {username}.")
    else:
        print(f"Eu sei qual é o seu número favorito! É {number}.")

get_numero_favorito()


"""Firebase client for push notifications."""
import logging
import os

import firebase_admin
from firebase_admin import credentials, messaging

cred = credentials.Certificate(os.environ.get("FIREBASE_PATH"))
firebase_admin.initialize_app(cred)

logger = logging.getLogger(__name__)

class FirebaseClient:
    """Firebase Client for sending push notifications to Android and iOS devices based on events."""

    def __init__(
            self,
            fcm_token: str,
            title: str,
            body: str,
    ):
        self.fcm_token = fcm_token
        self.title = title
        self.body = body

    def send_ios_push_notification(self):
        """Send notification to ios device."""
        message = messaging.Message(
            data={
                'title': self.title,
                'body': self.body,
                'sound': 'default'
            },
            token=self.fcm_token,
            apns=messaging.APNSConfig(
                payload=messaging.APNSPayload(
                    aps=messaging.Aps(sound='default')
                )
            )
        )

        try:
            messaging.send(message)
        except Exception as e:
            logger.exception(f"Push Notification failed to send. Error: {str(e)}")

    def send_android_push_notification(self):
        """Send notification to android device."""
        message = messaging.Message(
            data={
                'title': self.title,
                'body': self.body
            },
            token=self.fcm_token,
            android=messaging.AndroidConfig(
                priority='high',
                notification=messaging.AndroidNotification(
                    title=self.title,
                    body=self.body,
                    sound='default'
                )
            )
        )
        try:
            messaging.send(message)
        except Exception as e:
            logger.exception(f"Push Notification failed to send. Error: {str(e)}")


from flask import Flask, request, render_template, jsonify
from flask_restful import Api, Resource, reqparse, abort
from flask_sqlalchemy import SQLAlchemy
import sys

app = Flask(__name__)
api = Api(app)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'
db = SQLAlchemy(app)

class UserModel(db.Model):
    user_id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(30), nullable=False)

    def __repr__(self):
        return f"User(username = {username})"

class RoomModel(db.Model):
    room_id = db.Column(db.Integer, primary_key=True)
    roomname = db.Column(db.String(30), nullable=False)

    def __repr__(self):
        return f"Room(roomname = {roomname})"

db.drop_all()
db.create_all()

roomMessages = []
listOfMessages = []
listOfUsers = []
messages = []

listRoom = []
listRoomUser = []
listRoomOwner = []
nestedListuser = []
loggedin = ''
currentRoom = ''

class UserMessage:
    def __init__(self, user_id, message):
        self.user_id = user_id
        self.message = message

    def __repr__(self):
        return f"Message(message = {message})"

    def __str__(self):
        return f"Message(message = {message})"

@app.route("/", methods=['GET', 'POST'])
def index():
    return render_template('login.html', uservalues=UserModel.query.all())

@app.route("/goback", methods=['GET', 'POST'])
def goBack():
    global nestedListuser
    global loggedin
    return render_template('index.html', uservalues=UserModel.query.all(), roomvalues=RoomModel.query.all(), listUsers=nestedListuser, loggedin=loggedin, listRoomUser=listRoomUser)

@app.route("/api/users", methods=['GET', 'POST'])
def adduser():
    if request.method == 'POST':
        name=request.form['username']
        user_id=UserModel(username=name)
        user = UserModel(user_id=user_id.user_id, username=name)
        db.session.add(user)
        db.session.commit()
        listOfUsers.append(user.user_id)
        return render_template('login.html', uservalues=UserModel.query.all())
    else: return render_template('login.html', uservalues=UserModel.query.all())

@app.route("/api/users/<string:name>", methods=['GET', 'POST'])
def addclientuser(name):
    global loggedin
    user_id=UserModel(username=name)
    user = UserModel(user_id=user_id.user_id, username=name)
    db.session.add(user)
    db.session.commit()
    loggedin = user.user_id
    listOfUsers.append(user.user_id)
    return str(loggedin)

@app.route("/api/userlogin/<int:user_id>")
def login(user_id):
    global loggedin
    loggedin = user_id
    return render_template('index.html', uservalues=UserModel.query.all(), roomvalues=RoomModel.query.all(), loggedin=loggedin, listRoomUser=listRoomUser)

@app.route("/api/user/<int:user_id>")
def deleteuser(user_id):
    try:
        user = UserModel.query.filter_by(user_id=user_id).delete()
        db.session.commit()
        listOfUsers.remove(user.user_id)
        return render_template('login.html', uservalues=UserModel.query.all())
    except: abort(404, message="User ID is not valid")

@app.route("/api/rooms", methods=['GET', 'POST'])
def addroom():
    global listRoom
    global listRoomUser
    global listRoomOwner
    global nestedListuser
    global loggedin
    if request.method == 'POST':
        name=request.form['roomname']
        room_id=RoomModel(roomname=name)
        room = RoomModel(room_id=room_id.room_id, roomname=name)
        db.session.add(room)
        db.session.commit()
        listRoom.append(room.room_id)
        listRoomUser.append([])
        roomMessages.append([])
        return render_template('index.html', uservalues=UserModel.query.all(), roomvalues=RoomModel.query.all(), listUsers=nestedListuser, loggedin=loggedin, listRoomUser=listRoomUser)
    else: return render_template('index.html', uservalues=UserModel.query.all(), roomvalues=RoomModel.query.all(), listUsers=nestedListuser, loggedin=loggedin, listRoomUser=listRoomUser)

@app.route("/api/rooms/<string:name>", methods=['GET', 'POST'])
def addclientroom(name):
    global listRoom
    global listRoomUser
    room_id=RoomModel(roomname=name)
    room = RoomModel(room_id=room_id.room_id, roomname=name)
    db.session.add(room)
    db.session.commit()
    listRoom.append(room.room_id)
    listRoomUser.append([])
    roomMessages.append([])
    return str(room.room_id)

@app.route("/api/room/<int:room_id>", methods=['GET'])
def getroom(room_id):
    currentRoom = room_id
    return render_template('room.html', uservalues=UserModel.query.all(), roomvalues=RoomModel.query.all(), listUsers=nestedListuser, messages=listOfMessages, loggedin=loggedin, currentRoom=currentRoom, roomMessages=roomMessages, listRoomUser=listRoomUser)

@app.route("/api/room/<int:room_id>/messages", methods=['GET'])
def onlygetmessage(room_id):
    global nestedListuser
    global loggedin
    global listOfMessages
    a = listRoom.index(room_id)
    listOfMessages = roomMessages[a]
    return render_template('chatroom.html', uservalues=UserModel.query.all(), roomvalues=RoomModel.query.all(), messages=listOfMessages, listUsers=nestedListuser, loggedin=loggedin, currentRoom=currentRoom, roomMessages=roomMessages)

@app.route("/api/room/<int:room_id>/<int:user_id>/messages", methods=['GET', 'POST'])
def message(room_id, user_id):
    global nestedListuser
    global loggedin
    global listOfMessages
    if user_id in listOfUsers:
        try:
            if request.method == 'POST':
                inMessage=request.form['message']
                m = UserMessage(user_id, inMessage)
                a = listRoom.index(room_id)
                listOfMessages = roomMessages[a]
                listOfMessages.append(m)
                return render_template('chatroom.html', uservalues=UserModel.query.all(), roomvalues=RoomModel.query.all(), messages=listOfMessages, listUsers=nestedListuser, loggedin=loggedin, currentRoom=currentRoom, roomMessages=roomMessages)
            return render_template('chatroom.html', uservalues=UserModel.query.all(), roomvalues=RoomModel.query.all(), messages=listOfMessages, listUsers=nestedListuser, loggedin=loggedin, currentRoom=currentRoom, roomMessages=roomMessages)
        except:
            return render_template('room.html', uservalues=UserModel.query.all(), roomvalues=RoomModel.query.all(), messages=listOfMessages, listUsers=nestedListuser, loggedin=loggedin, currentRoom=currentRoom, roomMessages=roomMessages)
    else: abort(404, message="User id does not exist")

@app.route("/api/room/<string:message>/<int:room_id>/<int:user_id>/messages", methods=['GET', 'POST'])
def messageclient(message, room_id, user_id):
    global nestedListuser
    global listOfMessages
    try:
        m = UserMessage(user_id, message)
        a = listRoom.index(room_id)
        listOfMessages = roomMessages[a]
        listOfMessages.append(m)
        return render_template('room.html', uservalues=UserModel.query.all(), roomvalues=RoomModel.query.all(), messages=listOfMessages, listUsers=nestedListuser, loggedin=loggedin, currentRoom=currentRoom, roomMessages=roomMessages)
    except:
        return render_template('room.html', uservalues=UserModel.query.all(), roomvalues=RoomModel.query.all(), messages=listOfMessages, listUsers=nestedListuser, loggedin=loggedin, currentRoom=currentRoom, roomMessages=roomMessages)

@app.route("/api/room/<int:room_id>/users", methods=['GET', 'POST'])
def roomusers(room_id):
    global listRoomUser
    global listRoom
    global loggedin
    global nestedListuser
    global currentRoom
    try:
        currentRoom = room_id
        a = listRoom.index(room_id)
        nestedListuser = listRoomUser[a]
        nestedListuser.append(loggedin)
        return render_template('index.html', uservalues=UserModel.query.all(), roomvalues=RoomModel.query.all(), listUsers=nestedListuser, messages=listOfMessages, loggedin=loggedin, currentRoom=currentRoom, roomMessages=roomMessages, listRoomUser=listRoomUser)
    except:
        return render_template('index.html', uservalues=UserModel.query.all(), roomvalues=RoomModel.query.all(), listUsers=nestedListuser, messages=listOfMessages, loggedin=loggedin, currentRoom=currentRoom, roomMessages=roomMessages, listRoomUser=listRoomUser)

@app.route("/api/room/<int:room_id>/<int:user_id>/fetch", methods=['GET', 'POST'])
def fetchMessages(room_id, user_id):
    m = UserMessage(user_id, message)
    a = listRoom.index(room_id)
    listOfMessages = roomMessages[a]
    messagesarray = []
    for mes in listOfMessages:
        messagesarray.append(mes.message)
    return jsonify(messagesarray)

@app.route("/api/room/fetch", methods=['GET'])
def fetchAllMessages():
    allMessages = []
    nestedMessages = []
    for i in listRoom:
        allMessages.append([])

    for mes in roomMessages:
        for j in mes:
            allMessages[roomMessages.index(mes)].append(j.message)
    return jsonify(allMessages)

@app.route("/api/room/fetchRoom_idList", methods=['GET'])
def fetchlistOfRoom_id():
    return jsonify(listRoom)

@app.route("/api/room/fetchRoomUsers", methods=['GET'])
def fetchRoomUsers():
    return jsonify(listRoomUser)

if __name__ == "__main__":
    app.run(debug=True)


import json
from models import User, session
from wallet import WalletApi

client = WalletApi()

def get_orders(id):
    "Returns all orders attached to a specifici user"
    pass

def get_products1():
    "Pulls down al the store products"
    file = open('./products.json')
    data = json.load(file)
    return data['First Listing']

def get_products2():
    "product types & prices"
    file = open('./products.json')
    data = json.load(file)
    return data['Second Listing']

def get_user(msg):
    "Returns or creates a new user"
    id = msg.from_user.id

    user = session.query(User).filter_by(id=id).first()
    if user:
        return user
    else:
        mnemonic, address = client.create_wallet()
        user = User(id=id, balance="0", orders=0, address=address, mnemonic=mnemonic)
        session.add(user)
        session.commit()
        return user

def update_balance(msg):
    "Updates User Balance"
    user = get_user(msg)

    balance = client.get_balance(address = user.address)
    user.balance = str(balance)
    session.add(user)
    session.commit()
    return str(balance)

def get_received_msg(msg):
    "Delete This Message"

    message_id = msg.message_id
    chat = msg.chat
    return chat, message_id

def send_out_payment(user, amount, wallet):
    status = client.send_money(user, amount, wallet)
    return status


# -*- coding: utf-8 -*-
"""
Part I Autumn Term
Lecture 2: Frequency domain analysis

Fast Fourier Transform - complex conjugate.

Last modified on Thu Sep 15 02:11:19 2022
@author: Dr Frederic Cegla, Amanda Lee
"""

###############################################################
# Import required functions, modules, packages, and libraries #
###############################################################
# Functions
from numpy import pi as pi                     # Import NumPy constants and mathematical functions
from numpy.fft import fft as fft, ifft as ifft # Import NumPy discrete Fourier transform functions

# Modules, packages, and libraries
import soundfile as sf                         # Import audio library
import numpy as np                             # Import the fundamental package for scientific computing with Python
import matplotlib.pyplot as plt                # Import the state-based interface for interactive plots and simple cases of programmatic plot generation

######################################
# Step 1: Display time domain signal #
######################################
(data, Fs) = sf.read("Chimes.wav") # Read data and extract sampling frequency from sound file
FNy = Fs/2 # Define Nyquist frequency
T = (len(data)-1)/Fs # Define time period
t = np.linspace(0, T, len(data)) # Create time vector
y = data[:, 0] # Extract data from channel 1 only (note that the loaded wave file is stereo)

plt.figure("Figure 1: Time domain signal") # Create a new figure
plt.title("Time domain signal") # Set a title for the axes
plt.plot(t, y) # Plot y vs t
plt.xlim(t[0], t[-1]) # Set the x limits of the current axes
plt.xlabel("Time / s") # Set the label for the x-axis
plt.ylabel("Amplitude / arb. unit") # Set the label for the y-axis

###########################################
# Step 2: Display frequency domain signal #
###########################################
F = np.linspace(0, Fs, len(t)) # Create frequency vector
Fy = fft(y) # Take FFT of signal y

fig = plt.figure("Figure 2: Frequency domain signal") # Create a new figure
fig.suptitle("Frequency domain signal") # Add a centered suptitle to the figure

plt.subplot(2, 1, 1) # Add an axes to the current figure (top plot)
plt.plot(F, np.abs(Fy)) # Plot Fy vs F (magnitude)
plt.xlim(0, FNy) # Display up to Nyquist frequency
plt.ylim(bottom=0) # Set the y limits of the current axes
plt.xlabel("Frequency / Hz") # Set the label for the x-axis
plt.ylabel("Amplitude / arb. unit") # Set the label for the y-axis

plt.subplot(2, 1, 2) # Add an axes to the current figure (bottom plot)
plt.plot(F, np.angle(Fy)) # Plot Fy vs F (phase)
plt.xlim(0, FNy) # Display up to Nyquist frequency
plt.ylim(-pi, pi) # Set the y limits of the current axes
plt.xlabel("Frequency / Hz") # Set the label for the x-axis
plt.ylabel("Phase / rad") # Set the label for the y-axis

plt.tight_layout()

##################################################
# Step 3: Recreate upper half frequency spectrum #
##################################################
Fy_new = np.zeros(np.size(Fy), dtype="complex_") # Initialise an array to store new spectrum
FNy_idx = int( len(F)/2 ) - 1 # Find the Nyquist frequency array index
Fy_new[1 : FNy_idx+1] = Fy[1 : FNy_idx+1] # Copy spectrum up to Nyquist frequency
Fy_new[FNy_idx+1 :] = np.conj( Fy[FNy_idx+1 : 0 : -1] ) # Recreate spectrum above Nyquist frequency

plt.figure("Figure 3: Frequency domain signal (reconstructed)") # Create a new figure
plt.title("Frequency domain signal (reconstructed)") # Set a title for the axes
plt.plot(F, np.abs(Fy_new), label="Reconstructed signal") # Plot reconstructed signal (Fy_new vs F; magnitude)
plt.plot(F, np.abs(Fy), ":", label="Original signal") # Plot original signal (Fy vs F; magnitude)
plt.axvline(x=FNy, color="k", linestyle="--") # Display axis of symmetry at Nyquist frequency
plt.xlim(F[0], F[-1]) # Set the x limits of the current axes
plt.ylim(bottom=0) # Set the y limits of the current axes
plt.xlabel("Frequency / Hz") # Set the label for the x-axis
plt.ylabel("Amplitude / arb. unit") # Set the label for the y-axis
plt.legend() # Place a legend on the axes

###############################################
# Step 4: Recover original time domain signal #
###############################################
y_new = np.real( ifft(Fy_new) ) # Take IFFT of signal Fy_new

plt.figure("Figure 4: Time domain signal (reconstructed)") # Create a new figure
plt.title("Time domain signal (reconstructed)") # Set a title for the axes
plt.plot(t, y_new, label="Reconstructed signal") # Plot reconstructed signal (y_new vs t)
plt.plot(t, y, ":", label="Original signal") # Plot original signal (y vs t)
plt.xlim(t[0], t[-1]) # Set the x limits of the current axes
plt.xlabel("Time / s") # Set the label for the x-axis
plt.ylabel("Amplitude / arb. unit") # Set the label for the y-axis
plt.legend() # Place a legend on the axes
plt.show() # Display all open figures


# SW 수열이란?
# 1~N 사이의 서로 다른 정수로 이루어짐
# |현재항 - 이전항| > |다음항 - 현재항|
# 점점 갈수록 차이가 줄어들어야 함
# 가장 큰 숫자 - 가장 작은 숫자 - 가장 큰 숫자 - 가장 작은 숫자 ...
from collections import deque

n = int(input())
queue = deque()
for i in range(1, n+1):
    queue.append(i)

answer = []
while queue:
    answer.append(queue[-1])
    queue.pop()
    if queue:
        answer.append(queue[0])
        queue.popleft()

print(" ".join(map(str, answer)))


from django.urls import path
from .views import add_movies,list_movies,edit_movie,delete_movie

urlpatterns = [
	path('movie/create', add_movies, name='add_movies'),
	path('', list_movies, name='list_movies'),
	path('movie/edit/<int:id>', edit_movie, name='edit_movie'),
	path('movie/delete/<int:id>', delete_movie, name='delete_movie'),

]


import numpy as np
import scipy.io.wavfile as wav
import scipy.signal as signal
import matplotlib.pyplot as plt

# Load audio file
rate, audio = wav.read("speech.wav")

# Normalize audio data
audio = audio / np.max(np.abs(audio))

# Apply pre-emphasis filter
pre_emphasis = 0.97
emphasized_audio = np.append(audio[0], audio[1:] - pre_emphasis * audio[:-1])

# Define frame length and overlap
frame_length = int(0.025 * rate)
frame_overlap = int(0.01 * rate)

# Generate frames of audio data
frames = []
for i in range(0, len(emphasized_audio) - frame_length, frame_overlap):
    frame = emphasized_audio[i:i + frame_length]
    frames.append(frame)

# Apply Hamming window to frames
windowed_frames = np.array(frames) * signal.hamming(frame_length)

# Compute power spectrum of frames using Fourier Transform
power_spectrum = np.abs(np.fft.rfft(windowed_frames, n=512))**2

# Compute Mel filterbank energies
num_filters = 26
low_freq_mel = 0
high_freq_mel = (2595 * np.log10(1 + (rate / 2) / 700))  # Convert Hz to Mel
mel_points = np.linspace(low_freq_mel, high_freq_mel, num_filters + 2)
hz_points = 700 * (10**(mel_points / 2595) - 1)  # Convert Mel to Hz
bin = np.floor((frame_length + 1) * hz_points / rate)

filterbank = np.zeros((num_filters, int(np.floor(frame_length / 2 + 1))))
for m in range(1, num_filters + 1):
    f_m_minus = int(bin[m - 1])
    f_m = int(bin[m])
    f_m_plus = int(bin[m + 1])

    for k in range(f_m_minus, f_m):
        filterbank[m - 1, k] = (k - bin[m - 1]) / (bin[m] - bin[m - 1])
    for k in range(f_m, f_m_plus):
        filterbank[m - 1, k] = (bin[m + 1] - k) / (bin[m + 1] - bin[m])

filterbank_energies = np.dot(power_spectrum, filterbank.T)
filterbank_energies = np.where(filterbank_energies == 0, np.finfo(float).eps, filterbank_energies)  # Numerical Stability

# Compute logarithmic Mel spectrum
log_filterbank_energies = 20 * np.log10(filterbank_energies)

# Apply discrete cosine transform (DCT) to decorrelate the filterbank energies
num_ceps = 12
mfcc = np.zeros((len(log_filterbank_energies), num_ceps))
for i in range(num_ceps):
    norm = np.sqrt(2.0 / frame_length)
    if i == 0:
        norm = np.sqrt(1.0 / frame_length)
    for j in range(len(log_filterbank_energies)):
        mfcc[j, i] = norm * np.sum(log_filterbank_energies[j] * np.cos(np.pi * i / num_filters * (np.arange(num_filters) + 0.5)))

# Use the first 12 MFCC coefficients as features for speech recognition
features = mfcc[:, 0:12]

# Train a


import io
import contextlib
import sys
import numpy as np

def split(data: io.BytesIO, size: int) -> list[bytes]:
    """
    Split a BytesIO object into chunks of size `size`.
    """
    data.seek(0)
    chunks = []
    while True:
        chunk = data.read(size)
        if not chunk:
            break
        chunks.append(chunk)
    return chunks

def fmt(s: str, *fmts: str) -> str:
    """
    Colorize a string.
    """
    format_defs = {
        'green': '\033[92m',
        'blue': '\033[94m',
        'purple': '\033[95m',
        'gray': '\033[90m',
        'yellow': '\033[93m',
        'italic': '\033[3m',
        'bold': '\033[1m',
    }
    return ''.join(format_defs[fmt] for fmt in fmts) + s + '\033[0m'

@contextlib.contextmanager
def silence():
    """
    Suppress stdout.
    """
    save_stdout = sys.stdout
    sys.stdout = io.StringIO()
    yield
    sys.stdout = save_stdout

def ndcg(expected: list[str], actual: list[str], form="linear"):
    """
    Calculate normalized discounted cumulative gain (NDCG).

    Args:
        expected: list of expected result IDs
        actual: list of actual result IDs
        form: formula to use, either 'linear' or 'exp'
    """
    rel_pred = [(len(expected) - actual.index(id)) for id in expected]
    rel_true = list(range(len(expected), 0, -1))
    p = len(rel_pred)
    discount = 1 / (np.log2(np.arange(p) + 2))

    if form == "linear":
        idcg = np.sum(rel_true[:p] * discount)
        dcg = np.sum(rel_pred[:p] * discount)
    elif form == "exp":
        idcg = np.sum([2**x - 1 for x in rel_true[:p]] * discount)
        dcg = np.sum([2**x - 1 for x in rel_pred[:p]] * discount)
    else:
        raise ValueError("Only supported for two formula, 'linear' or 'exp'")

    return dcg / idcg


from tkinter import *
from tkinter import filedialog
from PIL import ImageTk, Image
import luminance_ops as l
import numpy as np
from matplotlib import pyplot as plt
import io

#Constants
N_IMG_BUTTONS = 4
IMAGE_COLUMNS=3
FILTERS_DICT = {"Raiz":l.sqrt_ilum, "Cuadrado":l.pow2_ilum, "Lineal":l.lineal_ilum, "Ecualización":l.equalize_ilum}
IMAGE_TYPES = [("Images", "*.png"), ("Images", "*.jpg"), ("Images", "*.jpeg")]
#Global variables
img_arr = [None]*2
tk_imgs = [None]*2

def view_histogram(master, img_index):
    if not showing_hist[img_index]:
        my_dpi=96
        yiq_img = l.rgb_to_yiq(np.array(img_arr[img_index]))
        img_counts, bins = np.histogram(yiq_img[:,:,0], bins=20)
        buf = io.BytesIO()
        buf.seek(0)
        fig = plt.figure(figsize=(600/my_dpi, 600/my_dpi), dpi=my_dpi)
        plt.stairs(img_counts, bins)
        fig.savefig(buf)
        buf.seek(0)
        png_hist =  Image.open(buf)
        tk_imgs[img_index] = ImageTk.PhotoImage(png_hist)
        showing_hist[img_index] = True
    else:
        tk_imgs[img_index] = ImageTk.PhotoImage(img_arr[img_index])
        showing_hist[img_index] = False
    img_b =Button(master,image=tk_imgs[img_index])
    img_b.grid(row=0, columnspan=IMAGE_COLUMNS)

def upload_file(img_index, master):
    filename = filedialog.askopenfilename(filetypes=IMAGE_TYPES)
    img = Image.open(filename).convert("RGB").resize((600,600))
    tk_img= ImageTk.PhotoImage(img)
    img_b =Button(master,image=tk_img)
    img_b.grid(row=0, columnspan=IMAGE_COLUMNS)
    img_arr[img_index] = img
    tk_imgs[img_index] = tk_img

def filter_img(img1, master):
    img_arr[-1] = FILTERS_DICT[selected_filter.get()](img1)
    tk_imgs[-1] = ImageTk.PhotoImage(img_arr[-1])
    b3 =Button(master,image=tk_imgs[-1])
    b3.grid(row=0,columnspan=6)

def create_image_frame(master):
    images_frame = Frame(master)
    images_frame.grid(row=0)
    #Create image upload buttons
    first_image_frame = Frame(images_frame)
    b1 = Button(first_image_frame, text='Cargar primera imagen',
    width=20,command = lambda:upload_file(0, first_image_frame))
    b1.grid(row=1, column=0)

    b2 = Button(first_image_frame, text='Histograma',
    width=20,command = lambda:view_histogram(first_image_frame,0))
    b2.grid(row=1, column=1)
    first_image_frame.grid(row=0,column=0)
    #Second image
    second_image_frame = Frame(images_frame)
    operations_menu = OptionMenu(second_image_frame, selected_filter, *FILTERS_DICT.keys())
    operations_menu.grid(row=1, column=0)

    b3 = Button(second_image_frame, text='Filtrar',
    width=20,command = lambda:filter_img(img_arr[0], second_image_frame))
    b3.grid(row=1, column=1)

    b4 = Button(second_image_frame, text='Histograma',
    width=20,command = lambda:view_histogram(second_image_frame,1))
    b4.grid(row=1, column=2)
    second_image_frame.grid(row=0, column=1)

root = Tk()
root.title("Operaciones aritmeticas entre imagenes")
root.geometry("1200x800+50+50")  # width x height + x + y

#String vars
selected_filter = StringVar()
selected_filter.set("Elegir filtro")
#Flags
showing_hist = [False, False]

create_image_frame(root)
root.mainloop()


import hmac
import os

from typing import Union

from bip32 import BIP32
from bip_utils import Bech32Encoder, Bech32Decoder
from hashlib import blake2b, pbkdf2_hmac, sha512

from nacl import bindings
from nacl.signing import SigningKey, VerifyKey

from mimblewimble.crypto.bulletproof import EBulletproofType

from mimblewimble.crypto.commitment import Commitment
from mimblewimble.crypto.secret_key import SecretKey
from mimblewimble.crypto.public_keys import PublicKeys
from mimblewimble.crypto.rangeproof import RangeProof
from mimblewimble.crypto.pedersen import Pedersen

from mimblewimble.crypto.bulletproof import EBulletproofType
from mimblewimble.crypto.bulletproof import ProofMessage
from mimblewimble.crypto.bulletproof import RewoundProof
from mimblewimble.crypto.bulletproof import Bulletproof

class KeyChain:
    def __init__(self, master_key: bytes, bulletproof_nonce: SecretKey):
        self.master_key = master_key
        self.bulletproof_nonce = bulletproof_nonce

    def derivePrivateKey(self, path: str):
        # derive the seed at the path
        master_key = self.master_key.getBytes()
        bip32 = BIP32(
            chaincode=master_key[32:], privkey=master_key[:32])
        sk = bip32.get_privkey_from_path(path)
        return SecretKey(sk)

    def derivePrivateKeyAmount(self, path: str, amount: int):
        p = Pedersen()
        sk = self.derivePrivateKey(path)
        ska = p.blindSwitch(sk, amount)
        return ska

    def deriveED25519Seed(self, path: str):
        sk_der = self.derivePrivateKey(path)

        # compute the blake2 hash of that key and that is ed25519 seed
        seed_blake = blake2b(sk_der.getBytes(), digest_size=32).digest()
        return seed_blake

    def deriveED25519SecretKey(self, path: str):
        # get the seed
        seed_blake = self.deriveED25519Seed(path)

        # get the ed25519 secret key and public key from it
        pk, sk = bindings.crypto_sign_seed_keypair(seed_blake)
        return sk

    def deriveED25519PublicKey(self, path: str):
        # get the seed
        seed_blake = self.deriveED25519Seed(path)

        # get the ed25519 public key and public key from it
        pk, sk = bindings.crypto_sign_seed_keypair(seed_blake)
        return pk

    def signED25519(self, message: bytes, path: str) -> bytes:
        sk = self.deriveED25519SecretKey(path)
        signature = bindings.crypto_sign(message, sk)
        del sk
        return signature

    @classmethod
    def verifyED25519(
            self,
            public_key: Union[bytes, str],
            signature: bytes,
            message: bytes) -> bool:
        public_key_bytes = public_key
        if isinstance(public_key, str):
            public_key_bytes = KeyChain.slatepackAddressToED25519PublicKey(public_key)
        recovered = bindings.crypto_sign_open(signature, public_key_bytes)
        return recovered == message

    def deriveSlatepackAddress(self, path: str, testnet=False):
        pk = self.deriveED25519PublicKey(path)

        # compute the slatepack address
        network = 'grin'
        if testnet:
            network = 'tgrin'
        slatepack_address = Bech32Encoder.Encode(network, pk)

        return slatepack_address

    @classmethod
    def slatepackAddressToED25519PublicKey(
            self, address: str, testnet=False) -> bytes:
        # compute the slatepack address
        network = 'grin'
        if testnet:
            network = 'tgrin'

        public_key = Bech32Decoder.Decode(network, address)
        return public_key

    def rewindRangeProof(
            self,
            commitment: Commitment,
            rangeproof: RangeProof,
            bulletproof_type: EBulletproofType):
        b = Bulletproof()
        if bulletproof_type == EBulletproofType.ORIGINAL:
            nonce = KeyChain.createNonce(
                commitment, self.bulletproof_nonce)
            return b.rewindProof(
                commitment, rangeproof, nonce)
        elif bulletproof_type == EBulletproofType.ENHANCED:
            pks = PublicKeys()
            master_public_key = pks.calculatePublicKey(self.master_key)

            rewind_nonce_hash = SecretKey(blake2b(
                master_public_key.getBytes(),
                digest_size=32).digest())

            return b.rewindProof(
                commitment,
                rangeproof,
                KeyChain.createNonce(commitment, rewind_nonce_hash))
        raise ValueError('Unimplemented bulletproof type')

    def generateRangeProof(
            self,
            path: str,
            amount: int,
            commitment: Commitment,
            blinding_factor: SecretKey,
            bulletproof_type: EBulletproofType):

        key_indices = KeyChain.getKeyIndices(path)
        proof_message = ProofMessage.fromKeyIndices(
            key_indices, bulletproof_type)

        b = Bulletproof()
        if bulletproof_type == EBulletproofType.ORIGINAL:
            nonce = KeyChain.createNonce(
                commitment, self.bulletproof_nonce)
            return b.generateRangeProof(
                amount, blinding_factor, nonce, nonce, proof_message)
        elif bulletproof_type == EBulletproofType.ENHANCED:
            private_nonce_hash = SecretKey(blake2b(
                self.master_key.getBytes(),
                digest_size=32).digest())

            pks = PublicKeys()
            master_public_key = pks.calculatePublicKey(self.master_key)

            rewind_nonce_hash = SecretKey(blake2b(
                master_public_key.getBytes(),
                digest_size=32).digest())

            return b.generateRangeProof(
                amount,
                blinding_factor,
                KeyChain.createNonce(commitment, private_nonce_hash),
                KeyChain.createNonce(commitment, rewind_nonce_hash),
                proof_message)
        raise ValueError('Unimplemented bulletproof type')

    @classmethod
    def getKeyIndices(self, path: str):
        key_indices = []
        for v in path.split('/'):
            try:
                i = int(v)
            except:
                continue
            key_indices.append(i)
        return key_indices

    @classmethod
    def createNonce(self, commitment: Commitment, nonce_hash: SecretKey):
        nonce = blake2b(
            commitment.getBytes() + nonce_hash.getBytes(),
            digest_size=32).digest()
        return SecretKey(nonce)

    @classmethod
    def fromSeed(self, master_seed):
        # I AM VOLDEMORT
        m = hmac.new('IamVoldemort'.encode('utf8'), digestmod=sha512)
        m.update(master_seed)
        master_key = SecretKey(m.digest())
        p = Pedersen()
        bulletproof_nonce = p.blindSwitch(master_key, 0)
        return KeyChain(master_key, bulletproof_nonce)

    @classmethod
    def fromRandom(self):
        master_seed = os.urandom(32)
        return KeyChain.fromSeed(master_seed)


from django.conf import settings

from forj import constants
from forj.cart import Cart
from forj.models import Page

def base(request):
    default_currency = settings.DEFAULT_CURRENCY

    _, _, value = constants.CURRENCY_CHOICES.values[default_currency]

    cart = Cart.from_request(request)
    if cart is None:
        cart = Cart()

    return {
        "cart": cart,
        "page_list": Page.objects.order_by("rank"),
        "FORJ_PHONE_NUMBER": settings.FORJ_PHONE_NUMBER,
        "FORJ_CONTACT_EMAIL": settings.FORJ_CONTACT_EMAIL,
        "FORJ_INSTAGRAM_URL": settings.FORJ_INSTAGRAM_URL,
        "FORJ_FACEBOOK_URL": settings.FORJ_FACEBOOK_URL,
        "STATIC_URL": settings.STATIC_URL,
        "CURRENCY": default_currency,
        "CURRENCY_DISPLAY": value,
        "AMOUNT_PRECISION": settings.AMOUNT_PRECISION,
        "STRIPE_PUBLISHABLE_KEY": getattr(settings, "STRIPE_PUBLISHABLE_KEY", None),
        "STRIPE_SECRET_KEY": getattr(settings, "STRIPE_SECRET_KEY", None),
    }


import json
import cv2 as cv
import numpy as np

class AnnotationReader:
    def __init__(self, jsonpath="dsc_train/new.json", image_path='dsc_train/'):
        self._image_path = image_path
        with open(jsonpath) as file:
            self._json_file = json.load(file)

    def get_boxes(self, num):
        """
        Returns
        """
        boxes = self._json_file[num]['annotations'][0]['coordinates']
        x_center = int(boxes['x'])
        y_center = int(boxes['y'])
        width = int(boxes['width'])
        height = int(boxes['height'])

        x1 = int((x_center - int(width / 2)))
        x2 = int((x_center + int(width / 2)))
        y1 = int((y_center - int(height / 2)))
        y2 = int((y_center + int(height / 2)))

        return [x1, y1, x2, y2]

    def get_image(self, frame_num: int):
        filename = self._json_file[frame_num]['image']
        img = cv.imread(self._image_path+filename)
        return img

    def get_size(self):
        return len(self._json_file)

    def get_shape(self):
        "return x shape, y shape"
        return self.get_image(0).shape[1], self.get_image(0).shape[0]

    def get_name(self, num):
        "return x shape, y shape"
        return self._json_file[num]['image']

    @staticmethod
    def is_cross(a, b):
        ax1, ay1, ax2, ay2 = a[0], a[1], a[2], a[3]  # прямоугольник А
        bx1, by1, bx2, by2 = b[0], b[1], b[2], b[3]  # прямоугольник B
        # это были координаты точек диагонали по каждому прямоугольнику

        # 1. Проверить условия перекрытия, например, если XПA<XЛB ,
        #    то прямоугольники не пересекаются,и общая площадь равна нулю.
        #   (это случай, когда они справа и слева) и аналогично, если они сверху
        #    и снизу относительно друг друга.
        #    (XПА - это  Х Правой точки прямоугольника А)
        #    (ХЛВ - Х Левой точки прямоугольника В )
        #    нарисуй картинку (должно стать понятнее)

        xA = [ax1, ax2]  # координаты x обеих точек прямоугольника А
        xB = [bx1, bx2]  # координаты x обеих точке прямоугольника В

        yA = [ay1, ay2]  # координаты x обеих точек прямоугольника А
        yB = [by1, by2]  # координаты x обеих точек прямоугольника В

        if max(xA) < min(xB) or max(yA) < min(yB) or min(yA) > max(yB) or max(xB) < min(xA):
            return False  # не пересекаются

        # 2. Определить стороны прямоугольника образованного пересечением,
        # например,
        # если XПA>XЛB, а XЛA<XЛB, то ΔX=XПA−XЛB

        elif max(xA) > min(xB) and min(xA) < min(xB):
            dx = max(xA) - min(xB)
            return True  # пересекаются
        else:
            return True  # пересекаются
    @staticmethod
    def get_iou(boxA, boxB):
        # determine the (x, y)-coordinates of the intersection rectangle
        xA = max(boxA[0], boxB[0])
        yA = max(boxA[1], boxB[1])
        xB = min(boxA[2], boxB[2])
        yB = min(boxA[3], boxB[3])

        if not AnnotationReader.is_cross(boxA, boxB):
            return 0
        # compute the area of intersection rectangle
        interArea = abs(max((abs(xB - xA), 0)) * max(abs(yB - yA), 0))
        if interArea == 0:
            return 0
        # compute the area of both the prediction and ground-truth
        # rectangles
        boxAArea = (boxA[2] - boxA[0]) * (boxA[3] - boxA[1])
        boxBArea = (boxB[2] - boxB[0]) * (boxB[3] - boxB[1])
        boxAArea = abs(boxAArea)
        boxBArea = abs(boxBArea)
        # compute the intersection over union by taking the intersection
        # area and dividing it by the sum of prediction + ground-truth
        # areas - the interesection area
        iou = interArea / float(boxAArea + boxBArea - interArea)
        iou = abs(iou)
        if iou > 1:
            return 0
        # return the intersection over union value
        return abs(iou)

    @staticmethod
    def get_area(boxA):
        xA = boxA[0]
        yA = boxA[1]
        xB = boxA[2]
        yB = boxA[3]
        width = xA - xB
        height = yB - yA
        return abs(width * height)


import requests
import shutil
import os

from . import auth

DOWNLOAD_URL = "https://api.sketchfab.com/v3/models/{}/download"

def _get_download_url(uid):
    """Get download url for a model.

    Keyword arguments:
    uid -- The unique identifier of the model.
    """

    print(f"Getting download url for uid {uid}")
    r = requests.get(
        DOWNLOAD_URL.format(uid),
        headers={
            "Content-Type": "application/json",
            "Authorization": f"Token {auth.__API_TOKEN}",
        },
    )

    data = None
    try:
        data = r.json()
    except ValueError:
        pass

    assert r.ok, f"Failed to get download url for model {uid}: {r.status_code} - {data}"

    assert "gltf" in data, f"'gltf' field not found in response: {data}"
    gltf = data.get("gltf")

    assert "url" in gltf, f"'url' field not found in response: {data}"
    url = gltf.get("url")

    assert "size" in gltf, f"'size' field not found in response: {data}"
    size = gltf.get("size")

    return {"url": url, "size": size}

def download_model(model_uid, file_path):
    """Download a model.

    Keyword arguments:
    model_uid -- The unique identifier of the model.
    file_path -- The folder to store the downloaded model to.
    """

    data = _get_download_url(model_uid)

    # Construct path to same directory as download destination
    file_path.replace("\\", "/")
    parts = file_path.split("/")[:-1]
    if len(parts) == 0:
        parts.append(".")

    directory = ""
    for part in parts:
        directory += part + "/"

    assert os.path.exists(directory), f"Download directory '{directory}'' doesn't exist"

    download_path = f"{directory}{model_uid}.zip"

    print(f"Downloading model, size {(data['size'] / (1024 * 1024)):.1f}MB")
    with requests.get(data["url"], stream=True) as r:
        with open(download_path, "wb") as f:
            shutil.copyfileobj(r.raw, f)

    shutil.unpack_archive(download_path, file_path, "zip")
    os.unlink(download_path)

    print(f"Finished downloading to {file_path}")

    return file_path


import shutil

from kivy import utils
from kivy.clock import Clock
from kivy.core.text import LabelBase
from kivy.graphics.texture import Texture
from kivy.properties import ObjectProperty, StringProperty
from kivy.uix.image import Image
from kivy.uix.screenmanager import Screen, ScreenManager
from kivymd.app import MDApp
import cv2
import os
from kivymd.font_definitions import theme_font_styles
from kivymd.uix.button import MDIconButton, MDFloatingActionButtonSpeedDial
from kivymd.uix.label import MDLabel
from datetime import datetime

import measureDimension
import objectDetection
import textRecognition
import warpPerspective

pathImage = "images/1.jpg"
imgChosen = False
img = cv2.imread(pathImage)

class MainScreen(Screen):
    pass

class MainScreenManager(ScreenManager):
    screen_stack = []
    header_text = StringProperty()
    recognized_text = StringProperty()
    image_path = StringProperty()

    options = {
        'Warp Perspective': 'perspective-less',
        'Object Detection': 'cube-scan',
        'Recognize Text': 'text-recognition',
        'Measure': 'tape-measure',
    }

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

    def push(self, screen_name):
        if screen_name not in self.screen_stack:
            self.screen_stack.append(self.current)
            self.transition.direction = "up"
            self.current = screen_name

    def pop(self):
        if len(self.screen_stack) > 0:
            screen_name = self.screen_stack[-1]
            del self.screen_stack[-1]
            self.transition.direction = "down"
            self.current = screen_name

    def start_button_clicked(self):
        self.image_per_frame = Image(allow_stretch=True)
        self.header_text = 'Measure'
    #Object Detection
        self.tinyNetwork = objectDetection.initializeNetwork()
        self.network = objectDetection.initializeNetwork(tiny=False)
    #adding screen
        screen_layout = MainScreen(name='main_screen')
        self.add_widget(screen_layout)
    #displaying cam feed
        screen_layout.add_widget(self.image_per_frame)
    #capture button
        capture_button = MDIconButton(icon="camera-iris",
                                      pos_hint={"center_x": .5, "center_y": .1},
                                      user_font_size="45sp",
                                      theme_text_color="Custom",
                                      text_color= utils.get_color_from_hex('CEDFF0'))
        screen_layout.add_widget(capture_button)
        capture_button.bind(on_press=self.take_picture)

    #select from gallery button
        gallery_button = MDIconButton(icon='camera-burst',
                                      pos_hint={"center_x": .15, "center_y": .1},
                                      user_font_size="30sp",
                                      theme_text_color="Custom",
                                      text_color=utils.get_color_from_hex('CEDFF0')
                                      )
        screen_layout.add_widget(gallery_button)
        gallery_button.bind(on_press=self.open_gallery)
    #Floating Speed dial button
        speed_dial = MDFloatingActionButtonSpeedDial(callback= self.callback)
        speed_dial.data = self.options
        speed_dial.root_button_anim = True
        screen_layout.add_widget(speed_dial)
        self.ids['my_speed_dial'] = speed_dial
    #video capture
        self.capture = cv2.VideoCapture(0)
        Clock.schedule_interval(self.update, 1 / 60)
    #Adding Border
        screen_layout.add_widget(Image(source='ui/Border.png',
                                       allow_stretch=True,
                                       keep_ratio=False))
    #Flash Light Button
        flash_button = MDIconButton(icon='flash-off',
                                    pos_hint={"center_x": .1, "center_y": .95},
                                    user_font_size="20sp",
                                    theme_text_color="Custom",
                                    text_color=utils.get_color_from_hex('CEDFF0')
                                    )
        screen_layout.add_widget(flash_button)
        self.ids['my_flash_button'] = flash_button
        flash_button.bind(on_press= self.flash_button_pressed)
    #Close Button
        close_button = MDIconButton(icon='close',
                                    pos_hint={"center_x": .9, "center_y": .95},
                                    user_font_size="20sp",
                                    theme_text_color="Custom",
                                    text_color=utils.get_color_from_hex('CEDFF0'))
        screen_layout.add_widget(close_button)
        close_button.bind(on_press= self.close_button_clicked)
    #Header
        header_label = MDLabel(text=self.header_text,
                               halign="center",
                               font_style='Quicksand',
                               pos_hint={"center_y": .90})
        screen_layout.add_widget(header_label)
        self.ids['my_header_label'] = header_label

    def flash_button_pressed(self, value):
        if self.ids.my_flash_button.icon == 'flash-off':
            self.ids.my_flash_button.icon = 'flash'
        else:
            self.ids.my_flash_button.icon = 'flash-off'

    def close_button_clicked(self, value):
        MDApp.get_running_app().stop()

    def callback(self, instance):
        if instance.icon == 'tape-measure':
            self.header_text = 'Measure'
        elif instance.icon == 'text-recognition':
            self.header_text = 'Recognize Text'
        elif instance.icon == 'perspective-less':
            self.header_text = 'Warp Perspective'
        elif instance.icon == 'cube-scan':
            self.header_text = 'Object Detection'

        self.ids.my_header_label.text = self.header_text

    def update(self, *args):
        self.load_video()

    def createTexture(self, frame):
        buffer = cv2.flip(frame, 0).tobytes()
        texture = Texture.create(size=(frame.shape[1], frame.shape[0]), colorfmt='bgr')
        texture.blit_buffer(buffer, colorfmt='bgr', bufferfmt='ubyte')
        return texture

    def load_video(self, *args):
        ret, frame = self.capture.read()
        if not ret or imgChosen:
            frame = img
        self.image_per_frame_cv = frame
        if self.header_text == 'Warp Perspective' and self.header_text == 'Measure':
            texture = self.load_video_for_warpPerspective(frame)
            self.image_per_frame.texture = texture
        elif self.header_text == 'Object Detection':
            texture = self.load_video_for_object_detection(frame)
            self.image_per_frame.texture = texture
        else:
            texture = self.createTexture(frame)
            self.image_per_frame.texture = texture

    def load_video_for_warpPerspective(self, image_per_frame_cv):
        imgBigContour, warpedImg = warpPerspective.warpPers(image_per_frame_cv)
        texture = self.createTexture(imgBigContour)
        return texture

    def load_video_for_object_detection(self, image_per_frame_cv):
        #objectDetectedImg = objectDetection.detectObject(self.tinyNetwork, image_per_frame_cv)
        objectDetectedImg = image_per_frame_cv
        texture = self.createTexture(objectDetectedImg)
        return texture

    def take_picture(self, *args):
        now = datetime.now()
        image_name = 'Image'+now.strftime("_%Y_%m_%d_%H_%M_%S.png")
        imgCaptured = self.image_per_frame_cv
    #Recognize Text
        if self.header_text == 'Recognize Text':
            self.recognized_text = textRecognition.getText(self.image_per_frame_cv)
            imgCaptured = textRecognition.boundingBoxes(imgCaptured)
    #Object Detection
        elif self.header_text == 'Object Detection':
            imgCaptured = objectDetection.detectObject(self.network, imgCaptured)
    #Measure
        elif self.header_text == 'Measure':
            imgCaptured = measureDimension.measureDim(self.image_per_frame_cv)
    #WarpPerspective
        elif self.header_text == 'Warp Perspective':
            imgBigContour, warpedImg = warpPerspective.warpPers(self.image_per_frame_cv)
            imgCaptured = warpedImg

        cv2.imwrite(image_name, imgCaptured)
        self.image_path = image_name

        if self.header_text == 'Recognize Text':
            self.push('bottom_sheet_tr')
        else:
            self.push('bottom_sheet_all')

    def saveImage(self, imgPath):
        path = 'images'
        shutil.move(imgPath, path)

    def deleteCapturedImage(self, imgPath):
        if os.path.exists(imgPath):
            os.remove(imgPath)

    def open_gallery(self, *args):
        self.push('bottom_sheet_screen')

    def chooseImage(self, imgPath):
        global img
        img = cv2.imread(imgPath)
        global imgChosen
        imgChosen = True
        self.pop()

class OTDRSystem(MDApp):
    manager = ObjectProperty(None)
    def build(self):
        self.theme_cls.theme_style = "Dark"
        self.theme_cls.primary_palette = "Blue"
        self.theme_cls.primary_hue = "50"
        # Adding Custom Font
        LabelBase.register(name='Quicksand',
                           fn_regular='fonts/Quicksand-Regular.ttf')
        theme_font_styles.append('Quicksand')
        self.theme_cls.font_styles['Quicksand'] = ['Quicksand',
                                                   16,
                                                   False,
                                                   0.15, ]
        self.manager = MainScreenManager()

        return  self.manager

OTDRSystem().run()


import pyautogui
import time
import xlrd
import pyperclip

save_path='H:\\pythonProject\\test\\savepath\\'
i=1
symbol_location=pyautogui.locateCenterOnScreen('./img/symbol.png',confidence=0.9)
pyautogui.click(symbol_location.x-50, symbol_location.y+50, clicks=1, interval=0.2, duration=0.2, button='left')
while(i<10):
    print(i)
    pyautogui.hotkey('alt','a')
    pyautogui.click()
    save_location=pyautogui.locateCenterOnScreen('./img/save3.png',confidence=0.9)
    pyautogui.click(save_location.x-10,save_location.y,clicks=1,interval=0.2,duration=0.2,button='left')
    #symbol2_location = pyautogui.locateOnScreen('./symbol2.png', confidence=0.3)
    pyautogui.click(200, 450, clicks=1, interval=0.2, duration=0.2, button='left')
    pyautogui.hotkey('ctrl', 'a')
    pyautogui.press('backspace')
    inputValue=save_path+str(i)
    print(inputValue)
    pyautogui.click(200, 450, clicks=1, interval=0.2, duration=0.2, button='left')
    pyperclip.copy(inputValue)
    pyautogui.hotkey('ctrl', 'v')
    #save2_location = pyautogui.locateCenterOnScreen('./img/save2.png', confidence=0.9)
    pyautogui.click(800, 500, clicks=1, interval=0.2, duration=0.2, button='left')
    pyautogui.click(symbol_location.x - 50, symbol_location.y + 100, clicks=1, interval=0.2, duration=0.2, button='left')
    pyautogui.scroll(-120000)
    time.sleep(0.1)
    i=i+1