from integrations.crudhub import maybe_json_or_raise
from connectors.core.connector import get_logger, ConnectorError
from django.conf import settings
from integrations.crudhub import make_request
import requests
import socket
import validators
import os

logger = get_logger('apivoid')

TMP_LOC = os.path.dirname(os.path.realpath(__file__)) + "/apivoid"
ENDPOINT = '/{}/v1/pay-as-you-go/'
MACRO_LIST = ["IP_Enrichment_Playbooks_IRIs", "URL_Enrichment_Playbooks_IRIs", "Domain_Enrichment_Playbooks_IRIs",
              "Email_Enrichment_Playbooks_IRIs"]
CONNECTOR_NAME = "apivoid"
endpoints_map = {
    "threatlog": "host",
    "domainbl": "host",
    "iprep": "ip",
    "screenshot": "url",
    "urlrep": "url",
    "domainage": "host",
    "sitetrust": "host",
    "parkeddomain": "host",
    "urlstatus": "url",
    "emailverify": "email",
    "dnspropagation": "host",
    "urltohtml": "url",
    "sslinfo": "host"
}

def _is_valid_domain(domain):
    """Returns True if input string is a valid domain or fqdn (domain.com)."""
    return validators.domain(domain)

def _is_valid_url(url):
    """Returns True if input string is a valid url (http://domain.com)."""
    return validators.url(url)

def _is_valid_email(email):
    """Returns True if input string is a valid email (someone@domain.com)."""
    return validators.email(email)

def _is_valid_ip(ip):
    """Returns True if input string is ipv4/ipv6."""
    if not ip or "\x00" in ip:
        return False
    try:
        res = socket.getaddrinfo(
            ip, 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_NUMERICHOST
        )
        return bool(res)
    except socket.gaierror as e:
        if e.args[0] == socket.EAI_NONAME:
            return False
        raise ConnectorError(e)

def _get_input(params, key, type=str):
    ret_val = params.get(key, None)
    if ret_val:
        if isinstance(ret_val, bytes):
            ret_val = ret_val.decode('utf-8')
        if isinstance(ret_val, type):
            return ret_val
        else:
            logger.info(
                "Parameter Input Type is Invalid: Parameter is: {0}, Required Parameter Type"
                " is: {1}".format(str(key), str(type)))
            raise ConnectorError("Parameter Input Type is Invalid: Parameter is: {0}, Required "
                                 "Parameter Type is: {1}".format(str(key), str(type)))
    else:
        if ret_val == {} or ret_val == [] or ret_val == 0:
            return ret_val
        return None

def _get_config(config):
    verify_ssl = config.get("verify_ssl", None)
    server_url = _get_input(config, "server")
    api_key = _get_input(config, "api_key")
    # logger.debug('{}\n{}\n{}\n{}\n'.format(server_url, api_key, verify_ssl,config))
    if server_url[:7] != 'http://' and server_url[:8] != 'https://':
        server_url = 'https://{}'.format(server_url)
    return server_url, api_key, verify_ssl

def _api_request(endpoint, config, req_params=None, method='get'):
    ''' returns json or str '''
    try:
        server_url, api_key, verify_ssl = _get_config(config)
        url = server_url + endpoint
        if req_params is None:
            req_params = {}
        req_params.update({'key': api_key})
        api_response = requests.request(method=method, url=url, params=req_params, verify=verify_ssl)
        logger.debug("api_response: response_code :{0}  response_message:{1}".format(api_response.status_code,
                                                                                api_response.text))
        response = maybe_json_or_raise(api_response)
        if 'error' not in response:
            return response
        else:
            logger.error('Fail To request API \n{0}\n response is : \n{1}\n'.
                         format(str(url), response))
            raise ConnectorError('Fail To request API \n{0}\n response is : \n{1}\n'.
                                 format(str(url), response))
    except Exception as Err:
        raise ConnectorError(Err)

def upload_file_to_cyops(file_name, file_content, file_description):
    try:
        # Conditional import based on the FortiSOAR version.
        try:
            from integrations.crudhub import make_file_upload_request
            response = make_file_upload_request(file_name, file_content, 'application/octet-stream')

        except:
            from cshmac.requests import HmacAuth
            from integrations.crudhub import maybe_json_or_raise
            from requests import post

            url = settings.CRUD_HUB_URL + '/api/3/files'
            auth = HmacAuth(url, 'POST', settings.APPLIANCE_PUBLIC_KEY,
                            settings.APPLIANCE_PRIVATE_KEY,
                            settings.APPLIANCE_PUBLIC_KEY.encode('utf-8'))
            files = {'file': (file_name, file_content, {'Expire': 0})}
            response = post(url, auth=auth, files=files, verify=False)
            response = maybe_json_or_raise(response)

        logger.info('File upload complete {0}'.format(str(response)))
        file_id = response['@id']
        attach_response = make_request('/api/3/attachments', 'POST',
                                       {'name': file_name, 'file': file_id, 'description': file_description})
        logger.info('attach file completed: {0}'.format(attach_response))
        return attach_response
    except Exception as err:
        logger.exception('An exception occurred {0}'.format(str(err)))
        raise ConnectorError('An exception occurred {0}'.format(str(err)))

def handle_upload_file_to_cyops(file_details, file_path):
    try:
        file_name = file_details.get("file_name")
        file_description = file_details.get("file_description")
        file_content = open(file_path, "rb")
        attach_response = upload_file_to_cyops(file_name, file_content, file_description)
        logger.debug('{0}'.format(str(type(attach_response))))
        os.remove(file_path)
        return attach_response
    except Exception as err:
        os.remove(file_path)
        logger.exception('An exception occurred {0}'.format(str(err)))
        raise ConnectorError('An exception occurred {0}'.format(str(err)))

def _save_file(filename, response):
    tmp_path = TMP_LOC
    import base64
    imgdata = base64.b64decode(response)
    if not os.path.isdir(tmp_path):
        os.mkdir(tmp_path)
    with open("{0}/{1}".format(tmp_path, filename), "wb") as file_to_write:
        file_to_write.write(imgdata)
    return "{0}/{1}".format(tmp_path, filename)

def _get_threat_intel(config, params):
    try:
        url_params = {}
        req_type = _get_input(params, "operation")
        req_value = _get_input(params, "req_value")
        if not validation_function_map[req_type](req_value):
            raise ConnectorError("Invalid {0} input paramter: {1}".format(req_type, req_value))
        if 'dnspropagation' in req_type:
            url_params.update({'dns_type': _get_input(params, "dns_record_type")})
        url_params.update({endpoints_map[req_type]: req_value})
        return {"result": _api_request(ENDPOINT.format(req_type), config, url_params),
                "status": "Success"}
    except Exception as Err:
        logger.error(str(Err))
        raise ConnectorError(str(Err))

def get_screenshot(config, params):
    try:
        req_value = _get_input(params, "req_value")
        resp = _get_threat_intel(config, params)
        # add file in attachment module
        file_name = req_value.split("/")[2] + ".png"
        file_details = {
            "file_name": file_name,
            "file_description": "apivoid- Screenshot captured for URL {0}".format(req_value)
        }
        temp_path = _save_file(file_name, resp['result']['data']['base64_file'])
        attachment_resp = handle_upload_file_to_cyops(file_details, temp_path)
        return attachment_resp
    except Exception as Err:
        logger.error(str(Err))
        raise ConnectorError(str(Err))

def _check_health(config):
    try:
        result = _api_request(ENDPOINT.format("iprep") + '?stats', config, req_params={"ip": "1.1.1.1"})
        if result:
            return True
        else:
            return False
    except Exception as err:
        if "Max retries exceeded with url" in str(err):
            raise ConnectorError("Invalid Server URL")
        elif "Fail To request API" in str(err):
            raise ConnectorError("Invalid API Key")
        else:
            raise ConnectorError(str(err))

operations = {
    "threatlog": _get_threat_intel,
    "domainbl": _get_threat_intel,
    "iprep": _get_threat_intel,
    "screenshot": get_screenshot,
    "urlrep": _get_threat_intel,
    "domainage": _get_threat_intel,
    "sitetrust": _get_threat_intel,
    "parkeddomain": _get_threat_intel,
    "urlstatus": _get_threat_intel,
    "emailverify": _get_threat_intel,
    "dnspropagation": _get_threat_intel,
    "urltohtml": _get_threat_intel,
    "sslinfo": _get_threat_intel
}

validation_function_map = {
    "threatlog": _is_valid_domain,
    "domainbl": _is_valid_domain,
    "iprep": _is_valid_ip,
    "screenshot": _is_valid_url,
    "urlrep": _is_valid_url,
    "domainage": _is_valid_domain,
    "sitetrust": _is_valid_domain,
    "parkeddomain": _is_valid_domain,
    "urlstatus": _is_valid_url,
    "emailverify": _is_valid_email,
    "dnspropagation": _is_valid_domain,
    "urltohtml": _is_valid_url,
    "sslinfo": _is_valid_domain
}


import requests, concurrent.futures

import requests, json

def get_github_repo(repo_name, github_username):
    request = f'https://api.github.com/repos/{github_username}/{repo_name}'
    return json.dumps(requests.get(request).json(), indent=4)

if __name__=="__main__":
    with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
        response_one = executor.submit(get_github_repo, "LearnPython", "LetusDevops").result()
        response_two = executor.submit(get_github_repo, "PythonTraining", "Hamdi-Limam").result()
    # Fake database file
    with open("result.txt", "a") as file:
        file.write(response_one)
        file.write(response_two)


bl_info = {
    "name": "VI-Suite",
    "author": "Ryan Southall",
    "version": (0, 1, 0),
    "blender": (2, 7, 0),
    "api":"",
    "location": "Node Editor & 3D View > Properties Panel",
    "description": "Radiance/EnergyPlus exporter and results visualiser",
    "warning": "This is a beta script. Some functionality is buggy",
    "wiki_url": "",
    "tracker_url": "",
    "category": "Import-Export"}

if "bpy" in locals():
    import imp
    imp.reload(vi_node)
    imp.reload(vi_operators)
    imp.reload(vi_ui)
    imp.reload(vi_func)
    imp.reload(envi_mat)
else:
    from .vi_node import vinode_categories, envinode_categories
    from .envi_mat import envi_materials, envi_constructions
    from .vi_func import iprop, bprop, eprop, fprop, sprop, fvprop, sunpath1
    from .vi_operators import *
    from .vi_ui import *

import sys, os, platform, inspect, bpy, nodeitems_utils

epversion = "8-1-0"
addonpath = os.path.dirname(inspect.getfile(inspect.currentframe()))

if str(sys.platform) == 'darwin':
    if not hasattr(os.environ, 'RAYPATH'):
        if platform.architecture() == "64bit":
            os.environ["PATH"] = os.environ["PATH"] + ":/usr/local/radiance/bin:{}/osx/64:/Applications/EnergyPlus-{}/bin".format(addonpath, epversion)
        else:
             os.environ["PATH"] = os.environ["PATH"] + ":/usr/local/radiance/bin:{}/osx:/Applications/EnergyPlus-{}/bin".format(addonpath, epversion)
        os.environ["RAYPATH"] = "/usr/local/radiance/lib:{}/lib".format(addonpath)

if str(sys.platform) == 'linux':
    if not hasattr(os.environ, 'RAYPATH'):
        raddir =  '/usr/share/radiance' if os.path.isdir('/usr/share/radiance') else '/usr/local/radiance'
        os.environ["PATH"] = os.environ["PATH"] + ":{}/bin:{}/linux:/usr/local/EnergyPlus-{}/bin".format(raddir, addonpath, epversion)
        os.environ["RAYPATH"] = "{}/lib:{}/lib".format(raddir, addonpath)

elif str(sys.platform) == 'win32':
    if not hasattr(os.environ, 'RAYPATH'):
        if os.path.isdir(r"C:\Program Files (x86)\Radiance"):
            os.environ["PATH"] = os.environ["PATH"] + r";C:\Program Files (x86)\Radiance\bin;{}\windows;C:\EnergyPlusV{}".format(addonpath,epversion)
            os.environ["RAYPATH"] = r"C:\Program Files (x86)\Radiance\lib;{}\lib".format(addonpath)
        elif os.path.isdir(r"C:\Program Files\Radiance"):
            os.environ["PATH"] = os.environ["PATH"] + r";C:\Program Files\Radiance\bin;{}\windows;C:\EnergyPlusV{}".format(addonpath, epversion)
            os.environ["RAYPATH"] = "C:\Program Files\Radiance\lib;{}\lib".format(addonpath)
        else:
            print("Cannot find a valid Radiance directory. Please check that you have Radiance installed in either C:\Program Files(x86) (64bit windows) \
or C:\Program Files (32bit windows)")

matpath = addonpath+'/EPFiles/Materials/Materials.data'
epwpath = addonpath+'/EPFiles/Weather/'
envi_mats = envi_materials()
envi_cons = envi_constructions()

