PPOCRLabel.py 83.1 KB
Newer Older
qq_25193841's avatar
qq_25193841 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
# Copyright (c) <2015-Present> Tzutalin
# Copyright (C) 2013  MIT, Computer Science and Artificial Intelligence Laboratory. Bryan Russell, Antonio Torralba,
# William T. Freeman. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
# associated documentation files (the "Software"), to deal in the Software without restriction, including without
# limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
# Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of
# the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
# NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
# CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# pyrcc5 -o libs/resources.py resources.qrc
import argparse
import ast
import codecs
import os.path
import platform
import subprocess
import sys
from functools import partial
from collections import defaultdict
import json

qq_25193841's avatar
qq_25193841 已提交
28

qq_25193841's avatar
qq_25193841 已提交
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
__dir__ = os.path.dirname(os.path.abspath(__file__))
sys.path.append(__dir__)
sys.path.append(os.path.abspath(os.path.join(__dir__, '../..')))
sys.path.append("..")

from paddleocr import PaddleOCR

try:
    from PyQt5 import QtCore, QtGui, QtWidgets
    from PyQt5.QtGui import *
    from PyQt5.QtCore import *
    from PyQt5.QtWidgets import *
except ImportError:
    # needed for py3+qt4
    # Ref:
    # http://pyqt.sourceforge.net/Docs/PyQt4/incompatible_apis.html
    # http://stackoverflow.com/questions/21217399/pyqt4-qtcore-qvariant-object-instead-of-a-string
    if sys.version_info.major >= 3:
        import sip

        sip.setapi('QVariant', 2)
    from PyQt4.QtGui import *
    from PyQt4.QtCore import *

from combobox import ComboBox
from libs.constants import *
from libs.utils import *
from libs.settings import Settings
from libs.shape import Shape, DEFAULT_LINE_COLOR, DEFAULT_FILL_COLOR
from libs.stringBundle import StringBundle
from libs.canvas import Canvas
from libs.zoomWidget import ZoomWidget
from libs.autoDialog import AutoDialog
from libs.labelDialog import LabelDialog
from libs.colorDialog import ColorDialog
qq_25193841's avatar
qq_25193841 已提交
64
from libs.labelFile import LabelFile, LabelFileError
qq_25193841's avatar
qq_25193841 已提交
65 66 67 68 69 70 71 72
from libs.toolBar import ToolBar
from libs.ustr import ustr
from libs.hashableQListWidgetItem import HashableQListWidgetItem

__appname__ = 'PPOCRLabel'


class WindowMixin(object):
qq_25193841's avatar
qq_25193841 已提交
73

qq_25193841's avatar
qq_25193841 已提交
74 75 76 77 78 79
    def menu(self, title, actions=None):
        menu = self.menuBar().addMenu(title)
        if actions:
            addActions(menu, actions)
        return menu

qq_25193841's avatar
qq_25193841 已提交
80
    def toolbar(self, title, actions=None):  
qq_25193841's avatar
qq_25193841 已提交
81 82 83 84 85 86 87 88 89 90 91 92 93
        toolbar = ToolBar(title)
        toolbar.setObjectName(u'%sToolBar' % title)
        # toolbar.setOrientation(Qt.Vertical)
        toolbar.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
        if actions:
            addActions(toolbar, actions)
        self.addToolBar(Qt.LeftToolBarArea, toolbar)
        return toolbar


class MainWindow(QMainWindow, WindowMixin):
    FIT_WINDOW, FIT_WIDTH, MANUAL_ZOOM = list(range(3))

qq_25193841's avatar
qq_25193841 已提交
94
    def __init__(self, lang="ch", defaultFilename=None, defaultPrefdefClassFile=None, defaultSaveDir=None):
qq_25193841's avatar
qq_25193841 已提交
95 96 97 98 99
        super(MainWindow, self).__init__()
        self.setWindowTitle(__appname__)

        # Load setting in the main thread
        self.settings = Settings()
qq_25193841's avatar
qq_25193841 已提交
100
        self.settings.load()  
qq_25193841's avatar
qq_25193841 已提交
101
        settings = self.settings
qq_25193841's avatar
qq_25193841 已提交
102
        self.lang = lang
qq_25193841's avatar
qq_25193841 已提交
103
        # Load string bundle for i18n
qq_25193841's avatar
qq_25193841 已提交
104 105
        if lang not in ['ch', 'en']:
            lang = 'en'
qq_25193841's avatar
qq_25193841 已提交
106
        self.stringBundle = StringBundle.getBundle(localeStr='zh-CN' if lang=='ch' else 'en') # 'en'
qq_25193841's avatar
qq_25193841 已提交
107 108 109
        getStr = lambda strId: self.stringBundle.getString(strId)

        self.defaultSaveDir = defaultSaveDir
qq_25193841's avatar
qq_25193841 已提交
110
        self.ocr = PaddleOCR(use_pdserving=False, use_angle_cls=True, det=True, cls=True, use_gpu=False, lang=lang)
qq_25193841's avatar
qq_25193841 已提交
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127

        if os.path.exists('./data/paddle.png'):
            result = self.ocr.ocr('./data/paddle.png', cls=True, det=True)

        # For loading all image under a directory
        self.mImgList = []
        self.mImgList5 = []
        self.dirname = None
        self.labelHist = []
        self.lastOpenDir = None
        self.result_dic = []

        self.changeFileFolder = False
        self.haveAutoReced = False
        self.labelFile = None
        self.currIndex = 0

qq_25193841's avatar
qq_25193841 已提交
128

qq_25193841's avatar
qq_25193841 已提交
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159
        # Whether we need to save or not.
        self.dirty = False

        self._noSelectionSlot = False
        self._beginner = True
        self.screencastViewer = self.getAvailableScreencastViewer()
        self.screencast = "https://github.com/PaddlePaddle/PaddleOCR"

        # Load predefined classes to the list
        self.loadPredefinedClasses(defaultPrefdefClassFile)

        # Main widgets and related state.
        self.labelDialog = LabelDialog(parent=self, listItem=self.labelHist)
        self.autoDialog = AutoDialog(parent=self)

        self.itemsToShapes = {}
        self.shapesToItems = {}
        self.itemsToShapesbox = {}
        self.shapesToItemsbox = {}
        self.prevLabelText = getStr('tempLabel')
        self.model = 'paddle'
        self.PPreader = None
        self.autoSaveNum = 10

        ################# file list  ###############
        self.fileListWidget = QListWidget()
        self.fileListWidget.itemClicked.connect(self.fileitemDoubleClicked)
        self.fileListWidget.setIconSize(QSize(25, 25))
        filelistLayout = QVBoxLayout()
        filelistLayout.setContentsMargins(0, 0, 0, 0)
        filelistLayout.addWidget(self.fileListWidget)
qq_25193841's avatar
qq_25193841 已提交
160
        
qq_25193841's avatar
qq_25193841 已提交
161 162 163 164
        self.AutoRecognition = QToolButton()
        self.AutoRecognition.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
        self.AutoRecognition.setIcon(newIcon('Auto'))
        # self.AutoRecognition.setIconSize(QSize(100,20))
qq_25193841's avatar
qq_25193841 已提交
165
        # self.AutoRecognition.setFixedSize(QSize(80,30))
qq_25193841's avatar
qq_25193841 已提交
166 167 168 169 170 171 172 173 174 175 176 177 178 179
        # self.AutoRecognition.setStyleSheet('text-align:center;')#border:none;font-size : 12pt;
        autoRecLayout = QHBoxLayout()
        autoRecLayout.setContentsMargins(0, 0, 0, 0)
        autoRecLayout.addWidget(self.AutoRecognition)
        autoRecContainer = QWidget()
        autoRecContainer.setLayout(autoRecLayout)
        filelistLayout.addWidget(autoRecContainer)

        fileListContainer = QWidget()
        fileListContainer.setLayout(filelistLayout)
        self.filedock = QDockWidget(getStr('fileList'), self)
        self.filedock.setObjectName(getStr('files'))
        self.filedock.setWidget(fileListContainer)
        self.addDockWidget(Qt.LeftDockWidgetArea, self.filedock)
qq_25193841's avatar
qq_25193841 已提交
180
        
qq_25193841's avatar
qq_25193841 已提交
181 182 183 184 185 186 187 188 189 190 191
        ######## Right area ##########
        listLayout = QVBoxLayout()
        listLayout.setContentsMargins(0, 0, 0, 0)

        # Create a widget for edit and diffc button
        self.diffcButton = QCheckBox(getStr('useDifficult'))
        self.diffcButton.setChecked(False)
        self.diffcButton.stateChanged.connect(self.btnstate)
        self.editButton = QToolButton()
        self.reRecogButton = QToolButton()
        self.reRecogButton.setIcon(newIcon('reRec', 30))
qq_25193841's avatar
qq_25193841 已提交
192
        # self.reRecogButton.setFixedSize(QSize(80,30))
qq_25193841's avatar
qq_25193841 已提交
193 194 195 196
        self.reRecogButton.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)

        self.newButton = QToolButton()
        self.newButton.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
qq_25193841's avatar
qq_25193841 已提交
197
        # self.newButton.setFixedSize(QSize(80, 30))
qq_25193841's avatar
qq_25193841 已提交
198 199
        self.SaveButton = QToolButton()
        self.SaveButton.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
qq_25193841's avatar
qq_25193841 已提交
200
        # self.SaveButton.setFixedSize(QSize(60, 30))
qq_25193841's avatar
qq_25193841 已提交
201 202
        self.DelButton = QToolButton()
        self.DelButton.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
qq_25193841's avatar
qq_25193841 已提交
203
        # self.DelButton.setFixedSize(QSize(80, 30))
qq_25193841's avatar
qq_25193841 已提交
204

qq_25193841's avatar
qq_25193841 已提交
205

qq_25193841's avatar
qq_25193841 已提交
206 207 208 209 210 211 212
        lefttoptoolbox = QHBoxLayout()
        lefttoptoolbox.addWidget(self.newButton)
        lefttoptoolbox.addWidget(self.reRecogButton)
        lefttoptoolboxcontainer = QWidget()
        lefttoptoolboxcontainer.setLayout(lefttoptoolbox)
        listLayout.addWidget(lefttoptoolboxcontainer)

qq_25193841's avatar
qq_25193841 已提交
213

qq_25193841's avatar
qq_25193841 已提交
214 215 216 217 218 219 220 221 222 223
        ################## label list ####################
        # Create and add a widget for showing current label items
        self.labelList = QListWidget()
        labelListContainer = QWidget()
        labelListContainer.setLayout(listLayout)
        self.labelList.itemActivated.connect(self.labelSelectionChanged)
        self.labelList.itemSelectionChanged.connect(self.labelSelectionChanged)
        self.labelList.itemDoubleClicked.connect(self.editLabel)
        # Connect to itemChanged to detect checkbox changes.
        self.labelList.itemChanged.connect(self.labelItemChanged)
qq_25193841's avatar
qq_25193841 已提交
224
        self.labelListDock = QDockWidget(getStr('recognitionResult'),self)
qq_25193841's avatar
qq_25193841 已提交
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
        self.labelListDock.setWidget(self.labelList)
        self.labelListDock.setFeatures(QDockWidget.NoDockWidgetFeatures)
        listLayout.addWidget(self.labelListDock)

        ################## detection box ####################
        self.BoxList = QListWidget()

        self.BoxList.itemActivated.connect(self.boxSelectionChanged)
        self.BoxList.itemSelectionChanged.connect(self.boxSelectionChanged)
        self.BoxList.itemDoubleClicked.connect(self.editBox)
        # Connect to itemChanged to detect checkbox changes.
        self.BoxList.itemChanged.connect(self.boxItemChanged)
        self.BoxListDock = QDockWidget(getStr('detectionBoxposition'), self)
        self.BoxListDock.setWidget(self.BoxList)
        self.BoxListDock.setFeatures(QDockWidget.NoDockWidgetFeatures)
        listLayout.addWidget(self.BoxListDock)

        ############ lower right area ############
        leftbtmtoolbox = QHBoxLayout()
        leftbtmtoolbox.addWidget(self.SaveButton)
        leftbtmtoolbox.addWidget(self.DelButton)
        leftbtmtoolboxcontainer = QWidget()
        leftbtmtoolboxcontainer.setLayout(leftbtmtoolbox)
        listLayout.addWidget(leftbtmtoolboxcontainer)

        self.dock = QDockWidget(getStr('boxLabelText'), self)
        self.dock.setObjectName(getStr('labels'))
        self.dock.setWidget(labelListContainer)

