프로젝트

일반

사용자정보

통계
| 개정판:

hytos / DTI_PID / DTI_PID / AppDocData.py @ ff3d1c7a

이력 | 보기 | 이력해설 | 다운로드 (38.8 KB)

1 e4b3e191 humkyung
# coding: utf-8
2
3 dc620556 humkyung
import sys
4 e4b3e191 humkyung
import os
5 74d14da9 humkyung
from PyQt5.QtCore import *
6 e4b3e191 humkyung
import sqlite3
7 09dfdab8 김정우
import datetime
8 7b2a4455 김정우
from PIL import PngImagePlugin, JpegImagePlugin
9
from PIL import Image
10
from PIL.ImageQt import ImageQt
11
12
try:
13
    from PyQt5.QtCore import QBuffer
14
    from PyQt5.QtGui import QImage, QPixmap
15
except ImportError:
16
    from PyQt4.QtCore import QBuffer
17
    from PyQt4.QtGui import QImage, QPixmap
18
import numpy as np
19
20 467d9e29 humkyung
from SingletonInstance import SingletonInstane
21
import Project
22
import SymbolBase
23
import symbol
24
from EquipmentData import EquipmentData
25
26 7b2a4455 김정우
class Source:
27
    def __init__(self, source):
28
        if type(source) is np.ndarray:
29
            self.source = Image.fromarray(source)
30
        elif type(source) is PngImagePlugin.PngImageFile or type(source) is JpegImagePlugin.JpegImageFile:
31
            self.source = source
32
        elif type(source) is QImage:
33
            self.source = Image.fromqimage(source)
34
        elif type(source) is QPixmap:
35
            self.source = Image.fromqpixmap(source)
36
            
37
    def getPyImageOnRect(self, rect):
38
        return self.source.copy().crop((rect.left(), rect.top(), rect.right(), rect.bottom()))
39
40
    def getQImageOnRect(self, rect):
41
        image = ImageQt(self.getPyImageOnRect(rect))
42
        return image.convertToFormat(QImage.Format_RGBA8888)
43 e4b3e191 humkyung
44 5278f161 humkyung
class Area:
45
    def __init__(self):
46
        self.name = None
47
        self.x = None
48
        self.y = None
49
        self.width = None
50
        self.height = None
51
    
52
    '''
53
        @brief  clone an object
54
    '''
55
    def clone(self):
56
        clone = Area()
57
        clone.x = self.x
58
        clone.y = self.y
59
        clone.width = self.width
60
        clone.height = self.height
61
62 8c5431cc humkyung
class Config:
63
    def __init__(self, section, key, value):
64
        self.section = section
65
        self.key = key
66
        self.value = value
67
68 02294b59 humkyung
class NominalPipeSize:
69 f5943099 humkyung
    def __init__(self, code, metric, inch, inchStr, metricStr):
70 02294b59 humkyung
        self.code = code
71
        self.metric = metric
72
        self.inch = inch
73
        self.inchStr = inchStr
74 f5943099 humkyung
        self.metricStr = metricStr
75
        self.sizeUnit = 'Metric'
76
77
    '''
78
        @brief  return size value string
79
        @author humkyung
80
        @date   2018.04.24
81
    '''
82
    def sizeValue(self):
83
        return self.inchStr if 'Inch' == self.sizeUnit else self.metricStr
84 02294b59 humkyung
85 e4b3e191 humkyung
class AppDocData(SingletonInstane):
86 5278f161 humkyung
    def __init__(self):
87 68ce37ea humkyung
        self.imgName = None
88
        self.imgWidth = 0
89
        self.imgHeight = 0
90
91 5278f161 humkyung
        self._areas = []
92 f21ec5b3 humkyung
        self.equipments = []
93 467d9e29 humkyung
        self.equipmentDataList = []
94 8c5431cc humkyung
        self.lineNos = []
95 5278f161 humkyung
96 7b2a4455 김정우
    def setCurrentPidSource(self, image):
97
        self.currentPidSource = Source(image)
98
99
    def getCurrentPidSource(self):
100
        return self.currentPidSource
101
102 e4b3e191 humkyung
    '''
103 24219f3d 김정우
        @brief      Check if Exist data or not, Moved from SG_DbHelper
104
        @author     Jeongwoo
105
        @date       2018.05.03
106
    '''
107
    def isExistData(self, fieldName, data):
108
        rows = None
109
        try:
110
            dbPath = self.getCurrentProject().getDbFilePath() + "/ITI_PID.db"
111
112
            conn = sqlite3.connect(dbPath)
113
            cursor = conn.cursor()
114
            sql = ""
115
            if isinstance(data, str):
116
                sql = "SELECT * FROM Symbol WHERE " + fieldName + " = '"+ data +"'"
117
            else:
118
                sql = "SELECT * FROM Symbol WHERE " + fieldName + " = "+ str(data) +""
119
            cursor.execute(sql)
120
            rows = cursor.fetchall()
121 ff3d1c7a 김정우
        # Catch the exception
122
        except Exception as ex:
123
            # Roll back any change if something goes wrong
124
            conn.rollback()
125
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
126 24219f3d 김정우
        finally:
127
            conn.close()
128
            if rows is not None and len(rows) > 0:
129
                return True
130
            else:
131
                return False
132
133
    '''
134
        @brief      Check if exist file name or not, Moved from SG_DbHelper
135
        @author     Jeongwoo
136
        @date       2018.05.03
137
    '''
