import torch
import torch.nn as nn
import faiss
import numpy as np
import math
from copy import deepcopy

def robust_norm(var, dim=2):
    return ((var ** 2).sum(dim=dim) + 1e-8).sqrt()

class FScore():
    def __init__(self, device):
        self.dimension = 3
        self.k = 1
        #
        self.device = device
        self.gpu_id = torch.cuda.current_device()
        self.faiss_gpu = hasattr(faiss, 'StandardGpuResources')

        if self.faiss_gpu:
            # we need only a StandardGpuResources per GPU
            self.res = faiss.StandardGpuResources()
            # self.res.setTempMemoryFraction(0.1)
            #self.res.setTempMemory(
            #    4 * (1024 * 1024 * 1024)
            #)  # Bytes, the single digit is basically GB)
            self.flat_config = faiss.GpuIndexFlatConfig()
            self.flat_config.device = self.gpu_id

        # place holder
        self.forward_loss = torch.FloatTensor([0])
        self.backward_loss = torch.FloatTensor([0])

    def build_nn_index(self, database):
        """
        :param database: numpy array of Nx3
        :return: Faiss index, in CPU
        """
        # index = faiss.GpuIndexFlatL2(self.res, self.dimension, self.flat_config)  # dimension is 3
        index_cpu = faiss.IndexFlatL2(self.dimension)

        if self.faiss_gpu:
            index = faiss.index_cpu_to_gpu(self.res, self.gpu_id, index_cpu)
        else:
            index = index_cpu

        index.add(database)
        return index

    def search_nn(self, index, query, k):
        """
        :param index: Faiss index
        :param query: numpy array of Nx3
        :return: D: Variable of Nxk, type FloatTensor, in GPU
                 I: Variable of Nxk, type LongTensor, in GPU
        """
        D, I = index.search(query, k)

        D_var = torch.from_numpy(np.ascontiguousarray(D))
        I_var = torch.from_numpy(np.ascontiguousarray(I).astype(np.int64))
        if self.gpu_id >= 0:
            D_var = D_var.to(self.device)
            I_var = I_var.to(self.device)

        return D_var, I_var

    def getAvgDist(self, index, query):
        D, I = index.search(query, 2)

        m_d = math.sqrt(np.percentile(D[:,1],90))
        return m_d

    def getOpMatch(self, points):
        return (points.max(axis = 0) - points.min(axis = 0)).max() / 100

    def score(self, predict_pc_6, gt_pc_6, use_normals=True):
        """
        :param predict_pc: Bx3xM Variable in GPU
        :param gt_pc: Bx3xN Variable in GPU
        :return:
        """
        if self.gpu_id >= 0:
            predict_pc_6 = predict_pc_6.to(self.device)
            gt_pc_6 = gt_pc_6.to(self.device)

        predict_pc = predict_pc_6[:, :3, :]
        gt_pc = gt_pc_6[:, :3, :]
        #
        predict_pcn = predict_pc_6[:, 3:, :]
        gt_pcn = gt_pc_6[:, 3:, :]

        predict_pc_size = predict_pc.size()
        gt_pc_size = gt_pc.size()

        predict_pc_np = np.ascontiguousarray(
            torch.transpose(predict_pc.data.clone(), 1, 2).cpu().numpy()
        )  # BxMx3
        gt_pc_np = np.ascontiguousarray(
            torch.transpose(gt_pc.data.clone(), 1, 2).cpu().numpy()
        )  # BxNx3

        # selected_gt: Bxkx3xM
        selected_gt_by_predict = torch.FloatTensor(
            predict_pc_size[0], self.k, predict_pc_size[1], predict_pc_size[2]
        )
        # selected_predict: Bxkx3xN
        selected_predict_by_gt = torch.FloatTensor(
            gt_pc_size[0], self.k, gt_pc_size[1], gt_pc_size[2]
        )
        if use_normals:
            # normals
            selected_gt_by_predictn = torch.FloatTensor(
                predict_pc_size[0], self.k, predict_pc_size[1], predict_pc_size[2]
            )
            selected_predict_by_gtn = torch.FloatTensor(
                gt_pc_size[0], self.k, gt_pc_size[1], gt_pc_size[2]
            )

        if self.gpu_id >= 0:
            selected_gt_by_predict = selected_gt_by_predict.to(self.device)
            selected_predict_by_gt = selected_predict_by_gt.to(self.device)
            if use_normals:
                selected_gt_by_predictn = selected_gt_by_predictn.to(self.device)
                selected_predict_by_gtn = selected_predict_by_gtn.to(self.device)

        # process each batch independently.
        for i in range(predict_pc_np.shape[0]):
            index_predict = self.build_nn_index(predict_pc_np[i])
            index_gt = self.build_nn_index(gt_pc_np[i])

            # database is gt_pc, predict_pc -> gt_pc -----------------------------------------------------------
            _, I_var = self.search_nn(index_gt, predict_pc_np[i], self.k)

            # process nearest k neighbors
            for k in range(self.k):
                selected_gt_by_predict[i, k, ...] = gt_pc[i].index_select(
                    1, I_var[:, k]
                )
                if use_normals:
                    selected_gt_by_predictn[i, k, ...] = gt_pcn[i].index_select(
                        1, I_var[:, k]
                    )

            # database is predict_pc, gt_pc -> predict_pc -------------------------------------------------------
            _, I_var = self.search_nn(index_predict, gt_pc_np[i], self.k)

            # process nearest k neighbors
            for k in range(self.k):
                selected_predict_by_gt[i, k, ...] = predict_pc[i].index_select(
                    1, I_var[:, k]
                )
                if use_normals:
                    selected_predict_by_gtn[i, k, ...] = predict_pcn[i].index_select(
                        1, I_var[:, k]
                    )

        index_gt = self.build_nn_index(gt_pc_np[i])

        dist = self.getAvgDist(index_gt, gt_pc_np[0])

        # compute loss ===================================================
        # selected_gt(Bxkx3xM) vs predict_pc(Bx3xM)
        r_to_gt = predict_pc.unsqueeze(1).expand_as(selected_gt_by_predict) - selected_gt_by_predict #Forward as in reconstructed to ground truth?
        gt_to_r = selected_predict_by_gt - gt_pc.unsqueeze(1).expand_as(selected_predict_by_gt) #Backward as in ground truth to reconstructed?

        r_to_gt = robust_norm(
            selected_gt_by_predict
            - predict_pc.unsqueeze(1).expand_as(selected_gt_by_predict),
            dim=2
        ).cpu().detach().numpy()

        gt_to_r = robust_norm(
            selected_predict_by_gt
            - gt_pc.unsqueeze(1).expand_as(selected_predict_by_gt),
            dim=2
        ).cpu().detach().numpy()

        r_to_gt = r_to_gt.flatten()
        gt_to_r = gt_to_r.flatten()

        ones = np.ones(r_to_gt.shape)

        dt = dist

        precision = (100 / ones.shape[0]) * np.sum(ones[r_to_gt < dt])
        recall = (100 / ones.shape[0]) * np.sum(ones[gt_to_r < dt])

        return (2*precision*recall) / (precision + recall + 1e-8)

class ChamferLoss(nn.Module):
    def __init__(self, device):
        super(ChamferLoss, self).__init__()
        self.dimension = 3
        self.k = 1
        #
        self.device = device
        self.gpu_id = torch.cuda.current_device()

        self.faiss_gpu = hasattr(faiss, 'StandardGpuResources')
        if self.faiss_gpu:
            # we need only a StandardGpuResources per GPU
            self.res = faiss.StandardGpuResources()
            # self.res.setTempMemoryFraction(0.1)
            #self.res.setTempMemory(
            #    4 * (1024 * 1024 * 1024)
            #)  # Bytes, the single digit is basically GB)
            self.flat_config = faiss.GpuIndexFlatConfig()
            self.flat_config.device = self.gpu_id

    def build_nn_index(self, database):
        """
        :param database: numpy array of Nx3
        :return: Faiss index, in CPU
        """
        # index = faiss.GpuIndexFlatL2(self.res, self.dimension, self.flat_config)  # dimension is 3
        index_cpu = faiss.IndexFlatL2(self.dimension)

        if self.faiss_gpu:
            index = faiss.index_cpu_to_gpu(self.res, self.gpu_id, index_cpu)
        else:
            index = index_cpu

        index.add(database)
        return index

    def search_nn(self, index, query, k):
        """
        :param index: Faiss index
        :param query: numpy array of Nx3
        :return: D: Variable of Nxk, type FloatTensor, in GPU
                 I: Variable of Nxk, type LongTensor, in GPU
        """
        D, I = index.search(query, k)

        D_var = torch.from_numpy(np.ascontiguousarray(D))
        I_var = torch.from_numpy(np.ascontiguousarray(I).astype(np.int64))
        if self.gpu_id >= 0:
            D_var = D_var.to(self.device)
            I_var = I_var.to(self.device)

        return D_var, I_var

    def forward(self, predict_pc_6, gt_pc_6, thresh, keep_dim=False, use_normals=True):
        """
        :param predict_pc: Bx3xM Variable in GPU
        :param gt_pc: Bx3xN Variable in GPU
        :return:
        """

        predict_pc = predict_pc_6[:, :3, :]
        gt_pc = gt_pc_6[:, :3, :]
        #
        if use_normals:
            predict_pcn = predict_pc_6[:, 3:, :]
            gt_pcn = gt_pc_6[:, 3:, :]

        predict_pc_size = predict_pc.size()
        gt_pc_size = gt_pc.size()

        predict_pc_np = np.ascontiguousarray(
            torch.transpose(predict_pc.data.clone(), 1, 2).cpu().numpy()
        )  # BxMx3
        gt_pc_np = np.ascontiguousarray(
            torch.transpose(gt_pc.data.clone(), 1, 2).cpu().numpy()
        )  # BxNx3

        # selected_gt: Bxkx3xM
        selected_gt_by_predict = torch.FloatTensor(
            predict_pc_size[0], self.k, predict_pc_size[1], predict_pc_size[2]
        )
        # selected_predict: Bxkx3xN
        selected_predict_by_gt = torch.FloatTensor(
            gt_pc_size[0], self.k, gt_pc_size[1], gt_pc_size[2]
        )

        if use_normals:
            # normals
            selected_gt_by_predictn = torch.FloatTensor(
                predict_pc_size[0], self.k, predict_pc_size[1], predict_pc_size[2]
            )
            selected_predict_by_gtn = torch.FloatTensor(
                gt_pc_size[0], self.k, gt_pc_size[1], gt_pc_size[2]
            )

        if self.gpu_id >= 0:
            selected_gt_by_predict = selected_gt_by_predict.to(self.device)
            selected_predict_by_gt = selected_predict_by_gt.to(self.device)
            if use_normals:
                selected_gt_by_predictn = selected_gt_by_predictn.to(self.device)
                selected_predict_by_gtn = selected_predict_by_gtn.to(self.device)

        # process each batch independently.
        for i in range(predict_pc_np.shape[0]):
            index_predict = self.build_nn_index(predict_pc_np[i])
            index_gt = self.build_nn_index(gt_pc_np[i])

            # database is gt_pc, predict_pc -> gt_pc -----------------------------------------------------------
            _, I_var = self.search_nn(index_gt, predict_pc_np[i], self.k)

            # process nearest k neighbors
            for k in range(self.k):
                selected_gt_by_predict[i, k, ...] = gt_pc[i].index_select(
                    1, I_var[:, k]
                )
                if use_normals:
                    selected_gt_by_predictn[i, k, ...] = gt_pcn[i].index_select(
                        1, I_var[:, k]
                    )

            # database is predict_pc, gt_pc -> predict_pc -------------------------------------------------------
            _, I_var = self.search_nn(index_predict, gt_pc_np[i], self.k)

            # process nearest k neighbors
            for k in range(self.k):
                selected_predict_by_gt[i, k, ...] = predict_pc[i].index_select(
                    1, I_var[:, k]
                )
                if use_normals:
                    selected_predict_by_gtn[i, k, ...] = predict_pcn[i].index_select(
                        1, I_var[:, k]
                    )

        # compute loss ===================================================

        # selected_gt(Bxkx3xM) vs predict_pc(Bx3xM)
        forward_loss_element = robust_norm(
            selected_gt_by_predict
            - predict_pc.unsqueeze(1).expand_as(selected_gt_by_predict)
        )
        self.forward_loss = forward_loss_element.mean()
        self.forward_loss_array = forward_loss_element.mean(dim=1).mean(dim=1)

        # selected_predict(Bxkx3xN) vs gt_pc(Bx3xN)
        backward_loss_element = robust_norm(
            selected_predict_by_gt
            - gt_pc.unsqueeze(1).expand_as(selected_predict_by_gt)
        )  # BxkxN
        self.backward_loss = backward_loss_element.mean()
        self.backward_loss_array = backward_loss_element.mean(dim=1).mean(dim=1)
        #

        if keep_dim:
            self.forward_loss = torch.relu(forward_loss_element - thresh).squeeze(1).mean(dim=1)
            self.backward_loss = torch.relu(backward_loss_element - thresh).squeeze(1).mean(dim=1)
            return self.forward_loss + self.backward_loss
        else:
            self.forward_loss = torch.relu(forward_loss_element.flatten() - thresh).mean()
            self.backward_loss = torch.relu(backward_loss_element.flatten() - thresh).mean()
            return self.forward_loss + self.backward_loss

    def __call__(self, predict_pc, gt_pc, ang_wt, keep_dim=False):
        # start_time = time.time()
        loss = self.forward(predict_pc, gt_pc, ang_wt, keep_dim)
        # print(time.time()w-start_time)
        return loss

