def save_published_id(self, published_offer_list):
        print( "Salving Ids")
        
        # Porcessamentos por categoria
        for category in categories:
            print("\t{0}".format( category[ 'name' ] ))

            # Pega a lista de ofertas salva localmente
            local_offers = IOUtil.json_to_dic( 'offers.json', category[ 'id' ] )
            count_remove = 0

            # Percorre todas as ofertas locais 
            for local_offer in tqdm( reversed( local_offers ) ):
                # Buscando por link - a ofertas local tem de está na lista publicada - a menos que foi recusada
                published_offer = self.find_offer(local_offer, published_offer_list, field='link')
                
                # Se a não está publicada, em teoria é porque foi recusada e deve sair da base local
                if published_offer is None:
                    
                    # Deletando a oferta localmente
                    self.process_delete( [local_offer] )
                    local_offers.remove( local_offer )
                    count_remove += 1
                
                else:
                    local_offer['published_id'] = published_offer['id']

            # Salvando as atualizações
            print("Amount of removed offers:", count_remove)
            IOUtil.dic_to_json('offers.json', category[ 'id' ], local_offers)
    def fill_gtin(self, offers, category):
        dic_gtin = IOUtil.json_to_dic('gtin.json', category )
        print( "Requesting GTIN by offer...")

        # Função que busca e preenche cada GTIN    
        def local_request_gtin(offer, dic_gtin):
            # Verifica se tem o GTIN armazendo locamente para aquele produto
            if offer['id'] in dic_gtin.keys():
                # Armazena o GTIN
                gtin = dic_gtin[ offer['id'] ]
            else:
                # Tenta obter o GTIN na Web
                gtin = request_gtin( offer['names'], offer['brand'] )
                
                # Verifica se GTIN foi encontrado
                if gtin is None: 
                    # Tenta pegar o GTIN de outras ofertas do mesmo produto
                    product_id = offer['id'].split('_')[0]
                    
                    # Procura por ofertas do mesmo produto
                    offer_id = None
                    for key in dic_gtin.keys():
                        if product_id in key:
                            offer_id = key
                            break 
                    
                    # Verifica se foi encontrado
                    if offer_id is not None:
                        # Pega o GTIN da oferta
                        gtin = dic_gtin[ offer_id ]
                        
            if gtin is not None:
                offer['gtin'] = gtin
            
            return offer
        
        # Requerindo o GTIN - paralelizado
        nc = mp.cpu_count()
        offers = Parallel(n_jobs=nc)(delayed(local_request_gtin) (offer, dic_gtin) for offer in tqdm(offers))
        
        offers_without_gtin = []
        for offer in reversed( offers ):
            # Armazenando o GTIN
            if 'gtin' in offer.keys():
                # Armazena o GTIN na base local para uso futuro
                dic_gtin[ offer['id'] ] = offer['gtin']
            else:
                # Armazena a oferta sem GTIN para busca manual
                offers_without_gtin.append( offer )
                # Remove a oferta para não ser publicada
                offers.remove( offer )

        # Atualizando a lista de GTINs
        IOUtil.dic_to_json( 'gtin.json', category, dic_gtin)
        # IOUtil.dic_to_json( 'offers_without_gtin.json', category, offers_without_gtin)

        print("Amount of offers without GTIN: ", len(offers_without_gtin))
        return offers
    def process_offers(self, new_offer_list, category):
        print("Processing the offers...")
       
        # Carregando as ofertas por categoria e criando os vetores
        local_offer_list = IOUtil.json_to_dic( 'offers.json', category[ 'id' ] )
        offer_to_add, offer_to_delete, offer_to_update = [], [], []
        
        print("\tStep 1/2")
        # Produtos que serão removidos
        for local_offer in tqdm( reversed(local_offer_list) ):
            # Se a oferta local não estiver mais disponivel, ela deve ser removida
            if self.find_offer(local_offer, new_offer_list) is None:
                # Verifica se a oferta já havia sido publicada
                if 'published_id' in local_offer.keys():
                    # Adicionando para deletar a publicação
                    offer_to_delete.append( local_offer['published_id'] )
                # Removendo a oferta da base local
                local_offer_list.remove( local_offer )
        
        print("\tStep 2/2")
        # Produtos a serem inseridos e atualizados
        for new_offer in tqdm( new_offer_list ):
            # Buscando o produto na lista de publicados
            published_offer = self.find_offer(new_offer, local_offer_list)
            # Não tem esse produto publicado, então ele será publicado e salvo na base local
            if published_offer is None:
                offer_to_add.append( new_offer )
                local_offer_list.append( new_offer )
            
            # Tem o produto publicado, mas o mesmo possui updates
            elif self.has_updates( published_offer, new_offer ):
                # Removendo a oferta da base local
                local_offer_list.remove( published_offer )
                # Verifica se a oferta possui o id de publicação
                if 'published_id' in published_offer.keys():
                    # Adicionando oferta na lista de atualização
                    new_offer['published_id'] = published_offer['published_id']
                    offer_to_update.append( new_offer )
                # Adicionado a oferta atualizada na base local    
                local_offer_list.append( new_offer )
                
        # Salvando as ofertas locamente
        IOUtil.dic_to_json( 'offers.json', category[ 'id' ], local_offer_list )
        print("offer_to_add: ", len(offer_to_add))

        # Retonas as listas
        return offer_to_add, offer_to_delete, offer_to_update
    def brands_updates(self, _categories=None, to_json=True):
        url = self._get_url('category/_id/{0}')
        dic_brands = defaultdict(list)
        # categories_filter = []
        if _categories is None: _categories = categories

        # percorre todas as categorias listadas 
        print("Searching brands by category")
        for category in tqdm(_categories):
            
            # buscas as informações da categoria
            # print("\tGetting Brands of Category '" + category['name'] + "'")
            json_data = IOUtil.request_json_from_url(url.format(category[ 'id' ]))
            
            # pega somente a lista de marcas
            json_filters = json_data['categories'][0]['filters']
            
            # Check if has filters
            if len(json_filters) == 0: continue

            # categories_filter.append( category )
            json_brands = json_filters[0]['options']
            list_brands = []

            # faz uma lista com as marcas e os ids 
            for brand in json_brands:
                list_brands.append(brand)
            
            # salva essa lista em um dict
            dic_brands[str(category[ 'id' ])] = list_brands

        # print( "Categories without brands: ", count_no_brand)

        # gerar um json com todas as marcas
        dic_brands = self.remove_brands(dic_brands) 
        if to_json: IOUtil.dic_to_json('brands.json', None, dic_brands)
        # IOUtil.dic_to_json('categories_filter.json', None,  categories_filter)

        return dic_brands