qq_25193841's avatar
qq_25193841 已提交
254

qq_25193841's avatar
qq_25193841 已提交
255 256 257 258 259 260 261
        ########## zoom bar #########
        self.imgsplider = QSlider(Qt.Horizontal)
        self.imgsplider.valueChanged.connect(self.CanvasSizeChange)
        self.imgsplider.setMinimum(-150)
        self.imgsplider.setMaximum(150)
        self.imgsplider.setSingleStep(1)
        self.imgsplider.setTickPosition(QSlider.TicksBelow)
qq_25193841's avatar
qq_25193841 已提交
262
        self.imgsplider.setTickInterval(1) 
qq_25193841's avatar
qq_25193841 已提交
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
        op = QGraphicsOpacityEffect()
        op.setOpacity(0.2)
        self.imgsplider.setGraphicsEffect(op)
        # self.imgsplider.setAttribute(Qt.WA_TranslucentBackground)
        self.imgsplider.setStyleSheet("background-color:transparent")
        self.imgsliderDock = QDockWidget(getStr('ImageResize'), self)
        self.imgsliderDock.setObjectName(getStr('IR'))
        self.imgsliderDock.setWidget(self.imgsplider)
        self.imgsliderDock.setFeatures(QDockWidget.DockWidgetFloatable)
        # op = QGraphicsOpacityEffect()
        # op.setOpacity(0.2)
        # self.imgsliderDock.setGraphicsEffect(op)
        self.imgsliderDock.setAttribute(Qt.WA_TranslucentBackground)
        self.addDockWidget(Qt.RightDockWidgetArea, self.imgsliderDock)

        self.zoomWidget = ZoomWidget()
        self.colorDialog = ColorDialog(parent=self)
        self.zoomWidgetValue = self.zoomWidget.value()
qq_25193841's avatar
qq_25193841 已提交
281
        
qq_25193841's avatar
qq_25193841 已提交
282 283 284 285 286 287 288 289
        ########## thumbnail #########
        hlayout = QHBoxLayout()
        m = (0, 0, 0, 0)
        hlayout.setSpacing(0)
        hlayout.setContentsMargins(*m)
        self.preButton = QToolButton()
        # self.preButton.setFixedHeight(100)
        # self.preButton.setText(getStr("prevImg"))
qq_25193841's avatar
qq_25193841 已提交
290
        self.preButton.setIcon(newIcon("prev",40))
qq_25193841's avatar
qq_25193841 已提交
291 292 293 294 295 296 297 298 299 300 301 302 303
        self.preButton.setIconSize(QSize(40, 100))
        self.preButton.clicked.connect(self.openPrevImg)
        # self.preButton.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
        self.preButton.setStyleSheet('border: none;')
        self.iconlist = QListWidget()
        self.iconlist.setViewMode(QListView.IconMode)
        self.iconlist.setFlow(QListView.TopToBottom)
        self.iconlist.setSpacing(10)
        self.iconlist.setIconSize(QSize(50, 50))
        self.iconlist.setMovement(False)
        self.iconlist.setResizeMode(QListView.Adjust)
        # self.iconlist.itemDoubleClicked.connect(self.iconitemDoubleClicked)
        self.iconlist.itemClicked.connect(self.iconitemDoubleClicked)
qq_25193841's avatar
qq_25193841 已提交
304
        self.iconlist.setStyleSheet("background-color:transparent; border: none;")
qq_25193841's avatar
qq_25193841 已提交
305 306 307 308 309 310 311 312 313 314
        self.iconlist.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        # self.iconlist.setStyleSheet('border: none;')
        self.nextButton = QToolButton()
        # self.nextButton.setFixedHeight(100)
        # self.nextButton.setText(getStr("nextImg"))
        self.nextButton.setIcon(newIcon("next", 40))
        self.nextButton.setIconSize(QSize(40, 100))
        self.nextButton.setStyleSheet('border: none;')
        self.nextButton.clicked.connect(self.openNextImg)
        # self.nextButton.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
qq_25193841's avatar
qq_25193841 已提交
315
        
qq_25193841's avatar
qq_25193841 已提交
316 317 318 319 320 321 322 323 324 325 326 327 328
        hlayout.addWidget(self.preButton)
        hlayout.addWidget(self.iconlist)
        hlayout.addWidget(self.nextButton)

        # self.setLayout(hlayout)

        iconListContainer = QWidget()
        iconListContainer.setLayout(hlayout)
        iconListContainer.setFixedHeight(100)
        # iconListContainer.setFixedWidth(530)
        # op = QGraphicsOpacityEffect()
        # op.setOpacity(0.5)
        # iconListContainer.setGraphicsEffect(op)
qq_25193841's avatar
qq_25193841 已提交
329
        
qq_25193841's avatar
qq_25193841 已提交
330 331 332
        ########### Canvas ###########
        self.canvas = Canvas(parent=self)
        self.canvas.zoomRequest.connect(self.zoomRequest)
qq_25193841's avatar
qq_25193841 已提交
333
        self.canvas.setDrawingShapeToSquare(settings.get(SETTING_DRAW_SQUARE, False))
qq_25193841's avatar
qq_25193841 已提交
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353

        scroll = QScrollArea()
        scroll.setWidget(self.canvas)
        scroll.setWidgetResizable(True)
        self.scrollBars = {
            Qt.Vertical: scroll.verticalScrollBar(),
            Qt.Horizontal: scroll.horizontalScrollBar()
        }
        self.scrollArea = scroll
        self.canvas.scrollRequest.connect(self.scrollRequest)

        self.canvas.newShape.connect(self.newShape)
        self.canvas.shapeMoved.connect(self.updateBoxlist)  # self.setDirty
        self.canvas.selectionChanged.connect(self.shapeSelectionChanged)
        self.canvas.drawingPolygon.connect(self.toggleDrawingSensitive)

        centerLayout = QVBoxLayout()
        centerLayout.setContentsMargins(0, 0, 0, 0)
        centerLayout.addWidget(scroll)
        #centerLayout.addWidget(self.icondock)
qq_25193841's avatar
qq_25193841 已提交
354
        centerLayout.addWidget(iconListContainer,0,Qt.AlignCenter)
qq_25193841's avatar
qq_25193841 已提交
355 356 357 358 359 360 361 362 363 364 365
        centercontainer = QWidget()
        centercontainer.setLayout(centerLayout)

        # self.scrolldock = QDockWidget('WorkSpace',self)
        # self.scrolldock.setObjectName('WorkSpace')
        # self.scrolldock.setWidget(centercontainer)
        # self.scrolldock.setFeatures(QDockWidget.NoDockWidgetFeatures)
        # orititle = self.scrolldock.titleBarWidget()
        # tmpwidget = QWidget()
        # self.scrolldock.setTitleBarWidget(tmpwidget)
        # del orititle
qq_25193841's avatar
qq_25193841 已提交
366
        self.setCentralWidget(centercontainer) #self.scrolldock
qq_25193841's avatar
qq_25193841 已提交
367 368
        self.addDockWidget(Qt.RightDockWidgetArea, self.dock)

qq_25193841's avatar
qq_25193841 已提交
369

qq_25193841's avatar
qq_25193841 已提交
370
        # self.filedock.setFeatures(QDockWidget.DockWidgetFloatable)
qq_25193841's avatar
qq_25193841 已提交
371
        self.filedock.setFeatures(self.filedock.features() ^ QDockWidget.DockWidgetFloatable)
qq_25193841's avatar
qq_25193841 已提交
372 373 374 375 376 377 378 379

        self.dockFeatures = QDockWidget.DockWidgetClosable | QDockWidget.DockWidgetFloatable
        self.dock.setFeatures(self.dock.features() ^ self.dockFeatures)

        self.filedock.setFeatures(QDockWidget.NoDockWidgetFeatures)

        ###### Actions #######
        action = partial(newAction, self)
qq_25193841's avatar
qq_25193841 已提交
380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
        quit = action(getStr('quit'), self.close,
                      'Ctrl+Q', 'quit', getStr('quitApp'))

        open = action(getStr('openFile'), self.openFile,
                      'Ctrl+O', 'open', getStr('openFileDetail'))

        opendir = action(getStr('openDir'), self.openDirDialog,
                         'Ctrl+u', 'open', getStr('openDir'))

        openNextImg = action(getStr('nextImg'), self.openNextImg,
                             'd', 'next', getStr('nextImgDetail'))

        openPrevImg = action(getStr('prevImg'), self.openPrevImg,
                             'a', 'prev', getStr('prevImgDetail'))

        verify = action(getStr('verifyImg'), self.verifyImg,
                        'space', 'verify', getStr('verifyImgDetail'))

        save = action(getStr('save'), self.saveFile,
                      'Ctrl+S', 'save', getStr('saveDetail'), enabled=False)

        alcm = action(getStr('choosemodel'), self.autolcm,
                                        'Ctrl+M', 'next', getStr('tipchoosemodel'))

        deleteImg = action(getStr('deleteImg'), self.deleteImg, 'Ctrl+D', 'close', getStr('deleteImgDetail'),
                           enabled=True)

        resetAll = action(getStr('resetAll'), self.resetAll, None, 'resetall', getStr('resetAllDetail'))

        color1 = action(getStr('boxLineColor'), self.chooseColor1,
                        'Ctrl+L', 'color_line', getStr('boxLineColorDetail'))

        createMode = action(getStr('crtBox'), self.setCreateMode,
                            'w', 'new', getStr('crtBoxDetail'), enabled=False)
        editMode = action('&Edit\nRectBox', self.setEditMode,
                          'Ctrl+J', 'edit', u'Move and edit Boxs', enabled=False)

        create = action(getStr('crtBox'), self.createShape,
                        'w', 'new', getStr('crtBoxDetail'), enabled=False)

        delete = action(getStr('delBox'), self.deleteSelectedShape,
                        'Delete', 'delete', getStr('delBoxDetail'), enabled=False)
        copy = action(getStr('dupBox'), self.copySelectedShape,
                      'Ctrl+D', 'copy', getStr('dupBoxDetail'),
                      enabled=False)

        hideAll = action(getStr('hideBox'), partial(self.togglePolygons, False),
                         'Ctrl+H', 'hide', getStr('hideAllBoxDetail'),
                         enabled=False)
        showAll = action(getStr('showBox'), partial(self.togglePolygons, True),
                         'Ctrl+A', 'hide', getStr('showAllBoxDetail'),
                         enabled=False)

        help = action(getStr('tutorial'), self.showTutorialDialog, None, 'help', getStr('tutorialDetail'))
        showInfo = action(getStr('info'), self.showInfoDialog, None, 'help', getStr('info'))
        showSteps = action(getStr('steps'), self.showStepsDialog, None, 'help', getStr('steps'))
qq_25193841's avatar
qq_25193841 已提交
436 437 438 439 440 441 442 443 444

        zoom = QWidgetAction(self)
        zoom.setDefaultWidget(self.zoomWidget)
        self.zoomWidget.setWhatsThis(
            u"Zoom in or out of the image. Also accessible with"
            " %s and %s from the canvas." % (fmtShortcut("Ctrl+[-+]"),
                                             fmtShortcut("Ctrl+Wheel")))
        self.zoomWidget.setEnabled(False)

qq_25193841's avatar
qq_25193841 已提交
445 446 447 448 449 450 451 452 453 454 455 456
        zoomIn = action(getStr('zoomin'), partial(self.addZoom, 10),
                        'Ctrl++', 'zoom-in', getStr('zoominDetail'), enabled=False)
        zoomOut = action(getStr('zoomout'), partial(self.addZoom, -10),
                         'Ctrl+-', 'zoom-out', getStr('zoomoutDetail'), enabled=False)
        zoomOrg = action(getStr('originalsize'), partial(self.setZoom, 100),
                         'Ctrl+=', 'zoom', getStr('originalsizeDetail'), enabled=False)
        fitWindow = action(getStr('fitWin'), self.setFitWindow,
                           'Ctrl+F', 'fit-window', getStr('fitWinDetail'),
                           checkable=True, enabled=False)
        fitWidth = action(getStr('fitWidth'), self.setFitWidth,
                          'Ctrl+Shift+F', 'fit-width', getStr('fitWidthDetail'),
                          checkable=True, enabled=False)
qq_25193841's avatar
qq_25193841 已提交
457
        # Group zoom controls into a list for easier toggling.
qq_25193841's avatar
qq_25193841 已提交
458 459
        zoomActions = (self.zoomWidget, zoomIn, zoomOut,
                       zoomOrg, fitWindow, fitWidth)