def weighted_mae_loss(input, target, weight):
    return torch.sum(weight * (input - target).abs())

closs = torch.nn.BCEWithLogitsLoss(reduction='sum', pos_weight = torch.tensor(0.2))
celoss = nn.CrossEntropyLoss(reduction='sum')

# 0 -> start
# 1 -> Cuboid
# 2 -> attach
# 3 -> reflect
# 4 -> translate
# 5 -> squeeze
# 6 -> end

# 0 - 7 -> commandIndex
# 7 -> 18 -> cuboid1
# 18 -> 29 -> cuboid2
# 29 -> 40 -> cuboid3
# 40 -> 43 -> l,h,w
# 43 -> 46 -> x1,y1,z1
# 46 -> 49 -> x2,y2,z2
# 49 - 52 -> symaxis
# 52 -> num
# 53 -> scale
# 54 - 60 face
# 60 - 62 - UV
# 62 -> aligned

# BBOX DIMS 40 42

class ProgLoss(nn.Module):
    def forward(self, pred, target, weight):

        if target.shape[1] > pred.shape[1]:
            target = target[:,:pred.shape[1],:]
            weight = weight[:,:pred.shape[1],:]

        commands = torch.argmax(target[:,:,:7], dim = 2).flatten()
        pcommands = torch.argmax(pred[:,:,:7], dim = 2).flatten()

        cmdc = (commands == pcommands).sum().item() * 1.0

        cmd_loss = celoss(
            pred[:,:,:7].view(-1,7),
            commands
        )

        cub_inds = (commands==1).nonzero().flatten()
        ap_inds = (commands==2).nonzero().flatten()
        ref_inds = (commands==3).nonzero().flatten()
        trans_inds = (commands==4).nonzero().flatten()
        sq_inds = (commands==5).nonzero().flatten()

        cub_prm_loss = 0.
        align_loss = 0.
        align_num_pos = 0.
        align_num_neg = 0.
        align_posc = 0.
        align_negc = 0.

        if cub_inds.sum() > 0:
            cub_prm_loss = weighted_mae_loss(
                pred[:,cub_inds,:], target[:,cub_inds,:], weight[:,cub_inds,:]
            )

        if cub_inds.sum() > 1:
            align_pos_inds = cub_inds[1:][(target[:, cub_inds[1:], 62].flatten() == 1.).nonzero().flatten()]
            align_neg_inds = cub_inds[1:][(target[:, cub_inds[1:], 62].flatten() == 0.).nonzero().flatten()]

            align_num_pos += align_pos_inds.shape[0]
            align_num_neg += align_neg_inds.shape[0]

            align_loss = closs(
                pred[:, cub_inds[1:], 62].flatten(),
                target[:, cub_inds[1:], 62].flatten()
            )

            align_posc = (pred[:, align_pos_inds, 62] > 0.).sum().float()
            align_negc = (pred[:, align_neg_inds, 62] <= 0.).sum().float()

        xyz_prm_loss = 0
        cubc = 0
        ap_cub_loss = 0

        if ap_inds.sum() > 0:

            xyz_prm_loss = weighted_mae_loss(
                pred[:,ap_inds,:], target[:,ap_inds,:], weight[:,ap_inds,:]
            )

            ap_cube_1s = torch.argmax(target[:,ap_inds,7:18], dim=2).flatten()
            ap_cube_2s = torch.argmax(target[:,ap_inds,18:29], dim=2).flatten()

            ap_pcube_1s = torch.argmax(pred[:,ap_inds,7:18], dim=2).flatten()
            ap_pcube_2s = torch.argmax(pred[:,ap_inds,18:29], dim=2).flatten()

            ap_cubc = ((ap_pcube_1s == ap_cube_1s) * (ap_pcube_2s == ap_cube_2s)).sum().item() * 1.0

            cubc = ap_cubc

            ap_cub_loss = celoss(
                pred[:,ap_inds,7:18].view(-1, 11),
                ap_cube_1s
            )

            ap_cub_loss += celoss(
                pred[:,ap_inds,18:29].view(-1, 11),
                ap_cube_2s
            )

        cub_loss = ap_cub_loss

        axisc = 0.
        axis_loss = 0.
        sym_cubc = 0.
        sym_cub_loss = 0.
        sym_prm_loss = 0.

        if ref_inds.sum() > 0:
            ref_cube_1s = torch.argmax(target[:,ref_inds,7:18], dim=2).flatten()
            ref_pcube_1s = torch.argmax(pred[:,ref_inds,7:18], dim=2).flatten()

            ref_cubc = ((ref_pcube_1s == ref_cube_1s)).sum().item() * 1.0

            ref_axis = torch.argmax(target[:, ref_inds, 49:52], dim=2).flatten()
            ref_paxis = torch.argmax(pred[:, ref_inds, 49:52], dim=2).flatten()
            ref_axisc = ((ref_paxis == ref_axis)).sum().item() * 1.0

            ref_axis_loss = celoss(
                pred[:,ref_inds,49:52].view(-1, 3),
                ref_axis
            )

            ref_cub_loss = celoss(
                pred[:,ref_inds,7:18].view(-1, 11),
                ref_cube_1s
            )

            axisc += ref_axisc
            axis_loss += ref_axis_loss
            sym_cubc += ref_cubc
            sym_cub_loss += ref_cub_loss

        if trans_inds.sum() > 0:

            trans_cube_1s = torch.argmax(target[:,trans_inds,7:18], dim=2).flatten()
            trans_pcube_1s = torch.argmax(pred[:,trans_inds,7:18], dim=2).flatten()

            trans_cubc = ((trans_pcube_1s == trans_cube_1s)).sum().item() * 1.0

            trans_axis = torch.argmax(target[:, trans_inds, 49:52], dim=2).flatten()
            trans_paxis = torch.argmax(pred[:, trans_inds, 49:52], dim=2).flatten()
            trans_axisc = ((trans_paxis == trans_axis)).sum().item() * 1.0
            trans_axis_loss = celoss(
                pred[:,trans_inds,49:52].view(-1, 3),
                trans_axis
            )

            trans_cub_loss = celoss(
                pred[:,trans_inds,7:18].view(-1, 11),
                trans_cube_1s
            )

            trans_prm_loss = weighted_mae_loss(
                pred[:,trans_inds,:], target[:,trans_inds,:], weight[:,trans_inds,:]
            )

            axisc += trans_axisc
            axis_loss += trans_axis_loss
            sym_cubc += trans_cubc
            sym_cub_loss += trans_cub_loss
            sym_prm_loss += trans_prm_loss

        uv_prm_loss = 0
        sq_cubc = 0
        sq_cub_loss = 0
        face_loss = 0
        facec = 0

        if sq_inds.sum() > 0:

            uv_prm_loss = weighted_mae_loss(
                pred[:,sq_inds,:],
                target[:,sq_inds,:],
                weight[:,sq_inds,:]
            )

            sq_cube_1s = torch.argmax(target[:,sq_inds,7:18], dim=2).flatten()
            sq_cube_2s = torch.argmax(target[:,sq_inds,18:29], dim=2).flatten()
            sq_cube_3s = torch.argmax(target[:,sq_inds,29:40], dim=2).flatten()
            faces = torch.argmax(target[:, sq_inds, 54:60], dim=2).flatten()

            sq_pcube_1s = torch.argmax(pred[:,sq_inds,7:18], dim=2).flatten()
            sq_pcube_2s = torch.argmax(pred[:,sq_inds,18:29], dim=2).flatten()
            sq_pcube_3s = torch.argmax(pred[:,sq_inds,29:40], dim=2).flatten()
            pfaces = torch.argmax(pred[:,sq_inds,54:60], dim=2).flatten()

            sq_cubc = (
                (sq_pcube_1s == sq_cube_1s) * \
                (sq_pcube_2s == sq_cube_2s) * \
                (sq_pcube_3s == sq_cube_3s)
            ).sum().item() * 1.0

            facec = (faces == pfaces).sum().item() * 1.0

            sq_cub_loss = celoss(
                pred[:,sq_inds,7:18].view(-1, 11),
                sq_cube_1s
            )

            sq_cub_loss += celoss(
                pred[:,sq_inds,18:29].view(-1, 11),
                sq_cube_2s
            )

            sq_cub_loss += celoss(
                pred[:,sq_inds,29:40].view(-1, 11),
                sq_cube_3s
            )

            face_loss = celoss(
                pred[:,sq_inds,54:60].view(-1, 6),
                faces
            )

        losses = {
            'cmd': cmd_loss,
            'cub_prm': cub_prm_loss,
            'xyz_prm': xyz_prm_loss,
            'uv_prm': uv_prm_loss,
            'sym_prm': sym_prm_loss,#
            'cub': cub_loss,
            'sq_cub': sq_cub_loss,
            'sym_cub': sym_cub_loss,#
            'axis': axis_loss,#
            'face': face_loss,
            'cmdc': cmdc,
            'cubc': cubc,
            'sq_cubc': sq_cubc,
            'sym_cubc': sym_cubc,#
            'axisc': axisc,#
            'facec': facec,
            'align': align_loss,
            'palignc': align_posc,
            'nalignc': align_negc,
            'nan': align_num_neg,
            'nap': align_num_pos,
            'na': ap_inds.shape[0] * 1.0,
            'nc': cub_inds.shape[0] * 1.0,
            'ns': (ref_inds.shape[0] * 1.0) + (trans_inds.shape[0] * 1.0),
            'nsq': sq_inds.shape[0] * 1.0
        }
        return losses


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations
import smart_selects.db_fields
import multiselectfield.db.fields
from django.conf import settings
import django.core.validators