def matfunc(i):
    if i == 0:
        return [((brick, brick, 'Contruction type')) for brick in list(envi_mats.brick_dat.keys())]
    elif i == 1:
        return [((stone, stone, 'Contruction type')) for stone in list(envi_mats.stone_dat.keys())]
    elif i == 2:
        return [((metal, metal, 'Contruction type')) for metal in list(envi_mats.metal_dat.keys())]
    elif i == 3:
        return [((wood, wood, 'Contruction type')) for wood in list(envi_mats.wood_dat.keys())]
    elif i == 4:
        return [((gas, gas, 'Contruction type')) for gas in list(envi_mats.gas_dat.keys())]
    elif i == 5:
        return [((glass, glass, 'Contruction type')) for glass in list(envi_mats.glass_dat.keys())]
    elif i == 6:
        return [((concrete, concrete, 'Contruction type')) for concrete in list(envi_mats.concrete_dat.keys())]
    elif i == 7:
        return [((insulation, insulation, 'Contruction type')) for insulation in list(envi_mats.insulation_dat.keys())]
    elif i == 8:
        return [((wgas, wgas, 'Contruction type')) for wgas in list(envi_mats.wgas_dat.keys())]
    elif i == 9:
        return [((cladding, cladding, 'Contruction type')) for cladding in list(envi_mats.cladding_dat.keys())]
def confunc(i):
    if i == 0:
        return [((wallcon, wallcon, 'Contruction type')) for wallcon in list(envi_cons.wall_con.keys())]
    elif i == 1:
        return [((floorcon, floorcon, 'Contruction type')) for floorcon in list(envi_cons.floor_con.keys())]
    elif i == 2:
        return [((roofcon, roofcon, 'Contruction type')) for roofcon in list(envi_cons.roof_con.keys())]
    elif i == 3:
        return [((doorcon, doorcon, 'Contruction type')) for doorcon in list(envi_cons.door_con.keys())]
    elif i == 4:
        return [((windowcon, windowcon, 'Contruction type')) for windowcon in list(envi_cons.glaze_con.keys())]

(bricklist, stonelist, metallist, woodlist, gaslist, glasslist, concretelist, insullist, wgaslist, claddinglist) = [matfunc(i) for i in range(10)]
(wallconlist, floorconlist, roofconlist, doorconlist, glazeconlist) = [confunc(i) for i in range(5)]

def eupdate(self, context):
    inv = 0
    for frame in range(context.scene.frame_start, context.scene.frame_end + 1):
        for o in [obj for obj in bpy.data.objects if obj.lires == 1]:
            if str(frame) in o['omax'].keys():
                maxo, mino = max(o['omax'].values()), min(o['omin'].values())
                if len(o['cverts']) == 0:
                    for i, fli in enumerate([(face, face.loop_indices) for face in o.data.polygons if face.select == True]):
                        for li in fli[1]:
                            vi = o.data.loops[li].vertex_index
                            o.data.shape_keys.key_blocks[str(frame)].data[vi].co = o.data.shape_keys.key_blocks['Basis'].data[vi].co + context.scene.vi_disp_3dlevel * (abs(inv - (o['oreslist'][str(frame)][i]-mino)/(maxo - mino)) * fli[0].normal)
                for vn, v in enumerate(o['cverts']):
                    o.data.shape_keys.key_blocks[str(frame)].data[v].co = o.data.shape_keys.key_blocks['Basis'].data[v].co + context.scene.vi_disp_3dlevel * (abs(inv - (o['oreslist'][str(frame)][vn]-mino)/(maxo - mino)) * o.data.vertices[v].normal)
                o.data.update()

def register():
    bpy.utils.register_module(__name__)
    Object = bpy.types.Object
    Scene = bpy.types.Scene
    Material = bpy.types.Material

# LiVi object properties

    Object.livi_merr = bprop("LiVi simple mesh export", "Boolean for simple mesh export", False)
    Object.ies_name = sprop("", "IES File", 1024, "")
    Object.ies_strength = fprop("", "Strength of IES lamp", 0, 1, 1)
    Object.ies_unit = eprop([("m", "Meters", ""), ("c", "Centimeters", ""), ("f", "Feet", ""), ("i", "Inches", "")], "", "Specify the IES file measurement unit", "m")
    Object.ies_colour = fvprop(3, "IES Colour",'IES Colour', [1.0, 1.0, 1.0], 'COLOR', 0, 1)
    Object.licalc = bprop("", "", False)
    Object.lires = bprop("", "", False)
    Object.limerr = bprop("", "", False)
    Object.manip = bprop("", "", False)

# EnVi zone definitions

    Object.envi_type = eprop([("0", "None", "None"), ("1", "Thermal", "Thermal Zone"), ("2", "Shading", "Shading Object")], "EnVi object type", "Specify the EnVi object type", "0")
    Object.envi_heats1 = bprop("Schedule 1", "Enable period 1 zone heating", False)
    Object.envi_heats2 = bprop("Schedule 2", "Enable period 2 zone heating", False)
    Object.envi_heats1d = eprop([("0", "Every Day", "Daily Heating"), ("1", "Weekdays", "Weekday Heating"), ("2", "Weekend", "Weekend Heating")], "", "Heating", "0")
    Object.envi_heats2dwd = eprop([("1", "Weekdays", "Weekday cooling")], "", "Occupancy", "1")
    Object.envi_heats2dwe = eprop([("2", "Weekend", "Weekend cooling")], "", "Occupancy", "2")
    Object.envi_heats1c = iprop("Capacity (W)", "Maximum Heating Capacity (W)", 1, 50000, 500)
    Object.envi_heats1sp1 = iprop("Set-point ("+ u'\u00b0'+"C)", "Heating set-point ("+ u'\u00b0'+"C)", 1, 30, 20)
    Object.envi_heats2sp1 = iprop("Set-point ("+ u'\u00b0'+"'C)", "Heating set-point ("+ u'\u00b0'+"C)", 1, 30, 20)
    Object.envi_heats1sp2 = iprop("Set-point ("+ u'\u00b0'+"C)", "Heating set-point ("+ u'\u00b0'+"C)", 1, 30, 20)
    Object.envi_heats2sp2 = iprop("Set-point ("+ u'\u00b0'+"C)", "Heating set-point ("+ u'\u00b0'+"C)", 1, 30, 20)
    Object.envi_heats1sp3 = iprop("Set-point ("+ u'\u00b0'+"C)", "Heating set-point ("+ u'\u00b0'+"C)", 1, 30, 20)
    Object.envi_heats2sp3 = iprop("Set-point ("+ u'\u00b0'+"C)", "Heating set-point ("+ u'\u00b0'+"C)", 1, 30, 20)
    Object.envi_heats1p1st = iprop("Start hour", "Heating Start Time", 1, 24, 0)
    Object.envi_heats1p1et = iprop("End hour", "Heating End Time", 1, 24, 0)
    Object.envi_heats1p2st = iprop("Start hour", "Heating Start Time", 1, 24, 0)
    Object.envi_heats1p2et = iprop("End hour", "Heating End Time", 1, 24, 0)
    Object.envi_heats1p3st = iprop("Start hour", "Heating Start Time", 1, 24, 0)
    Object.envi_heats1p3et = iprop("End hour", "Heating End Time", 1, 24, 0)
    Object.envi_heats2p1st = iprop("Start hour", "Heating Start Time", 1, 24, 0)
    Object.envi_heats2p1et = iprop("End hour", "Heating End Time", 1, 24, 0)
    Object.envi_heats2p2st = iprop("Start hour", "Heating Start Time", 1,24, 0)
    Object.envi_heats2p2et = iprop("End hour", "Heating End Time", 1, 24, 0)
    Object.envi_heats2p3st = iprop("Start hour", "Heating Start Time", 1, 24, 0)
    Object.envi_heats2p3et = iprop("End hour", "Heating End Time", 1, 24, 0)
    Object.envi_cools1 = bprop("Schedule 1", "Enable period 1 zone heating", False)
    Object.envi_cools2 = bprop("Schedule 2", "Enable period 2 zone heating", False)
    Object.envi_cools1p1 = bprop("Period 1", "Enable period 1 zone cooling", False)
    Object.envi_cools1p2 = bprop("Period 2", "Enable period 2 zone cooling", False)
    Object.envi_cools1p3 = bprop("Period 3", "Enable period 3 zone cooling", False)
    Object.envi_cools2p1 = bprop("Period 1", "Enable period 1 zone cooling", False)
    Object.envi_cools2p2 = bprop("Period 2", "Enable period 2 zone cooling", False)
    Object.envi_cools2p3 = bprop("Period 3", "Enable period 3 zone cooling", False)
    Object.envi_cools1d = eprop([("0", "Every Day", "Daily cooling"), ("1", "Weekdays", "Weekday cooling"), ("2", "Weekend", "Weekend cooling")], "", "Occupancy", "0")
    Object.envi_cools2dwd = eprop([("1", "Weekdays", "Weekday cooling")], "", "Occupancy", "1")
    Object.envi_cools2dwe = eprop([("2", "Weekend", "Weekend cooling")], "", "Occupancy", "2")
    Object.envi_cools1c = iprop("Capacity (W)", "Maximum cooling Capacity (W)", 1, 50000, 0)
    Object.envi_cools1sp1 = iprop("Set-point("+ u'\u00b0'+"C)", "cooling set-point ("+ u'\u00b0'+"C)", 1, 30, 20)
    Object.envi_cools1sp2 = iprop("Set-point("+ u'\u00b0'+"C)", "cooling set-point ("+ u'\u00b0'+"C)", 1, 30, 20)
    Object.envi_cools1sp3 = iprop("Set-point("+ u'\u00b0'+"C)", "cooling set-point ("+ u'\u00b0'+"C)", 1, 30, 20)
    Object.envi_cools2sp1 = iprop("Set-point("+ u'\u00b0'+"C)", "cooling set-point ("+ u'\u00b0'+"C)", 1, 30, 20)
    Object.envi_cools2sp2 = iprop("Set-point("+ u'\u00b0'+"C)", "cooling set-point ("+ u'\u00b0'+"C)", 1, 30, 20)
    Object.envi_cools2sp3 = iprop("Set-point("+ u'\u00b0'+"C)", "cooling set-point ("+ u'\u00b0'+"C)", 1, 30, 20)
    Object.envi_cools1p1st = iprop("Start hour", "Cooling Start Time",1, 24, 1)
    Object.envi_cools1p1et = iprop("End hour", "Cooling End Time",1, 24, 1)
    Object.envi_cools1p2st = iprop("Start hour", "Cooling Start Time",1, 24, 1)
    Object.envi_cools1p2et = iprop("End hour", "Cooling End Time",1, 24, 1)
    Object.envi_cools1p3st = iprop("Start hour", "Cooling Start Time",1, 24, 1)
    Object.envi_cools1p3et = iprop("End hour", "Cooling End Time",1, 24, 1)
    Object.envi_cools2p1st = iprop("Start hour", "Cooling Start Time", 1, 24, 1)
    Object.envi_cools2p1et = iprop("End hour", "Cooling End Time",1, 24, 1)
    Object.envi_cools2p2st = iprop("Start hour", "Cooling Start Time", 1, 24, 1)
    Object.envi_cools2p2et = iprop("End hour", "Cooling End Time", 1, 24, 1)
    Object.envi_cools2p3st = iprop("Start hour", "Cooling Start Time", 1, 24, 1)
    Object.envi_cools2p3et = iprop("End hour", "Cooling End Time", 1, 24, 1)
    Object.envi_occs1 = bprop("Period 1", "Enable zone occupation for period 1", False)
    Object.envi_occs2 = bprop("Period 2", "Enable zone occupation for period 1", False)
    Object.envi_occtype = eprop([("0", "None", "No occupancy"),("1", "Occupants", "Actual number of people"), ("2", "Person/m"+ u'\u00b2', "Number of people per squared metre floor area"),
                                              ("3", "m"+ u'\u00b2'+"/Person", "Floor area per person")], "", "The type of zone occupancy specification", "0")
    Object.envi_occsmax = fprop("Max", "Maximum level of occupancy that will occur in this schedule", 1, 500, 1)
    Object.envi_occs1d = eprop([("0", "Every Day", "Daily Occupancy"), ("1", "Weekdays", "Weekday Occupancy"), ("2", "Weekend", "Weekend Occupancy")], "", "Occupancy", "0")
    Object.envi_occs2dwd = eprop([("1", "Weekdays", "Weekday occupancy")], "", "Occupancy", "1")
    Object.envi_occs2dwe = eprop([("2", "Weekend", "Weekend occupancy")], "", "Occupancy", "2")
    Object.envi_occs1p1st = iprop("Start hour", "Occupancy Start Time", 1, 24, 1)
    Object.envi_occs1p1et = iprop("End hour", "Occupancy End Time", 1, 24, 1)
    Object.envi_occs1p1level = fprop("Fraction", "Fraction of maximum evel of occupancy", 0, 500, 0)
    Object.envi_occs1p2st = iprop("Start hour", "Occupancy Start Time", 1, 24, 1)
    Object.envi_occs1p2et = iprop("End hour", "Occupancy End Time", 1, 24, 1)
    Object.envi_occs1p2level = fprop("Fraction", "Fraction of maximum level of occupancy", 0, 1, 0)
    Object.envi_occs1p3st = iprop("Start hour", "Occupancy Start Time", 1, 24, 1)
    Object.envi_occs1p3et = iprop("End hour", "Occupancy End Time", 1, 24, 1)
    Object.envi_occs1p3level = fprop("Fraction", "Fraction of maximum evel of occupancy", 0, 1, 0)
    Object.envi_occs1watts = iprop("W/p", "Watts per person", 70, 800, 90)
    Object.envi_occs2p1st = iprop("Start hour", "Occupancy Start Time", 1, 24, 1)
    Object.envi_occs2p1et = iprop("End hour", "Occupancy End Time", 1, 24, 1)
    Object.envi_occs2p1level = fprop("Fraction", "Fraction of maximum evel of occupancy", 0, 1, 0)
    Object.envi_occs2p2st = iprop("Start hour", "Occupancy Start Time", 1, 24, 1)
    Object.envi_occs2p2et = iprop("End hour", "Occupancy End Time", 1, 24, 1)
    Object.envi_occs2p2level = fprop("Fraction", "Fraction of maximum evel of occupancy", 0, 1, 0)
    Object.envi_occs2p3st = iprop("Start hour", "Occupancy Start Time", 1, 24, 1)
    Object.envi_occs2p3et = iprop("End hour", "Occupancy End Time", 1, 24, 1)
    Object.envi_occs2p3level = fprop("Fraction", "Fraction of maximum evel of occupancy", 0, 1, 0)
    Object.envi_occs2watts = iprop("W/p", "Watts per person", 70, 800, 90)
    Object.envi_inftype = eprop([("0", "None", "No infiltration"), ("2", "m"+ u'\u00b3'+"/s", "metre cubed per second"), ("3", "ACH", "Air changes per hour")], "", "The type of zone infiltration specification", "0")
    Object.envi_occinftype = eprop([("0", "None", "No infiltration"),("1", "l/s/p", "litres per second per person"), ("2", "m"+ u'\u00b3'+"/s", "metre cubed per second"),
                                    ("3", "ACH", "Air changes per hour")], "", "The type of zone infiltration specification", "0")
    Object.envi_infbasetype = eprop([("0", "m"+ u'\u00b3'+"/s", "metre cubed per second"), ("1", "ACH", "Air changes per hour")], "", "The type of zone base infiltration specification", "1")
    Object.envi_infbaselevel = fprop("Level", "Level of Infiltration", 0, 500, 0.1)
    Object.envi_inflevel = fprop("Level", "Level of Infiltration", 0, 500, 0.1)
    Object.envi_infs1d = eprop([("0", "Every Day", "Daily Infiltration"), ("1", "Weekdays", "Weekday Infiltration"), ("2", "Weekend", "Weekend Infiltration")], "", "Infiltration", "0")
    Object.envi_infs1p1st = iprop("Start hour", "Infiltration Start Time",1, 24, 1)
    Object.envi_infs1p1et = iprop("End hour", "Infiltration End Time",1, 24, 1)
    Object.envi_infs1p1level = iprop("Level", "Level of Infiltration", 1, 500, 0)
    Object.envi_infs1p2st = iprop("Start hour", "Infiltration Start Time", 1, 24, 1)
    Object.envi_infs1p2et = iprop("End hour", "Infiltration End Time", 1, 24, 1)
    Object.envi_infs1p2level = iprop("Level", "Level of Infiltration", 1, 500, 0)
    Object.envi_infs1p3st = iprop("Start hour", "Infiltration Start Time", 1, 24, 1)
    Object.envi_infs1p3et = iprop("End hour", "Infiltration End Time",1, 24, 1)
    Object.envi_infs1p3level = iprop("Level", "Level of Infiltration", 1, 500, 0)
    Object.envi_infs2d = eprop([("0", "Every Day", "Daily Infiltration"), ("1", "Weekdays", "Weekday Infiltration"), ("2", "Weekend", "Weekend Infiltration")],"", "Infiltration", "0")
    Object.envi_infs2p1st = iprop("Start hour", "Infiltration Start Time", 1, 24, 1)
    Object.envi_infs2p1et = iprop("End hour", "Infiltration End Time", 1, 24, 1)
    Object.envi_infs2p1level = iprop("Level", "Level of Infiltration", 1, 500, 0)
    Object.envi_infs2p2st = iprop("Start hour", "Infiltration Start Time", 1, 24, 1)
    Object.envi_infs2p2et = iprop("End hour", "Infiltration End Time", 1, 24, 1)
    Object.envi_infs2p2level = iprop("Level", "Level of Infiltration", 1, 500, 0)
    Object.envi_infs2p3st = iprop("Start hour", "Infiltration Start Time", 1, 24, 1)
    Object.envi_infs2p3et = iprop("End hour", "Infiltration End Time", 1, 24, 1)
    Object.envi_infs2p3level = iprop("Level", "Level of Infiltration", 1, 500, 0)
    Object.envi_infs2watts = iprop("W/p", "Watts per person",70, 800, 90)
    Object.envi_inf3d = eprop([("0", "Every Day", "Daily Infiltration"), ("1", "Weekdays", "Weekday Infiltration"), ("2", "Weekend", "Weekend Infiltration")], "", "Infiltration", "0")
    Object.envi_infs3p1st = iprop("Start hour", "Infiltration Start Time", 1, 24, 1)
    Object.envi_infs3p1et = iprop("End hour", "Infiltration End Time", 1, 24, 1)
    Object.envi_infs3p1level = iprop("Level", "Level of Infiltration", 1, 500, 0)
    Object.envi_infs3p2st = iprop("Start hour", "Infiltration Start Time", 1, 24, 1)
    Object.envi_infs3p2et = iprop("End hour", "Infiltration End Time", 1, 24, 1)
    Object.envi_infs3p2level = iprop("Level", "Level of Infiltration", 1, 500, 0)
    Object.envi_infs3p3st = iprop("Start hour", "Infiltration Start Time", 1, 24, 1)
    Object.envi_infs3p3et = iprop("End hour", "Infiltration End Time", 1, 24, 1)
    Object.envi_infs3p3level = iprop("Level", "Level of Infiltration", 1, 500, 0)
    Object.envi_inf3watts = iprop("W/p", "Watts per person",70, 800, 90)

