Example #1
0
class Panel(models.Model):
    _name = 'favite_bif.panel'
    _inherit = ['favite_common.geometry']

    _sql_constraints = [
        ('name_uniq', 'unique (name,bif_id)', "Name already exists !"),
    ]

    active = fields.Boolean(default=True)

    @api.model
    def _default_geo(self):
        geo = {
            "filter": {
                "objs": []
            },
        }
        return geo

    geo = fields.Jsonb(string="geometry value", default=_default_geo)
    glass = fields.Jsonb(related='gmd_id.glass', readonly=True)

    bif_id = fields.Many2one('favite_bif.bif', ondelete='cascade')
    gsp_id = fields.Many2one('favite_bif.gsp',
                             ondelete='set null',
                             domain="[('bif_id', '=', bif_id)]")

    gmd_id = fields.Many2one('favite_gmd.gmd', related='bif_id.gmd_id')
    camera_path = fields.Char(related='gmd_id.camera_path', readonly=True)
    camera_ini = fields.Text(related='gmd_id.camera_ini', readonly=True)

    @api.multi
    def get_formview_id(self, access_uid=None):
        return self.env.ref('favite_bif.favite_bif_panel_map').id
Example #2
0
class Pad(models.Model):
    _name = 'favite_bif.pad'   
    _inherit = ['favite_common.geometry']
    
    @api.one
    @api.depends('gmd_id','gmd_id.geo')
    def _compute_geo(self):
        self.geo['glass'] = self.gmd_id.geo['glass']
    
    geo = fields.Jsonb(string = "geometry value",compute='_compute_geo',store=True)   
    gmd_id = fields.Many2one('favite_gmd.gmd',ondelete='cascade')
    src_panel_id = fields.Many2one('favite_bif.panel',ondelete='set null',domain="[('gmd_id', '=', gmd_id)]") 
    
    camera_path = fields.Char(related='gmd_id.camera_path', readonly=True)
    camera_ini = fields.Text(related='gmd_id.camera_ini', readonly=True)
    
    @api.multi  
    def open_map(self):
        self.ensure_one()
        return {
            'type': 'ir.actions.act_window',
            'name': self.name,
            'res_model': self._name,
            'res_id': self.id,
            'view_id': self.env.ref('favite_bif.favite_bif_pad_map').id,
            'view_type': 'map',
            'view_mode': 'map',
            'target': 'current',
            'flags':{'hasSearchView':False}
            }
Example #3
0
class Panel(models.Model):
    _name = 'favite_bif.panel'   
    _inherit = ['favite_common.geometry']
    
    active = fields.Boolean(default=True)
    
    @api.model
    def _default_geo(self):
        geo = {
        "filter":{"objs":[]},
        }
        return geo
        
    @api.one
    @api.onchange('gmd_id','gmd_id.geo')
    def _compute_geo(self):
        self.geo['glass'] = self.gmd_id.geo['glass']
    
    geo = fields.Jsonb(string = "geometry value",default=_default_geo)   
       
    bif_id = fields.Many2one('favite_bif.bif',ondelete='cascade')  
    gsp_id = fields.Many2one('favite_bif.gsp',ondelete='set null',domain="[('bif_id', '=', bif_id)]")
    
    gmd_id = fields.Many2one('favite_gmd.gmd',related='bif_id.gmd_id')
    camera_path = fields.Char(related='gmd_id.camera_path', readonly=True)
    camera_ini = fields.Text(related='gmd_id.camera_ini', readonly=True)
    
    @api.multi
    def get_formview_id(self, access_uid=None):
        return self.env.ref('favite_bif.favite_bif_panel_map').id