class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('lugar', '__first__'),
        ('organizacion', '0001_initial'),
    ]

    operations = [
        migrations.CreateModel(
            name='Actividades_Produccion',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('nombre', models.CharField(max_length=200)),
            ],
            options={
                'verbose_name': 'Actividad de Producci\xf3n',
                'verbose_name_plural': 'Actividades de Producci\xf3n',
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='Adicional',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('interes', models.IntegerField(blank=True, null=True, verbose_name=b'Tiene interes en ampliar las \xc3\xa1reas de cacao', choices=[(1, b'Si'), (2, b'No')])),
                ('cuanto', models.FloatField(default=b'0', null=True, blank=True)),
            ],
            options={
                'verbose_name': 'Amplici\xf3n \xe1reas de cacao',
                'verbose_name_plural': 'Amplici\xf3n \xe1reas de cacao',
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='Area_Cacao',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('area', models.FloatField(verbose_name=b'\xc3\x81rea total de cacao establecida en finca(Mz)')),
            ],
            options={
                'verbose_name': '9 \xc1rea de cacao en finca',
                'verbose_name_plural': '9 \xc1rea de cacao en fincas',
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='Beneficios',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('beneficio', models.CharField(max_length=200)),
            ],
            options={
                'verbose_name': 'Beneficio',
                'verbose_name_plural': 'Beneficios',
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='Capacitaciones_Socioeconomicas',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('capacitaciones_socio', models.IntegerField(verbose_name=b'Capacitaciones', choices=[(1, b'Formaci\xc3\xb3n y fortalecimiento organizacional'), (2, b'Contabilidad b\xc3\xa1sica y administraci\xc3\xb3n'), (3, b'Equidad de g\xc3\xa9nero'), (4, b'Manejo de cr\xc3\xa9ditos'), (5, b'Administraci\xc3\xb3n de peque\xc3\xb1os negocios'), (6, b'Gesti\xc3\xb3n empresarial'), (7, b'Cadena de valor de cacao'), (8, b'Transformaci\xc3\xb3n de cacao')])),
                ('opciones_socio', multiselectfield.db.fields.MultiSelectField(max_length=7, verbose_name=b'Opciones', choices=[(1, b'Jefe familia var\xc3\xb3n'), (2, b'Jefa familia mujer'), (3, b'Hijos'), (4, b'Hijas')])),
            ],
            options={
                'verbose_name': '13.2 Capacitaciones socioecon\xf3mico/org',
                'verbose_name_plural': '13.2 Capacitaciones socioecon\xf3mico/org',
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='Capacitaciones_Tecnicas',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('capacitaciones', models.IntegerField(choices=[(1, b'Regular en sombra'), (2, b'Poda'), (3, b'Manejo de plagas y enfermedades'), (4, b'Elaboraci\xc3\xb3n de abonos org\xc3\xa1nicos'), (5, b'Elaboraci\xc3\xb3n de productos para control de plagas'), (6, b'Establecimiento de vivero'), (7, b'Injertaci\xc3\xb3n de cacao'), (8, b'Selecci\xc3\xb3n de \xc3\xa1rboles \xc3\xa9lites para producci\xc3\xb3n de semillas'), (9, b'Manejo de post-cosecha (selecci\xc3\xb3n, cosecha, fermentado, secado)'), (10, b'Manejo de calidad de cacao'), (11, b'Certificaci\xc3\xb3n org\xc3\xa1nica')])),
                ('opciones', multiselectfield.db.fields.MultiSelectField(max_length=7, choices=[(1, b'Jefe familia var\xc3\xb3n'), (2, b'Jefa familia mujer'), (3, b'Hijos'), (4, b'Hijas')])),
            ],
            options={
                'verbose_name': '13.1 Capacitaci\xf3n familia',
                'verbose_name_plural': '13.1 Capacitaci\xf3n familia',
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='Caracterizacion_Terreno',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('textura_suelo', models.IntegerField(verbose_name=b'\xc2\xbfCu\xc3\xa1l es el tipo de textura del suelo?', choices=[(1, b'Arcilloso'), (2, b'Limoso'), (3, b'Arenoso'), (4, b'Franco'), (5, b'Franco arenoso')])),
                ('pendiente_terreno', models.IntegerField(verbose_name=b'\xc2\xbfCu\xc3\xa1l es la pendiente del terreno?', choices=[(1, b'Plana'), (2, b'Inclinada'), (3, b'Muy inclinada')])),
                ('contenido_hojarasca', models.IntegerField(verbose_name=b'\xc2\xbfC\xc3\xb3mo en el contenido de hojarasca?', choices=[(1, b'Alta'), (2, b'Medio'), (3, b'Baja')])),
                ('porfundidad_suelo', models.IntegerField(verbose_name=b'\xc2\xbfCu\xc3\xa1l es la profundidad de suelo?', choices=[(1, b'Poco profundo'), (2, b'Medio profundo'), (3, b'Muy profundo')])),
                ('drenaje_suelo', models.IntegerField(verbose_name=b'\xc2\xbfC\xc3\xb3mo en el drenaje del suelo?', choices=[(1, b'Bueno'), (2, b'Regular'), (3, b'Malo')])),
            ],
            options={
                'verbose_name': '5 Caracterizaci\xf3n de terreno',
                'verbose_name_plural': '5 Caracterizaci\xf3n de terreno',
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='Certificacion',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('cacao_certificado', models.IntegerField(verbose_name=b'Posee \xc3\xa1reas de cacao certificada', choices=[(1, b'Si'), (2, b'No')])),
                ('mant_area_cacao', models.FloatField(null=True, verbose_name=b'Mantenimiento de \xc3\xa1rea de cacao (C$)', blank=True)),
                ('mant_area_finca', models.FloatField(null=True, verbose_name=b'Mantenimiento de la finca (C$)', blank=True)),
                ('costo_certificacion', models.FloatField(null=True, verbose_name=b'Costo de estar certificado', blank=True)),
            ],
            options={
                'verbose_name': '10-1 Tipo de certificaci\xf3n que posee',
                'verbose_name_plural': '10-1 Tipo de certificaci\xf3n que posee',
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='Comercializacion_Cacao',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('producto', models.IntegerField(choices=[(1, b'Mazorca de cacao (unidad)'), (2, b'Semilla para siembra (unidad)'), (3, b'Cacao en baba (qq)'), (4, b'Cacao rojo sin fermentar (qq)'), (5, b'Cacao fermentado (lb)'), (6, b'Chocolate artesanal (lb)'), (7, b'Cacao en polvo (lb)'), (8, b'Cacao procesado/ pinolillo (lb)'), (9, b'Cajeta de cacao (lb)'), (10, b'Pasta de cacao (lb)'), (11, b'Vino de cacao (lt)')])),
                ('auto_consumo', models.FloatField(verbose_name=b'Auto-consumo')),
                ('venta', models.FloatField()),
                ('precio_venta', models.FloatField(verbose_name=b'Precio venta por unidad')),
                ('quien_vende', multiselectfield.db.fields.MultiSelectField(max_length=7, verbose_name=b'\xc2\xbfA qui\xc3\xa9n le vende?', choices=[(1, b'Comunidad'), (2, b'Intermediario'), (3, b'Mercado'), (4, b'Cooperativa')])),
                ('donde_vende', models.ManyToManyField(to='lugar.Municipio', verbose_name=b'\xc2\xbfD\xc3\xb3nde lo vende?')),
            ],
            options={
                'verbose_name': '12 Comercializaci\xf3n de cacao',
                'verbose_name_plural': '12 Comercializaci\xf3n de cacao',
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='Distancia_Comercio_Cacao',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('distancia', models.FloatField()),
            ],
            options={
                'verbose_name': '12.1 Distancia recorrida (Km)',
                'verbose_name_plural': '12.1 Distancia recorrida (Km)',
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='Educacion',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('rango', models.IntegerField(verbose_name=b'Selecci\xc3\xb3n', choices=[(1, b'Hombres mayores 31 a\xc3\xb1os'), (2, b'Mujeres mayores 31 a\xc3\xb1os'), (3, b'Hombre joven 19 a 30 a\xc3\xb1os'), (4, b'Mujer joven 19 a 30 a\xc3\xb1os'), (5, b'Hombre adoles. 13 a 18 a\xc3\xb1os'), (6, b'Mujer adoles. 13 a 18 a\xc3\xb1os'), (7, b'Ni\xc3\xb1os 0 a 12 a\xc3\xb1os'), (8, b'Ni\xc3\xb1as 0 a 12 a\xc3\xb1os'), (9, b'Ancianos (> 64 a\xc3\xb1os)')])),
                ('numero_total', models.IntegerField()),
                ('no_lee_ni_escribe', models.IntegerField()),
                ('primaria_incompleta', models.IntegerField()),
                ('primaria_completa', models.IntegerField()),
                ('secundaria_incompleta', models.IntegerField()),
                ('bachiller', models.IntegerField()),
                ('universitario_tecnico', models.IntegerField()),
                ('viven_fuera', models.IntegerField(verbose_name=b'N\xc3\xbamero de personas que viven fuera de la finca')),
            ],
            options={
                'verbose_name': '1-2 Nivel de educaci\xf3n de la Familia',
                'verbose_name_plural': '1-2 Nivel de educaci\xf3n de la Familia',
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='Encuesta',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('fecha', models.DateField()),
                ('anno', models.IntegerField()),
                ('organizacion', models.ForeignKey(verbose_name=b'Organizaci\xc3\xb3n', to='organizacion.Organizacion')),
            ],
            options={
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='Familia',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('miembros', models.IntegerField(verbose_name=b'N\xc3\xbamero de miembros')),
                ('encuesta', models.ForeignKey(to='monitoreo.Encuesta')),
            ],
            options={
                'verbose_name': '1-1 Miembros de la Familia',
                'verbose_name_plural': '1-1 Miembros de la Familia',
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='Fenomenos_Naturales',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('sequia', models.IntegerField(verbose_name=b'Sequ\xc3\xada', choices=[(1, b'Fuerte'), (2, b'Poco fuerte'), (3, b'Leve'), (4, b'No hubo')])),
                ('innundacion', models.IntegerField(verbose_name=b'Inundaci\xc3\xb3n', choices=[(1, b'Fuerte'), (2, b'Poco fuerte'), (3, b'Leve'), (4, b'No hubo')])),
                ('lluvia', models.IntegerField(choices=[(1, b'Fuerte'), (2, b'Poco fuerte'), (3, b'Leve'), (4, b'No hubo')])),
                ('viento', models.IntegerField(choices=[(1, b'Fuerte'), (2, b'Poco fuerte'), (3, b'Leve'), (4, b'No hubo')])),
                ('deslizamiento', models.IntegerField(choices=[(1, b'Fuerte'), (2, b'Poco fuerte'), (3, b'Leve'), (4, b'No hubo')])),
                ('encuesta', models.ForeignKey(to='monitoreo.Encuesta')),
            ],
            options={
                'verbose_name': '6 Fen\xf3menos naturales',
                'verbose_name_plural': '6 Fen\xf3menos naturales',
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='Genero',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('ingresos', models.IntegerField(verbose_name=b'\xc2\xbfUsted recibe ingresos por las actividades que realiza?', choices=[(1, b'Si'), (2, b'No')])),
                ('ingreso_mesual', models.FloatField(null=True, verbose_name=b'Ingreso mensual aproximado percibido', blank=True)),
                ('destino_ingresos', models.CharField(max_length=300, verbose_name=b'Destino de los ingresos percibidos')),
                ('decisiones', multiselectfield.db.fields.MultiSelectField(max_length=7, verbose_name=b'Decisiones sobre destino de la producci\xc3\xb3n', choices=[(1, b'Decide Usted sobre la siembra de cacao'), (2, b'Decide Usted sobre la cosecha de cacao'), (3, b'Decide Usted sobre la venta de cacao'), (4, b'Decide Usted sobre la Ingresos de cacao')])),
                ('actividades', models.ManyToManyField(to='monitoreo.Actividades_Produccion', verbose_name=b'Actividades en las que participa')),
                ('encuesta', models.ForeignKey(to='monitoreo.Encuesta')),
            ],
            options={
                'verbose_name': '14 G\xe9nero',
                'verbose_name_plural': '14 G\xe9nero',
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='Genero_2',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('ganaderia', models.IntegerField(verbose_name=b'Ganader\xc3\xada', choices=[(1, b'1'), (2, b'2'), (3, b'3'), (4, b'4'), (5, b'5')])),
                ('granos_basicos', models.IntegerField(verbose_name=b'Granos B\xc3\xa1sicos', choices=[(1, b'1'), (2, b'2'), (3, b'3'), (4, b'4'), (5, b'5')])),
                ('cacao', models.IntegerField(verbose_name=b'Cacao', choices=[(1, b'1'), (2, b'2'), (3, b'3'), (4, b'4'), (5, b'5')])),
                ('cafe', models.IntegerField(verbose_name=b'Caf\xc3\xa9', choices=[(1, b'1'), (2, b'2'), (3, b'3'), (4, b'4'), (5, b'5')])),
                ('madera', models.IntegerField(verbose_name=b'Madera', choices=[(1, b'1'), (2, b'2'), (3, b'3'), (4, b'4'), (5, b'5')])),
                ('encuesta', models.ForeignKey(to='monitoreo.Encuesta')),
            ],
            options={
                'verbose_name': 'Sobre otros Ingresos',
                'verbose_name_plural': 'Sobre otros Ingresos',
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='Inversion',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('invierte_cacao', models.IntegerField(verbose_name=b'Invierte en cacao', choices=[(1, b'Si'), (2, b'No')])),
                ('interes_invertrir', models.IntegerField(verbose_name=b'Inter\xc3\xa9s de invertir', choices=[(1, b'Si'), (2, b'No')])),
                ('falta_credito', models.IntegerField(verbose_name=b'Falta de cr\xc3\xa9dito', choices=[(1, b'Si'), (2, b'No')])),
                ('altos_intereses', models.IntegerField(choices=[(1, b'Si'), (2, b'No')])),
                ('robo_producto', models.IntegerField(verbose_name=b'Robo de producto', choices=[(1, b'Si'), (2, b'No')])),
                ('encuesta', models.ForeignKey(to='monitoreo.Encuesta')),
            ],
            options={
                'verbose_name': '6 Inversi\xf3n',
                'verbose_name_plural': '6 Inversi\xf3n',
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='Lista_Certificaciones',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('nombre', models.CharField(max_length=200)),
            ],
            options={
                'verbose_name': 'Certificaci\xf3n',
                'verbose_name_plural': 'Certificaciones',
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='Mitigacion_Riesgos',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('monitoreo_plagas', models.IntegerField(verbose_name=b'\xc2\xbfRealiza monitoreo de plagas y enfermedades?', choices=[(1, b'Si'), (2, b'No')])),
                ('manejo_cultivo', models.IntegerField(verbose_name=b'\xc2\xbfCuenta con un manejo adecuado para el cultivo?', choices=[(1, b'Si'), (2, b'No')])),
                ('manejo_recursos', models.IntegerField(verbose_name=b'\xc2\xbfDisponen suficiente recursos para manejo de finca?', choices=[(1, b'Si'), (2, b'No')])),
                ('almacenamiento_agua', models.IntegerField(verbose_name=b'\xc2\xbfCuenta con obras para almacenamiento de agua?', choices=[(1, b'Si'), (2, b'No')])),
                ('distribucion_cacao', models.IntegerField(verbose_name=b'\xc2\xbfParticipan en cadena de distribuci\xc3\xb3n de producto cacao?', choices=[(1, b'Si'), (2, b'No')])),
                ('venta_cacao', models.IntegerField(verbose_name=b'\xc2\xbfCuenta con un contrato para la venta de cacao?', choices=[(1, b'Si'), (2, b'No')])),
                ('tecnologia_secado', models.CharField(max_length=200, null=True, verbose_name=b'\xc2\xbfDispone de tecnolog\xc3\xada para el secado y almacenamiento de cosecha? Mencione', blank=True)),
                ('encuesta', models.ForeignKey(to='monitoreo.Encuesta')),
            ],
            options={
                'verbose_name': '7 Mitigaci\xf3n de Riesgos',
                'verbose_name_plural': '7 Mitigaci\xf3n de Riesgos',
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='Organizacion_Asociada',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('socio', models.IntegerField(verbose_name=b'Trabaja con alguna Organizaci\xc3\xb3n/Instituci\xc3\xb3n', choices=[(1, b'Si'), (2, b'No')])),
                ('beneficios', models.ManyToManyField(to='monitoreo.Beneficios', null=True, verbose_name=b'Beneficios de estar asociado', blank=True)),
                ('encuesta', models.ForeignKey(to='monitoreo.Encuesta')),
                ('organizacion', models.ManyToManyField(to='organizacion.Organizacion', null=True, verbose_name=b'Organizaci\xc3\xb3n/Instituci\xc3\xb3n con la que trabaja', blank=True)),
            ],
            options={
                'verbose_name': '8 Org. productiva-comercial asociado',
                'verbose_name_plural': '8 Org. productiva-comercial asociado',
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='Paga_Certifica',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('nombre', models.CharField(max_length=200)),
            ],
            options={
                'verbose_name': 'Qui\xe9n paga la certifica',
                'verbose_name_plural': 'Quienes pagan la certificaci\xf3n',
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='Persona',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('nombre', models.CharField(max_length=200, verbose_name=b'Nombre de jefa/e de familia')),
                ('cedula', models.CharField(max_length=20, null=True, verbose_name=b'C\xc3\xa9ula de entrevistado/a', blank=True)),
                ('fecha_nacimiento', models.DateField(verbose_name=b'Fecha de nacimiento')),
                ('sexo', models.IntegerField(choices=[(1, b'Hombre'), (2, b'Mujer')])),
                ('latitud', models.FloatField(null=True, blank=True)),
                ('longitud', models.FloatField(null=True, blank=True)),
                ('comunidad', smart_selects.db_fields.ChainedForeignKey(chained_model_field=b'municipio', chained_field=b'municipio', auto_choose=True, to='lugar.Comunidad')),
                ('departamento', models.ForeignKey(to='lugar.Departamento')),
                ('municipio', smart_selects.db_fields.ChainedForeignKey(chained_model_field=b'departamento', chained_field=b'departamento', auto_choose=True, to='lugar.Municipio')),
            ],
            options={
                'verbose_name': 'Persona',
                'verbose_name_plural': 'Personas',
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='Plantacion',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('edad', models.IntegerField(choices=[(1, b'Menor de un a\xc3\xb1o'), (2, b'De 1 a 3 a\xc3\xb1os'), (3, b'De 4 a 10 a\xc3\xb1os'), (4, b'De 10 a 20 a\xc3\xb1os'), (5, b'Mayores de 20 a\xc3\xb1os')])),
                ('area', models.FloatField(verbose_name=b'\xc3\x81rea en Mz')),
                ('edad_real', models.FloatField(verbose_name=b'Edad real de la Plantaci\xc3\xb3n (a\xc3\xb1os)')),
                ('numero_p_semilla', models.IntegerField(verbose_name=b'N\xc3\xbamero de plantas establecidas por semilla')),
                ('numero_p_injerto', models.IntegerField(verbose_name=b'N\xc3\xbamero de plantas establecidas por injerto')),
                ('numero_p_improductivas', models.IntegerField(verbose_name=b'N\xc3\xbamero de plantas improductivas en el \xc3\xa1rea')),
                ('encuesta', models.ForeignKey(to='monitoreo.Encuesta')),
            ],
            options={
                'verbose_name': '9-1 Edad de la plantaci\xf3n',
                'verbose_name_plural': '9-1 Edad de la plantaci\xf3n',
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='Problemas_Cacao',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('fertilidad', models.IntegerField(verbose_name=b'Baja fertilidad del suelo', choices=[(1, b'1'), (2, b'2'), (3, b'3'), (4, b'4'), (5, b'5')])),
                ('arboles', models.IntegerField(verbose_name=b'\xc3\x81rboles poco productivos', choices=[(1, b'1'), (2, b'2'), (3, b'3'), (4, b'4'), (5, b'5')])),
                ('plantaciones', models.IntegerField(verbose_name=b'Plantaciones muy viejas', choices=[(1, b'1'), (2, b'2'), (3, b'3'), (4, b'4'), (5, b'5')])),
                ('plagas', models.IntegerField(verbose_name=b'Plagas y enfermedades', choices=[(1, b'1'), (2, b'2'), (3, b'3'), (4, b'4'), (5, b'5')])),
                ('produccion', models.IntegerField(verbose_name=b'Poca producci\xc3\xb3n', choices=[(1, b'1'), (2, b'2'), (3, b'3'), (4, b'4'), (5, b'5')])),
                ('mano_obra', models.IntegerField(verbose_name=b'Poca disponibilidad de mano de obra', choices=[(1, b'1'), (2, b'2'), (3, b'3'), (4, b'4'), (5, b'5')])),
                ('encuesta', models.ForeignKey(to='monitoreo.Encuesta')),
            ],
            options={
                'verbose_name': '13.3 Problemas \xe1rea de cacao',
                'verbose_name_plural': '13.3 Problemas \xe1rea de cacao',
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='Produccion_Cacao',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('produccion_c_baba', models.FloatField(verbose_name=b'Producci\xc3\xb3n cacao en baba (qq baba/seco)')),
                ('produccion_c_seco', models.FloatField(verbose_name=b'Producci\xc3\xb3n cacao seco sin fermentar (qq seco)')),
                ('produccion_c_fermentado', models.FloatField(verbose_name=b'Producci\xc3\xb3n cacao fermentado convencional (qq seco)')),
                ('produccion_c_organico', models.FloatField(verbose_name=b'Producci\xc3\xb3n cacao organico (qq seco)')),
                ('meses_produccion', multiselectfield.db.fields.MultiSelectField(max_length=26, verbose_name=b'Meses de mayor producci\xc3\xb3n de cacao', choices=[(1, b'Enero'), (2, b'Febrero'), (3, b'Marzo'), (4, b'Abril'), (5, b'Mayo'), (6, b'Junio'), (7, b'Julio'), (8, b'Agosto'), (9, b'Septiembre'), (10, b'Octubre'), (11, b'Noviembre'), (12, b'Diciembre')])),
                ('encuesta', models.ForeignKey(to='monitoreo.Encuesta')),
            ],
            options={
                'verbose_name': '9-2 Producci\xf3n de cacao \xfaltimo a\xf1o',
                'verbose_name_plural': '9-2 Producci\xf3n de cacao \xfaltimo a\xf1o',
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='Profesion',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('nombre', models.CharField(max_length=200)),
            ],
            options={
                'verbose_name': 'Profesi\xf3n',
                'verbose_name_plural': 'Profesiones',
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='Quien_Certifica',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('nombre', models.CharField(max_length=200)),
            ],
            options={
                'verbose_name': 'Qui\xe9n certifica',
                'verbose_name_plural': 'Quienes certifican',
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='Razones_Agricolas',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('plantas_improductivas', models.IntegerField(choices=[(1, b'Alto (40%)'), (2, b'Medio (30%)'), (3, b'Baja (10%)')])),
                ('plagas_enfermedades', models.IntegerField(verbose_name=b'Plagas y enfermedades', choices=[(1, b'Si'), (2, b'No')])),
                ('quemas', models.IntegerField(choices=[(1, b'Si'), (2, b'No')])),
                ('encuesta', models.ForeignKey(to='monitoreo.Encuesta')),
            ],
            options={
                'verbose_name': '6 Razones agr\xedcolas',
                'verbose_name_plural': '6 Razones agr\xedcolas',
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='Razones_Mercado',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('bajo_precio', models.IntegerField(choices=[(1, b'Si'), (2, b'No')])),
                ('falta_venta', models.IntegerField(verbose_name=b'Falta de venta', choices=[(1, b'Si'), (2, b'No')])),
                ('estafa_contrato', models.IntegerField(verbose_name=b'Estafa de contrato', choices=[(1, b'Si'), (2, b'No')])),
                ('calidad_producto', models.IntegerField(verbose_name=b'Mala calidad de producto', choices=[(1, b'Si'), (2, b'No')])),
                ('encuesta', models.ForeignKey(to='monitoreo.Encuesta')),
            ],
            options={
                'verbose_name': '6 Razones de mercado',
                'verbose_name_plural': '6 Razones de mercado',
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='Recolector',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('nombre', models.CharField(max_length=200)),
            ],
            options={
                'verbose_name': 'Recolector',
                'verbose_name_plural': 'Recolectores',
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='Reforestacion',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('enriquecimiento_bosques', models.IntegerField(verbose_name=b'Enriquecimiento de los bosques', choices=[(1, b'Si'), (2, b'No')])),
                ('proteccion_agua', models.IntegerField(verbose_name=b'Protecci\xc3\xb3n de fuentes de agua', choices=[(1, b'Si'), (2, b'No')])),
                ('cercas_vivas', models.IntegerField(verbose_name=b'Establecimiento de cercas viva', choices=[(1, b'Si'), (2, b'No')])),
                ('viveros', models.IntegerField(verbose_name=b'Establecimiento de viveros', choices=[(1, b'Si'), (2, b'No')])),
                ('siembre_cacao', models.IntegerField(verbose_name=b'Siembra de \xc3\xa1rboles en cacao', choices=[(1, b'Si'), (2, b'No')])),
                ('forestales', models.IntegerField(verbose_name=b'Plantaciones forestales', choices=[(1, b'Si'), (2, b'No')])),
                ('potrero', models.IntegerField(verbose_name=b'Siembra de \xc3\xa1rboles en potrero', choices=[(1, b'Si'), (2, b'No')])),
                ('frutales', models.IntegerField(verbose_name=b'Parcelas frutales', choices=[(1, b'Si'), (2, b'No')])),
                ('encuesta', models.ForeignKey(to='monitoreo.Encuesta')),
            ],
            options={
                'verbose_name': '4 Reforestaci\xf3n',
                'verbose_name_plural': '4 Reforestaci\xf3n',
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='Situacion',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('nombre', models.CharField(max_length=200)),
            ],
            options={
                'verbose_name': 'Situaci\xf3n',
                'verbose_name_plural': 'Situaciones',
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='Tecnicas_Aplicadas',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('viveros', multiselectfield.db.fields.MultiSelectField(max_length=15, choices=[(1, b'Preparaci\xc3\xb3n del sitio'), (2, b'Preparaci\xc3\xb3n del sustrato'), (3, b'Llenado de bolsa'), (4, b'Selecci\xc3\xb3n de semilla'), (5, b'Siembra de semilla'), (6, b'Uso de riego'), (7, b'Control de malas hierba'), (8, b'Fertilizaci\xc3\xb3n org\xc3\xa1nica')])),
                ('fertilizacion', multiselectfield.db.fields.MultiSelectField(max_length=15, verbose_name=b'Pr\xc3\xa1cticas de fertilizaci\xc3\xb3n', choices=[(1, b'Aplicaci\xc3\xb3n de t\xc3\xa9 de esti\xc3\xa9rcol'), (2, b'Aplicaci\xc3\xb3n de gallinaza'), (3, b'Aplicaci\xc3\xb3n de Bocashi'), (4, b'Aplicaci\xc3\xb3n de foliares naturales'), (5, b'Uso de triple cal'), (6, b'Aplicaci\xc3\xb3n de lombrihumus'), (7, b'Aplicaci\xc3\xb3n de urea'), (8, b'Aplicaci\xc3\xb3n de fertilizante completo')])),
                ('pract_manejo_fis', multiselectfield.db.fields.MultiSelectField(max_length=11, verbose_name=b'Pr\xc3\xa1cticas de manejo fitosanitario', choices=[(1, b'Control de malas hierbas con machete'), (2, b'Aplica herbicidas para controlar las malas hierbas'), (3, b'Manejo de plagas con productos naturales'), (4, b'Manejo de enfermedades con productos naturales'), (5, b'Manejo de enfermedades con fungicidas'), (6, b'Recolecci\xc3\xb3n e eliminaci\xc3\xb3n de frutos enfermos')])),
                ('pract_manejo_prod', multiselectfield.db.fields.MultiSelectField(max_length=7, verbose_name=b'Pr\xc3\xa1cticas de manejo productivo', choices=[(1, b'Poda de formaci\xc3\xb3n'), (2, b'Poda de mantenimiento'), (3, b'Poda de rehabilitaci\xc3\xb3n o renovaci\xc3\xb3n'), (4, b'Regulaci\xc3\xb3n en sombra')])),
                ('pract_mejora_plat', multiselectfield.db.fields.MultiSelectField(max_length=7, verbose_name=b'Pr\xc3\xa1cticas de mejoramiento de la plantaci\xc3\xb3n', choices=[(1, b'Selecci\xc3\xb3n de \xc3\xa1rboles superiores'), (2, b'Injertaci\xc3\xb3n en \xc3\xa1rboles adultos'), (3, b'Renovaci\xc3\xb3n de \xc3\xa1rea con plantas injertadas'), (4, b'Enriquecimiento de \xc3\xa1reas con plantas injertadas')])),
                ('pract_manejo_post_c', multiselectfield.db.fields.MultiSelectField(max_length=15, verbose_name=b'Pr\xc3\xa1cticas de manejo postcosecha y beneficiado', choices=[(1, b'Selecci\xc3\xb3n y clasificaci\xc3\xb3n de mazorcas por variedad'), (2, b'Selecci\xc3\xb3n de cacao en baba a fermentar'), (3, b'Fermentaci\xc3\xb3n en sacos'), (4, b'Fermentaci\xc3\xb3n en cajones'), (5, b'Fermentaci\xc3\xb3n en cajillas'), (6, b'Lo vende en baba a un centro de acopio'), (7, b'Solo la saca de la mazorca y lo seca'), (8, b'Lo saca de la mazorca, lo lava y luego lo seca')])),
                ('acopio_cacao', models.IntegerField(verbose_name=b'Acopio de cacao en la comunidad/municipio', choices=[(1, b'Si'), (2, b'No')])),
                ('acopio_org', models.IntegerField(verbose_name=b'Asociaci\xc3\xb3n con Org. que acopia cacao', choices=[(1, b'Si'), (2, b'No')])),
                ('encuesta', models.ForeignKey(to='monitoreo.Encuesta')),
            ],
            options={
                'verbose_name': '11 T\xe9cn. aplicadas \xe1rea de cacao',
                'verbose_name_plural': '11 T\xe9cn. aplicadas \xe1rea de cacao',
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='Tenencia_Propiedad',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('dueno_propiedad', models.IntegerField(verbose_name=b'Son ustedes due\xc3\xb1os de la propiedad', choices=[(1, b'Si'), (2, b'No')])),
                ('si', models.IntegerField(blank=True, null=True, verbose_name=b'En el caso Si, a nombre de quien esta la propiedad', choices=[(1, b'A nombre del Hombre'), (2, b'A nombre de la Mujer'), (3, b'A nombre de Hijas/hijos'), (4, b'A nombre del Hombre y Mujer'), (5, b'Colectivo')])),
                ('encuesta', models.ForeignKey(to='monitoreo.Encuesta')),
                ('no', models.ForeignKey(verbose_name=b'En el caso que diga NO, especifique la situaci\xc3\xb3n', blank=True, to='monitoreo.Situacion', null=True)),
            ],
            options={
                'verbose_name': '2 Tenencia de Propiedad',
                'verbose_name_plural': '2 Tenencia de Propiedad',
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='Tipos_Servicio',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('servicio', models.CharField(max_length=200)),
            ],
            options={
                'verbose_name': 'Tipo de Servicio',
                'verbose_name_plural': 'Tipos de Servicios',
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='Uso_Tierra',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('area_total', models.FloatField(default=b'0', verbose_name=b'\xc3\x81rea total en manzanas de la propiedad', validators=[django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(200)])),
                ('bosque', models.FloatField(default=b'0', verbose_name=b'Bosques', validators=[django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(100)])),
                ('tacotal', models.FloatField(default=b'0', verbose_name=b'Tacotal o \xc3\xa1rea de descanso', validators=[django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(100)])),
                ('cultivo_anual', models.FloatField(default=b'0', verbose_name=b'Cultivo anual ( que produce en el a\xc3\xb1o)', validators=[django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(100)])),
                ('plantacion_forestal', models.FloatField(default=b'0', verbose_name=b'Plantaci\xc3\xb3n forestal ( madera y le\xc3\xb1a)', validators=[django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(100)])),
                ('area_pasto_abierto', models.FloatField(default=b'0', verbose_name=b'\xc3\x81rea de pastos abierto', validators=[django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(100)])),
                ('area_pasto_arboles', models.FloatField(default=b'0', verbose_name=b'\xc3\x81rea de pastos con \xc3\xa1rboles', validators=[django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(100)])),
                ('cultivo_perenne', models.FloatField(default=b'0', verbose_name=b'Cultivo perenne (frutales)', validators=[django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(100)])),
                ('cultivo_semi_perenne', models.FloatField(default=b'0', verbose_name=b'Cultivo semi-perenne (mus\xc3\xa1cea, pi\xc3\xb1a)', validators=[django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(100)])),
                ('cacao', models.FloatField(default=b'0', verbose_name=b'Solo destinado para cacao', validators=[django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(100)])),
                ('huerto_mixto_cacao', models.FloatField(default=b'0', verbose_name=b'Huerto mixto con cacao', validators=[django.core.validators.MinValueValidator(0), django.core.validators.MaxValueValidator(100)])),
                ('encuesta', models.ForeignKey(to='monitoreo.Encuesta')),
            ],
            options={
                'verbose_name': '3 Uso de Tierra',
                'verbose_name_plural': '3 Uso de Tierra',
            },
            bases=(models.Model,),
        ),
        migrations.AddField(
            model_name='persona',
            name='profesion',
            field=models.ForeignKey(to='monitoreo.Profesion'),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='organizacion_asociada',
            name='tipos_servicio',
            field=models.ManyToManyField(to='monitoreo.Tipos_Servicio', null=True, verbose_name=b'Tipos de servicios que recibe', blank=True),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='encuesta',
            name='persona',
            field=models.ForeignKey(verbose_name=b'Nombre', to='monitoreo.Persona'),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='encuesta',
            name='recolector',
            field=models.ForeignKey(to='monitoreo.Recolector'),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='encuesta',
            name='usuario',
            field=models.ForeignKey(to=settings.AUTH_USER_MODEL),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='educacion',
            name='encuesta',
            field=models.ForeignKey(to='monitoreo.Encuesta'),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='distancia_comercio_cacao',
            name='encuesta',
            field=models.ForeignKey(to='monitoreo.Encuesta'),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='comercializacion_cacao',
            name='encuesta',
            field=models.ForeignKey(to='monitoreo.Encuesta'),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='certificacion',
            name='encuesta',
            field=models.ForeignKey(to='monitoreo.Encuesta'),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='certificacion',
            name='paga_certificacion',
            field=models.ManyToManyField(to='monitoreo.Paga_Certifica', null=True, verbose_name=b'\xc2\xbfQui\xc3\xa9n paga la certificaci\xc3\xb3n?', blank=True),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='certificacion',
            name='quien_certifica',
            field=models.ManyToManyField(to='monitoreo.Quien_Certifica', null=True, verbose_name=b'\xc2\xbfQui\xc3\xa9n certifica?', blank=True),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='certificacion',
            name='tipo',
            field=models.ManyToManyField(to='monitoreo.Lista_Certificaciones', null=True, verbose_name=b'Tipo de certificaci\xc3\xb3n', blank=True),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='caracterizacion_terreno',
            name='encuesta',
            field=models.ForeignKey(to='monitoreo.Encuesta'),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='capacitaciones_tecnicas',
            name='encuesta',
            field=models.ForeignKey(to='monitoreo.Encuesta'),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='capacitaciones_socioeconomicas',
            name='encuesta',
            field=models.ForeignKey(to='monitoreo.Encuesta'),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='area_cacao',
            name='encuesta',
            field=models.ForeignKey(to='monitoreo.Encuesta'),
            preserve_default=True,
        ),
        migrations.AddField(
            model_name='adicional',
            name='encuesta',
            field=models.ForeignKey(to='monitoreo.Encuesta'),
            preserve_default=True,
        ),
    ]