qq_25193841's avatar
qq_25193841 已提交
460 461 462 463 464 465 466 467
        self.zoomMode = self.MANUAL_ZOOM
        self.scalers = {
            self.FIT_WINDOW: self.scaleFitWindow,
            self.FIT_WIDTH: self.scaleFitWidth,
            # Set to one to scale to 100% when loading files.
            self.MANUAL_ZOOM: lambda: 1,
        }

qq_25193841's avatar
qq_25193841 已提交
468 469 470
        edit = action(getStr('editLabel'), self.editLabel,
                      'Ctrl+E', 'edit', getStr('editLabelDetail'),
                      enabled=False)
qq_25193841's avatar
qq_25193841 已提交
471 472

        ######## New actions #######
qq_25193841's avatar
qq_25193841 已提交
473 474 475 476 477 478 479 480 481 482 483
        AutoRec = action(getStr('autoRecognition'), self.autoRecognition,
                      'Ctrl+Shift+A', 'Auto', getStr('autoRecognition'), enabled=False)

        reRec = action(getStr('reRecognition'), self.reRecognition, 
                      'Ctrl+Shift+R', 'reRec', getStr('reRecognition'), enabled=False)

        createpoly = action(getStr('creatPolygon'), self.createPolygon,
                            'p', 'new', 'Creat Polygon', enabled=True)

        saveRec = action(getStr('saveRec'), self.saveRecResult,
                            '', 'saveRec', getStr('saveRec'), enabled=False)
qq_25193841's avatar
qq_25193841 已提交
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513

        self.editButton.setDefaultAction(edit)
        self.newButton.setDefaultAction(create)
        self.DelButton.setDefaultAction(deleteImg)
        self.SaveButton.setDefaultAction(save)
        self.AutoRecognition.setDefaultAction(AutoRec)
        self.reRecogButton.setDefaultAction(reRec)
        # self.preButton.setDefaultAction(openPrevImg)
        # self.nextButton.setDefaultAction(openNextImg)

        ############# Zoom layout ##############
        zoomLayout = QHBoxLayout()
        zoomLayout.addStretch()
        self.zoominButton = QToolButton()
        self.zoominButton.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
        self.zoominButton.setDefaultAction(zoomIn)
        self.zoomoutButton = QToolButton()
        self.zoomoutButton.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
        self.zoomoutButton.setDefaultAction(zoomOut)
        self.zoomorgButton = QToolButton()
        self.zoomorgButton.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
        self.zoomorgButton.setDefaultAction(zoomOrg)
        zoomLayout.addWidget(self.zoominButton)
        zoomLayout.addWidget(self.zoomorgButton)
        zoomLayout.addWidget(self.zoomoutButton)

        zoomContainer = QWidget()
        zoomContainer.setLayout(zoomLayout)
        zoomContainer.setGeometry(0, 0, 30, 150)

qq_25193841's avatar
qq_25193841 已提交
514 515 516 517 518 519
        shapeLineColor = action(getStr('shapeLineColor'), self.chshapeLineColor,
                                icon='color_line', tip=getStr('shapeLineColorDetail'),
                                enabled=False)
        shapeFillColor = action(getStr('shapeFillColor'), self.chshapeFillColor,
                                icon='color', tip=getStr('shapeFillColorDetail'),
                                enabled=False)
qq_25193841's avatar
qq_25193841 已提交
520 521 522 523 524 525 526 527 528 529

        # labels = self.dock.toggleViewAction()
        # labels.setText(getStr('showHide'))
        # labels.setShortcut('Ctrl+Shift+L')

        # Label list context menu.
        labelMenu = QMenu()
        addActions(labelMenu, (edit, delete))

        self.labelList.setContextMenuPolicy(Qt.CustomContextMenu)
qq_25193841's avatar
qq_25193841 已提交
530 531
        self.labelList.customContextMenuRequested.connect(
            self.popLabelListMenu)
qq_25193841's avatar
qq_25193841 已提交
532 533 534 535 536

        # Draw squares/rectangles
        self.drawSquaresOption = QAction(getStr('drawSquares'), self)
        self.drawSquaresOption.setShortcut('Ctrl+Shift+R')
        self.drawSquaresOption.setCheckable(True)
qq_25193841's avatar
qq_25193841 已提交
537
        self.drawSquaresOption.setChecked(settings.get(SETTING_DRAW_SQUARE, False))
qq_25193841's avatar
qq_25193841 已提交
538 539 540
        self.drawSquaresOption.triggered.connect(self.toogleDrawSquare)

        # Store actions for further handling.
qq_25193841's avatar
qq_25193841 已提交
541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559
        self.actions = struct(save=save,  open=open,  resetAll=resetAll, deleteImg=deleteImg,
                              lineColor=color1, create=create, delete=delete, edit=edit, copy=copy,
                              saveRec=saveRec,
                              createMode=createMode, editMode=editMode,
                              shapeLineColor=shapeLineColor, shapeFillColor=shapeFillColor,
                              zoom=zoom, zoomIn=zoomIn, zoomOut=zoomOut, zoomOrg=zoomOrg,
                              fitWindow=fitWindow, fitWidth=fitWidth,
                              zoomActions=zoomActions,
                              fileMenuActions=(
                                  open, opendir, save,  resetAll, quit),
                              beginner=(), advanced=(),
                              editMenu=(createpoly, edit, copy, delete,
                                        None, color1, self.drawSquaresOption),
                              beginnerContext=(create, edit, copy, delete),
                              advancedContext=(createMode, editMode, edit, copy,
                                               delete, shapeLineColor, shapeFillColor),
                              onLoadActive=(
                                   create, createMode, editMode),
                              onShapesPresent=(hideAll, showAll))
qq_25193841's avatar
qq_25193841 已提交
560 561 562

        # menus
        self.menus = struct(
qq_25193841's avatar
qq_25193841 已提交
563 564 565
            file=self.menu('&'+getStr('mfile')),
            edit=self.menu('&'+getStr('medit')),
            view=self.menu('&'+getStr('mview')),
qq_25193841's avatar
qq_25193841 已提交
566
            autolabel=self.menu('&PaddleOCR'),
qq_25193841's avatar
qq_25193841 已提交
567
            help=self.menu('&'+getStr('mhelp')),
qq_25193841's avatar
qq_25193841 已提交
568 569 570
            recentFiles=QMenu('Open &Recent'),
            labelList=labelMenu)

qq_25193841's avatar
qq_25193841 已提交
571

qq_25193841's avatar
qq_25193841 已提交
572 573 574 575
        # Sync single class mode from PR#106
        self.singleClassMode = QAction(getStr('singleClsMode'), self)
        self.singleClassMode.setShortcut("Ctrl+Shift+S")
        self.singleClassMode.setCheckable(True)
qq_25193841's avatar
qq_25193841 已提交
576
        self.singleClassMode.setChecked(settings.get(SETTING_SINGLE_CLASS, False))
qq_25193841's avatar
qq_25193841 已提交
577 578 579 580 581
        self.lastLabel = None
        # Add option to enable/disable labels being displayed at the top of bounding boxes
        self.displayLabelOption = QAction(getStr('displayLabel'), self)
        self.displayLabelOption.setShortcut("Ctrl+Shift+P")
        self.displayLabelOption.setCheckable(True)
qq_25193841's avatar
qq_25193841 已提交
582
        self.displayLabelOption.setChecked(settings.get(SETTING_PAINT_LABEL, False))
qq_25193841's avatar
qq_25193841 已提交
583 584 585
        self.displayLabelOption.triggered.connect(self.togglePaintLabelsOption)

        addActions(self.menus.file,
qq_25193841's avatar
qq_25193841 已提交
586
                   (opendir, None, save,  resetAll, deleteImg, quit))
qq_25193841's avatar
qq_25193841 已提交
587 588

        addActions(self.menus.help, (showSteps, showInfo))
qq_25193841's avatar
qq_25193841 已提交
589 590 591 592 593 594 595 596
        addActions(self.menus.view, (
            self.displayLabelOption, # labels,
             None,
            hideAll, showAll, None,
            zoomIn, zoomOut, zoomOrg, None,
            fitWindow, fitWidth))

        addActions(self.menus.autolabel, (alcm, saveRec, None, help)) #
qq_25193841's avatar
qq_25193841 已提交
597 598 599 600 601

        self.menus.file.aboutToShow.connect(self.updateFileMenu)

        # Custom context menu for the canvas widget:
        addActions(self.canvas.menus[0], self.actions.beginnerContext)
qq_25193841's avatar
qq_25193841 已提交
602 603 604
        addActions(self.canvas.menus[1], (
            action('&Copy here', self.copyShape),
            action('&Move here', self.moveShape)))
qq_25193841's avatar
qq_25193841 已提交
605 606 607

        # self.tools = self.toolbar('Tools')

qq_25193841's avatar
qq_25193841 已提交
608 609 610
        self.actions.beginner = (
            open, opendir, openNextImg, openPrevImg, verify, save, None, create, copy, delete, None,
            zoomIn, zoom, zoomOut, fitWindow, fitWidth)
qq_25193841's avatar
qq_25193841 已提交
611

qq_25193841's avatar
qq_25193841 已提交
612 613 614 615
        self.actions.advanced = (
            open, opendir, openNextImg, openPrevImg, save, None,
            createMode, editMode, None,
            hideAll, showAll)
qq_25193841's avatar
qq_25193841 已提交
616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638

        self.statusBar().showMessage('%s started.' % __appname__)
        self.statusBar().show()

        # Application state.
        self.image = QImage()
        self.filePath = ustr(defaultFilename)
        self.lastOpenDir = None
        self.recentFiles = []
        self.maxRecent = 7
        self.lineColor = None
        self.fillColor = None
        self.zoom_level = 100
        self.fit_window = False
        # Add Chris
        self.difficult = False

        ## Fix the compatible issue for qt4 and qt5. Convert the QStringList to python list
        if settings.get(SETTING_RECENT_FILES):
            if have_qstring():
                recentFileQStringList = settings.get(SETTING_RECENT_FILES)
                self.recentFiles = [ustr(i) for i in recentFileQStringList]
            else:
qq_25193841's avatar
qq_25193841 已提交
639
                self.recentFiles = recentFileQStringList = settings.get(SETTING_RECENT_FILES)
qq_25193841's avatar
qq_25193841 已提交
640 641 642 643 644 645 646

        size = settings.get(SETTING_WIN_SIZE, QSize(1200, 800))

        position = QPoint(0, 0)
        saved_position = settings.get(SETTING_WIN_POSE, position)
        # Fix the multiple monitors issue
        for i in range(QApplication.desktop().screenCount()):
qq_25193841's avatar
qq_25193841 已提交
647
            if QApplication.desktop().availableGeometry(i).contains(saved_position):
qq_25193841's avatar
qq_25193841 已提交
648 649 650 651 652 653 654 655
                position = saved_position
                break
        self.resize(size)
        self.move(position)
        saveDir = ustr(settings.get(SETTING_SAVE_DIR, None))
        self.lastOpenDir = ustr(settings.get(SETTING_LAST_OPEN_DIR, None))

        self.restoreState(settings.get(SETTING_WIN_STATE, QByteArray()))
qq_25193841's avatar
qq_25193841 已提交
656 657
        Shape.line_color = self.lineColor = QColor(settings.get(SETTING_LINE_COLOR, DEFAULT_LINE_COLOR))
        Shape.fill_color = self.fillColor = QColor(settings.get(SETTING_FILL_COLOR, DEFAULT_FILL_COLOR))
qq_25193841's avatar
qq_25193841 已提交
658 659 660 661
        self.canvas.setDrawingColor(self.lineColor)
        # Add chris
        Shape.difficult = self.difficult

qq_25193841's avatar
qq_25193841 已提交
662

qq_25193841's avatar
qq_25193841 已提交
663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694
        # ADD:
        # Populate the File menu dynamically.
        self.updateFileMenu()

        # Since loading the file may take some time, make sure it runs in the background.
        if self.filePath and os.path.isdir(self.filePath):
            self.queueEvent(partial(self.importDirImages, self.filePath or ""))
        elif self.filePath:
            self.queueEvent(partial(self.loadFile, self.filePath or ""))

        # Callbacks:
        self.zoomWidget.valueChanged.connect(self.paintCanvas)

        self.populateModeActions()

        # Display cursor coordinates at the right of status bar
        self.labelCoordinates = QLabel('')
        self.statusBar().addPermanentWidget(self.labelCoordinates)

        # Open Dir if deafult file
        if self.filePath and os.path.isdir(self.filePath):
            self.openDirDialog(dirpath=self.filePath, silent=True)

    def keyReleaseEvent(self, event):
        if event.key() == Qt.Key_Control:
            self.canvas.setDrawingShapeToSquare(False)

    def keyPressEvent(self, event):
        if event.key() == Qt.Key_Control:
            # Draw rectangle if Ctrl is pressed
            self.canvas.setDrawingShapeToSquare(True)