Example #4
0
class Gsp(models.Model):
    _name = 'favite_bif.gsp'
    _inherit = ['favite_common.geometry']
    _order = 'id'

    #     _sql_constraints = [
    #         ('name_uniq', 'unique (name,bif_id)', "Name already exists !"),
    #     ]

    #     zone_enabletbz =  fields.Boolean(string='Enable tbz')
    #     zone_ids = fields.One2many('favite_bif.gsp_zone', 'gsp_id', string='Zone')

    def _default_geo(self, bif_id, src_panel_id):
        bif = self.env['favite_bif.bif'].browse(bif_id)
        panel = self.env['favite_bif.panel'].browse(src_panel_id)
        objs = bif.geo['panel']['objs']
        geo = {
            "zoneFrame": {
                "objs": []
            },
            "brightDomain": {
                "objs": []
            },
            "darkDomain": {
                "objs": []
            },
            "zone": {
                "objs": []
            },
            "polygon": {
                "objs": []
            },
            "circle": {
                "objs": []
            },
            "bow": {
                "objs": []
            },
            "panel": {
                "noselect": True,
                "readonly": True,
                'objs': [obj for obj in objs if obj['name'] == panel.name]
            }
        }
        return geo

    @api.one
    def _compute_name(self):
        self.name = 'gsp%d' % self.id

    @api.one
    def _compute_seq(self):
        gsp = self.env['favite_bif.gsp'].sudo().search([('id', '<', self.id),
                                                        ('bif_id', '=',
                                                         self.bif_id.id)])
        self.sequence = len(gsp)

    @api.one
    #    @api.depends('x_inspect_mode','x_miniledcompare_period','x_todcompare_period','x_multiperiodcompare_period','x_ps_basicperiod','x_neighorcompare_shortperiod_period')
    def _compute_period(self):
        if self.x_inspect_mode == 2:
            self.period = self.x_neighorcompare_shortperiod_period
        elif self.x_inspect_mode == 3:
            self.period = self.x_ps_basicperiod
        elif self.x_inspect_mode == 4:
            self.period = self.x_multiperiodcompare_period
        elif self.x_inspect_mode == 5:
            self.period = self.x_todcompare_period
        elif self.x_inspect_mode == 6:
            self.period = self.x_neighorcompare_shortperiod_period
        elif self.x_inspect_mode == 7:
            self.period = self.x_miniledcompare_period
        else:
            self.period = self.x_neighorcompare_shortperiod_period

    @api.multi
    def refresh(self):
        for g in self:
            objs = g.bif_id.geo['panel']['objs']

            geo = g.geo
            geo['panel'] = {
                "noselect": True,
                "readonly": True,
                'objs':
                [obj for obj in objs if obj['name'] == g.src_panel_id.name]
            }
            g.write({'geo': geo})

    name = fields.Char(compute='_compute_name')
    sequence = fields.Integer(compute='_compute_seq')
    period = fields.NumericArray(compute='_compute_period')
    geo = fields.Jsonb(string="geometry value")
    glass = fields.Jsonb(related='gmd_id.glass', readonly=True)
    bif_id = fields.Many2one('favite_bif.bif', ondelete='cascade')
    gmd_id = fields.Many2one('favite_gmd.gmd', related='bif_id.gmd_id')
    pad_id = fields.Many2one(
        'favite_bif.pad',
        ondelete='set null',
        domain="[('gmd_id', '=', gmd_id),('src_panel_id', '=', src_panel_id)]")
    src_panel_id = fields.Many2one('favite_bif.panel',
                                   ondelete='cascade',
                                   domain="[('bif_id', '=', bif_id)]")

    camera_path = fields.Char(related='gmd_id.camera_path', readonly=True)
    camera_ini = fields.Text(related='gmd_id.camera_ini', readonly=True)

    @api.model
    def newFromPanel(self, bif_id, src_panel_name):
        panel = self.env['favite_bif.panel'].sudo().search([
            ('name', '=', src_panel_name), ('bif_id', '=', bif_id)
        ])
        gsp = self.create({'bif_id': bif_id, 'src_panel_id': panel.id})
        return gsp.id

    @api.model
    def create(self, vals):
        vals['geo'] = self._default_geo(vals['bif_id'], vals['src_panel_id'])
        return super(Gsp, self).create(vals)

    @api.one
    def write(self, vals):
        for g in self:

            inspect_mode = vals[
                'x_inspect_mode'] if 'x_inspect_mode' in vals else g.x_inspect_mode

            if inspect_mode == 2:
                period = vals[
                    'x_neighorcompare_shortperiod_period'] if 'x_neighorcompare_shortperiod_period' in vals else g.x_neighorcompare_shortperiod_period
            elif inspect_mode == 3:
                period = vals[
                    'x_ps_basicperiod'] if 'x_ps_basicperiod' in vals else g.x_ps_basicperiod
            elif inspect_mode == 4:
                period = vals[
                    'x_multiperiodcompare_period'] if 'x_multiperiodcompare_period' in vals else g.x_multiperiodcompare_period
            elif inspect_mode == 5:
                period = vals[
                    'x_todcompare_period'] if 'x_todcompare_period' in vals else g.x_todcompare_period
            elif inspect_mode == 6:
                period = vals[
                    'x_neighorcompare_shortperiod_period'] if 'x_neighorcompare_shortperiod_period' in vals else g.x_neighorcompare_shortperiod_period
            elif inspect_mode == 7:
                period = vals[
                    'x_miniledcompare_period'] if 'x_miniledcompare_period' in vals else g.x_miniledcompare_period

            if period:
                if not 'geo' in vals:
                    vals['geo'] = g.geo

                for o in vals['geo']['zone']['objs']:
                    x = (o['points'][0]['x'] + o['points'][1]['x']) / 2
                    y = (o['points'][0]['y'] + o['points'][1]['y']) / 2
                    o['points'][0]['x'] = x - float(period[0] / 2)
                    o['points'][0]['y'] = y - float(period[1] / 2)
                    o['points'][1]['x'] = x + float(period[0] / 2)
                    o['points'][1]['y'] = y + float(period[1] / 2)

        return super(Gsp, self).write(vals)

    @api.multi
    def edit_dialog(self):
        form_view = self.env.ref('favite_bif.favite_bif_gsp_map')
        return {
            'name': _('Gsp'),
            'res_model': self._name,
            'res_id': self.id,
            'views': [
                (form_view.id, 'form'),
            ],
            'type': 'ir.actions.act_window',
            'target': 'new'
        }

    @api.multi
    def open_map(self):
        self.ensure_one()
        return {
            'type': 'ir.actions.act_window',
            'name': self.name,
            'res_model': self._name,
            'res_id': self.id,
            'view_id': self.env.ref('favite_bif.gsp_form').id,
            'view_type': 'map',
            'view_mode': 'map',
            'target': 'current',
            'flags': {
                'hasSearchView': False
            },
        }

    @api.multi
    def open_pad_list(self):
        ctx = dict(
            default_gmd_id=self.gmd_id.id,
            default_src_panel_id=self.src_panel_id.id,
        )
        return {
            'type':
            'ir.actions.act_window',
            'name':
            'Pad',
            'res_model':
            'favite_bif.pad',
            'view_mode':
            'kanban,form',
            'view_id':
            False,
            'target':
            'current',
            'flags': {
                'import_enabled': False
            },
            'domain': [('src_panel_id', '=', self.src_panel_id.id),
                       ('gmd_id', '=', self.gmd_id.id)],
            'context':
            ctx,
        }

    def export_image(self, directory_ids):
        if len(self.geo['zoneFrame']['objs']) == 0:
            return
        imgWidth = int(self.geo['zoneFrame']['objs'][0]['imgWidth3'])
        imgHeight = int(self.geo['zoneFrame']['objs'][0]['imgHeight3'])
        blocks = json.loads(self.geo['zoneFrame']['objs'][0]['strBlocks3'])

        origin = Image.new('L', (imgWidth, imgHeight))
        left = 0
        top = 0
        for x in range(len(blocks)):
            for y in range(len(blocks[x]) - 1, -1, -1):
                b = blocks[x][y]
                if b is None or b['bHasIntersection'] == False:
                    continue

                try:
                    #imgFile = '%s/Image/IP%d/jpegfile/AoiL_IP%d_scan%d_block%d.jpg' % (self.camera_path,b['iIPIndex']+1,b['iIPIndex'],b['iScanIndex'],b['iBlockIndex'])
                    imgFile = self.gmd_id.compute_jpeg_path(
                        b['iIPIndex'], b['iScanIndex'], b['iBlockIndex'])
                    with Image.open(imgFile) as im:
                        im = im.transpose(Image.FLIP_TOP_BOTTOM)
                        region = im.crop(
                            (b['iInterSectionStartX'],
                             im.height - (b['iInterSectionStartY'] +
                                          b['iInterSectionHeight']),
                             b['iInterSectionStartX'] +
                             b['iInterSectionWidth'],
                             im.height - b['iInterSectionStartY']))
                        origin.paste(region, (left, top))
                        if y == 0:
                            left += region.width
                            top = 0
                        else:
                            top += region.height
                except:
                    raise UserError("No such file:%s" % (imgFile))
        origin = origin.transpose(Image.FLIP_TOP_BOTTOM)
        for d in directory_ids:
            dir = os.path.join(d.name, 'bif')
            if not os.path.isdir(dir):
                os.makedirs(dir)
            path = os.path.join(
                dir, self.bif_id.name + '_' + self.name + '_org.bmp')
            with open(path, 'wb') as f:
                origin.save(f, format="BMP")

        imgWidth = int(self.geo['zoneFrame']['objs'][0]['imgWidth'])
        imgHeight = int(self.geo['zoneFrame']['objs'][0]['imgHeight'])
        blocks = json.loads(self.geo['zoneFrame']['objs'][0]['strBlocks'])

        zone_origin = Image.new('L', (imgWidth, imgHeight))
        left = 0
        top = 0
        for x in range(len(blocks)):
            for y in range(len(blocks[x]) - 1, -1, -1):
                b = blocks[x][y]
                if b is None or b['bHasIntersection'] == False:
                    continue

                try:
                    #imgFile = '%s/Image/IP%d/jpegfile/AoiL_IP%d_scan%d_block%d.jpg' % (self.camera_path,b['iIPIndex']+1,b['iIPIndex'],b['iScanIndex'],b['iBlockIndex'])
                    imgFile = self.gmd_id.compute_jpeg_path(
                        b['iIPIndex'], b['iScanIndex'], b['iBlockIndex'])
                    with Image.open(imgFile) as im:
                        im = im.transpose(Image.FLIP_TOP_BOTTOM)
                        region = im.crop(
                            (b['iInterSectionStartX'],
                             im.height - (b['iInterSectionStartY'] +
                                          b['iInterSectionHeight']),
                             b['iInterSectionStartX'] +
                             b['iInterSectionWidth'],
                             im.height - b['iInterSectionStartY']))
                        zone_origin.paste(region, (left, top))
                        if y == 0:
                            left += region.width
                            top = 0
                        else:
                            top += region.height
                except:
                    raise UserError("No such file:%s" % (imgFile))
        zone_origin = zone_origin.transpose(Image.FLIP_TOP_BOTTOM)
        for d in directory_ids:
            dir = os.path.join(d.name, 'bif')
            if not os.path.isdir(dir):
                os.makedirs(dir)
            path = os.path.join(
                dir, self.bif_id.name + '_' + self.name + '_zone_org.bmp')
            with open(path, 'wb') as f:
                zone_origin.save(f, format="BMP")

        zone = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
        b = np.array(
            [[[0, 0], [0, imgHeight], [imgWidth, imgHeight], [imgWidth, 0]]],
            dtype=np.int32)
        cv2.fillPoly(
            zone, b,
            int(self.geo['zone']['background'] if 'background' in
                self.geo['zone'] else '0'))
        for o in self.geo['zone']['objs']:
            if len(o['points']) < 2:
                continue

            p2 = [[int(p['offsetX']), int(p['offsetY'])] for p in o['points']]

            b = np.array([p2], dtype=np.int32)
            cv2.fillPoly(zone, b, int(o['level'] if 'level' in o else '15'))

        for d in directory_ids:
            dir = os.path.join(d.name, 'bif')
            if not os.path.isdir(dir):
                os.makedirs(dir)
            path = os.path.join(
                dir, self.bif_id.name + '_' + self.name + '_zone.bmp')
            cv2.imwrite(path, zone)

        obj = self.geo['panel']['objs'][0]
        p0 = obj['points'][0]
        p1 = obj['points'][1]
        p2 = obj['points'][2]
        p3 = obj['points'][3]
        left = min(p0['x'], p1['x'], p2['x'], p3['x'])
        right = max(p0['x'], p1['x'], p2['x'], p3['x'])
        bottom = min(p1['y'], p2['y'], p0['y'], p3['y'])
        top = max(p1['y'], p2['y'], p0['y'], p3['y'])

        imgWidth = self.bif_id.x_global_polygon_width
        rate = imgWidth / (right - left)
        imgHeight = int(rate * (top - bottom))
        polygon = np.zeros([imgHeight, imgWidth], dtype=np.uint8)
        for o in self.geo['polygon']['objs']:
            p2 = []
            for p in o['points']:
                p2.append([(p['x'] - left) * rate, (top - p['y']) * rate])
            b = np.array([p2], dtype=np.int32)
            cv2.fillPoly(polygon, b, 255)

        def _calculate_cicular(x1, y1, x2, y2, x3, y3):
            e = 2 * (x2 - x1)
            f = 2 * (y2 - y1)
            g = x2 * x2 - x1 * x1 + y2 * y2 - y1 * y1
            a = 2 * (x3 - x2)
            b = 2 * (y3 - y2)
            c = x3 * x3 - x2 * x2 + y3 * y3 - y2 * y2

            x = (g * b - c * f) / (e * b - a * f)
            y = (a * g - c * e) / (a * f - b * e)
            r = math.sqrt((x - x1) * (x - x1) + (y - y1) * (y - y1))
            return {
                'x': x,
                'y': y,
                'r': r
            }

        for o in self.geo['bow']['objs']:
            p = o['points']
            x1 = (p[0]['x'] - left) * rate
            y1 = (top - p[0]['y']) * rate
            x2 = (p[1]['x'] - left) * rate
            y2 = (top - p[1]['y']) * rate
            x3 = (p[2]['x'] - left) * rate
            y3 = (top - p[2]['y']) * rate
            res = _calculate_cicular(x1, y1, x2, y2, x3, y3)
            x = int(res['x'])
            y = int(res['y'])
            r = int(res['r'])

            p2 = [[x, y], [int(x1), int(y1)], [int(x3), int(y3)]]
            b = np.array([p2], dtype=np.int32)
            startAngle = math.degrees(math.atan2(y1 - y, x1 - x))
            endAngle = math.degrees(math.atan2(y3 - y, x3 - x))
            dir = (x2 - x1) * (y3 - y2) - (y2 - y1) * (x3 - x2)
            if dir > 0:
                startAngle = math.degrees(math.atan2(y1 - y, x1 - x))
                endAngle = math.degrees(math.atan2(y3 - y, x3 - x))
            else:
                endAngle = math.degrees(math.atan2(y1 - y, x1 - x))
                startAngle = math.degrees(math.atan2(y3 - y, x3 - x))

            cv2.ellipse(polygon, (x, y), (r, r), 0, startAngle, endAngle, 255,
                        cv2.FILLED)

            if abs(startAngle - endAngle) > 180:
                cv2.fillPoly(polygon, b, 255)
            else:
                cv2.fillPoly(polygon, b, 0)

        for o in self.geo['circle']['objs']:
            p = o['points']
            x1 = (p[0]['x'] - left) * rate
            y1 = (top - p[0]['y']) * rate
            x2 = (p[1]['x'] - left) * rate
            y2 = (top - p[1]['y']) * rate
            x3 = (p[2]['x'] - left) * rate
            y3 = (top - p[2]['y']) * rate
            res = _calculate_cicular(x1, y1, x2, y2, x3, y3)
            x = int(res['x'])
            y = int(res['y'])
            r = int(res['r'])
            cv2.circle(polygon, (x, y), int(r), 255, cv2.FILLED)

        for d in directory_ids:
            dir = os.path.join(d.name, 'bif')
            if not os.path.isdir(dir):
                os.makedirs(dir)
            path = os.path.join(
                dir, self.bif_id.name + '_' + self.name + '_polygon.bmp')
            cv2.imwrite(path, polygon)

    def export_string(self, index):
        geo = self._export_geo()

        strPolygon = 'gsp.%d.polygon = %s\n' % (index,
                                                json.dumps(geo['polygon']))
        strPolygon += 'gsp.%d.circle = %s\n' % (index, json.dumps(
            geo['circle']))
        strPolygon += 'gsp.%d.bow = %s\n' % (index, json.dumps(geo['bow']))

        num = len(geo['zone']['objs'])
        strZone = 'gsp.%d.zone.number = %d\n' % (index, num)
        for i in range(0, num):
            strZone += 'gsp.%d.zone.%d.obj = %s\n' % (
                index, i, json.dumps(geo['zone']['objs'][i]))
            strZone += 'gsp.%d.zone.%d.level = %s\n' % (
                index, i, geo['zone']['objs'][i]['level']
                if 'level' in geo['zone']['objs'][i] else '15')
            strZone += 'gsp.%d.zone.%d.darktol = %s\n' % (
                index, i, geo['zone']['objs'][i]['darktol']
                if 'darktol' in geo['zone']['objs'][i] else '15')
            strZone += 'gsp.%d.zone.%d.brighttol = %s\n' % (
                index, i, geo['zone']['objs'][i]['brighttol']
                if 'brighttol' in geo['zone']['objs'][i] else '15')
            strZone += 'gsp.%d.zone.%d.longedgeminsize = %s\n' % (
                index, i, geo['zone']['objs'][i]['longedgeminsize']
                if 'longedgeminsize' in geo['zone']['objs'][i] else '0')
            strZone += 'gsp.%d.zone.%d.longedgemaxsize = %s\n' % (
                index, i, geo['zone']['objs'][i]['longedgemaxsize']
                if 'longedgemaxsize' in geo['zone']['objs'][i] else '0')
            strZone += 'gsp.%d.zone.%d.shortedgeminsize = %s\n' % (
                index, i, geo['zone']['objs'][i]['shortedgeminsize']
                if 'shortedgeminsize' in geo['zone']['objs'][i] else '0')
            strZone += 'gsp.%d.zone.%d.shortedgemaxsize = %s\n' % (
                index, i, geo['zone']['objs'][i]['shortedgemaxsize']
                if 'shortedgemaxsize' in geo['zone']['objs'][i] else '0')

        strDomain = 'gsp.%d.zoneFrame = %s\n' % (index,
                                                 json.dumps(geo['zoneFrame']))

        num = len(geo['darkDomain']['objs'])
        strDark = 'gsp.%d.domain.dark.number = %d\n' % (index, num)
        for i in range(0, num):
            obj = geo['darkDomain']['objs'][i]
            p1 = obj['points'][0]
            p2 = obj['points'][1]
            left = min(p1['offsetX'], p2['offsetX'])
            right = max(p1['offsetX'], p2['offsetX'])
            bottom = min(p1['offsetY'], p2['offsetY'])
            top = max(p1['offsetY'], p2['offsetY'])
            strDark += 'gsp.%d.domain.dark.%d.obj = %s\n' % (index, i,
                                                             json.dumps(obj))
            strDark += 'gsp.%d.domain.dark.%d.position = %d,%d,%d,%d\n' % (
                index, i, int(left), int(top), int(right), int(bottom))

        num = len(geo['brightDomain']['objs'])
        strBright = 'gsp.%d.domain.bright.number = %d\n' % (index, num)
        for i in range(0, num):
            obj = geo['brightDomain']['objs'][i]
            p1 = obj['points'][0]
            p2 = obj['points'][1]
            left = min(p1['offsetX'], p2['offsetX'])
            right = max(p1['offsetX'], p2['offsetX'])
            bottom = min(p1['offsetY'], p2['offsetY'])
            top = max(p1['offsetY'], p2['offsetY'])
            strBright += 'gsp.%d.domain.bright.%d.obj = %s\n' % (
                index, i, json.dumps(obj))
            strBright += 'gsp.%d.domain.bright.%d.position = %d,%d,%d,%d\n' % (
                index, i, int(left), int(top), int(right), int(bottom))

        strParameter = 'gsp.%d.name = %s\n' % (index, self.name)
        fields_data = self.env['ir.model.fields']._get_manual_field_data(
            self._name)
        for name, field in sorted(self._fields.items(), key=lambda f: f[0]):
            if not field.manual or not name.startswith('x_'):
                continue
            elif field.type == 'boolean' or field.type == 'selection':
                strParameter += 'gsp.%d.%s = %d\n' % (
                    index, fields_data[name]['complete_name'], self[name])
            else:
                strParameter += 'gsp.%d.%s = %s\n' % (
                    index, fields_data[name]['complete_name'],
                    field.convert_to_export(self[name], self))
        return strParameter + strPolygon + strDomain + strZone + strDark + strBright

    @api.model
    def import_string(self, par, gspname, gspindex, bif, panel):
        self = self.with_context(default_bif_id=bif.id,
                                 default_src_panel_id=panel.id)

        prefix = 'gsp.%s.' % gspindex
        obj = {'name': gspname}
        geo = {
            "zoneFrame": {
                "objs": []
            },
            "brightDomain": {
                "objs": []
            },
            "darkDomain": {
                "objs": []
            },
            "zone": {
                "objs": []
            },
            "polygon": {
                "objs": []
            },
            "circle": {
                "objs": []
            },
            "bow": {
                "objs": []
            },
            "panel": {
                "noselect":
                True,
                "readonly":
                True,
                'objs': [
                    obj for obj in bif.geo['panel']['objs']
                    if obj['name'] == panel.name
                ]
            }
        }

        #         pad_item = 'gsp.%s.padfile'% gspindex
        #         if pad_item in par:
        #             name,_ = par[pad_item].split('.')
        #             pad = self.env['favite_bif.pad'].sudo().search([('name','=',name),('src_panel_id','=',panel.id)])
        #             if pad:
        #                 obj['pad_id'] = pad.id
        #             else:
        #                 raise UserError("File(%s) must first be imported!" % par[pad_item])

        geo['polygon'] = json.loads(par['gsp.%s.polygon' % gspindex])
        geo['circle'] = json.loads(par['gsp.%s.circle' % gspindex])
        geo['bow'] = json.loads(par['gsp.%s.bow' % gspindex])
        geo['zoneFrame'] = json.loads(par['gsp.%s.zoneFrame' % gspindex])

        num = int(par.get('gsp.%s.domain.dark.number' % gspindex, 0))
        for i in range(0, num):
            o = json.loads(par['gsp.%s.domain.dark.%d.obj' % (gspindex, i)])
            geo['darkDomain']['objs'].append(o)

        num = int(par.get('gsp.%s.domain.bright.number' % gspindex, 0))
        for i in range(0, num):
            o = json.loads(par['gsp.%s.domain.bright.%d.obj' % (gspindex, i)])
            geo['brightDomain']['objs'].append(o)

        num = int(par.get('gsp.%s.zone.number' % gspindex, 0))
        for i in range(0, num):
            o = json.loads(par['gsp.%s.zone.%d.obj' % (gspindex, i)])
            geo['zone']['objs'].append(o)

        fields_data = self.env['ir.model.fields']._get_manual_field_data(
            self._name)
        for name, field in self._fields.items():
            if not field.manual or not name.startswith('x_'):
                continue

            complete_name = prefix + fields_data[name]['complete_name']
            if complete_name.lower() in par:
                value = par[complete_name.lower()]
                obj[name] = field.convert_to_cache(value, self)
                if isinstance(obj[name], bool):
                    obj[name] = value == '1'

        obj['geo'] = geo
        return self.create(obj)._import_geo()