from  tkinter import *
from tkinter import filedialog
from PIL import ImageTk, Image
from time import time
from pencocokan import *

window = Tk()
window.title("AlgeOwO")
window.geometry("900x600")
window.configure(bg="white")

processed = False

newimagedir=""
def insertimage():
    global newimagedir
    newimagedir = filedialog.askopenfilename(filetypes=[("jpg image","*.jpg"),("png image","*.png")])
    no_image_selected.config(text=newimagedir)
    #print(newimagedir)
    newimage = ImageTk.PhotoImage(Image.open(newimagedir).resize((300,300)))
    pimg_test.config(image=newimage)
    pimg_test.image=newimage

newfolderdir=""
def insertfolderdir():
    global newfolderdir
    newfolderdir = filedialog.askdirectory()
    no_dataset_selected.config(text=newfolderdir)

resultpath=""
execution_time = 0
def processimage():
    start = time()
    global processed
    global execution_time
    resultpath = test_image(newfolderdir,newimagedir)
    execution_time = time() - start
    print(f"Execution time: {round(execution_time)}")
    if resultpath:
        resultimage = ImageTk.PhotoImage(Image.open(resultpath).resize((300,300)))
        pimg_result.config(image=resultimage)
        pimg_result.image=resultimage
        not_found.config(text="")
        execution_time_text.config(text="Execution time : "+str(round(execution_time,1))+" detik")
        execution_time_text.place(x=550, y=535)

    else:
        not_found.place(x=550 ,y=410)
        not_found.config(text="Tidak ada gambar yang cocok")
        execution_time_text.config(text="Execution time : "+str(round(execution_time,1))+" detik")
        execution_time_text.place(x=550, y=535)
        # no_dataset_selected.config(text="Tidak ada gambar yang cocok")
        print("Tidak ada gambar yang cocok")
        resultimage = ImageTk.PhotoImage(Image.open("no_image.png").resize((300,300)))
        pimg_result.config(image=resultimage)
        pimg_result.image=resultimage

