#!usr/bin/env python
#-*- coding:utf-8 -*-

import requests
from lxml import etree
from matplotlib import pyplot as plt

from pylab import mpl

mpl.rcParams['font.sans-serif'] = ['FangSong'] # 指定默认字体
mpl.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题

all_data = []
def spider(url):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36',
    }
    html = requests.get(url,headers=headers).content.decode("utf-8")
    text = etree.HTML(html)
    div_list = text.xpath('//div[@class="conMidtab"]')[0]
    div2_list = div_list.xpath('./div[@class="conMidtab2"]')
    for i in div2_list:
        tr_list = i.xpath(".//tr")[2:]
        for index,tr in enumerate(tr_list):
            city = tr.xpath("./td[1]/a/text()")[0]
            if index==0:
                low_temp = tr.xpath("./td[5]/text()")[0]
            else:
                low_temp = tr.xpath("./td[4]/text()")[0]
            all_data.append({'city':city,'low_temp':int(low_temp)})

def main():
    url_list = [
     'http://www.weather.com.cn/textFC/hb.shtml',
    'http://www.weather.com.cn/textFC/db.shtml',
    'http://www.weather.com.cn/textFC/hd.shtml',
    'http://www.weather.com.cn/textFC/hz.shtml',
     'http://www.weather.com.cn/textFC/hn.shtml',
        'http://www.weather.com.cn/textFC/xb.shtml',
        'http://www.weather.com.cn/textFC/xn.shtml',
]
    for url in url_list:
        spider(url)
if __name__ == '__main__':
    main()
    print(all_data)
    all_data.sort(key=lambda data: data['low_temp'], reverse=True)
    data = all_data[0:10]
    print(data)
    citys = []
    min_temp = []
    for i in data:
        citys.append(i['city'])
        min_temp.append(i['low_temp'])
    plt.bar(citys, min_temp)
    plt.show()


#!/usr/bin/python
# -*- Mode: Python; coding: utf-8; indent-tabs-mode: nil; tab-width: 4 -*-
### BEGIN LICENSE
# Copyright (C) 2013 <Zane Swafford> <zane@zaneswafford.com>
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
### END LICENSE
from gi.repository import GdkPixbuf
from spindl_lib.treeviewFormat import format_column
from timeFormat import time_in_span, tuple_time, unformat_time
from math import ceil

class TrendView:
	def __init__(self, treeview_window, treestore, activity_cellrenderedtext,
					trend_pixbuf, percent_change_cellrenderedtext, image_directory):
		self.treeview_window = treeview_window
		self.treestore = treestore
		self.activity_cellrenderedtext = activity_cellrenderedtext
		self.trend_pixbuf = trend_pixbuf
		self.percent_change_cellrenderedtext = percent_change_cellrenderedtext
		self.data = []
		# Make the trendview visible by default
		self.visible = True
		# Load up the pixbufs
		self.image_directory = image_directory
		self.up_pixbuf = GdkPixbuf.Pixbuf.new_from_file(self.image_directory + 'up.png')
		self.same_pixbuf = GdkPixbuf.Pixbuf.new_from_file(self.image_directory + 'same.png')
		self.down_pixbuf = GdkPixbuf.Pixbuf.new_from_file(self.image_directory + 'down.png')
		# Format the treeview_window
		format_column(None, None, self.activity_cellrenderedtext,
					self.percent_change_cellrenderedtext, self.trend_pixbuf)

	def generate_day_trends(self, date):
		"""Takes logs from self.data and changes them to activity trends for
		since the previous day based on a given date tuple"""
		day_activity_list = []
		previous_day_activity_list = []
		trends = []
		# Iterate through the log data.
		for log in self.data:
			# Get and format the information we need from the log.
			activity = log[0]
			log_start = unformat_time(tuple_time(log[1]))
			log_end = unformat_time(tuple_time(log[2]))
			minimum = unformat_time((0,0,0,date[0],date[1],date[2]))
			maximum = unformat_time((59,59,23,date[0],date[1],date[2]))
			# Add the time and activity to the chart_list.
			log_time = time_in_span(log_start, log_end, minimum, maximum)
			# Check if the activity has already been added to chart_list.
			in_day_activity_list = False
			for entry in day_activity_list:
				# If the activity is in the chart_list, make a note and add.
				# its time to the existing list item.
				if entry[0] == activity:
					entry[1] += log_time
					in_day_activity_list = True
			# If the log is not in the chart_list and it is in the span, add
			# it to the chart_list.
			if not in_day_activity_list and log_time > 0:
				day_activity_list.append([activity, log_time])
		# Iterate through the log data.
		for log in self.data:
			# Get and format the information we need from the log.
			activity = log[0]
			log_start = unformat_time(tuple_time(log[1]))
			log_end = unformat_time(tuple_time(log[2]))
			minimum = unformat_time((0,0,0,date[0],date[1],date[2]))
			minimum -= unformat_time((0,0,0,1,0,0))
			maximum = unformat_time((59,59,23,date[0],date[1],date[2]))
			maximum -= unformat_time((0,0,0,1,0,0))
			# Add the time and activity to the chart_list.
			log_time = time_in_span(log_start, log_end, minimum, maximum)
			# Check if the activity has already been added to chart_list.
			in_previous_day_activity_list = False
			for entry in previous_day_activity_list:
				# If the activity is in the chart_list, make a note and add.
				# its time to the existing list item.
				if entry[0] == activity:
					entry[1] += log_time
					in_previous_day_activity_list = True
			# If the log is not in the chart_list and it is in the span, add
			# it to the chart_list.
			if not in_previous_day_activity_list and log_time > 0:
				previous_day_activity_list.append([activity, log_time])
		# Search through the day_activity_list and previous_day_activity_list
		# for matching activities
		for activity in day_activity_list:
			for previous_activity in previous_day_activity_list:
				if activity[0] == previous_activity[0]:
					# Get the percent change between the two activities' times
					# as a string in the form of 100.00%
					percent_change = (((activity[1]-previous_activity[1])*1.00)
										/(previous_activity[1]*1.00))
					percent_change = str((ceil(percent_change*10000.00))/100.00)
					if percent_change[-2] == '.':
						percent_change += '0'
					percent_change += '%'
					# Add this activity and it's percent change to trends list
					trends.append([activity[0], percent_change])
		# Set data as trends
		self.data = trends

	def generate_month_trends(self, date):
		"""Takes logs from self.data and changes them to activity trends for
		since the previous month based on a given date tuple"""
		month_activity_list = []
		previous_month_activity_list = []
		trends = []
		# Iterate through the log data.
		for log in self.data:
			# Get and format the information we need from the log.
			activity = log[0]
			log_start = unformat_time(tuple_time(log[1]))
			log_end = unformat_time(tuple_time(log[2]))
			minimum = unformat_time((0,0,0,1,date[1],date[2]))
			maximum = unformat_time((59,59,23,date[0],date[1],date[2]))
			# Add the time and activity to the chart_list.
			log_time = time_in_span(log_start, log_end, minimum, maximum)
			# Check if the activity has already been added to chart_list.
			in_month_activity_list = False
			for entry in month_activity_list:
				# If the activity is in the chart_list, make a note and add.
				# its time to the existing list item.
				if entry[0] == activity:
					entry[1] += log_time
					in_month_activity_list = True
			# If the log is not in the chart_list and it is in the span, add
			# it to the chart_list.
			if not in_month_activity_list and log_time > 0:
				month_activity_list.append([activity, log_time])
		# Iterate through the log data.
		for log in self.data:
			# Get and format the information we need from the log.
			activity = log[0]
			log_start = unformat_time(tuple_time(log[1]))
			log_end = unformat_time(tuple_time(log[2]))
			if date[1] > 1:
				minimum = unformat_time((0,0,0,1,date[1]-1,date[2]))
			else:
				minimum = unformat_time((0,0,0,1,12,date[2]-1))
			maximum = unformat_time((59,59,23,1,date[1],date[2]))
			maximum -= unformat_time((0,0,0,1,0,0))
			# Add the time and activity to the chart_list.
			log_time = time_in_span(log_start, log_end, minimum, maximum)
			# Check if the activity has already been added to chart_list.
			in_previous_month_activity_list = False
			for entry in previous_month_activity_list:
				# If the activity is in the chart_list, make a note and add.
				# its time to the existing list item.
				if entry[0] == activity:
					entry[1] += log_time
					in_previous_month_activity_list = True
			# If the log is not in the chart_list and it is in the span, add
			# it to the chart_list.
			if not in_previous_month_activity_list and log_time > 0:
				previous_month_activity_list.append([activity, log_time])
		# Search through the month_activity_list and
		# previous_month_activity_list for matching activities
		for activity in month_activity_list:
			for previous_activity in previous_month_activity_list:
				if activity[0] == previous_activity[0]:
					# Get the percent change between the two activities' times
					# as a string in the form of 100.00%
					percent_change = (((activity[1]-previous_activity[1])*1.00)
										/(previous_activity[1]*1.00))
					percent_change = str((ceil(percent_change*10000.00))/100.00)
					if percent_change[-2] == '.':
						percent_change += '0'
					percent_change += '%'
					# Add this activity and it's percent change to trends list
					trends.append([activity[0], percent_change])
		# Set data as trends
		self.data = trends

	def generate_span_trends(self, from_date, to_date):
		"""Takes logs from self.data and changes them to activity trends for
		since the previous day based on a given date tuple"""
		activity_list = []
		# Iterate through the log data.
		for log in self.data:
			# Get and format the information we need from the log.
			activity = log[0]
			log_start = unformat_time(tuple_time(log[1]))
			log_end = unformat_time(tuple_time(log[2]))
			minimum = unformat_time((0, 0, 0, from_date[0], from_date[1],
										from_date[2]))
			maximum = unformat_time((59, 59, 23, to_date[0], to_date[1],
										to_date[2]))
			log_time = time_in_span(log_start, log_end, minimum, maximum)
			# If the log exists in the span
			if log_time > 0:
				in_activity_list = False
				# Iterate through the activity list to check for duplicates
				for entry in activity_list:
					if entry[0] == activity:
						# Then the entry is in the activity list
						in_activity_list = True
						# Set the maximum of the span to check as the end of the
						# from_date
						maximum = unformat_time((59, 59, 23, from_date[0],
													from_date[1], from_date[2]))
						# If the log did not happen on the from date
						if not (time_in_span(log_start, log_end,
												minimum, maximum) == 0):
							# add the log's time in the span to the activity's
							# start trend time.
							entry[1] += time_in_span(log_start, log_end,
														minimum, maximum)
						else:
							# Else add it the activity's end trend time
							entry[2] += log_time
				# If the log is not already in the activity list, add it.
				if not in_activity_list:
					activity_list.append([activity, log_time, 0])
		# Make a list of the activities and their respective trends
		trends_list = []
		# Iterate through the activity list
		for entry in activity_list:
			# If the end trend time of the activity exists (I.E. not zero)
			if not entry[2] == 0:
				# Get the trend and convert it to a string with a percent symbol
				percent_change = (((entry[2] - entry[1])*1.00)/(entry[1]*1.00))
				percent_change = str((ceil(percent_change*10000.00))/100.00)
				if percent_change[-2] == '.':
					percent_change += '0'
				percent_change += '%'
				trends_list.append([entry[0], str(percent_change)])
		# Set data as trends
		self.data = trends_list

	def load_into_treeview_window(self):
		"""Load the treeviews data into the treestore widget"""
		for trend in self.data:
			# Get which pixbuf we will be using based on whether or not the
			# trend is positive.
			if float(trend[1][:-1]) > 0:
				pixbuf = self.up_pixbuf
			elif float(trend[1][:-1]) < 0:
				pixbuf = self.down_pixbuf
				trend[1] = trend[1][1:]
			else:
				pixbuf = self.same_pixbuf
			# append the data to the treestore
			self.treestore.append(None, (trend[0], pixbuf, trend[1]))

	def set_visible(self, visible=True):
		"""Used to make loading animation work correctly, need to remove"""
		self.treeview_window.set_visible(visible)
		self.visible = visible

	def clear(self):
		"""Clears the TrendView"""
		self.data = []
		self.treestore.clear()