138
    def isExistFileName(self, name):
139
        rows = None
140
        try:
141
            dbPath = self.getCurrentProject().getDbFilePath() + "/ITI_PID.db"
142
            conn = sqlite3.connect(dbPath)
143
            cursor = conn.cursor()
144
            sql = "SELECT * FROM Symbol WHERE name = '"+ name +"'"
145
            cursor.execute(sql)
146
            rows = cursor.fetchall()
147 ff3d1c7a 김정우
        # Catch the exception
148
        except Exception as ex:
149
            # Roll back any change if something goes wrong
150
            conn.rollback()
151
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
152 24219f3d 김정우
        finally:
153
            conn.close()
154
            if rows is not None and len(rows) > 0:
155
                return True
156
            else:
157
                return False
158
159
    '''
160
        @brief      Insert new symbol into Symbol Table, Moved from SG_DbHelper
161
        @author     Jeongwoo
162
        @date       2018.05.03
163
    '''
164
    def insertSymbol(self, symbol):
165
        isAdded = False
166
        try:
167
            dbPath = self.getCurrentProject().getDbFilePath() + "/ITI_PID.db"
168
            conn = sqlite3.connect(dbPath)
169
            
170
            INSERT_SYMBOL_SQL = '''
171
                INSERT INTO Symbol(symId, name, type, threshold, minMatchPoint, isDetectOrigin, rotationCount, ocrOption, isContainChild, originalPoint, connectionPoint, baseSymbol, additionalSymbol, isExceptDetect) 
172
                VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);
173
            '''
174
175
            cursor = conn.cursor()
176
            query = (symbol.getId(), symbol.getName(), symbol.getType(), symbol.getThreshold()
177
                           , symbol.getMinMatchCount(), symbol.getIsDetectOnOrigin(), symbol.getRotationCount()
178
                           , symbol.getOcrOption(), symbol.getIsContainChild()
179
                           , symbol.getOriginalPoint(), symbol.getConnectionPoint()
180
                           , symbol.getBaseSymbol(), symbol.getAdditionalSymbol(), symbol.getIsExceptDetect())
181
            cursor.execute(INSERT_SYMBOL_SQL, query)
182
            conn.commit()
183
            isAdded = True
184 ff3d1c7a 김정우
        # Catch the exception
185
        except Exception as ex:
186
            # Roll back any change if something goes wrong
187
            conn.rollback()
188
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
189 24219f3d 김정우
        finally:
190
            conn.close()
191
            return (isAdded, symbol.getType(), symbol.getName(), symbol.getPath())
192
193
    '''
194
        @brief      Update symbol in Symbol Table, Moved from SG_DbHelper
195
        @author     Jeongwoo
196
        @date       2018.05.03
197
    '''
198
    def updateSymbol(self, symbol):
199
        isUpdated = False
200
        try:
201
            dbPath = self.getCurrentProject().getDbFilePath() + "/ITI_PID.db"
202
            conn = sqlite3.connect(dbPath)
203
            
204
            UPDATE_SYMBOL_SQL = '''
205
                UPDATE Symbol
206
                SET
207
                    symId = ?, name = ?, type = ?, threshold = ?, minMatchPoint = ?, isDetectOrigin = ?,
208
                    rotationCount = ?, ocrOption = ?, isContainChild = ?, originalPoint = ?, connectionPoint = ?,
209
                    baseSymbol = ?, additionalSymbol = ?, isExceptDetect = ?
210
                WHERE uid = ?
211
            '''
212
            
213
            cursor = conn.cursor()
214
            query = (symbol.getId(), symbol.getName(), symbol.getType(), symbol.getThreshold()
215
                           , symbol.getMinMatchCount(), symbol.getIsDetectOnOrigin(), symbol.getRotationCount()
216
                           , symbol.getOcrOption(), symbol.getIsContainChild()
217
                           , symbol.getOriginalPoint(), symbol.getConnectionPoint()
218
                           , symbol.getBaseSymbol(), symbol.getAdditionalSymbol(), symbol.getIsExceptDetect(), symbol.getUid())
219
            cursor.execute(UPDATE_SYMBOL_SQL, query)
220
            conn.commit()
221
            isUpdated = True
222 ff3d1c7a 김정우
        # Catch the exception
223
        except Exception as ex:
224
            # Roll back any change if something goes wrong
225
            conn.rollback()
226
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
227 24219f3d 김정우
        finally:
228
            conn.close()
229
            return (isUpdated, symbol.getType(), symbol.getName(), symbol.getPath())
230
231
    '''
232 8d35dc6e 김정우
        @brief      Get Detecting Target Symbol List (Field 'isExceptDetect' == False(0))
233
        @author     Jeongwoo
234
        @date       18.04.24
235
    '''
236
    def getTargetSymbolList(self):
237
        targetSymbolList = []
238
239
        try:
240
            dbPath = self.getCurrentProject().getDbFilePath() + "/ITI_PID.db"
241
242
            conn = sqlite3.connect(dbPath)
243
            cursor = conn.cursor()
244
            sql = 'SELECT * FROM Symbol WHERE isExceptDetect = 0'
245
            try:
246
                cursor.execute(sql)
247
                rows = cursor.fetchall()
248
                for row in rows:
249
                    sym = symbol.SymbolBase(row[1], row[2], row[3], row[4], row[5], row[6], row[7], row[8], row[9], row[10], row[11], row[12], row[13], row[14], row[0]) ## uid is last item
250
                    targetSymbolList.append(sym)
251
            except Exception as ex:
252
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
253
        finally:
254
            conn.close()
255
256
        return targetSymbolList
257
258
    '''
259 02294b59 humkyung
        @brief  build application database
260
        @author humkyung
261
        @date   2018.04.20
262
    '''
263
    def buildAppDatabase(self):
264
        try:
265
            path = os.path.join(os.getenv('ALLUSERSPROFILE'), 'Digital PID')
266
            appDatabaseFilePath = os.path.join(path, 'App.db')
267
268
            # Creates or opens a file called mydb with a SQLite3 DB
269
            conn = sqlite3.connect(appDatabaseFilePath)
270
            # Get a cursor object
271
            cursor = conn.cursor()
272
273
            sqlFiles = ['App.Configuration.sql', 'App.Styles.sql']
274
            for sqlFile in sqlFiles:
275
                filePath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'Scripts', sqlFile)
276
                try:
277
                    file = QFile(filePath)
278
                    file.open(QFile.ReadOnly)
279
                    sql = file.readAll()
280
                    sql = str(sql, encoding='utf8')
281
                    cursor.executescript(sql)
282
                finally:
283
                    file.close()
284
            conn.commit()
285
        # Catch the exception
286
        except Exception as ex:
287
            # Roll back any change if something goes wrong
288
            conn.rollback()
289
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
290
        finally:
291
            # Close the db connection
292
            conn.close()
293
294
    '''
295
        @brief  load app style
296
        @author humkyung
297
        @date   2018.04.20
298
    '''
299
    def loadAppStyle(self):
300
        style = 'Fusion'
301
302
        path = os.path.join(os.getenv('ALLUSERSPROFILE'), 'Digital PID')
303
        if not os.path.exists(path): os.makedirs(path)
304
305
        self.buildAppDatabase()
306
        try:
307
            appDatabaseFilePath = os.path.join(path, 'App.db')
308
            # Creates or opens a file called mydb with a SQLite3 DB
309
            conn = sqlite3.connect(appDatabaseFilePath)
310
            # Get a cursor object
311
            cursor = conn.cursor()
312
313
            sql = "select Value from Configuration where Section='App' and Key='Style'" 
314
            cursor.execute(sql)
315
            rows = cursor.fetchall()
316
            style = rows[0][0] if 1 == len(rows) else 'Fusion'
317
        # Catch the exception
318
        except Exception as ex:
319
            # Roll back any change if something goes wrong
320
            conn.rollback()
321
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
322
        finally:
323
            # Close the db connection
324
            conn.close()
325
326
        return style
327
328
    '''
329
        @brief  load app styles and then return a list
330
        @author humkyung
331
        @date   2018.04.20
332
    '''
333
    def loadAppStyles(self):
334
        styles = []
335
336
        try:
337
            self.buildAppDatabase()
338
339
            path = os.path.join(os.getenv('ALLUSERSPROFILE'), 'Digital PID')
340
            appDatabaseFilePath = os.path.join(path, 'App.db')
341
342
            # Creates or opens a file called mydb with a SQLite3 DB
343
            conn = sqlite3.connect(appDatabaseFilePath)
344
            # Get a cursor object
345
            cursor = conn.cursor()
346
347
            sql = 'select UID,Value from Styles'
348
            cursor.execute(sql)
349
            rows = cursor.fetchall()
350
            for row in rows: styles.append(row[1])
351
            if 0 == len(rows): rows.append('fusion')
352
        # Catch the exception
353
        except Exception as ex:
354
            # Roll back any change if something goes wrong
355
            conn.rollback()
356
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
357
        finally:
358
            # Close the db connection
359
            conn.close()
360
361
        return styles
362
363
    '''
364 d52b3462 김정우
        @brief  Set current Project
365
    '''
366
    def setCurrentProject(self, project):
367
        self.project = project
368
369 74d14da9 humkyung
        try:
370
            # Creates or opens a file called mydb with a SQLite3 DB
371
            dbPath = self.getCurrentProject().getDbFilePath() + "/ITI_PID.db"
372
            conn = sqlite3.connect(dbPath)
373
            # Get a cursor object
374
            cursor = conn.cursor()
375
376
            fileNames = os.listdir(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'Scripts'))
377
            for fileName in fileNames:
378 80f6becd humkyung
                if fileName.endswith(".sql") and (1 == len(os.path.splitext(fileName)[0].split('.'))):
379 74d14da9 humkyung
                    try:
380
                        file = QFile(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'Scripts', fileName))
381
                        file.open(QFile.ReadOnly)
382
                        sql = file.readAll()
383
                        sql = str(sql, encoding='utf8')
384
                        cursor.executescript(sql)
385
                    finally:
386
                        file.close()
387
            conn.commit()
388
        # Catch the exception
389
        except Exception as ex:
390
            # Roll back any change if something goes wrong
391
            conn.rollback()
392
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
393
        finally:
394
            # Close the db connection
395
            conn.close()
396
397 d52b3462 김정우
    '''
398
        @brief  Get current Project
399
    '''
400
    def getCurrentProject(self):
401
        return self.project
402
403
    '''
404 2709dc9f humkyung
        @brief      return project database path
405
        @history    humkyung 2018.04.19 return Project.db in Program Data folder instead of PROJECT_DB_PATH variable
406 dc620556 humkyung
    '''