# kumpulan label
header = Label(window, text="Face Recognition",bg="white",font=("Arial",24),fg="black")
insert_dataset_text = Label(window, text="Insert Your Dataset ", bg="white",font=("Times New Roman",12),fg="black")
insert_image_text  = Label(window, text="Insert Your Image ", bg="white",font=("Times New Roman",12),fg="black")
no_dataset_selected = Label(window, text="No Dataset Selected", bg="grey",font=("Times New Roman",12),fg="black")
no_image_selected = Label(window, text="No Image Selected", bg="grey",font=("Times New Roman",12),fg="black")
not_found  = Label(window, text="Tidak ada gambar yang cocok", bg="white",font=("Times New Roman",12),fg="red")

#result_text = insert_dataset = tk.Label(window, text="Result ", bg="white",font=("Times New Roman",12),fg="black")
test_image_text = Label(window, text="Test image ", bg="white",font=("Times New Roman",12),fg="black")
closest_result_text = Label(window, text="Closest Result ", bg="white",font=("Times New Roman",12),fg="black")

execution_time_text = Label(window, text="Execution time: ", bg="white",font=("Times New Roman",12),fg="black")

# kumpulan button
folder_file = ImageTk.PhotoImage(Image.open("choose_folder.png").resize((120,32)))
tombol_folder = Button(window, image=folder_file, fg="blue", bg="white",borderwidth=0)
button_file = ImageTk.PhotoImage(Image.open("choose_file.png").resize((120,32)))
tombol_file = Button(window, image=button_file, fg="blue", bg="white", borderwidth=0)
process_image = ImageTk.PhotoImage(Image.open("process_image.png").resize((120,32)))
tombol_process = Button(window, image=process_image, fg="blue",borderwidth=0)
tombol_file.config(command=lambda:insertimage())
tombol_folder.config(command=lambda:insertfolderdir())
tombol_process.config(command=lambda:processimage())