import re

import boto.ec2

import ec2.metrics
import ec2.specs

def ec2_conn(env):
    return boto.ec2.connect_to_region(
        env['aws_ec2']['aws_region'],
        aws_access_key_id=env['aws_ec2']['aws_access_key'],
        aws_secret_access_key=env['aws_ec2']['aws_secret_key'])

def pull(env):
    """
    pulls interesting fields for all instances in the supplied envs from aws
    """
    interesting = [
        'id',
        'instance_type',
        'launch_time',
        'placement',
        'state',
        'tags',
        'virtualization_type',
        'vpc_id', ]

    instances = []
    conn = ec2_conn(env)
    for reservation in conn.get_all_instances():
        for instance in reservation.instances:
            data = {}
            for x in interesting:
                data[x] = getattr(instance, x)
            instances.append(data)
    return instances

def cook(instances):
    """
    takes a list of instances as retured by *pull* and normalizes the data to a
    useful form
    """
    vpcs = {}

    for instance in instances:
        vpc_id = instance['vpc_id']
        tags = instance['tags']
        if vpc_id and vpc_id not in vpcs:
            if 'Name' in tags:
                parts = tags['Name'].split('.')
                if len(parts) == 4:
                    vpcs[vpc_id] = parts[1]

    def env(instance):
        vpc_id = instance['vpc_id']
        tags = instance['tags']
        if vpc_id in vpcs:
            return vpcs[vpc_id]
        if 'Name' in tags:
            parts = tags['Name'].split('.')
            if len(parts) == 4:
                return parts[1]
        return 'unknown'

    def role(instance):
        tags = instance['tags']
        if 'role' in tags:
            return tags['role']
        if 'Name' in tags:
            prefix = tags['Name'].split('.')[0]
            match = re.match('^([a-z]*)\d', prefix)
            if match:
                return match.group(1)
        return 'unknown'

    columns = [
        ('role', lambda i: role(i)),
        ('env', lambda i: env(i)),
        ('host', lambda i: i['tags'].get('Name')),
        ('az', lambda i: i['placement']),
        ('type', lambda i: i['instance_type']),
        ('time', lambda i: i['launch_time']),
        ('virt', lambda i: i['virtualization_type']),
        ('state', None),
        ('id', None), ]

    cooked = []
    for instance in instances:
        row = {}
        for key, f in columns:
            f = f or (lambda i: instance[key])
            row[key] = f(instance)
        cooked.append(row)
    return cooked

#TODO THIS FUNCTION IS KINDA A BAD IDEA... IT SHOULD BE A PROGRAM ITSELF?
def get(envs, refresh=False):
    instances = []
    for env in envs:
        instances += pull(env)
    return cook(instances)

# lazy load and cache shared instance data
class DATA(object):
    def __init__(self):
        self._metrics = None
        self._specs = None

    @property
    def metrics(self):
        if not self._metrics:
            self._metrics = ec2.metrics.get()
        return self._metrics

    @property
    def specs(self):
        if not self._specs:
            self._specs = ec2.specs.get()
        return self._specs

DATA = DATA()