Example #5
0
class Pad(models.Model):
    _name = 'favite_bif.pad'
    _inherit = ['favite_common.geometry']
    _sql_constraints = [
        ('name_uniq', 'unique (name)', "Name already exists !"),
    ]

    @api.model
    def _default_geo(self):
        gmd = self.env['favite_gmd.gmd'].browse(
            self._context['default_gmd_id'])
        panel = self.env['favite_bif.panel'].browse(
            self._context['default_src_panel_id'])

        geo = {
            "mark": {
                "objs": []
            },
            "submark": {
                "objs": [],
                "no_add": True
            },
            "regular": {
                "objs": []
            },
            "filterregion": {
                "objs": []
            },
            "frame": {
                "objs": [],
                "no_add": True
            },
            "region": {
                "objs": [],
                "no_add": True,
                "readonly": True
            },
            "panel": {
                "noselect": True,
                "readonly": True,
                'objs': []
            }
        }

        p = panel.gsp_id.geo['panel']['objs'][0]
        geo['panel']['objs'].append(p)

        return geo

    geo = fields.Jsonb(string="geometry value", default=_default_geo)
    glass = fields.Jsonb(related='gmd_id.glass', readonly=True)
    gmd_id = fields.Many2one('favite_gmd.gmd', ondelete='cascade')
    src_panel_id = fields.Many2one('favite_bif.panel',
                                   ondelete='cascade',
                                   domain="[('gmd_id', '=', gmd_id)]")

    camera_path = fields.Char(related='gmd_id.camera_path', readonly=True)
    camera_ini = fields.Text(related='gmd_id.camera_ini', readonly=True)

    mainMark = fields.Binary(attachment=True)
    subMark = fields.Binary(attachment=True)

    @api.one
    @api.depends('geo')
    def _compute_attachment(self):
        self.mainMark_attachment_id = self.env['ir.attachment'].search(
            [('res_field', '=', 'mainMark'), ('res_id', '=', self.id),
             ('res_model', '=', 'favite_bif.pad')],
            limit=1)
        self.subMark_attachment_id = self.env['ir.attachment'].search(
            [('res_field', '=', 'subMark'), ('res_id', '=', self.id),
             ('res_model', '=', 'favite_bif.pad')],
            limit=1)

    mainMark_attachment_id = fields.Many2one('ir.attachment',
                                             compute='_compute_attachment',
                                             ondelete='restrict',
                                             readonly=True)
    subMark_attachment_id = fields.Many2one('ir.attachment',
                                            compute='_compute_attachment',
                                            ondelete='restrict',
                                            readonly=True)

    @api.model
    def _fields_view_get(self,
                         view_id=None,
                         view_type='form',
                         toolbar=False,
                         submenu=False):
        if view_type == 'map' and not view_id:
            view_id = self.env.ref('favite_bif.favite_bif_pad_map').id

        res = super(Pad, self)._fields_view_get(view_id=view_id,
                                                view_type=view_type,
                                                toolbar=toolbar,
                                                submenu=submenu)
        return res

    @api.multi
    def edit_dialog(self):
        form_view = self.env.ref('favite_bif.favite_bif_pad_map')
        return {
            'name': _('Pad'),
            'res_model': self._name,
            'res_id': self.id,
            'views': [
                (form_view.id, 'form'),
            ],
            'type': 'ir.actions.act_window',
            'target': 'new'
        }

    @api.multi
    def open_map(self):
        self.ensure_one()
        return {
            'type': 'ir.actions.act_window',
            'name': self.name,
            'res_model': self._name,
            'res_id': self.id,
            'view_id': self.env.ref('favite_bif.favite_bif_pad_map').id,
            'view_type': 'map',
            'view_mode': 'map',
            'target': 'current',
            'flags': {
                'hasSearchView': False
            }
        }

    @api.multi
    def save_mark(self, pad):

        mark = None
        markWidth = 0
        markHeight = 0
        markStartx = 0
        markList = []

        for obj in pad['objs']:
            height = 0
            block_list = []
            iInterSectionWidth = 0

            if 'blocks' not in obj:
                continue

            for b in obj['blocks']:
                if (not 'iInterSectionHeight' in b):
                    continue
                if iInterSectionWidth == 0:
                    iInterSectionWidth = b['iInterSectionWidth']

                height += b['iInterSectionHeight']
                #imgFile = '%s/Image/IP%d/jpegfile/AoiL_IP%d_scan%d_block%d.jpg' % (self.camera_path,b['iIPIndex']+1,b['iIPIndex'],b['iScanIndex'],b['iBlockIndex'])
                imgFile = self.gmd_id.compute_jpeg_path(
                    b['iIPIndex'], b['iScanIndex'], b['iBlockIndex'])
                try:
                    im = Image.open(imgFile)
                except Exception as e:
                    im = Image.new(
                        'L',
                        (b['iInterSectionWidth'], b['iInterSectionHeight']))

                left = b['iInterSectionStartX']
                right = b['iInterSectionStartX'] + b['iInterSectionWidth']
                upper = im.height - (b['iInterSectionStartY'] +
                                     b['iInterSectionHeight'])
                lower = im.height - b['iInterSectionStartY']
                im = im.transpose(Image.FLIP_TOP_BOTTOM)
                region = im.crop((left, upper, right, lower))
                block_list.append(region)
                im.close()

            markWidth += iInterSectionWidth
            markStartx += iInterSectionWidth
            markHeight = height if height > markHeight else markHeight
            if len(block_list):
                markList.append(block_list)

        if len(markList):
            mark = Image.new('L', (markWidth, markHeight))
            left = 0
            for blocks in markList:
                lower = markHeight
                for region in blocks:
                    upper = lower - region.size[1]
                    right = left + region.size[0]
                    mark.paste(region, (left, upper, right, lower))

                    lower = markHeight - region.size[1]
                left += blocks[0].size[0]

            b = BytesIO()
            mark.save(b, 'BMP')
            mainMark = base64.b64encode(b.getvalue())

            return mainMark

    @api.multi
    def write(self, values):
        if 'geo' in values:
            geo = values['geo']
            if geo['mark'].get('modified', False):
                del geo['mark']['modified']
                mark = self.save_mark(geo['mark'])
                if mark is not None:
                    values['mainMark'] = mark

            if geo['submark'].get('modified', False):
                del geo['submark']['modified']
                mark = self.save_mark(geo['submark'])
                if mark is not None:
                    values['subMark'] = mark

        return super(Pad, self).write(values)

    @api.multi
    def search_goa(self, vals):
        self.ensure_one()
        try:
            getattr(windll, "AutoPeriod")
        except:
            raise UserError("'auto search' not supported on goa")

        width = vals['width']
        height = vals['height']
        strBlocks = vals['strBlocks']
        strPoints = vals['strPoints']
        type = vals['type']

        blocks = json.loads(strBlocks)
        points = json.loads(strPoints)

        dest = Image.new('L', (width, height))
        left = 0
        top = 0
        for x in range(len(blocks)):
            for y in range(len(blocks[x]) - 1, -1, -1):
                b = blocks[x][y]
                if b is None or b['bHasIntersection'] == False:
                    continue

                try:
                    #imgFile = '%s/Image/IP%d/jpegfile/AoiL_IP%d_scan%d_block%d.jpg' % (self.camera_path,b['iIPIndex']+1,b['iIPIndex'],b['iScanIndex'],b['iBlockIndex'])
                    imgFile = self.gmd_id.compute_jpeg_path(
                        b['iIPIndex'], b['iScanIndex'], b['iBlockIndex'])
                    with Image.open(imgFile) as im:
                        im = im.transpose(Image.FLIP_TOP_BOTTOM)
                        region = im.crop(
                            (b['iInterSectionStartX'],
                             im.height - (b['iInterSectionStartY'] +
                                          b['iInterSectionHeight']),
                             b['iInterSectionStartX'] +
                             b['iInterSectionWidth'],
                             im.height - b['iInterSectionStartY']))
                        dest.paste(region, (left, top))
                        if y == 0:
                            left += region.width
                            top = 0
                        else:
                            top += region.height
                except:
                    raise UserError("No such file:%s" % (imgFile))

        dest = dest.transpose(Image.FLIP_TOP_BOTTOM)
        pSrcStart = dest.tobytes()
        step = width
        nVertices = len(points['x'])
        aVerticesX = (c_int * nVertices)(*points['x'])
        aVerticesY = (c_int * nVertices)(*points['y'])
        periodX = c_int()
        periodY = c_int()
        periodType = c_int(type)
        pMapStart = create_string_buffer(width * height * 3)
        nMapStep = 3 * width

        with open('d:/src.bmp', 'wb') as f:
            dest.save(f, format="BMP")

        with open('d:/src.txt', 'wt') as f:
            f.write("width:%d\n" % width)
            f.write("height:%d\n" % height)
            f.write("step:%d\n" % step)
            f.write("nVertices:%d\n" % nVertices)
            f.write("aVerticesX:%s\n" % strPoints)

        res = windll.AutoPeriod.GetPeriod(pSrcStart, width, height, step,
                                          nVertices, aVerticesX, aVerticesY,
                                          byref(periodX), byref(periodY),
                                          periodType, pMapStart, nMapStep)
        if res == 1:
            out = Image.frombytes('RGB', (width, height), pMapStart)
            b = BytesIO()
            out.save(b, 'JPEG')

            return {
                'result': True,
                "periodX": periodX.value,
                "periodY": periodY.value,
                'map': base64.b64encode(b.getvalue())
            }
        else:
            return {'result': False}

    def export_mark(self, objs, name, cx, cy):
        markWidth = 0
        markStartx = 0
        markNumber = 0

        strMark = 'regular.%s.number = %d\n' % (name, len(objs))
        strMark += 'regular.%s.imagename = %s_mainmark.bmp\n' % (name,
                                                                 self.name)
        for obj in objs:
            if not 'blocks' in obj:
                raise UserError("Please perform the save operation first!")

            height = 0
            iInterSectionWidth = 0

            for block in obj['blocks']:
                if (not 'iInterSectionHeight' in block):
                    continue
                if iInterSectionWidth == 0:
                    iInterSectionWidth = block['iInterSectionWidth']

                height += block['iInterSectionHeight']

            markWidth += iInterSectionWidth
            strMark += 'regular.%s.%d.image.size = %d,%d\n' % (
                name, markNumber, iInterSectionWidth, height)
            strMark += 'regular.%s.%d.image.position = %d,%d\n' % (
                name, markNumber, markStartx, 0)

            x = (obj['points'][0]['x'] + obj['points'][1]['x']) / 2 - cx
            y = (obj['points'][0]['y'] + obj['points'][1]['y']) / 2 - cy
            strMark += 'regular.%s.%d.panelcenter.position = %f,%f\n' % (
                name, markNumber, x, y)
            strMark += 'regular.%s.%d.ipindex = %d\n' % (name, markNumber,
                                                         block['iIPIndex'])
            strMark += 'regular.%s.%d.scanindex = %d\n' % (name, markNumber,
                                                           block['iScanIndex'])

            markStartx += iInterSectionWidth
            markNumber += 1

        return strMark

    @api.one
    def export_file(self, directory_ids):
        geo = self._export_geo()

        p1 = geo['panel']['objs'][0]['points'][0]
        p2 = geo['panel']['objs'][0]['points'][1]
        panel_x = (p1['x'] + p2['x']) / 2.0
        panel_y = (p1['y'] + p2['y']) / 2.0
        strMainMark = self.export_mark(geo['mark']['objs'], 'mainmark',
                                       panel_x, panel_y)
        strSubMark = self.export_mark(geo['submark']['objs'], 'submark',
                                      panel_x, panel_y)

        strParameter = 'panelcenter.position = %f,%f' % (panel_x, panel_y)
        fields_data = self.env['ir.model.fields']._get_manual_field_data(
            self._name)
        for name, field in sorted(self._fields.items(), key=lambda f: f[0]):
            if not field.manual or not name.startswith('x_'):
                continue
            elif field.type == 'boolean' or field.type == 'selection':
                strParameter += '%s = %d\n' % (
                    fields_data[name]['complete_name'], self[name])
            else:
                strParameter += '%s = %s\n' % (
                    fields_data[name]['complete_name'],
                    field.convert_to_export(self[name], self))

        num = len(geo['regular']['objs'])
        strRegular = 'regular.number = %d\n' % num
        for i in range(0, num):
            obj = geo['regular']['objs'][i]
            p1 = obj['points'][0]
            p2 = obj['points'][1]
            left = min(p1['x'], p2['x']) - panel_x
            right = max(p1['x'], p2['x']) - panel_x
            bottom = min(p1['y'], p2['y']) - panel_Y
            top = max(p1['y'], p2['y']) - panel_y
            strRegular += 'regular.%d.position = %f,%f,%f,%f\n' % (
                i, left, top, right, bottom)
            strRegular += 'regular.%d.period = %f,%f\n' % (i, obj['periodX'],
                                                           obj['periodY'])
            strRegular += 'regular.%d.enabled1g1 = %d\n' % (i,
                                                            obj['enable_d1g1'])

        strFrame = ''
        frameNum = 0
        for p in self.geo['frame']['objs']:
            p1 = p['points'][0]
            p2 = p['points'][1]
            left = min(p1['x'], p2['x']) - panel_x
            right = max(p1['x'], p2['x']) - panel_x
            bottom = min(p1['y'], p2['y']) - panel_Y
            top = max(p1['y'], p2['y']) - panel_Y
            strFrame += 'frame.%d.position.topleft = %f,%f\n' % (frameNum,
                                                                 left, top)
            strFrame += 'frame.%d.position.topright = %f,%f\n' % (frameNum,
                                                                  right, top)
            strFrame += 'frame.%d.position.bottomleft = %f,%f\n' % (
                frameNum, left, bottom)
            strFrame += 'frame.%d.position.bottomright = %f,%f\n' % (
                frameNum, right, bottom)
            frameNum = frameNum + 1
        strFrame += 'frame.number = %d\n' % frameNum

        num = len(geo['region']['objs'])
        strRegion = 'region.number = %d\n' % num
        for i in range(0, num):
            obj = geo['region']['objs'][i]
            p1 = obj['points'][0]
            p2 = obj['points'][1]
            left = min(p1['x'], p2['x']) - panel_x
            right = max(p1['x'], p2['x']) - panel_x
            bottom = min(p1['y'], p2['y']) - panel_Y
            top = max(p1['y'], p2['y']) - panel_y
            strRegion += 'region.%d.position = %f,%f,%f,%f\n' % (i, left, top,
                                                                 right, bottom)
            strRegion += 'region.%d.frameindex = %d' % (i, obj['iFrameNo'])

        num = len(geo['filterregion']['objs'])
        strFilterregion = 'filterregion.number = %d\n' % num
        for i in range(0, num):
            obj = geo['filterregion']['objs'][i]
            p1 = obj['points'][0]
            p2 = obj['points'][1]
            left = min(p1['x'], p2['x']) - panel_x
            right = max(p1['x'], p2['x']) - panel_x
            bottom = min(p1['y'], p2['y']) - panel_Y
            top = max(p1['y'], p2['y']) - panel_y
            strFilterregion += 'filterregion.%d.position = %f,%f,%f,%f\n' % (
                i, left, top, right, bottom)

        for d in directory_ids:
            dir = os.path.join(d.name, 'bif')
            if not os.path.isdir(dir):
                os.makedirs(dir)
            dir = os.path.join(dir, 'pad')
            if not os.path.isdir(dir):
                os.makedirs(dir)
            path = os.path.join(dir, self.name + '.pad')
            with open(path, 'w') as f:
                f.write(strParameter)
                f.write(strMainMark)
                f.write(strSubMark)
                f.write(strRegular)
                f.write(strFrame)
                f.write(strRegion)
                f.write(strFilterregion)
                f.write(
                    '\n#######Do not edit this field; automatically generated by export.##############\n'
                )
                f.write('gmd=%s\n' % self.gmd_id.name)
                f.write('mark=%s\n' % json.dumps(geo['mark']))
                f.write('submark=%s\n' % json.dumps(geo['submark']))
                f.write('src_panel=%s\n' % self.src_panel_id.name)

            if self.mainMark:
                path = os.path.join(dir, self.name + '_mainmark.bmp')
                with open(path, 'wb') as f:
                    f.write(base64.b64decode(self.mainMark))

            if self.subMark:
                path = os.path.join(dir, self.name + '_submark.bmp')
                with open(path, 'wb') as f:
                    f.write(base64.b64decode(self.subMark))

    @api.model
    def import_file(self, file):
        written = True
        message = 'Success'

        obj = {'name': file.filename.split('.')[0]}
        geo = {
            "mark": {
                "objs": []
            },
            "regular": {
                "objs": []
            },
            "filterregion": {
                "objs": []
            },
            "frame": {
                "objs": [],
                "no_add": True
            },
            "region": {
                "objs": [],
                "no_add": True,
                "readonly": True
            },
        }

        try:
            parser = ConfigParser.RawConfigParser()
            parser.read_string("[DEFAULT]\r\n" + file.read().decode())
            par = parser._defaults

            geo['mark'] = json.loads(par['mark'])
            geo['submark'] = json.loads(par['submark'])

            panelcenter_x, panelcenter_y = (
                float(s) for s in par['panelcenter.position'].split(','))

            if 'gmd' in par:
                name = par['gmd']
                gmd = self.env['favite_gmd.gmd'].sudo().search([('name', '=',
                                                                 name)])
                if not gmd:
                    raise UserError("File(%s) must first be imported!" %
                                    par['gmd'])
            else:
                raise UserError("File(%s) must contain gmd!" % file.filename)

            if 'src_panel' in par:
                name = par['src_panel']
                panel = self.env['favite_bif.panel'].sudo().search([
                    ('name', '=', name), ('gmd_id', '=', gmd.id)
                ])
                if not panel:
                    raise UserError("File(%s) must first be imported!" %
                                    par['src_panel'])
            else:
                raise UserError("File(%s) must contain src_panel!" %
                                file.filename)

            for b in gmd.geo['block']['objs']:
                for p in b['panels']:
                    if p['name'] == panel.name:
                        geo['panel']['objs'].append(p)

            m = int(par.get('regular.number', 0))
            for j in range(0, m):
                left, top, right, bottom = (
                    float(s)
                    for s in par['regular.%d.position' % j].split(','))
                left += panelcenter_x
                right += panelcenter_x
                top += panelcenter_y
                bottom += panelcenter_y
                o = {'points': []}
                o['points'].append({'x': left, 'y': top})
                o['points'].append({'x': right, 'y': bottom})

                o['periodX'], o['periodY'] = (
                    float(s) for s in par['regular.%d.period' % j].split(','))
                o['enable_d1g1'] = int(par['regular.%d.enabled1g1' % j])
                geo['regular']['objs'].append(o)

            m = int(par.get('frame.number', 0))
            for j in range(0, m):
                left, top = (float(s)
                             for s in par['frame.%d.position.topleft' %
                                          j].split(','))
                right, bottom = (float(s)
                                 for s in par['frame.%d.position.bottomright' %
                                              j].split(','))
                left += panelcenter_x
                right += panelcenter_x
                top += panelcenter_y
                bottom += panelcenter_y
                o = {'points': []}
                o['points'].append({'x': left, 'y': top})
                o['points'].append({'x': right, 'y': bottom})
                geo['frame']['objs'].append(o)

            m = int(par.get('region.number', 0))
            for j in range(0, m):
                left, top, right, bottom = (float(s)
                                            for s in par['region.%d.position' %
                                                         j].split(','))
                left += panelcenter_x
                right += panelcenter_x
                top += panelcenter_y
                bottom += panelcenter_y
                o = {'points': []}
                o['points'].append({'x': left, 'y': top})
                o['points'].append({'x': right, 'y': bottom})
                o['iFrameNo'] = int(par['region.%d.frameindex' % j])

                geo['region']['objs'].append(o)

            m = int(par.get('filterregion.number', 0))
            for j in range(0, m):
                left, top, right, bottom = (
                    float(s)
                    for s in par['filterregion.%d.position' % j].split(','))
                left += panelcenter_x
                right += panelcenter_x
                top += panelcenter_y
                bottom += panelcenter_y
                o = {'points': []}
                o['points'].append({'x': left, 'y': top})
                o['points'].append({'x': right, 'y': bottom})
                geo['filterregion']['objs'].append(o)

            fields_data = self.env['ir.model.fields']._get_manual_field_data(
                self._name)
            for name, field in self._fields.items():
                if not field.manual or not name.startswith('x_'):
                    continue

                complete_name = fields_data[name]['complete_name']
                if complete_name.lower() in par:
                    value = par[complete_name.lower()]
                    obj[name] = field.convert_to_cache(value, self)
                    if isinstance(obj[name], bool):
                        obj[name] = value == '1'

            obj['gmd_id'] = gmd.id
            obj['src_panel_id'] = panel.id
            obj.geo = geo
            self.create(obj)._import_geo()

        except Exception as e:
            written = False
            message = str(e)
        return {'success': written, 'message': message}