# kumpulan place
header.place(x=330, y=15)

insert_dataset_text.place(x=550, y=450)
tombol_folder.place(x =550, y = 475)
no_dataset_selected.place(x =550, y=510 )

insert_image_text.place(x=95,y = 450 )
tombol_file.place(x =95, y = 475)
no_image_selected.place(x=95, y = 510)

tombol_process.place(x=415,y=125)

#result_text.place(x=25, y=300)
test_image_text.place(x=120, y=75)

closest_result_text.place(x=575, y=75)

img_test=ImageTk.PhotoImage(Image.open("no_image.png").resize((270,270)))
pimg_test=Label(window)
pimg_test.config(width=300,height=300)
pimg_test.place(x=95,y=100)
pimg_test.config(image=img_test)
#resultimg = Label(window)
#resultimg.config(width=300,height=300)
#pimg_right = Label(window)

img_result=ImageTk.PhotoImage(Image.open("no_image.png").resize((270,270)))
pimg_result=Label(window)
pimg_result.config(width=300,height=300)
pimg_result.place(x=550,y=100)
pimg_result.config(image=img_test)
#pimg_result = Label(window)

window.mainloop()


__id__        = "$Id$"
__version__   = "$Revision$"
__date__      = "$Date$"
__copyright__ = "Copyright (c) 2014 Igalia, S.L."
__license__   = "LGPL"

import orca.focus_manager as focus_manager
import orca.scripts.toolkits.gtk as gtk
import orca.scripts.toolkits.WebKitGtk as WebKitGtk

_focusManager = focus_manager.getManager()

class Script(WebKitGtk.Script):

    def __init__(self, app):
        WebKitGtk.Script.__init__(self, app)

    def onWindowActivated(self, event):
        """Callback for window:activate accessibility events."""

        gtk.Script.onWindowActivated(self, event)

        obj = self.utilities.getCaretContext()[0]
        if obj:
            _focusManager.set_locus_of_focus(None, obj)

    def onWindowDeactivated(self, event):
        """Callback for window:deactivate accessibility events."""

        gtk.Script.onWindowDeactivated(self, event)


def Get_babyname_soup(html):
    from bs4 import BeautifulSoup
    soup=BeautifulSoup(html,'html.parser')
    names=soup.find_all(class_='blob-code blob-code-inner js-file-line')
    for name in names:
        print((name.text))
        break

import requests,time
def Get_html(url,year):
    try:
        html=requests.get(url=url)
        html.encoding='utf-8'
        html=html.text
        return html
    except Exception as e:
        main(year+1)

def Get_babynames(html,year):
    try:
        names=re.findall(reg,html)
        return names
    except:
        main(year+1)

def save_txt(names,year):
    with open(r'F:\c语言\python\babynames\yob%s.txt'%year,'w',encoding='utf-8') as f:
        for name in names:
                f.write(name+'\n')
        print('the %s babynames has done'%year)

def main(year):
    url='https://github.com/tspike/babynames/blob/master/data/yob%s.txt'%year
    html=Get_html(url,year)
    names=Get_babyname_soup(html=html)
    names=re.findall(reg,html)
    save_txt(names=names,year=year)
    Get_babyname_soup(html)
    print('the totally time is :%s '%(time.time()-starts))
import re
reg=r'(.*?)\r	'
reg=re.compile(reg)
starts=time.time()
years=range(1980,2014)
for year in years:
    main(year)


def convertToJsonHomework(ObjectsTuple):
    if ObjectsTuple:
        homeworks = [

        ]

        for homework, userHomework in ObjectsTuple:
            homeworks.append({'id':homework.id_homework, 'subject':homework.subject, 'title':homework.title, 'description': homework.description,
                            'status': homework.status, 'drafting_date': userHomework.drafting_date, 'deadline': userHomework.deadline})

    return homeworks

def convertToJsonUsers(ObjectsTuple):
    if ObjectsTuple:
        usersList = []

        for user in ObjectsTuple:
            usersList.append(user.username)

    return usersList


from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status

from backend.models import Attendance, User, Section, Student
from backend.serializers import (
    UserSerializer,
    StudentSerializer,
    MentorSerializer,
    SectionSerializer,
    CourseSerializer,
    AttendanceSerializer
)

@api_view(["GET"])
def users(request):
    users = User.objects.all()
    serializer = UserSerializer(users, many=True)
    return Response(serializer.data, status=status.HTTP_200_OK)

@api_view(["GET"])
def sections(request):
    sections = Section.objects.all()
    serializer = SectionSerializer(sections, many=True)
    return Response(serializer.data, status=status.HTTP_200_OK)

@api_view(["GET", "DELETE"])
def section_students(request, section_id):
    if request.method == "GET":
        section = Section.objects.get(id=section_id)
        students = section.student_set.filter(active=True)
        serializer = StudentSerializer(students, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)

    elif request.method == "DELETE":
        students = Section.objects.get(id=section_id).student_set.filter(active=True)
        student = students.get(id = request.data.get("value"))
        student.active = False
        student.save()
        return Response(status=status.HTTP_201_CREATED)

@api_view(["GET", "POST"])
def section_details(request, section_id):
    """
    GET: Return section details
    POST: Update section details
        - format: { "capacity": int, "description": str }
    """
    if request.method == "GET":
        section = Section.objects.get(id=section_id)
        serializer = SectionSerializer(section)
        return Response(serializer.data, status=status.HTTP_200_OK)
    elif request.method == "POST":
        section = Section.objects.get(id=section_id)
        capacity = request.data.get("capacity")
        description = request.data.get("description")
        if capacity is not None:
            section.capacity = capacity
        if description is not None:
            section.description = description
        section.save()
        return Response(status=status.HTTP_201_CREATED)

@api_view(["GET"])
def student_details(request, student_id):
    """
    GET: Return student details
    """
    if request.method == "GET":
        student = Student.objects.get(id=student_id)
        serializer = StudentSerializer(student)
        return Response(serializer.data, status=status.HTTP_200_OK)

@api_view(["GET", "POST"])
def attendance_details(request, attendance_id):
    """
    GET: Return student details
    """
    if request.method == "GET":
        attendance = Attendance.objects.get(id=attendance_id)
        serializer = AttendanceSerializer(attendance)
        return Response(serializer.data, status=status.HTTP_200_OK)

    elif request.method == "POST":
        attendance = Attendance.objects.get(id=attendance_id)
        attendance.presence = request.data.get("value")
        attendance.save()
        return Response(status=status.HTTP_201_CREATED)

@api_view(["GET"])
def attendance_student(request, student_id):
    """
    GET: Return student details
    """
    if request.method == "GET":
        attendance = Attendance.objects.filter(student_id = student_id)
        serializer = AttendanceSerializer(attendance, many = True)
        return Response(serializer.data, status=status.HTTP_200_OK)


from .handler import BaseHandler

class AskIfFerryHandler(BaseHandler):
    def match(self) -> bool:
        if self.is_last_message_user() and self.get_last_user_intent() in (
                'ask_if_ferry'
        ):
            return True
        else:
            return False

    def process(self):
        self.utter_message("您好，我们只提供机场的接送服务")


# -*- coding:gb18030 -*-

# 玩家比赛额外信息记录，这些信息在玩家在线期间只会被查询一次，每次参与活动结束后只需保存一次。
#
# 例如：
# 个人竞技，组队竞技，帮会竞技：
# 上次参赛获得积分：ABCD
# 累计参赛获得积分：ABCD
#
# 武道大会，组队擂台，帮会擂台:
# 上次参赛获得名次：32强/16强/8强/4强/决赛/冠军
# 获得最好参赛名次：32强/16强/8强/4强/决赛/冠军
#
# sm_param1和sm_param2可以根据比赛类型做不同的解释。比赛类型定义在csdefine中的MATCH_TYPE_***
# 各比赛的设计没有总体的规划，也没有良好的设计，同时此模块不考虑太多的扩展需要，可实现当前的比赛数据存储查询即可。