# LiVi material definitions
    Material.vi_shadow = bprop("VI Shadow", "Flag to signify whether the material represents a VI Shadow sensing surface", False)
    Material.livi_sense = bprop("LiVi Sensor", "Flag to signify whether the material represents a LiVi sensing surface", False)
    Material.livi_compliance = bprop("LiVi Compliance Surface", "Flag to siginify whether the material represents a LiVi compliance surface", False)
    Material.gl_roof = bprop("Glazed Roof", "Flag to siginify whether the communal area has a glazed roof", False)
    hspacetype = [('0', 'Public/Staff', 'Public/Staff area'), ('1', 'Patient', 'Patient area')]
    rspacetype = [('0', "Kitchen", "Kitchen space"), ('1', "Living/Dining/Study", "Living/Dining/Study area"), ('2', "Communal", "Non-residential or communal area")]
    respacetype = [('0', "Sales", "Sales space"), ('1', "Occupied", "Occupied space")]

    Material.hspacemenu = eprop(hspacetype, "", "Type of healthcare space", '0')
    Material.rspacemenu = eprop(rspacetype, "", "Type of residential space", '0')
    Material.respacemenu = eprop(respacetype, "", "Type of retail space", '0')

# EnVi material definitions

    Material.envi_con_type = eprop([("Wall", "Wall", "Wall construction"),("Floor", "Floor", "Floor construction"),("Roof", "Roof", "Roof construction"),("Window", "Window", "Window construction"), ("Door", "Door", "Door construction"),
                    ("Shading", "Shading", "Shading material"),("Aperture", "Aperture", "Airflow Aperture"),("None", "None", "Surface to be ignored")], "", "Specify the construction type", "None")
    Material.envi_boundary = bprop("On zone boundary", "Flag to siginify whether the material represents a zone boundary", False)
    Material.afsurface = bprop("Airflow surface", "Flag to siginify whether the material represents an airflow surface", False)
    Material.envi_aperture = eprop([("0", "External", "External facade airflow component", 0), ("1", "Internal", "Zone boundary airflow component", 1),], "", "Position of the airflow component", "0")
    Material.envi_con_makeup = eprop([("0", "Pre-set", "Construction pre-set"),("1", "Layers", "Custom layers"),("2", "Dummy", "Adiabatic")], "", "Pre-set construction of custom layers", "0")
    Material.envi_layero = eprop([("0", "None", "Not present"), ("1", "Database", "Select from databse"), ("2", "Custom", "Define custom material properties")], "", "Composition of the outer layer", "0")
    Material.envi_layerott = Material.envi_layer1tt = Material.envi_layer2tt = Material.envi_layer3tt = Material.envi_layer4tt = eprop(
                    [("0", "Glass", "Choose a material from the glass database"),("1", "Gas", "Choose a material from the gas database")], "", "Composition of the outer layer", "0")

    Material.envi_layeroto = Material.envi_layer1to = Material.envi_layer2to = Material.envi_layer3to = Material.envi_layer4to = eprop(
            [("0", "Brick", "Choose a material from the brick database"),("1", "Cladding", "Choose a material from the cladding database"), ("2", "Concrete", "Choose a material from the concrete database"),("3", "Metal", "Choose a material from the metal database"),
                   ("4", "Stone", "Choose a material from the stone database"),("5", "Wood", "Choose a material from the wood database"),
                   ("6", "Gas", "Choose a material from the gas database"),("7", "Insulation", "Choose a material from the insulation database")],"","Composition of the outer layer","0")

    Material.envi_layer1 = eprop([("0", "None", "Not present"),("1", "Database", "Select from databse"),("2", "Custom", "Define custom material properties")], "", "Composition of the next layer", "0")
    Material.envi_layer2 = eprop([("0", "None", "Not present"),("1", "Database", "Select from databse"),("2", "Custom", "Define custom material properties")],"","Composition of the next layer","0")
    Material.envi_layer3 = eprop([("0", "None", "Not present"),("1", "Database", "Select from databse"), ("2", "Custom", "Define custom material properties")],"","Composition of the next layer","0")
    Material.envi_layer4 = eprop([("0", "None", "Not present"),("1", "Database", "Select from databse"), ("2", "Custom", "Define custom material properties")], "", "Composition of the next layer", "0")
    Material.envi_export = bprop("Material Export", "Flag to tell EnVi to export this material", False)
    Material.envi_export_wallconlist = eprop(wallconlist, "Wall Constructions", "", wallconlist[0][0])
    Material.envi_export_floorconlist = eprop(floorconlist, "Floor Constructions",  "", floorconlist[0][0])
    Material.envi_export_roofconlist = eprop(roofconlist, "Roof Constructions",  "", roofconlist[0][0])
    Material.envi_export_doorconlist = eprop(doorconlist, "Door Constructions",  "", doorconlist[0][0])
    Material.envi_export_glazeconlist = eprop(glazeconlist, "Window Constructions",  "", glazeconlist[0][0])
    Material.envi_export_bricklist_lo = eprop(bricklist, "", "", bricklist[0][0])
    Material.envi_export_claddinglist_lo = eprop(claddinglist, "", "", claddinglist[0][0])
    Material.envi_export_stonelist_lo = eprop(stonelist, "",  "", stonelist[0][0])
    Material.envi_export_woodlist_lo = eprop(woodlist, "",  "", woodlist[0][0])
    Material.envi_export_metallist_lo = eprop(metallist, "",  "", metallist[0][0])
    Material.envi_export_gaslist_lo = eprop(gaslist, "",  "", gaslist[0][0])
    Material.envi_export_glasslist_lo = eprop(glasslist, "",  "", glasslist[0][0])
    Material.envi_export_concretelist_lo = eprop(concretelist, "",  "", concretelist[0][0])
    Material.envi_export_insulationlist_lo = eprop(insullist, "",  "", insullist[0][0])
    Material.envi_export_wgaslist_lo = eprop(wgaslist, "",  "", wgaslist[0][0])
    Material.envi_export_bricklist_l1 = eprop(bricklist, "",  "", bricklist[0][0])
    Material.envi_export_claddinglist_l1 = eprop(claddinglist, "", "", claddinglist[0][0])
    Material.envi_export_stonelist_l1 = eprop(stonelist, "",  "", stonelist[0][0])
    Material.envi_export_woodlist_l1 = eprop(woodlist, "",  "", woodlist[0][0])
    Material.envi_export_metallist_l1 = eprop(metallist, "",  "", metallist[0][0])
    Material.envi_export_gaslist_l1 = eprop(gaslist, "",  "", gaslist[0][0])
    Material.envi_export_glasslist_l1 = eprop(glasslist, "",  "", glasslist[0][0])
    Material.envi_export_concretelist_l1 = eprop(concretelist, "",  "", concretelist[0][0])
    Material.envi_export_insulationlist_l1 = eprop(insullist, "",  "", insullist[0][0])
    Material.envi_export_wgaslist_l1 = eprop(wgaslist, "",  "", wgaslist[0][0])
    Material.envi_export_bricklist_l2 = eprop(bricklist, "",  "", bricklist[0][0])
    Material.envi_export_claddinglist_l2 = eprop(claddinglist, "", "", claddinglist[0][0])
    Material.envi_export_stonelist_l2 = eprop(stonelist, "",  "", stonelist[0][0])
    Material.envi_export_woodlist_l2 = eprop(woodlist, "",  "", woodlist[0][0])
    Material.envi_export_metallist_l2 = eprop(metallist, "",  "", metallist[0][0])
    Material.envi_export_gaslist_l2 = eprop(gaslist, "",  "", gaslist[0][0])
    Material.envi_export_glasslist_l2 = eprop(glasslist, "",  "", glasslist[0][0])
    Material.envi_export_concretelist_l2 = eprop(concretelist, "",  "", concretelist[0][0])
    Material.envi_export_insulationlist_l2 = eprop(insullist, "",  "", insullist[0][0])
    Material.envi_export_wgaslist_l2 = eprop(wgaslist, "",  "", wgaslist[0][0])
    Material.envi_export_bricklist_l3 = eprop(bricklist, "",  "", bricklist[0][0])
    Material.envi_export_claddinglist_l3 = eprop(claddinglist, "", "", claddinglist[0][0])
    Material.envi_export_stonelist_l3 = eprop(stonelist, "",  "", stonelist[0][0])
    Material.envi_export_woodlist_l3 = eprop(woodlist, "",  "", woodlist[0][0])
    Material.envi_export_metallist_l3 = eprop(metallist, "",  "", metallist[0][0])
    Material.envi_export_gaslist_l3 = eprop(gaslist, "",  "", gaslist[0][0])
    Material.envi_export_glasslist_l3 = eprop(glasslist, "",  "", glasslist[0][0])
    Material.envi_export_concretelist_l3 = eprop(concretelist, "",  "", concretelist[0][0])
    Material.envi_export_insulationlist_l3 = eprop(insullist, "",  "", insullist[0][0])
    Material.envi_export_wgaslist_l3 = eprop(wgaslist, "",  "", wgaslist[0][0])
    Material.envi_export_bricklist_l4 = eprop(bricklist, "",  "", bricklist[0][0])
    Material.envi_export_claddinglist_l4 = eprop(claddinglist, "", "", claddinglist[0][0])
    Material.envi_export_stonelist_l4 = eprop(stonelist, "",  "", stonelist[0][0])
    Material.envi_export_woodlist_l4 = eprop(woodlist, "",  "", woodlist[0][0])
    Material.envi_export_metallist_l4 = eprop(metallist, "",  "", metallist[0][0])
    Material.envi_export_gaslist_l4 = eprop(gaslist, "",  "", gaslist[0][0])
    Material.envi_export_glasslist_l4 = eprop(glasslist, "",  "", glasslist[0][0])
    Material.envi_export_concretelist_l4 = eprop(concretelist, "",  "", concretelist[0][0])
    Material.envi_export_insulationlist_l4 = eprop(insullist, "",  "", insullist[0][0])
    Material.envi_export_wgaslist_l4 = eprop(wgaslist, "",  "", wgaslist[0][0])
    Material.envi_export_lo_name = sprop("Layer name", "Layer name", 0, "")
    Material.envi_export_l1_name = sprop("Layer name", "Layer name", 0, "")
    Material.envi_export_l2_name = sprop("Layer name", "Layer name", 0, "")
    Material.envi_export_l3_name = sprop("Layer name", "Layer name", 0, "")
    Material.envi_export_l4_name = sprop("Layer name", "Layer name", 0, "")
    Material.envi_export_lo_tc = fprop("Conductivity", "Thermal Conductivity", 0, 10, 0.5)
    Material.envi_export_l1_tc = fprop("Conductivity", "Thermal Conductivity", 0, 10, 0.5)
    Material.envi_export_l2_tc = fprop("Conductivity", "Thermal Conductivity", 0, 10, 0.5)
    Material.envi_export_l3_tc = fprop("Conductivity", "Thermal Conductivity", 0, 10, 0.5)
    Material.envi_export_l4_tc = fprop("Conductivity", "Thermal Conductivity", 0, 10, 0.5)
    Material.envi_export_lo_rough = eprop([("VeryRough", "VeryRough", "Roughness"), ("Rough", "Rough", "Roughness"), ("MediumRough", "MediumRough", "Roughness"),
                                                        ("MediumSmooth", "MediumSmooth", "Roughness"), ("Smooth", "Smooth", "Roughness"), ("VerySmooth", "VerySmooth", "Roughness")],
                                                        "Material surface roughness",
                                                        "specify the material rughness for convection calculations",
                                                        "Rough")
    Material.envi_export_l1_rough = eprop([("VeryRough", "VeryRough", "Roughness"), ("Rough", "Rough", "Roughness"), ("MediumRough", "MediumRough", "Roughness"),
                                                        ("MediumSmooth", "MediumSmooth", "Roughness"), ("Smooth", "Smooth", "Roughness"), ("VerySmooth", "VerySmooth", "Roughness")],
                                                        "Material surface roughness",
                                                        "specify the material rughness for convection calculations",
                                                        "Rough")
    Material.envi_export_l2_rough = eprop([("VeryRough", "VeryRough", "Roughness"), ("Rough", "Rough", "Roughness"), ("MediumRough", "MediumRough", "Roughness"),
                                                        ("MediumSmooth", "MediumSmooth", "Roughness"), ("Smooth", "Smooth", "Roughness"), ("VerySmooth", "VerySmooth", "Roughness")],
                                                        "Material surface roughness",
                                                        "specify the material rughness for convection calculations",
                                                        "Rough")
    Material.envi_export_l3_rough = eprop([("VeryRough", "VeryRough", "Roughness"), ("Rough", "Rough", "Roughness"), ("MediumRough", "MediumRough", "Roughness"),
                                                        ("MediumSmooth", "MediumSmooth", "Roughness"), ("Smooth", "Smooth", "Roughness"), ("VerySmooth", "VerySmooth", "Roughness")],
                                                        "Material surface roughness",
                                                        "specify the material rughness for convection calculations",
                                                        "Rough")
    Material.envi_export_l4_rough = eprop([("VeryRough", "VeryRough", "Roughness"), ("Rough", "Rough", "Roughness"), ("MediumRough", "MediumRough", "Roughness"),
                                                        ("MediumSmooth", "MediumSmooth", "Roughness"), ("Smooth", "Smooth", "Roughness"), ("VerySmooth", "VerySmooth", "Roughness")],
                                                        "Material surface roughness",
                                                        "specify the material rughness for convection calculations",
                                                        "Rough")
    Material.envi_export_lo_rho = fprop("Density", "Density (kg/m3)", 0, 10000, 1000)
    Material.envi_export_l1_rho = fprop("Density", "Density (kg/m3)", 0, 10000, 1000)
    Material.envi_export_l2_rho = fprop("Density", "Density (kg/m3)", 0, 10000, 1000)
    Material.envi_export_l3_rho = fprop("Density", "Density (kg/m3)", 0, 10000, 1000)
    Material.envi_export_l4_rho = fprop("Density", "Density (kg/m3)", 0, 10000, 1000)
    Material.envi_export_lo_shc = fprop("SHC", "Specific Heat Capacity (J/kgK)", 0, 10000, 1000)
    Material.envi_export_l1_shc = fprop("SHC", "Specific Heat Capacity (J/kgK)", 0, 10000, 1000)
    Material.envi_export_l2_shc = fprop("SHC", "Specific Heat Capacity (J/kgK)", 0, 10000, 1000)
    Material.envi_export_l3_shc = fprop("SHC", "Specific Heat Capacity (J/kgK)", 0, 10000, 1000)
    Material.envi_export_l4_shc = fprop("SHC", "Specific Heat Capacity (J/kgK)", 0, 10000, 1000)
    Material.envi_export_lo_thi = fprop("Thickness", "Thickness (mm)", 0, 10000, 100)
    Material.envi_export_l1_thi = fprop("Thickness", "Thickness (mm)", 0, 10000, 100)
    Material.envi_export_l2_thi = fprop("Thickness", "Thickness (mm)", 0, 10000, 100)
    Material.envi_export_l3_thi = fprop("Thickness", "Thickness (mm)", 0, 10000, 100)
    Material.envi_export_l4_thi = fprop("Thickness", "Thickness (mm)", 0, 10000, 100)
    Material.envi_export_lo_tab = fprop("TA", "Thermal Absorptance", 0, 1, 0.8)
    Material.envi_export_l1_tab = fprop("TA", "Thermal Absorptance", 0, 1, 0.8)
    Material.envi_export_l2_tab = fprop("TA", "Thermal Absorptance", 0, 1, 0.8)
    Material.envi_export_l3_tab = fprop("TA", "Thermal Absorptance", 0, 1, 0.8)
    Material.envi_export_l4_tab = fprop("TA", "Thermal Absorptance", 0, 1, 0.8)
    Material.envi_export_lo_sab = fprop("SA", "Solar Absorptance", 0, 1, 0.6)
    Material.envi_export_l1_sab = fprop("SA", "Solar Absorptance", 0, 1, 0.6)
    Material.envi_export_l2_sab = fprop("SA", "Solar Absorptance", 0, 1, 0.6)
    Material.envi_export_l3_sab = fprop("SA", "Solar Absorptance", 0, 1, 0.6)
    Material.envi_export_l4_sab = fprop("SA", "Solar Absorptance", 0, 1, 0.6)
    Material.envi_export_lo_vab = fprop("VA", "Visible Absorptance", 0, 1, 0.6)
    Material.envi_export_l1_vab = fprop("VA", "Visible Absorptance", 0, 1, 0.6)
    Material.envi_export_l2_vab = fprop("VA", "Visible Absorptance", 0, 1, 0.6)
    Material.envi_export_l3_vab = fprop("VA", "Visible Absorptance", 0, 1, 0.6)
    Material.envi_export_l4_vab = fprop("VA", "Visible Absorptance", 0, 1, 0.6)
    Material.envi_export_lo_odt = eprop([("SpectralAverage", "SpectralAverage", "Optical Data Type")], "Optical Data Type", "Optical Data Type", "SpectralAverage")
    Material.envi_export_l1_odt = eprop([("SpectralAverage", "SpectralAverage", "Optical Data Type")], "Optical Data Type", "Optical Data Type", "SpectralAverage")
    Material.envi_export_l2_odt = eprop([("SpectralAverage", "SpectralAverage", "Optical Data Type")], "Optical Data Type", "Optical Data Type", "SpectralAverage")
    Material.envi_export_l3_odt = eprop([("SpectralAverage", "SpectralAverage", "Optical Data Type")], "Optical Data Type", "Optical Data Type", "SpectralAverage")
    Material.envi_export_l4_odt = eprop([("SpectralAverage", "SpectralAverage", "Optical Data Type")], "Optical Data Type", "Optical Data Type", "SpectralAverage")
    Material.envi_export_lo_sds = eprop([("0", "", "Window Glass Spectral Data Set Name")], "Window Glass Spectral Data Set Name", "Window Glass Spectral Data Set Name", "0")
    Material.envi_export_l1_sds = eprop([("0", "", "Window Glass Spectral Data Set Name")], "Window Glass Spectral Data Set Name", "Window Glass Spectral Data Set Name", "0")
    Material.envi_export_l2_sds = eprop([("0", "", "Window Glass Spectral Data Set Name")], "Window Glass Spectral Data Set Name", "Window Glass Spectral Data Set Name", "0")
    Material.envi_export_l3_sds = eprop([("0", "", "Window Glass Spectral Data Set Name")], "Window Glass Spectral Data Set Name", "Window Glass Spectral Data Set Name", "0")
    Material.envi_export_l4_sds = eprop([("0", "", "Window Glass Spectral Data Set Name")], "Window Glass Spectral Data Set Name", "Window Glass Spectral Data Set Name", "0")
    Material.envi_export_lo_stn = fprop("STN", "Solar Transmittance at Normal Incidence", 0, 1, 0.9)
    Material.envi_export_l1_stn = fprop("STN", "Solar Transmittance at Normal Incidence", 0, 1, 0.9)
    Material.envi_export_l2_stn = fprop("STN", "Solar Transmittance at Normal Incidence", 0, 1, 0.9)
    Material.envi_export_l3_stn = fprop("STN", "Solar Transmittance at Normal Incidence", 0, 1, 0.9)
    Material.envi_export_l4_stn = fprop("STN", "Solar Transmittance at Normal Incidence", 0, 1, 0.9)
    Material.envi_export_lo_fsn = fprop("FSN", "Front Side Solar Reflectance at Normal Incidence", 0, 1, 0.075)
    Material.envi_export_l1_fsn = fprop("FSN", "Front Side Solar Reflectance at Normal Incidence", 0, 1, 0.075)
    Material.envi_export_l2_fsn = fprop("FSN", "Front Side Solar Reflectance at Normal Incidence", 0, 1, 0.075)
    Material.envi_export_l3_fsn = fprop("FSN", "Front Side Solar Reflectance at Normal Incidence", 0, 1, 0.075)
    Material.envi_export_l4_fsn = fprop("FSN", "Front Side Solar Reflectance at Normal Incidence", 0, 1, 0.075)
    Material.envi_export_lo_bsn = fprop("BSN", "Back Side Solar Reflectance at Normal Incidence", 0, 1, 0.075)
    Material.envi_export_l1_bsn = fprop("BSN", "Back Side Solar Reflectance at Normal Incidence", 0, 1, 0.075)
    Material.envi_export_l2_bsn = fprop("BSN", "Back Side Solar Reflectance at Normal Incidence", 0, 1, 0.075)
    Material.envi_export_l3_bsn = fprop("BSN", "Back Side Solar Reflectance at Normal Incidence", 0, 1, 0.075)
    Material.envi_export_l4_bsn = fprop("BSN", "Back Side Solar Reflectance at Normal Incidence", 0, 1, 0.075)
    Material.envi_export_lo_vtn = fprop("VTN", "Visible Transmittance at Normal Incidence", 0, 1, 0.9)
    Material.envi_export_l1_vtn = fprop("VTN", "Visible Transmittance at Normal Incidence", 0, 1, 0.9)
    Material.envi_export_l2_vtn = fprop("VTN", "Visible Transmittance at Normal Incidence", 0, 1, 0.9)
    Material.envi_export_l3_vtn = fprop("VTN", "Visible Transmittance at Normal Incidence", 0, 1, 0.9)
    Material.envi_export_l4_vtn = fprop("VTN", "Visible Transmittance at Normal Incidence", 0, 1, 0.9)
    Material.envi_export_lo_fvrn = fprop("FVRN", "Front Side Visible Reflectance at Normal Incidence", 0, 1, 0.08)
    Material.envi_export_l1_fvrn = fprop("FVRN", "Front Side Visible Reflectance at Normal Incidence", 0, 1, 0.08)
    Material.envi_export_l2_fvrn = fprop("FVRN", "Front Side Visible Reflectance at Normal Incidence", 0, 1, 0.08)
    Material.envi_export_l3_fvrn = fprop("FVRN", "Front Side Visible Reflectance at Normal Incidence", 0, 1, 0.08)
    Material.envi_export_l4_fvrn = fprop("FVRN", "Front Side Visible Reflectance at Normal Incidence", 0, 1, 0.08)
    Material.envi_export_lo_bvrn = fprop("BVRN", "Back Side Visible Reflectance at Normal Incidence", 0, 1, 0.08)
    Material.envi_export_l1_bvrn = fprop("BVRN", "Back Side Visible Reflectance at Normal Incidence", 0, 1, 0.08)
    Material.envi_export_l2_bvrn = fprop("BVRN", "Back Side Visible Reflectance at Normal Incidence", 0, 1, 0.08)
    Material.envi_export_l3_bvrn = fprop("BVRN", "Back Side Visible Reflectance at Normal Incidence", 0, 1, 0.08)
    Material.envi_export_l4_bvrn = fprop("BVRN", "Back Side Visible Reflectance at Normal Incidence", 0, 1, 0.08)
    Material.envi_export_lo_itn = fprop("ITN", "Infrared Transmittance at Normal Incidence", 0, 1, 0.0)
    Material.envi_export_l1_itn = fprop("ITN", "Infrared Transmittance at Normal Incidence", 0, 1, 0.0)
    Material.envi_export_l2_itn = fprop("ITN", "Infrared Transmittance at Normal Incidence", 0, 1, 0.0)
    Material.envi_export_l3_itn = fprop("ITN", "Infrared Transmittance at Normal Incidence", 0, 1, 0.0)
    Material.envi_export_l4_itn = fprop("ITN", "Infrared Transmittance at Normal Incidence", 0, 1, 0.0)
    Material.envi_export_lo_fie = fprop("FIE", "Front Side Infrared Hemispherical Emissivity", 0, 1, 0.84)
    Material.envi_export_l1_fie = fprop("FIE", "Front Side Infrared Hemispherical Emissivity", 0, 1, 0.84)
    Material.envi_export_l2_fie = fprop("FIE", "Front Side Infrared Hemispherical Emissivity", 0, 1, 0.84)
    Material.envi_export_l3_fie = fprop("FIE", "Front Side Infrared Hemispherical Emissivity", 0, 1, 0.84)
    Material.envi_export_l4_fie = fprop("FIE", "Front Side Infrared Hemispherical Emissivity", 0, 1, 0.84)
    Material.envi_export_lo_bie = fprop("BIE", "Back Side Infrared Hemispherical Emissivity", 0, 1, 0.84)
    Material.envi_export_l1_bie = fprop("BIE", "Back Side Infrared Hemispherical Emissivity", 0, 1, 0.84)
    Material.envi_export_l2_bie = fprop("BIE", "Back Side Infrared Hemispherical Emissivity", 0, 1, 0.84)
    Material.envi_export_l3_bie = fprop("BIE", "Back Side Infrared Hemispherical Emissivity", 0, 1, 0.84)
    Material.envi_export_l4_bie = fprop("BIE", "Back Side Infrared Hemispherical Emissivity", 0, 1, 0.84)
    Material.envi_shad_att = bprop("Attached", "Flag to specify shading attached to the building",False)

    # Scene parameters

    Scene.fs = iprop("Frame start", "Starting frame",0, 1000, 0)
    Scene.fe = iprop("Frame start", "End frame",0, 50000, 0)
    Scene.gfe = iprop("Frame start", "End frame",0, 50000, 0)
    Scene.cfe = iprop("Frame start", "End frame",0, 50000, 0)
    Scene.vipath = sprop("VI Path", "Path to files included with the VI-Suite ", 1024, addonpath)
    Scene.solday = bpy.props.IntProperty(name = "", description = "Day of year", min = 1, max = 365, default = 1, update=sunpath1)
    Scene.solhour = bpy.props.FloatProperty(name = "", description = "Time of day", min = 0, max = 24, default = 12, update=sunpath1)
    Scene.soldistance = bpy.props.IntProperty(name = "", description = "Sun path scale", min = 1, max = 5000, default = 100, update=sunpath1)
    Scene.hourdisp = bprop("", "",0)
    Scene.spupdate = bprop("", "",0)
