from tkinter import *
import tkinter as tk
from tkinter import ttk
import sqlite3
import tkinter.messagebox
import datetime
import os
import random
import math

pid=[]
pname=[]
pdiscount=[]
prate=[]
pquantity=[]
pamount=[]
product_list=[]

conn = sqlite3.connect("/home/babucode/Git/Python3-Programming/superStoreSoftware/database/store.db")
c = conn.cursor()

date = datetime.datetime.now().date()

class Application:
    def __init__(self,master,*args,**kwargs):
        self.master  = master

        self.heading = Label(master, text="ABC Super Store", font=("arial 30 bold"), fg="steelblue")
        self.heading.place(x=500, y= 10)

        #frames
        # left frame  to search anda  entry product details
        self.left_frame = Frame(master, width=350, height=600, bg="lightblue")
        self.left_frame.pack(side=LEFT,)
        self.left_frame.place(x=30,y=75)

        # middle frame for detailsview
        self.middle_frame = Frame(master, width=570, height=600, bg="grey")
        self.middle_frame.pack(side=RIGHT )
        self.middle_frame.place(x=390,y=75)

        # right frame to show bill
        self.right_frame = Frame(master, width=370, height=600, bg="lightblue")
        self.right_frame.pack(side=RIGHT )
        self.right_frame.place(x=970,y=75)

        # for left frame
        self.heading = Label(self.left_frame, text="Search for the product", font=("arial 20 bold"), bg="lightblue",fg="steelblue")
        self.heading.place(x=5, y= 20)

        self.labal_product_id = Label(self.left_frame,text=("Enter Product Id"), font=("arial 15 bold"), bg="lightblue", fg="black" )
        self.labal_product_id.place(x=10,y=70)

        self.entry_product_id = Entry(self.left_frame, width ="7",font=("arial 15 bold"),bg="white", fg="black")
        self.entry_product_id.place(x=150,y=70)

        self.btn_search= Button(self.left_frame, text=" Search",width ="7",height=1,font=("arial 12 bold"),bg="green", fg="black", command=self.see_details)
        self.btn_search.place(x=250,y=70)

        #getting details after calling the function
        self.labal_product_name = Label(self.left_frame,text=(""), font=("arial 15 bold"), bg="lightblue", fg="black" )
        self.labal_product_name.place(x=10,y=150)

        self.labal_number_of_stocks = Label(self.left_frame,text=(""), font=("arial 15 bold"), bg="lightblue", fg="black" )
        self.labal_number_of_stocks.place(x=10,y=200)

        self.labal_marked_price = Label(self.left_frame,text=(""), font=("arial 15 bold"), bg="lightblue", fg="black" )
        self.labal_marked_price.place(x=10,y=250)

        self.labal_change_amount = Label(self.left_frame,text="", font=("arial 13 bold"), bg="lightblue", fg="black" )
        self.labal_change_amount.place(x=10,y=470)

        # for middle frame

        self.table_frame = Frame(master, width=550, height=530, bg="white")
        self.table_frame.place(x=400,y=130)

        self.labal_id = Label(self.middle_frame,text=("Product Id"), font=("arial 15 bold"), bg="grey", fg="black" )
        self.labal_id.place(x=10,y=10)

        self.entry_id = Entry(self.middle_frame, width="10",font=("arial 15 bold"), bg="lightblue", fg="black" )
        self.entry_id.place(x=150,y=10)

        self.btn_show_detail= Button(self.middle_frame, text=" Show",width ="7",height=1,font=("arial 12 bold"),bg="green", fg="black", command=self.show_detail)
        self.btn_show_detail.place(x=300,y=10)

        self.btn_show_detailAll= Button(self.middle_frame, text=" Show All",width ="7",height=1,font=("arial 12 bold"),bg="green", fg="black",command=self.show_detailAll)
        self.btn_show_detailAll.place(x=450,y=10)

        self.horizontalScrollbar = ttk.Scrollbar(self.table_frame,orient='horizontal')
        self.verticalScrollbar = ttk.Scrollbar(self.table_frame,orient='vertical')

        self.trv = ttk.Treeview(self.table_frame,height="25",xscrollcommand=self.horizontalScrollbar,yscrollcommand=self.verticalScrollbar)

        self.trv['columns']=('Id','Product','Stocks','CostPrice','Mfd.Date','Exp.Date','Max.Ret.Price','MarkedPrice')

        self.horizontalScrollbar.pack(fill = X, side=BOTTOM)
        self.verticalScrollbar.pack(fill = BOTH, side=RIGHT)
        self.horizontalScrollbar.configure(command=self.trv.xview)
        self.verticalScrollbar.configure(command=self.trv.yview)

        self.trv['show']= 'headings'
        self.trv.column('Id',width=20,minwidth=20,anchor=tk.CENTER)
        self.trv.column('Product',width=125,minwidth=100,anchor=tk.CENTER)
        self.trv.column('Stocks',width=50,minwidth=50,anchor=tk.CENTER)
        self.trv.column('CostPrice',width=60,minwidth=50,anchor=tk.CENTER)
        self.trv.column('Mfd.Date',width=80,minwidth=70,anchor=tk.CENTER)
        self.trv.column('Exp.Date',width=80,minwidth=70,anchor=tk.CENTER)
        self.trv.column('Max.Ret.Price',width=60,minwidth=60,anchor=tk.CENTER)
        self.trv.column('MarkedPrice',width=60,minwidth=60,anchor=tk.CENTER)

        self.trv.heading('Id',text='Id',anchor=tk.CENTER)
        self.trv.heading('Product',text='Product',anchor=tk.CENTER)
        self.trv.heading('Stocks',text='Stock',anchor=tk.CENTER)
        self.trv.heading('CostPrice',text='C.P.',anchor=tk.CENTER)
        self.trv.heading('Mfd.Date',text='Mfd.Date',anchor=tk.CENTER)
        self.trv.heading('Exp.Date',text='Exp.Date',anchor=tk.CENTER)
        self.trv.heading('Max.Ret.Price',text='M.R.P.',anchor=tk.CENTER)
        self.trv.heading('MarkedPrice',text='M.P.',anchor=tk.CENTER)
        self.trv.pack(fill=BOTH)
        self.show_detailAll()

        # for the right frame
        self.labal_date_today= Label(self.right_frame, text= "Today's Date:"+ str(date), font=(" arial 10 bold"), bg="lightblue", fg="black")
        self.labal_date_today.place(x=200, y=10)

        self.tab_product = Label(self.right_frame, text= "Products",font=(" arial 11 bold"), bg="lightblue", fg="black")
        self.tab_product.place(x=20,y=50)

        self.tab_rate = Label(self.right_frame, text= "Rate",font=(" arial 11 bold"), bg="lightblue", fg="black")
        self.tab_rate.place(x=160,y=50)

        self.tab_quantity = Label(self.right_frame, text= "Quantity",font=(" arial 11 bold"), bg="lightblue", fg="black")
        self.tab_quantity.place(x=230,y=50)

        self.tab_amount = Label(self.right_frame, text= "Amount",font=(" arial 11 bold"), bg="lightblue", fg="black")
        self.tab_amount.place(x=310,y=50)

        self.labal_total_bill = Label(self.right_frame,text=(""), font=("arial 11 bold"), bg="lightgrey", fg="black" )
        self.labal_total_bill.place(x=190,y=450)

    def see_details(self,*args, **kwargs):

        self.get_id = self.entry_product_id.get()
        # getting the value from the data base nad filling the labal
        sql = "SELECT  product_id, product_name, number_of_stocks, marked_price FROM product_details WHERE  product_id=?"
        result = c.execute(sql,(self.get_id,))

        for self.r in result:
            if self.r[2]>0:
                self.get_product_id= self.r[0]
                self.get_product_name= self.r[1]
                self.get_number_of_stocks= self.r[2]
                self.get_marked_price= self.r[3]

            else:
                tkinter.messagebox.showinfo("Error!","Sorry!\nWe have no such Product...")

            self.labal_product_name.configure(text="Product Name:"+ str(self.get_product_name))
            self.labal_number_of_stocks.configure(text="Number of Stocks:"+ str(self.get_number_of_stocks))
            self.labal_marked_price.configure(text="Marked Price:"+ str(self.get_marked_price))

        # to enter the details of the product to sell.
        self.labal_quantity = Label(self.left_frame,text=("Quantity of Product"), font=("arial 13 bold"), bg="lightblue", fg="black" )
        self.labal_quantity.place(x=10,y=300)
        self.entry_quantity = Entry(self.left_frame, width ="10",font=("arial 15 bold"),bg="white", fg="black")
        self.entry_quantity.place(x=225,y=300)
        self.entry_quantity.focus()

        self.labal_discount = Label(self.left_frame,text=("Discount Amount"), font=("arial 13 bold"), bg="lightblue", fg="black" )
        self.labal_discount.place(x=10,y=340)
        self.entry_discount = Entry(self.left_frame, width ="10",font=("arial 15 bold"),bg="white", fg="black")
        self.entry_discount.place(x=225,y=340)
        self.entry_discount.insert(END,0)

        # to add to bill
        self.btn_add_to_cart= Button(self.left_frame, text=" Add to Cart",width ="11",height=1,font=("arial 11 bold"),bg="green", fg="black", command=self.add_to_cart)
        self.btn_add_to_cart.place(x=225,y=380)

        # for the amount change
        self.labal_given_amount = Label(self.left_frame,text=("Given Amount"), font=("arial 13 bold"), bg="lightblue", fg="black" )
        self.labal_given_amount.place(x=10,y=420)
        self.entry_given_amount = Entry(self.left_frame, width ="8",font=("arial 15 bold"),bg="white", fg="black")
        self.entry_given_amount.place(x=150,y=420)

        self.btn_make_change= Button(self.left_frame, text=" Change",width ="7",height=1,font=("arial 11 bold"),bg="yellow", fg="black", command=self.change)
        self.btn_make_change.place(x=255,y=420)

        # to generate the bill
        self.btn_generate_bill= Button(self.left_frame, text=" Generate Bill",width ="25",height=2,font=("arial 15 bold"),bg="red", fg="black", command=self.generate_bill)
        self.btn_generate_bill.place(x=25,y=520)

    def add_to_cart(self, *args, **kwargs):

        if int(self.entry_discount.get())>0:
            self.get_marked_price -=int(self.entry_discount.get())

        self.quantity = int(self.entry_quantity.get())

        if self.quantity > int(self.get_number_of_stocks):
           tkinter.messagebox.showinfo("Error!"," We have only limited Products.\n Number of" + str(self.get_product_name)+ " is "+ str(self.get_number_of_stocks))
        else:
            pid.append(self.get_product_id)
            pname.append(self.get_product_name)
            pdiscount.append(self.entry_discount.get())
            prate.append(self.get_marked_price)
            pquantity.append(self.entry_quantity.get())
            amount= int(self.entry_quantity.get()) * int(self.get_marked_price)
            pamount.append(amount)
            self.xin=20
            self.yin=70
            self.coun =0
            self.total_amount=0

            for self.p in pname:
                self.tempname= Label(self.right_frame, text=str(pname[self.coun]), font=("arial 10 bold"), bg="lightgreen", fg="black")
                self.tempname.place(x=20, y= self.yin)
                product_list.append(self.tempname)

                self.temprate= Label(self.right_frame, text=str(prate[self.coun]), font=("arial 10 bold"), bg="lightgreen", fg="black")
                self.temprate.place(x=160, y= self.yin)
                product_list.append(self.temprate)

                self.tempquantity= Label(self.right_frame, text=str(pquantity[self.coun]), font=("arial 10 bold"), bg="lightgreen", fg="black")
                self.tempquantity.place(x=230, y= self.yin)
                product_list.append(self.tempquantity)

                self.tempamount= Label(self.right_frame, text=str(pamount[self.coun]), font=("arial 10 bold"), bg="lightgreen", fg="black")
                self.tempamount.place(x=310, y= self.yin)
                product_list.append(self.tempamount)

                self.total_amount += pamount[self.coun]
                self.labal_total_bill.configure(text="Your Total Bill: Rs."+ str(self.total_amount))

                self.yin+=20
                self.coun +=1

            self.labal_product_name.configure(text="")
            self.labal_number_of_stocks.configure(text="")
            self.labal_marked_price.configure(text="")

            self.labal_quantity.place_forget()
            self.entry_quantity.place_forget()

            self.labal_discount.place_forget()
            self.entry_discount.place_forget()

            self.btn_add_to_cart.destroy()

            self.entry_product_id.focus()
            self.entry_product_id.delete(0,END)

    def change(self, *args, **kwargs):
        self.bill_given_amount= float(self.entry_given_amount.get())
        self.bill_total_amount = float(self.total_amount)

        if  self.bill_total_amount <= self.bill_given_amount:
            self.bill_change_amount = float(self.bill_given_amount- self.bill_total_amount)
            self.labal_change_amount.configure(text=" Your Change Amount:"+str(self.bill_change_amount))

        elif self.bill_total_amount > self.bill_given_amount:
            self.bill_change_amount = self.bill_total_amount-float(self.bill_given_amount)
            self.entry_given_amount.focus()
            self.entry_given_amount.delete(0,END)
            tkinter.messagebox.showinfo("Error!","The Given Amount is insufficient.\n Rs." + str(self.bill_change_amount)+ " is Required!")
        else:
            self.entry_given_amount.focus()
            self.entry_given_amount.delete(0,END)
            tkinter.messagebox.showinfo("Error!","The Given Amount is insufficient.\n Or \n More Amount is Required!  ")

    def generate_bill(self, *args, **kwargs):

        # create the bill before updating the database
        directory ="/home/babucode/Git/Python3-Programming/superStoreSoftware/bill/bill_"+str(date)+".docx"
        if os.path.exists(directory):
            os.makedirs(directory)

        # tempalte for the bill
        comapny = "\n\t\t\t\t\tABC Super Store \n"
        address = "\t\t\t\t\tKathmandu-19, Nepal\n"
        phone =   "\t\t\t\t\tPhone:015161741\n"
        sample =  "\t\t\t\t\tInvoice\n"
        dt=       "\t\t\t\t\t"+str(date)

        table_header = "\n\n\t---------------------------------------------------------------------------\n\tS.n.\tProduct name\t\t Rate\t\tQuantity\tAmount\n\t---------------------------------------------------------------------------"
        final = comapny+address+phone+sample+dt+"\n"+table_header

        file_name =str(directory)+str(random.randrange(5000,10000))

        f = open(file_name,'w')

        f.write(final)
        r = 0
        for t in pname:
            f.write("\n\t"+str(r+1)+"\t"+str(pname[r][:10])+"\t\t"+str(prate[r])+"\t\t"+str(pquantity[r])+"\t\t"+str(pamount[r]))
            r+=1
        f.write("\n\t---------------------------------------------------------------------------\n\t\t\t\t\t\tYour Total bill is Rs."+ str(sum(pamount)))
        f.write("\n\t\tThank you! for visiting Us.........\t\tUser:")
        # os.startfile(file_name, "print")
        f.close()

        # to make change quantity
        self.x=0
        sql= "SELECT * FROM product_details WHERE product_id=?"
        result=c.execute(sql,(pid[self.x],))
        for i in pname:

            for r in result:
                self.old_stock = r[2]

            self.new_stock= int(self.old_stock)-int(pquantity[self.x])
            sql = "UPDATE product_details SET number_of_stocks=? WHERE product_id=?"
            c.execute(sql,(self.new_stock,pid[self.x]))
            conn.commit()

            sql2 = "INSERT INTO transactions (product_id, product_name,discount,selling_price,quantity, amount, date) VALUES (?,?,?,?,?,?,?)"
            c.execute(sql2,(pid[self.x],pname[self.x],pdiscount[self.x],prate[self.x], pquantity[self.x],pamount[self.x],date))
            conn.commit()

            self.x+=1

        for a in product_list:
            a.destroy()

        del(pid[:])
        del(pname[:])
        del(pdiscount[:])
        del(prate[:])
        del(pquantity[:])
        del(pamount[:])
        self.labal_total_bill.configure(text="")
        self.entry_given_amount.delete(0,END)
        self.labal_change_amount.configure(text="")
        del self.total_amount

        tkinter.messagebox.showinfo("Success","Done!\nCompletelly...")

    def show_detail(self, *args, **kwargs):
        self.get_id = self.entry_id.get()
        # getting the value from the data base nad filling the labal
        sql = "SELECT  product_id, product_name, number_of_stocks,cost_price, manufacture_date,expiry_date,maximum_retail_price, marked_price,remarks FROM product_details WHERE  product_id=?"

        c.execute(sql,(self.get_id,))

        self.rows=c.fetchall()
        if len(self.rows)!=0:
            self.trv.delete(*self.trv.get_children())
            self.i =0
            for row in self.rows:

                self.trv.insert('',self.i,text='',values=(row[0],row[1],row[2],row[3],row[4],row[5],row[6],row[7],row[8]))
                self.i+=1
        self.entry_id.delete(0,END)

    def show_detailAll(self, *args, **kwargs):

        sql = "SELECT  product_id, product_name, number_of_stocks,cost_price, manufacture_date,expiry_date,maximum_retail_price, marked_price,remarks FROM product_details "
        c.execute(sql)
        self.rows=c.fetchall()

        if len(self.rows)!=0:
            self.trv.delete(*self.trv.get_children())
            self.i =0
            for row in self.rows:

                self.trv.insert('',self.i,text='',values=(row[0],row[1],row[2],row[3],row[4],row[5],row[6],row[7],row[8]))
                self.i+=1
        conn.commit()