Example #6
0
class Fixpoint(models.Model):
    _name = 'favite_bif.fixpoint'
    _inherit = ['favite_common.geometry']
    _sql_constraints = [
        ('name_uniq', 'unique (name)', "Name already exists !"),
    ]

    @api.model
    def _default_geo(self):
        geo = {
            "region": {
                "objs": []
            },
        }
        return geo

    geo = fields.Jsonb(string="geometry value", default=_default_geo)
    glass = fields.Jsonb(related='gmd_id.glass', readonly=True)
    gmd_id = fields.Many2one('favite_gmd.gmd',
                             ondelete='cascade',
                             require=True)

    camera_path = fields.Char(related='gmd_id.camera_path', readonly=True)
    camera_ini = fields.Text(related='gmd_id.camera_ini', readonly=True)

    @api.multi
    def get_formview_id(self, access_uid=None):
        return self.env.ref('favite_bif.favite_bif_fixpoint_map').id

    def _export_geo(self):
        iniFile = os.path.join(self.camera_path, self.gmd_id.camera_name)
        iniConf = ConfigParser.RawConfigParser()
        with open(iniFile, 'r') as f:
            iniConf.read_string("[DEFAULT]\r\n" + f.read())
            dGlassCenterX, dGlassCenterY = (
                float(s)
                for s in iniConf._defaults['glass.center.position.0'].split(
                    ','))
            dAngle = float(iniConf._defaults['glass.angle.0'])

            geo = copy.deepcopy(self.geo)
            for o in geo['region']['objs']:
                for p in o['points']:
                    dInputX = p['x']
                    dInputY = p['y']
                    p['x'] = (dInputX - dGlassCenterX) * math.cos(dAngle) + (
                        dInputY - dGlassCenterY) * math.sin(dAngle)
                    p['y'] = -(dInputX - dGlassCenterX) * math.sin(dAngle) + (
                        dInputY - dGlassCenterY) * math.cos(dAngle)

        return geo

    def _import_geo(self):
        iniFile = os.path.join(self.camera_path, self.gmd_id.camera_name)
        iniConf = ConfigParser.RawConfigParser()
        with open(iniFile, 'r') as f:
            iniConf.read_string("[DEFAULT]\r\n" + f.read())
            dGlassCenterX, dGlassCenterY = (
                float(s)
                for s in iniConf._defaults['glass.center.position.0'].split(
                    ','))
            dAngle = float(iniConf._defaults['glass.angle.0'])

            geo = self.geo
            for o in geo['region']['objs']:
                for p in o['points']:
                    dInputX = p['x']
                    dInputY = p['y']
                    p['x'] = dInputX * math.cos(-dAngle) + dInputY * math.sin(
                        -dAngle) + dGlassCenterX
                    p['y'] = -dInputX * math.sin(-dAngle) + dInputY * math.cos(
                        -dAngle) + dGlassCenterY

            self.write({'geo': geo})

    @api.one
    def export_file(self, directory_ids):
        geo = self._export_geo()

        num = 0
        strRegion = ''
        for f in geo['region']['objs']:
            p1 = f['points'][0]
            p2 = f['points'][1]
            left = int(min(p1['x'], p2['x']))
            right = int(max(p1['x'], p2['x']))
            bottom = int(min(p1['y'], p2['y']))
            top = int(max(p1['y'], p2['y']))
            strRegion += 'region.%d.name = %s\n' % (num, f['name'])
            strRegion += 'region.%d.position = %d,%d,%d,%d\n' % (
                num, (left + right) / 2,
                (top + bottom) / 2, right - left, top - bottom)
            num = num + 1
        strRegion += 'region.number = %d\n' % (num, )

        strParameter = ''
        fields_data = self.env['ir.model.fields']._get_manual_field_data(
            self._name)
        for name, field in sorted(self._fields.items(), key=lambda f: f[0]):
            if not field.manual or not name.startswith('x_'):
                continue
            elif field.type == 'boolean' or field.type == 'selection':
                strParameter += '%s = %d\n' % (
                    fields_data[name]['complete_name'], self[name])
            else:
                strParameter += '%s = %s\n' % (
                    fields_data[name]['complete_name'],
                    field.convert_to_export(self[name], self))

        for d in directory_ids:
            dir = os.path.join(d.name, 'bif')
            if not os.path.isdir(dir):
                os.makedirs(dir)
            dir = os.path.join(dir, 'fixpoint')
            if not os.path.isdir(dir):
                os.makedirs(dir)
            path = os.path.join(dir, self.name + '.fxp')
            with open(path, 'w') as f:
                f.write(strParameter)
                f.write(strRegion)
                f.write('gmd=%s\n' % self.gmd_id.name)

    @api.model
    def import_file(self, file):
        written = True
        message = 'Success'

        obj = {'name': file.filename.split('.')[0]}
        geo = {
            "region": {
                "objs": []
            },
        }

        try:
            parser = ConfigParser.RawConfigParser()
            parser.read_string("[DEFAULT]\r\n" + file.read().decode())
            par = parser._defaults

            if 'gmd' in par:
                name = par['gmd']
                gmd = self.env['favite_gmd.gmd'].sudo().search([('name', '=',
                                                                 name)])
                if not gmd:
                    raise UserError("File(%s) must first be imported!" %
                                    par['gmd'])
            else:
                raise UserError("File(%s) must contain gmd!" % file.filename)

            m = int(par.get('region.number', 0))
            for j in range(0, m):
                cx, cy, w, h = (float(s) for s in par['region.%d.position' %
                                                      j].split(','))
                o = {'points': []}
                o['points'].append({'x': cx - w / 2, 'y': cy + h / 2})
                o['points'].append({'x': cx + w / 2, 'y': cy - h / 2})
                geo['region']['objs'].append(o)

            obj['geo'] = geo
            obj['gmd_id'] = gmd.id

            fields_data = self.env['ir.model.fields']._get_manual_field_data(
                self._name)
            for name, field in self._fields.items():
                if not field.manual or not name.startswith('x_'):
                    continue

                complete_name = fields_data[name]['complete_name']
                if complete_name.lower() in par:
                    value = par[complete_name.lower()]
                    obj[name] = field.convert_to_cache(value, self)
                    if isinstance(obj[name], bool):
                        obj[name] = value == '1'

            self.create(obj)._import_geo()

        except Exception as e:
            written = False
            message = str(e)
        return {'success': written, 'message': message}
Example #7
0
class Bif(models.Model):
    _name = 'favite_bif.bif'
    _inherit = ['favite_common.geometry']

    _sql_constraints = [
        ('name_uniq', 'unique (name)', "Name already exists !"),
    ]

    @api.one
    def _inverse_geo(self):
        def _check_region(filter, left, right, bottom, top):
            for pt in f['points']:
                if pt['x'] > right or pt['x'] < left or pt['y'] > top or pt[
                        'y'] < bottom:
                    return False
            return True

        bif_geo = dict(self.geo)

        for p in bif_geo['panel']['objs']:
            geo = {
                "filter": {
                    "objs": []
                },
            }

            p1 = p['points'][0]
            p2 = p['points'][1]
            left = min(p1['x'], p2['x'])
            right = max(p1['x'], p2['x'])
            bottom = min(p1['y'], p2['y'])
            top = max(p1['y'], p2['y'])
            for f in bif_geo['panel_filter']['objs']:
                if _check_region(f, left, right, bottom, top):
                    geo['filter']['objs'].append(f)

            panel = self.env['favite_bif.panel'].sudo().search([
                ('name', '=', p['name']), ('bif_id', '=', self.id)
            ])
            if 'gsp' in p:
                gsp = self.env['favite_bif.gsp'].sudo().search([
                    ('id', '=', p['gsp']), ('bif_id', '=', self.id)
                ])
                if gsp:
                    panel.write({'geo': geo, 'gsp_id': gsp.id})
            else:
                panel.write({'geo': geo})

        gsp = self.env['favite_bif.gsp'].sudo().search([('bif_id', '=',
                                                         self.id)])
        gsp.refresh()

    @api.one
    @api.depends('gmd_id', 'gmd_id.geo')
    def _compute_geo(self):
        self.geo['mark'] = self.gmd_id.geo['mark']
        self.geo['mark']['readonly'] = True
        self.geo['panel'] = {"objs": [], "readonly": True}

        total = self.env['favite_bif.panel'].sudo().search([('bif_id', '=',
                                                             self.id)])

        names = []
        for b in self.gmd_id.geo['block']['objs']:
            if 'panels' in b:
                for p in b['panels']:
                    names.append(p['name'])

        cur = self.env['favite_bif.panel'].sudo().search([('name', 'in', names)
                                                          ])
        (total - cur).unlink()

        self.geo['panel']['objs'] = []
        for b in self.gmd_id.geo['block']['objs']:
            if 'panels' in b:
                for p in b['panels']:
                    panel = self.env['favite_bif.panel'].sudo().search([
                        ('name', '=', p['name']), ('bif_id', '=', self.id)
                    ])
                    if panel:
                        if panel.gsp_id:
                            panel.gsp_id.refresh()
                            p['gsp'] = panel.gsp_id.id
                            p['color'] = panel.gsp_id.color
                    else:
                        self.env['favite_bif.panel'].sudo().create({
                            'bif_id':
                            self.id,
                            'name':
                            p['name']
                        })
                    self.geo['panel']['objs'].append(p)

        self.geo['panel_filter'] = {"objs": []}
        for panel in self.panel_ids:
            for obj in panel.geo['filter']['objs']:
                filter = obj
                filter['name'] = panel['name']
                self.geo['panel_filter']['objs'].append(filter)

        gsp = self.env['favite_bif.gsp'].sudo().search([('bif_id', '=',
                                                         self.id)])
        gsp.refresh()

    geo = fields.Jsonb(string="geometry value",
                       compute='_compute_geo',
                       inverse='_inverse_geo')
    glass = fields.Jsonb(related='gmd_id.glass', readonly=True)

    camera_path = fields.Char(related='gmd_id.camera_path', readonly=True)
    camera_ini = fields.Text(related='gmd_id.camera_ini', readonly=True)

    gmd_id = fields.Many2one('favite_gmd.gmd',
                             ondelete='cascade',
                             required=True)

    frame_id = fields.Many2one('favite_bif.frame', ondelete='set null')
    mark_id = fields.Many2one('favite_bif.mark', ondelete='set null')
    measure_id = fields.Many2one('favite_bif.measure', ondelete='set null')
    fixpoint_id = fields.Many2one('favite_bif.fixpoint', ondelete='set null')
    lut_id = fields.Many2one('favite_bif.lut', ondelete='set null')

    panel_ids = fields.One2many('favite_bif.panel', 'bif_id', string='Panel')
    gsp_ids = fields.One2many('favite_bif.gsp', 'bif_id', string='Gsp')

    color = fields.Integer('Color Index', default=0)

    @api.multi
    def open_map(self):
        self.ensure_one()
        return {
            'type': 'ir.actions.act_window',
            'name': self.name,
            'res_model': self._name,
            'res_id': self.id,
            'view_id': self.env.ref('favite_bif.favite_bif_bif_map').id,
            'view_type': 'map',
            'view_mode': 'map',
            'target': 'current',
            'flags': {
                'hasSearchView': False
            }
        }

    @api.multi
    def open_gsp_list(self):
        ctx = dict(default_bif_id=self.id, )
        return {
            'type': 'ir.actions.act_window',
            'name': 'Gsp',
            'res_model': 'favite_bif.gsp',
            'view_mode': 'kanban,form',
            'view_id': False,
            'target': 'current',
            'flags': {
                'import_enabled': False
            },
            'domain': [('bif_id', '=', self.id)],
            'context': ctx,
        }

    def _export_geo(self):
        iniFile = os.path.join(self.camera_path, self.gmd_id.camera_name)
        iniConf = ConfigParser.RawConfigParser()
        with open(iniFile, 'r') as f:
            iniConf.read_string("[DEFAULT]\r\n" + f.read())
            dGlassCenterX, dGlassCenterY = (
                float(s)
                for s in iniConf._defaults['glass.center.position.0'].split(
                    ','))
            dAngle = float(iniConf._defaults['glass.angle.0'])

            geo = copy.deepcopy(self.geo)
            for o in geo['panel']['objs']:
                for p in o['points']:
                    dInputX = p['x']
                    dInputY = p['y']
                    p['x'] = (dInputX - dGlassCenterX) * math.cos(dAngle) + (
                        dInputY - dGlassCenterY) * math.sin(dAngle)
                    p['y'] = -(dInputX - dGlassCenterX) * math.sin(dAngle) + (
                        dInputY - dGlassCenterY) * math.cos(dAngle)

            for o in geo['mark']['objs']:
                for p in o['points']:
                    dInputX = p['x']
                    dInputY = p['y']
                    p['x'] = (dInputX - dGlassCenterX) * math.cos(dAngle) + (
                        dInputY - dGlassCenterY) * math.sin(dAngle)
                    p['y'] = -(dInputX - dGlassCenterX) * math.sin(dAngle) + (
                        dInputY - dGlassCenterY) * math.cos(dAngle)

        return geo

    @api.one
    def export_file(self, directory_ids):
        self.gmd_id.export_file(directory_ids)

        geo = self._export_geo()
        markNum = len(geo['mark']['objs'])
        strMark = 'mark.number = %d\n' % markNum
        for i in range(0, markNum):
            p1 = geo['mark']['objs'][i]['points'][0]
            p2 = geo['mark']['objs'][i]['points'][1]
            x = (p1['x'] + p2['x']) / 2
            y = (p1['y'] + p2['y']) / 2
            strMark += 'mark.%d.position = %f,%f\n' % (i, x, y)
            w = abs(p1['x'] - p2['x'])
            h = abs(p1['y'] - p2['y'])
            strMark += 'mark.%d.size = %f,%f\n' % (i, w, h)

        gsp_list = []
        panelNum = 0
        strPanel = 'panel.gmd = %s\n' % self.gmd_id.name
        for p in geo['panel']['objs']:
            panel = self.env['favite_bif.panel'].sudo().search([
                ('name', '=', p['name']), ('bif_id', '=', self.id)
            ])
            if not panel.gsp_id:
                continue