qq_25193841's avatar
qq_25193841 已提交
695

qq_25193841's avatar
qq_25193841 已提交
696 697 698
    def noShapes(self):
        return not self.itemsToShapes

qq_25193841's avatar
qq_25193841 已提交
699

qq_25193841's avatar
qq_25193841 已提交
700 701 702 703
    def populateModeActions(self):
        self.canvas.menus[0].clear()
        addActions(self.canvas.menus[0], self.actions.beginnerContext)
        self.menus.edit.clear()
qq_25193841's avatar
qq_25193841 已提交
704
        actions = (self.actions.create,)  # if self.beginner() else (self.actions.createMode, self.actions.editMode)
qq_25193841's avatar
qq_25193841 已提交
705 706
        addActions(self.menus.edit, actions + self.actions.editMenu)

qq_25193841's avatar
qq_25193841 已提交
707

qq_25193841's avatar
qq_25193841 已提交
708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785
    def setDirty(self):
        self.dirty = True
        self.actions.save.setEnabled(True)

    def setClean(self):
        self.dirty = False
        self.actions.save.setEnabled(False)
        self.actions.create.setEnabled(True)

    def toggleActions(self, value=True):
        """Enable/Disable widgets which depend on an opened image."""
        for z in self.actions.zoomActions:
            z.setEnabled(value)
        for action in self.actions.onLoadActive:
            action.setEnabled(value)

    def queueEvent(self, function):
        QTimer.singleShot(0, function)

    def status(self, message, delay=5000):
        self.statusBar().showMessage(message, delay)

    def resetState(self):
        self.itemsToShapes.clear()
        self.shapesToItems.clear()
        self.itemsToShapesbox.clear()  # ADD
        self.shapesToItemsbox.clear()
        self.labelList.clear()
        self.BoxList.clear()
        self.filePath = None
        self.imageData = None
        self.labelFile = None
        self.canvas.resetState()
        self.labelCoordinates.clear()
        # self.comboBox.cb.clear()
        self.result_dic = []

    def currentItem(self):
        items = self.labelList.selectedItems()
        if items:
            return items[0]
        return None

    def currentBox(self):
        items = self.BoxList.selectedItems()
        if items:
            return items[0]
        return None

    def addRecentFile(self, filePath):
        if filePath in self.recentFiles:
            self.recentFiles.remove(filePath)
        elif len(self.recentFiles) >= self.maxRecent:
            self.recentFiles.pop()
        self.recentFiles.insert(0, filePath)

    def beginner(self):
        return self._beginner

    def advanced(self):
        return not self.beginner()

    def getAvailableScreencastViewer(self):
        osName = platform.system()

        if osName == 'Windows':
            return ['C:\\Program Files\\Internet Explorer\\iexplore.exe']
        elif osName == 'Linux':
            return ['xdg-open']
        elif osName == 'Darwin':
            return ['open']

    ## Callbacks ##
    def showTutorialDialog(self):
        subprocess.Popen(self.screencastViewer + [self.screencast])

    def showInfoDialog(self):
        from libs.__init__ import __version__
qq_25193841's avatar
qq_25193841 已提交
786
        msg = u'Name:{0} \nApp Version:{1} \n{2} '.format(__appname__, __version__, sys.version_info)
qq_25193841's avatar
qq_25193841 已提交
787 788 789
        QMessageBox.information(self, u'Information', msg)

    def showStepsDialog(self):
qq_25193841's avatar
qq_25193841 已提交
790
        msg = stepsInfo(self.lang)
qq_25193841's avatar
qq_25193841 已提交
791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836
        QMessageBox.information(self, u'Information', msg)

    def createShape(self):
        assert self.beginner()
        self.canvas.setEditing(False)
        self.actions.create.setEnabled(False)
        self.canvas.fourpoint = False

    def createPolygon(self):
        assert self.beginner()
        self.canvas.setEditing(False)
        self.canvas.fourpoint = True
        self.actions.create.setEnabled(False)

    def toggleDrawingSensitive(self, drawing=True):
        """In the middle of drawing, toggling between modes should be disabled."""
        self.actions.editMode.setEnabled(not drawing)
        if not drawing and self.beginner():
            # Cancel creation.
            print('Cancel creation.')
            self.canvas.setEditing(True)
            self.canvas.restoreCursor()
            self.actions.create.setEnabled(True)

    def toggleDrawMode(self, edit=True):
        self.canvas.setEditing(edit)
        self.actions.createMode.setEnabled(edit)
        self.actions.editMode.setEnabled(not edit)

    def setCreateMode(self):
        assert self.advanced()
        self.toggleDrawMode(False)

    def setEditMode(self):
        assert self.advanced()
        self.toggleDrawMode(True)
        self.labelSelectionChanged()

    def updateFileMenu(self):
        currFilePath = self.filePath

        def exists(filename):
            return os.path.exists(filename)

        menu = self.menus.recentFiles
        menu.clear()
qq_25193841's avatar
qq_25193841 已提交
837 838
        files = [f for f in self.recentFiles if f !=
                 currFilePath and exists(f)]
qq_25193841's avatar
qq_25193841 已提交
839 840
        for i, f in enumerate(files):
            icon = newIcon('labels')
qq_25193841's avatar
qq_25193841 已提交
841 842
            action = QAction(
                icon, '&%d %s' % (i + 1, QFileInfo(f).fileName()), self)
qq_25193841's avatar
qq_25193841 已提交
843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892
            action.triggered.connect(partial(self.loadRecent, f))
            menu.addAction(action)

    def popLabelListMenu(self, point):
        self.menus.labelList.exec_(self.labelList.mapToGlobal(point))

    def editLabel(self):
        if not self.canvas.editing():
            return
        item = self.currentItem()
        if not item:
            return
        text = self.labelDialog.popUp(item.text())
        if text is not None:
            item.setText(text)
            # item.setBackground(generateColorByText(text))
            self.setDirty()
            self.updateComboBox()

    ######## detection box related functions #######

    def boxItemChanged(self, item):
        shape = self.itemsToShapesbox[item]

        box = ast.literal_eval(item.text())
        # print('shape in labelItemChanged is',shape.points)
        if box != [(p.x(), p.y()) for p in shape.points]:
            # shape.points = box
            shape.points = [QPointF(p[0], p[1]) for p in box]

            # QPointF(x,y)
            # shape.line_color = generateColorByText(shape.label)
            self.setDirty()
        else:  # User probably changed item visibility
            self.canvas.setShapeVisible(shape, item.checkState() == Qt.Checked)

    def editBox(self):  # ADD
        if not self.canvas.editing():
            return
        item = self.currentBox()
        if not item:
            return
        text = self.labelDialog.popUp(item.text())

        imageSize = str(self.image.size())
        width, height = self.image.width(), self.image.height()
        if text:
            try:
                text_list = eval(text)
            except:
qq_25193841's avatar
qq_25193841 已提交
893
                msg_box = QMessageBox(QMessageBox.Warning, 'Warning', 'Please enter the correct format')
qq_25193841's avatar
qq_25193841 已提交
894 895 896
                msg_box.exec_()
                return
            if len(text_list) < 4:
qq_25193841's avatar
qq_25193841 已提交
897
                msg_box = QMessageBox(QMessageBox.Warning, 'Warning', 'Please enter the coordinates of 4 points')
qq_25193841's avatar
qq_25193841 已提交
898 899 900
                msg_box.exec_()
                return
            for box in text_list:
qq_25193841's avatar
qq_25193841 已提交
901 902
                if box[0] > width or box[0] < 0 or box[1] > height or box[1] < 0:
                    msg_box = QMessageBox(QMessageBox.Warning, 'Warning', 'Out of picture size')
qq_25193841's avatar
qq_25193841 已提交
903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920
                    msg_box.exec_()
                    return

            item.setText(text)
            # item.setBackground(generateColorByText(text))
            self.setDirty()
            self.updateComboBox()

    def updateBoxlist(self):
        shape = self.canvas.selectedShape
        item = self.shapesToItemsbox[shape]  # listitem
        text = [(int(p.x()), int(p.y())) for p in shape.points]
        item.setText(str(text))
        self.setDirty()

    def indexTo5Files(self, currIndex):
        if currIndex < 2:
            return self.mImgList[:5]
qq_25193841's avatar
qq_25193841 已提交
921
        elif currIndex > len(self.mImgList)-3:
qq_25193841's avatar
qq_25193841 已提交
922 923
            return self.mImgList[-5:]
        else:
qq_25193841's avatar
qq_25193841 已提交
924 925
            return self.mImgList[currIndex - 2 : currIndex + 3]

qq_25193841's avatar
qq_25193841 已提交
926 927 928

    # Tzutalin 20160906 : Add file list and dock to move faster
    def fileitemDoubleClicked(self, item=None):
qq_25193841's avatar
qq_25193841 已提交
929
        self.currIndex = self.mImgList.index(ustr(os.path.join(os.path.abspath(self.dirname), item.text())))
qq_25193841's avatar
qq_25193841 已提交
930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945
        filename = self.mImgList[self.currIndex]
        if filename:
            self.mImgList5 = self.indexTo5Files(self.currIndex)
            # self.additems5(None)
            self.loadFile(filename)

    def iconitemDoubleClicked(self, item=None):
        self.currIndex = self.mImgList.index(ustr(os.path.join(item.toolTip())))
        filename = self.mImgList[self.currIndex]
        if filename:
            self.mImgList5 = self.indexTo5Files(self.currIndex)
            # self.additems5(None)
            self.loadFile(filename)

    def CanvasSizeChange(self):
        if len(self.mImgList) > 0:
qq_25193841's avatar
qq_25193841 已提交
946
            self.zoomWidget.setValue(self.zoomWidgetValue + self.imgsplider.value())
qq_25193841's avatar
qq_25193841 已提交
947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970

    # Add chris
    def btnstate(self, item=None):
        """ Function to handle difficult examples
        Update on each object """
        if not self.canvas.editing():
            return

        item = self.currentItem()
        if not item:  # If not selected Item, take the first one
            item = self.labelList.item(self.labelList.count() - 1)

        difficult = self.diffcButton.isChecked()

        try:
            shape = self.itemsToShapes[item]
        except:
            pass
        # Checked and Update
        try:
            if difficult != shape.difficult:
                shape.difficult = difficult
                self.setDirty()
            else:  # User probably changed item visibility
qq_25193841's avatar
qq_25193841 已提交
971
                self.canvas.setShapeVisible(shape, item.checkState() == Qt.Checked)
qq_25193841's avatar
qq_25193841 已提交
972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003
        except:
            pass

    # React to canvas signals.
    def shapeSelectionChanged(self, selected=False):
        if self._noSelectionSlot:
            self._noSelectionSlot = False
        else:
            shape = self.canvas.selectedShape
            if shape:
                self.shapesToItems[shape].setSelected(True)
                self.shapesToItemsbox[shape].setSelected(True)  # ADD
            else:
                self.labelList.clearSelection()
        self.actions.delete.setEnabled(selected)
        self.actions.copy.setEnabled(selected)
        self.actions.edit.setEnabled(selected)
        self.actions.shapeLineColor.setEnabled(selected)
        self.actions.shapeFillColor.setEnabled(selected)

    def addLabel(self, shape):
        shape.paintLabel = self.displayLabelOption.isChecked()
        item = HashableQListWidgetItem(shape.label)
        item.setFlags(item.flags() | Qt.ItemIsUserCheckable)
        item.setCheckState(Qt.Checked)
        # item.setBackground(generateColorByText(shape.label))
        self.itemsToShapes[item] = shape
        self.shapesToItems[shape] = item
        self.labelList.addItem(item)
        # print('item in add label is ',[(p.x(), p.y()) for p in shape.points], shape.label)

        # ADD for box
qq_25193841's avatar
qq_25193841 已提交
1004
        item = HashableQListWidgetItem(str([(int(p.x()), int(p.y())) for p in shape.points]))