root = Tk()
b = Application(root)
root.geometry("1356x768+0+0")
root.title("Sell Product Page")
root.resizable(False,False)
root.mainloop()


""" Workout Tracker API implemented using Google Cloud Endpoints.
"""

import endpoints
from protorpc import messages
from protorpc import message_types
from protorpc import remote

from google.appengine.api import users
from google.appengine.ext import ndb

package = 'Workout'

# class Exercise(ndb.Model):
#   sets = ndb.IntegerProperty()
#   reps = ndb.IntegerProperty()
#   routineKey = ndb.KeyProperty(kind='Routine')

# class Workout(ndb.Model):
#   name = ndb.StringProperty()
#   exercises = ndb.KeyProperty(kind='Exercise', repeated=True)

# class WorkoutSession(ndb.Model):
#   user = ndb.UserProperty()
#   timeStamp = ndb.DateTimeProperty()
#   workout = ndb.KeyProperty(kind='Workout');

# class Exercise(messages.Message):
#   """ A routine with sets and reps. """
#   id = messages.StringField(1)
#   routine = messages.MessageField(Routine, 2)
#   sets = messages.IntegerField(3)
#   reps = messages.IntegerField(4)
#   time_stamp = message_types.DateTimeField(5)

# class Workout(messages.Message):
#   """ A workout session consisting of multiple exercises. """
#   id = messages.StringField(1)
#   exercises = messages.MessageField(Exercise, 2, repeated=True)

class RoutineModel(ndb.Model):
    name = ndb.StringProperty()
    description = ndb.TextProperty()

    def to_message(self):
        return Routine(id=self.key.id(),
            name = self.name,
            description= self.description)

    @classmethod
    def from_message(cls, message):
        if message.id:
            key = ndb.Key('RoutineModel', message.id)
            model = key.get()
            model.name = message.name
            model.description = message.description
            return model
        else:
             return cls(name=message.name, description=message.description)

class Routine(messages.Message):
    """ A workout routine."""
    id = messages.IntegerField(1)
    name = messages.StringField(2)
    description = messages.StringField(3)

class RoutineCollection(messages.Message):
    """ A collection of routines """
    items = messages.MessageField(Routine, 1, repeated=True)

class ExerciseModel(ndb.Model):
    sets = ndb.IntegerProperty()
    reps = ndb.IntegerProperty()
    routine_key = ndb.KeyProperty(kind='Routine')
    time_stamp = ndb.DateTimeProperty()

    def to_message(self):
        return Exercise(id=self.key.id(),
            sets = self.sets,
            reps = self.reps,
            time_stamp = self.time_stamp,
            routine = self.routineKey.get().to_message())

    @classmethod
    def from_message(cls, message):
        if message.id:
            key = ndb.Key('ExerciseModel', message.id)
            model = key.get()
            model.sets = message.sets
            model.reps = message.reps
            model.time_stamp = message.time_stamp
            model.routine_key = ndb.key('RoutineModel', message.routine.id)
            return model;
        else:
            return cls(sets=message.sets, reps=message.reps,
                routineKey= ndb.key('RoutineModel', message.routine.id))

class Exercise(messages.Message):
    """ An exercise. """
    id = messages.IntegerField(1)
    sets = messages.IntegerField(2)
    reps = messages.IntegerField(3)
    time_stamp = message_types.DateTimeField(4)
    routine = messages.MessageField(Routine, 5)

class ExerciseCollection(messages.Message):
    """ A collection of exercises"""
    items = messages.MessageField(Exercise, 1, repeated=True)

class Exercise(messages.Message):
    id = messages.IntegerField(1)

@endpoints.api(name='workout', version='v1')
class WorkoutApi(remote.Service):
    """Workout API v1."""

    ID_RESOURCE = endpoints.ResourceContainer(
        message_types.VoidMessage,
        id=messages.IntegerField(1))

    @endpoints.method(message_types.VoidMessage, RoutineCollection,
                      path='routine', http_method='GET',
                      name='routines.listRoutines')
    def routines_list(self, unused_request):
        routines = RoutineModel.query().order(RoutineModel.name)
        return RoutineCollection(
            items=map(lambda r: r.to_message(), routines))

    @endpoints.method(ID_RESOURCE, Routine,
                      path='routine/{id}', http_method='GET',
                      name='routines.getRoutine')
    def routine_get(self, request):
        try:
            key = ndb.Key('RoutineModel', request.id)
            return key.get().to_message()
        except (IndexError, TypeError):
            raise endpoints.NotFoundException('Routine %s not found.' %
                                              (request.id))

    @endpoints.method(Routine, Routine, path='routine', http_method='POST',
                      name='routines.postRoutine')
    def routine_post(self, request):
        model = RoutineModel.from_message(request)
        model.put()
        return model.to_message()

    @endpoints.method(message_types.VoidMessage, ExerciseCollection,
                      path='exercise', http_method='GET',
                      name='exercises.listExercise')
    def exercises_list(self, unused_request):
        exercises = ExerciseModel.query().order(ExerciseModel.time_stamp)
        return ExerciseCollection(
            items=map(lambda e: e.to_message(), exercises))

    @endpoints.method(ID_RESOURCE, Exercise,
                      path='exercise/{id}', http_method='GET',
                      name='exercises.getExercise')
    def exercise_get(self, request):
        try:
            key = ndb.Key('ExerciseModel', request.id)
            return key.get().to_message()
        except (IndexError, TypeError):
            raise endpoints.NotFoundException('Exercise %s not found',
                (request.id))

    @endpoints.method(Exercise, Exercise, path='exercise', http_method='POST',
                      name='exercises.postExercise')
    def exercise_post(self, request):
        model = ExerciseModel.from_message(request)
        model.put()
        return model.to_message()