class Group(object):
    """
    represents a group of instances
    """
    def __init__(self, key):
        self.key = key
        self.instances = []

    def __getattr__(self, name):
        if name in self.instances[0]:
            return self.instances[0][name]
        raise AttributeError(name)

    def price(self, name, instance_type=None):
        prices = [
            DATA.specs[
                instance_type and instance_type or x['type']]['prices'][name]
            for x in self.instances]
        return sum(prices)

    def metric(self, name):
        members = [x[name] for x in self.metrics]
        if not members:
            return -1
        return sum(members) / len(members)

    @property
    def metrics(self):
        return [
            DATA.metrics[x['id']]
            for x in self.instances if x['id'] in DATA.metrics]

    @property
    def type(self):
        return list(set([x['type'] for x in self.instances]))

    @property
    def new(self):
        return bool([
            x for x in self.instances if x['virt'] == 'hvm'])

    def __len__(self):
        return len(self.instances)

    def __repr__(self):
        return 'Group(%s: %s)' % (self.key, len(self.instances))


import numpy as np
from time import sleep
from PIL import Image
from ppadb.client import Client as AdbClient

# Establish connection between device and computer
# Default is "127.0.0.1" and 5037
client = AdbClient(host="127.0.0.1", port=5037)
devices = client.devices()
device = devices[0]

phone_height_pixels = 2280
height = int(phone_height_pixels * 0.75)

for repeats in range(1000):
    borders = [] # [Right edge of start tower, Left edge of target tower, Right edge of target tower]
    found_start = False # Found left edge of start tower
    black = True # Is the current pixel black

    # Takes screenshot
    image = device.screencap()
    with open("screencapture.png", "wb") as fp:
        fp.write(image)

    # Open PIL image
    image = Image.open("screencapture.png")

    # Convert image to numpy array
    image = np.array(image)
    for i in range(1080):

        # Find leftmost edge of starting tower
        if not found_start:
            if (image[1800][i][0] < 10):
                found_start = True
            else:
                continue

        # No black to black transition
        if image[height][i][0] < 10 and not black:
            borders.append(i)
            black = not black

        # Black to not black transition
        if image[height][i][0] > 10 and black:
            borders.append(i)
            black = not black

    # Solves the case when the target tower spans to the
    # right edge of the screen.
    if (len(borders) < 3):
        borders.append(1079)

    gap = borders[1] - borders[0]
    platform_width = borders[2] - borders[1]
    distance = gap + platform_width/2 # Ninja to the red target
    distance = distance * 0.98 # Scaling factor

    # Input press to phone app
    device.shell("input touchscreen swipe 500 500 500 500 {}".format(int(distance)))

    # Wait for next level to load
    sleep(2.8)


# Author: Jintao Huang
# Time: 2020-5-28
import torch.nn as nn
import torch