qq_25193841's avatar
qq_25193841 已提交
1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064
        # item = QListWidgetItem(str([(p.x(), p.y()) for p in shape.points]))
        item.setFlags(item.flags() | Qt.ItemIsUserCheckable)
        item.setCheckState(Qt.Checked)
        # item.setBackground(generateColorByText(shape.label))
        self.itemsToShapesbox[item] = shape
        self.shapesToItemsbox[shape] = item
        self.BoxList.addItem(item)
        for action in self.actions.onShapesPresent:
            action.setEnabled(True)
        self.updateComboBox()

    def remLabel(self, shape):
        if shape is None:
            # print('rm empty label')
            return
        item = self.shapesToItems[shape]
        self.labelList.takeItem(self.labelList.row(item))
        del self.shapesToItems[shape]
        del self.itemsToShapes[item]
        self.updateComboBox()

        # ADD:
        item = self.shapesToItemsbox[shape]
        self.BoxList.takeItem(self.BoxList.row(item))
        del self.shapesToItemsbox[shape]
        del self.itemsToShapesbox[item]
        self.updateComboBox()

    def loadLabels(self, shapes):
        s = []
        for label, points, line_color, fill_color, difficult in shapes:
            shape = Shape(label=label)
            for x, y in points:

                # Ensure the labels are within the bounds of the image. If not, fix them.
                x, y, snapped = self.canvas.snapPointToCanvas(x, y)
                if snapped:
                    self.setDirty()

                shape.addPoint(QPointF(x, y))
            shape.difficult = difficult
            shape.close()
            s.append(shape)

            # if line_color:
            #     shape.line_color = QColor(*line_color)
            # else:
            #     shape.line_color = generateColorByText(label)
            #
            # if fill_color:
            #     shape.fill_color = QColor(*fill_color)
            # else:
            #     shape.fill_color = generateColorByText(label)

            self.addLabel(shape)
        self.updateComboBox()
        self.canvas.loadShapes(s)

    def updateComboBox(self):
        # Get the unique labels and add them to the Combobox.
qq_25193841's avatar
qq_25193841 已提交
1065
        itemsTextList = [str(self.labelList.item(i).text()) for i in range(self.labelList.count())]
qq_25193841's avatar
qq_25193841 已提交
1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081

        uniqueTextList = list(set(itemsTextList))
        # Add a null row for showing all the labels
        uniqueTextList.append("")
        uniqueTextList.sort()

        # self.comboBox.update_items(uniqueTextList)

    def saveLabels(self, annotationFilePath, mode='Auto'):
        annotationFilePath = ustr(annotationFilePath)
        if self.labelFile is None:
            self.labelFile = LabelFile()
            self.labelFile.verified = self.canvas.verified

        def format_shape(s):
            # print('s in saveLabels is ',s)
qq_25193841's avatar
qq_25193841 已提交
1082 1083 1084 1085 1086 1087
            return dict(label=s.label,  # str
                        line_color=s.line_color.getRgb(),
                        fill_color=s.fill_color.getRgb(),
                        points=[(p.x(), p.y()) for p in s.points],  # QPonitF
                       # add chris
                        difficult=s.difficult)  # bool
qq_25193841's avatar
qq_25193841 已提交
1088 1089 1090 1091 1092 1093 1094

        shapes = [] if mode == 'Auto' else \
            [format_shape(shape) for shape in self.canvas.shapes]
        # Can add differrent annotation formats here

        if self.model == 'paddle':
            for box in self.result_dic:
qq_25193841's avatar
qq_25193841 已提交
1095
                trans_dic = {"label": box[1][0], "points": box[0], 'difficult': False}
qq_25193841's avatar
qq_25193841 已提交
1096 1097 1098 1099 1100 1101 1102
                if trans_dic["label"] is "" and mode == 'Auto':
                    continue
                shapes.append(trans_dic)

        try:
            trans_dic = []
            for box in shapes:
qq_25193841's avatar
qq_25193841 已提交
1103
                trans_dic.append({"transcription": box['label'], "points": box['points'], 'difficult': False})
qq_25193841's avatar
qq_25193841 已提交
1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122
            self.PPlabel[annotationFilePath] = trans_dic

            if mode == 'Auto':
                self.Cachelabel[annotationFilePath] = trans_dic

            # else:
            #     self.labelFile.save(annotationFilePath, shapes, self.filePath, self.imageData,
            #                         self.lineColor.getRgb(), self.fillColor.getRgb())
            # print('Image:{0} -> Annotation:{1}'.format(self.filePath, annotationFilePath))
            return True
        except LabelFileError as e:
            self.errorMessage(u'Error saving label data', u'<b>%s</b>' % e)
            return False

    def copySelectedShape(self):
        self.addLabel(self.canvas.copySelectedShape())
        # fix copy and delete
        self.shapeSelectionChanged(True)

qq_25193841's avatar
qq_25193841 已提交
1123

qq_25193841's avatar
qq_25193841 已提交
1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158
    def labelSelectionChanged(self):
        item = self.currentItem()
        if item and self.canvas.editing():
            self._noSelectionSlot = True
            self.canvas.selectShape(self.itemsToShapes[item])
            shape = self.itemsToShapes[item]
            # Add Chris
            self.diffcButton.setChecked(shape.difficult)

    def boxSelectionChanged(self):
        item = self.currentBox()
        if item and self.canvas.editing():
            self._noSelectionSlot = True
            self.canvas.selectShape(self.itemsToShapesbox[item])
            shape = self.itemsToShapesbox[item]
            # Add Chris
            self.diffcButton.setChecked(shape.difficult)

    def labelItemChanged(self, item):
        shape = self.itemsToShapes[item]
        label = item.text()
        if label != shape.label:
            shape.label = item.text()
            # shape.line_color = generateColorByText(shape.label)
            self.setDirty()
        else:  # User probably changed item visibility
            self.canvas.setShapeVisible(shape, item.checkState() == Qt.Checked)

    # Callback functions:
    def newShape(self):
        """Pop-up and give focus to the label editor.

        position MUST be in global coordinates.
        """
        if len(self.labelHist) > 0:
qq_25193841's avatar
qq_25193841 已提交
1159 1160
            self.labelDialog = LabelDialog(
                parent=self, listItem=self.labelHist)
qq_25193841's avatar
qq_25193841 已提交
1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173

        # Sync single class mode from PR#106
        if self.singleClassMode.isChecked() and self.lastLabel:
            text = self.lastLabel
        else:
            text = self.labelDialog.popUp(text=self.prevLabelText)
            self.lastLabel = text

        # Add Chris
        self.diffcButton.setChecked(False)
        if text is not None:
            self.prevLabelText = self.stringBundle.getString('tempLabel')
            # generate_color = generateColorByText(text)
qq_25193841's avatar
qq_25193841 已提交
1174
            shape = self.canvas.setLastLabel(text, None, None)#generate_color, generate_color
qq_25193841's avatar
qq_25193841 已提交
1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187
            self.addLabel(shape)
            if self.beginner():  # Switch to edit mode.
                self.canvas.setEditing(True)
                self.actions.create.setEnabled(True)
            else:
                self.actions.editMode.setEnabled(True)
            self.setDirty()

        else:
            # self.canvas.undoLastLine()
            self.canvas.resetAllLines()

    def scrollRequest(self, delta, orientation):
qq_25193841's avatar
qq_25193841 已提交
1188
        units = - delta / (8 * 15)
qq_25193841's avatar
qq_25193841 已提交
1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298
        bar = self.scrollBars[orientation]
        bar.setValue(bar.value() + bar.singleStep() * units)

    def setZoom(self, value):
        self.actions.fitWidth.setChecked(False)
        self.actions.fitWindow.setChecked(False)
        self.zoomMode = self.MANUAL_ZOOM
        self.zoomWidget.setValue(value)

    def addZoom(self, increment=10):
        self.setZoom(self.zoomWidget.value() + increment)

    def zoomRequest(self, delta):
        # get the current scrollbar positions
        # calculate the percentages ~ coordinates
        h_bar = self.scrollBars[Qt.Horizontal]
        v_bar = self.scrollBars[Qt.Vertical]

        # get the current maximum, to know the difference after zooming
        h_bar_max = h_bar.maximum()
        v_bar_max = v_bar.maximum()

        # get the cursor position and canvas size
        # calculate the desired movement from 0 to 1
        # where 0 = move left
        #       1 = move right
        # up and down analogous
        cursor = QCursor()
        pos = cursor.pos()
        relative_pos = QWidget.mapFromGlobal(self, pos)

        cursor_x = relative_pos.x()
        cursor_y = relative_pos.y()

        w = self.scrollArea.width()
        h = self.scrollArea.height()

        # the scaling from 0 to 1 has some padding
        # you don't have to hit the very leftmost pixel for a maximum-left movement
        margin = 0.1
        move_x = (cursor_x - margin * w) / (w - 2 * margin * w)
        move_y = (cursor_y - margin * h) / (h - 2 * margin * h)

        # clamp the values from 0 to 1
        move_x = min(max(move_x, 0), 1)
        move_y = min(max(move_y, 0), 1)

        # zoom in
        units = delta / (8 * 15)
        scale = 10
        self.addZoom(scale * units)

        # get the difference in scrollbar values
        # this is how far we can move
        d_h_bar_max = h_bar.maximum() - h_bar_max
        d_v_bar_max = v_bar.maximum() - v_bar_max

        # get the new scrollbar values
        new_h_bar_value = h_bar.value() + move_x * d_h_bar_max
        new_v_bar_value = v_bar.value() + move_y * d_v_bar_max

        h_bar.setValue(new_h_bar_value)
        v_bar.setValue(new_v_bar_value)

    def setFitWindow(self, value=True):
        if value:
            self.actions.fitWidth.setChecked(False)
        self.zoomMode = self.FIT_WINDOW if value else self.MANUAL_ZOOM
        self.adjustScale()

    def setFitWidth(self, value=True):
        if value:
            self.actions.fitWindow.setChecked(False)
        self.zoomMode = self.FIT_WIDTH if value else self.MANUAL_ZOOM
        self.adjustScale()

    def togglePolygons(self, value):
        for item, shape in self.itemsToShapes.items():
            item.setCheckState(Qt.Checked if value else Qt.Unchecked)

    def loadFile(self, filePath=None):
        """Load the specified file, or the last opened file if None."""
        self.resetState()
        self.canvas.setEnabled(False)
        if filePath is None:
            filePath = self.settings.get(SETTING_FILENAME)

        # Make sure that filePath is a regular python string, rather than QString
        filePath = ustr(filePath)
        # Fix bug: An index error after select a directory when open a new file.
        unicodeFilePath = ustr(filePath)
        # unicodeFilePath = os.path.abspath(unicodeFilePath)
        # Tzutalin 20160906 : Add file list and dock to move faster
        # Highlight the file item
        if unicodeFilePath and self.fileListWidget.count() > 0:
            if unicodeFilePath in self.mImgList:
                index = self.mImgList.index(unicodeFilePath)
                fileWidgetItem = self.fileListWidget.item(index)
                print('unicodeFilePath is', unicodeFilePath)
                fileWidgetItem.setSelected(True)
                ###
                self.iconlist.clear()
                self.additems5(None)
                for i in range(5):
                    item_tooltip = self.iconlist.item(i).toolTip()
                    # print(i,"---",item_tooltip)
                    if item_tooltip == ustr(filePath):
                        titem = self.iconlist.item(i)
                        titem.setSelected(True)
                        self.iconlist.scrollToItem(titem)
qq_25193841's avatar
qq_25193841 已提交
1299
                        break 
qq_25193841's avatar
qq_25193841 已提交
1300 1301 1302 1303 1304 1305 1306
            else:
                self.fileListWidget.clear()
                self.mImgList.clear()
                self.iconlist.clear()

        # if unicodeFilePath and self.iconList.count() > 0:
        #     if unicodeFilePath in self.mImgList:
qq_25193841's avatar
qq_25193841 已提交
1307
                
qq_25193841's avatar
qq_25193841 已提交
1308 1309 1310 1311 1312
        if unicodeFilePath and os.path.exists(unicodeFilePath):
            if LabelFile.isLabelFile(unicodeFilePath):
                try:
                    self.labelFile = LabelFile(unicodeFilePath)
                except LabelFileError as e:
qq_25193841's avatar
qq_25193841 已提交
1313 1314 1315 1316
                    self.errorMessage(u'Error opening file',
                                      (u"<p><b>%s</b></p>"
                                       u"<p>Make sure <i>%s</i> is a valid label file.")
                                      % (e, unicodeFilePath))