app = endpoints.api_server([WorkoutApi])


import logging
import os
from flask import Flask
from config import Config
from flask_mail import Mail
from flask_migrate import Migrate
from flask_moment import Moment
from flask_login import LoginManager
from flask_bootstrap import Bootstrap
from flask_sqlalchemy import SQLAlchemy
from logging.handlers import SMTPHandler, RotatingFileHandler

mail = Mail()
db = SQLAlchemy()
migrate = Migrate()
moment = Moment()
login = LoginManager()
bootstrap = Bootstrap()
login.login_view = 'auth.login'
login.login_message_category = "info"

# define the name of your app below
APP_NAME = 'Template - Name'
app = Flask(__name__)

def create_app(config_class=Config):
    app = Flask(__name__)
    app.config.from_object(config_class)

    db.init_app(app)
    login.init_app(app)
    bootstrap.init_app(app)
    moment.init_app(app)
    migrate.init_app(app, db)
    mail.init_app(app)

    # import the blueprint
    from app.auth.routes import auth
    from app.main.routes import main
    from app.rooms.routes import rooms
    from app.errors.handlers import errors
    from app.bookings.routes import bookings

    # register the blueprint
    app.register_blueprint(auth)
    app.register_blueprint(main)
    app.register_blueprint(rooms)
    app.register_blueprint(errors)
    app.register_blueprint(bookings)

    if not app.debug and not app.testing:
        if app.config['MAIL_SERVER']:
            auth = None
            if app.config['MAIL_USERNAME'] or app.config['MAIL_PASSWORD']:
                auth = (app.config['MAIL_USERNAME'],
                        app.config['MAIL_PASSWORD'])
            secure = None
            if app.config['MAIL_USE_TLS']:
                secure = ()
            mail_handler = SMTPHandler(
                mailhost=(app.config['MAIL_SERVER'], app.config['MAIL_PORT']),
                fromaddr='no-reply@' + app.config['MAIL_SERVER'],
                toaddrs=app.config['ADMINS'], subject=f'{APP_NAME} Failure',
                credentials=auth, secure=secure)
            mail_handler.setLevel(logging.ERROR)
            app.logger.addHandler(mail_handler)

        if not os.path.exists('logs'):
            os.mkdir('logs')
        file_handler = RotatingFileHandler(f'logs/{APP_NAME.lower()}.log',
                                           maxBytes=10240, backupCount=10)
        file_handler.setFormatter(logging.Formatter(
            '%(asctime)s %(levelname)s: %(message)s '
            '[in %(pathname)s:%(lineno)d]'))
        file_handler.setLevel(logging.INFO)
        app.logger.addHandler(file_handler)

        app.logger.setLevel(logging.INFO)
        app.logger.info(f'{APP_NAME} startup')

    return app


import re
import requests
import string
from collections import deque
import numpy as np
from itertools import combinations
import jax
import jax.numpy as jnp
from jax.config import config
from functools import partial
config.update("jax_enable_x64", True)

extract_single_props = {'Molecular Weight' : 'Mw',
                        'Critical Temperature' : 'Tc',
                        'Critical Pressure' : 'Pc',
                        'Critical Volume' : 'Vc',
                        'Acentric factor' : 'w',
                        'Normal boiling point' : 'Tb',
                        'Heat of vaporization' : 'HvapNb'}

extract_coeff_props={'Vapor Pressure' : 'Pvap',
                     'Ideal Gas Heat Capacity' : 'CpIG',
                     'Liquid Heat Capacity' : 'CpL',
                     'Solid Heat Capacity' : 'CpS',
                     'Heat of Vaporization' : 'Hvap'}
base_url = 'https://raw.githubusercontent.com/profteachkids/CHE2064/master/data/'

BIP_file = 'https://raw.githubusercontent.com/profteachkids/CHE2064/master/data/BinaryNRTL.txt'

class Props():
    def __init__(self,comps, get_NRTL=True, base_url=base_url, extract_single_props=extract_single_props,
                 extract_coeff_props=extract_coeff_props, BIP_file=BIP_file, suffix='Props.txt'):

        comps = [comps] if isinstance(comps,str) else comps
        self.N_comps = len(comps)

        id_pat = re.compile(r'ID\s+(\d+)')
        formula_pat = re.compile(r'Formula:\s+([A-Z0-9]+)')
        single_props_pat = re.compile(r'^\s+([\w \/.]+?)\s+:\s+([-.0-9e+]+)\s+[\w\s/]*$', re.MULTILINE)
        coeffs_name_pat = re.compile(r"([\w ]+)\s[^\n]*?Equation.*?Coeffs:([- e\d.+]+)+?", re.DOTALL)
        coeffs_pat = re.compile(r'([-\de.+]+)')

        props_deque=deque()
        for comp in comps:
            res = requests.get(base_url+comp + suffix)
            if res.status_code != 200:
                raise ValueError(f'{comp} - no available data')
            text=res.text
            props={'Name': comp}
            props['ID']=id_pat.search(text).groups(1)[0]
            props['Formula']=formula_pat.search(text).groups(1)[0]
            single_props = dict(single_props_pat.findall(text))
            for k,v in extract_single_props.items():
                props[v]=float(single_props.pop(k))

            coeffs_name_strings = dict(coeffs_name_pat.findall(text))
            for k,v in extract_coeff_props.items():
                coeffs = coeffs_pat.findall(coeffs_name_strings[k])
                for letter, value in zip(string.ascii_uppercase,coeffs):
                    props[v+letter]=float(value)
            props_deque.append(props)

        for prop in props_deque[0].keys():
            if self.N_comps>1:
                values = np.array([comp[prop] for comp in props_deque])
            else:
                values = props_deque[0][prop]
            setattr(self,prop,values)

        if (self.N_comps > 1) and get_NRTL:
            text = requests.get(BIP_file).text

            comps_string = '|'.join(self.ID)
            id_name_pat = re.compile(r'^\s+(\d+)[ ]+(' + comps_string +')[ ]+[A-Za-z]',re.MULTILINE)
            id_str = id_name_pat.findall(text)
            #maintain order of components
            id_dict = {v:k for k,v in id_str}
            id_str = [id_dict[id] for id in self.ID]
            comb_strs = combinations(id_str,2)
            comb_indices = combinations(range(self.N_comps),2)
            self.NRTL_A, self.NRTL_B, self.NRTL_C, self.NRTL_D, self.NRTL_alpha = np.zeros((5, self.N_comps,self.N_comps))
            start=re.search(r'Dij\s+Dji',text).span()[0]

            for comb_str, comb_index in zip(comb_strs, comb_indices):
                comb_str = '|'.join(comb_str)
                comb_values_pat = re.compile(r'^[ ]+(' + comb_str +
                                             r')[ ]+(?:' + comb_str + r')(.*)$', re.MULTILINE)

                first_id, values = comb_values_pat.search(text[start:]).groups(1)
                #if matched order is flipped, also flip indices
                if first_id != comb_index[0]:
                    comb_index = (comb_index[1],comb_index[0])
                bij, bji, alpha, aij, aji, cij, cji, dij, dji  = [float(val) for val in values.split()]
                np.add.at(self.NRTL_B, comb_index, bij)
                np.add.at(self.NRTL_B, (comb_index[1],comb_index[0]), bji)
                np.add.at(self.NRTL_A, comb_index, aij)
                np.add.at(self.NRTL_A, (comb_index[1],comb_index[0]), aji)
                np.add.at(self.NRTL_C, comb_index, cij)
                np.add.at(self.NRTL_C, (comb_index[1],comb_index[0]), cji)
                np.add.at(self.NRTL_D, comb_index, dij)
                np.add.at(self.NRTL_D, (comb_index[1],comb_index[0]), dji)
                np.add.at(self.NRTL_alpha, comb_index, alpha)
                np.add.at(self.NRTL_alpha, (comb_index[1],comb_index[0]), alpha)

    @partial(jax.jit, static_argnums=(0,))
    def Pvap(self,T):
        T=jnp.squeeze(T)
        return jnp.exp(self.PvapA + self.PvapB/T + self.PvapC*jnp.log(T) +
                       self.PvapD*jnp.power(T,self.PvapE))

    @partial(jax.jit, static_argnums=(0,))
    def CpIG(self, T):
        T=jnp.squeeze(T)
        return (self.CpIGA + self.CpIGB*(self.CpIGC/T/jnp.sinh(self.CpIGC/T))**2 +
                self.CpIGD*(self.CpIGE/T/jnp.cosh(self.CpIGE/T))**2)

    @partial(jax.jit, static_argnums=(0,))
    def Hvap(self, T):
        T=jnp.squeeze(T)
        Tr = T/self.Tc
        return (self.HvapA*jnp.power(1-Tr, self.HvapB + (self.HvapC+(self.HvapD+self.HvapE*Tr)*Tr)*Tr ))

    @partial(jax.jit, static_argnums=(0,))
    def deltaHsensL(self, T):
        T=jnp.squeeze(T)
        return T * (self.CpLA + T * (self.CpLB / 2 + T * (self.CpLC / 3 + T * (self.CpLD / 4 + self.CpLE / 5 * T))))

    @partial(jax.jit, static_argnums=(0,))
    def Hmix(self, nV, nL, T):
        T=jnp.squeeze(T)

        return jnp.dot(nL + nV, self.deltaHsensL(T)) + jnp.dot(nV, self.Hvap(T))

    @partial(jax.jit, static_argnums=(0,))
    def NRTL_gamma(self, x, T):
        tau = (self.NRTL_A + self.NRTL_B / T + self.NRTL_C * jnp.log(T) +
               self.NRTL_D * T)
        G = jnp.exp(-self.NRTL_alpha * tau)

        xG=jnp.dot(x,G)
        xtauGdivxG = jnp.dot(x,tau * G) / xG
        lngamma = xtauGdivxG + jnp.dot((x / xG), (G * (tau - xtauGdivxG)).T)
        return jnp.exp(lngamma)

@jax.jit
def qtox(q):
    q=jnp.atleast_1d(q)
    xm1 = jnp.exp(q)/(1+jnp.sum(jnp.exp(q)))
    return jnp.concatenate((xm1, jnp.atleast_1d(1.-jnp.sum(xm1))))