class AnchorGenerator(nn.Module):
    def __init__(self, scales, pyramid_levels=None):
        """

        :param scales: tuple[tuple(H, W)].
        :param pyramid_levels: tuple[int]
        """
        super(AnchorGenerator, self).__init__()
        pyramid_levels = pyramid_levels or (3, 4, 5)
        self.scales = scales
        self.strides = [2 ** i for i in pyramid_levels]
        self.image_size = None  # int
        self.anchors = None

    def forward(self, x):
        """

        :param x: (images)Tensor[N, 3, H, W]. need: {.shape, .device, .dtype}
        :return: anchors[X(F*H*W*A), 5]. (cell_x, cell_y, stride, width, height)
        """
        image_size, dtype, device = x.shape[3], x.dtype, x.device
        if self.image_size == image_size:  # Anchors has been generated
            return self.anchors.to(device, dtype, copy=False)  # default: False
        else:
            self.image_size = image_size

        anchors_all = []
        for stride, scales in zip(self.strides, self.scales):
            anchors_level = []
            for scale in scales:
                if image_size % stride != 0:
                    raise ValueError('input size must be divided by the stride.')
                anchor_h, anchor_w = scale
                cell_x = torch.arange(0, image_size // stride, dtype=dtype, device=device)
                cell_y = torch.arange(0, image_size // stride, dtype=dtype, device=device)
                cell_y, cell_x = torch.meshgrid(cell_y, cell_x)
                cell_x = cell_x.reshape(-1)
                cell_y = cell_y.reshape(-1)
                strides = torch.full_like(cell_x, stride, dtype=dtype, device=device)
                anchor_w = torch.full_like(cell_x, anchor_w, dtype=dtype, device=device)
                anchor_h = torch.full_like(cell_x, anchor_h, dtype=dtype, device=device)

                # shape(X, 5)
                anchors = torch.stack([cell_x, cell_y, strides, anchor_w, anchor_h], dim=-1)
                anchors_level.append(anchors)

            anchors_level = torch.stack(anchors_level, dim=1).reshape(-1, 5)  # shape(X, A, 5) -> (-1, 5)
            anchors_all.append(anchors_level)
        self.anchors = torch.cat(anchors_all, dim=0)  # shape(-1, 5)
        return self.anchors


#!/usr/bin/env python3
from controllers.viewController import ViewController
from models.mcuSettingsModel import Settings
from utils.config import ConfigValues

class App():
    def __init__(self):

        self.settings = Settings.fromConfig()

        config = ConfigValues()
        self.viewController = ViewController()

    def showMainView(self):
        self.viewController.mainloop()

if __name__ == "__main__":
    app = App()
    app.viewController.asyncio()

    app.showMainView()

    print ('bye')


# scanSnippetsVsc
## import all optional arguments used in command line
import argparse, sys
# create a parser
parser = argparse.ArgumentParser()
# read sublime text snippets
with open(sys.argv[1], 'r') as fileInput:
    contents = fileInput.readlines()
parser.add_argument(sys.argv[1])
for x in ["-vsc", "-atom", "-sublime", "-vim", "-all"]:
    parser.add_argument(x, action="store_true")
# add an argument to get our arguments from parser
args = parser.parse_args()

# find description between <description> </description>

# find prefix between <tabTrigger> </tabTrigger>


from django.shortcuts import render
from django.http import HttpResponse,HttpResponseRedirect
from django.urls import reverse
from .models import Superhero

# Create your views here.
def index(request):
    all_heroes = Superhero.objects.all()
    context ={
        'all_heroes':all_heroes
    }
    return render(request,'superheroes/index.html', context)

def detail(request,hero_id):
    single_hero = Superhero.objects.get(pk = hero_id)
    context ={
        'single_hero':single_hero
    }
    return render(request,'superheroes/detail.html', context)

def create(request):
    if request.method == 'POST':
        name = request.POST.get('name')
        alter_ego = request.POST.get('alter_ego')
        primary = request.POST.get('primary')
        secondary = request.POST.get('secondary')
        catch_phrase = request.POST.get('catchphrase')

        new_hero = Superhero(name=name, alter_ego=alter_ego, primary_ability = primary, secondary_ability= secondary, catch_phrase = catch_phrase)
        new_hero.save()

        return HttpResponseRedirect(reverse('superheroes:index'))

    else:
        return render(request,'superheroes/create.html')

def edit(request,hero_id):
    hero_to_update = Superhero.objects.get(pk = hero_id)
    context ={
        'hero_to_update':hero_to_update
    }

    if request.method == 'POST':
        update_hero = Superhero.objects.get(pk = hero_id)
        update_hero.name = request.POST.get('name')
        update_hero.alter_ego = request.POST.get('alter_ego')
        update_hero.primary_ability = request.POST.get('primary')
        update_hero.secondary_ability = request.POST.get('secondary')
        update_hero.catch_phrase = request.POST.get('catchphrase')

        update_hero.save()

        return HttpResponseRedirect(reverse('superheroes:detail', kwargs={'hero_id': hero_id}))
    else:
        return render(request,'superheroes/edit.html', context)

def delete(request,hero_id):

    list_hero = Superhero.objects.get(pk = hero_id)
    context1 ={
        'list_hero':list_hero
    }
    delete_hero = Superhero.objects.get(pk = hero_id)
    context ={
        'delete_hero':delete_hero
    }
    delete_hero.delete()
    return HttpResponseRedirect(reverse('superheroes:index'))

    # return render(request,'superheroes/delete.html', context1)


# -*- coding: utf-8 -*-
"""
Created on Wed Mar 17 20:22:06 2021

@author: kolof
"""
import os
import pandas
import zipfile
from Logger import Logger

class DataPreparer:

    #создание класса
    def __init__(self, zipFilesPath, xmlSavePath, log):

        self._zipFilesPath = zipFilesPath
        self._xmlSavePath = xmlSavePath
        self.z = None
        self.log = log

    #смена директории хранения zip файлов
    def changeZipDirectory(self, newDirectory):
        self._zipFilesPath = newDirectory

    #смена директории хранения xml-файлов
    def changeXMLDirectory(self, newDirectory):
        self._xmlSavePath = newDirectory

    #чтение zip-файла
    def openZip(self, file):
        if os.path.exists(file):
            if zipfile.is_zipfile(file):
                self.z = zipfile.ZipFile(file, 'r')
                self.log.add('Открытие файла ' + os.path.basename(file) )
            else:
                raise FileNotFoundError
                self.log.add_error('Не удалось открыть файл ' + os.path.basename(file))

    #Извлечение всех файлов
    def extractZip(self, filetype = None):
        if self.z:
            self.log.add('Извлечение данных из файла ' + self.z.filename)
            if not filetype:
                self.z.extractall(self._xmlSavePath)
            else:
                for file in self.z.infolist():
                    if file.filename.endswith('.' + filetype):
                        self.z.extract(file.filename, self._xmlSavePath)
            self.z.close()
        else:
            raise FileNotFoundError

    #Открыть и извлечь файл
    def openAndExtractZip(self, file, filetype = None):
        self.openZip(file)
        self.extractZip(filetype)

    #Извлечение всех zip-файлов из активной директории
    def openAndExtractAllZip(self, filetype = None):
      with os.scandir(self._zipFilesPath) as listOfEntries:
          for entry in listOfEntries:
              print ('открываю файл', entry)
              self.openAndExtractZip(entry, filetype)

    #Закрытие zip-файла
    def close(self):
        if self.z:
            self.z.close()

    #Имя файла
    @property
    def filename(self):
        return os.path.basename(self.z)

    #Путь активной xmlдиректории
    @property
    def xmlRoute(self):
        return self._xmlSavePath

    #Путь активной zip директории
    @property
    def zipRoute(self):
        return self._zipFilesPath

zipFilesPath = 'D:\\Documents\\Учебная практика\\2020-2021\\Февраль 2021\\Код\\Data\\Raw'
xmlSavePath = 'D:\\Documents\\Учебная практика\\2020-2021\\Февраль 2021\\Код\\Data\\Prepared\\extractedXml'
zipReader = DataPreparer(zipFilesPath, xmlSavePath, Logger('log'))
zipReader.openAndExtractAllZip(filetype = 'xml')


#Backstage
import openpyxl as op
import pandas as pd
import obtenerTokenmodulo as otm
from tkinter import*
from tkinter import ttk
from tkinter import messagebox as mb
import requests
import json
import correctortitulo as ct
tok= False
#Diccionarios
dic_titulo = {}
dic_autor = {}
dic_editorial = {}
dic_precio = {}
dic_titulopub = {}
portada = {}
contraportada = {}
paginaextra1 = {}
paginaextra2 = {}
paginaextra3 = {}
paginaextra4 = {}
dic_tema = {}
apellido = {}
imagenes = {}
lista_publicados=[]
lista_no_publicados=[]
dic_no_publicados={}
isbns = []
isbn_depurado = []
en_la_base = []
no_en_la_base = []
corregidos={}
dic_real_isbn={}
corregidos_isbn_concat={}
corregidos_precio_concat={}
global excel
excel=False
global csvcon
csvcon=False
a=0

def revisar_tokenpresxistente():
	global tok
	tok=otm.revisar_token_activo()
	if tok==False:
		otm.obtenertoken()
	else:
		pass
def funerariat(tit, isbnd):
	"""
	colon=""
	if ',' in tit:
		titu = tit.split(',')
		arti = titu [1].strip(" ")
		titul = titu[0].strip(" ")
		largo_arit=len(arti)
		if largo_arit > 3:
				if arti[2]==" ":
					artic= arti[0]+arti[1]
				elif arti[2]=="s" or arti[2]=="o" or arti[2]=="a":
					artic= arti[0]+arti[1]+arti[2]
					colon=arti[3:]
				elif arti[2]=="/":
					artic= arti[0]+arti[1]
				else:
					artic= arti[0]+arti[1]
					colon=arti[3:]
		else:
			if arti[1]==" ":
				artic=	arti[0]
			elif arti[1]=="a" or arti[1]=="l" or arti[1]=="o":
				artic= arti[0]+arti[1]
			else:
				artic=""
		if len(colon)>0:
			titulo = artic + " " + titul+" "+colon
		else:
			titulo = artic + " " + titul
	else:
		titulo = tit
	tituloo = titulo.title()
	titulod = tituloo.strip()
	dic_titulo[isbnd] = titulod
	"""
	dic_titulo[isbnd]=ct.corrector_titulo(tit)
def funerariaa(aut, isbnd):
	"""
	if ',' in aut:
		auto = aut.split(',')
		artic = auto [1].strip(" ")
		ape = auto[0].strip(" ")
		autor = artic + " " + ape
		apellido[isbnd] = ape.title()
	else:
		autor = aut.strip("	")
		apellido[isbnd] = autor.title()
	autort = autor.strip(" ")
	autord = autort.title()
	#ct.corrector_autor(aut)
	dic_autor[isbnd] = autord
	"""
	autor,apell=ct.corrector_autor(aut)
	apellido[isbnd] = apell
	dic_autor[isbnd] = autor

def funerariae(edit, isbnd):
	editora = edit.title()
	editorial = editora.strip(" ")
	dic_editorial[isbnd] = editorial
def funerariap(pre, isbnd):
	dic_precio[isbnd] =str(pre)

def concatenadopub(isbnd):
	dic_titulopub[isbnd] = dic_titulo[isbnd] + " - "+ apellido[isbnd] + " - " + dic_editorial[isbnd]

def funerariatema(isbnd, tem):
	dic_tema[isbnd] = tem.title()
def desplegar_copiableaexcel():
	toplevel_arbol=Toplevel(window)
	toplevel_arbol.title("Publicaciones")
	cuadro_resultado_frame=Frame(toplevel_arbol)
	cuadro_resultado_frame.pack()
	cuadro_resultado = Text(cuadro_resultado_frame, width=75, height=25)
	cuadro_resultado.grid(column=1, row=3, padx=5, pady=5)

	scroll = Scrollbar(cuadro_resultado_frame, command=cuadro_resultado.yview)
	scroll.grid(column=2, row=3, sticky="nsew")
	cuadro_resultado.config(yscrollcommand=scroll.set)
	for isbnd in en_la_base:
		cuadro_resultado.insert(
			END, dic_titulopub[isbnd] + "," +
			isbnd + "," + imagenes[isbnd] + "," +
			isbnd + "," + "1" + "," + dic_precio[isbnd] + "," + "Nuevo" + "," + "des" + "," + " " + "," +
			"Clásica" + "," + "Mercado Envíos | Mercado Envíos Flex" + "," + "A cargo del comprador" + "," +
			"Acepto" + "," + "Garantía del vendedor"  + "," + "1" + "," + "meses"  + "," + "Papel" + "," +
			dic_tema[isbnd]  + "," + dic_titulo[isbnd] + "," + dic_autor[isbnd] + "," + "Español" + "," +
			dic_editorial[isbnd] + "," + dic_tema[isbnd] + "\n"
			)

def arbolgeneral():
	a=0
	for isb in en_la_base:
		arb.insert(parent='',index=a, iid=a, text='', values=(dic_titulopub[isb][:59],dic_real_isbn[isb],imagenes[isb],isb,"1",dic_precio[isb],dic_tema[isb],dic_titulo[isb],dic_autor[isb],dic_editorial[isb]))
		a+=1
	arb.pack()
def busqueda(xrow, isbnd, x):
	#cuadro_resultado.insert(END, isbnd)
	#cuadro_resultado.insert(END, xrow)
	if isbnd==str(xrow):
		en_la_base.append(isbnd)
		global sheet
		global excel_titulo_conc
		global excel_autor_conc
		global excel_editorial_conc
		global excel_precio_conc
		global excel_tema_conc
		#print(sheet.cell(row=x, column=2).value)
		tit = sheet.cell(row=x, column=excel_titulo_conc).value
		aut = sheet.cell(row=x, column=excel_autor_conc).value
		edit = sheet.cell(row=x, column=excel_editorial_conc).value
		pre = sheet.cell(row=x, column=excel_precio_conc).value
		tem = sheet.cell(row=x, column=excel_tema_conc).value
		funerariat(tit, isbnd)
		funerariaa(aut, isbnd)
		funerariae(edit, isbnd)
		funerariap(pre, isbnd)
		funerariatema(isbnd, tem)
		concatenadopub(isbnd)
		dic_real_isbn[isbnd]=isbnd
def busqudacsv(isbnd):
	if len(isbnd)!=13:
		bus_isbn = str(isbnd)+"   "
	else:
		bus_isbn= str(isbnd)
	global csv
	fila_isbn=csv[csv.ISBN==bus_isbn]
	global num_tit
	global num_aut
	global num_edit
	global num_pre
	global num_tem
	try:
		tit = fila_isbn.iat[0,int(num_tit)]
		aut = fila_isbn.iat[0,int(num_aut)]
		edit = fila_isbn.iat[0,int(num_edit)]
		pre = fila_isbn.iat[0,int(num_pre)]
		tem = fila_isbn.iat[0,int(num_tem)]
		funerariat(tit, isbnd)
		funerariaa(aut, isbnd)
		funerariae(edit, isbnd)
		funerariap(pre, isbnd)
		funerariatema(isbnd, tem)
		concatenadopub(isbnd)
		dic_real_isbn[isbnd]=isbnd
		en_la_base.append(isbnd)

	except IndexError:
		no_en_la_base.append(isbnd)
def concatenado(isbnd):
	"""concatena las imágenes de portada y contraportada"""
	if isbnd in portada:
		if isbnd in contraportada:
			if isbnd in paginaextra1:
				if isbnd in paginaextra2:
					if isbnd in paginaextra3:
						if isbnd in paginaextra4:
							imagenes[isbnd] = portada[isbnd] + "; " + contraportada[isbnd] + "; " + paginaextra1[isbnd] + "; " + paginaextra2[isbnd] + "; " + paginaextra3[isbnd] + "; " + paginaextra4[isbnd] + "; https://i.postimg.cc/B6SMfSSh/001.jpg"
						else:
							imagenes[isbnd] = portada[isbnd] + "; " + contraportada[isbnd] + "; " + paginaextra1[isbnd] + "; " + paginaextra2[isbnd] + "; " + paginaextra3[isbnd] + "; https://i.postimg.cc/B6SMfSSh/001.jpg"
					else:
						imagenes[isbnd] = portada[isbnd] + "; " + contraportada[isbnd] + "; " + paginaextra1[isbnd] + "; " + paginaextra2[isbnd] + "; https://i.postimg.cc/B6SMfSSh/001.jpg"
				else:
					imagenes[isbnd] = portada[isbnd] + "; " + contraportada[isbnd] + "; " + paginaextra1[isbnd] + "; https://i.postimg.cc/B6SMfSSh/001.jpg"
			else:
				imagenes[isbnd] = portada[isbnd] + "; " + contraportada[isbnd] + "; https://i.postimg.cc/B6SMfSSh/001.jpg"
				#cuadro_resultado.insert(END, imagenes)
		else:
			imagenes[isbnd] = portada[isbnd] + "; https://i.postimg.cc/B6SMfSSh/001.jpg"
	else:
		imagenes[isbnd] =  "https://i.postimg.cc/B6SMfSSh/001.jpg"

def deconstruirisbns(presibn, listas):
	if presibn[-7] != "0":
		isbn_con_error(presibn)
		#cuadro_resultado.insert(END, "\n" + presibn + " será excluido de la lista final porque no tiene el formato adecuado.\n Recordá que después del ISBN debe incluir 001.jpg\n así se determina la posición de la foto.")
	else:
		if presibn[-21] == "/":
			largo = len(presibn)
			desde = int(largo)-20
			preisbna = presibn[desde:largo]
			isbn = preisbna[0:13]
			resto = preisbna[13:20]
			isbns.append(isbn)
			if resto == "001.jpg":
				portada[isbn] = listas[0]
				listas.pop(0)
			elif resto == "002.jpg":
				contraportada[isbn] = listas[0]
				listas.pop(0)
			elif resto == "003.jpg":
				paginaextra1[isbn] = listas[0]
				listas.pop(0)
			elif resto == "004.jpg":
				paginaextra2[isbn] = listas[0]
				listas.pop(0)
			elif resto == "005.jpg":
				paginaextra3[isbn] = listas[0]
				listas.pop(0)
			elif resto == "006.jpg":
				paginaextra4[isbn] = listas[0]
				listas.pop(0)
		else:
			largo = len(presibn)
			desde = int(largo)-17
			preisbna = presibn[desde:largo]
			isbn = preisbna[0:10]
			resto = preisbna[10:17]
			isbns.append(isbn)
			if resto == "001.jpg":
				portada[isbn] = listas[0]
				listas.pop(0)
			elif resto == "002.jpg":
				contraportada[isbn] = listas[0]
				listas.pop(0)
			elif resto == "003.jpg":
				paginaextra1[isbn] = listas[0]
				listas.pop(0)
			elif resto == "004.jpg":
				paginaextra2[isbn] = listas[0]
				listas.pop(0)
			elif resto == "005.jpg":
				paginaextra3[isbn] = listas[0]
				listas.pop(0)
			elif resto == "006.jpg":
				paginaextra4[isbn] = listas[0]
				listas.pop(0)
def fin():
	mb.showinfo('Aviso', 'Proceso concluido')
def noenlabase():
	for n in no_en_la_base:
		mb.showinfo('Aviso', n + '\n no se encontraban en la base de datos')

def cargarexcel():
	global excel_concatenador_libro
	libro_ex_conca=excel_concatenador_libro.get()
	global excel_concatenador_hoja
	hoja_ex_conca=excel_concatenador_hoja.get()
	wb = op.load_workbook(libro_ex_conca+'.xlsx')
	global sheet
	sheet = wb[hoja_ex_conca]
	global excel_concatenador_columna_isbn_ent
	global excel_isbn_conc
	excel_isbn_conc = int(excel_concatenador_columna_isbn_ent.get())
	global excel_concatenador_columna_titulo_ent
	global excel_titulo_conc
	excel_titulo_conc = int(excel_concatenador_columna_titulo_ent.get())
	global excel_concatenador_columna_autor_ent
	global excel_autor_conc
	excel_autor_conc = int(excel_concatenador_columna_autor_ent.get())
	global excel_concatenador_columna_editorial_ent
	global excel_editorial_conc
	excel_editorial_conc = int(excel_concatenador_columna_editorial_ent.get())
	global excel_concatenador_columna_precio_ent
	global excel_precio_conc
	excel_precio_conc = int(excel_concatenador_columna_precio_ent.get())
	global excel_concatenador_columna_tema_ent
	global excel_tema_conc
	excel_tema_conc = int(excel_concatenador_columna_tema_ent.get())
	global excel
	excel = True
	toplevel_desdeExcel_concatenador.destroy()
def desdeExcel_concatenador():
	#Toplevel de ingreso de datos
	global toplevel_desdeExcel_concatenador
	toplevel_desdeExcel_concatenador = Toplevel(window)
	toplevel_desdeExcel_concatenador.title("Ingresar Catálogo desde Excel")
	frame_DE = Frame(toplevel_desdeExcel_concatenador)
	frame_DE.pack()
	frame_DE2=Frame(toplevel_desdeExcel_concatenador)
	frame_DE2.pack()
	#Ingresar lista de publicaciones
	excel_concatenador_libro_lab = Label(frame_DE, text="Inserte Libro de publicaciones:")
	excel_concatenador_libro_lab.grid(column=1, row=2)
	excel_concatenador_libro_lab2 = Label(frame_DE, text=".xlsx")
	excel_concatenador_libro_lab2.grid(column=3, row=2)
	global excel_concatenador_libro
	excel_concatenador_libro = Entry(frame_DE, width=15)
	excel_concatenador_libro.grid(column=2, row=2, padx=5, pady=5)
	excel_concatenador_libro.insert(END,"EML")
	excel_concatenador_hoja_lab = Label(frame_DE, text="Inserte nombre de la hoja:")
	excel_concatenador_hoja_lab.grid(column=1, row=3)
	global excel_concatenador_hoja
	excel_concatenador_hoja = Entry(frame_DE, width=15)
	excel_concatenador_hoja.grid(column=2, row=3, padx=5, pady=5)
	excel_concatenador_hoja.insert(END,"EML")
	excel_concatenador_columna_titulo_lab= Label(frame_DE, text="Inserte el número de columna de Título")
	excel_concatenador_columna_titulo_lab.grid(column=1, row=4)
	global excel_concatenador_columna_titulo_ent
	excel_concatenador_columna_titulo_ent= Entry(frame_DE, width=5)
	excel_concatenador_columna_titulo_ent.grid(column=2, row=4, padx=5, pady=5)
	excel_concatenador_columna_titulo_ent.insert(END,"2")
	excel_concatenador_columna_autor_lab= Label(frame_DE, text="Inserte el número de columna de Autor:")
	excel_concatenador_columna_autor_lab.grid(column=1, row=5)
	global excel_concatenador_columna_autor_ent
	excel_concatenador_columna_autor_ent= Entry(frame_DE, width=5)
	excel_concatenador_columna_autor_ent.grid(column=2, row=5, padx=5, pady=5)
	excel_concatenador_columna_autor_ent.insert(END,"3")
	excel_concatenador_columna_editorial_lab= Label(frame_DE, text="Inserte el número de columna de Editorial:")
	excel_concatenador_columna_editorial_lab.grid(column=1, row=6)
	global excel_concatenador_columna_editorial_ent
	excel_concatenador_columna_editorial_ent= Entry(frame_DE, width=5)
	excel_concatenador_columna_editorial_ent.grid(column=2, row=6, padx=5, pady=5)
	excel_concatenador_columna_editorial_ent.insert(END,"4")
	excel_concatenador_columna_isbn_lab= Label(frame_DE, text="Inserte el número de columna de ISBN:")
	excel_concatenador_columna_isbn_lab.grid(column=1, row=7)
	global excel_concatenador_columna_isbn_ent
	excel_concatenador_columna_isbn_ent= Entry(frame_DE, width=5)
	excel_concatenador_columna_isbn_ent.grid(column=2, row=7, padx=5, pady=5)
	excel_concatenador_columna_isbn_ent.insert(END,"9")
	excel_concatenador_columna_precio_lab= Label(frame_DE, text="Inserte el número de columna de Precio:")
	excel_concatenador_columna_precio_lab.grid(column=1, row=8)
	global excel_concatenador_columna_precio_ent
	excel_concatenador_columna_precio_ent= Entry(frame_DE, width=5)
	excel_concatenador_columna_precio_ent.grid(column=2, row=8, padx=5, pady=5)
	excel_concatenador_columna_precio_ent.insert(END,"29")
	excel_concatenador_columna_tema_lab= Label(frame_DE, text="Inserte el número de columna de Tema:")
	excel_concatenador_columna_tema_lab.grid(column=1, row=9)
	global excel_concatenador_columna_tema_ent
	excel_concatenador_columna_tema_ent= Entry(frame_DE, width=5)
	excel_concatenador_columna_tema_ent.grid(column=2, row=9, padx=5, pady=5)
	excel_concatenador_columna_tema_ent.insert(END,"6")
	bot_guardar_catalogo = Button(frame_DE2, text="Guardar", command=cargarexcel)
	bot_guardar_catalogo.pack()
def cargarcsv():
	global Csv_concatenador_libro
	hoja_csv=Csv_concatenador_libro.get()
	global csv
	csv=pd.read_csv(hoja_csv+'.txt',sep=';')
	global num_tit
	num_tit = Csv_concatenador_columna_titulo_ent.get()
	global num_aut
	num_aut = Csv_concatenador_columna_autor_ent.get()
	global num_edit
	num_edit = Csv_concatenador_columna_editorial_ent.get()
	global num_pre
	num_pre = Csv_concatenador_columna_precio_ent.get()
	global num_tem
	num_tem = Csv_concatenador_columna_tema_ent.get()
	global csvcon
	csvcon = True
	toplevel_desdeCsv_concatenador.destroy()
def desdecsv_concatenador():
	#Toplevel de ingreso de datos
	global toplevel_desdeCsv_concatenador
	toplevel_desdeCsv_concatenador = Toplevel(window)
	toplevel_desdeCsv_concatenador.title("Ingresar Catálogo desde Csv")
	frame_DE = Frame(toplevel_desdeCsv_concatenador)
	frame_DE.pack()
	frame_DE2=Frame(toplevel_desdeCsv_concatenador)
	frame_DE2.pack()
	#Ingresar lista de publicaciones
	Csv_concatenador_libro_lab = Label(frame_DE, text="Inserte Libro de publicaciones:")
	Csv_concatenador_libro_lab.grid(column=1, row=2)
	Csv_concatenador_libro_lab2 = Label(frame_DE, text=".csv")
	Csv_concatenador_libro_lab2.grid(column=3, row=2)
	global Csv_concatenador_libro
	Csv_concatenador_libro = Entry(frame_DE, width=15)
	Csv_concatenador_libro.grid(column=2, row=2, padx=5, pady=5)
	Csv_concatenador_libro.insert(END,"EML")
	Csv_concatenador_columna_titulo_lab= Label(frame_DE, text="Inserte el número de columna de Título")
	Csv_concatenador_columna_titulo_lab.grid(column=1, row=4)
	global Csv_concatenador_columna_titulo_ent
	Csv_concatenador_columna_titulo_ent= Entry(frame_DE, width=5)
	Csv_concatenador_columna_titulo_ent.grid(column=2, row=4, padx=5, pady=5)
	Csv_concatenador_columna_titulo_ent.insert(END,"1")
	Csv_concatenador_columna_autor_lab= Label(frame_DE, text="Inserte el número de columna de Autor:")
	Csv_concatenador_columna_autor_lab.grid(column=1, row=5)
	global Csv_concatenador_columna_autor_ent
	Csv_concatenador_columna_autor_ent= Entry(frame_DE, width=5)
	Csv_concatenador_columna_autor_ent.grid(column=2, row=5, padx=5, pady=5)
	Csv_concatenador_columna_autor_ent.insert(END,"2")
	Csv_concatenador_columna_editorial_lab= Label(frame_DE, text="Inserte el número de columna de Editorial:")
	Csv_concatenador_columna_editorial_lab.grid(column=1, row=6)
	global Csv_concatenador_columna_editorial_ent
	Csv_concatenador_columna_editorial_ent= Entry(frame_DE, width=5)
	Csv_concatenador_columna_editorial_ent.grid(column=2, row=6, padx=5, pady=5)
	Csv_concatenador_columna_editorial_ent.insert(END,"3")
	Csv_concatenador_columna_isbn_lab= Label(frame_DE, text="Inserte el número de columna de ISBN:")
	Csv_concatenador_columna_isbn_lab.grid(column=1, row=7)
	global Csv_concatenador_columna_isbn_ent
	Csv_concatenador_columna_isbn_ent= Entry(frame_DE, width=5)
	Csv_concatenador_columna_isbn_ent.grid(column=2, row=7, padx=5, pady=5)
	Csv_concatenador_columna_isbn_ent.insert(END,"8")
	Csv_concatenador_columna_precio_lab= Label(frame_DE, text="Inserte el número de columna de Precio:")
	Csv_concatenador_columna_precio_lab.grid(column=1, row=8)
	global Csv_concatenador_columna_precio_ent
	Csv_concatenador_columna_precio_ent= Entry(frame_DE, width=5)
	Csv_concatenador_columna_precio_ent.grid(column=2, row=8, padx=5, pady=5)
	Csv_concatenador_columna_precio_ent.insert(END,"28")
	Csv_concatenador_columna_tema_lab= Label(frame_DE, text="Inserte el número de columna de Tema:")
	Csv_concatenador_columna_tema_lab.grid(column=1, row=9)
	global Csv_concatenador_columna_tema_ent
	Csv_concatenador_columna_tema_ent= Entry(frame_DE, width=5)
	Csv_concatenador_columna_tema_ent.grid(column=2, row=9, padx=5, pady=5)
	Csv_concatenador_columna_tema_ent.insert(END,"5")
	bot_guardar_catalogo = Button(frame_DE2, text="Guardar", command=cargarcsv)
	bot_guardar_catalogo.pack()

def concatenar():
	global excel
	global csvcon
	if excel == False and csvcon == False:
		mb.showerror("Error","No se ha cargado el catálogo")
	else:
		lista = ingreso.get()
		listas = lista.split()
		preisbns = listas[:]
		while len(listas)>0:
			for d in preisbns:
				deconstruirisbns(d, listas)
			for i in isbns:
				if i not in isbn_depurado:
					isbn_depurado.append(i)
			for isbnd in isbn_depurado:
				concatenado(isbnd)
				if excel==True:
					global sheet
					ga = (len(sheet['A'])+1)
					for x in range (1,ga):
						global excel_isbn_conc
						xrow = sheet.cell(row=x, column=excel_isbn_conc).value
						busqueda(xrow, isbnd, x)
					if isbnd not in en_la_base:
						no_en_la_base.append(isbnd)
				elif csvcon==True:
					busqudacsv(isbnd)
				#cuadro_resultado.insert(END, dic_titulopub[isbnd] + "," + isbnd + "," + imagenes[isbnd] + "," + isbnd + "," + dic_titulo[isbnd] + "," + dic_autor[isbnd] + "," + dic_editorial[isbnd])
		arbolgeneral()
		print(no_en_la_base)
		noenlabase()
		fin()
def isbn_con_error(isbn):
	mb.showinfo('Aviso', isbn + ' no pudo ser concatenado por no tener el formato adecuado')

def formato_correcto():
	mb.showinfo(
		'Formato correcto',
		'Los URLs deben ser ingresados en una línea separados por espacios.'
		+ '\n con la forma: http://***/ISBN001.jpg \n' +
		'Donde 001.jpg será la portada, 002.jpg será la contraportada \n'
		+ 'se puede incluir hasta 006.jpg.\n' +
		'El concatenador soporta ISBN 10 y EAN13'
		)
def desplegar_corrector_concat():
	global desplegable_corector
	desplegable_corector = Toplevel(window)
	desplegable_corector.title("Corrector")
	botonera_desplegable = Frame(desplegable_corector)
	botonera_desplegable.pack()
	boton_corregir= Button(botonera_desplegable,text="Guardar",command=corregir)
	boton_corregir.pack()
	frame2=Frame(desplegable_corector)
	frame2.pack(fill=BOTH, expand=1)

	canvas = Canvas(frame2)
	canvas.pack(side=LEFT, fill=BOTH, expand=1)

	scroll = ttk.Scrollbar(frame2, orient=VERTICAL, command=canvas.yview)
	scroll.pack(side=RIGHT, fill=Y)

	canvas.configure(yscrollcommand=scroll.set)
	canvas.bind('<Configure>', lambda e: canvas.configure(scrollregion=canvas.bbox("all")))

	panel_corrector = Frame(canvas)
	canvas.create_window((0,0), window=panel_corrector, anchor="nw")
	#panel_corrector= Frame(desplegable_corector)
	#panel_corrector.pack()
	x=0
	for isbn in en_la_base:
		label_titulo_publicacion = Label(panel_corrector, text=dic_titulopub[isbn][:59])
		label_titulo_publicacion.grid(column=0,row=x)
		entry_titulo_publicacion = Entry(panel_corrector, width=50)
		entry_titulo_publicacion.grid(column=0,row=x+1, padx=5, pady=5)
		entry_titulo_publicacion.insert(END, dic_titulopub[isbn])
		corregidos[isbn]=entry_titulo_publicacion
		label_isbn_correccion = Label(panel_corrector, text=dic_real_isbn[isbn])
		label_isbn_correccion.grid(column=1,row=x)
		entry_isbn_correccion = Entry(panel_corrector, width=20)
		entry_isbn_correccion.grid(column=1,row=x+1, padx=5, pady=5)
		entry_isbn_correccion.insert(END, dic_real_isbn[isbn])
		corregidos_isbn_concat[isbn]=entry_isbn_correccion
		label_precio_correccion = Label(panel_corrector, text=dic_precio[isbn])
		label_precio_correccion.grid(column=2,row=x)
		entry_precio_correccion = Entry(panel_corrector, width=10)
		entry_precio_correccion.grid(column=2,row=x+1, padx=5, pady=5)
		entry_precio_correccion.insert(END, dic_precio[isbn])
		corregidos_precio_concat[isbn]=entry_precio_correccion
		x+=2
def corregir():
	for isbn, corregido in corregidos.items():
		item=corregido.get()
		dic_titulopub[isbn]=item
	for isbn, correg in corregidos_isbn_concat.items():
		items=correg.get()
		dic_real_isbn[isbn]=items
	for isbn, corregi in corregidos_precio_concat.items():
		ite=corregi.get()
		dic_precio[isbn]=ite
	for item in arb.get_children():
   		arb.delete(item)
	arbolgeneral()
	global desplegable_corector
	desplegable_corector.destroy()
def publicar():
	if tok == False:
		mb.showerror("Error", "No hay token Cargado")
	else:
		for isbnd in en_la_base:
			imag_sub=imagenes[isbnd].split("; ")
			lista_para_subir = []
			for i in imag_sub:
				lista_para_subir.append({"source":i})
				print(i)
			print(lista_para_subir)
			url="https://api.mercadolibre.com/items"
			token=tok
			headers = {"Authorization": str("Bearer "+token)}
			data= {
			  "title": str(dic_titulopub[isbnd][:59]),
			  "category_id":"MLA412445",
			  "price":dic_precio[isbnd],
			  "currency_id":"ARS",
			  "available_quantity":1,
			  "buying_mode":"buy_it_now",
			  "condition":"new",
			  "listing_type_id":"gold_special",
			  "sale_terms":[
			     {
			        "id":"WARRANTY_TYPE",
			        "value_name":"Garantía del vendedor"
			     },
			     {
			        "id":"WARRANTY_TIME",
			        "value_name":"30 días"
			     }
			  ],
			  "pictures":lista_para_subir,
			  "shipping":{
			  	"mode":"me2",
			  	"local_pick_up": True,
			  	"logistic_type": "xd_drop_off"
			  },
			  "attributes":[
			     {
			        "id":"AUTHOR",
			        "value_name": dic_autor[isbnd]
			     },
			     {
			        "id":"BOOK_GENRE",
			        "value_name": dic_tema[isbnd]
			     },
			     {
			        "id":"BOOK_TITLE",
			        "value_name":dic_titulo[isbnd]
			     },
			     {
			        "id":"FORMAT",
			        "value_name":"Papel"
			     },
			     {
			        "id":"GTIN",
			        "value_name":dic_real_isbn[isbnd]
			     },
			     {
			        "id":"ITEM_CONDITION",
			        "value_name":"Nuevo"
			     },
			     {
			        "id":"LANGUAGE",
			        "value_name":"Español"
			     },
			     {
			        "id":"NARRATION_TYPE",
			        "value_name":dic_tema[isbnd]
			     },
			     {
			        "id":"PUBLISHER",
			        "value_name":dic_editorial[isbnd]
			     },
			     {
			        "id":"SELLER_SKU",
			        "value_name":isbnd
			     }
			  ]
			}
			req = requests.post(url, headers=headers, json=data)
			if req.status_code == 201:
				lista_publicados.append(isbnd)
			else:
				lista_no_publicados.append(isbnd)
				dic_no_publicados[isbnd] = req.content
		mb.showinfo("Proceso concluido", "Se publicaron "+str(len(lista_publicados))+" items")
#GUI

def excluidos():
	nv = Toplevel(window)
	cuadro_excluidos = Text(nv, width=75, height=25)
	cuadro_excluidos.pack()
	for isbndn in no_en_la_base:
		cuadro_excluidos.insert(END, isbndn + "," + imagenes[isbndn] + "\n")
def nopubicados():
	nv = Toplevel(window)
	cuadro_excluidos = Text(nv, width=75, height=25)
	cuadro_excluidos.pack()
	for isbndn in lista_no_publicados:
		cuadro_excluidos.insert(END, isbndn + "," + imagenes[isbndn] +"\n")
		print(dic_no_publicados[isbndn])
		print(type(dic_no_publicados[isbndn]))
	for isbndn in lista_no_publicados:
		bit = dic_no_publicados[isbndn].decode()
		cuadro_excluidos.insert(END, isbndn + "," + bit)

window = Tk()
window.title("Librería Losada")

frame = Frame(window)
frame.grid(column=0, row=0)
botonera_concatenador = Frame(window)
botonera_concatenador.grid(column=1, row=3)

bienvenida = Label(frame, text="Concatenador de imágenes")
bienvenida.grid(column=1, row=0)

ingrese = Label(
	frame,
	text="Ingrese URL de imágenes:"
	)

ingrese.grid(column=0, row=1)

ingreso = Entry(frame, width=75)
ingreso.grid(column=1, row=1, padx=5, pady=5)

boton = Button(botonera_concatenador, text="Concatenar URL", width=15, height=5, command=concatenar)
boton.grid(column=0, row=3,padx=5, pady=5)

boton_excel_concatenador = Button(botonera_concatenador, text="Cargar Excel", width=10, height=1, command=desdeExcel_concatenador)
boton_excel_concatenador.grid(column=0, row=1,padx=5, pady=5)
boton_csv_concatenador = Button(botonera_concatenador, text="Cargar CSV", width=10, height=1, command=desdecsv_concatenador)
boton_csv_concatenador.grid(column=1, row=1,padx=5, pady=5)
boton_toplevel_arbol = Button(botonera_concatenador, text="desplegar copiable", command=desplegar_copiableaexcel)
boton_toplevel_arbol.grid(column=0, row=4,padx=5, pady=5)
boton_de_formato = Button(botonera_concatenador, text="Ver formato correcto", command=formato_correcto)
boton_de_formato.grid(column=0, row=0,padx=5, pady=5)
boton_de_excluidos = Button(botonera_concatenador, text="Ver URLs excluidos", command=excluidos)
boton_de_excluidos.grid(column=1, row=4,padx=5, pady=5)
boton_de_corrector = Button(botonera_concatenador, text="Corregir títulos", command=desplegar_corrector_concat)
boton_de_corrector.grid(column=1, row=3,padx=5, pady=5)
boton_de_corrector = Button(botonera_concatenador, text="Publicar por API", command=publicar)
boton_de_corrector.grid(column=0, row=5,padx=5, pady=5)
boton_de_corrector = Button(botonera_concatenador, text="Errores de publicación", command=nopubicados)
boton_de_corrector.grid(column=1, row=5,padx=5, pady=5)
bot_obtener_token = Button(botonera_concatenador, text="Obtener Token", command=revisar_tokenpresxistente)
bot_obtener_token.grid(column=0, row=6, padx=5, pady=5)

resultado = Label(frame, text="URL concatenados:")
resultado.grid(column=0, row=2, padx=5, pady=5),

frame_arbol=Frame(window)
frame_arbol.grid(column=0, row=3, padx=5, pady=5)
arb = ttk.Treeview(frame_arbol)
arb['columns']=('Título de publicación','ISBN','Imágenes','SKU','cantidad','precio','tema','título','autor','editorial')
arb.column('#0', width=0, stretch=NO)
arb.column('Título de publicación', anchor=W, width=340)
arb.column('ISBN', anchor=CENTER, width=70)
arb.column('Imágenes', anchor=CENTER, width=20)
arb.column('SKU', anchor=CENTER, width=20)
arb.column('cantidad', anchor=CENTER, width=40)
arb.column('precio', anchor=CENTER, width=40)
arb.column('tema', anchor=CENTER, width=80)
arb.column('título', anchor=CENTER, width=80)
arb.column('autor', anchor=CENTER, width=80)
arb.column('editorial', anchor=CENTER, width=80)

arb.heading('#0', text='',anchor=CENTER)
arb.heading('Título de publicación', text='Título de publicación',anchor=CENTER)
arb.heading('ISBN', text='ISBN',anchor=CENTER)
arb.heading('Imágenes', text='Imágenes',anchor=CENTER)
arb.heading('SKU', text='SKU',anchor=CENTER)
arb.heading('cantidad', text='cantidad',anchor=CENTER)
arb.heading('precio', text='precio',anchor=CENTER)
arb.heading('tema', text='tema',anchor=CENTER)
arb.heading('título', text='título',anchor=CENTER)
arb.heading('autor', text='autor',anchor=CENTER)
arb.heading('editorial', text='editorial',anchor=CENTER)
"""
cuadro_resultado = Text(frame, width=75, height=25)
cuadro_resultado.grid(column=1, row=3, padx=5, pady=5)

scroll = Scrollbar(frame, command=cuadro_resultado.yview)
scroll.grid(column=2, row=3, sticky="nsew")
cuadro_resultado.config(yscrollcommand=scroll.set)
"""

window.mainloop()


from django.urls import path
from .views import (
    create_blog_view,
    detail_blog_view,
    edit_blog_view,
    delete_blog_view,
    delete_comment_view,
    post_list_view,
    up_vote_view,
)

app_name = 'forum'

urlpatterns = [
    path('', post_list_view, name="post_list"),
    path('create/', create_blog_view, name="create"),
    path('<id>/<title>/', detail_blog_view, name="detail"),
    path('<id>/<title>/edit/', edit_blog_view, name="edit"),
    path('<id>/<title>/delete/', delete_blog_view, name='delete'),

    # comments
    path('<id>/<title>/comment/<cid>/delete', delete_comment_view, name='comment_delete'),

    # vote
    path('up/<id>/<title>', up_vote_view, name='up_vote'),

]