qq_25193841's avatar
qq_25193841 已提交
1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331
                    self.status("Error reading %s" % unicodeFilePath)
                    return False
                self.imageData = self.labelFile.imageData
                self.lineColor = QColor(*self.labelFile.lineColor)
                self.fillColor = QColor(*self.labelFile.fillColor)
                self.canvas.verified = self.labelFile.verified
            else:
                # Load image:
                # read data first and store for saving into label file.
                self.imageData = read(unicodeFilePath, None)
                self.labelFile = None
                self.canvas.verified = False

            image = QImage.fromData(self.imageData)
            if image.isNull():
qq_25193841's avatar
qq_25193841 已提交
1332 1333
                self.errorMessage(u'Error opening file',
                                  u"<p>Make sure <i>%s</i> is a valid image file." % unicodeFilePath)
qq_25193841's avatar
qq_25193841 已提交
1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353
                self.status("Error reading %s" % unicodeFilePath)
                return False
            self.status("Loaded %s" % os.path.basename(unicodeFilePath))
            self.image = image
            self.filePath = unicodeFilePath
            self.canvas.loadPixmap(QPixmap.fromImage(image))
            if self.labelFile:
                self.loadLabels(self.labelFile.shapes)
            if self.validFilestate(filePath) is True:
                self.setClean()
            else:
                self.dirty = False
                self.actions.save.setEnabled(True)

            self.canvas.setEnabled(True)
            self.adjustScale(initial=True)
            self.paintCanvas()
            self.addRecentFile(self.filePath)
            self.toggleActions(True)
            self.showBoundingBoxFromPPlabel(filePath)
qq_25193841's avatar
qq_25193841 已提交
1354
            
qq_25193841's avatar
qq_25193841 已提交
1355 1356 1357 1358
            self.setWindowTitle(__appname__ + ' ' + filePath)

            # Default : select last item if there is at least one item
            if self.labelList.count():
qq_25193841's avatar
qq_25193841 已提交
1359 1360
                self.labelList.setCurrentItem(self.labelList.item(self.labelList.count() - 1))
                self.labelList.item(self.labelList.count() - 1).setSelected(True)
qq_25193841's avatar
qq_25193841 已提交
1361 1362 1363 1364 1365

            self.canvas.setFocus(True)
            return True
        return False

qq_25193841's avatar
qq_25193841 已提交
1366
    
qq_25193841's avatar
qq_25193841 已提交
1367 1368 1369 1370 1371 1372
    def showBoundingBoxFromPPlabel(self, filePath):
        imgidx = self.getImglabelidx(filePath)
        if imgidx not in self.PPlabel.keys():
            return
        shapes = []
        for box in self.PPlabel[imgidx]:
qq_25193841's avatar
qq_25193841 已提交
1373
            shapes.append((box['transcription'], box['points'], None, None, box['difficult']))
qq_25193841's avatar
qq_25193841 已提交
1374 1375 1376 1377 1378

        print(shapes)
        self.loadLabels(shapes)
        self.canvas.verified = False

qq_25193841's avatar
qq_25193841 已提交
1379

qq_25193841's avatar
qq_25193841 已提交
1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407
    def validFilestate(self, filePath):
        if filePath not in self.fileStatedict.keys():
            return None
        elif self.fileStatedict[filePath] == 1:
            return True
        else:
            return False

    def resizeEvent(self, event):
        if self.canvas and not self.image.isNull() \
           and self.zoomMode != self.MANUAL_ZOOM:
            self.adjustScale()
        super(MainWindow, self).resizeEvent(event)

    def paintCanvas(self):
        assert not self.image.isNull(), "cannot paint null image"
        self.canvas.scale = 0.01 * self.zoomWidget.value()
        self.canvas.adjustSize()
        self.canvas.update()

    def adjustScale(self, initial=False):
        value = self.scalers[self.FIT_WINDOW if initial else self.zoomMode]()
        self.zoomWidget.setValue(int(100 * value))

    def scaleFitWindow(self):
        """Figure out the size of the pixmap in order to fit the main widget."""
        e = 2.0  # So that no scrollbars are generated.
        w1 = self.centralWidget().width() - e
qq_25193841's avatar
qq_25193841 已提交
1408
        h1 = self.centralWidget().height() - e -110
qq_25193841's avatar
qq_25193841 已提交
1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427
        a1 = w1 / h1
        # Calculate a new scale value based on the pixmap's aspect ratio.
        w2 = self.canvas.pixmap.width() - 0.0
        h2 = self.canvas.pixmap.height() - 0.0
        a2 = w2 / h2
        return w1 / w2 if a2 >= a1 else h1 / h2

    def scaleFitWidth(self):
        # The epsilon does not seem to work too well here.
        w = self.centralWidget().width() - 2.0
        return w / self.canvas.pixmap.width()

    def closeEvent(self, event):
        if not self.mayContinue():
            event.ignore()
        else:
            settings = self.settings
            # If it loads images from dir, don't load it at the begining
            if self.dirname is None:
qq_25193841's avatar
qq_25193841 已提交
1428
                settings[SETTING_FILENAME] = self.filePath if self.filePath else ''
qq_25193841's avatar
qq_25193841 已提交
1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463
            else:
                settings[SETTING_FILENAME] = ''

            settings[SETTING_WIN_SIZE] = self.size()
            settings[SETTING_WIN_POSE] = self.pos()
            settings[SETTING_WIN_STATE] = self.saveState()
            settings[SETTING_LINE_COLOR] = self.lineColor
            settings[SETTING_FILL_COLOR] = self.fillColor
            settings[SETTING_RECENT_FILES] = self.recentFiles
            settings[SETTING_ADVANCE_MODE] = not self._beginner
            if self.defaultSaveDir and os.path.exists(self.defaultSaveDir):
                settings[SETTING_SAVE_DIR] = ustr(self.defaultSaveDir)
            else:
                settings[SETTING_SAVE_DIR] = ''

            if self.lastOpenDir and os.path.exists(self.lastOpenDir):
                settings[SETTING_LAST_OPEN_DIR] = self.lastOpenDir
            else:
                settings[SETTING_LAST_OPEN_DIR] = ''

            settings[SETTING_SINGLE_CLASS] = self.singleClassMode.isChecked()
            settings[SETTING_PAINT_LABEL] = self.displayLabelOption.isChecked()
            settings[SETTING_DRAW_SQUARE] = self.drawSquaresOption.isChecked()
            settings.save()
            try:
                self.saveFilestate()
                self.savePPlabel()
            except:
                pass

    def loadRecent(self, filename):
        if self.mayContinue():
            self.loadFile(filename)

    def scanAllImages(self, folderPath):
qq_25193841's avatar
qq_25193841 已提交
1464
        extensions = ['.%s' % fmt.data().decode("ascii").lower() for fmt in QImageReader.supportedImageFormats()]
qq_25193841's avatar
qq_25193841 已提交
1465 1466 1467 1468 1469 1470 1471 1472 1473 1474
        images = []

        for file in os.listdir(folderPath):
            if file.lower().endswith(tuple(extensions)):
                relativePath = os.path.join(folderPath, file)
                path = ustr(os.path.abspath(relativePath))
                images.append(path)
        natural_sort(images, key=lambda x: x.lower())
        return images

qq_25193841's avatar
qq_25193841 已提交
1475 1476


qq_25193841's avatar
qq_25193841 已提交
1477 1478 1479 1480 1481 1482 1483 1484
    def openDirDialog(self, _value=False, dirpath=None, silent=False):
        if not self.mayContinue():
            return

        defaultOpenDirPath = dirpath if dirpath else '.'
        if self.lastOpenDir and os.path.exists(self.lastOpenDir):
            defaultOpenDirPath = self.lastOpenDir
        else:
qq_25193841's avatar
qq_25193841 已提交
1485
            defaultOpenDirPath = os.path.dirname(self.filePath) if self.filePath else '.'
qq_25193841's avatar
qq_25193841 已提交
1486
        if silent != True:
qq_25193841's avatar
qq_25193841 已提交
1487 1488 1489 1490
            targetDirPath = ustr(QFileDialog.getExistingDirectory(self,
                                                         '%s - Open Directory' % __appname__,
                                                         defaultOpenDirPath,
                                                         QFileDialog.ShowDirsOnly | QFileDialog.DontResolveSymlinks))
qq_25193841's avatar
qq_25193841 已提交
1491 1492 1493 1494 1495
        else:
            targetDirPath = ustr(defaultOpenDirPath)
        self.lastOpenDir = targetDirPath
        self.importDirImages(targetDirPath)

qq_25193841's avatar
qq_25193841 已提交
1496
    def importDirImages(self, dirpath, isDelete = False):
qq_25193841's avatar
qq_25193841 已提交
1497 1498 1499 1500 1501 1502 1503 1504
        if not self.mayContinue() or not dirpath:
            return
        if self.defaultSaveDir and self.defaultSaveDir != dirpath:
            self.saveFilestate()
            self.savePPlabel()

        if not isDelete:
            self.loadFilestate(dirpath)
qq_25193841's avatar
qq_25193841 已提交
1505
            self.PPlabelpath = dirpath+ '/Label.txt'
qq_25193841's avatar
qq_25193841 已提交
1506 1507 1508 1509 1510 1511 1512 1513
            self.PPlabel = self.loadLabelFile(self.PPlabelpath)
            self.Cachelabelpath = dirpath + '/Cache.cach'
            self.Cachelabel = self.loadLabelFile(self.Cachelabelpath)
            if self.Cachelabel:
                self.PPlabel = dict(self.Cachelabel, **self.PPlabel)
        self.lastOpenDir = dirpath
        self.dirname = dirpath

qq_25193841's avatar
qq_25193841 已提交
1514

qq_25193841's avatar
qq_25193841 已提交
1515
        self.defaultSaveDir = dirpath
qq_25193841's avatar
qq_25193841 已提交
1516 1517
        self.statusBar().showMessage('%s started. Annotation will be saved to %s' %
                                     (__appname__, self.defaultSaveDir))
qq_25193841's avatar
qq_25193841 已提交
1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566
        self.statusBar().show()

        self.filePath = None
        self.fileListWidget.clear()
        self.mImgList = self.scanAllImages(dirpath)
        self.mImgList5 = self.mImgList[:5]
        self.openNextImg()
        doneicon = newIcon('done')
        closeicon = newIcon('close')
        for imgPath in self.mImgList:
            filename = os.path.basename(imgPath)
            if self.validFilestate(imgPath) is True:
                item = QListWidgetItem(doneicon, filename)
            else:
                item = QListWidgetItem(closeicon, filename)
            self.fileListWidget.addItem(item)

        print('dirPath in importDirImages is', dirpath)
        self.iconlist.clear()
        self.additems5(dirpath)
        self.changeFileFolder = True
        self.haveAutoReced = False
        self.AutoRecognition.setEnabled(True)
        self.reRecogButton.setEnabled(True)

    def verifyImg(self, _value=False):
        # Proceding next image without dialog if having any label
        if self.filePath is not None:
            try:
                self.labelFile.toggleVerify()
            except AttributeError:
                # If the labelling file does not exist yet, create if and
                # re-save it with the verified attribute.
                self.saveFile()
                if self.labelFile != None:
                    self.labelFile.toggleVerify()
                else:
                    return

            self.canvas.verified = self.labelFile.verified
            self.paintCanvas()
            self.saveFile()

    def openPrevImg(self, _value=False):
        if len(self.mImgList) <= 0:
            return

        if self.filePath is None:
            return
qq_25193841's avatar
qq_25193841 已提交
1567
        
qq_25193841's avatar
qq_25193841 已提交
1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594
        currIndex = self.mImgList.index(self.filePath)
        self.mImgList5 = self.mImgList[:5]
        if currIndex - 1 >= 0:
            filename = self.mImgList[currIndex - 1]
            self.mImgList5 = self.indexTo5Files(currIndex - 1)
            if filename:
                self.loadFile(filename)

    def openNextImg(self, _value=False):
        if not self.mayContinue():
            return

        if len(self.mImgList) <= 0:
            return

        filename = None
        if self.filePath is None:
            filename = self.mImgList[0]
            self.mImgList5 = self.mImgList[:5]
        else:
            currIndex = self.mImgList.index(self.filePath)
            if currIndex + 1 < len(self.mImgList):
                filename = self.mImgList[currIndex + 1]
                self.mImgList5 = self.indexTo5Files(currIndex + 1)
            else:
                self.mImgList5 = self.indexTo5Files(currIndex)
        if filename:
qq_25193841's avatar
qq_25193841 已提交
1595
            print('file name in openNext is ',filename)