@jax.jit
def xtoq(x):
    x=jnp.atleast_1d(x)
    return jnp.log(x[:-1]) + jnp.log(1.+ (1. - x[-1])/x[-1])

if __name__=='__main__':
    p=Props(['Isopropanol','Water'])
    print(p.Pvap(300))


# -*- coding: utf-8 -*-
"""
Created on Thu Feb 23 23:38:44 2017

@author: HSIN
"""

from PIL import Image
import numpy as np
import sys

im = Image.open(sys.argv[1])
im_modified = Image.open(sys.argv[2])

im_np_data = np.array(im.getdata())
im_modified_np_data = np.array(im_modified.getdata())
im_diff = im_np_data - im_modified_np_data

ans_two = Image.new('RGBA', im.size, color = None)

for i in range(len(im_np_data)):
    if not np.array_equal(im_diff[i], [0, 0, 0, 0]):
        ans_two.putpixel((i%im.size[0], int(i/im.size[0])), tuple(im_modified_np_data[i]))

ans_two.save('ans_two.png')


from OpenGL import GLU
import numpy as np
import realcomp
from realcomp.envs.realcomp_env import Goal
import gym

import os
import inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(os.path.dirname(currentdir))
os.sys.path.insert(0,parentdir)
from my_controller import MyController

Controller = MyController

scores = {}

def add_scores(challenge, score):
    if challenge in scores.keys():
        scores[challenge] += [score]
    else:
        scores[challenge] = [score]

def report_score():
    print("*****************")
    total_score = 0
    challenges = ['2D','2.5D','3D']
    for key in challenges:
        if key in scores.keys():
            results = scores[key]
            formatted_results = ", ".join(["{:.4f}".format(r) for r in results])
            challenge_score = np.mean(results)
        else:
            results = []
            formatted_results = "None"
            challenge_score = 0

        print("Challenge {} - {:.4f}".format(key, challenge_score))
        print("Goals: {}".format(formatted_results))
        total_score += challenge_score
    total_score /= len(challenges)
    print("Overall Score: {:.4f}".format(total_score))
    print("*****************")

def demo_run(extrinsic_trials=350):

    env = gym.make('REALComp-v0')
    controller = Controller(env.action_space)

    # change length of simulation for testing purposes
    env.intrinsic_timesteps = 1e7 #default = 1e7
    env.extrinsic_timesteps = 2e3 #default = 2e3

    # render simulation on screen
    # env.render('human')

    # reset simulation
    observation = env.reset()

    reward = 0
    done = False

    # intrinsic phase
    print("Starting intrinsic phase...")
    while not done:

        # Call your controller to chose action
        action = controller.step(observation, reward, done)

        # do action
        observation, reward, done, _ = env.step(action)

        # get frames for video making
        # rgb_array = env.render('rgb_array')

    # extrinsic phase
    print("Starting extrinsic phase...")
    totalScore = 0
    for k in range(extrinsic_trials):

        # reset simulation
        observation = env.reset()
        reward = 0
        done = False

        # set the extrinsic goal to pursue
        env.set_goal()
        print("Starting extrinsic trial...")

        while not done:

            # Call your controller to chose action
            action = controller.step(observation, reward, done)

            # do action
            observation, reward, done, _ = env.step(action)

            # get frames for video making
            # rgb_array = env.render('rgb_array')

        add_scores(*env.evaluateGoal())
        print("Current score:")
        report_score()

    print("Final score:")
    report_score()

if __name__=="__main__":
    demo_run()


from flask import Flask,jsonify, request

app = Flask(__name__)

@app.route('/getRecommendations')
def hello_world():
    id = request.args.get('id')
    try:
        return jsonify({"answer":int(id)})
    except (ValueError,TypeError):
        return jsonify({"answer":"please type integer id"})

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=9600, debug=True)


from __future__ import print_function, absolute_import, division

import tempfile

import pytest
import numpy as np
from astropy.wcs import WCS
from astropy.io import fits

from numpy.testing import assert_allclose

from ..casa_low_level_io import getdesc
from ..casa_wcs import wcs_casa2astropy
from ...tests.test_casafuncs import make_casa_testimage
from .test_casa_low_level_io import ALL_DATA_FIXTURES
from ...conftest import HEADER_FILENAME

try:
    from casatools import image
    CASATOOLS_INSTALLED = True
except ImportError:
    CASATOOLS_INSTALLED = False

@pytest.fixture
def filename(request):
    return request.getfixturevalue(request.param)

def assert_header_correct(casa_filename):

    fits_filename = tempfile.mktemp()

    # Use CASA to convert back to FITS and use that header as the reference

    ia = image()
    ia.open(casa_filename)
    ia.tofits(fits_filename, stokeslast=False)
    ia.done()
    ia.close()

    # Parse header with WCS - for the purposes of this function
    # we are not interested in keywords/values not in WCS
    reference_wcs = WCS(fits_filename)
    reference_header = reference_wcs.to_header()

    # Now use our wcs_casa2astropy function to create the header and compare
    # the results.
    desc = getdesc(casa_filename)
    actual_wcs = wcs_casa2astropy(desc['_keywords_']['coords'])
    actual_header = actual_wcs.to_header()

    assert sorted(actual_header) == sorted(reference_header)

    for key in reference_header:
        if isinstance(actual_header[key], str):
            assert actual_header[key] == reference_header[key]
        else:
            assert_allclose(actual_header[key], reference_header[key])

@pytest.mark.skipif('not CASATOOLS_INSTALLED')
@pytest.mark.parametrize('filename', ALL_DATA_FIXTURES, indirect=['filename'])
def test_wcs_casa2astropy(tmp_path, filename):
    casa_filename = str(tmp_path / 'casa.image')
    make_casa_testimage(filename, casa_filename)
    assert_header_correct(casa_filename)

@pytest.mark.skipif('not CASATOOLS_INSTALLED')
def test_wcs_casa2astropy_linear(tmp_path):

    # Test that things work properly when the WCS coordinates aren't set

    casa_filename = str(tmp_path / 'test.image')

    data = np.random.random((3, 4, 5, 6, 7))

    ia = image()
    ia.fromarray(outfile=casa_filename, pixels=data, log=False)
    ia.close()

    assert_header_correct(casa_filename)

def header_copy_with(**kwargs):
    header = fits.Header.fromtextfile(HEADER_FILENAME).copy()
    header.update(kwargs)
    return header

ALL_HEADERS = [
    header_copy_with(),
    header_copy_with(CTYPE1='GLON-TAN', CTYPE2='GLAT-TAN'),
    header_copy_with(CTYPE1='SLON-TAN', CTYPE2='SLAT-TAN'),
    header_copy_with(CTYPE1='ELON-TAN', CTYPE2='ELAT-TAN'),
    header_copy_with(CTYPE1='HLON-TAN', CTYPE2='HLAT-TAN'),
    header_copy_with(SPECSYS=''),
    header_copy_with(SPECSYS='TOPOCENT'),
    header_copy_with(SPECSYS='GEOCENTR'),
    header_copy_with(SPECSYS='BARYCENT'),
    header_copy_with(SPECSYS='HELIOCEN'),
    header_copy_with(SPECSYS='LSRK'),
    header_copy_with(SPECSYS='LSRD'),
    header_copy_with(SPECSYS='GALACTOC'),
    header_copy_with(SPECSYS='LOCALGRP'),
    header_copy_with(SPECSYS='CMBDIPOL'),
    header_copy_with(SPECSYS='SOURCE'),
    header_copy_with(RADESYS='FK4'),
    header_copy_with(RADESYS='FK4-NO-E'),
    header_copy_with(RADESYS='FK5'),
    header_copy_with(RADESYS='ICRS'),
    header_copy_with(EQUINOX=1950.),
    header_copy_with(EQUINOX=1979.9),
    header_copy_with(EQUINOX=2000),
    header_copy_with(EQUINOX=2010),
    header_copy_with(CTYPE3='FREQ', CUNIT3='GHz', CRVAL3=100., CDELT3=1.),
    header_copy_with(CTYPE3='WAVE', CUNIT3='m', CRVAL3=1e-6, CDELT3=1e-8),
    header_copy_with(CTYPE3='VOPT'),
    header_copy_with(CTYPE3='VRAD')
]

@pytest.mark.skipif('not CASATOOLS_INSTALLED')
@pytest.mark.parametrize('header', ALL_HEADERS)
def test_wcs_casa2astropy_additional(tmp_path, header):

    # More cases to improve coverage

    casa_filename = str(tmp_path / 'casa.image')
    fits_filename = str(tmp_path / 'casa.fits')

    fits.writeto(fits_filename, np.ones((2, 3, 4, 5)), header)

    make_casa_testimage(fits_filename, casa_filename)

    assert_header_correct(casa_filename)


from django.http import HttpResponse
from django.shortcuts import render, redirect
from .forms import *
from .models import *
import os
import cv2
import math
import numpy as np
from PIL import Image as im
from django.core.files.base import ContentFile