407
    def getPrjDatabasePath(self):
408 2709dc9f humkyung
        path = os.path.join(os.getenv('ALLUSERSPROFILE'), 'Digital PID')
409
        if not os.path.exists(path): os.makedirs(path)
410
411
        prjDatabaseFilePath = os.path.join(path, 'Project.db')
412
        try:
413
            # Creates or opens a file called mydb with a SQLite3 DB
414
            conn = sqlite3.connect(prjDatabaseFilePath)
415
            # Get a cursor object
416
            cursor = conn.cursor()
417
418
            filePath = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'Scripts', 'Project.Projects.sql')
419
            try:
420
                file = QFile(filePath)
421
                file.open(QFile.ReadOnly)
422
                sql = file.readAll()
423
                sql = str(sql, encoding='utf8')
424
                cursor.executescript(sql)
425
            finally:
426
                file.close()
427
            conn.commit()
428
        # Catch the exception
429
        except Exception as ex:
430
            # Roll back any change if something goes wrong
431
            conn.rollback()
432
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
433
        finally:
434
            # Close the db connection
435
            conn.close()
436
        
437
        return prjDatabaseFilePath
438 09dfdab8 김정우
439
    '''
440 77ba1662 humkyung
        @brief  return line properties
441
        @author humkyung
442
        @date   2018.04.09
443
    '''
444
    def getLineProperties(self):
445
        res = []
446
        try:
447
            # Creates or opens a file called mydb with a SQLite3 DB
448 f5943099 humkyung
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
449 8c5431cc humkyung
            db = sqlite3.connect(dbPath)
450 77ba1662 humkyung
            # Get a cursor object
451
            cursor = db.cursor()
452
453
            sql = "select Name from LineProperties order by Name" 
454
            cursor.execute(sql)
455
            rows = cursor.fetchall()
456
            for row in rows:
457
                res.append(row[0])
458
        # Catch the exception
459 7eb77e34 humkyung
        except Exception as ex:
460 77ba1662 humkyung
            # Roll back any change if something goes wrong
461
            db.rollback()
462 7eb77e34 humkyung
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
463 77ba1662 humkyung
        finally:
464
            # Close the db connection
465
            db.close()
466
467
        return res
468
469
    '''
470 09dfdab8 김정우
        @brief      Insert New Project Info
471
        @author     Jeongwoo
472
        @date       2018.04.06
473 2709dc9f humkyung
        @history    humkyung 2018.04.19 use getPrjDatabasePath function instead of PROJECT_DB_PATH variable
474 09dfdab8 김정우
    '''
475
    def insertProjectInfo(self, dir):
476 2709dc9f humkyung
        try:
477
            prjDatabaseFilePath = self.getPrjDatabasePath()
478
            conn = sqlite3.connect(prjDatabaseFilePath)
479
            folderName = dir.split('/')[-1]
480
            if folderName:
481
                nowDate = datetime.datetime.now().strftime('%Y.%m.%d %H:%M')
482
                sql = "INSERT INTO Projects(Name, Path, CreatedDate, UpdatedDate) VALUES('" + folderName + "', '" + dir + "', '" + nowDate + "', '" + nowDate + "')"
483
                cur = conn.cursor()
484
                cur.execute(sql)
485
                conn.commit()
486
            else:
487
                print("Empty folder name")
488
        except Exception as ex:
489
            # Roll back any change if something goes wrong
490
            conn.rollback()
491
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
492
        finally:
493 09dfdab8 김정우
            conn.close()
494
495
    '''
496 2b474929 김정우
        @brief      Update Project UpdatedDate Field
497 09dfdab8 김정우
        @author     Jeongwoo
498
        @date       2018.04.06
499 2709dc9f humkyung
        @history    humkyung 2018.04.19 use getPrjDatabasePath function instead of PROJECT_DB_PATH variable
500 09dfdab8 김정우
    '''
501
    def updateProjectUpdatedDate(self, id):
502 2709dc9f humkyung
        try:
503
            prjDatabaseFilePath = self.getPrjDatabasePath()
504
            conn = sqlite3.connect(prjDatabaseFilePath)
505
            nowDate = datetime.datetime.now().strftime('%Y.%m.%d %H:%M')
506
            sql = '''
507
                UPDATE Projects
508
                SET UpdatedDate = ?
509
                WHERE Id = ?
510
            '''
511
            cur = conn.cursor()
512
            cur.execute(sql, (nowDate, id))
513
            conn.commit()
514
        except Exception as ex:
515
            # Roll back any change if something goes wrong
516
            conn.rollback()
517
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
518
        finally:
519
            conn.close()
520 dc620556 humkyung
521
    '''
522
        @brief  get project list from database
523 2709dc9f humkyung
        @history    humkyung 2018.04.18 add only project which's project exists
524 dc620556 humkyung
    '''
525
    def getProjectList(self):
526
        from Project import Project
527
528
        projectList = []
529
530
        try:
531
            conn = sqlite3.connect(self.getPrjDatabasePath())
532
            cursor = conn.cursor()
533 2709dc9f humkyung
            sql = 'SELECT id,name,path,createddate,updateddate  FROM Projects ORDER BY UpdatedDate DESC'
534 dc620556 humkyung
            try:
535
                cursor.execute(sql)
536
                rows = cursor.fetchall()