import BigWorld
from bwdebug import *
import csdefine
from Function import Functor

# 增加一条记录的sql语句
sqlCmdInsert = "insert into custom_RoleMatchRecord set sm_playerDBID = %i, sm_matchType = %i, sm_param1 = %i, sm_param2 = %i, sm_time = now();"
# 更新竞技类比赛信息的sql语句
sqlCmdUpdateCpt = "update custom_RoleMatchRecord set sm_param1 = %i, sm_param2 = sm_param2 + %i, sm_time = now() where sm_playerDBID = %i and sm_matchType = %i;"
# 更新擂台类比赛信息的sql语句
sqlCmdUpdateAba = "update custom_RoleMatchRecord set sm_param1 = %i, sm_param2 = if( %i < sm_param2, %i, sm_param2 ), sm_time = now() where sm_playerDBID = %i and sm_matchType = %i;"
# 查询比赛信息的sql语句
sqlCmdQuery = "select sm_matchType, sm_param1, sm_param2 from custom_RoleMatchRecord where sm_playerDBID = %i;"

cptMatchTypes = ( csdefine.MATCH_TYPE_PERSON_COMPETITION, csdefine.MATCH_TYPE_TEAM_COMPETITION, csdefine.MATCH_TYPE_TONG_COMPETITION )	# 竞技比赛定义类型集合
abaMatchTypes = ( csdefine.MATCH_TYPE_PERSON_ABA, csdefine.MATCH_TYPE_TEAM_ABA, csdefine.MATCH_TYPE_TONG_ABA )							# 擂台比赛定义类型集合

def getUpdateCmd( playerDBID, matchType, scoreOrRound ):	# 生成更新比赛日志的sql语句
	if matchType in cptMatchTypes:		# 竞技比赛
		return sqlCmdUpdateCpt % ( scoreOrRound, scoreOrRound, playerDBID, matchType )
	else:								# 其他是擂台比赛
		return sqlCmdUpdateAba % ( scoreOrRound, scoreOrRound, scoreOrRound, playerDBID, matchType )

def createTable():
	"""
	@sm_playerDBID : 玩家的dbid
	@sm_matchType : 活动类型
	@sm_param1 : 活动日志数据1，例如：上次参赛获得积分 或 上次参赛获得名次
	@sm_param2 : 活动日志数据2，例如：累计参赛获得积分 或 获得最好参赛名次
	@sm_time : 时间戳，更新比赛记录时此字段会被更新以标明记录的存在。避免更新的比赛数据如果和已经存在的数据一样时，
				记录不会被更改导致脚本会认为不存在此角色的记录而插入一条重复的纪录。
	"""
	sqlCmd = """CREATE TABLE IF NOT EXISTS `custom_RoleMatchRecord` (
					`id` bigint(20) NOT NULL AUTO_INCREMENT,
					`sm_playerDBID` BIGINT(20) UNSIGNED NOT NULL,
					`sm_matchType` TINYINT UNSIGNED NOT NULL,
					`sm_param1` int(32) NOT NULL default 0,
					`sm_param2` int(32) NOT NULL default 0,
					`sm_time` TIMESTAMP(8),
					PRIMARY KEY (`id`),
					key (sm_playerDBID),
					key (sm_matchType)
					)ENGINE=InnoDB;
					"""
	BigWorld.executeRawDatabaseCommand( sqlCmd, createTableCB )

def createTableCB( result, rows, errstr ):
	if errstr:
		ERROR_MSG( "create custom_RoleMatchRecord error:%s." % errstr )
		return
	INFO_MSG( "create custom_RoleMatchRecord success." )

def update( playerDBID, matchType, scoreOrRound, playerBase = None ):	# 更新比赛数据
	sqlCmd = getUpdateCmd( playerDBID, matchType, scoreOrRound )
	BigWorld.executeRawDatabaseCommand( sqlCmd, Functor( updateCB, playerDBID, playerBase, matchType, scoreOrRound ) )

def updateCB( playerDBID, playerBase, matchType, scoreOrRound, result, rows, errstr ):
	if errstr:
		ERROR_MSG( "update>>>( playerDBID:%i,matchType:%i,scoreOrRound:%i ):%s" % ( playerDBID, matchType, scoreOrRound, errstr ) )
		return
	if rows == 0:	# 没有相应的记录，那么建立此玩家的相关记录
		sqlCmd = sqlCmdInsert % ( playerDBID, matchType, scoreOrRound, scoreOrRound )
		BigWorld.executeRawDatabaseCommand( sqlCmd, Functor( insertCB, playerDBID, playerBase, matchType, scoreOrRound ) )
		return
	if playerBase:
		playerBase.client.updateMatchRecord( matchType, scoreOrRound )

def insertCB( playerDBID, playerBase, matchType, scoreOrRound, result, rows, errstr ):
	if errstr:
		ERROR_MSG( "insert>>>( playerDBID:%i,matchType:%i,scoreOrRound:%i ):%s" % ( playerDBID, matchType, scoreOrRound, errstr ) )
		return
	if playerBase:
		playerBase.client.initMatchRecord( matchType, scoreOrRound, scoreOrRound )

def query( playerBase ):	# 玩家查询所有比赛日志
	sqlCmd = sqlCmdQuery % playerBase.databaseID
	BigWorld.executeRawDatabaseCommand( sqlCmd, Functor( queryCB, playerBase ) )

def queryCB( playerBase, result, rows, errstr ):
	if errstr:
		ERROR_MSG( "query>>>playerDBID:%i:%s" % ( playerBase.databaseID, errstr ) )
		return
	if not result:
		DEBUG_MSG( "there is not result for player:%i." % playerBase.databaseID )
		return
	for matchType, param1, param2 in result:	# 目前每个玩家最多有6条
		playerBase.client.initMatchRecord( int( matchType ), int( param1 ), int( param2 ) )


import random, string

class Wordle():
    def __init__(self):
        self.currentword = None
        self.wordbankarray = []
        self.currentlettersguessed = []
        self.currentlettersinrightplace = []
        self.currentlettersinrightplaceindex = []
        self.currentlettersinword = []

    def getword(self): #Grabs the first word after shuffling the words and changes current word to the selected word
        random.shuffle(self.wordbankarray)
        self.currentword = self.wordbankarray[0]

    def gamestart(self): #Grabs from the word bank all the words and lowercases them to get them ready for grabbing the word from the function above
        words = open('C:\\Users\\kaors\\Documents\\Myprograms\\Wordle Game\\words.txt','r')
        for line in words:
            for word in line.split():
                self.wordbankarray.append(word.lower())

    def displayguesses(self):
        for index in range(len(self.currentlettersguessed)):
            if index == 0:
                print(self.currentlettersguessed[index],end='')
                continue
            print(self.currentlettersguessed[index],end='')
            if (index+1) % 5 == 0:
                print(f'\n')

    def playerguess(self):
        while True:
            playerinput = input('Please guess a 5 letter word ')

            if len(playerinput) == 5: #If correct input is provided -> append to current letters guessed to win check and change current guess
                if playerinput in self.wordbankarray:
                    for letters in range(len(playerinput)):
                        self.currentlettersguessed.append(playerinput[letters])
                    if playerinput.lower() == self.currentword:
                        return True #This will be the deciding factor to check if we won the game or not. Once it returns positive then we will end the game in the while loop
                    else:
                        return False #Since it returns false we will loop through the main function again
                else:
                    print('Word is not in my word bank! Please try a different word!')
                    continue

            if len(playerinput) != 5: #If incorrect input is provided
                print('Word is not 5 letters. Please try again')
                continue

    def wincheck(self):
        #Check letter index of all guesses if it is in the right place
        for index in range(0,5):
            for letter in range(index,len(self.currentlettersguessed),5):
                if self.currentlettersguessed[letter] == self.currentword[index]:
                    if self.currentlettersguessed[letter] in self.currentlettersinrightplace:
                        continue
                    else:
                        self.currentlettersinrightplace.append(self.currentlettersguessed[letter])
                        self.currentlettersinrightplaceindex.append(index+1)
        #If it is in the right place then it will be in the word so we will add these first
        for letter in range(0,len(self.currentlettersinrightplace)):
            if self.currentlettersinrightplace[letter] in self.currentlettersinword:
                continue
            else:
                self.currentlettersinword.append(self.currentlettersinrightplace[letter])
        #After adding the current letters we have in the right place then we will add the remaining letters that are not in the right place while making sure we don't repeat these letters
        for letter in range(0,len(self.currentlettersguessed)):
            if self.currentlettersguessed[letter] in self.currentword:
                if self.currentlettersguessed[letter] in self.currentlettersinword:
                    continue
                else:
                    self.currentlettersinword.append(self.currentlettersguessed[letter])
        if self.currentlettersinword:
            print(f'The letters {*self.currentlettersinword,} are in the word!')
            if self.currentlettersinrightplace:
                print(f'The letters {self.currentlettersinrightplace} are in the right place of {self.currentlettersinrightplaceindex} from place 1-5!')
            else:
                print('None of the letters are in the right place!')
        else:
            print('None of the letters are in the word!')
        #Return unique letters guessed so far and pending letters in the alphabet sorted
        lettersguessed = set(self.currentlettersguessed)
        alphabetlist = string.ascii_lowercase
        lettersmissing = list(set(lettersguessed)^set(alphabetlist))
        lettersmissing.sort()
        print(f'Unique letters guessed so far {lettersguessed}')
        print(f'Unique letters that have not been used {lettersmissing}')
        #Neat format that shows which place of the word you have gotten so far
        attemptedword = ''
        attemptedindex = 0
        for letter in range(1,6):
            if letter in self.currentlettersinrightplaceindex:
                attemptedword += self.currentlettersinrightplace[attemptedindex]
                attemptedindex += 1
            else:
                attemptedword += 'x'
        print(f'Attempted word so far is: {attemptedword}')

def replay(): #Check to see if the player wants to play again

    return input('Do you want to play again? Enter Yes or No: ').lower().startswith('y')

print('Welcome to Wordle!')
wordlegame = Wordle()
wordlegame.gamestart() #Inititates array of letters from text document

while True:
    # Resets the current word and arrays
    wordlegame.getword()
    wordlegame.currentlettersguessed = []
    wordlegame.currentlettersinword = []
    wordlegame.currentlettersinrightplace = []
    wordlegame.currentlettersinrightplaceindex = []

    #Check to see if the player wants to play

    play_game = input('Are you ready to play? Enter Yes or No.')

    if play_game.lower()[0] == 'y':
        game_on = True
    else:
        break

    while game_on:
        if len(wordlegame.currentlettersguessed) >= 30: #Ends game if the player has guessed more than 5 words
            print(f'Game Over! You have ran out of attempts! The correct word was {wordlegame.currentword}')
            break
        if wordlegame.playerguess() == True: #Ends game if the player guesses the word properly
            print(f'Congratulations the word was {wordlegame.currentword}!')
            break
        wordlegame.displayguesses()
        wordlegame.wincheck()

    if not replay():
        break


import pandas as pd
import nltk
from nltk.corpus import stopwords
from nltk.stem import SnowballStemmer, WordNetLemmatizer

#Requirments
nltk.download('wordnet')
nltk.download('stopwords')
stop_words = set(stopwords.words('english'))

stemmer = SnowballStemmer('english')
lemmatizer = WordNetLemmatizer()

def preprocess_sentence(sentence):

    sentence = sentence.lower()
    sentence = list(sentence.split())
    # sentence = list(set(sentence.split())) # Removing duplicates

    sentence = [word for word in sentence if not word in stop_words] # Removing stopwords

    sentence = [stemmer.stem(word) for word in sentence] # Stemming

    sentence = [lemmatizer.lemmatize(word) for word in sentence] # Lemmatization
    return sentence


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

"""
CNN梯度Demo
"""

import numpy as np
from NeuralNetwork.ANN.activators import IdentityActivator
from NeuralNetwork.CNN import cnn_math_utils