#paragraph segmentation
def ParagraphSegmentation(img):
    image = img.copy()
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    blur = cv2.GaussianBlur(gray, (7,7), 0)
    thresh = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

    # Create rectangular structuring element and dilate
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5,5))
    dilate = cv2.dilate(thresh, kernel, iterations=4)

    # Find contours and draw rectangle
    cnts = cv2.findContours(dilate, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    cnts = cnts[0] if len(cnts) == 2 else cnts[1]
    for c in cnts:
        x,y,w,h = cv2.boundingRect(c)
        cv2.rectangle(image, (x, y), (x + w, y + h), (255, 0, 0), 3)
    return image

# Word Segmentation
def WordSegmentation(img):
    image = img.copy()
    gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
    #binary
    ret,thresh = cv2.threshold(gray,127,255,cv2.THRESH_BINARY_INV)
    #dilation
    kernel = np.ones((5,5), np.uint8)
    img_dilation = cv2.dilate(thresh, kernel, iterations=1)
    #find contours
    contours, hier = cv2.findContours(img_dilation.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    for i, ctr in enumerate(contours):
        x, y, w, h = cv2.boundingRect(ctr)
        cv2.rectangle(image,(x,y),(x+w, y+h),(255,128,0),2)
    return image

#Line Segmentation
def LineSegmentation(img):
	 image = img
	 gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)

	 ret,thresh = cv2.threshold(gray,127,255,cv2.THRESH_BINARY_INV)

     #dilation
	 kernel = np.ones((5,100), np.uint8)
	 img_dilation = cv2.dilate(thresh, kernel, iterations=1)

     #find contours
	 ctrs, hier = cv2.findContours(img_dilation.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
     #sort contours
	 sorted_ctrs = sorted(ctrs, key=lambda ctr: cv2.boundingRect(ctr)[0])
	 for i, ctr in enumerate(sorted_ctrs):
		 x, y, w, h = cv2.boundingRect(ctr)
		 roi = image[y:y+h, x:x+w]
		 cv2.rectangle(image,(x,y),(x+w, y+h),(90,0,255),2)

	 return image

#CharSegmentation
def CharSegmentation(img):
    image = img.copy()
    image = cv2.fastNlMeansDenoisingColored(image,None,10,10,7,21)
    gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
    #threshold
    res,thresh = cv2.threshold(gray,150,255,cv2.THRESH_BINARY_INV)
    kernel = cv2.getStructuringElement(cv2.MORPH_CROSS,(1,3))

    #dilation
    dilated = cv2.dilate(thresh,kernel,iterations = 1)
    #find contours
    contours, hierarchy = cv2.findContours(dilated,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)

    for contour in contours:
        [x,y,w,h] = cv2.boundingRect(contour)
        cv2.rectangle(image,(x,y),(x+w, y+h),(76,0,153),1)

    return image

# Create your views here.
def add_image(request):
    W = Text.objects.all()
    W.delete()
    if request.method == 'POST':
        form = TextForm(request.POST,request.FILES)
        if form.is_valid():
            form.save()
            val=request.POST.get('All')
            print(val)
            image = Text.objects.last()
            imagefile = image.Img
            image = np.asarray(bytearray(imagefile.read()), dtype="uint8")

            image_encode1 = cv2.imdecode(image, cv2.IMREAD_COLOR)
            image_encode2 = cv2.imdecode(image, cv2.IMREAD_COLOR)
            image_encode3 = cv2.imdecode(image, cv2.IMREAD_COLOR)
            image_encode4 = cv2.imdecode(image, cv2.IMREAD_COLOR)

            img_para = ParagraphSegmentation(image_encode1)
            img_word =  WordSegmentation(image_encode2)
            img_line = LineSegmentation(image_encode3)
            img_char = CharSegmentation(image_encode4)

        cv2.imwrite("text_segmentation/static/text_segmentation/img_para.png",img_para)
        cv2.imwrite("text_segmentation/static/text_segmentation/img_word.png",img_word)
        cv2.imwrite("text_segmentation/static/text_segmentation/img_line.png",img_line)
        cv2.imwrite("text_segmentation/static/text_segmentation/img_char.png",img_char)

        return render(request, 'text_segmentation/img.html', {'form' : form,'success':'yes'})
    else:
        form = TextForm()
        return render(request, 'text_segmentation/img.html',{'form':form})

def disp_word(request):
    return render(request, 'text_segmentation/Disp_word.html')

def disp_para(request):
    return render(request, 'text_segmentation/Disp_para.html')

def disp_line(request):
    return render(request, 'text_segmentation/Disp_line.html')

def disp_char(request):
    return render(request, 'text_segmentation/Disp_char.html')

def disp_all(request):
    return render(request, 'text_segmentation/Disp_all.html')


from selenium import webdriver

driver = webdriver.Chrome("C:\\Browsers_Selenium\\Chrome\\ChromeDriver.exe")
driver.maximize_window()
#Save website URL in variable
URL = "http://seleniumhq.org"
#Navigate to the URL
driver.get(URL)

#screenshot for whole webpage
driver.get_screenshot_as_file('screenshot_demo1.jpg')


import numpy as np
import pandas as pd
import copy
import math
import time
import os
from tqdm import tqdm
import argparse
from matplotlib import pyplot as plt

from c import Common
from make_M import WPMatrix
from make_S import SMatrix
import cdf

'''
#DrDe class
##Calculate DrDe by SM, PWM; Do classifiction with r0, e0
    Calculation done at initi state, just follow the method rised by paper

##Varibales:
    df_drde: a [pairs_num * 5] pandas DataFrame, columns=['u','v','dr','de','st']
    c: common parameters
    classified: Whether classified

##Methods:
    classify(self, dr_t, de_t): Do classifiction with r0, e0. result store in df_drde['st']
    outputDrDe_to_file(filename): Output ['u','v','dr','de','st'] to the file.
    st_to_file(filename): Output ['u','v','st'] to the file.
'''

class DrDe():
    def __init__(self, wpm):
        if wpm.pairs_num <= 0:
            print("There is no edge in wpm")
            exit(-1)
        self.df_drde = pd.DataFrame(np.zeros(wpm.pairs_num * 5).reshape((wpm.pairs_num, 5)),\
                                columns=['u','v','dr','de','st'])
        self.classified = False
        self.st_result = [0, 0, 0, 0]

        '''Calculate Dr and De'''
        pbar = tqdm(total=len(wpm.WM.keys()), ncols=25)
        pbar.set_description("Calcu drde:")
        index = 0
        for uv in wpm.WM:
            sum, dr, de = 0.0, 0.0, 0.0
            for tl in wpm.WM[uv]:
                dr += wpm.get_w(uv, tl) * wpm.get_p(uv, tl)
                sum += wpm.get_w(uv, tl)
                if(wpm.get_w(uv, tl) != 0):
                    de = de+1
            dr = dr/sum
            de = math.log(de,2)
            self.df_drde.iloc[index] = [uv[0], uv[1], dr, de, 0]
            index += 1
            pbar.update(1)
        pbar.close()

    def classify(self, dr_t, de_t):
        def compare_it(r, e, r_t, e_t):
            '''S:1, F:2, FS:3, IR:4'''
            st = 0
            if r > r_t:
                st += 2
            if e > e_t:
                st += 1
            st += 1
            return st
        print("---------------------")
        print("Separating st now...")
        time_start=time.time()

        self.df_drde['st'] = self.df_drde.apply(lambda x: \
                            compare_it(x['dr'],x['de'],dr_t,de_t), axis=1)

        tmp_result = self.df_drde['st'].value_counts(sort=False)
        for i in range(1, 5):
            if i in tmp_result:
                self.st_result[i-1] = tmp_result[i]
        labels = ['S','F','FS','IR']
        for i in range(4):
            print("%s:%d"%(labels[i], self.st_result[i]))
        self.classified = True
        time_end=time.time();
        print ("Used %.2f s"%(time_end-time_start))

    def outputDrDe_to_file(self, filename):
        self.df_drde['u'] = self.df_drde['u'].apply(lambda x: '%d'%x)
        self.df_drde['v'] = self.df_drde['v'].apply(lambda x: '%d'%x)
        print("Print DrDe to: %s"%(filename))
        self.df_drde.to_csv(filename, index = False)

    def st_to_file(self, filename):
        self.df_drde['u'] = self.df_drde['u'].apply(lambda x: '%d'%x)
        self.df_drde['v'] = self.df_drde['v'].apply(lambda x: '%d'%x)
        print("Print DrDe to: %s"%(filename))
        self.df_drde[['u','v','st']].to_csv(filename, index = False)

    def drawCDF(self, axs):
        cdf.cdf(self.df_drde['dr'], axs[0], "Dr", 'r', 'o')
        cdf.cdf(self.df_drde['de'], axs[1], "De", 'r', 'o')

    def drawResult(self, name):
        if(self.classified == True):
            colors = [(6/255,102/255,177/255),(254/255,220/255,25/255),(0,173/255,79/255),(237/255,27/255,58/255)]

            patches, texts = plt.pie(self.st_result, wedgeprops=dict(width=0.4), colors=colors, startangle =90,)
            plt.title("Ratio of social ties")
            plt.axis('equal')

            labels = ["S: {:.2f}%".format(self.st_result[0] / sum(self.st_result) * 100),
                    "F: {:.2f}%".format(self.st_result[1] / sum(self.st_result) * 100),
                    "FS: {:.2f}%".format(self.st_result[2] / sum(self.st_result) * 100),
                    "IR: {:.2f}%".format(self.st_result[3] / sum(self.st_result) * 100)]

            sort_legend = True
            if sort_legend:
                patches, labels, dummy =  zip(*sorted(zip(patches, labels, self.st_result),
                                                      key=lambda x: x[2],
                                                      reverse=True))

            plt.legend(patches, labels, loc='center')
            plt.savefig("%s_result.png"%(name))

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--T", default = 10080, type = int, help = "Major cycle (minutes).")
    parser.add_argument("--delta_T", default = 180, type = int, help = "Time step (minutes).")
    parser.add_argument("--access_file", default = "", type = str, help = "Path of access files.")
    parser.add_argument("--meet_file", default = "", type = str, help = "Path of meet files.")
    args = parser.parse_args()

    c = Common(args.T, args.delta_T)
    c.generate_params_from_data(args.access_file)
    s = SMatrix(c)
    s.get_SM_from_file(args.access_file)
    wp = WPMatrix(c)
    wp.get_WPM_from_file(args.meet_file, s)
    del s

    drde = DrDe(wp)
    del wp
    drde.classify(0.083, 0.5)
    drde.drawResult('test')
    #drde.outputDrDe_to_file("drde_test.csv")

if __name__ == "__main__":
    main()


import praw
from urllib2 import urlopen
import json

key = "[redacted]" # Google Youtube API key
pewdielink = "https://www.googleapis.com/youtube/v3/channels?part=statistics&forUsername=pewdiepie&key="+key
tserieslink = "https://www.googleapis.com/youtube/v3/channels?part=statistics&forUsername=tseries&key="+key

def commentreply (comment) :

    pewdiedata = urlopen(pewdielink).read()
    tseriesdata = urlopen(tserieslink).read()

    pewdiesubs = int( json.loads(pewdiedata)["items"][0]["statistics"]["subscriberCount"] )
    tseriessubs = int( json.loads(tseriesdata)["items"][0]["statistics"]["subscriberCount"] )

    if (pewdiesubs > tseriessubs) :
        comment.reply("PewDiePie currently has **" + ("{:,d}".format( int(pewdiesubs) - int(tseriessubs) )) + "** more subscribers than T-Series! \n *** \n ^(I'm just a student's CS project, please don't hurt me! If there's an issue, please PM me. Have a nice day!)")
    elif (tseriessubs > pewdiesubs) :
        comment.reply("T-Series currently has " + ("{:,d}".format( tseriessubs - pewdiesubs )) + " more subscribers than PewDiePie!")

    comment.upvote()


import os
import math

import cv2
import numpy as np

from utils import *
from utils_camera import *

def depthimg_bilateral(depthImg, maxdiff=3.0):
    """ Smooth depth image using a bilateral filter ignoring large differences """
    depthImg_bilateral = cv2.bilateralFilter(
        np.float32(depthImg), 15, 20.0, 20.0)
    h, w = depthImg.shape
    finalDepth = np.zeros([h, w])
    for y in range(0, h):
        for x in range(0, w):
            cur = depthImg[y, x]
            smo = depthImg_bilateral[y, x]
            if abs(smo - cur) < maxdiff:
                finalDepth[y, x] = smo
            else:
                finalDepth[y, x] = cur
    return finalDepth

def read_ColorImage(strFilePath, imgResize=False, resizeSize=(240, 320)):
    """ Given a path to an image, read it into a numpy array. Resize as required. """
    # clrImg = misc.imread(strFilePath)
    # if imgResize: clrImg = misc.imresize(clrImg, resizeSize, interp='bicubic')
    clrImg = cv2.imread(strFilePath)  # any old color image loading
    if imgResize:
        clrImg = cv2.resize(
            clrImg,
            (resizeSize[1],
             resizeSize[0]),
            interpolation=cv2.INTER_AREA)
    return clrImg

def read_depth16bit_image(strFilePath, imgResize=False, resizeSize=(240, 320)):
    """ Read the a 16bit depth image data into a numpy array. """
    depthImg = cv2.imread(strFilePath, -1)  # regular 16-bit PNG loading
    if imgResize:
        depthImg = cv2.resize(
            depthImg,
            (resizeSize[1],
             resizeSize[0]),
            interpolation=cv2.INTER_NEAREST)
    return depthImg

def image_fusion(
        camera_params,
        depthData,
        clrImg=None,
        normals=None,
        threshold=False):
    """
        Given a depth image and its corresponding color image, return a colored point cloud as a vector of (x, y, z, r, g, b).
        Assume only depth and color, and if provided with normals, fuse those too.
        The output format is a PLY (required to view it in color in MeshLab).
    """
    # nanLocationsDepth = np.isnan(depthData)
    # numberOfVertices = depthData.size - np.count_nonzero(nanLocationsDepth)
    # depthData[nanLocationsDepth] = -1 # replace all NaN values with -1

    bHasColors = clrImg is not None
    bHasNormals = normals is not None
    if bHasNormals:
        nanLocationsNormals = np.isnan(normals)
        normals[nanLocationsNormals] = 0

    h, w = depthData.shape

    # generate point cloud via numpy array functions
    coords = np.indices((h, w))

    # geometry
    xcoords = (((coords[1] - camera_params.cx) /
                camera_params.fx) * depthData).flatten()
    ycoords = (((coords[0] - camera_params.cy) /
                camera_params.fy) * depthData).flatten()
    zcoords = depthData.flatten()

    # color
    chan_red = chan_blue = chan_green = None
    if bHasColors:
        # chan_red = clrImg[..., 0].flatten()
        # chan_blue = clrImg[..., 1].flatten()
        # chan_green = clrImg[..., 2].flatten()

        chan_red = clrImg[..., 2].flatten()
        chan_blue = clrImg[..., 1].flatten()
        chan_green = clrImg[..., 0].flatten()

    ptcloud = None

    # normals
    normalsX = normalsY = normalsZ = None
    if bHasNormals:
        normalsX = normals[..., 0].flatten()
        normalsY = normals[..., 1].flatten()
        normalsZ = normals[..., 2].flatten()

    if bHasColors and bHasNormals:
        ptcloud = np.dstack(
            (xcoords,
             ycoords,
             zcoords,
             normalsX,
             normalsY,
             normalsZ,
             chan_red,
             chan_blue,
             chan_green))[0]
    elif bHasColors and not bHasNormals:
        ptcloud = np.dstack(
            (xcoords,
             ycoords,
             zcoords,
             chan_red,
             chan_blue,
             chan_green))[0]
    elif not bHasColors and bHasNormals:
        ptcloud = np.dstack(
            (xcoords,
             ycoords,
             zcoords,
             normalsX,
             normalsY,
             normalsZ))[0]
    else:
        ptcloud = np.dstack((xcoords, ycoords, zcoords))[0]
    # depth filtering
    if threshold:
        filters = np.where(ptcloud[:, 2] >= 2800)
        ptcloud = np.delete(ptcloud[:], filters, 0)

    return ptcloud, ptcloud.size // 6

def output_pointcloud(nVertices, ptcloud, strOutputPath, bHasNormals=False):
    """
        Given a point cloud produced from image_fusion, output it to a PLY file.
        TODO: Consider having a separate flag to allow for outputing just the depth and not colors.
    """
    # open the file and write out the standard ply header
    outputFile = open(strOutputPath + ".ply", "w")
    outputFile.write("ply\n")
    outputFile.write("format ascii 1.0\n")
    outputFile.write("comment generated via python script Process3DImage\n")
    outputFile.write("element vertex %d\n" % (nVertices))
    outputFile.write("property float x\n")
    outputFile.write("property float y\n")
    outputFile.write("property float z\n")

    if bHasNormals:
        outputFile.write("property float nx\n")
        outputFile.write("property float ny\n")
        outputFile.write("property float nz\n")

    outputFile.write("property uchar red\n")
    outputFile.write("property uchar green\n")
    outputFile.write("property uchar blue\n")
    outputFile.write("element face 0\n")
    outputFile.write("property list uchar int vertex_indices\n")
    outputFile.write("end_header\n")

    # output the actual points
    for pt in ptcloud:
        dx, dy, dz = pt[0:3]

        dx *= 0.001
        dy *= 0.001
        dz *= 0.001

        if bHasNormals:
            nx, ny, nz, r, g, b = pt[3:]
            outputFile.write(
                "%10.6f %10.6f %10.6f %10.6f %10.6f %10.6f %d %d %d\n" %
                (-dx, dy, dz, nx, ny, nz, r, g, b))
        else:
            r, g, b = pt[3:]
            outputFile.write(
                "%10.6f %10.6f %10.6f %d %d %d\n" %
                (dx, dy, dz, r, g, b))

    outputFile.close()

def images_to_textured_mesh(
        img_color,
        img_depth,
        camera_params,
        tri_dist_thres=0.75):
    """ Given an rgb-d image pair, return a textured mesh using the spherical model. """
    ptcloud = []
    triangles = []
    texcoords = []

    img_h, img_w = img_depth.shape
    n_points_total = img_w * img_h
    n_points_processed = 0

    for h in range(0, img_h):
        for w in range(0, img_w):
            depth_val = img_depth[h, w]
            r, g, b = img_color[h, w]

            xcoord = ((w - camera_params.cx) / camera_params.fx) * depth_val
            ycoord = ((h - camera_params.cy) / camera_params.fy) * depth_val
            zcoord = depth_val

            ptcloud.append([xcoord, ycoord, zcoord, r, g, b])

            # texcoords.append([1.0 - w_ratio, 1.0 - h_ratio])
            texcoords.append([w / img_w, 1.0 - h / img_h])

            n_points_processed += 1
            print_text_progress_bar(
                n_points_processed / n_points_total,
                bar_name='Images to textured mesh   ')
    print()

    skip_val = 2
    n_triangles_processed = 0
    for h in range(0, img_h, 2):
        for w in range(0, img_w, 2):
            idx_00 = h * img_w + w  # top left
            idx_10 = h * img_w + w + skip_val  # top right
            idx_01 = (h + skip_val) * img_w + w  # bottom left
            idx_11 = (h + skip_val) * img_w + w + skip_val  # bottom right

            if (idx_00 < len(ptcloud)) and (idx_10 < len(ptcloud)) and (
                    idx_01 < len(ptcloud)) and (idx_11 < len(ptcloud)):
                pt_tl = np.array(ptcloud[idx_00][0:3])
                pt_tr = np.array(ptcloud[idx_10][0:3])
                pt_bl = np.array(ptcloud[idx_01][0:3])
                pt_br = np.array(ptcloud[idx_11][0:3])

                # compute pair-wise distances and exclude triangles who have
                # edges which are too long
                d_tltr = np.linalg.norm(pt_tl - pt_tr)
                d_trbr = np.linalg.norm(pt_tr - pt_br)
                d_brbl = np.linalg.norm(pt_br - pt_bl)
                d_bltl = np.linalg.norm(pt_bl - pt_tl)
                d_trbl = np.linalg.norm(pt_tr - pt_bl)

                if (
                    d_tltr < tri_dist_thres) and (
                    d_trbr < tri_dist_thres) and (
                    d_brbl < tri_dist_thres) and (
                    d_bltl < tri_dist_thres) and (
                        d_trbl < tri_dist_thres):
                    triangles.append(
                        [idx_00 + 1, idx_01 + 1, idx_10 + 1])  # triangle 1
                    triangles.append(
                        [idx_10 + 1, idx_01 + 1, idx_11 + 1])  # triangle 2

            n_triangles_processed += 2
            print_text_progress_bar(
                n_triangles_processed / (img_h * img_w * 2), bar_name='Triangulating....   ')

    return np.array(ptcloud), np.array(
        triangles), np.array(texcoords), n_points_total

def output_textured_mesh(
        ptcloud,
        texcoords,
        triangles,
        fname_image_texture,
        fname_obj,
        strOutputPath):
    texture_file = open(
        os.path.join(
            strOutputPath,
            fname_image_texture) +
        ".mtl",
        "w")
    texture_file.write("newmtl material0\n")
    texture_file.write("Ka 1.000000 1.000000 1.000000\n")
    texture_file.write("Kd 1.000000 1.000000 1.000000\n")
    texture_file.write("Ks 0.000000 0.000000 0.000000\n")
    texture_file.write("Tr 1.000000\n")
    texture_file.write("illum 1\n")
    texture_file.write("Ns 0.000000\n")
    texture_file.write("map_Kd " + fname_image_texture + ".png\n")
    texture_file.close()

    print("Writing point cloud to '" + str(strOutputPath + \
          fname_obj + ".obj") + "' ... ", end="", flush=True)
    outputFile = open(os.path.join(strOutputPath, fname_obj) + ".obj", "w")
    outputFile.write("mtllib ./" + fname_image_texture + ".mtl\n")

    # output the actual points
    for pt in ptcloud:
        dx, dy, dz = pt[0:3]
        outputFile.write("v %.6f %.6f %.6f\n" % (dx, dy, dz))
        outputFile.write("vn 0.0 0.0 0.0\n")

    for vt in texcoords:
        tex_u, tex_v = vt
        outputFile.write("vt %.6f %.6f\n" % (tex_u, tex_v))

    outputFile.write("usemtl material0\n")
    for t in triangles:
        idx_1, idx_2, idx_3 = t
        outputFile.write(
            "f %d/%d/%d %d/%d/%d %d/%d/%d\n" %
            (idx_1, idx_1, idx_1, idx_2, idx_2, idx_2, idx_3, idx_3, idx_3))

    outputFile.close()

    print("Finished!")

if __name__ == "__main__":
    # strInputPath = "/home/po/Documents/data/body_reconstruction_deep_learning/00_testdataset_01/snaps01/"
    # strOutputPath = strInputPath
    # process_multiview(strInputPath, strOutputPath, 3)

    for i in range(1, 4):
        strInputPath = "F:/data/deep-learning/additive_depth/98_vr_calib/test01_img_seq/cam0" + \
            str(i) + "/"
        strColorFolder = os.path.join(strInputPath, "color")
        strDepthFolder = os.path.join(strInputPath, "depth")

        strColorFilename = os.path.join(strColorFolder, "1519264284736.jpg")
        strDepthFilename = os.path.join(strDepthFolder, "1519264284736.png")

        img_color = cv2.imread(strColorFilename)
        img_depth = cv2.imread(strDepthFilename, -1)

        params = GetCameraParameters("OrbbecAstra", 0.5)

        # output textured mesh
        strOutputPath = "F:/data/deep-learning/additive_depth/98_vr_calib/test01_calib_frames/"
        if not os.path.exists(strOutputPath):
            os.makedirs(strOutputPath)
        texture_img_name = "cam0" + str(i) + "-image-texture"

        cv2.imwrite(
            os.path.join(
                strOutputPath,
                texture_img_name +
                '.png'),
            img_color)
        # plt.imsave(, cv2.flip( (imgC_clr/255), 1 ))
        # ptcloud, triangles, texcoords, n_points_total = images_to_textured_mesh(cv2.cvtColor(img_color, cv2.COLOR_BGR2RGB), pred_00)

        ptcloud, triangles, texcoords, n_points_total = images_to_textured_mesh(
            img_color, img_depth / 1000, params, tri_dist_thres=0.25)
        output_textured_mesh(
            ptcloud,
            texcoords,
            triangles,
            texture_img_name,
            "cam0" + str(i),
            strOutputPath)
        print()


import os
import cv2
import sys

sys.path.append('..')
import numpy as np
from math import cos, sin
# from moviepy.editor import *
from lib.FSANET_model import *
import numpy as np
from keras.layers import Average

# from moviepy.editor import *
# from mtcnn.mtcnn import MTCNN

def draw_axis(img, yaw, pitch, roll, tdx=None, tdy=None, size=50):
    print(yaw, roll, pitch)
    pitch = pitch * np.pi / 180
    yaw = -(yaw * np.pi / 180)
    roll = roll * np.pi / 180

    if tdx != None and tdy != None:
        tdx = tdx
        tdy = tdy
    else:
        height, width = img.shape[:2]
        tdx = width / 2
        tdy = height / 2

    # X-Axis pointing to right. drawn in red
    x1 = size * (cos(yaw) * cos(roll)) + tdx
    y1 = size * (cos(pitch) * sin(roll) + cos(roll) * sin(pitch) * sin(yaw)) + tdy

    # Y-Axis | drawn in green
    #        v
    x2 = size * (-cos(yaw) * sin(roll)) + tdx
    y2 = size * (cos(pitch) * cos(roll) - sin(pitch) * sin(yaw) * sin(roll)) + tdy

    # Z-Axis (out of the screen) drawn in blue
    x3 = size * (sin(yaw)) + tdx
    y3 = size * (-cos(yaw) * sin(pitch)) + tdy

    cv2.line(img, (int(tdx), int(tdy)), (int(x1), int(y1)), (0, 0, 255), 3)
    cv2.line(img, (int(tdx), int(tdy)), (int(x2), int(y2)), (0, 255, 0), 3)
    cv2.line(img, (int(tdx), int(tdy)), (int(x3), int(y3)), (255, 0, 0), 2)

    return img

def draw_results_ssd(detected, input_img, faces, ad, img_size, img_w, img_h, model, time_detection, time_network,
                     time_plot):
    # loop over the detections
    if detected.shape[2] > 0:
        for i in range(0, detected.shape[2]):
            # extract the confidence (i.e., probability) associated with the
            # prediction
            confidence = detected[0, 0, i, 2]

            # filter out weak detections
            if confidence > 0.5:
                # compute the (x, y)-coordinates of the bounding box for
                # the face and extract the face ROI
                (h0, w0) = input_img.shape[:2]
                box = detected[0, 0, i, 3:7] * np.array([w0, h0, w0, h0])
                (startX, startY, endX, endY) = box.astype("int")
                # print((startX, startY, endX, endY))
                x1 = startX
                y1 = startY
                w = endX - startX
                h = endY - startY

                x2 = x1 + w
                y2 = y1 + h

                xw1 = max(int(x1 - ad * w), 0)
                yw1 = max(int(y1 - ad * h), 0)
                xw2 = min(int(x2 + ad * w), img_w - 1)
                yw2 = min(int(y2 + ad * h), img_h - 1)

                faces[i, :, :, :] = cv2.resize(input_img[yw1:yw2 + 1, xw1:xw2 + 1, :], (img_size, img_size))
                faces[i, :, :, :] = cv2.normalize(faces[i, :, :, :], None, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX)

                face = np.expand_dims(faces[i, :, :, :], axis=0)
                p_result = model.predict(face)

                face = face.squeeze()

                # print(p_result[0][0], p_result[0][1], p_result[0][2])

                # img = draw_axis(input_img[yw1:yw2 + 1, xw1:xw2 + 1, :], p_result[0][0], p_result[0][1], p_result[0][2])

                # input_img[yw1:yw2 + 1, xw1:xw2 + 1, :] = img
                break

    # cv2.imshow("result", input_img)
    try:
        return input_img, [p_result[0][0], p_result[0][1], p_result[0][2]]  # ,time_network,time_plot
    except:
        return

class FSAnet:
    # def __init__(self, input_img, nums):
    #     self.input_img = input_img
    #     self.nums = nums

    try:
        os.mkdir('./img')
    except OSError:
        pass

    # face_cascade = cv2.CascadeClassifier('lbpcascade_frontalface_improved.xml')
    # detector = MTCNN()

    # load model and weights
    img_size = 64
    stage_num = [3, 3, 3]
    lambda_local = 1
    lambda_d = 1
    img_idx = 0
    detected = ''  # make this not local variable
    time_detection = 0
    time_network = 0
    time_plot = 0
    skip_frame = 1  # every 5 frame do 1 detection and network forward propagation
    ad = 0.6

    # Parameters
    num_capsule = 3
    dim_capsule = 16
    routings = 2
    stage_num = [3, 3, 3]
    lambda_d = 1
    num_classes = 3
    image_size = 64
    num_primcaps = 7 * 3
    m_dim = 5
    S_set = [num_capsule, dim_capsule, routings, num_primcaps, m_dim]

    model1 = FSA_net_Capsule(image_size, num_classes, stage_num, lambda_d, S_set)()
    model2 = FSA_net_Var_Capsule(image_size, num_classes, stage_num, lambda_d, S_set)()

    num_primcaps = 8 * 8 * 3
    S_set = [num_capsule, dim_capsule, routings, num_primcaps, m_dim]

    model3 = FSA_net_noS_Capsule(image_size, num_classes, stage_num, lambda_d, S_set)()

    print('Loading models ...')

    weight_file1 = '../pre-trained/300W_LP_models/fsanet_capsule_3_16_2_21_5/fsanet_capsule_3_16_2_21_5.h5'
    model1.load_weights(weight_file1)
    print('Finished loading model 1.')

    weight_file2 = '../pre-trained/300W_LP_models/fsanet_var_capsule_3_16_2_21_5/fsanet_var_capsule_3_16_2_21_5.h5'
    model2.load_weights(weight_file2)
    print('Finished loading model 2.')

    weight_file3 = '../pre-trained/300W_LP_models/fsanet_noS_capsule_3_16_2_192_5/fsanet_noS_capsule_3_16_2_192_5.h5'
    model3.load_weights(weight_file3)
    print('Finished loading model 3.')

    inputs = Input(shape=(64, 64, 3))
    x1 = model1(inputs)  # 1x1
    x2 = model2(inputs)  # var
    x3 = model3(inputs)  # w/o
    avg_model = Average()([x1, x2, x3])
    model = Model(inputs=inputs, outputs=avg_model)

    # load our serialized face detector from disk
    print("[INFO] loading face detector...")
    protoPath = os.path.sep.join(["face_detector", "deploy.prototxt"])
    modelPath = os.path.sep.join(["face_detector",
                                  "res10_300x300_ssd_iter_140000.caffemodel"])
    net = cv2.dnn.readNetFromCaffe(protoPath, modelPath)

    print('Start detecting pose ...')
    detected_pre = np.empty((1, 1, 1))

    def calculate(self, input_img, number=0):

        skip_frame = self.skip_frame
        net = self.net
        detected_pre = self.detected_pre

        img_idx = number
        img_h, img_w, _ = np.shape(input_img)

        if img_idx == 1 or img_idx % skip_frame == 0:
            time_detection = 0
            time_network = 0
            time_plot = 0

            # detect faces using LBP detector
            gray_img = cv2.cvtColor(input_img, cv2.COLOR_BGR2GRAY)
            # detected = face_cascade.detectMultiScale(gray_img, 1.1)
            # detected = detector.detect_faces(input_img)
            # pass the blob through the network and obtain the detections and
            # predictions
            blob = cv2.dnn.blobFromImage(cv2.resize(input_img, (300, 300)), 1.0,
                                         (300, 300), (104.0, 177.0, 123.0))
            net.setInput(blob)
            detected = net.forward()

            if detected_pre.shape[2] > 0 and detected.shape[2] == 0:
                detected = detected_pre

            faces = np.empty((detected.shape[2], self.img_size, self.img_size, 3))
            try:

                input_img, eular_angles = draw_results_ssd(detected, input_img, faces, self.ad, self.img_size, img_w, img_h, self.model,
                                             time_detection,
                                             time_network, time_plot)
            except:
                return

            # cv2.imwrite('img/' + str(img_idx) + '.png', input_img)

        else:
            input_img, eular_angles = draw_results_ssd(self.detected, input_img, self.faces, self.ad, self.img_size, img_w, img_h,
                                         self.model, self.time_detection,
                                         self.time_network, self.time_plot)

        if detected.shape[2] > detected_pre.shape[2] or img_idx % (skip_frame * 3) == 0:
            detected_pre = detected

        key = cv2.waitKey(1)
        return eular_angles

# -------------------------------- Mitchell: for single image head pose estimation -----------------------------
if __name__ == '__main__':
    dataset = sys.argv[1]
    method = sys.argv[2]

    flag = 0
    if dataset == "forensics":
        flag = 1

    # input_img = cv2.imread('/home/xiangmingcan/notespace/cvpr_data/celeba/11663.jpg')
    src = "/home/xiangmingcan/notespace/cvpr_data/" + dataset
    tgt = "/home/xiangmingcan/notespace/cvpr_result/" + dataset + '/' + method

    save_log = os.path.join("headPose/", dataset, method + ".txt")

    path = os.path.join("headPose/", dataset)
    if not os.path.exists(path):
        os.makedirs(path)

    logFile = open(save_log, 'w')

    img_list = os.listdir(tgt)
    sorted(img_list)

    fsanet = FSAnet()

    for input_img in img_list:
        if '_mask' in input_img:
            continue

        try:
            refer_img = input_img.split('-')[1]
            if flag:
                refer_img = refer_img[:-3] + "png"

        except:
            print("img1_name = img2_name.split('-')[1]")
            print("IndexError: list index out of range")
            continue

        refer_img_folder = refer_img.split('_')[0]
        refer_img = refer_img.split(refer_img_folder)[1][1:]

        result_cv2 = cv2.imread(os.path.join(tgt, input_img))
        refer_cv2 = cv2.imread(os.path.join(src, refer_img_folder, refer_img))

        # 如果读出来的img不存在，则删去
        if refer_cv2 is None or refer_cv2 is None:
            continue

        # result image 的欧拉角
        eular_angles_result = fsanet.calculate(result_cv2)
        print(eular_angles_result)

        # reference image 的欧拉角
        eular_angles_refer = fsanet.calculate(refer_cv2)
        print(eular_angles_refer)

        if eular_angles_result is None or eular_angles_refer is None:
            continue

        vec1 = np.array(eular_angles_result)
        vec2 = np.array(eular_angles_refer)

        distance = np.linalg.norm(vec1 - vec2)
        print(distance)
        print('\n')

        logFile.write(str(distance))
        logFile.write('\n')

    logFile.close()


import matplotlib.pyplot as plt
import numpy as np
from experiment_utils.plot_utils import load_exps_data, defaultdict, group_by, correct_limit, filter

plt.style.use('ggplot')
import matplotlib
matplotlib.use('TkAgg')

SMALL_SIZE = 20
MEDIUM_SIZE = 24
BIGGER_SIZE = 28
BIG_SIZE = 30
LINEWIDTH = 3
YELLOW = '#FBC15E'
BLUE = '#348ABD'

plt.rc('font', size=MEDIUM_SIZE)          # controls default text sizes
plt.rc('axes', titlesize=BIGGER_SIZE)     # fontsize of the axes title
plt.rc('axes', labelsize=BIGGER_SIZE)    # fontsize of the x and y labels
plt.rc('xtick', labelsize=SMALL_SIZE)    # fontsize of the tick labels
plt.rc('ytick', labelsize=SMALL_SIZE)    # fontsize of the tick labels
plt.rc('legend', fontsize=MEDIUM_SIZE)    # legend fontsize
plt.rc('figure', titlesize=BIG_SIZE)  # fontsize of the figure title

prop_cycle = plt.rcParams['axes.prop_cycle']
colors = [
    (255, 128, 14),  # BLUE
    (0, 107, 164),  # ORANGE
    # (171, 171, 171),  # GREY
    # (89, 89, 89),  # LIGHT GREY
    (137, 137, 137),  # VERY DARK GREY
    (95, 158, 209),  # LIGHT BLUE
    # (163, 200, 236), # VERY LIGHT BLUE
    # (255, 188, 121),  # LIGHT ORANGE
    (200, 82, 0),  # RED
    (207, 207, 207),  # LIGHT GREY
]
for idx, color in enumerate(colors):
    colors[idx] = '#%02x%02x%02x' % color
COLORS = dict()
LEGEND_ORDER = {'regularization': 0, 'no-regularization': 1}

data_path = './data/corl_data/regularization_comparison/'

exps_data = load_exps_data([data_path])

sampling_time = {'meta_mb.envs.mb_envs.walker2d.Walker2dEnv': 0.008,
                 'Walker2d': 0.008,
                 'meta_mb.envs.mb_envs.half_cheetah.HalfCheetahEnv': 0.05,
                 'HalfCheetah': 0.05,
                 'meta_mb.envs.mb_envs.ant.AntEnv': 0.05,
                 'Ant': 0.05,
                 'meta_mb.envs.mb_envs.hopper.HopperEnv': 0.008,
                 'meta_mb.envs.mujoco.hopper_env.HopperEnv': 0.008,
                 'Hopper': 0.008,
                 }
round_plot = {'a-me-ppo': {'Hopper': 5000,
                           'Walker2d': 5000,
                           'Ant': 5000,
                           'HalfCheetah': 5000,
                      },
            'me-ppo': {'meta_mb.envs.mb_envs.hopper.HopperEnv': 5000,
                        'meta_mb.envs.mb_envs.walker2d.Walker2dEnv': 5000,
                        'meta_mb.envs.mb_envs.ant.AntEnv': 5000,
                        'meta_mb.envs.mb_envs.half_cheetah.HalfCheetahEnv': 5000,
                      },
            'me-trpo': {'meta_mb.envs.mb_envs.hopper.HopperEnv': 5000,
                        'meta_mb.envs.mb_envs.walker2d.Walker2dEnv': 5000,
                        'meta_mb.envs.mb_envs.ant.AntEnv': 5000,
                        'meta_mb.envs.mb_envs.half_cheetah.HalfCheetahEnv': 5000,
                      },
            'mbmpo': {'meta_mb.envs.mb_envs.hopper.HopperEnv': 5000,
                        'meta_mb.envs.mb_envs.walker2d.Walker2dEnv': 5000,
                        'meta_mb.envs.mb_envs.ant.AntEnv': 5000,
                        'meta_mb.envs.mb_envs.half_cheetah.HalfCheetahEnv': 5000,
                      }

         }

x_limits = {'meta_mb.envs.mb_envs.walker2d.Walker2dEnv': [0, 10e4],
            'Walker2d': [0, 10e4],
            'meta_mb.envs.mb_envs.half_cheetah.HalfCheetahEnv': [0, 10e4],
            'HalfCheetah': [0, 10e4],
            'meta_mb.envs.mb_envs.ant.AntEnv': [0, 10e4],
            'Ant': [0, 10e4],
            'meta_mb.envs.mb_envs.hopper.HopperEnv': [0, 10e4],
            'meta_mb.envs.mujoco.hopper_env.HopperEnv': [0, 10e4],
            'Hopper': [0, 10e4],
            }

def prepare_data_for_plot(exp_data,
                          y_key=None,
                          sup_y_key=None,
                          round_x=None,
                          add_sampling_time=False):
    x_y_tuples = []
    x_key = 'n_timesteps'
    asynch = exp_data[0]['flat_params'].get('async', False)
    for exp in exp_data:
        if not asynch:
            if sup_y_key is not None:
                assert type(sup_y_key) is list
                for key in sup_y_key:
                    if key in exp['progress'].keys():
                        x_y_tuples.extend(list(zip(exp['progress'][x_key], exp['progress'][key])))
                        break
            else:
                x_y_tuples.extend(list(zip(exp['progress'][x_key], exp['progress'][y_key])))
        else:
            if sup_y_key is not None:
                assert type(sup_y_key) is list
                for key in sup_y_key:
                    if key in exp['progress'].keys():
                        env_time = sampling_time[exp['flat_params']['env']]
                        x_y_tuples.extend(list(zip(exp['progress']['Data-TimeSoFar']/env_time, exp['progress'][key])))
                        break
            else:
                raise NotImplementedError
    x_y_dict = defaultdict(list)
    if asynch:
        env = exp_data[0]['flat_params']['env']
    else:
        env = exp_data[0]['flat_params']['env.$class']

    algo = exp_data[0]['flat_params']['algo']
    _round_x = round_plot.get(algo, dict()).get(env, None)
    round_x = _round_x if _round_x is not None else round_x
    for k, v in x_y_tuples:
        if round_x is not None:
            x_y_dict[(k//round_x) * round_x].append(v)
        else:
            x_y_dict[k].append(v)
    means, stddevs = [], []
    for key in sorted(x_y_dict.keys()):
        means.append(np.mean(x_y_dict[key]))
        stddevs.append(np.std(x_y_dict[key]))
    return np.array(sorted(x_y_dict.keys())), np.array(means), np.array(stddevs), x_limits[env]

def sorting_legend(label):
    return LEGEND_ORDER[label]

def get_color(label):
    if label not in COLORS.keys():
        if YELLOW in colors:
            colors.remove(YELLOW)
            COLORS[label] = YELLOW
        elif BLUE in colors:
            COLORS[label] = BLUE
            colors.remove(BLUE)
        else:
            COLORS[label] = colors.pop(0)
    return COLORS[label]

def plot_from_exps(exp_data,
                   filters={},
                   split_figures_by=None,
                   split_plots_by=None,
                   x_key='n_timesteps',
                   y_key=None,
                   sup_y_key=None,
                   plot_name='./bad-models.png',
                   subfigure_titles=None,
                   plot_labels=['interleaved policy learning', 'in-order policy learning'],
                   x_label=None,
                   y_label=None,
                   num_rows=1,
                   y_limits=None,
                   report_max_performance=False,
                   log_scale=False,
                   round_x=None,
                   ):

    exp_data = filter(exp_data, filters=filters)
    exps_per_plot = group_by(exp_data, group_by_key=split_figures_by)
    num_columns = len(exps_per_plot.keys())
    assert num_columns % num_rows == 0
    num_columns = num_columns // num_rows
    fig, axarr = plt.subplots(num_rows, num_columns, figsize=(11, 16))
    axarr = np.reshape(axarr, (num_rows, num_columns))
    fig.tight_layout(pad=5.0, w_pad=0, h_pad=3, rect=[0, 0, 1, 1])

    # iterate over subfigures
    for i, (default_plot_title, plot_exps) in enumerate(sorted(exps_per_plot.items())):
        plots_in_figure_exps = group_by(plot_exps, split_plots_by)
        subfigure_title = subfigure_titles[i] if subfigure_titles else default_plot_title
        r, c = i//num_columns, i%num_columns
        axarr[r, c].set_title(subfigure_title)
        axarr[r, c].xaxis.set_major_locator(plt.MaxNLocator(5))
        axarr[r, c].ticklabel_format(style='sci', axis='x', scilimits=(0, 0))

        # iterate over plots in figure
        y_max_mean = -1e10
        y_axis_min = 1e10
        y_axis_max = -1e10
        for j, default_label in enumerate(sorted(plots_in_figure_exps, key=sorting_legend)):
            exps = plots_in_figure_exps[default_label]
            x, y_mean, y_std, x_limits = prepare_data_for_plot(exps,
                                                     y_key=y_key,
                                                     sup_y_key=sup_y_key,
                                                     round_x=round_x)

            label = plot_labels[j] if plot_labels else default_label
            _label = label if i == 0 else "__nolabel__"
            if log_scale:
                axarr[r, c].semilogx(x, y_mean, label=_label, linewidth=LINEWIDTH, color=get_color(label))
            else:
                axarr[r, c].plot(x, y_mean, label=_label, linewidth=LINEWIDTH, color=get_color(label))

            axarr[r, c].fill_between(x, y_mean + y_std, y_mean - y_std, alpha=0.2, color=get_color(label))

            # axis labels
            axarr[r, c].set_xlabel(x_label if x_label else x_key)
            axarr[r, c].set_ylabel(y_label if y_label else y_key)
            if x_limits is not None:
                axarr[r, c].set_xlim(*x_limits)
            if y_limits is not None:
                axarr[r, c].set_ylim(*y_limits)
            else:
                _y_axis_min, _y_axis_max = correct_limit(axarr[r, c], x, y_mean-y_std, y_mean+y_std)
                y_axis_max = max(_y_axis_max, y_axis_max)
                y_axis_min = min(_y_axis_min, y_axis_min)
                if max(y_mean) > y_max_mean:
                    y_max_mean = max(y_mean)

        if report_max_performance:
            label = 'max' if i == 0 else "__nolabel__"
            axarr[r, c].plot(axarr[r, c].get_xlim(), [y_max_mean]*2, 'k--', label=label)
        if y_limits is None:
            axarr[r, c].set_ylim([y_axis_min, y_axis_max])

    fig.legend(loc='lower center', ncol=1, bbox_transform=plt.gcf().transFigure)
    fig.savefig(plot_name)

# filter_dict = {'fast_lr': 0.001, 'path_length':200}
filter_dict = {}

exps_data_filtered = filter(exps_data, filter_dict)

plot_from_exps(exps_data,
               split_figures_by='env.$class',
               split_plots_by='exp_tag',
               y_key='train-AverageReturn',
               x_key='Time',
               filters=filter_dict,
               sup_y_key=['EnvTrajs-AverageReturn',
                          'Data-EnvTrajs-AverageReturn',
                          'train-AverageReturn'],
               # subfigure_titles=['HalfCheetah - output_bias_range [0.0, 0.1]',
               #                  'HalfCheetah - output_bias_range [0.0, 0.5]',
               #                  'HalfCheetah - output_bias_range [0.0, 1.0]'],
               # plot_labels=['ME-MPG', 'ME-TRPO'],
               x_label='Time-steps',
               y_label='Average Return',
               plot_name='./comparison_regularization.png',
               num_rows=2,
               report_max_performance=False,
               log_scale=False,
               round_x=5000,
               )