#             p1 = p['points'][0]
#             p2 = p['points'][1]
#             left = min(p1['x'],p2['x'])
#             right = max(p1['x'],p2['x'])
#             bottom = min(p1['y'],p2['y'])
#             top = max(p1['y'],p2['y'])
#             strPanel += 'panel.%d.bottomleft = %f,%f\n' % (panelNum,left,top)
#             strPanel += 'panel.%d.bottomright = %f,%f\n' % (panelNum,right,top)
#             strPanel += 'panel.%d.topleft = %f,%f\n' % (panelNum,left,bottom)
#             strPanel += 'panel.%d.topright = %f,%f\n' % (panelNum,right,bottom)
            p0 = p['points'][0]
            p1 = p['points'][1]
            p2 = p['points'][2]
            p3 = p['points'][3]

            strPanel += 'panel.%d.topleft = %f,%f\n' % (panelNum, p0['x'],
                                                        p0['y'])
            strPanel += 'panel.%d.topright = %f,%f\n' % (panelNum, p1['x'],
                                                         p1['y'])
            strPanel += 'panel.%d.bottomright = %f,%f\n' % (panelNum, p2['x'],
                                                            p2['y'])
            strPanel += 'panel.%d.bottomleft = %f,%f\n' % (panelNum, p3['x'],
                                                           p3['y'])

            strPanel += 'panel.%d.name = %s\n' % (panelNum, panel.name)
            strPanel += 'panel.%d.gspname = %s\n' % (panelNum,
                                                     panel.gsp_id.name)
            if panel.gsp_id not in gsp_list:
                strPanel += 'panel.%d.gspindex = %d\n' % (panelNum,
                                                          len(gsp_list))
                gsp_list.append(panel.gsp_id)
            else:
                strPanel += 'panel.%d.gspindex = %d\n' % (
                    panelNum, gsp_list.index(panel.gsp_id))

            panelFilterNum = 0
            for f in panel.geo['filter']['objs']:
                p1 = f['points'][0]
                p2 = f['points'][1]
                left = min(p1['x'], p2['x'])
                right = max(p1['x'], p2['x'])
                bottom = min(p1['y'], p2['y'])
                top = max(p1['y'], p2['y'])
                strPanel += 'panel.%d.filter.%d.topleft = %f,%f\n' % (
                    panelNum, panelFilterNum, left, bottom)
                strPanel += 'panel.%d.filter.%d.topright = %f,%f\n' % (
                    panelNum, panelFilterNum, right, bottom)
                strPanel += 'panel.%d.filter.%d.bottomleft = %f,%f\n' % (
                    panelNum, panelFilterNum, left, top)
                strPanel += 'panel.%d.filter.%d.bottomright = %f,%f\n' % (
                    panelNum, panelFilterNum, right, top)
                panelFilterNum = panelFilterNum + 1
            strPanel += 'panel.%d.filternumber = %d\n' % (panelNum,
                                                          panelFilterNum)
            panelNum = panelNum + 1
        strPanel += 'panel.number = %d\n' % panelNum

        gspNum = len(gsp_list)
        strGsp = 'gsp.number = %d\n' % gspNum
        for i in range(0, gspNum):
            if gsp_list[i].pad_id:
                gsp_list[i].pad_id.export_file(directory_ids)
                strGsp += 'gsp.%d.padfile = %s.pad\n' % (
                    i, gsp_list[i].pad_id.name)
            strGsp += gsp_list[i].export_string(i)
            gsp_list[i].export_image(directory_ids)
            strGsp += 'gsp.%d.zone.originimage = %s_%s_org.bmp\n' % (
                i, self.name, gsp_list[i].name)
            strGsp += 'gsp.%d.zone.zoneimage = %s_%s_zone.bmp\n' % (
                i, self.name, gsp_list[i].name)
            strGsp += 'gsp.%d.panelpolygon = %s_%s_polygon.bmp\n' % (
                i, self.name, gsp_list[i].name)

        strSubbif = ''
        if self.frame_id:
            strSubbif += 'subbif.frame = %s.frm\n' % self.frame_id.name
            self.frame_id.export_file(directory_ids)
        if self.mark_id:
            strSubbif += 'subbif.mark = %s.mrk\n' % self.mark_id.name
            self.mark_id.export_file(directory_ids)
        if self.measure_id:
            strSubbif += 'subbif.measure = %s.msr\n' % self.measure_id.name
            self.measure_id.export_file(directory_ids)
        if self.fixpoint_id:
            strSubbif += 'subbif.fixpoint = %s.fxp\n' % self.fixpoint_id.name
            self.fixpoint_id.export_file(directory_ids)
        if self.lut_id:
            strSubbif += 'subbif.lut = %s.lut\n' % self.lut_id.name
            self.lut_id.export_file(directory_ids)

        strParameter = ''
        fields_data = self.env['ir.model.fields']._get_manual_field_data(
            self._name)
        for name, field in sorted(self._fields.items(), key=lambda f: f[0]):
            if not field.manual or not name.startswith('x_'):
                continue
            elif field.type == 'boolean' or field.type == 'selection':
                strParameter += '%s = %d\n' % (
                    fields_data[name]['complete_name'], self[name])
            else:
                strParameter += '%s = %s\n' % (
                    fields_data[name]['complete_name'],
                    field.convert_to_export(self[name], self))

        for d in directory_ids:
            dir = os.path.join(d.name, 'bif')
            if not os.path.isdir(dir):
                os.makedirs(dir)
            path = os.path.join(dir, self.name + '.bif')
            with open(path, 'w') as f:
                f.write(strParameter)
                f.write(strMark)
                f.write(strPanel)
                f.write(strGsp)
                f.write(strSubbif)

    def _import_geo(self):
        iniFile = os.path.join(self.camera_path, self.gmd_id.camera_name)
        iniConf = ConfigParser.RawConfigParser()
        with open(iniFile, 'r') as f:
            iniConf.read_string("[DEFAULT]\r\n" + f.read())
            dGlassCenterX, dGlassCenterY = (
                float(s)
                for s in iniConf._defaults['glass.center.position.0'].split(
                    ','))
            dAngle = float(iniConf._defaults['glass.angle.0'])

            geo = self.geo
            for o in geo['panel']['objs']:
                for p in o['points']:
                    dInputX = p['x']
                    dInputY = p['y']
                    p['x'] = dInputX * math.cos(-dAngle) + dInputY * math.sin(
                        -dAngle) + dGlassCenterX
                    p['y'] = -dInputX * math.sin(-dAngle) + dInputY * math.cos(
                        -dAngle) + dGlassCenterY

            self.write({'geo': geo})

    @api.model
    def import_file(self, file):
        written = True
        message = 'Success'
        obj = {'name': file.filename.split('.')[0]}

        try:
            parser = ConfigParser.RawConfigParser()
            parser.read_string("[DEFAULT]\r\n" + file.read().decode())
            par = parser._defaults

            if 'panel.gmd' in par:
                name = par['panel.gmd']
                gmd = self.env['favite_gmd.gmd'].sudo().search([('name', '=',
                                                                 name)])
                if gmd:
                    obj['gmd_id'] = gmd.id
                else:
                    raise UserError("File(%s) must first be imported!" %
                                    par['panel.gmd'])
            else:
                raise UserError("File(%s) must contain gmd!" % file.filename)

            if 'subbif.frame' in par:
                name, _ = par['subbif.frame'].split('.')
                model = self.env['favite_bif.frame'].sudo().search([
                    ('name', '=', name)
                ])
                if model:
                    obj['frame_id'] = model.id
                else:
                    raise UserError("File(%s) must first be imported!" %
                                    par['subbif.frame'])

            if 'subbif.mark' in par:
                name, _ = par['subbif.mark'].split('.')
                model = self.env['favite_bif.mark'].sudo().search([
                    ('name', '=', name)
                ])
                if model:
                    obj['mark_id'] = model.id
                else:
                    raise UserError("File(%s) must first be imported!" %
                                    par['subbif.mark'])

            if 'subbif.measure' in par:
                name, _ = par['subbif.measure'].split('.')
                model = self.env['favite_bif.measure'].sudo().search([
                    ('name', '=', name)
                ])
                if model:
                    obj['measure_id'] = model.id
                else:
                    raise UserError("File(%s) must first be imported!" %
                                    par['subbif.measure'])

            if 'subbif.fixpoint' in par:
                name, _ = par['subbif.fixpoint'].split('.')
                model = self.env['favite_bif.fixpoint'].sudo().search([
                    ('name', '=', name)
                ])
                if model:
                    obj['fixpoint_id'] = model.id
                else:
                    raise UserError("File(%s) must first be imported!" %
                                    par['subbif.fixpoint'])

            if 'subbif.lut' in par:
                name, _ = par['subbif.lut'].split('.')
                model = self.env['favite_bif.lut'].sudo().search([('name', '=',
                                                                   name)])
                if model:
                    obj['lut_id'] = model.id
                else:
                    raise UserError("File(%s) must first be imported!" %
                                    par['subbif.lut'])

            fields_data = self.env['ir.model.fields']._get_manual_field_data(
                self._name)
            for name, field in self._fields.items():
                if not field.manual or not name.startswith('x_'):
                    continue

                complete_name = fields_data[name]['complete_name']
                if complete_name.lower() in par:
                    value = par[complete_name.lower()]
                    obj[name] = field.convert_to_cache(value, self)
                    if isinstance(obj[name], bool):
                        obj[name] = value == '1'

            bif = self.create(obj)

            n = int(par.get('panel.number', 0))
            for i in range(0, n):
                name = par['panel.%d.name' % i]
                panel = self.env['favite_bif.panel'].sudo().search([
                    ('name', '=', name), ('bif_id', '=', bif.id)
                ])

                gspname = par['panel.%d.gspname' % i]
                gspindex = par['panel.%d.gspindex' % i]
                gsp = self.env['favite_bif.gsp'].sudo().search([
                    ('name', '=', gspname), ('bif_id', '=', bif.id)
                ])
                if not gsp:
                    gsp = self.env['favite_bif.gsp'].sudo().import_string(
                        par, gspname, gspindex, bif, panel)

                geo = {
                    "filter": {
                        "objs": []
                    },
                }

                m = int(par.get('panel.%d.filternumber' % i, 0))
                for j in range(0, m):
                    left, bottom = (float(s)
                                    for s in par['panel.%d.filter.%d.topleft' %
                                                 (i, j)].split(','))
                    right, top = (
                        float(s)
                        for s in par['panel.%d.filter.%d.bottomright' %
                                     (i, j)].split(','))
                    o = {'points': []}
                    o['points'].append({'x': left, 'y': top})
                    o['points'].append({'x': right, 'y': bottom})
                    geo['filter']['objs'].append(o)

                panel.write({'gsp_id': gsp.id, 'geo': geo})

        except Exception as e:
            written = False
            message = str(e)
            raise UserError(message)
        return {'success': written, 'message': message}