def main(sellerApi, category):
    timer = Timer()

    timer.start()
    if category['id'] is None:
        print("Top offers...")
        offers = sellerApi.get_top_offers()
    else:
        offers = sellerApi.get_offers(category)
    print("Time elapsed to get {0} produts: ".format(len(offers)),
          timer.diff())

    timer.start()
    adds, deletes, updates = sellerApi.process_offers(offers, category)
    print("Time elapsed to process the products: ", timer.diff())

    print("Produts to add: ", len(adds))
    print("Produts to update: ", len(updates))
    print("Produts to delete: ", len(deletes))

    # Salvando os ultimos produtos enviados para o csv
    IOUtil.dic_to_json('to_add.json', category['id'], adds)
    IOUtil.dic_to_json('to_update.json', category['id'], updates)
    IOUtil.dic_to_json('to_delete.json', category['id'], deletes)
from io_util import IOUtil
from tqdm import tqdm
import os
from site_api import upload_to_site

DELETE_ALL = True

if DELETE_ALL:

    files = glob("./Data/*")
    print("Number of files data to clean: ", len(files))
    for file in tqdm(files):
        if 'pem' not in file and 'gtin' not in file:
            if '.json' in file:
                if 'offers' in file:
                    IOUtil.dic_to_json(file, None, [], change_path=False)
                else:
                    IOUtil.dic_to_json(file, None, {}, change_path=False)
            else:
                os.remove(file)

    files = glob("./woow/ImagesProducts/*")
    print("Number of images to remove: ", len(files))
    for file in tqdm(files):
        os.remove(file)

    list_products = list.do()
    print("Number of published offers: ", len(list_products))

    delete_list = []
    for product in list_products:
Beispiel #7
0
from seller_api import SellerAPI
from io_util import IOUtil

api = SellerAPI()
offers = api.get_top_offers()
IOUtil.dic_to_json('test.json', None, offers)