def gradient_check():
    """
    梯度检查
    """

    # 设计一个误差函数，取所有节点输出项之和
    error_function = lambda o: o.sum()

    # 计算forward值
    a, b, cl = cnn_math_utils.load_test()
    cl.forward(a)

    # 求取sensitivity map
    sensitivity_array = np.ones(cl.output_array.shape, dtype=np.float64)

    # 计算梯度
    cl.backward(a, sensitivity_array, IdentityActivator())

    # 检查梯度
    epsilon = 10e-4
    for d in range(cl.filters[0].weights_grad.shape[0]):
        for i in range(cl.filters[0].weights_grad.shape[1]):
            for j in range(cl.filters[0].weights_grad.shape[2]):
                cl.filters[0].weights[d, i, j] += epsilon
                cl.forward(a)
                err1 = error_function(cl.output_array)
                cl.filters[0].weights[d, i, j] -= 2 * epsilon
                cl.forward(a)
                err2 = error_function(cl.output_array)
                expect_grad = (err1 - err2) / (2 * epsilon)
                cl.filters[0].weights[d, i, j] += epsilon
                print('weights(%d,%d,%d): expected - actural %f - %f' % (d, i, j, expect_grad, cl.filters[0].weights_grad[d, i, j]))

if __name__=='__main__':
    gradient_check()


import random

word_list = ["apple", "pear", "banana", "peach", "grape"]
print(word_list)

word = random.choice(word_list)
print(word)

user_guess = input("Choose a letter: ")

if len(user_guess) == 1 and user_guess.isalpha():
    print("Good Guess")
else:
    print("not valid")


from odoo import api, fields, models

class MailComposeMessage(models.TransientModel):
    _inherit = "mail.compose.message"

    @api.model
    def default_get(self, fields_list):
        res = super(MailComposeMessage, self).default_get(fields_list)
        res.setdefault(
            "autofollow_recipients", self.env.context.get("mail_post_autofollow", False)
        )
        return res

    autofollow_recipients = fields.Boolean(
        string="Make recipients followers",
        help="""if checked, the additional recipients will be added as\
        followers on the related object""",
    )

    def send_mail(self, auto_commit=False):
        for wizard in self:
            super(
                MailComposeMessage,
                wizard.with_context(mail_post_autofollow=wizard.autofollow_recipients),
            ).send_mail(auto_commit=auto_commit)
        return True


from libs import *
import Enemys
import sys

n = nave()
e = list()

for a in range(8):
    for b in range(4):
        e.append(enemy(Enemys.Aliens[randint(0,2)],a*5,b*6))
tiros = []

class Vitoria:
    def __init__(self, master):
        photo = PhotoImage(file='youwin.png')
        self.w = w = Label(master, image=photo)

        width = photo.width()
        height = photo.height()

        master.geometry("%dx%d+0+0" % (width, height))
        w.photo = photo
        w.pack()

        self.exit = Button(master, text="Fechar", command=sys.exit, height=1, width=3, fg= "white",bg = "black")
        self.exit.config(font=("Courier", 10))
        self.exit.place(x=130, y=180)

def v():
    root = Tk()
    app = Vitoria(root)
    root.mainloop()

def myReshape(w, h):
    glViewport(0, 0, w, h)
    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    gluPerspective(70, float(w)/h+0.2, 0.1, 60)
    glMatrixMode(GL_MODELVIEW)
    glutPostRedisplay()

def myKeyboard(tecla,x,y):
    if(tecla == GLUT_KEY_RIGHT):
        n.move('r')
    if(tecla == GLUT_KEY_LEFT):
        n.move('l')
    if(tecla == GLUT_KEY_UP):
        tiros.append(n.tiro(n))

def mytimetiro(time):

    for t in tiros:
        t.pos[1] += 0.5
        if(t.pos[1] > 60):
            tiros.remove(t)

    glutPostRedisplay()
    glutTimerFunc(2,mytimetiro,0)

def mytimeEnemy(time):
    for a in e:
        a.y -= 0.05
        if(a.face < -1):
            close()

    glutPostRedisplay()
    glutTimerFunc(3,mytimeEnemy,0)

def myDisplay():
    glClearColor(0.2, 0.2, 0.2, 1.0)
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

    glLoadIdentity()
    gluLookAt(30.5,-6,15,
              30.5,9,0,
              0, 1, 0)

    n.draw_nave()
    n.draw_tiro(tiros)

    r = colisao(n,tiros,e)
    if(r != -1 and r != "Game Over"):
        e.remove(r[0])
        tiros.remove(r[1])
    elif(r == "Game Over"):
        print(r)
        close()
    if(len(e) == 0):
        v()

    for a in e:
        a.draw_enemy()

    glutSwapBuffers()

def main():
    glutInit(sys.argv)
    glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA)
    glutInitWindowSize(1400, 800)
    glutInitWindowPosition(0, 0)
    window = glutCreateWindow("Space Invader")
    glEnable(GL_DEPTH_TEST)

    glutReshapeFunc(myReshape)
    glutDisplayFunc(myDisplay)
    glutIdleFunc(myDisplay)
    glutSpecialFunc(myKeyboard)
    glutTimerFunc(2,mytimetiro,0)
    glutTimerFunc(2,mytimeEnemy,0)
    glutMainLoop()


# ~ 1:40
# t = int(input())

def find_parent(parent, x):
    if parent[x] != x:
        parent[x] = find_parent(parent, parent[x])
    return parent[x]

def union_parent(parent, a, b):
    a = find_parent(parent, a)
    b = find_parent(parent, b)
    if a < b:
        parent[b] = a
    else:
        parent[a] = b

n = int(input())
rank = list(map(int, input().split()))

parent = list(range(n+1))

m = int(input())
change = []
for _ in range(m):
    change.append(tuple(map(int, input().split())))

for a, b in change:
    union_parent(parent, a, b)

print(parent)
# case: ?
def check():
    new_rank = [r for r in rank]
    for a, b in change:
        if parent[a] != parent[b]:
            print('IMPOSSIBLE')
            return

        apos = rank.index(a)
        bpos = rank.index(b)
        order = 'asc'
        if apos < bpos:
            start, end = apos, bpos
        else:
            order = 'desc'
            start, end = bpos, apos

        if apos-bpos > 1: # 사이에 다른 팀 존재
            for c in rank[start+1:end]:
                if parent[c] != parent[a]:
                    print('?')
                    return

        print(apos,bpos,order)
        # 검사 통과한 경우 순위 변경
        napos, nbpos = new_rank.index(a), new_rank.index(b)
        if (order == 'asc' and napos < nbpos) or (order == 'desc' and napos > nbpos):
            new_rank[napos], new_rank[nbpos] = new_rank[nbpos], new_rank[napos]

    print(new_rank)
    return

check()

# case: impossible

# case: possible


#!/usr/bin/env python3

import syd

# -----------------------------------------------------------------------------
def find_patient(db, patient_name):

    patient = syd.find_one(db['Patient'], name = patient_name)
    if patient == None:
        s = f'Cannot find patient with name {patient_name}'
        syd.raise_except(s)

    return patient

# -----------------------------------------------------------------------------
def find_series(db, patient_id, grep):

    # select study from this patient
    studies = syd.find(db['DicomStudy'], patient_id = patient_id)
    study_ids = [s.id for s in studies]

    # series
    elements = syd.find(db['DicomSeries'], dicom_study_id=study_ids)

    # select series
    grep.append('%ignore')
    elements, s = syd.grep(db, 'DicomSeries', elements, grep=grep)

    return elements, s

# -----------------------------------------------------------------------------
def find_images(db, patient_id, grep):

    elements = syd.find(db['Image'], patient_id = patient_id)
    elements, s = syd.grep(db, 'Image', elements, grep=grep)

    return elements, s


import os
import json
import argparse

parser = argparse.ArgumentParser(description="Select label over twenty for clf task")
parser.add_argument("--babel_path", type=str, default="/private/home/yijunq/datasets/babel_v1.0_release")
parser.add_argument("--amass_path_ann", type=str, default="../datasets/babelsync.json")
parser.add_argument("--jname", type=str, default="../datasets/babelclf_ems.json")
args = parser.parse_args()

cur_annt = json.load(open(args.amass_path_ann))
# babel_trn = json.load(open(os.path.join(args.babel_path,"train.json")))
babel_val = json.load(open(os.path.join(args.babel_path,"val.json")))

new_dict = {}
label_dict = {}

num_acts = 0
match_dict = {}

label_over_twenty = [
 'place',
 'turn',
 'walk',
 'take',
 'stand with arms down',
 'stand',
 'turn left',
 'bend down',
 'tpose',
 'step forward',
 'step backward',
 'sit down',
 'walk forward',
 'step backwards',
 'turn around',
 'look down',
 'stand still',
 'walk backwards',
 'stand in place',
 'turn right',
 'apose',
 'stand up',
 'pick up object',
 'walk back',
 'stumble',
 'put down object',
 'bend over',
 'sit',
 'knock',
 'step back',
 'turn back',
 'step up',
 'step down',
 'squat',
 'jump',
 'run',
 'walk backward',
 'kick',
 'pick up',
 'turn around to the left',
 'crouch',
 'jog',
 'pick something up with right hand',
 'set down',
 'throw',
 'catch',
 'place object',
 'catch the ball',
 'catch ball',
 'stop',
 'turn around left',
 'throw the ball',
 'right foot forward']

# for k,v in babel_trn.items():
#     feat_path = "/".join(v["feat_p"].split("/")[1:])
#     match_dict[feat_path] = []
#     try:
#         dur = v["dur"]
#         frame_labels = v["frame_ann"]["labels"]
#         for frame_label in frame_labels:
#             proc_label = frame_label["proc_label"]
#             if proc_label not in label_dict:
#                 label_dict[proc_label] = num_acts
#                 num_acts+=1
#             start = frame_label["start_t"]/dur
#             end = frame_label["end_t"]/dur
#             match_dict[feat_path].append({"label":proc_label,"dur":[start,end]})
#     except:
#         print("ANNT {} LOAD ERROR".format(k))

for k,v in babel_val.items():
    feat_path = "/".join(v["feat_p"].split("/")[1:])
    match_dict[feat_path] = []
    try:
        dur = v["dur"]
        frame_labels = v["frame_ann"]["labels"]
        for frame_label in frame_labels:
            proc_label = frame_label["proc_label"]
            if proc_label not in label_dict:
                label_dict[proc_label] = num_acts
                num_acts+=1
            start = frame_label["start_t"]/dur
            end = frame_label["end_t"]/dur
            match_dict[feat_path].append({"label":proc_label,"dur":[start,end]})
    except:
        print("ANNT {} LOAD ERROR".format(k))

f = open("../datasets/babelsync-clf-splits/val","w")
for k,v in cur_annt.items():
    trim_start = v["trim"]["start"]
    trim_end = v["trim"]["end"]
    path = v["path"]
    max_overlps = 0
    if path not in match_dict:
        continue
    infos = match_dict[path]
    max_ovlp = 0
    max_ovlp_id = -1
    for infoid in range(len(infos)):
        info = infos[infoid]
        try:
            ovlp = (min(trim_end,info["dur"][1])-max(trim_start,info["dur"][0]))/(trim_end-trim_start)
        except:
            print(cur_annt[k])
            print(k,trim_start,trim_end)
            raise RuntimeError("check org annt")
        if ovlp>max_ovlp:
            max_ovlp = ovlp
            max_ovlp_id = infoid
    if max_ovlp_id == -1:
        print("ORG ANNT {} MIS MATCH".format(k))
        continue
    if infos[max_ovlp_id]["label"] in label_over_twenty:
        new_dict[k] = v
        new_dict[k]["labels"] = [label_over_twenty.index(infos[max_ovlp_id]["label"])]
        f.write(k+"\n")

json_str = json.dumps(new_dict,indent=4)
with open(args.jname,'w') as save_json:
    save_json.write(json_str)