Example #8
0
class Gsp(models.Model):
    _name = 'favite_bif.gsp'   
    _inherit = ['favite_common.geometry']
    
    @api.one
    @api.depends('gmd_id','gmd_id.geo','bif_id')
    def _compute_geo(self):
        self.geo['glass'] = self.gmd_id.geo['glass']
        self.geo['panel'] = self.bif_id.geo['panel']
    
    geo = fields.Jsonb(string = "geometry value",compute='_compute_geo',store=True)   
    bif_id = fields.Many2one('favite_bif.bif',ondelete='cascade')  
    gmd_id = fields.Many2one('favite_gmd.gmd',related='bif_id.gmd_id')
    pad_id = fields.Many2one('favite_bif.pad',ondelete='set null',domain="[('gmd_id', '=', gmd_id),('src_panel_id', '=', src_panel_id)]")  
    src_panel_id = fields.Many2one('favite_bif.panel',ondelete='set null', domain="[('gmd_id', '=', gmd_id)]")  
    panel_polygon_file = fields.Char()

    camera_path = fields.Char(related='gmd_id.camera_path', readonly=True)
    camera_ini = fields.Text(related='gmd_id.camera_ini', readonly=True) 
    
    @api.multi
    def edit_dialog(self):
        form_view = self.env.ref('favite_bif.favite_bif_gsp_map')
        return {
            'name': _('Gsp'),
            'res_model': self._name,
            'res_id': self.id,
            'views': [(form_view.id, 'form'),],
            'type': 'ir.actions.act_window',
            'target': 'new'
        }
            
    @api.multi  
    def open_map(self):
        self.ensure_one()
        return {
            'type': 'ir.actions.act_window',
            'name': self.name,
            'res_model': self._name,
            'res_id': self.id,
            'view_id': self.env.ref('favite_bif.gsp_form').id,
            'view_type': 'map',
            'view_mode': 'map',
            'target': 'current',
            'flags':{'hasSearchView':False}
            }
        
    @api.multi
    def open_pad_list(self):
        ctx = dict(
            default_gmd_id=self.gmd_id.id,
            default_src_panel_id=self.src_panel_id.id,
        )
        return {
            'type': 'ir.actions.act_window',
            'name':'Pad',
            'res_model': 'favite_bif.pad',
            'view_mode': 'kanban,form',
            'view_id': False,
            'target': 'current',
            'flags':{'import_enabled':False},
            'domain': [('src_panel_id', '=', self.src_panel_id.id),('gmd_id', '=', self.gmd_id.id)],
            'context': ctx,
            }
Example #9
0
class Bif(models.Model):
    _name = 'favite_bif.bif'
    _inherit = ['favite_common.geometry']
    
    @api.one
    def _inverse_geo(self):
        if self.frame_id:
            if 'frame_filter' in self.geo:
                self.frame_id.geo['filter'] = self.geo['frame_filter']
            if 'frame_inspect' in self.geo:
                self.frame_id.geo['inspect'] = self.geo['frame_inspect']
            self.frame_id.write({'geo':self.frame_id.geo})
    
    @api.one
    @api.depends('gmd_id','gmd_id.geo','frame_id','frame_id.geo')
    def _compute_geo(self):
        self.geo['glass'] = self.gmd_id.geo['glass']
        self.geo['mark'] = self.gmd_id.geo['mark']
        self.geo['panel'] = {"objs":[]}
        
        total = self.env['favite_bif.panel'].sudo().search([('bif_id','=',self.id)])
        names = [p['name'] for b in self.gmd_id.geo['block']['objs'] for p in b['panels'] ]
        cur = self.env['favite_bif.panel'].sudo().search([('name','in',names)])
        (total - cur).unlink()
        
        for b in self.gmd_id.geo['block']['objs']:
            for p in b['panels']:
                self.geo['panel']['objs'].append(p)
                panel = self.env['favite_bif.panel'].sudo().search([('name','=',p['name'])]);
                if not panel:
                    self.env['favite_bif.panel'].sudo().create({'bif_id': self.id,'name':p['name']})
         
        self.geo['frame_filter'] = self.frame_id.geo['filter'] if self.frame_id else  {"objs":[]}
        self.geo['frame_inspect'] = self.frame_id.geo['inspect'] if self.frame_id else  {"objs":[]}
        
        self.geo['panel_filter'] = {"objs":[]}
        for panel in self.panel_ids:
            for obj in panel.geo['filter']['objs']:
                filter = obj
                filter['name'] = panel['name']
                self.geo['panel_filter']['objs'].append(filter)
        
    geo = fields.Jsonb(string = "geometry value",compute='_compute_geo',inverse='_inverse_geo')
    
    camera_path = fields.Char(related='gmd_id.camera_path', readonly=True)
    camera_ini = fields.Text(related='gmd_id.camera_ini', readonly=True)
    
    gmd_id = fields.Many2one('favite_gmd.gmd',ondelete='cascade')
    
    frame_id = fields.Many2one('favite_gmd.frame',ondelete='set null')
    mark_id = fields.Many2one('favite_gmd.mark',ondelete='set null')
    measure_id = fields.Many2one('favite_gmd.measure',ondelete='set null')
    fixpoint_id = fields.Many2one('favite_gmd.fixpoint',ondelete='set null')
    lut_id = fields.Many2one('favite_gmd.lut',ondelete='set null')
    
    panel_ids = fields.One2many('favite_bif.panel', 'bif_id', string='Panel')
    gsp_ids = fields.One2many('favite_bif.gsp', 'bif_id', string='Gsp')
    
    color = fields.Integer('Color Index', default=0)
 
    _sql_constraints = [
        
    ]    
    
    @api.multi  
    def open_map(self):
        self.ensure_one()
        return {
            'type': 'ir.actions.act_window',
            'name': self.name,
            'res_model': self._name,
            'res_id': self.id,
            'view_id': self.env.ref('favite_bif.favite_bif_bif_map').id,
            'view_type': 'map',
            'view_mode': 'map',
            'target': 'current',
            'flags':{'hasSearchView':False}
            }
    
    @api.multi
    def open_gsp_list(self):
        ctx = dict(
            default_bif_id=self.id,
        )
        return {
            'type': 'ir.actions.act_window',
            'name':'Gsp',
            'res_model': 'favite_bif.gsp',
            'view_mode': 'kanban,form',
            'view_id': False,
            'target': 'current',
            'flags':{'import_enabled':False},
            'domain': [('bif_id', '=', self.id)],
            'context': ctx,
            }
Example #10
0
class CostumModel(models.AbstractModel):
    _name = 'favite_common.costum'

    name = fields.Char(required=True, )
    description = fields.Text()
    color = fields.Integer(string='Color Index', default=10)

    @api.one
    def _compute_config(self):
        self.conf = self.env['res.config.settings'].get_values()

    conf = fields.Jsonb(string="config", compute=_compute_config)

    @api.one
    @api.constrains('name')
    def _check_name(self):
        if not re.match(PADNAME_PATTERN, self.name):
            raise ValidationError(
                _('Invalid name. Only alphanumerical characters, underscore, hyphen are allowed.'
                  ))

    @api.multi
    def close_dialog(self):
        return {'type': 'ir.actions.act_window_close'}

    @api.model
    def open_kanban(self):
        return {
            'type': 'ir.actions.act_window',
            'name': self._name.split('.')[-1],
            'res_model': self._name,
            'view_mode': 'kanban,form',
            'view_id': False,
            'target': 'current',
            'flags': {
                'import_enabled': False
            }
        }

    @api.model
    def load_views(self, views, options=None):
        result = super(CostumModel, self).load_views(views, options)

        if 'map' in result['fields_views'] or 'form' in result['fields_views']:
            notebook = E.xpath(expr="//notebook", position="inside")

            pages = {}
            g1 = {}

            fields_data = self.env['ir.model.fields']._get_manual_field_data(
                self._name)
            for fname, field in sorted(fields_data.items(),
                                       key=lambda f: f[1]['sequence']):
                if field['state'] != 'manual':
                    continue
                if not fname.startswith('x_'):
                    continue

                if 'locate' not in field or field['locate'] is None:
                    names = ['Common', 'Others']
                else:
                    names = field['locate'].split('.')
                    if len(names) == 1:
                        names = names + ['Others']

                key1 = names[0]
                if key1 not in pages:
                    p = E.page(string=names[0])
                    pages[key1] = p
                    notebook.append(p)

                key2 = names[0] + '.' + names[1]
                if key2 not in g1:
                    g = E.group(string=names[1])
                    g1[key2] = g
                    pages[key1].append(g)
                g1[key2].append(E.field(name=fname))

            if 'map' in result['fields_views']:
                src = etree.fromstring(result['fields_views']['map']['arch'])
            elif 'form' in result['fields_views']:
                src = etree.fromstring(result['fields_views']['form']['arch'])
            View = self.env['ir.ui.view']
            node = View.locate_node(src, notebook)
            if node is not None:
                dest = View.apply_inheritance_specs(src, notebook, 0)

                if 'map' in result['fields_views']:
                    result['fields_views']['map']['arch'] = etree.tostring(
                        dest, encoding='unicode')
                elif 'form' in result['fields_views']:
                    result['fields_views']['form']['arch'] = etree.tostring(
                        dest, encoding='unicode')

        return result

    def export_file(self, dir):
        pass
Example #11
0
class Gmd(models.Model):
    _name = 'favite_gmd.gmd'
    _inherit = ['favite_common.geometry']
    _sql_constraints = [
        ('name_uniq', 'unique (name)', "Name already exists !"),
    ]
    
    @api.model
    def _default_geo(self):
        geo = {
        "lightregion":{"objs":[]},
        "markoffset":{"objs":[]},
        "mark":{"objs":[]},
        "block":{"objs":[],"mask":[]},
        }
        return geo
    
    @api.model
    def _default_glass(self):
        glass = {"corner":1,"size":[2200,2500],"coord":0,"iCenterMode":-1,"iLongEdge":-1,"iStartQuandrant":1}
        return glass
    
    @api.depends('camera_path')
    def _compute_name(self):
        for g in self:
            iniFile = os.path.join(g.camera_path, 'FISTConfig.ini')
            iniConf = ConfigParser.RawConfigParser()
            with open(iniFile, 'r') as f:
                iniConf.read_string("[DEFAULT]\r\n" + f.read())
                g.camera_name =  iniConf._defaults['CAMERA_FILE'.lower()]
    
    @api.depends('camera_path')
    def _compute_ini(self):
        for g in self:
            iniFile = os.path.join(g.camera_path , g.camera_name)
            iniConf = ConfigParser.RawConfigParser()
            with open(iniFile, 'r') as f:
                iniConf.read_string("[DEFAULT]\r\n" + f.read())
                g.camera_ini =  json.dumps(iniConf._defaults,indent=5)
            
    
    def _list_all_camers(self):
        cameras = []
        root = tools.config['camera_data_path']  
        for dir in os.listdir(root):   
            subdir = os.path.join(root , dir)
            if not os.path.isdir(subdir):
                continue
            
            iniFilePath = os.path.join(subdir, "FISTConfig.ini")
            if not os.path.isfile(iniFilePath):
                continue
            
            jpgFilePath = os.path.join(subdir , "Image")
            if not os.path.isdir(jpgFilePath):
                continue
            
            cameras.append((subdir,subdir))
