예제 #1
0
def content_based_filtering():
    conn = Database.Mysql()
    mycursor = conn.cursor(buffered=True)
    mycursor.execute("SELECT * FROM products")
    result = mycursor.fetchall()
    file = open('engines/csv/content_based_filtering_data.csv', "w+")
    with file:
        for item in tqdm(result):
            mycursor.execute(
                "SELECT * FROM products WHERE brand = %s AND type = %s AND category = %s",
                (str(item[2]), str(item[3]), str(item[4])))
            similarItems = mycursor.fetchall()
            similarItems.pop(0)
            if len(similarItems) > 20:
                for similarItem in similarItems:
                    count = 0
                    words = similarItem[1].split()
                    for word in words:
                        if word in item[1]:
                            count += 1
                    if count < 3:
                        similarItems.remove(similarItem)
            products = []
            for product in similarItems:
                products.append(product[0])

            fnames = ['product', 'recommendations']
            writer = csv.DictWriter(file, fieldnames=fnames)
            linedic = {
                'product': item[0],
                'recommendations': json.dumps(products)
            }
            writer.writerow(linedic)
    file.close()
예제 #2
0
 def connect(self):
     try:
         self.glpi = glpi()
         self.connections['glpi'] = True
     except:
         pass
     try:
         self.zabbix = zabbix()
         self.connections['zabbix'] = True
     except:
         pass
     try:
         self.database = Database()
         self.connections['database'] = True
     except:
         pass
예제 #3
0
class Filters:
    """
    Implementation of all available filters.

    Attributes:
        products (list): all stored products
        product (Query instance): filter constructor
    """
    def __init__(self):
        self.products = Database().products
        self.product = Query()

    def get_product_by_id(self, product_id):
        """Return products matching the provided ID.
        
        Args:
            product_id (int): product ID

        Returns:
            filtered (list): list containing all matching products
        """
        filtered = self.products.search(self.product.id == product_id)
        return filtered

    def get_product_by_name(self, name):
        """Return products matching the provided name.
        
        Args:
            name (str): product name

        Returns:
            filtered (list): list containing all matching products
        """
        name_filter = self.product.nome.search(name, flags=re.IGNORECASE)
        filtered = self.products.search(name_filter)
        return filtered

    def get_products_by_price(self, min_price=None, max_price=None):
        """Return products matching the given price range or value.
        
        Args:
            min_price (int): minimum price to match
            max_price (int): maximum price to match

        Returns:
            filtered (list): list containing all matching products
        """
        price = self.product.preco
        if not max_price:
            filtered = self.products.search(price >= min_price)
        elif not min_price:
            filtered = self.products.search(price <= max_price)
        else:
            filtered = self.products.search((price <= max_price)
                                            & (price >= min_price))
        return filtered

    def get_all_products(self):
        """Return all stored products"""
        return self.products.all()
예제 #4
0
def collaborativefiltering():
    conn = Database.Mysql()
    mycursor = conn.cursor()
    mycursor.execute("SELECT * FROM profiles_previously_viewed")
    result = mycursor.fetchall()
    file = open('engines/csv/collaboritive_filtering_data.csv', "w+")
    viewedPerProfile = {}

    for item in result:
        if item[0] in viewedPerProfile:
            viewedPerProfile[item[0]].append(item[1])
        else:
            viewedPerProfile[item[0]] = [item[1]]

    for key in list(viewedPerProfile):
        value = viewedPerProfile[key]
        if len(value) <= 1:
            del viewedPerProfile[key]
    with file:
        for item in tqdm(viewedPerProfile):
            key = item
            values = viewedPerProfile[item]
            recommendations = []
            counter = 0
            for compare in viewedPerProfile:
                compareValues = viewedPerProfile[compare]
                if len(list(set(compareValues) - set(values))) != 0:
                    for value in values:
                        for compareValue in compareValues:
                            if value == compareValue:
                                counter += 1
                            else:
                                continue
                if counter > 2:
                    recommendations = values + compareValues

            fnames = ['profid', 'recommendations']
            writer = csv.DictWriter(file, fieldnames=fnames)
            linedic = {
                'profid': key,
                'recommendations': json.dumps(recommendations)
            }
            writer.writerow(linedic)