#    Scene.latitude = bpy.props.FloatProperty(name="Latitude", description="Site Latitude", min=-90, max=90, default=52)
#    Scene.longitude = bpy.props.FloatProperty(name="Longitude", description="Site Longitude", min=-180, max=180, default=0)
    Scene.li_disp_panel = iprop("Display Panel", "Shows the Display Panel", -1, 2, 0)
    Scene.lic_disp_panel = bprop("", "",False)
    Scene.vi_disp_3d = bprop("VI 3D display", "Boolean for 3D results display",  False)
    Scene.vi_disp_3dlevel = bpy.props.FloatProperty(name = "", description = "Level of 3D result plane extrusion", min = 0, max = 500, default = 0, update = eupdate)
    Scene.vi_display = bprop("", "",False)
    Scene.sp_disp_panel = bprop("", "",False)
    Scene.wr_disp_panel = bprop("", "",False)
    Scene.ss_disp_panel = iprop("Display Panel", "Shows the Display Panel", -1, 2, 0)
    Scene.ss_leg_display = bprop("", "",False)
    Scene.en_disp_panel = bprop("", "",False)
    Scene.li_compliance = bprop("", "", False)
    Scene.vi_display_rp = bprop("", "", False)
    Scene.vi_leg_display = bprop("", "", False)
    Scene.vi_display_sel_only = bprop("", "", False)
    Scene.vi_display_vis_only = bprop("", "", False)
    Scene.vi_display_rp_fs = iprop("", "Point result font size", 4, 48, 9)
    Scene.vi_display_rp_fc = fvprop(4, "", "Font colour", [0.0, 0.0, 0.0, 1.0], 'COLOR', 0, 1)
    Scene.vi_display_rp_fsh = fvprop(4, "", "Font shadow", [0.0, 0.0, 0.0, 1.0], 'COLOR', 0, 1)
    Scene.li_projname = sprop("", "Name of the building project", 1024, '')
    Scene.li_assorg = sprop("", "Name of the assessing organisation", 1024, '')
    Scene.li_assind = sprop("", "Name of the assessing individual", 1024, '')
    Scene.li_jobno = sprop("", "Project job number", 1024, '')
    Scene.resnode = sprop("", "", 0, "")
    Scene.restree = sprop("", "", 0, "")

    nodeitems_utils.register_node_categories("Vi Nodes", vinode_categories)
    nodeitems_utils.register_node_categories("EnVi Nodes", envinode_categories)