#                 
#             glass_map = os.path.join(subdir , "glass.bmp")
#             if not os.path.isfile(glass_map):
#                 iniFile = os.path.join(subdir, 'FISTConfig.ini')
#                 iniConf = ConfigParser.RawConfigParser()
#                 with open(iniFile, 'r') as f:
#                     iniConf.read_string("[DEFAULT]\r\n" + f.read())
#                     camera_name =  iniConf._defaults['CAMERA_FILE'.lower()]
#             
#                     self._generate_glass_map(subdir,camera_name)
#                 
        return cameras
    
    @api.model
    def _default_camera(self):
        camera = ''
        root = tools.config['camera_data_path']  
        for dir in os.listdir(root):   
            subdir = os.path.join(root , dir)
            if not os.path.isdir(subdir):
                continue
            
            iniFilePath = os.path.join(subdir, "FISTConfig.ini")
            if not os.path.isfile(iniFilePath):
                continue
            
            jpgFilePath = os.path.join(subdir , "Image")
            if not os.path.isdir(jpgFilePath):
                continue
            
            if dir == 'default':
                camera = subdir
                break
                
        return camera
    
    source_path = fields.Selection(selection='_list_all_camers',default=_default_camera,string='Camera data path', required=True)
    camera_path = fields.Char(required=True)
    camera_name = fields.Text(compute='_compute_name')
    camera_ini = fields.Text(compute='_compute_ini')
    geo = fields.Jsonb(required=True,string = "geometry value",default=_default_geo)
    glass = fields.Jsonb(required=True,string = "glass value",default=_default_glass)
    color = fields.Integer('Color Index', default=0)
    
    def compute_jpeg_path(self,ip,scan,block):
        if self.x_img_path and self.x_img_path != '':
            return os.path.join(self.x_img_path,'IP%d'%(ip+1),'jpegfile','AoiL_IP%d_scan%d_block%d.jpg'%(ip,scan,block))
         
        selfPath = os.path.join(self.camera_path,'Image','IP%d'%(ip+1),'jpegfile','AoiL_IP%d_scan%d_block%d.jpg'%(ip,scan,block))
        if os.path.isfile(selfPath):
            return selfPath
         
        sourcePath = os.path.join(self.source_path,'Image','IP%d'%(ip+1),'jpegfile','AoiL_IP%d_scan%d_block%d.jpg'%(ip,scan,block))
        if os.path.isfile(sourcePath):
            return sourcePath
        
        iniFile = os.path.join(self.camera_path, 'FISTConfig.ini')
        iniConf = ConfigParser.RawConfigParser()
        with open(iniFile, 'r') as f:
            iniConf.read_string("[DEFAULT]\r\n" + f.read())
            ip_path = iniConf._defaults['net_path_ip%d'%(ip+1)]
            backupPath = os.path.join(ip_path,'jpegfile','AoiL_IP%d_scan%d_block%d.jpg'%(ip,scan,block))
            
        if os.path.isfile(backupPath):
            return backupPath
        
        raise UserError('Image file does not exist.')
    
    def compute_bmp_path(self,ip,scan):
        if self.x_img_path and self.x_img_path != '':
            return os.path.join(self.x_img_path,'IP%d'%(ip+1),'bmp','AoiL_IP%d_small%d.bmp'%(ip,scan))
        
        selfPath = os.path.join(self.camera_path,'Image','IP%d'%(ip+1),'bmp','AoiL_IP%d_small%d.bmp'%(ip,scan))
        if os.path.isfile(selfPath):
            return selfPath
        
        sourcePath = os.path.join(self.source_path,'Image','IP%d'%(ip+1),'bmp','AoiL_IP%d_small%d.bmp'%(ip,scan))
        if os.path.isfile(sourcePath):
            return sourcePath
        
        iniFile = os.path.join(self.camera_path, 'FISTConfig.ini')
        iniConf = ConfigParser.RawConfigParser()
        with open(iniFile, 'r') as f:
            iniConf.read_string("[DEFAULT]\r\n" + f.read())
            ip_path = iniConf._defaults['net_path_ip%d'%(ip+1)]
            backupPath = os.path.join(ip_path,'bmp','AoiL_IP%d_small%d.bmp'%(ip,scan))
            
        if os.path.isfile(backupPath):
            return backupPath
        
        raise UserError('Image file does not exist.')
    
    @api.one
    @api.constrains('x_img_path')
    def _check_img_path(self):
        if self.x_img_path and self.x_img_path != '':
            if not os.path.isfile(os.path.join(self.x_img_path,'IP1','jpegfile','AoiL_IP0_scan0_block0.jpg')):
                raise ValidationError('Invalid image file directory.')
        
    @api.model
    def create(self, vals):   
        root = tools.config['camera_data_path']     
        newPath = os.path.join(root , vals['name'])
        shutil.copytree(vals['source_path'],newPath,ignore=lambda src,names:[] if src == vals['source_path'] else names) 
        vals['camera_path'] = newPath
        
        gmd = super(Gmd, self).create(vals)
        
        if not os.path.isfile(os.path.join(gmd.camera_path , 'glass.bmp')):
            gmd._generate_glass_map()
        
        return gmd

        
    def _create_block(self,vals):
        if 'geo' not in vals:
            return 
        if 'block' not in vals['geo']:
            return 
        
        total = self.env['favite_gmd.block'].sudo().search([])
        names = [b['name'] for b in vals['geo']['block']['objs'] ]
        cur = self.env['favite_gmd.block'].sudo().search([('name','in',names)])
        (total - cur).unlink()
        
        for b in vals['geo']['block']['objs']:
            block = self.env['favite_gmd.block'].sudo().search([('name','=',b['name'])]);
            if not block:
                self.env['favite_gmd.block'].sudo().create({'gmd_id': self.id, 'name':b['name']})
    
    def check_data_path(self,root):
        if not os.path.exists(root):
            raise ValidationError(_('Invalid data directory.'))
        
        cameraFile = root + '/camera.ini'
        if not os.path.isfile(cameraFile):
            raise UserError("File(%s) doesn't exist" % 'camera.ini')
    
    
    def _get_top_left(self,conf,ip,scan,dLeft):
        iCameraNoPerRow = 2
        dOffset = [int(s) for s in conf['ip.%d.scan.%d.offset'%(ip,scan)].split(',')]
        iTotalScan = int(conf['ip.scan.number'])
        if (ip % iCameraNoPerRow) == 0  and scan == 0:
            dOffset0 = [int(s) for s in conf['ip.%d.scan.%d.offset'%(0,0)].split(',')]
            
            dResolution = [float(s) for s in conf['ip.%d.scan.%d.res'%(ip,scan)].split(',')]
            dLeft = (dOffset[0] - dOffset0[0]) / dResolution[0]
        elif scan == 0:
            dOffset0 = [int(s) for s in conf['ip.%d.scan.%d.offset'%(ip - 1,iTotalScan - 1)].split(',')]
            dResolution = [float(s) for s in conf['ip.%d.scan.%d.res'%(ip,iTotalScan - 1)].split(',')]
            dLeft += (dOffset[0] - dOffset0[0]) / dResolution[0]
        else:
            dOffset0 = [int(s) for s in conf['ip.%d.scan.%d.offset'%(ip,scan-1)].split(',')]
            dResolution = [float(s) for s in conf['ip.%d.scan.%d.res'%(ip,iTotalScan - 1)].split(',')]
            dLeft += (dOffset[0] - dOffset0[0]) / dResolution[0]
            
        dOffset00 = [int(s) for s in conf['ip.%d.scan.%d.offset'%(0,0)].split(',')]
        if ip >= iCameraNoPerRow:
            dOffset0 = [int(s) for s in conf['ip.%d.scan.%d.offset'%(ip- iCameraNoPerRow,scan)].split(',')]
            dResolution = [float(s) for s in conf['ip.%d.scan.%d.res'%(ip- iCameraNoPerRow,scan)].split(',')]
            dBottom = (dOffset[1] - dOffset0[1]) / dResolution[1] + (dOffset0[1] - dOffset00[1]) / dResolution[1]
        else:
            dResolution = [float(s) for s in conf['ip.%d.scan.%d.res'%(ip,scan)].split(',')]
            dBottom = (dOffset[1] - dOffset00[1]) / dResolution[1];
            
        iRange_Left = math.ceil(dLeft);
        iRange_Bottom = math.ceil(dBottom)
            
        return dLeft,iRange_Left,iRange_Bottom
    
    def _generate_glass_map(self):          
        iniFile = os.path.join(self.camera_path , self.camera_name)
        conf = ConfigParser.RawConfigParser()
        with open(iniFile, 'r') as f:
            conf.read_string("[DEFAULT]\r\n" + f.read())
            
        ip_num = int(conf._defaults['ip.number'])
        scan_num = int(conf._defaults['ip.scan.number'])
        dLeft = 0
        
        scanrect = [int(s) for s in conf._defaults['image.scanrect'].split(',')]
        resizerate = [float(s) for s in conf._defaults['image.dm.resizerate'].split(',')]
        
        dms = []
        width = 0
        height = 0
        for ip in range(ip_num):
            for scan in range(scan_num):
                dLeft,iRange_Left,iRange_Bottom = self._get_top_left(conf._defaults,ip,scan,dLeft)
                #imgFile = root + '\\Image\\IP%d\\bmp\\AoiL_IP%d_small%d.bmp'%(ip+1,ip,scan)
                imgFile = self.compute_bmp_path(ip,scan)
                dms.append({'imgFile':imgFile,'iRange_Left':iRange_Left,'iRange_Bottom':iRange_Bottom})
                if iRange_Left > width:
                    width = iRange_Left
                if iRange_Bottom > height:
                    height = iRange_Bottom

        width = math.floor((width+scanrect[2])/resizerate[0])
        height = math.floor((height+scanrect[3])/resizerate[1])
        dest = Image.new('L', (width,height))        
        for dm in dms:
            im = Image.open(dm['imgFile'])
            left = math.ceil(dm['iRange_Left'] / resizerate[0])
            top = height - math.ceil((dm['iRange_Bottom'] + scanrect[3] -1) / resizerate[1])
            dest.paste(im, (left,top))
            im.close()
                
        dest.save(os.path.join(self.camera_path , 'glass.bmp'), format="bmp")    
    
    def _generate_glass_map2(self,root,camera_name):
        conf = ConfigParser.RawConfigParser()
        with open(os.path.join(root , camera_name), 'r') as f:
            conf.read_string("[DEFAULT]\r\n" + f.read())
            
        ip_num = int(conf._defaults['ip.number'])
        scan_num = int(conf._defaults['ip.scan.number'])
        dLeft = 0
        
        scanrect = [int(s) for s in conf._defaults['image.scanrect'].split(',')]
        resizerate = [float(s) for s in conf._defaults['image.dm.resizerate'].split(',')]
        
        dms = []
        width = 0
        height = 0
        for ip in range(ip_num):
            for scan in range(scan_num):
                dLeft,iRange_Left,iRange_Bottom = self._get_top_left(conf._defaults,ip,scan,dLeft)
                #imgFile = root + '\\Image\\IP%d\\bmp\\AoiL_IP%d_small%d.bmp'%(ip+1,ip,scan)
                imgFile = self.compute_bmp_path(ip,scan)
                dms.append({'imgFile':imgFile,'iRange_Left':iRange_Left,'iRange_Bottom':iRange_Bottom})
                if iRange_Left > width:
                    width = iRange_Left
                if iRange_Bottom > height:
                    height = iRange_Bottom

        width = math.floor((width+scanrect[2])/resizerate[0])
        height = math.floor((height+scanrect[3])/resizerate[1])
        dest = Image.new('L', (width,height))        
        for dm in dms:
            im = Image.open(dm['imgFile'])
            left = math.ceil(dm['iRange_Left'] / resizerate[0])
            top = height - math.ceil((dm['iRange_Bottom'] + scanrect[3] -1) / resizerate[1])
            dest.paste(im, (left,top))
            im.close()
                
        dest.save(root + '\glass.bmp', format="bmp")
        
    def generate_panel_map(self,panelName,width,height,strBlocks,map_rate):
        root = self.camera_path  
        blocks = json.loads(strBlocks)
        dest = Image.new('L', (int(width*map_rate),int(height*map_rate)))
        left = 0
        top = 0
        for x in range(len(blocks)):
            for y in range(len(blocks[x])-1,-1,-1):
                b = blocks[x][y]    
                if b is None or b['bHasIntersection'] == False:
                    continue;
                
                #imgFile = '%s/Image/IP%d/jpegfile/AoiL_IP%d_scan%d_block%d.jpg' % (root,b['iIPIndex']+1,b['iIPIndex'],b['iScanIndex'],b['iBlockIndex'])
                imgFile = self.compute_jpeg_path(b['iIPIndex'],b['iScanIndex'],b['iBlockIndex'])
                rw = int(b['iInterSectionWidth']*map_rate)
                rh = int(b['iInterSectionHeight']*map_rate)
                try:
                    im = Image.open(imgFile)
                    im = im.transpose(Image.FLIP_TOP_BOTTOM)
                    region = im.crop((b['iInterSectionStartX'] ,im.height-(b['iInterSectionStartY']+b['iInterSectionHeight']),b['iInterSectionStartX']+ b['iInterSectionWidth'], im.height-b['iInterSectionStartY']))
                    
                    region = region.resize((rw,rh))
                    dest.paste(region, (left,top))
                    im.close()
                except Exception as e:
                    pass
                
                if y == 0:
                    left += rw
                    top = 0
                else:
                    top += rh
        dest.save(root +'/'+ panelName +'.jpg', format="jpeg")



    def export_coord(self):
        iCenterMode = 1
        iLongEdge = 1
        iStartQuandrant = 1
        if self.glass['coord'] == 0:
            iCenterMode = 1
            iLongEdge = 1
            iStartQuandrant = 1
        elif self.glass['coord'] == 1:
            iCenterMode = 1
            iLongEdge = 1
            iStartQuandrant = 2
        elif self.glass['coord'] == 2:
            iCenterMode = 1
            iLongEdge = 1
            iStartQuandrant = 3
        elif self.glass['coord'] == 3:
            iCenterMode = 1
            iLongEdge = 1
            iStartQuandrant = 4
        elif self.glass['coord'] == 4:
            iCenterMode = 1
            iLongEdge = 0
            iStartQuandrant = 1
        elif self.glass['coord'] == 5:
            iCenterMode = 1
            iLongEdge = 0
            iStartQuandrant = 2
        elif self.glass['coord'] == 6:
            iCenterMode = 1
            iLongEdge = 0
            iStartQuandrant = 3
        elif self.glass['coord'] == 1:
            iCenterMode = 1
            iLongEdge = 0
            iStartQuandrant = 4
        elif self.glass['coord'] == 1:
            iCenterMode = 0
            iLongEdge = 1
            iStartQuandrant = 1
        elif self.glass['coord'] == 1:
            iCenterMode = 0
            iLongEdge = 1
            iStartQuandrant = 2
        elif self.glass['coord'] == 1:
            iCenterMode = 0
            iLongEdge = 1
            iStartQuandrant = 3
        elif self.glass['coord'] == 1:
            iCenterMode = 0
            iLongEdge = 1;
            iStartQuandrant = 4
        elif self.glass['coord'] == 1:
            iCenterMode = 0
            iLongEdge = 0
            iStartQuandrant = 1
        elif self.glass['coord'] == 1:
            iCenterMode = 0
            iLongEdge = 0
            iStartQuandrant = 2
        elif self.glass['coord'] == 1:
            iCenterMode = 0
            iLongEdge = 0
            iStartQuandrant = 3
        elif self.glass['coord'] == 1:
            iCenterMode = 0
            iLongEdge = 0
            iStartQuandrant = 4

        return iCenterMode,iLongEdge,iStartQuandrant
    
    @api.model
    def import_coord(self, par):
        ret = 1
        centermode = 1
        longedge = 1
        iStartQuadrant = 1
        if 'coordtransform.centermode' in par:
            centermode = int(par['coordtransform.centermode'])
        if 'coordtransform.dm.longedge' in par:
            longedge = int(par['coordtransform.dm.longedge'])
        if 'coordtransform.dm.minquadrant' in par:
            iStartQuadrant = int(par['coordtransform.dm.minquadrant'])
            
        if centermode == 0:
            if iStartQuadrant == 1:
                ret = 8 if longedge else 12
            elif iStartQuadrant == 2:
                ret = 9 if longedge else 13
            elif iStartQuadrant == 3:
                ret = 10 if longedge else 14
            elif iStartQuadrant == 4:
                ret = 11 if longedge else 15
        elif centermode == 1:
            if iStartQuadrant == 1:
                ret = 0 if longedge else 4
            elif iStartQuadrant == 2:
                ret = 1 if longedge else 5
            elif iStartQuadrant == 3:
                ret = 2 if longedge else 6
            elif iStartQuadrant == 4:
                ret = 3 if longedge else 7
                
        return ret
 
    def _get_panels(self,p1,p2,blocks):
        res = []
        left = min(p1['x'],p2['x'])
        right = max(p1['x'],p2['x'])
        top = max(p1['y'],p2['y'])
        bottom = min(p1['y'],p2['y'])
            
        def _check_panel(points):
            return points[0]['x'] >= left and points[0]['x'] <= right and points[1]['x'] >= left and points[1]['x'] <= right and points[0]['y'] >= bottom and points[0]['y'] <= top and points[1]['y'] >= bottom and points[1]['y'] <= top

        for b in blocks:
            for p in b['panels']:
                if _check_panel(p['points']):
                    res.append(p['name'])
        return ','.join(res)
    
    def _um2customer(self,dCustomerPointX,dCustomerPointY,dGlassCenterX,dGlassCenterY,dAngle):
        iCenterMode,iLongEdge,iStartQuadrant = self.export_coord()
        
        dInputX = dCustomerPointX
        dInputY = dCustomerPointY
        dCustomerPointX = (dInputX -dGlassCenterX) * math.cos(dAngle) + (dInputY - dGlassCenterY) * math.sin(dAngle)
        dCustomerPointY = -(dInputX - dGlassCenterX) * math.sin(dAngle) + (dInputY - dGlassCenterY) * math.cos(dAngle)

        if iStartQuadrant == 1 or iStartQuadrant == 2:
            dCustomerPointY *= -1

        if iStartQuadrant == 1 or iStartQuadrant == 4:
            dCustomerPointX *= -1

        if iCenterMode == 0:
            dCustomerPointX += m_dGlassSizeX / 2
            dCustomerPointY += m_dGlassSizeY / 2
        elif iCenterMode == 2:
            if self.glass['size'][0] < self.glass['size'][1]:
                dCustomerPointX += self.glass['size'][0] / 2
            else:
                dCustomerPointY += self.glass['size'][1] / 2
        elif iCenterMode == 3:
            if self.glass['size'][0] > self.glass['size'][1]:
                dCustomerPointX += self.glass['size'][0] / 2
            else:
                dCustomerPointY += self.glass['size'][1] / 2