예제 #5
0
def runApplication():
    running = True
    conn = Database.Mysql()
    mycursor = conn.cursor(buffered=True)
    while running:
        task = int(
            input('Welkom bij de recommendations engine van Fabio! \n'
                  'Selecteer om een opdracht uit te voeren: \n'
                  '1: Maak de recommendation data klaar \n'
                  '2: Doe een recommendation voor een profiel \n'
                  '3" Doe een recommendation voor een product \n'
                  '4: Sluit het programma af\n'))

        if task == 1:
            initialize_data()
        elif task == 2:
            profId = input('Voer een profiel id in: \n')
            mycursor.execute(
                "SELECT * FROM recommendations_collaboritive WHERE '%s'" %
                profId)
            result = mycursor.fetchone()
            products = json.loads(result[1])
            for item in products:
                mycursor.execute("SELECT * FROM products WHERE id = '%s'" %
                                 item)
                productInfo = mycursor.fetchone()
                print(productInfo)
        elif task == 3:
            productId = input('Voer een product id in: \n')
            mycursor.execute(
                "SELECT * FROM recommendations_content_based WHERE '%s'" %
                productId)
            result = mycursor.fetchone()
            products = json.loads(result[1])
            for item in products:
                mycursor.execute("SELECT * FROM products WHERE id = '%s'" %
                                 item)
                productInfo = mycursor.fetchone()
                print(productInfo)

        else:
            running = False
예제 #6
0
from SimpleWebSocketServer import SimpleWebSocketServer
import util.logging as log
from database.connection import Database
import manager


log.line("#####################")
log.line("#                   #")
log.line("#   Scuti  Server   #")
log.line("#                   #")
log.line("#####################")


scuti.clients = {}
try:
    scuti.db = Database("localhost", "root", "", "scuti")
    log.info("Connected to database!")
    # Room
    manager.room.load_rooms()
    log.info("Room manager loaded!")
    # Users
    manager.user.load_users()
    log.info("User manager loaded!")
except Exception as e:
    log.error(str(e))
    exit()


log.line()
log.info("Server online!")
server = SimpleWebSocketServer("", 3000, Server)
예제 #7
0
 def __init__(self):
     self.products = Database().products
     self.product = Query()