537
                for row in rows:
538 2709dc9f humkyung
                    if os.path.isdir(row[2]):   # check if folder exists
539
                        projectList.append(Project(row[0], row[1], row[2], row[3], row[4]))
540 dc620556 humkyung
            except Exception as ex:
541
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
542
        finally:
543
            conn.close()
544
545
        return projectList
546
547
    '''
548 e4b3e191 humkyung
        @brief  get sliding window size
549 8c5431cc humkyung
        @author humkyung
550 e4b3e191 humkyung
    '''
551
    def getSlidingWindowSize(self):
552
        res = [10,10]
553
        try:
554 8c5431cc humkyung
            configs = self.getConfigs('Sliding Window')
555
            for config in configs:
556
                if config.key == 'Width':
557
                    res[0] = int(config.value)
558
                elif config.key == 'Height':
559
                    res[1] = int(config.value)
560
        # Catch the exception
561
        except Exception as ex:
562
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
563
        
564
        return res
565
566
    '''
567
        @brief  get line no configuration
568
        @author humkyung
569
        @date   2018.04.16
570
    '''
571
    def getLineNoConfiguration(self):
572
        res = None
573
        try:
574 e4b3e191 humkyung
            # Creates or opens a file called mydb with a SQLite3 DB
575 f5943099 humkyung
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
576 8c5431cc humkyung
            conn = sqlite3.connect(dbPath)
577 e4b3e191 humkyung
            # Get a cursor object
578 dc620556 humkyung
            cursor = conn.cursor()
579 e4b3e191 humkyung
580 8c5431cc humkyung
            delimiter = None
581
            sql = "select * from configuration where section='Line No' and key='Delimiter"
582 e4b3e191 humkyung
            cursor.execute(sql)
583
            rows = cursor.fetchall()
584 8c5431cc humkyung
            if len(rows) == 1:
585
                delimiter = rows[0][2]
586
587
            if delimiter is not None:
588
                sql = "select * from configuration where section='Line No' and key='Configuration'"
589
                cursor.execute(sql)
590
                rows = cursor.fetchall()
591
                if len(rows) == 1:
592
                    res = rows[0][2].split(delimiter)
593 e4b3e191 humkyung
        # Catch the exception
594 8c5431cc humkyung
        except Exception as ex:
595 e4b3e191 humkyung
            # Roll back any change if something goes wrong
596 dc620556 humkyung
            conn.rollback()
597 8c5431cc humkyung
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
598 e4b3e191 humkyung
        finally:
599
            # Close the db connection
600 dc620556 humkyung
            conn.close()
601 e4b3e191 humkyung
        
602
        return res
603
604 35d6d96c 김정우
    '''
605 5278f161 humkyung
        @brief  get area list
606 8c5431cc humkyung
        @author humkyung
607 5278f161 humkyung
    '''
608
    def getAreaList(self):
609
        if len(self._areas) == 0:
610
            try:
611
                # Creates or opens a file called mydb with a SQLite3 DB
612 8c5431cc humkyung
                dbPath = self.getCurrentProject().getDbFilePath() + "/ITI_PID.db"
613
                conn = sqlite3.connect(dbPath)
614 5278f161 humkyung
                # Get a cursor object
615
                cursor = conn.cursor()
616
617
                sql = "select * from configuration where section='Area'"
618
                cursor.execute(sql)
619
                rows = cursor.fetchall()
620
                for row in rows:
621
                    area = Area()
622
                    area.name = row[1]
623
                    tokens = row[2].split(',')
624
                    area.x = float(tokens[0])
625
                    area.y = float(tokens[1])
626
                    area.width = float(tokens[2])
627
                    area.height = float(tokens[3])
628
                    self._areas.append(area)
629
            # Catch the exception
630 02294b59 humkyung
            except Exception as ex:
631 5278f161 humkyung
                # Roll back any change if something goes wrong
632
                conn.rollback()
633 8c5431cc humkyung
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
634 5278f161 humkyung
            finally:
635
                # Close the db connection
636
                conn.close()
637
        
638
        return self._areas 
639
640
    '''
641 528bc774 humkyung
        @brief  get area of given name
642
        @author humkyung
643
        @date   2018.04.07
644
    '''
645
    def getArea(self, name):
646
        areas = self.getAreaList()
647
        matches = [area for area in areas if area.name==name]
648
        if 1 == len(matches): return matches[0]
649
650
        return None
651
652
    '''
653 8c5431cc humkyung
        @brief  get configurations
654
        @author humkyung
655
        @date   2018.04.16
656
    '''
657
    def getConfigs(self, section, key=None):
658
        res = []
659
660
        try:
661
            # Creates or opens a file called mydb with a SQLite3 DB
662 f5943099 humkyung
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
663 8c5431cc humkyung
            conn = sqlite3.connect(dbPath)
664
            # Get a cursor object
665
            cursor = conn.cursor()
666
667
            if key is not None:
668
                sql = "select * from configuration where section='{}' and key='{}'".format(section, key)
669
            else:
670
                sql = "select * from configuration where section='{}'".format(section)
671
672
            cursor.execute(sql)
673
            rows = cursor.fetchall()
674
            for row in rows:
675
                res.append(Config(row[0], row[1], row[2]))
676
        # Catch the exception
677
        except Exception as ex:
678
            # Roll back any change if something goes wrong
679
            conn.rollback()
680
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
681
        finally:
682
            # Close the db connection
683
            conn.close()
684
685
        return res
686
687
    '''
688
        @brief  save configurations
689
        @author humkyung
690
        @date   2018.04.16
691
    '''
692
    def saveConfigs(self, configs):
693
        try:
694
            # Creates or opens a file called mydb with a SQLite3 DB
695
            dbPath = self.getCurrentProject().getDbFilePath() + "/ITI_PID.db"
696
            conn = sqlite3.connect(dbPath)
697
            # Get a cursor object
698
            cursor = conn.cursor()
699
700
            for config in configs:
701
                sql = "insert or replace into configuration values('{}','{}','{}')".format(config.section, config.key, config.value)
702
                cursor.execute(sql)
703
            conn.commit()
704
        # Catch the exception
705
        except Exception as ex:
706
            # Roll back any change if something goes wrong
707
            conn.rollback()
708
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
709
        finally:
710
            # Close the db connection
711
            conn.close()
712
713
    '''
714 5278f161 humkyung
        @brief  set area list
715
    '''
716
    def setAreaList(self, areas):
717
        for area in areas:
718
            matches = [x for x in self._areas if x.name==area.name]
719
            if 1 == len(matches):
720
                matches[0].x = area.x
721
                matches[0].y = area.y
722
                matches[0].width = area.width
723
                matches[0].height = area.height
724
            elif 0 == len(matches):
725
                self._areas.append(area)
726
727
        try:
728
            # Creates or opens a file called mydb with a SQLite3 DB
729 8c5431cc humkyung
            dbPath = self.getCurrentProject().getDbFilePath() + "/ITI_PID.db"
730
            conn = sqlite3.connect(dbPath)
731 5278f161 humkyung
            # Get a cursor object
732
            cursor = conn.cursor()
733
734
            for area in self._areas:
735
                sql = "insert or replace into configuration values('Area','{}','{},{},{},{}')".format(area.name, area.x, area.y, area.width, area.height)
736
                cursor.execute(sql)
737
738
            conn.commit()
739
        # Catch the exception
740 8c5431cc humkyung
        except Exception as ex:
741 5278f161 humkyung
            # Roll back any change if something goes wrong
742
            conn.rollback()
743 8c5431cc humkyung
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
744 5278f161 humkyung
        finally:
745
            # Close the db connection
746
            conn.close()
747 2b474929 김정우
            
748 5278f161 humkyung
    '''
749 35d6d96c 김정우
        @brief  get symbol name list
750
    '''
751
    def getSymbolNameList(self):
752
        symbolNametList = []
753
754
        try:
755 02294b59 humkyung
            dbPath = self.getCurrentProject().getDbFilePath() + "/ITI_PID.db"
756
757
            conn = sqlite3.connect(dbPath)
758 35d6d96c 김정우
            cursor = conn.cursor()
759
            sql = 'SELECT * FROM SymbolName'
760
            try:
761
                cursor.execute(sql)
762
                rows = cursor.fetchall()
763
                for row in rows:
764 2b474929 김정우
                    symbolNametList.append(row[2]) # Name String
765 35d6d96c 김정우
            except Exception as ex:
766
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
767
        finally:
768
            conn.close()
769
770
        return symbolNametList
771
772 1b502652 김정우
    '''
773 2b474929 김정우
        @brief      get symbol name list by symbol Type
774
        @author     Jeongwoo
775
        @date       18.04.06
776
        @history    .
777
    '''
778
    def getSymbolNameListByType(self, type):
779
        symbolNametList = []
780
781
        try:
782 02294b59 humkyung
            dbPath = self.getCurrentProject().getDbFilePath() + "/ITI_PID.db"
783
784
            conn = sqlite3.connect(dbPath)
785 2b474929 김정우
            cursor = conn.cursor()
786
            sql = ''
787
            if type is not None:
788
                sql = 'SELECT * FROM SymbolName WHERE type = "' + type + '"'
789
                try:
790
                    cursor.execute(sql)
791
                    rows = cursor.fetchall()
792
                    for row in rows:
793
                        symbolNametList.append(row[2]) # Name String
794
                except Exception as ex:
795
                    print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
796
        finally:
797
            conn.close()
798
799
        return symbolNametList
800
801
    '''
802 1b502652 김정우
        @brief  delete added symbol data
803
    '''
804 2b474929 김정우
    def deleteSymbol(self, fileName):
805 1b502652 김정우
        ret = False
806
        try:
807 d52b3462 김정우
            dbPath = self.getCurrentProject().getPath() + "/db/ITI_PID.db"
808 1b502652 김정우
            conn = sqlite3.connect(dbPath)
809
            cursor = conn.cursor()
810 2b474929 김정우
            sql = "DELETE FROM Symbol WHERE name = ?"
811 1b502652 김정우
            try:
812 2b474929 김정우
                cursor.execute(sql, (fileName,))
813 1b502652 김정우
                conn.commit()
814
                ret = True
815
            except Exception as ex:
816
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
817
                ret = False
818
        finally:
819
            conn.close()
820 2b474929 김정우
            return (ret, fileName)
821 ed2b4ab0 김정우
        
822 d52b3462 김정우
    '''
823 ed2b4ab0 김정우
        @brief  get symbol name
824 8d35dc6e 김정우
        @history    18.04.24    Jeongwoo    Add isExceptDetect Field
825 d52b3462 김정우
    '''