qq_25193841's avatar
qq_25193841 已提交
1596 1597 1598 1599 1600 1601
            self.loadFile(filename)

    def openFile(self, _value=False):
        if not self.mayContinue():
            return
        path = os.path.dirname(ustr(self.filePath)) if self.filePath else '.'
qq_25193841's avatar
qq_25193841 已提交
1602 1603 1604
        formats = ['*.%s' % fmt.data().decode("ascii").lower() for fmt in QImageReader.supportedImageFormats()]
        filters = "Image & Label files (%s)" % ' '.join(formats + ['*%s' % LabelFile.suffix])
        filename = QFileDialog.getOpenFileName(self, '%s - Choose Image or Label file' % __appname__, path, filters)
qq_25193841's avatar
qq_25193841 已提交
1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625
        if filename:
            if isinstance(filename, (tuple, list)):
                filename = filename[0]
            self.loadFile(filename)
            # print('filename in openfile is ', self.filePath)
        self.filePath = None
        self.fileListWidget.clear()
        self.iconlist.clear()
        self.mImgList = [filename]
        self.openNextImg()
        if self.validFilestate(filename) is True:
            item = QListWidgetItem(newIcon('done'), filename)
            self.setClean()
        elif self.validFilestate(filename) is None:
            item = QListWidgetItem(newIcon('close'), filename)
        else:
            item = QListWidgetItem(newIcon('close'), filename)
            self.setDirty()
        self.fileListWidget.addItem(filename)
        self.additems5(None)
        print('opened image is', filename)
qq_25193841's avatar
qq_25193841 已提交
1626
        
qq_25193841's avatar
qq_25193841 已提交
1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640
    def updateFileListIcon(self, filename):
        pass

    def saveFile(self, _value=False, mode='Manual'):
        if self.defaultSaveDir is not None and len(ustr(self.defaultSaveDir)):
            if self.filePath:
                imgidx = self.getImglabelidx(self.filePath)
                self._saveFile(imgidx, mode=mode)

        else:
            imgFileDir = os.path.dirname(self.filePath)
            imgFileName = os.path.basename(self.filePath)
            savedFileName = os.path.splitext(imgFileName)[0]
            savedPath = os.path.join(imgFileDir, savedFileName)
qq_25193841's avatar
qq_25193841 已提交
1641 1642
            self._saveFile(savedPath if self.labelFile
                           else self.saveFileDialog(removeExt=False), mode=mode)
qq_25193841's avatar
qq_25193841 已提交
1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660

    def saveFileAs(self, _value=False):
        assert not self.image.isNull(), "cannot save empty image"
        self._saveFile(self.saveFileDialog())

    def saveFileDialog(self, removeExt=True):
        caption = '%s - Choose File' % __appname__
        filters = 'File (*%s)' % LabelFile.suffix
        openDialogPath = self.currentPath()
        dlg = QFileDialog(self, caption, openDialogPath, filters)
        dlg.setDefaultSuffix(LabelFile.suffix[1:])
        dlg.setAcceptMode(QFileDialog.AcceptSave)
        filenameWithoutExtension = os.path.splitext(self.filePath)[0]
        dlg.selectFile(filenameWithoutExtension)
        dlg.setOption(QFileDialog.DontUseNativeDialog, False)
        if dlg.exec_():
            fullFilePath = ustr(dlg.selectedFiles()[0])
            if removeExt:
qq_25193841's avatar
qq_25193841 已提交
1661
                return os.path.splitext(fullFilePath)[0]  # Return file path without the extension.
qq_25193841's avatar
qq_25193841 已提交
1662 1663 1664 1665 1666 1667
            else:
                return fullFilePath
        return ''

    def _saveFile(self, annotationFilePath, mode='Manual'):
        if mode == 'Manual':
qq_25193841's avatar
qq_25193841 已提交
1668
            if annotationFilePath and self.saveLabels(annotationFilePath, mode=mode):
qq_25193841's avatar
qq_25193841 已提交
1669
                self.setClean()
qq_25193841's avatar
qq_25193841 已提交
1670
                self.statusBar().showMessage('Saved to  %s' % annotationFilePath)
qq_25193841's avatar
qq_25193841 已提交
1671 1672 1673 1674 1675 1676
                self.statusBar().show()
                currIndex = self.mImgList.index(self.filePath)
                item = self.fileListWidget.item(currIndex)
                item.setIcon(newIcon('done'))

                self.fileStatedict[self.filePath] = 1
qq_25193841's avatar
qq_25193841 已提交
1677
                if len(self.fileStatedict)%self.autoSaveNum ==0:
qq_25193841's avatar
qq_25193841 已提交
1678 1679 1680 1681 1682 1683 1684 1685
                    self.saveFilestate()
                    self.savePPlabel(mode='Auto')

                self.fileListWidget.insertItem(int(currIndex), item)
                self.openNextImg()
                self.actions.saveRec.setEnabled(True)

        elif mode == 'Auto':
qq_25193841's avatar
qq_25193841 已提交
1686
            if annotationFilePath and self.saveLabels(annotationFilePath, mode=mode):
qq_25193841's avatar
qq_25193841 已提交
1687 1688

                self.setClean()
qq_25193841's avatar
qq_25193841 已提交
1689
                self.statusBar().showMessage('Saved to  %s' % annotationFilePath)
qq_25193841's avatar
qq_25193841 已提交
1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707
                self.statusBar().show()

    def closeFile(self, _value=False):
        if not self.mayContinue():
            return
        self.resetState()
        self.setClean()
        self.toggleActions(False)
        self.canvas.setEnabled(False)
        self.actions.saveAs.setEnabled(False)

    def deleteImg(self):
        deletePath = self.filePath
        if deletePath is not None:
            deleteInfo = self.deleteImgDialog()
            if deleteInfo == QMessageBox.Yes:
                if platform.system() == 'Windows':
                    from win32com.shell import shell, shellcon
qq_25193841's avatar
qq_25193841 已提交
1708 1709 1710
                    shell.SHFileOperation((0, shellcon.FO_DELETE, deletePath, None,
                                               shellcon.FOF_SILENT | shellcon.FOF_ALLOWUNDO | shellcon.FOF_NOCONFIRMATION,
                                               None, None))
qq_25193841's avatar
qq_25193841 已提交
1711 1712 1713 1714 1715 1716 1717
                    # linux
                elif platform.system() == 'Linux':
                    cmd = 'trash ' + deletePath
                    os.system(cmd)
                    # macOS
                elif platform.system() == 'Darwin':
                    import subprocess
qq_25193841's avatar
qq_25193841 已提交
1718 1719 1720
                    absPath = os.path.abspath(deletePath).replace('\\', '\\\\').replace('"', '\\"')
                    cmd = ['osascript', '-e',
                           'tell app "Finder" to move {the POSIX file "' + absPath + '"} to trash']
qq_25193841's avatar
qq_25193841 已提交
1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743
                    print(cmd)
                    subprocess.call(cmd, stdout=open(os.devnull, 'w'))

                if self.filePath in self.fileStatedict.keys():
                    self.fileStatedict.pop(self.filePath)
                imgidx = self.getImglabelidx(self.filePath)
                if imgidx in self.PPlabel.keys():
                    self.PPlabel.pop(imgidx)
                self.openNextImg()
                self.importDirImages(self.lastOpenDir, isDelete=True)

    def deleteImgDialog(self):
        yes, cancel = QMessageBox.Yes, QMessageBox.Cancel
        msg = u'The image will be deleted to the recycle bin'
        return QMessageBox.warning(self, u'Attention', msg, yes | cancel)

    def resetAll(self):
        self.settings.reset()
        self.close()
        proc = QProcess()
        proc.startDetached(os.path.abspath(__file__))

    def mayContinue(self):  #
qq_25193841's avatar
qq_25193841 已提交
1744
        if not self.dirty:                                    
qq_25193841's avatar
qq_25193841 已提交
1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768
            return True
        else:
            discardChanges = self.discardChangesDialog()
            if discardChanges == QMessageBox.No:
                return True
            elif discardChanges == QMessageBox.Yes:
                self.saveFile()
                return True
            else:
                return False

    def discardChangesDialog(self):
        yes, no, cancel = QMessageBox.Yes, QMessageBox.No, QMessageBox.Cancel
        msg = u'You have unsaved changes, would you like to save them and proceed?\nClick "No" to undo all changes.'
        return QMessageBox.warning(self, u'Attention', msg, yes | no | cancel)

    def errorMessage(self, title, message):
        return QMessageBox.critical(self, title,
                                    '<p><b>%s</b></p>%s' % (title, message))

    def currentPath(self):
        return os.path.dirname(self.filePath) if self.filePath else '.'

    def chooseColor1(self):
qq_25193841's avatar
qq_25193841 已提交
1769 1770
        color = self.colorDialog.getColor(self.lineColor, u'Choose line color',
                                          default=DEFAULT_LINE_COLOR)
qq_25193841's avatar
qq_25193841 已提交
1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785
        if color:
            self.lineColor = color
            Shape.line_color = color
            self.canvas.setDrawingColor(color)
            self.canvas.update()
            self.setDirty()

    def deleteSelectedShape(self):
        self.remLabel(self.canvas.deleteSelected())
        self.setDirty()
        if self.noShapes():
            for action in self.actions.onShapesPresent:
                action.setEnabled(False)

    def chshapeLineColor(self):
qq_25193841's avatar
qq_25193841 已提交
1786 1787
        color = self.colorDialog.getColor(self.lineColor, u'Choose line color',
                                          default=DEFAULT_LINE_COLOR)
qq_25193841's avatar
qq_25193841 已提交
1788 1789 1790 1791 1792 1793
        if color:
            self.canvas.selectedShape.line_color = color
            self.canvas.update()
            self.setDirty()

    def chshapeFillColor(self):
qq_25193841's avatar
qq_25193841 已提交
1794 1795
        color = self.colorDialog.getColor(self.fillColor, u'Choose fill color',
                                          default=DEFAULT_FILL_COLOR)
qq_25193841's avatar
qq_25193841 已提交
1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819
        if color:
            self.canvas.selectedShape.fill_color = color
            self.canvas.update()
            self.setDirty()

    def copyShape(self):
        self.canvas.endMove(copy=True)
        self.addLabel(self.canvas.selectedShape)
        self.setDirty()

    def moveShape(self):
        self.canvas.endMove(copy=False)
        self.setDirty()

    def loadPredefinedClasses(self, predefClassesFile):
        if os.path.exists(predefClassesFile) is True:
            with codecs.open(predefClassesFile, 'r', 'utf8') as f:
                for line in f:
                    line = line.strip()
                    if self.labelHist is None:
                        self.labelHist = [line]
                    else:
                        self.labelHist.append(line)

qq_25193841's avatar
qq_25193841 已提交
1820

qq_25193841's avatar
qq_25193841 已提交
1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832
    def togglePaintLabelsOption(self):
        for shape in self.canvas.shapes:
            shape.paintLabel = self.displayLabelOption.isChecked()

    def toogleDrawSquare(self):
        self.canvas.setDrawingShapeToSquare(self.drawSquaresOption.isChecked())

    def additems(self, dirpath):
        for file in self.mImgList:
            pix = QPixmap(file)
            _, filename = os.path.split(file)
            filename, _ = os.path.splitext(filename)
qq_25193841's avatar
qq_25193841 已提交
1833 1834
            item = QListWidgetItem(QIcon(pix.scaled(100, 100, Qt.IgnoreAspectRatio, Qt.FastTransformation)),
                                   filename[:10])
qq_25193841's avatar
qq_25193841 已提交
1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848
            item.setToolTip(file)
            self.iconlist.addItem(item)

    def additems5(self, dirpath):
        for file in self.mImgList5:
            pix = QPixmap(file)
            _, filename = os.path.split(file)
            filename, _ = os.path.splitext(filename)
            pfilename = filename[:10]
            if len(pfilename) < 10:
                lentoken = 12 - len(pfilename)
                prelen = lentoken // 2
                bfilename = prelen * " " + pfilename + (lentoken - prelen) * " "
            # item = QListWidgetItem(QIcon(pix.scaled(100, 100, Qt.KeepAspectRatio, Qt.SmoothTransformation)),filename[:10])
qq_25193841's avatar
qq_25193841 已提交
1849
            item = QListWidgetItem(QIcon(pix.scaled(100, 100, Qt.IgnoreAspectRatio, Qt.FastTransformation)),pfilename)