def unregister():
    bpy.utils.unregister_module(__name__)
    nodeitems_utils.unregister_node_categories("Vi Nodes")
    nodeitems_utils.unregister_node_categories("EnVi Nodes")


from django.contrib.auth.models import Group
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.contrib.auth.models import User
from courses_app.models import Badge

def populate_models(sender, **kwargs):
    list_of_groups = ["teacher", "student"]
    for group in list_of_groups:
        Group.objects.get_or_create(name=group)
    badge_all_tasks = {"title":"Выполнил все задания", "description":"Выдается тому, кто выполнил все задания"}
    Badge.objects.get_or_create(title = badge_all_tasks["title"], description = badge_all_tasks["description"])
    badge_keyword_tasks = {"title":"Выполнил все задания с ключевым словом", "description":"Выдается тому, кто выполнил все заданияс ключевым словом"}
    Badge.objects.get_or_create(title = badge_keyword_tasks["title"], description = badge_keyword_tasks["description"])

#
# @receiver(post_save, sender=User)
# def save_profile(sender, instance, **kwargs):
#     instance.profile.save()

@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        if instance.access_key == "teacher":
            instance.groups.add(Group.objects.get(name='teacher'))
        else:
            instance.groups.add(Group.objects.get(name='student'))


from flask import session, request
from bson import ObjectId
from website import api_key, users, carts, reviews, models, photos
from website.settings import DIST_OFFSET
import json, urllib, urllib2, re

def base_context():
    context = {}
    context['API_KEY'] = api_key
    context['user'] = None

    if 'username' in session:
        context['user'] = users.find_one(username=session['username'])

    return context

def serialize(obj):
    for k in obj:
        try:
            json.dumps(obj[k])

        except TypeError:
            if type(obj) == dict:
                if type(obj[k]) == dict:
                    serialize(obj[k])
                else:
                    obj[k] = str(obj[k])

            elif type(obj) == list:
                serialize(k)

            else:
                obj = str(obj)

# Borrowed from online to create a unique list
def unique_objs(seq):
    seen = set()
    seen_add = seen.add
    return [x for x in seq if x.get_id() not in seen and not seen_add(x.get_id())]

# Get carts near a certain location
def get_carts_near(address, offset, number, search_object={}):
    # Geocode an address using a google maps api
    data = urllib2.urlopen('http://maps.googleapis.com/maps/api/geocode/json?api_key%s&sensor=false&address=%s' % (api_key, urllib.quote(address)))
    data = json.loads(data.read())
    geometry = data['results'][0]['geometry']
    results = []

    # Find all results within certain bounds
    try:
        box = []

        if geometry.has_key('bounds'):
            ne = geometry['bounds']['northeast']
            sw = geometry['bounds']['southwest']

            if ne['lat'] - sw['lat'] > DIST_OFFSET \
                    and ne['lng'] - sw['lng'] > DIST_OFFSET:
                box = [ [sw['lat'], sw['lng']], [ne['lat'], ne['lng']] ]

        if box == []:
            loc = geometry['location']
            box = [ [loc['lat'] - DIST_OFFSET, loc['lng'] - DIST_OFFSET],
                    [loc['lat'] + DIST_OFFSET, loc['lng'] + DIST_OFFSET] ]

        results += carts.within(box, offset, number, **search_object);

    except ValueError:
        pass

    return results

# Search for items using regex find
def search(item_type, offset, number, keywords, location):
    objs = []

    # Change objs depending on item type
    if item_type == 'cart':
        # Get results for each keyword
        for word in keywords:
            if word == '':
                continue

            # Check each text field
            for tfield in carts.text_fields():
                kwd = re.compile(r'(?: |^)' + word + '(?: |$)', re.IGNORECASE)
                search_object = {tfield: kwd}

                if len(objs) == 0:
                    if location != '':
                        objs += get_carts_near(location, offset, number,
                                search_object)

                    else:
                        objs += carts.find(offset, number, **search_object)

            search_object = {'tags': {'$in': [word]}}
            objs += carts.find(offset, number, **search_object)

        # If there are no keywords, use location instead
        if len(objs) == 0 and keywords[0] == '' and len(keywords) == 1:
            objs += get_carts_near(location, offset, number)

    elif item_type == 'review':
        for word in keywords:
            for tfield in reviews.text_fields():
                kwd = re.compile(r'(?: |^)' + word + '(?: |$)', re.IGNORECASE)
                search_object = {tfield: kwd}
                objs += reviews.find(**search_object)

    return unique_objs(objs)

# Searches data
def search_data():
    item_type = request.args.get('item_type', None)
    keywords = urllib.unquote(request.args.get('keywords')).split(' ')
    location = request.args.get('location', '')
    offset = int(request.args.get('offset', 0))
    number = int(request.args.get('number', 20))

    objs = search(item_type, offset, number, keywords, location)
    results = [o._obj for o in objs]

    # Remove incompatible types
    for r in results:
        serialize(r)

    # Return results as an array
    data = {'results': results}
    return json.dumps(data)