826
    def getSymbolByQuery(self, fieldName, param):
827 936111d1 김정우
        ret = None
828 d52b3462 김정우
829
        try:
830 8d35dc6e 김정우
            dbPath = self.getCurrentProject().getDbFilePath() + "/ITI_PID.db"
831 d52b3462 김정우
            conn = sqlite3.connect(dbPath)
832
            cursor = conn.cursor()
833
            sql = 'SELECT * FROM Symbol WHERE ' + fieldName + ' = "' + param + '"'
834
            try:
835
                cursor.execute(sql)
836
                rows = cursor.fetchall()
837
                if rows is not None and len(rows) > 0:
838 936111d1 김정우
                    symbolTuple = rows[0]
839
                    ret = symbol.SymbolBase(symbolTuple[1], symbolTuple[2], symbolTuple[3], symbolTuple[4]
840
                                            , symbolTuple[5], symbolTuple[6], symbolTuple[7], symbolTuple[8], symbolTuple[9]
841 8d35dc6e 김정우
                                            , symbolTuple[10], symbolTuple[11], symbolTuple[12], symbolTuple[13], symbolTuple[14], symbolTuple[0]) ## uid is last item
842 3926c898 김정우
                    #ret = symbol.SymbolBase(symbolTuple[1], symbolTuple[2], symbolTuple[3], symbolTuple[4]
843
                    #                        , symbolTuple[5], symbolTuple[6], symbolTuple[7], symbolTuple[8], symbolTuple[9]
844
                    #                        , symbolTuple[10], symbolTuple[11], symbolTuple[12], symbolTuple[13], symbolTuple[14], symbolTuple[0]) ## uid is last item
845 d52b3462 김정우
            except Exception as ex:
846
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
847
        finally:
848
            conn.close()
849
850 936111d1 김정우
        return ret
851 d52b3462 김정우
852 936111d1 김정우
    '''
853 ed2b4ab0 김정우
        @brief  get symbol name list
854 8d35dc6e 김정우
        @history    18.04.24    Jeongwoo    Add isExceptDetect Field
855 ed2b4ab0 김정우
    '''
856
    def getSymbolListByQuery(self, fieldName=None, param=None):
857
        ret = []
858
859
        try:
860 8d35dc6e 김정우
            dbPath = self.getCurrentProject().getDbFilePath() + "/ITI_PID.db"
861 ed2b4ab0 김정우
            conn = sqlite3.connect(dbPath)
862
            cursor = conn.cursor()
863
            if fieldName is not None and param is not None:
864
                sql = 'SELECT * FROM Symbol WHERE ' + fieldName + ' = "' + param + '"'
865
            else:
866
                sql = 'SELECT * FROM Symbol'
867
            try:
868
                cursor.execute(sql)
869
                rows = cursor.fetchall()
870
                if rows is not None and len(rows) > 0:
871
                    for symbolTuple in rows:
872
                        sym = symbol.SymbolBase(symbolTuple[1], symbolTuple[2], symbolTuple[3], symbolTuple[4]
873
                                                , symbolTuple[5], symbolTuple[6], symbolTuple[7], symbolTuple[8], symbolTuple[9]
874 8d35dc6e 김정우
                                                , symbolTuple[10], symbolTuple[11], symbolTuple[12], symbolTuple[13], symbolTuple[14], symbolTuple[0]) ## uid is last item
875 ed2b4ab0 김정우
                        ret.append(sym)
876
            except Exception as ex:
877
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
878
        finally:
879
            conn.close()
880
881
        return ret
882
883
    '''
884 f5943099 humkyung
        @brief      get nominal pipe size
885
        @author     humkyung
886
        @date       2018.04.20
887
        @history    humkyung 2018.04.24 read MetricStr column and set size unit
888 02294b59 humkyung
    '''
889
    def getNomialPipeSizeData(self):
890
        res = []
891
        try:
892 f5943099 humkyung
            configs = self.getConfigs('Line No', 'Size Unit')
893
            sizeUnit = configs[0].value if 1 == len(configs) else 'Metric'
894
895 02294b59 humkyung
            # Creates or opens a file called mydb with a SQLite3 DB
896 f5943099 humkyung
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
897 02294b59 humkyung
            conn = sqlite3.connect(dbPath)
898
            # Get a cursor object
899
            cursor = conn.cursor()
900
901 f5943099 humkyung
            sql = "select Code,Metric,Inch,InchStr,MetricStr from 'NOMINAL PIPE SIZE'"
902 02294b59 humkyung
            cursor.execute(sql)
903
            rows = cursor.fetchall()
904
            for row in rows:
905 f5943099 humkyung
                pipeSize = NominalPipeSize(row[0], float(row[1]) if row[1] is not None else -1, float(row[2]) if row[2] is not None else -1, row[3], row[4])
906
                pipeSize.sizeUnit = sizeUnit
907
                res.append(pipeSize)
908 02294b59 humkyung
        # Catch the exception
909
        except Exception as ex:
910
            # Roll back any change if something goes wrong
911
            conn.rollback()
912
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
913
        finally:
914
            # Close the db connection
915
            conn.close()
916
917
        return res
918 467d9e29 humkyung
    
919
    '''
920
        @brief      get equipment data list
921
        @author     humkyung
922
        @date       2018.05.03
923
    '''
924
    def getEquipmentDataList(self):
925
        from EquipmentData import EquipmentData