예제 #8
0
class BeltisBot:
    def __init__(self, dispatcher):
        self.dispatcher = dispatcher
        self.bot_name = "Beltis TI bot"
        self.bot_description = "*AINDA EM PRODUÇÃO*"
        self.bot = bot
        self.get_version()
        self.connections = {"glpi": False, "zabbix": False, "database": False}
        self.connect()
        self.validation = validation(self)
        self.run_bot()

    def get_version(self):
        path = os.path.join(
            os.path.split(os.path.dirname(__file__))[0], 'version')
        version = open(path, 'r').read()
        self.version = version

    def connect(self):
        try:
            self.glpi = glpi()
            self.connections['glpi'] = True
        except:
            pass
        try:
            self.zabbix = zabbix()
            self.connections['zabbix'] = True
        except:
            pass
        try:
            self.database = Database()
            self.connections['database'] = True
        except:
            pass

    def run_bot(self):
        @self.dispatcher.message_handler(commands=['start', 'help'])
        async def send_welcome(message: types.Message):
            user = self.database.get_user(message)
            help_message = f"""*{self.bot_name}.*
 _{self.bot_description}_

 Available commands:
  - /help: Retorna a lista de comandos habilitados;
  - /getid: Retorna seu id de usuário do telegram;
  - /getgroup: Retorna a id do grupo;
"""
            if user:
                help_message += """   - /ticket ID: Retorna as informações sobre um ticket específico;
   - /validate: Validates bot information and session connections"""

            await message.reply(help_message)

        @self.dispatcher.message_handler(commands=['getid'])
        async def return_user_id(message: types.Message):
            await bot.send_chat_action(message.chat.id, "typing")
            msg = extract_user_object(message)
            await message.reply(msg.telegram_id)

        @self.dispatcher.message_handler(commands=['getgroup'])
        async def return_user_id(message: types.Message):
            await bot.send_chat_action(message.chat.id, "typing")
            chat = extract_chat_object(message)
            if chat.chat_type != "group":
                await message.reply(
                    "Por favor, execute este comando em um grupo para que a informação possa ser retornada corretamente."
                )
            else:
                await message.reply(chat.chat_id)

        @self.dispatcher.message_handler(commands=['ticket'])
        async def ticket_handler(message: types.Message):
            await bot.send_chat_action(message.chat.id, "typing")
            if (len(message.text) > 7):
                ticket_id = message.text.split(' ')[1]
                ticket_status = self.glpi.getTicket(ticket_id)
                await message.reply(ticket_status)
            else:
                chat = extract_chat_object(message)
                user = extract_user_object(message)
                response = await self.validation.ticket_creation_process(
                    user.telegram_id, chat.chat_id)
                await message.reply(response)

        @self.dispatcher.message_handler(commands=['glpi'])
        async def registrate_glpi_user(message: types.Message):
            await bot.send_chat_action(message.chat.id, "typing")
            if self.connections['database'] == False:
                await message.reply(
                    "Bot em manutenção. Por favor, contate os administradores."
                )
                return
            else:
                user = self.database.get_user(message)
                if user.glpi_user:
                    await message.reply("Usuário já cadastrado")
                else:
                    chat = extract_chat_object(message)
                    user = extract_user_object(message)
                    response = await self.validation.glpi_registration_process(
                        user.telegram_id, chat.chat_id)
                    await message.reply(response)

        @self.dispatcher.message_handler(commands=['zhosts'])
        async def zabbix_hosts(message: types.Message):
            await bot.send_chat_action(message.chat.id, "typing")
            response = self.zabbix.getHosts()
            await message.reply(response)

        @self.dispatcher.message_handler(commands=['zhost'])
        async def zabbix_host(message: types.Message):
            await bot.send_chat_action(message.chat.id, "typing")
            response = self.zabbix.getHost()
            await message.reply(response)

        @self.dispatcher.message_handler(commands=['info'])
        async def testMessage(message: types.Message):
            user = self.database.get_user(message)
            print(user, message)
            await message.reply(message)

        @self.dispatcher.message_handler(commands=['create_poll'])
        async def teste(message: types.Message):
            msg = await bot.send_poll(
                1021953062,
                'Qual a boa?',
                ['Supimpa', 'Tranquilo', 'Só desgraça', 'Irineu'],
                disable_notification=None)
            print(msg)

        @self.dispatcher.message_handler(commands=['get_poll'])
        async def teste(message: types.Message):
            msg = await bot.stop_poll(1021953062, 3941)
            print(msg)
            await message.reply(msg)

        @self.dispatcher.message_handler(commands=['validate'])
        async def validate_glpi_api(message: types.Message):
            await bot.send_chat_action(message.chat.id, "typing")
            if self.connections['database'] == False:
                await message.reply(
                    "Bot em manutenção. Por favor, contate os administradores."
                )
                return
            user = self.database.get_user(message)
            if user.is_admin == False or user == False:
                await message.reply("Comando não autorizado")
            else:
                msg = f">- *BOT:*\n    _{self.bot_name}_  `{self.version}`"
                msg += f"\n\n>- *Database:*\n    Status: `{self.connections['database']}`"
                msg += f"\n\n>- *GLPI:*\n    Status: `{self.connections['glpi']}`"
                if user.admin_level >= 3:
                    msg += f"\n    _App-Token:_ `{self.glpi.app_token}`\n    _Session-Token:_ `{self.glpi.session_token}`"
                msg += f"\n\n>- *Zabbix:*\n    Status: `{self.connections['zabbix']}`\n"
                if user.admin_level >= 3:
                    msg += f"    _User:_ `{self.zabbix.session['alias']}`\n    _Session:_ `{self.zabbix.session['sessionid']}`"
                await message.reply(msg)

        @self.dispatcher.message_handler()
        async def messages_helper(message: types.Message):
            if message.chat.type != "group":
                chat = extract_chat_object(message)
                user = extract_user_object(message)
                response = await self.validation.running_proccess(
                    user.telegram_id, chat.chat_id, message)
                if response:
                    await bot.send_message(chat.chat_id, response)
            else:
                return