# Serves data
def serve_data():
    item_type = request.args.get('item_type', None)
    rargs = request.args.copy()
    kwargs = {}

    # Copy request args into a copy
    for k in rargs.keys():
        if k != 'item_type':
            kwargs[k] = rargs[k]

        if '_id' in k:
            kwargs[k] = ObjectId(rargs[k])

    if item_type == 'cart':
        objs = carts.find(**kwargs)

    else:
        objs = reviews.find(**kwargs)

    results = [o._obj for o in objs]

    # Remove incompatible types
    for r in results:
        serialize(r)

    # Return results as an array
    data = {'results': results}
    return json.dumps(data)

# Get image by id
def serve_image(image_id):
    image = models.fs.get(ObjectId(image_id))
    data = image.read()
    image.close()
    return data

# Default image
def serve_default():
    # serve a default image
    img = photos.find_one(is_default=True)
    return img.read()


from __future__ import unicode_literals
from collections import Counter
from model import utils
from .logic_adapter import LogicAdapter

class MultiLogicAdapter(LogicAdapter):
    """
    MultiLogicAdapter allows ChatterBot to use multiple logic
    adapters. It has methods that allow ChatterBot to add an
    adapter, set the chat bot, and process an input statement
    to get a response.

    MultiLogicAdapter permite bot-ului sa aibe mai multe adaptoare logice
    selectand cel mai bun raspuns
    """

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

        # Adaptorul logic
        self.adapters = []

        # Adaptoare necesare
        # Neaparat NoKnowlegeAdapter
        self.system_adapters = []

    def process(self, statement):
        """
        Se da output ul unor adaptoare logice
        pentru un input
        """
        results = []
        result = None
        max_confidence = -1

        #se parcurg toate adaptoarele
        #se da un raspuns
        #se selecteaza cel mai bun
        for adapter in self.get_adapters():
            if adapter.can_process(statement):
                confidence, output = adapter.process(statement)
                results.append((confidence, output, ))

                if confidence > max_confidence:
                    result = output
                    max_confidence = confidence

        # Daca mai multe adaptoare au acelasi raspuns,
        # probabil e cel mai bun
        if len(results) >= 3:
            statements = [s[1] for s in results]
            count = Counter(statements)
            most_common = count.most_common()
            if most_common[0][1] > 1:
                result = most_common[0][0]
                max_confidence = self.get_greatest_confidence(result, results)

        return max_confidence, result

    def get_greatest_confidence(self, statement, options):
        """
        Trimite cea mai mare valoare de incredere pentru un statement
        ce apare de mai multe ori
        """
        values = []
        for option in options:
            if option[1] == statement:
                values.append(option[0])

        return max(values)

    def get_adapters(self):
        adapters = []
        adapters.extend(self.adapters)
        adapters.extend(self.system_adapters)
        return adapters

    def add_adapter(self, adapter, **kwargs):
        utils.validate_adapter_class(adapter, LogicAdapter)
        adapter = utils.initialize_class(adapter, **kwargs)
        self.adapters.append(adapter)

    def insert_logic_adapter(self, logic_adapter, insert_index, **kwargs):
        utils.validate_adapter_class(logic_adapter, LogicAdapter)

        NewAdapter = utils.import_module(logic_adapter)
        adapter = NewAdapter(**kwargs)

        self.adapters.insert(insert_index, adapter)

    def remove_logic_adapter(self, adapter_name):
        for index, adapter in enumerate(self.adapters):
            if adapter_name == type(adapter).__name__:
                del self.adapters[index]
                return True
        return False

    def set_chatbot(self, chatbot):
        super(MultiLogicAdapter, self).set_chatbot(chatbot)

        for adapter in self.get_adapters():
            adapter.set_chatbot(chatbot)


#!/home/nvidia/Documents/dora-rover/venv/bin/python3

import sensor_msgs.point_cloud2 as pc2
import rospy
from sensor_msgs.msg import PointCloud2, Imu
from geometry_msgs.msg import PoseStamped
import numpy as np
from dora import Node
import time
from scipy.spatial.transform import Rotation as R

import typing
from opentelemetry import trace
from opentelemetry.exporter.jaeger.thrift import JaegerExporter
from opentelemetry.sdk.resources import SERVICE_NAME, Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.trace.propagation.tracecontext import (
    TraceContextTextMapPropagator,
)

def serialize_context(context: dict) -> str:
    output = ""
    for key, value in context.items():
        output += f"{key}:{value};"
    return output

CarrierT = typing.TypeVar("CarrierT")
propagator = TraceContextTextMapPropagator()

trace.set_tracer_provider(
    TracerProvider(resource=Resource.create({SERVICE_NAME: "ndt_pose"}))
)
tracer = trace.get_tracer(__name__)
jaeger_exporter = JaegerExporter(
    agent_host_name="172.17.0.1",
    agent_port=6831,
)
span_processor = BatchSpanProcessor(jaeger_exporter)
trace.get_tracer_provider().add_span_processor(span_processor)

node = Node()
initial_orientation = None
orientation = None

GOAL_LOCATION = np.array([[0, 0, 0], [3, 0, 0], [3, -8, 0]])

def imu_callback(data):

    global initial_orientation
    global orientation

    if initial_orientation is None:
        initial_orientation = R.from_quat(
            [
                data.orientation.x,
                data.orientation.y,
                data.orientation.z,
                data.orientation.w,
            ]
        )
        print(
            f"INITIAL ORIENTATION: {initial_orientation.as_euler('xyz', degrees=True)}"
        )

        abs_goal_location = initial_orientation.apply(GOAL_LOCATION)
        abs_goal_location = abs_goal_location[:, :2]
        node.send_output("gps_waypoints", abs_goal_location.tobytes())

    orientation = [
        data.orientation.x,
        data.orientation.y,
        data.orientation.z,
        data.orientation.w,
    ]

    # node.send_output("imu", orientation.tobytes())

start = time.time()

def pose_callback(data):
    global start
    global initial_orientation
    global orientation
    position = np.array(
        [
            data.pose.position.x,
            data.pose.position.y,
            data.pose.position.z,
        ]
    )
    if initial_orientation is None:
        return None

    position = initial_orientation.apply(position)
    position = np.concatenate([position, orientation])

    if time.time() - start > 1:
        with tracer.start_as_current_span("start") as _span:
            output = {}
            propagator.inject(output)
            metadata = {"open_telemetry_context": serialize_context(output)}
            node.send_output("position", position.tobytes(), metadata)
            start = time.time()

rospy.init_node("listener", anonymous=True)
rospy.Subscriber("mavros/imu/data", Imu, imu_callback)
rospy.Subscriber("current_pose", PoseStamped, pose_callback)

rospy.spin()


import matplotlib.pyplot as plt

from parsare_fisier import data, graf, matrix
from solutie_initiala import *
import networkx as nx
import numpy as np

solutie_delfini = [[1, 35, 4, 41, 15], [2, 27, 28, 42, 55, 23, 32, 26, 8, 18, 29, 10, 37], [45, 3, 11], [9, 60],
                   [5, 12, 25, 52], [14, 56, 57, 58, 49, 7, 40, 6], [20, 31, 48, 43], [13, 34, 17], [46, 24],
                   [21, 38, 59, 53, 22, 44, 16, 51, 39, 19], [36, 30], [61, 33], [47, 50], [54, 62]]

def reprezentare_solutii_finale(solutie):
    legaturi = []
    for comunitate in solutie:
        for nod in comunitate:
            for j in range(len(comunitate)):
                if comunitate[j] != nod and matrix[nod - 1][comunitate[j] - 1] == 1:
                    if [comunitate[j], nod] not in legaturi:
                        legaturi.append([nod, comunitate[j]])
    print(legaturi)
    return legaturi

legatura = reprezentare_solutii_finale(solutie_delfini)

G = nx.Graph(legatura)

nx.draw(G, with_labels=True, font_size=15,
        node_color='blue', node_size=1000)
plt.show()


import cv2
import numpy as np

# Function to get the most prominent color
def get_most_prominent_color(frame):
    pixels = frame.reshape(-1, 3)
    num_clusters = 3  # Number of clusters (colors) to find
    criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 100, 0.2)
    _, labels, centers = cv2.kmeans(pixels.astype(np.float32), num_clusters, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS)
    counts = np.bincount(labels.flatten())
    prominent_color = centers[np.argmax(counts)]
    return prominent_color

# Function to get the color name based on the BGR value
def get_color_name(bgr):
    b, g, r = bgr
    if r > g and r > b:
        return "Red"
    elif g > r and g > b:
        return "Green"
    elif b > r and b > g:
        return "Blue"
    else:
        return "Other"

# Taking input from webcam
vid = cv2.VideoCapture(0)

while True:
    # Capturing the current frame
    _, frame = vid.read()

    # Get the most prominent color
    prominent_color = get_most_prominent_color(frame)

    # Convert BGR to RGB for displaying
    rgb_color = (prominent_color[2], prominent_color[1], prominent_color[0])
    rgb_color = tuple(np.clip(rgb_color, 0, 255))  # Ensure values are within 0-255 range

    # Create a rectangle image filled with the most prominent color
    rect_image = np.zeros_like(frame)
    rect_image[:] = rgb_color

    # Combine the frame and the rectangle image
    combined_frame = cv2.addWeighted(frame, 0.7, rect_image, 0.3, 0)

    # Display the color name and accuracy
    color_name = get_color_name(prominent_color)
    cv2.putText(combined_frame, f"Prominent Color: {color_name}", (10, 40), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 255), 2)

    # Display the frame with the most prominent color
    cv2.imshow("frame", combined_frame)

    # Stop the program when 'q' is pressed
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# Release the video capture and close all windows
vid.release()
cv2.destroyAllWindows()

RGB Color Detection/RGB Color Detection.py


import logging
import os
from typing import Union

import numpy
import spacy
import spacy_lefff
from spacy.language import Language
from spacy_lefff import LefffLemmatizer, POSTagger, Downloader

from melusine.utils.verbitim_transformer import VerbitimTransformer

logger = logging.getLogger(__name__)

@Language.factory('melt_tagger')
def create_melt_tagger(nlp, name: str) -> spacy_lefff.POSTagger:
    """
    Instanciates spacy pipeline component melt_tagger
    The decorator @Language.factory('melt_tagger') informs spacy that this is a nlp pipeline component labeled
    'melt_tagger'
    Parameters
    ----------
    nlp : spacy.lang.fr.Language
    A spacy nlp pipe object
    name : str
    Label of the component

    Returns a POSTagger component
    -------

    """
    return POSTagger()

@Language.factory('lefff_lemmatizer')
def create_french_lemmatizer(nlp, name: str) -> spacy_lefff.LefffLemmatizer :
    """
    Instanciates spacy pipeline component lefff_lemmatizer
    The decorator @Language.factory('lefff_lemmatizer') informs spacy that this is a nlp pipeline component labeled
    'lefff_lemmatizer'
    Parameters
    ----------
    nlp : spacy.lang.fr.Language
    A spacy nlp pipe object
    name : str
    Label of the component

    Returns a LefffLemmatizer component
    -------

    """
    return LefffLemmatizer(after_melt=True, default=True)

class BadConfigurationError(Exception):
    """Exception to raise when a bad configuration was passed to lemmatization engine"""
    pass

class Lemmatizer(VerbitimTransformer):
    """ Lemmatizer component for Socle NLP
        Available engines include : spacy and Lefff
    """

    _AVAILABLE_ENGINES = ['spacy',
                          'Lefff'
                          ]

    _SPACY_ARGS = {'exclude': ['senter', 'ner']}

    def __init__(self,
                 in_col: str,
                 out_col: str,
                 engine: str,
                 engine_conf: str,
                 **kwargs
                 ):
        """
        Initialize a Socle NLP Lemmatizer object

        Parameters
        ----------
        in_col : str
        Input column in pandas.DataFrame
        out_col : str
        Output column in pandas.DataFrame.Will be created if it does not exist
        engine : str
        Lemmatization engine to load. Choices are 'spacy' and 'Lefff'.
        engine_conf : str
        Spacy model to load under the hood. For french, choices are 'fr_core_news_sm', 'fr_core_news_md',
        'fr_core_news_lg'.
        """

        self.in_col = in_col
        self.out_col = out_col
        self.engine = engine
        self.engine_conf = engine_conf
        self.tagger = None

        assert engine in self._AVAILABLE_ENGINES, 'Specified engine is not supported. Available engines are ' \
                                                  'spacy, Lefff'
        try:
            if self.engine == 'spacy':
                assert isinstance(self.engine_conf, str), "You have specified spacy as lemmatization engine but " \
                                                          "failed to provide the spacy model name as str"
                self._SPACY_ARGS['name'] = self.engine_conf
                self.nlp = spacy.load(**self._SPACY_ARGS)

            if self.engine == 'Lefff':
                assert isinstance(self.engine_conf, str), "You have specified lefff as lemmatization engine but " \
                                                          "failed to provide the spacy model name as str"
                self._SPACY_ARGS['name'] = self.engine_conf
                self.nlp = spacy.load(**self._SPACY_ARGS)
                self.nlp.add_pipe('melt_tagger', after='parser')
                self.nlp.add_pipe('lefff_lemmatizer', after='melt_tagger')

        except IOError as SpacyError:
            logger.error(SpacyError)
            raise BadConfigurationError('Incorrect Spacy configuration. Please refer to the tutorial')

        def _get_lemmas(text: numpy.ndarray) -> numpy.ndarray:
            lemmas = numpy.empty(shape=text.shape, dtype='object')
            if self.engine == 'spacy':
                for i, doc in enumerate(self.nlp.pipe(text, **kwargs)):
                    lemmas.put(i, ' '.join([token.lemma_ for token in doc]))
            if self.engine == 'Lefff':
                for i, doc in enumerate(self.nlp.pipe(text, **kwargs)):
                    lemmas.put(i, ' '.join([token._.lefff_lemma for token in doc]))
            return lemmas

        super().__init__(_get_lemmas, None, self.in_col, self.out_col)