926
927
        if not self.equipmentDataList:
928
            try:
929
                # Creates or opens a file called mydb with a SQLite3 DB
930
                dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
931
                conn = sqlite3.connect(dbPath)
932
                # Get a cursor object
933
                cursor = conn.cursor()
934
935
                sql = 'select TAG_NO from EQUIPMENT_DATA_LIST'
936
                cursor.execute(sql)
937
                rows = cursor.fetchall()
938
                for row in rows:
939
                    data = EquipmentData(row[0])
940
                    self.equipmentDataList.append(data)
941
            # Catch the exception
942
            except Exception as ex:
943
                # Roll back any change if something goes wrong
944
                conn.rollback()
945
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
946
            finally:
947
                # Close the db connection
948
                conn.close()
949
950
        return self.equipmentDataList 
951
952
    '''
953
        @brief      set equipment data list
954
        @author     humkyung
955
        @date       2018.05.03
956
    '''
957
    def setEquipmentDataList(self, dataList):
958
        try:
959
            # Creates or opens a file called mydb with a SQLite3 DB
960
            dbPath = os.path.join(self.getCurrentProject().getDbFilePath(), 'ITI_PID.db')
961
            conn = sqlite3.connect(dbPath)
962
            # Get a cursor object
963
            cursor = conn.cursor()
964
965
            for data in dataList:
966
                sql = "insert or replace into EQUIPMENT_DATA_LIST(UID,TAG_NO) values(lower(hex(randomblob(16))),'{}')".format(data.tagNo)
967
                cursor.execute(sql)
968
            conn.commit()
969
970
            self.equipmentDataList = dataList
971
        # Catch the exception
972
        except Exception as ex:
973
            # Roll back any change if something goes wrong
974
            conn.rollback()
975
            print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
976
        finally:
977
            # Close the db connection
978
            conn.close()
979 02294b59 humkyung
980
    '''
981 936111d1 김정우
        @brief  get IsOriginDetect ComboBox Items
982
    '''
983
    def getIsOriginDetectComboBoxItems(self):
984
        return [("원본 도면", 0), ("텍스트 제거 도면", 1)]
985
986
    '''
987
        @brief  get IsOriginDetect ComboBox Items
988
    '''
989
    def getOcrOptionComboBoxItems(self):
990
        return [("OCR 미적용", 0), ("일반 심볼", 1), ("Instrument 계통", 2)]
991 ed2b4ab0 김정우
    
992 936111d1 김정우
    '''
993 2b474929 김정우
        @brief      Return Symbol Type Items
994
        @author     Jeongwoo
995 ed2b4ab0 김정우
        @date       18.04.20
996 2b474929 김정우
        @history    .
997
    '''
998 ed2b4ab0 김정우
    def getSymbolTypeList(self):
999 2b474929 김정우
        symbolTypeList = []
1000
1001
        try:
1002 02294b59 humkyung
            dbPath = self.getCurrentProject().getDbFilePath() + "/ITI_PID.db"
1003
1004
            conn = sqlite3.connect(dbPath)
1005 2b474929 김정우
            cursor = conn.cursor()
1006
            sql = 'SELECT * FROM SymbolType ORDER BY type ASC'
1007
            try:
1008
                cursor.execute(sql)
1009
                rows = cursor.fetchall()
1010
                for row in rows:
1011
                    symbolTypeList.append(row[1]) # Type String
1012
            except Exception as ex:
1013
                print('error occured({}) in {}:{}'.format(ex, sys.exc_info()[-1].tb_frame.f_code.co_filename, sys.exc_info()[-1].tb_lineno))
1014
        finally:
1015
            conn.close()
1016 ed2b4ab0 김정우
1017
        return symbolTypeList
1018
1019
    '''
1020
        @brief      Return Symbol Type Items with "None"
1021
        @author     Jeongwoo
1022
        @date       18.04.06
1023
        @history    Seperate SymbolTypeList and "None"
1024
    '''
1025
    def getSymbolTypeComboBoxItems(self):
1026
        symbolTypeList = self.getSymbolTypeList()
1027
        symbolTypeList.insert(0, "None")
1028 2b474929 김정우
1029
        return symbolTypeList
1030
1031
    '''
1032 936111d1 김정우
        @brief  get Base Symbol ComboBox Items
1033
    '''
1034 2b474929 김정우
    def getBaseSymbolComboBoxItems(self, type = None):
1035
        bsymbolNameList = self.getSymbolNameListByType(type)
1036 936111d1 김정우
        bsymbolNameList.sort()
1037
        bsymbolNameList.insert(0, "None")
1038
        return bsymbolNameList
1039
1040
    '''
1041
        @brief  get Additional Symbol ComboBox Items
1042
    '''
1043
    def getAdditionalSymbolComboBoxItems(self):
1044
        asymbolNameList = self.getSymbolNameList()
1045
        asymbolNameList.sort()
1046
        asymbolNameList.insert(0, "None")
1047
        return asymbolNameList
1048
1049
    '''
1050
        @brief  get Additional Symbol's default direction ComboBox Items
1051
    '''
1052
    def getDefaultSymbolDirectionComboBoxItems(self):
1053
        return [("UP", 0), ("DOWN", 2), ("LEFT", 3), ("RIGHT", 1)]
1054
    
1055 e4b3e191 humkyung
    pass
클립보드 이미지 추가 (최대 크기: 500 MB)