#         if iLongEdge != this.m_iGlassLongEdge:
#             dTemp = dCustomerPointX;
#             dCustomerPointX = dCustomerPointY;
#             dCustomerPointY = dTemp;

        return (dCustomerPointX, dCustomerPointY);
    
    def _export_geo(self):
        
        iniFile = os.path.join(self.camera_path , self.camera_name)
        iniConf = ConfigParser.RawConfigParser()
        with open(iniFile, 'r') as f:
            iniConf.read_string("[DEFAULT]\r\n" + f.read())
            dGlassCenterX,dGlassCenterY = (float(s) for s in iniConf._defaults['glass.center.position.0'].split(','))
            dAngle = float(iniConf._defaults['glass.angle.0'])
            
            geo = copy.deepcopy(self.geo)      
            for o in geo['lightregion']['objs']:
                for p in o['points']:
                    dCustomerPointX, dCustomerPointY = self._um2customer(p['x'],p['y'],dGlassCenterX,dGlassCenterY,dAngle)
                    p['x'] = dCustomerPointX
                    p['y'] = dCustomerPointY
                    
            for o in geo['markoffset']['objs']:
                for p in o['points']:
                    dCustomerPointX, dCustomerPointY = self._um2customer(p['x'],p['y'],dGlassCenterX,dGlassCenterY,dAngle)
                    p['x'] = dCustomerPointX
                    p['y'] = dCustomerPointY
                    
            for o in geo['mark']['objs']:
                for p in o['points']:
                    dCustomerPointX, dCustomerPointY = self._um2customer(p['x'],p['y'],dGlassCenterX,dGlassCenterY,dAngle)
                    p['x'] = dCustomerPointX
                    p['y'] = dCustomerPointY
                    
                    
            for b in geo['block']['objs']:
                if 'pad' not in b:
                    continue
                if 'panels' not in b:
                    continue
                
                for p in b['pad']['points']:
                    dCustomerPointX, dCustomerPointY = self._um2customer(p['x'],p['y'],dGlassCenterX,dGlassCenterY,dAngle)
                    p['x'] = dCustomerPointX
                    p['y'] = dCustomerPointY

                for panel in b['panels']:
                    for p in panel['points']:
                        dCustomerPointX, dCustomerPointY = self._um2customer(p['x'],p['y'],dGlassCenterX,dGlassCenterY,dAngle)
                        p['x'] = dCustomerPointX
                        p['y'] = dCustomerPointY

            return geo
    
    def _customer2um(self,dCustomerPointX,dCustomerPointY,dGlassCenterX,dGlassCenterY,dAngle):
        iCenterMode,iLongEdge,iStartQuadrant = self.export_coord()
        
        dFavitePointX = dCustomerPointX
        dFavitePointY = dCustomerPointY
#         if iImageLongEdge != this.m_iGlassLongEdge:
#             dTemp = dFavitePointX;
#             dFavitePointX = dFavitePointY;
#             dFavitePointY = dTemp;

        if iCenterMode == 0:
            dFavitePointX -= dGlassCenterX / 2
            dFavitePointY -= dGlassCenterY / 2
        elif iCenterMode == 2:
            if dGlassCenterX < dGlassCenterY:
                dFavitePointX -= dGlassCenterX / 2
            else:
                dFavitePointY -= dGlassCenterY / 2
        elif iCenterMode == 3:
            if dGlassCenterX > dGlassCenterY:
                dFavitePointX -= dGlassCenterX / 2
            else:
                dFavitePointY -= dGlassCenterY / 2

        if iStartQuadrant == 1 or this.m_iStartQuadrant == 2:
            dFavitePointY *= -1

        if iStartQuadrant == 1 or this.m_iStartQuadrant == 4:
            dFavitePointX *= -1
        
        dInputX = dFavitePointX
        dInputY = dFavitePointY
        dFavitePointX = dInputX * math.cos(-dAngle) + dInputY * math.sin(-dAngle) + dGlassCenterX;
        dFavitePointY = -dInputX * math.sin(-dAngle) + dInputY * math.cos(-dAngle) + dGlassCenterY;
        
        return (dFavitePointX,dFavitePointY)

    
    def _import_geo(self):
        iniFile = os.path.join(self.camera_path , self.camera_name)
        iniConf = ConfigParser.RawConfigParser()
        with open(iniFile, 'r') as f:
            iniConf.read_string("[DEFAULT]\r\n" + f.read())
            dGlassCenterX,dGlassCenterY = (float(s) for s in iniConf._defaults['glass.center.position.0'].split(','))
            dAngle = float(iniConf._defaults['glass.angle.0'])
            
            geo = self.geo    
            for o in geo['lightregion']['objs']:
                for p in o['points']:
                    dCustomerPointX, dCustomerPointY = self._customer2um(p['x'],p['y'],dGlassCenterX,dGlassCenterY,dAngle)
                    p['x'] = dCustomerPointX
                    p['y'] = dCustomerPointY
                    
            for o in geo['markoffset']['objs']:
                for p in o['points']:
                    dCustomerPointX, dCustomerPointY = self._customer2um(p['x'],p['y'],dGlassCenterX,dGlassCenterY,dAngle)
                    p['x'] = dCustomerPointX
                    p['y'] = dCustomerPointY
                    
            for o in geo['mark']['objs']:
                for p in o['points']:
                    dCustomerPointX, dCustomerPointY = self._customer2um(p['x'],p['y'],dGlassCenterX,dGlassCenterY,dAngle)
                    p['x'] = dCustomerPointX
                    p['y'] = dCustomerPointY
                    
                    
            for b in geo['block']['objs']:
                for p in b['pad']['points']:
                    dCustomerPointX, dCustomerPointY = self._customer2um(p['x'],p['y'],dGlassCenterX,dGlassCenterY,dAngle)
                    p['x'] = dCustomerPointX
                    p['y'] = dCustomerPointY

                for panel in b['panels']:
                    for p in panel['points']:
                        dCustomerPointX, dCustomerPointY = self._customer2um(p['x'],p['y'],dGlassCenterX,dGlassCenterY,dAngle)
                        p['x'] = dCustomerPointX
                        p['y'] = dCustomerPointY

        
            self.write({'geo': geo})
            
                   
    @api.one
    def export_file(self,directory_ids):
        strCoordtransform = 'coordtransform.customer.glasssize = %d,%d\n' % tuple(self.glass['size'])
        strCoordtransform += 'coordtransform.dm.cutcorner = %d\n' % self.glass['corner']
        
        iCenterMode,iLongEdge,iStartQuandrant = self.export_coord()
        strCoordtransform += 'coordtransform.centermode =  %d\n' % iCenterMode
        strCoordtransform += 'coordtransform.dm.longedge = %d\n' % iLongEdge
        strCoordtransform += 'coordtransform.dm.minquadrant = %d\n' % iStartQuandrant
        
        geo = self._export_geo()
        strMark = ''
        if len(geo['markoffset']['objs']) and len(geo['markoffset']['objs'][0]['points']) > 1:
            p1 = geo['markoffset']['objs'][0]['points'][0]
            p2 = geo['markoffset']['objs'][0]['points'][1]
            w = abs(p1['x'] - p2['x'])
            h = abs(p1['y'] - p2['y'])
            strMark += 'mark.offset = %f,%f\n' % (w,h)
            strMark += 'mark.offset.p1 = %f,%f\n' % (p1['x'],p1['y'])
            strMark += 'mark.offset.p2 = %f,%f\n' % (p2['x'],p2['y'])
            
        markNum = len(geo['mark']['objs'])
        strMark += 'mark.number = %d\n' % markNum
        for i in range(0,markNum):
            p1 = geo['mark']['objs'][i]['points'][0]
            p2 = geo['mark']['objs'][i]['points'][1]
            x = (p1['x'] + p2['x'])/2
            y = (p1['y'] + p2['y'])/2
            strMark += 'mark.%d.position = %f,%f\n' % (i,x,y)
            w = abs(p1['x'] - p2['x'])
            h = abs(p1['y'] - p2['y'])
            strMark += 'mark.%d.size = %f,%f\n' % (i,w,h)
            
        lightregionNum = len(geo['lightregion']['objs'])
        strlightregion = 'lightregion.number = %d\n' % lightregionNum
        for i in range(0,lightregionNum):
            p1 = geo['lightregion']['objs'][i]['points'][0]
            p2 = geo['lightregion']['objs'][i]['points'][1]
            left = min(p1['x'],p2['x'])
            right = max(p1['x'],p2['x'])
            bottom = min(p1['y'],p2['y'])
            top = max(p1['y'],p2['y'])
            strlightregion += 'lightregion.%d.position = %f,%f,%f,%f\n' % (i,left,bottom,right,top)
            
        maskNum = len(geo['block']['mask'])
        strMask = 'mask.group.number = %d\n' % maskNum
        for i in range(0,maskNum):
            strMask += 'mask.group.%d.threshold = %s\n' % (i,geo['block']['mask'][i]['threshold'])
            strMask += 'mask.group.%d.panellist = %s\n' % (i,geo['block']['mask'][i]['panels'])
            
        panelNum = 0
        strPanel = 'panel.idmode = 0\n'
        for b in geo['block']['objs']:
            if 'pad' not in b:
                continue
            if 'panels' not in b:
                continue
                
            padx = b['points'][0]['x'] - b['pad']['points'][0]['x']
            pady = b['points'][0]['y'] - b['pad']['points'][0]['y']
            for p in b['panels']:
                strPanel += 'panel.%d.pixelsize = %s\n' % (panelNum,p['pixelsize'])
                strPanel += 'panel.%d.d1g1 = %s\n' % (panelNum,p['d1g1'])
                strPanel += 'panel.%d.id = %s\n' % (panelNum,p['panel_index'])
                
                x1 = p['points'][0]['x']
                x2 = p['points'][2]['x']
                x3 = p['points'][1]['x']
                x4 = p['points'][3]['x']
                y1 = p['points'][0]['y']
                y2 = p['points'][2]['y']
                y3 = p['points'][1]['y']
                y4 = p['points'][3]['y']

                x = ((x1 - x2) * (x3 * y4 - x4 * y3) - (x3 - x4) * (x1 * y2 - x2 * y1))  / ((x3 - x4) * (y1 - y2) - (x1 - x2) * (y3 - y4))
                y = ((y1 - y2) * (x3 * y4 - x4 * y3) - (x1 * y2 - x2 * y1) * (y3 - y4))  / ((y1 - y2) * (x3 - x4) - (x1 - x2) * (y3 - y4))
                strPanel += 'panel.%d.position = %f,%f\n' % (panelNum,x,y)
                strPanel += 'panel.%d.size = %f,%f\n' % (panelNum,b['panel_width'],b['panel_height'])
                
                strPanel += 'panel.%d.padrange.left = %f\n' % (panelNum,min(x1,x2,x3,x4) - padx)
                strPanel += 'panel.%d.padrange.top = %f\n' % (panelNum,max(y1,y2,y3,y4) + pady)
                strPanel += 'panel.%d.padrange.right = %f\n' % (panelNum,max(x1,x2,x3,x4) + padx)
                strPanel += 'panel.%d.padrange.bottom = %f\n' % (panelNum,min(y1,y2,y3,y4) - pady)

                panelNum = panelNum + 1
        
        strPanel += 'panel.number = %d\n' % panelNum

        strParameter = ''
        fields_data = self.env['ir.model.fields']._get_manual_field_data(self._name)
        for name, field in sorted(self._fields.items(), key=lambda f: f[0]):
            if not field.manual or not name.startswith('x_'):
                continue
            elif field.type == 'boolean' or field.type == 'selection':
                strParameter += '%s = %d\n' % (fields_data[name]['complete_name'],self[name])
            else:
                strParameter += '%s = %s\n' % (fields_data[name]['complete_name'],field.convert_to_export(self[name],self))
                
        for d in directory_ids: 
            dir = os.path.join(d.name ,'recipe')
            if not os.path.isdir(dir):
                os.makedirs(dir) 
            dir = os.path.join(d.name ,'recipe','gmd')
            if not os.path.isdir(dir):
                os.makedirs(dir)
            path = os.path.join(dir,self.name+'.gmd')
            with open(path, 'w') as f:
                f.write(strParameter)
                f.write(strCoordtransform)
                f.write(strMark)
                f.write(strMask)
                f.write(strlightregion)
                f.write(strPanel)
                f.write('\n#######Do not edit this field; automatically generated by export.##############\n')
                f.write('camera_path = %s\n'%self.camera_path)
                f.write('block = %s\n'%json.dumps(geo['block']))

    @api.model
    def import_file(self,file):
        written = True
        message = 'Success'

        geo = {
        "lightregion":{"objs":[]},
        "markoffset":{"objs":[]},
        "mark":{"objs":[]},
        "block":{"objs":[],"mask":[]},
        }
        glass = {"corner":1,"size":[0,0],"coord":0}
        obj = {'name':file.filename.split('.')[0]}
        
        try:
            parser = ConfigParser.RawConfigParser()
            parser.read_string("[DEFAULT]\r\n" + file.read().decode())
            par = parser._defaults
            
            obj['camera_path'] = par['camera_path']
            if 'block' in par:
                geo['block'] = json.loads(par['block'])  
            
            if 'coordtransform.customer.glasssize' in par:
                glass['size'] = [int(s) for s in par['coordtransform.customer.glasssize'].split(',')]
            if 'coordtransform.dm.cutcorner' in par:
                glass['corner'] = int(par['coordtransform.dm.cutcorner'])
            glass['coord'] = self.import_coord(par)   
            
            p = {'points':[]}
            x,y = (float(s) for s in par['mark.offset.p1'].split(','))
            p['points'].append({'x':x,'y':y})
            x,y = (float(s) for s in par['mark.offset.p2'].split(','))
            p['points'].append({'x':x,'y':y})
            geo['markoffset']['objs'].append(p)
            
            n = int(par.get('mark.number'.lower(),0))
            for i in range(0, n):
                x,y = (float(s) for s in par['mark.%d.position'%i].split(','))
                w,h = (float(s) for s in par['mark.%d.size'%i].split(','))
                p = {'points':[]}
                p['points'].append({'x':x-w/2,'y':y-h/2})
                p['points'].append({'x':x+w/2,'y':y+h/2})
                geo['mark']['objs'].append(p)
                
            n = int(par.get('lightregion.number'.lower(),0))
            for i in range(0, n):
                x1,y1,x2,y2 = (float(s) for s in par['lightregion.%d.position'%i].split(','))
                p = {'points':[]}
                p['points'].append({'x':x1,'y':y1})
                p['points'].append({'x':x2,'y':y2})
                geo['lightregion']['objs'].append(p)    
                
            n = int(par.get('mask.group.number'.lower(),0))
            for i in range(0, n):
                g = {
                    'panels':par['mask.group.%d.panellist'%i],
                    'threshold':int(par.get('mask.group.%d.threshold'%i,0))
                    }
                geo['block']['mask'].append(g)  
                
                
            fields_data = self.env['ir.model.fields']._get_manual_field_data(self._name)
            for name, field in self._fields.items():
                if not field.manual or not name.startswith('x_'):
                    continue
                
                complete_name = fields_data[name]['complete_name']
                if complete_name.lower() in par:
                    value = par[complete_name.lower()]
                    obj[name] = field.convert_to_cache(value, self)   
                    if isinstance(obj[name], bool):
                        obj[name] = value == '1' 
                        
            obj['geo'] = geo 
            obj['glass'] = glass 
            self.create(obj)._import_geo()         
        except Exception as e:
            written = False
            message = str(e)
        return {'success': written,'message':message}