from numpy import array, round as np_round
import matplotlib.pyplot as plt
from statistics import mean
import os
import pandas as pd

# MAIN
CSV_FOLDER = os.getcwd() + "/all_data.csv"
HEADERS = pd.read_csv(CSV_FOLDER).columns.to_list()
# date, consumption, lep

USE_ONLY_ONE_YEAR = True

# ARIMA
ARIMA_FOLDER = (os.getcwd() + "/ARIMA_RESULTS")
ARIMA_FOLDER_CHECK = os.path.isdir(ARIMA_FOLDER)

# LSTM
LSTM_FOLDER = (os.getcwd() + "/LSTM_RESULTS")
LSTM_FOLDER_CHECK = os.path.isdir(LSTM_FOLDER)
N_EPOCHS = 8  # Epoch -> one iteration over the entire dataset
BATCH_SIZE = 24  # Batch_size -> divide dataset and pass into neural network.
TIMESTAMP = 24  # Parse and divide data into size of 24 hour of data.

# PROPHET
PROPHET_FOLDER = (os.getcwd() + "/PROPHET_RESULTS")
PROPHET_FOLDER_CHECK = os.path.isdir(PROPHET_FOLDER)

def prepare_tabulate(**kwargs):
    tabulate_txt = []
    real_errors = []
    lstm_errors = []
    real_cons = kwargs["real_cons"].to_list()
    real_pred_list = kwargs["real_pred_list"].to_list()

    for i in range(24):
        if kwargs['model_name'] == 'ARIMA':
            new_pred = round(kwargs["new_pred_cons"][i], 2)
        if kwargs['model_name'] == 'LSTM':
            new_pred = np_round(kwargs["new_pred_cons"][i][0], 2)
        if kwargs['model_name'] == 'PROPHET':
            new_pred = np_round(kwargs["new_pred_cons"][i], 2)

        real_pred = round(real_pred_list[i], 2)
        expected = round(real_cons[i], 2)

        # Calculate real and expected error
        error_lstm = round((abs(new_pred - expected) / expected) * 100.0, 2)
        error_real = round((abs(real_pred - expected) / expected) * 100.0, 2)
        tabulate_txt.append([expected, round(new_pred, 2), real_pred, error_lstm, error_real])
        lstm_errors.append(error_lstm)
        real_errors.append(error_real)

    # Prepare data for tabulate and txt file
    tabulate_txt.append(["-"*12, "-"*12, "-"*12, "-"*12, "-"*12])
    tabulate_txt.append(['Average Errors', '', '', round(mean(lstm_errors), 3), round(mean(real_errors),3)])
    tabulate_txt.append(['R^2', '', '', "%.3f" % kwargs["r2_score"], "%.3f" % kwargs["r2_real"]])
    tabulate_txt.append(["-"*12, "-"*12, "-"*12, "-"*12, "-"*12])
    tabulate_txt.append(['Time in sec.', kwargs["total_time"], ""])
    tabulate_txt.append(['Start Date', kwargs["first_date"], '', '', ''])
    tabulate_txt.append(['End Date', kwargs["end_date"], '', '', ''])
    tabulate_txt.append(['Predicting', kwargs["predicted_date"], '', '', ''])
    tabulate_txt.append(["-"*12, "-"*12, "-"*12, "-"*12, "-"*12])

    if kwargs['model_name'] == 'ARIMA':
        tabulate_txt.append(['ARIMA Order', kwargs["order"], '', '', ''])
        tabulate_txt.append(["-"*12, "-"*12, "-"*12, "-"*12, "-"*12])

    if kwargs['model_name'] == 'LSTM':
        tabulate_txt.append(['Epoch Count', kwargs["N_EPOCHS"], '', '', ''])
        tabulate_txt.append(['Batch Size', kwargs["BATCH_SIZE"], '', '', ''])
        tabulate_txt.append(['Timestamp', kwargs["TIMESTAMP"], '', '', ''])
        tabulate_txt.append(["-"*12, "-"*12, "-"*12, "-"*12, "-"*12])

    return tabulate_txt

# Plot graph with given data
def plotter(
    list_24_hours,
    real_24_data,
    real_24_predicted_data,
    label_real,
    predicted_24_data,
    label_predict,
    xlabel,
    ylabel,
    title,
    label_real_predict
    ):

    main_plot = plt.figure(1, figsize=(30, 30))
    plt.rcParams['font.size'] = '25'

    # Real data
    plt.plot(
        list_24_hours,
        real_24_data,
        color='black',
        linewidth=3,
        label=label_real
    )

    # Prediction
    plt.plot(
        list_24_hours,
        predicted_24_data,
        color='red',
        linewidth=3,
        label=label_predict
    )

    # Real Predicted Data
    plt.plot(
        list_24_hours,
        real_24_predicted_data,
        color='green',
        linewidth=3,
        label=label_real_predict,
    )

    plt.gcf().autofmt_xdate()
    plt.xticks(list_24_hours)
    plt.legend(frameon=True)
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
    plt.title(title)
    plt.grid()
    plt.show()

    return main_plot

def data_split(sequence, TIMESTAMP):
    X = []
    y = []
    for i in range(len(sequence)):
        end_ix = i + TIMESTAMP
        if end_ix > len(sequence)-1:
            break
        # i to end_ix as input
        # end_ix as target output
        seq_x, seq_y = sequence[i:end_ix], sequence[end_ix]
        X.append(seq_x)
        y.append(seq_y)
    return array(X), array(y)


import numpy as np
import torch
from torch import nn
import torchvision
import torch.nn.functional as F

from src.resnet import resnet9
from src.transformer import TransformerPooling
from src.vmz import r2plus1d_18, r2plus1d_34

class Normalize(nn.Module):
    def __init__(self, power=2):
        super(Normalize, self).__init__()
        self.power = power

    def forward(self, x):
        norm = x.pow(self.power).sum(1, keepdim=True).pow(1. / self.power)
        out = x.div(norm)
        return out

class TransposeSqueeze(nn.Module):
    def __init__(self, fdim, tdim):
        super(TransposeSqueeze, self).__init__()
        self.fdim = fdim
        self.tdim = tdim

    def forward(self, x):
        return x.view(-1, self.fdim, self.tdim).transpose(-1,-2)

class Flatten(nn.Module):
    """A shape adaptation layer to patch certain networks."""
    def __init__(self):
        super(Flatten, self).__init__()

    def forward(self, x):
        return x.view(x.shape[0], -1)

class Unsqueeze(nn.Module):
    """A shape adaptation layer to patch certain networks."""
    def __init__(self):
        super(Unsqueeze, self).__init__()

    def forward(self, x):
        return x.unsqueeze(-1)

class Identity(nn.Module):
    def __init__(self):
        super(Identity, self).__init__()

    def forward(self, x):
        return x

def random_weight_init(model):
    for m in model.modules():
        if isinstance(m, nn.Conv3d):
            m.weight = nn.init.kaiming_normal_(m.weight, mode='fan_out')
            if m.bias is not None:
                m.bias.data.zero_()
        elif isinstance(m, nn.BatchNorm3d):
            m.weight.data.fill_(1)
            m.bias.data.zero_()

class MLP(nn.Module):
    def __init__(self, n_input, n_classes, n_hidden=512, p=0.3):
        super(MLP, self).__init__()
        self.n_input = n_input
        self.n_classes = n_classes
        self.n_hidden = n_hidden
        if n_hidden is None:
            # use linear classifier
            self.block_forward = nn.Sequential(
                Flatten(),
                nn.Dropout(p=p),
                nn.Linear(n_input, n_classes, bias=True)
            )
        else:
            # use simple MLP classifier
            self.block_forward = nn.Sequential(
                Flatten(),
                nn.Dropout(p=p),
                nn.Linear(n_input, n_hidden, bias=False),
                Unsqueeze(),
                nn.BatchNorm1d(n_hidden),
                Flatten(),
                nn.ReLU(inplace=True),
                nn.Dropout(p=p),
                nn.Linear(n_hidden, n_classes, bias=True)
            )

    def forward(self, x):
        return self.block_forward(x)

def get_video_feature_extractor(
    vid_base_arch='r2plus1d_18',
    pretrained=False,
    duration=1,
    pre_pool=False,
):
    if vid_base_arch == 'r2plus1d_18':
        model = r2plus1d_18(pretrained=pretrained, larger_last=False)
        if not pretrained:
            print("Randomy initializing models")
            random_weight_init(model)
        if pre_pool:
            model.avgpool = nn.Identity()
        else:
            model.avgpool = nn.AdaptiveAvgPool3d((duration, 1, 1))
    elif vid_base_arch == 'r2plus1d_34':
        model = r2plus1d_34(pretrained=pretrained)
        if not pretrained:
            print("Randomy initializing models")
            random_weight_init(model)
        if pre_pool:
            model.avgpool = nn.Identity()
        else:
            model.avgpool = nn.AdaptiveAvgPool3d((duration, 1, 1))
    model.fc = Identity()
    return model

def get_audio_feature_extractor(
    aud_base_arch='resnet18',
    pretrained=False,
    duration=1
):
    assert(aud_base_arch in ['resnet9', 'resnet18'])
    if aud_base_arch == 'resnet18':
        model = torchvision.models.__dict__[aud_base_arch](
            pretrained=pretrained)
        model.conv1 = torch.nn.Conv2d(
            1,
            64,
            kernel_size=(7, 7),
            stride=(2, 2),
            padding=(3, 3),
            bias=False
        )
        model.fc = Identity()
        return model
    elif aud_base_arch == 'resnet9':
        print('resnet9, duration:', duration)
        model = resnet9(pretrained=False,progress=False)

        model.conv1 = torch.nn.Conv2d(
            1,
            64,
            kernel_size=(7, 7),
            stride=(2, 2),
            padding=(3, 3),
            bias=False
        )
        model.avgpool = nn.AdaptiveAvgPool2d((1,duration))
        return model

class VideoBaseNetwork(nn.Module):
    def __init__(
        self,
        vid_base_arch='r2plus1d_18',
        pretrained=False,
        norm_feat=False,
        duration=1,
        pre_pool=False,
    ):
        super(VideoBaseNetwork, self).__init__()
        self.base = get_video_feature_extractor(
            vid_base_arch,
            pretrained=pretrained,
            duration=duration,
            pre_pool=pre_pool,
        )
        self.norm_feat = norm_feat

    def forward(self, x):
        x = self.base(x).squeeze()
        if self.norm_feat:
            x = F.normalize(x, p=2, dim=1)
        return x

class AudioBaseNetwork(nn.Module):
    def __init__(
        self,
        aud_base_arch='resnet9',
        pretrained=False,
        norm_feat=False,
        duration=1
    ):
        super(AudioBaseNetwork, self).__init__()
        self.base = get_audio_feature_extractor(
            aud_base_arch,
            pretrained=pretrained,
            duration=duration
        )
        self.norm_feat = norm_feat

    def forward(self, x):
        x = self.base(x).squeeze()
        if self.norm_feat:
            x = F.normalize(x, p=2, dim=1)
        return x

class GDT(nn.Module):
    def __init__(
        self,
        vid_base_arch='r2plus1d_18',
        aud_base_arch='resnet9',
        pretrained=False,
        norm_feat=True,
        use_mlp=False,
        num_classes=256,
    ):
        super(GDT, self).__init__()
        print('Using GDT model')

        encoder_dim = 512
        encoder_dim_a = 512
        n_hidden = 512

        # Save proprties
        self.use_mlp = use_mlp
        self.norm_feat = norm_feat
        self.encoder_dim = encoder_dim

        self.video_network = VideoBaseNetwork(
            vid_base_arch,
            pretrained=pretrained
        )
        self.audio_network = AudioBaseNetwork(
            aud_base_arch,
            pretrained=pretrained
        )

        if use_mlp:
            print("Using MLP projection layer")
            self.mlp_v = MLP(
                encoder_dim, num_classes, n_hidden=n_hidden)
            self.mlp_a = MLP(encoder_dim_a, num_classes)
        else:
            print("Using Linear Layer")
            self.mlp_v = nn.Linear(encoder_dim, num_classes)
            self.mlp_a = nn.Linear(encoder_dim_a, num_classes)

    def forward(self, img, spec, whichhead=0):
        img_features = self.video_network(img).squeeze()
        aud_features = self.audio_network(spec).squeeze()

        if len(aud_features.shape) == 1:
            aud_features = aud_features.unsqueeze(0)
        if len(img_features.shape) == 1:
            img_features = img_features.unsqueeze(0)

        nce_img_features = self.mlp_v(img_features)
        nce_aud_features = self.mlp_a(aud_features)
        if self.norm_feat:
            nce_img_features = F.normalize(
                nce_img_features, p=2, dim=1)
            nce_aud_features = F.normalize(
                nce_aud_features, p=2, dim=1)
        return nce_img_features, nce_aud_features