qq_25193841's avatar
qq_25193841 已提交
1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860
            # item.setForeground(QBrush(Qt.white))
            item.setToolTip(file)
            self.iconlist.addItem(item)
        owidth = 0
        for index in range(len(self.mImgList5)):
            item = self.iconlist.item(index)
            itemwidget = self.iconlist.visualItemRect(item)
            owidth += itemwidget.width()
        self.iconlist.setMinimumWidth(owidth + 50)

    def getImglabelidx(self, filePath):
qq_25193841's avatar
qq_25193841 已提交
1861
        if platform.system()=='Windows':
qq_25193841's avatar
qq_25193841 已提交
1862 1863 1864 1865 1866 1867 1868 1869 1870 1871
            spliter = '\\'
        else:
            spliter = '/'
        filepathsplit = filePath.split(spliter)[-2:]
        return filepathsplit[0] + '/' + filepathsplit[1]

    def autoRecognition(self):
        assert self.mImgList is not None
        print('Using model from ', self.model)

qq_25193841's avatar
qq_25193841 已提交
1872 1873
        uncheckedList = [i for i in self.mImgList if i not in self.fileStatedict.keys()]
        self.autoDialog = AutoDialog(parent=self, ocr=self.ocr, mImgList=uncheckedList, lenbar=len(uncheckedList))
qq_25193841's avatar
qq_25193841 已提交
1874
        self.autoDialog.popUp()
qq_25193841's avatar
qq_25193841 已提交
1875 1876
        self.currIndex=len(self.mImgList)
        self.loadFile(self.filePath) # ADD
qq_25193841's avatar
qq_25193841 已提交
1877 1878 1879 1880 1881
        self.haveAutoReced = True
        self.AutoRecognition.setEnabled(False)
        self.setDirty()
        self.saveCacheLabel()

qq_25193841's avatar
qq_25193841 已提交
1882

qq_25193841's avatar
qq_25193841 已提交
1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910
    def reRecognition(self):
        img = cv2.imread(self.filePath)
        # org_box = [dic['points'] for dic in self.PPlabel[self.getImglabelidx(self.filePath)]]
        if self.canvas.shapes:
            self.result_dic = []
            rec_flag = 0
            for shape in self.canvas.shapes:
                box = [[int(p.x()), int(p.y())] for p in shape.points]
                assert len(box) == 4
                img_crop = get_rotate_crop_image(img, np.array(box, np.float32))
                if img_crop is None:
                    msg = 'Can not recognise the detection box in ' + self.filePath + '. Please change manually'
                    QMessageBox.information(self, "Information", msg)
                    return
                result = self.ocr.ocr(img_crop, cls=True, det=False)
                if result[0][0] is not '':
                    result.insert(0, box)
                    print('result in reRec is ', result)
                    self.result_dic.append(result)
                    if result[1][0] == shape.label:
                        print('label no change')
                    else:
                        rec_flag += 1

            if len(self.result_dic) > 0 and rec_flag > 0:
                self.saveFile(mode='Auto')
                self.loadFile(self.filePath)
                self.setDirty()
qq_25193841's avatar
qq_25193841 已提交
1911 1912
            elif len(self.result_dic) == len(self.canvas.shapes) and rec_flag == 0:
                QMessageBox.information(self, "Information", "The recognition result remains unchanged!")
qq_25193841's avatar
qq_25193841 已提交
1913 1914 1915 1916 1917
            else:
                print('Can not recgonise in ', self.filePath)
        else:
            QMessageBox.information(self, "Information", "Draw a box!")

qq_25193841's avatar
qq_25193841 已提交
1918

qq_25193841's avatar
qq_25193841 已提交
1919
    def autolcm(self):
qq_25193841's avatar
qq_25193841 已提交
1920 1921 1922 1923 1924 1925 1926
        vbox = QVBoxLayout()
        hbox = QHBoxLayout()
        self.panel = QLabel()
        self.panel.setText(self.stringBundle.getString('choseModelLg'))
        self.panel.setAlignment(Qt.AlignLeft)
        self.comboBox = QComboBox()
        self.comboBox.setObjectName("comboBox")
qq_25193841's avatar
qq_25193841 已提交
1927
        self.comboBox.addItems(['Chinese & English', 'English', 'French', 'German', 'Korean', 'Japanese'])
qq_25193841's avatar
qq_25193841 已提交
1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951
        # self.comboBox_lg = QComboBox()
        # self.comboBox_lg.setObjectName("comboBox_language")
        vbox.addWidget(self.panel)
        vbox.addWidget(self.comboBox)
        self.dialog = QDialog()
        self.dialog.resize(300, 100)
        self.okBtn = QPushButton(self.stringBundle.getString('ok'))
        self.cancelBtn = QPushButton(self.stringBundle.getString('cancel'))

        self.okBtn.clicked.connect(self.modelChoose)
        self.cancelBtn.clicked.connect(self.cancel)
        self.dialog.setWindowTitle(self.stringBundle.getString('choseModelLg'))

        hbox.addWidget(self.okBtn)
        hbox.addWidget(self.cancelBtn)

        vbox.addWidget(self.panel)
        vbox.addLayout(hbox)
        self.dialog.setLayout(vbox)
        self.dialog.setWindowModality(Qt.ApplicationModal)
        self.dialog.exec_()
        if self.filePath:
            self.AutoRecognition.setEnabled(True)

qq_25193841's avatar
qq_25193841 已提交
1952

qq_25193841's avatar
qq_25193841 已提交
1953 1954
    def modelChoose(self):
        print(self.comboBox.currentText())
qq_25193841's avatar
qq_25193841 已提交
1955 1956
        lg_idx = {'Chinese & English': 'ch', 'English': 'en', 'French': 'french', 'German': 'german',
                  'Korean': 'korean', 'Japanese': 'japan'}
qq_25193841's avatar
qq_25193841 已提交
1957
        del self.ocr
qq_25193841's avatar
qq_25193841 已提交
1958 1959
        self.ocr = PaddleOCR(use_pdserving=False, use_angle_cls=True, det=True, cls=True, use_gpu=False,
                             lang=lg_idx[self.comboBox.currentText()])
qq_25193841's avatar
qq_25193841 已提交
1960 1961 1962 1963
        self.dialog.close()

    def cancel(self):
        self.dialog.close()
qq_25193841's avatar
qq_25193841 已提交
1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976

    def loadFilestate(self, saveDir):
        self.fileStatepath = saveDir + '/fileState.txt'
        self.fileStatedict = {}
        if not os.path.exists(self.fileStatepath):
            f = open(self.fileStatepath, 'w', encoding='utf-8')
        else:
            with open(self.fileStatepath, 'r', encoding='utf-8') as f:
                states = f.readlines()
                for each in states:
                    file, state = each.split('\t')
                    self.fileStatedict[file] = 1

qq_25193841's avatar
qq_25193841 已提交
1977

qq_25193841's avatar
qq_25193841 已提交
1978 1979 1980 1981 1982 1983
    def saveFilestate(self):
        with open(self.fileStatepath, 'w', encoding='utf-8') as f:
            for key in self.fileStatedict:
                f.write(key + '\t')
                f.write(str(self.fileStatedict[key]) + '\n')

qq_25193841's avatar
qq_25193841 已提交
1984

qq_25193841's avatar
qq_25193841 已提交
1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001
    def loadLabelFile(self, labelpath):
        labeldict = {}
        if not os.path.exists(labelpath):
            f = open(labelpath, 'w', encoding='utf-8')

        else:
            with open(labelpath, 'r', encoding='utf-8') as f:
                data = f.readlines()
                for each in data:
                    file, label = each.split('\t')
                    if label:
                        label = label.replace('false', 'False')
                        labeldict[file] = eval(label)
                    else:
                        labeldict[file] = []
        return labeldict

qq_25193841's avatar
qq_25193841 已提交
2002 2003

    def savePPlabel(self,mode='Manual'):
qq_25193841's avatar
qq_25193841 已提交
2004 2005 2006 2007 2008
        savedfile = [self.getImglabelidx(i) for i in self.fileStatedict.keys()]
        with open(self.PPlabelpath, 'w', encoding='utf-8') as f:
            for key in self.PPlabel:
                if key in savedfile:
                    f.write(key + '\t')
qq_25193841's avatar
qq_25193841 已提交
2009
                    f.write(json.dumps(self.PPlabel[key], ensure_ascii=False) + '\n')
qq_25193841's avatar
qq_25193841 已提交
2010

qq_25193841's avatar
qq_25193841 已提交
2011 2012
        if mode=='Manual':
            msg = 'Images that have been checked are saved in '+ self.PPlabelpath
qq_25193841's avatar
qq_25193841 已提交
2013 2014 2015 2016 2017 2018
            QMessageBox.information(self, "Information", msg)

    def saveCacheLabel(self):
        with open(self.Cachelabelpath, 'w', encoding='utf-8') as f:
            for key in self.Cachelabel:
                f.write(key + '\t')
qq_25193841's avatar
qq_25193841 已提交
2019
                f.write(json.dumps(self.Cachelabel[key], ensure_ascii=False) + '\n')
qq_25193841's avatar
qq_25193841 已提交
2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035

    def saveRecResult(self):
        if None in [self.PPlabelpath, self.PPlabel, self.fileStatedict]:
            QMessageBox.information(self, "Information", "Save file first")
            return

        rec_gt_dir = os.path.dirname(self.PPlabelpath) + '/rec_gt.txt'
        crop_img_dir = os.path.dirname(self.PPlabelpath) + '/crop_img/'
        if not os.path.exists(crop_img_dir):
            os.mkdir(crop_img_dir)

        with open(rec_gt_dir, 'w', encoding='utf-8') as f:
            for key in self.fileStatedict:
                idx = self.getImglabelidx(key)
                for i, label in enumerate(self.PPlabel[idx]):
                    img = cv2.imread(key)
qq_25193841's avatar
qq_25193841 已提交
2036 2037 2038 2039
                    img_crop = get_rotate_crop_image(img, np.array(label['points'], np.float32))
                    img_name = os.path.splitext(os.path.basename(idx))[0] + '_crop_'+str(i)+'.jpg'
                    cv2.imwrite(crop_img_dir+img_name, img_crop)
                    f.write('crop_img/'+ img_name + '\t')
qq_25193841's avatar
qq_25193841 已提交
2040 2041
                    f.write(label['transcription'] + '\n')

qq_25193841's avatar
qq_25193841 已提交
2042
        QMessageBox.information(self, "Information", "Cropped images has been saved in "+str(crop_img_dir))
qq_25193841's avatar
qq_25193841 已提交
2043 2044

def inverted(color):
qq_25193841's avatar
qq_25193841 已提交
2045
    return QColor(*[255 - v for v in color.getRgb()])
qq_25193841's avatar
qq_25193841 已提交
2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065


def read(filename, default=None):
    try:
        with open(filename, 'rb') as f:
            return f.read()
    except:
        return default


def get_main_app(argv=[]):
    """
    Standard boilerplate Qt application code.
    Do everything but app.exec_() -- so that we can test the application in one thread
    """
    app = QApplication(argv)
    app.setApplicationName(__appname__)
    app.setWindowIcon(newIcon("app"))
    # Tzutalin 201705+: Accept extra agruments to change predefined class file
    argparser = argparse.ArgumentParser()
qq_25193841's avatar
qq_25193841 已提交
2066
    argparser.add_argument("--lang", default='ch', nargs="?")
qq_25193841's avatar
qq_25193841 已提交
2067 2068 2069
    argparser.add_argument("--predefined_classes_file",
                           default=os.path.join(os.path.dirname(__file__), "data", "predefined_classes.txt"),
                           nargs="?")
qq_25193841's avatar
qq_25193841 已提交
2070 2071
    args = argparser.parse_args(argv[1:])
    # Usage : labelImg.py image predefClassFile saveDir
qq_25193841's avatar
qq_25193841 已提交
2072 2073 2074
    win = MainWindow(lang=args.lang,
                     defaultPrefdefClassFile=args.predefined_classes_file,
                     )
qq_25193841's avatar
qq_25193841 已提交
2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085
    win.show()
    return app, win


def main():
    '''construct main app and run it'''
    app, _win = get_main_app(sys.argv)
    return app.exec_()


if __name__ == '__main__':
qq_25193841's avatar
qq_25193841 已提交
2086
        
qq_25193841's avatar
qq_25193841 已提交
2087 2088 2089 2090 2091 2092 2093
    resource_file = './libs/resources.py'
    if not os.path.exists(resource_file):
        output = os.system('pyrcc5 -o libs/resources.py resources.qrc')
        assert output is 0, "operate the cmd have some problems ,please check  whether there is a in the lib " \
                            "directory resources.py "
    import libs.resources
    sys.exit(main())