class Stica_TransformerFMCrop(nn.Module):
    def __init__(
        self,
        vid_base_arch='r2plus1d_18',
        aud_base_arch='resnet9',
        pretrained=False,
        norm_feat=True,
        use_mlp=False,
        num_classes=256,
        args=None,
    ):
        super(Stica_TransformerFMCrop, self).__init__()
        print('Using Stica-Transformer model that enables featuremap returns')

        # Save proprties
        self.use_mlp = use_mlp
        self.norm_feat = norm_feat
        encoder_dim_a = 512
        encoder_dim = 512
        self.encoder_dim = encoder_dim
        self.n_hidden = 512
        self.dp = args.dp if args is not None else 0.0
        self.num_layer = args.num_layer if args is not None else 2
        self.num_head = args.num_head if args is not None else 4
        self.positional_emb = args.positional_emb if args else False
        self.qkv_mha = args.qkv_mha if args else False

        if args.num_sec == 1:
            self.duration = 4
            aud_duration = 4
        elif args.num_sec == 2:
            self.duration = 8
            aud_duration = 7
        elif args.num_sec == 3:
            self.duration = 12
            aud_duration=10
        elif args.num_sec == 4:
            self.duration = 15
            aud_duration = 13
        else:
            assert(0)

        # Backbone
        self.video_network = VideoBaseNetwork(
            vid_base_arch,
            pretrained=pretrained,
            duration=self.duration,
            pre_pool=True,
        )
        self.audio_network = AudioBaseNetwork(
            aud_base_arch,
            pretrained=pretrained,
            duration=1
        )

        # Aggregation module
        if args.num_layer > 0:
            print('Using Transformer Pooling')
            transformer = TransformerPooling(
                emb_dim=encoder_dim,
                hidden_dim=encoder_dim,
                num_layer=self.num_layer,
                dp=self.dp,
                num_head=self.num_head,
                positional_emb=self.positional_emb,
                qkv_mha=self.qkv_mha,
            )
            self.video_pooling = nn.Sequential(
                nn.AdaptiveAvgPool3d((args.transformer_time_dim, 1, 1)),
                TransposeSqueeze(fdim=self.n_hidden, tdim=self.duration),
                transformer
            )
        else:
            print('Using Average Pooling')
            self.video_pooling = nn.AdaptiveAvgPool3d((1, 1, 1))

        # FNN module
        if use_mlp:
            print("Using MLP projection layer")
            self.mlp_v = MLP(encoder_dim, num_classes, n_hidden=self.n_hidden)
            self.mlp_a = MLP(encoder_dim_a, num_classes)
        else:
            print("Using Linear Layer")
            self.mlp_v = nn.Linear(encoder_dim, num_classes)
            self.mlp_a = nn.Linear(encoder_dim_a, num_classes)

    def feat2nce(self, img):
        img = self.video_pooling(img).squeeze()
        img = img.view(-1, self.encoder_dim)
        img = self.mlp_v(img)
        img = F.normalize(img, p=2, dim=1)
        return img

    def forward(self, img, spec, params=None):
        ## B: batch size
        ## N: num of chunk (num of sec)
        ## C: num of channel
        ## L: num of input frames for video per chunk
        ## H: height
        ## W: width
        ## T: num of input windows for audio per chunk
        ## S: num of bank (spectrogram)

        # Run backbone architecture
        # B C LN H W => B H V
        img = self.video_network(img).squeeze()
        # B C S TN => B H A
        spec = self.audio_network(spec).squeeze()

        # Feature Cropping Layer
        if params is not None:
            # params = [ space , crops]
            # space = [[ largecrop_locations], [small_croplocations]
            # location = [xmin,xmax,ymin,ymax] or [tmin,tmax]
            crop_nces = [[],[]]
            tcrop_nces = [[],[]]
            s_large_crops, s_small_crops = len(params[0][0]),len(params[0][1])
            t_large_crops, t_small_crops = len(params[1][0]),len(params[1][1])
            for i in range(s_large_crops):
                xmin, xmax, ymin, ymax = params[0][0][i]
                crop_nces[0].append(self.feat2nce(img[..., xmin:xmax,ymin:ymax]))
                for j in range(s_small_crops):
                    xmin, xmax, ymin, ymax = params[0][1][j]
                    crop_nces[1].append(self.feat2nce(img[..., xmin:xmax,ymin:ymax]))
            for ti in range(t_large_crops):
                tmin,tmax= params[1][0][ti]
                tcrop_nces[0].append(self.feat2nce(img[:,:, tmin:tmax, :,:]))
                for tj in range(t_small_crops):
                    tmin,tmax= params[1][1][tj]
                    tcrop_nces[1].append(self.feat2nce(img[:,:, tmin:tmax, :,:]))

        # Temporal Pooling: B V H => B H
        img = self.video_pooling(img)

        # Reshape Layer
        if len(spec.shape) == 1:
            spec = spec.unsqueeze(0)
        img = img.view(-1, self.encoder_dim)

        # MLP projection layer
        img = self.mlp_v(img)
        spec = self.mlp_a(spec)

        # Normalization layer
        if self.norm_feat:
            img = F.normalize(img, p=2, dim=1)
            spec = F.normalize(spec, p=2, dim=1)

        return (img, [crop_nces, tcrop_nces], spec)

class Text_Encoder(nn.Module):
    def __init__(
        self,
        embd_dim=256,
        token_to_word_path='datasets/data/dict.npy',
        num_embeddings=66250,
        word_embedding_dim=300,
        word2vec_path='datasets/data/word2vec.pth',
        max_words=16,
        output_dim=2048
    ):
        super(Text_Encoder, self).__init__()
        if word2vec_path:
            self.word_embd = nn.Embedding.from_pretrained(torch.load(word2vec_path))
        else:
            self.word_embd = nn.Embedding(num_embeddings, word_embedding_dim)
        self.fc1 = nn.Linear(word_embedding_dim, output_dim)
        self.word_to_token = {}
        self.max_words = max_words
        token_to_word = np.load(token_to_word_path)
        for i, t in enumerate(token_to_word):
            self.word_to_token[t] = i + 1

    def _zero_pad_tensor_token(self, tensor, size):
        if len(tensor) >= size:
            return tensor[:size]
        else:
            zero = torch.zeros(size - len(tensor)).long()
            return torch.cat((tensor, zero), dim=0)

    def is_cuda(self):
        return self.fc1.bias.is_cuda

    def _split_text(self, sentence):
        w = re.findall(r"[\w']+", str(sentence))
        return w

    def _words_to_token(self, words):
        words = [self.word_to_token[word] for word in words if word in self.word_to_token]
        if words:
            we = self._zero_pad_tensor_token(torch.LongTensor(words), self.max_words)
            return we
        else:
            return torch.zeros(self.max_words).long()

    def words_to_ids(self, x):
        split_x = [self._words_to_token(self._split_text(sent)) for sent in x]
        return torch.stack(split_x, dim=0)

    def forward(self, x, raw_text=False):
        if raw_text:
            x = self.words_to_ids(x)
        with torch.no_grad():
            x = self.word_embd(x)
        x = F.relu(self.fc1(x), inplace=True)
        x = torch.max(x, dim=1)[0]
        return x

class TextVid_GDT(nn.Module):
    def __init__(
        self,
        vid_base_arch='r2plus1d_18',
        text_base_arch='word2vec',
        pretrained=False,
        norm_feat=True,
        use_mlp=True,
        num_classes=256,
    ):
        super(TextVid_GDT, self).__init__()
        print('Using GDT video-text model')

        encoder_dim = 512
        n_hidden = 512

        # Save proprties
        self.use_mlp = use_mlp
        self.norm_feat = norm_feat
        self.encoder_dim = encoder_dim

        # Backbone architectures
        self.video_network = VideoBaseNetwork(
            vid_base_arch,
            pretrained=pretrained
        )
        self.text_network = Text_Encoder()

        # Projection Layer
        if use_mlp:
            print("Using MLP projection layer")
            self.mlp_v = MLP(encoder_dim, num_classes)
            self.mlp_t = MLP(2048, num_classes)
        else:
            print("Using Linear Layer")
            self.mlp_v = nn.Linear(512, num_classes)
            self.mlp_t = nn.Linear(2048, num_classes)

    def forward(self, img, text, whichhead=0):
        img_features = self.video_network(img).squeeze()
        text_features = self.text_network(text).squeeze()

        if len(text_features.shape) == 1:
            text_features = text_features.unsqueeze(0)
        if len(img_features.shape) == 1:
            img_features = img_features.unsqueeze(0)

        nce_img_features = self.mlp_v(img_features)
        nce_text_features = self.mlp_t(text_features)
        if self.norm_feat:
            nce_img_features = F.normalize(
                nce_img_features, p=2, dim=1)
            nce_text_features = F.normalize(
                nce_text_features, p=2, dim=1)
        return (
            nce_img_features, nce_text_features,
        )

def load_model(
    model_type='stica',
    vid_base_arch='r2plus1d_18',
    aud_base_arch='resnet9',
    pretrained=False,
    norm_feat=True,
    use_mlp=False,
    num_classes=256,
    args=None,
):
    # Cross-modal GDT
    if model_type == 'stica':
        print('Using Stica-Transformer FM CROP')
        model = Stica_TransformerFMCrop(
            vid_base_arch=vid_base_arch,
            aud_base_arch=aud_base_arch,
            pretrained=pretrained,
            norm_feat=norm_feat,
            use_mlp=use_mlp,
            num_classes=num_classes,
            args=args
        )
    elif model_type == 'vid_text_gdt':
        print('Using Video-Text GDT')
        model = TextVid_GDT(
            vid_base_arch=vid_base_arch,
            pretrained=pretrained,
            norm_feat=norm_feat,
            use_mlp=use_mlp,
            num_classes=num_classes,
        )
    else:
        print('Using Audio-Visual GDT')
        model = GDT(
            vid_base_arch=vid_base_arch,
            aud_base_arch=aud_base_arch,
            pretrained=pretrained,
            norm_feat=norm_feat,
            use_mlp=use_mlp,
            num_classes=num_classes,
        )
    return model


# some_file.py
import sys
# insert at 1, 0 is the script path (or '' in REPL)
sys.path.insert(1, './backend')
import ner
from flask_cors import CORS
from random import *
from flask_restful import Resource, Api
from flask import Flask, jsonify, request

app = Flask(__name__,
            static_folder="./dist/static",
            template_folder="./dist")

api = Api(app)
cors = CORS(app, resources={r"/api/*": {"origins": "*"}})

class Status(Resource):
     def get(self):
         try:
            return {'data': 'Api running'}
         except(error):
            return {'data': error}

class PredictNerOfSentence(Resource):
    def __init__(self):
        super().__init__()
        self.ner_result = ''

    def get(self):
        # self.ner_result = ner.predictNerOfSentence()
        return jsonify({'data': self.ner_result})

    def post(self):
        json_data = request.get_json(force=True)
        sentence = json_data["text"]
        self.ner_result = ner.predictNerOfSentence(sentence)
        return jsonify({'data': self.ner_result})

class PredictByDate(Resource):
    def __init__(self):
        super().__init__()
        self.ner_result_bydate = ''
        # self.ner_by_date = ner.predictByDate()

    def get(self):
        tgl = request.args.get('tgl')
        limit = request.args.get('limit')
        tgl_split = tgl.split('-')
        self.ner_result_bydate = ner.predictByDate(
            tahun=tgl_split[0],
            bulan=tgl_split[1],
            tgl=tgl_split[2],
            limit=limit
        )
        return jsonify({
            'data': self.ner_result_bydate
        })

api.add_resource(PredictNerOfSentence, '/api/predict')

api.add_resource(PredictByDate, '/api/predict-by-date')

api.add_resource(Status, '/')

if __name__ == '__main__':
    app.run()

# @app.route('/api/random')
# def random_number():
#     response = {
#         'randomNumber': randint(1, 100)
#     }
#     return jsonify(response)

# @app.route('/', defaults={'path': ''})
# @app.route('/<path:path>')
# def catch_all(path):
#     if app.debug:
#         return requests.get('http://localhost:8080/{}'.format(path)).text
#     return render_template("index.html")


'''takes two  command line arguments, the .json filename of a tagl_count file and an output file.
   creates a string with no. of occurrence as in the count
'''

import json, sys, re, math

if len(sys.argv) < 3:
  print('not enough arguments')

with open(sys.argv[1]) as file:
  data = json.load(file)

outstr = ''

for key in data.keys():
    key1 = re.sub(r'[ -/_]+','_',key)
    for i in range(int(math.log(data[key]))):
        outstr += key1 + ' '

with open(sys.argv[2], 'w') as file:
  file.write(outstr)