def __init__(self): self.events = Queue() self.app = QApplication(sys.argv) self.w = uic.loadUi("main.ui") self.w.setAttribute(Qt.WA_DeleteOnClose, True) self.w.show() self.sattable = self.w.satTable self.satview = self.w.mapCanvas self.scene = QtScene(self.satview) self.pal = QtPalette() self.rendersats = set() self.satcolors = dict() hdr = self.sattable.horizontalHeader() hdr.setSectionResizeMode(0, QHeaderView.ResizeToContents) hdr.setSectionResizeMode(1, QHeaderView.Fixed) hdr.setSectionResizeMode(2, QHeaderView.Fixed) self.w.dtFrom.setDateTime(QDateTime.currentDateTimeUtc()) self.w.dtTo.setDateTime( QDateTime.currentDateTimeUtc().addSecs(3600 * 2) ) self.filters = ["*", "*", "*", "*"] self.selectall = False self.nosats = True self.colchange = False self.connect_sigs()
def update_view_dateTime(self): if self._model.debug_mode: print("Updating view DateTime") if self._model.view_time_int == "custom": # TODO implement custom view time pass else: self._model.view_dateTime_stop = QDateTime.currentDateTimeUtc() if self._model.view_time_int == "1min": self._model.view_dateTime_start = \ self._model.view_dateTime_stop.addSecs(-60) elif self._model.view_time_int == "15min": self._model.view_dateTime_start = \ self._model.view_dateTime_stop.addSecs(-(60 * 15)) elif self._model.view_time_int == "1h": self._model.view_dateTime_start = \ self._model.view_dateTime_stop.addSecs(-(60 * 60)) elif self._model.view_time_int == "1d": self._model.view_dateTime_start = \ self._model.view_dateTime_stop.addDays(-1) elif self._model.view_time_int == "1w": self._model.view_dateTime_start = \ self._model.view_dateTime_stop.addDays(-7) elif self._model.view_time_int == "1m": self._model.view_dateTime_start = \ self._model.view_dateTime_stop.addMonths(-1)
def __init__(self, *args): QtWidgets.QWidget.__init__(self, *args) self.ui = Ui_TimeRange() self.ui.setupUi(self) now = QDateTime.currentDateTimeUtc() self.ui.from_time.setDateTime(now.addSecs(-2 * 60 * 60)) self.ui.to_time.setDateTime(now.addSecs(-1.50 * 60 * 60))
def setToDefault(wdgt=None): if isinstance(wdgt, QDoubleSpinBox) or isinstance(wdgt, QSpinBox): wdgt.setValue(-1) elif isinstance(wdgt, QCheckBox) or isinstance(wdgt, QGroupBox): wdgt.setChecked(False) elif isinstance(wdgt, QDateTimeEdit): val = QDateTime.currentDateTimeUtc() if isinstance(wdgt, QTimeEdit): val = QTime.fromString('0', '0') wdgt.setTime(val) else: wdgt.setDateTime(val) elif isinstance(wdgt, QDateEdit): wdgt.setDate(PyQt5.QtCore.QDate.currentDate()) elif isinstance(wdgt, QTimeEdit): val = QTime.fromString('0', '0') wdgt.setTime(val) elif isinstance(wdgt, QComboBox): wdgt.setCurrentIndex(0) else: wdgt.clear()
def setWidgetDateTime(self, index): tz = str(self.ui.countryList.itemData(index)) currentDateTime = QDateTime.currentDateTimeUtc().toTimeZone( QTimeZone(tz)) self.ui.calendarWidget.setDate(currentDateTime.date()) self.ui.timeEdit.setDateTime(currentDateTime)
def __init__(self): super().__init__() self._amount = 0 self._even_odd = '' self._enable_reset = False self._debug_mode = True self._view_dateTime_start = QDateTime.currentDateTimeUtc() self._view_dateTime_stop = QDateTime.currentDateTimeUtc() self._view_time_int = "1h" self._update_int = 5000 self._console_buffer = "" self._com_mode = False self._data = pd.DataFrame(columns=["Sinus", "Cosinus"]) self.x = np.linspace(-np.pi, np.pi, 201) self.sin = np.sin(self.x) self.cos = 5 * np.cos(self.x)
def getTagDate(self): date_time = QDateTime.currentDateTimeUtc() date = date_time.date() time = date_time.time() tagdate = "%s_%s_%s_%s_%s_%s" % (date.year(), date.month(), date.day(), time.hour(), time.minute(), time.second()) return tagdate
def __init__(self): super().__init__() self.ui = Ui_contact_admin() self.ui.setupUi(self) self.init() # 初始化日期 datetime = QDateTime.currentDateTimeUtc() current_date = datetime.toString('dddd, M/d/yyyy') self.ui.current_date_field.setText(current_date) # 绑定发送邮件 self.ui.submit_btn.clicked.connect(self.send_email)
def __pruneCache(self): """ Private slot to prune outdated cache entries and restart the timer. """ if self.__maxCacheTime > 0: current = QDateTime.currentDateTimeUtc() keysToBeDeleted = [] for key, lastAccessTime in self.__accesStore.items(): if lastAccessTime.secsTo(current) > self.__maxCacheTime: keysToBeDeleted.append(key) for key in keysToBeDeleted: self.remove(key) self.__cacheTimer.start()
def judge_num(self): time2 = QDateTime.currentDateTimeUtc().toString() if Thread4.flag == True: if Thread4.people_num > Thread4.people_limit: mes = time2 +"视频四:"+ str("人数为:%d ,超过阈值:%d,报警信息已发送" % (Thread4.people_num, Thread4.people_limit)) self.changeList.emit(mes) Thread4.flag = False else: pass else: if Thread4.people_num > Thread4.people_limit: mes = time2 +"视频四:"+ str("人数为:%d ,超过阈值:%d,报警信息已发送" % (Thread4.people_num, Thread4.people_limit)) self.changeList.emit(mes) else: mes = time2 +"视频四:"+str("人数为:%d ,低于阈值:%d,解除信号已发送" % (Thread4.people_num, Thread4.people_limit)) self.changeList.emit(mes) Thread4.flag = True pass
def onAction(self): dlg = QDialog() ui = Ui_QueryCallisto() ui.setupUi(dlg) now = QDateTime.currentDateTimeUtc() ui.start_time.setDateTime(now.addSecs(-2 * 60 * 60)) ui.end_time.setDateTime(now.addSecs(-1.50 * 60 * 60)) if dlg.exec_(): start_time = ui.start_time.dateTime().toString( QtCore.Qt.ISODate).replace("T", " ") end_time = ui.end_time.dateTime().toString( QtCore.Qt.ISODate).replace("T", " ") executeLongRunningTask( CallistoSpectrogram.from_range, [ui.instrument.currentText(), start_time, end_time], "Downloading", self._openSpectrogram)
def insert_report(self, money): # 获取goods_id的列表 columnCount = self.tableView.rowCount() # print(columnCount) goods_id = [] for i in range(columnCount): goods_id.append(self.tableView.item(i, 0).text()) # 表中的各项数据 goods_id_str = str(goods_id) num = self.total_num price = self.total_price currentTime = QDateTime.currentDateTimeUtc().toLocalTime().toString() id = 0 # 获取report 表中的行数,确定id的大小 db_2 = QSqlDatabase.addDatabase('QSQLITE') db_2.setDatabaseName('databases/goods.sqlite') db_2.open() db2 = QSqlQuery(db_2) db2.exec_("SELECT COUNT(id) FROM report;") print("select count") if db2.next(): id = db2.value(0)+1 # 数据插入 report 表 db_3 = QSqlDatabase.addDatabase('QSQLITE') db_3.setDatabaseName('databases/goods.sqlite') db_3.open() query = QSqlQuery(db_3) query.prepare("insert into report values(?,?,?,?,?,?)") query.addBindValue(id) query.addBindValue(num) query.addBindValue(price) query.addBindValue(money) query.addBindValue(goods_id_str) query.addBindValue(currentTime) if query.exec_(): print("success") else: text = query.lastError().text() QMessageBox.warning(self, "错误", text, QMessageBox.Yes)
def get(self, key): """ Public method to get an entry from the cache given its key. If the key is present in the cache, it is moved to the MRU position. @param key key of the item to be retrieved @type any hashable type that can be used as a dict key @return cached item for the given key or None, if the key is not present @rtype object or None """ if key in self.__store: self.__hits += 1 self.__moveLast(key) self.__accesStore[key] = QDateTime.currentDateTimeUtc() return self.__store[key] else: self.__misses += 1 return None
def add(self, key, item): """ Public method to add an item to the cache. If the key is already in use, the cached item is replaced by the new one given and is moved to the MRU position @param key key of the item to be retrieved @type any hashable type that can be used as a dict key @param item item to be cached under the given key @type object """ if key in self.__store: self.__moveLast(key) else: self.__keyList.append(key) self.__store[key] = item self.__accesStore[key] = QDateTime.currentDateTimeUtc() self.__adjustToSize() self.__maxsize = max(self.__maxsize, len(self.__keyList))
class videoDetectThread(QThread): changeNum = pyqtSignal(int) people_num = 0 people_limit = 100 add_img = pyqtSignal(bytes) add_res = pyqtSignal(str) set_num = pyqtSignal(int) time2 = QDateTime.currentDateTimeUtc().toString() encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), 60] video_idx = " " def setPeopleLimit(self, limit): self.people_limit = limit def setVideoInd(self, vidx): self.video_idx = vidx def detectFun(self, image_data): self.people_num = dt.detect_img(image_data) #Thread4.people_num = dt.detect_img(rgbImage) self.changeNum.emit(self.people_num) self.set_num.emit(self.people_num) #self.judge_num() # 组合检测结果并用json打包后放入结果池中 detect_res = {} detect_res['video_idx'] = self.video_idx detect_res['time'] = self.time2 detect_res['people_num'] = self.people_num detect_res_str = json.dumps(detect_res) self.add_res.emit(detect_res_str) # 压缩图片,并将图片放入图片池中,以字节流的形式保存 result, imencode = cv2.imencode('.jpg', image_data, self.encode_param) imencode = np.array(imencode) img_str = imencode.tostring() self.add_img.emit(img_str)
def __init__(self): self.client = HEKClient() self.query_id = 0 ToolController.__init__(self) self._view = QtWidgets.QWidget() self._ui = Ui_DownloadEvent() self._ui.setupUi(self._view) self._ui.message_box.hide() self.table = self._ui.table self._ui.event_type.addItems([c().item.upper() for c in hek.attrs.EventType.__subclasses__()]) header = self.table.horizontalHeader() for i in range(self.table.columnCount()): header.setSectionResizeMode(i, QtWidgets.QHeaderView.ResizeToContents) now = QDateTime.currentDateTimeUtc() self._ui.from_date.setDateTime(now.addSecs(-2 * 60 * 60)) self._ui.to_date.setDateTime(now.addSecs(-1.50 * 60 * 60)) self._ui.search_button.clicked.connect(self._onSearch) self._ui.query_button.clicked.connect(self._onQuery)
elif density == 'XXXHDPI': height *= 4 coin_id = 0 for coin_data in data['coins']: action = coin_data['action'] coin = dest_model.record() for field in fields: if field.name in ('id', 'image', 'obverseimg', 'reverseimg'): continue if field.name in SKIPPED_FIELDS: continue if field.name == 'updatedat': currentTime = QDateTime.currentDateTimeUtc() coin.setValue('updatedat', currentTime.toString(Qt.ISODate)) continue if field.name in coin_data: coin.setValue(field.name, coin_data[field.name]) image = QImage() for field_name in ('obverseimg', 'reverseimg'): if field_name in coin_data: img_file_name = os.path.join(image_path, coin_data[field_name]) img_file = open(img_file_name, 'rb') img_data = img_file.read() img_file.close() query = QSqlQuery(db)
def write_pot(self, metaData): quote = "\"" newLine = "\n" location = os.path.join(self.projectURL, self.translation_folder, self.projectName + ".pot") file = open(location, "w", newline="", encoding="utf8") file.write("msgid " + quote + quote + newLine) file.write("msgstr " + quote + quote + newLine) date = QDateTime.currentDateTimeUtc().toString(Qt.ISODate) file.write(quote + "POT-Creation-Date:" + date + "\\n" + quote + newLine) file.write(quote + "Content-Type: text/plain; charset=UTF-8\\n" + quote + newLine) file.write(quote + "Content-Transfer-Encoding: 8bit\\n" + quote + newLine) file.write( quote + "X-Generator: Krita Comics Project Manager Tools Plugin\\n" + quote + newLine) file.write(newLine) file.write("#. Title of the work" + newLine) file.write("msgctxt \"@meta-title\"" + newLine) file.write("msgid " + quote + metaData.get("title", "") + quote + newLine) file.write("msgstr " + quote + quote + newLine) file.write(newLine) file.write("#. The summary" + newLine) file.write("msgctxt \"@meta-summary\"" + newLine) file.write("msgid " + quote + metaData.get("summary", "") + quote + newLine) file.write("msgstr " + quote + quote + newLine) file.write(newLine) file.write("#. The keywords, these need to be comma separated." + newLine) file.write("msgctxt \"@meta-keywords\"" + newLine) file.write("msgid " + quote + metaData.get("keywords", "") + quote + newLine) file.write("msgstr " + quote + quote + newLine) file.write(newLine) file.write("#. The header that will prepend translator's notes" + newLine) file.write("msgctxt \"@meta-translator\"" + newLine) file.write("msgid " + quote + metaData.get("transnotes", "") + quote + newLine) file.write("msgstr " + quote + quote + newLine) for i in range(len(self.pageTitleKeys)): title = self.pageTitleKeys[i] file.write(newLine) file.write("msgctxt " + quote + "@page-title" + quote + newLine) file.write("msgid " + quote + title + quote + newLine) file.write("msgstr " + quote + quote + newLine) for key in self.translationKeys: if key != self.languageKey: file.write(newLine) if "translComment" in self.translationDict[key].keys(): file.write("# " + self.translationDict[key]["translator"] + newLine) if "extract" in self.translationDict[key].keys(): file.write("#. " + self.translationDict[key]["extract"] + newLine) string = self.translationDict[key]["text"] uniqueContext = False if string != key: uniqueContext = True string = string.replace(quote, "\\\"") string = string.replace("\'", "\\\'") string = string.replace("#", "\\#") if uniqueContext: file.write("msgctxt " + quote + key + quote + newLine) file.write("msgid " + quote + string + quote + newLine) file.write("msgstr " + quote + quote + newLine) file.close() print("CPMT: Translations have been written to:", location)
def run(self): # print(Thread.videoN) cap = cv2.VideoCapture(Thread4.videoN) qDebug('Worker.on_timeout get called from: %s' % hex(int(QThread.currentThreadId()))) # counter = 0 encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), 60] count = 0 while (cap.isOpened() == True): ret, frame = cap.read() name_part = 0 if ret: rgbImage = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) # cv2.imwrite(os.curdir()+'/out/'+videoName+'_'+str(name_part)+'.jpg', rgbImage) time2 = QDateTime.currentDateTimeUtc().toString() # print(np.array(rgbImage).shape) mes = time2 + str(np.array(rgbImage).shape) # self.changeList.emit(mes) # convertToQtFormat = QtGui.QImage(rgbImage.data, rgbImage.shape[1], rgbImage.shape[0], # QImage.Format_RGB888) # 在这里可以对每帧图像进行处理, # p = convertToQtFormat.scaled(640, 480, Qt.KeepAspectRatio) if count % freq == 0: Thread4.people_num = dt.detect_img(rgbImage) self.changeNum.emit(Thread4.people_num) self.judge_num() # 组合检测结果并用json打包后放入结果池中 detect_res = {} detect_res['video_idx'] = "video4" detect_res['time'] = time2 detect_res['people_num'] = Thread4.people_num detect_res_str = json.dumps(detect_res) self.add_res.emit(detect_res_str) # 压缩图片,并将图片放入图片池中,以字节流的形式保存 result, imencode = cv2.imencode('.jpg', frame, encode_param) imencode = np.array(imencode) img_str = imencode.tostring() self.add_img.emit(img_str) put_text = "people:" + str(Thread4.people_num) image_h, image_w, image_c = rgbImage.shape line_size, line_wid = judgeSize(image_w) img_with_num = cv2.putText(rgbImage, put_text, (int(image_w * 0.8), int(image_h * 0.1)), cv2.FONT_HERSHEY_COMPLEX, line_size, (255, 0, 0), line_wid, lineType=cv2.LINE_4) img_convertToQtFormat = QtGui.QImage(img_with_num.data, img_with_num.shape[1], img_with_num.shape[0], QImage.Format_RGB888) # 在这里可以对每帧图像进行处理, p_with_num = img_convertToQtFormat.scaled(640, 480, Qt.KeepAspectRatio) # 更新主界面的图片显示 self.changePixmap.emit(p_with_num) time.sleep(sleep_time) # 控制视频播放的速度 name_part += 1 count = (count + 1) % freq else: break
def writeJson(configDictionary={}): basedata = {} metadata = {} authorList = [] taglist = [] listOfRoles = [ "Writer", "Inker", "Creator", "Editor", "Cartoonist", "Colorist", "Letterer", "Penciller", "Painter", "Cover", "Artist" ] if "authorList" in configDictionary.keys(): for authorE in range(len(configDictionary["authorList"])): author = {} authorDict = configDictionary["authorList"][authorE] stringName = [] if "last-name" in authorDict.keys(): stringName.append(authorDict["last-name"]) if "first-name" in authorDict.keys(): stringName.append(authorDict["first-name"]) if "nickname" in authorDict.keys(): stringName.append("(" + authorDict["nickname"] + ")") author["person"] = ",".join(stringName) if "role" in authorDict.keys(): role = str(authorDict["role"]).title() if "editor" in role.lower(): role = "Editor" if "cover" in role.lower(): role = "Cover" if role in listOfRoles: author["role"] = role authorList.append(author) if "characters" in configDictionary.keys(): for character in configDictionary["characters"]: taglist.append(character) if "format" in configDictionary.keys(): for item in configDictionary["format"]: taglist.append(item) if "otherKeywords" in configDictionary.keys(): for item in configDictionary["otherKeywords"]: taglist.append(item) if "seriesName" in configDictionary.keys(): metadata["series"] = configDictionary["seriesName"] if "title" in configDictionary.keys(): metadata["title"] = configDictionary["title"] else: metadata["title"] = "Unnamed comic" if "publisherName" in configDictionary.keys(): metadata["publisher"] = configDictionary["publisherName"] if "publishingDate" in configDictionary.keys(): date = QDate.fromString(configDictionary["publishingDate"], Qt.ISODate) metadata["publicationMonth"] = date.month() metadata["publicationYear"] = date.year() if "seriesNumber" in configDictionary.keys(): metadata["issue"] = configDictionary["seriesNumber"] if "seriesVolume" in configDictionary.keys(): metadata["volume"] = configDictionary["seriesVolume"] if "genre" in configDictionary.keys(): if isinstance(configDictionary["genre"], dict): listKeys = [] for key in configDictionary["genre"].keys(): listKeys.append(key) metadata["genre"] = listKeys else: metadata["genre"] = configDictionary["genre"] if "language" in configDictionary.keys(): metadata["language"] = QLocale.languageToString( QLocale(configDictionary["language"]).language()) metadata["credits"] = authorList metadata["tags"] = taglist if "summary" in configDictionary.keys(): metadata["comments"] = configDictionary["summary"] else: metadata["comments"] = "File generated without summary" # basedata["appID"] = "Krita" basedata["lastModified"] = QDateTime.currentDateTimeUtc().toString( Qt.ISODate) basedata["ComicBookInfo/1.0"] = metadata return json.dumps(basedata)
def write_opf_file(path, configDictionary, htmlFiles, pagesList, coverpageurl, coverpagehtml, listofSpreads): # marc relators # This has several entries removed to reduce it to the most relevant entries. marcRelators = { "abr": i18n("Abridger"), "acp": i18n("Art copyist"), "act": i18n("Actor"), "adi": i18n("Art director"), "adp": i18n("Adapter"), "ann": i18n("Annotator"), "ant": i18n("Bibliographic antecedent"), "arc": i18n("Architect"), "ard": i18n("Artistic director"), "art": i18n("Artist"), "asn": i18n("Associated name"), "ato": i18n("Autographer"), "att": i18n("Attributed name"), "aud": i18n("Author of dialog"), "aut": i18n("Author"), "bdd": i18n("Binding designer"), "bjd": i18n("Bookjacket designer"), "bkd": i18n("Book designer"), "bkp": i18n("Book producer"), "blw": i18n("Blurb writer"), "bnd": i18n("Binder"), "bpd": i18n("Bookplate designer"), "bsl": i18n("Bookseller"), "cll": i18n("Calligrapher"), "clr": i18n("Colorist"), "cns": i18n("Censor"), "cov": i18n("Cover designer"), "cph": i18n("Copyright holder"), "cre": i18n("Creator"), "ctb": i18n("Contributor"), "cur": i18n("Curator"), "cwt": i18n("Commentator for written text"), "drm": i18n("Draftsman"), "dsr": i18n("Designer"), "dub": i18n("Dubious author"), "edt": i18n("Editor"), "etr": i18n("Etcher"), "exp": i18n("Expert"), "fnd": i18n("Funder"), "ill": i18n("Illustrator"), "ilu": i18n("Illuminator"), "ins": i18n("Inscriber"), "lse": i18n("Licensee"), "lso": i18n("Licensor"), "ltg": i18n("Lithographer"), "mdc": i18n("Metadata contact"), "oth": i18n("Other"), "own": i18n("Owner"), "pat": i18n("Patron"), "pbd": i18n("Publishing director"), "pbl": i18n("Publisher"), "prt": i18n("Printer"), "sce": i18n("Scenarist"), "scr": i18n("Scribe"), "spn": i18n("Sponsor"), "stl": i18n("Storyteller"), "trc": i18n("Transcriber"), "trl": i18n("Translator"), "tyd": i18n("Type designer"), "tyg": i18n("Typographer"), "wac": i18n("Writer of added commentary"), "wal": i18n("Writer of added lyrics"), "wam": i18n("Writer of accompanying material"), "wat": i18n("Writer of added text"), "win": i18n("Writer of introduction"), "wpr": i18n("Writer of preface"), "wst": i18n("Writer of supplementary textual content") } # opf file opfFile = QDomDocument() opfRoot = opfFile.createElement("package") opfRoot.setAttribute("version", "3.0") opfRoot.setAttribute("unique-identifier", "BookId") opfRoot.setAttribute("xmlns", "http://www.idpf.org/2007/opf") opfRoot.setAttribute("prefix", "rendition: http://www.idpf.org/vocab/rendition/#") opfFile.appendChild(opfRoot) opfMeta = opfFile.createElement("metadata") opfMeta.setAttribute("xmlns:dc", "http://purl.org/dc/elements/1.1/") opfMeta.setAttribute("xmlns:dcterms", "http://purl.org/dc/terms/") # EPUB metadata requires a title, language and uuid langString = "en-US" if "language" in configDictionary.keys(): langString = str(configDictionary["language"]).replace("_", "-") bookLang = opfFile.createElement("dc:language") bookLang.appendChild(opfFile.createTextNode(langString)) opfMeta.appendChild(bookLang) bookTitle = opfFile.createElement("dc:title") if "title" in configDictionary.keys(): bookTitle.appendChild( opfFile.createTextNode(str(configDictionary["title"]))) else: bookTitle.appendChild(opfFile.createTextNode("Comic with no Name")) opfMeta.appendChild(bookTitle) # Generate series title and the like here too. if "seriesName" in configDictionary.keys(): bookTitle.setAttribute("id", "main") refine = opfFile.createElement("meta") refine.setAttribute("refines", "#main") refine.setAttribute("property", "title-type") refine.appendChild(opfFile.createTextNode("main")) opfMeta.appendChild(refine) refine2 = opfFile.createElement("meta") refine2.setAttribute("refines", "#main") refine2.setAttribute("property", "display-seq") refine2.appendChild(opfFile.createTextNode("1")) opfMeta.appendChild(refine2) seriesTitle = opfFile.createElement("dc:title") seriesTitle.appendChild( opfFile.createTextNode(str(configDictionary["seriesName"]))) seriesTitle.setAttribute("id", "series") opfMeta.appendChild(seriesTitle) refineS = opfFile.createElement("meta") refineS.setAttribute("refines", "#series") refineS.setAttribute("property", "title-type") refineS.appendChild(opfFile.createTextNode("collection")) opfMeta.appendChild(refineS) refineS2 = opfFile.createElement("meta") refineS2.setAttribute("refines", "#series") refineS2.setAttribute("property", "display-seq") refineS2.appendChild(opfFile.createTextNode("2")) opfMeta.appendChild(refineS2) if "seriesNumber" in configDictionary.keys(): refineS3 = opfFile.createElement("meta") refineS3.setAttribute("refines", "#series") refineS3.setAttribute("property", "group-position") refineS3.appendChild( opfFile.createTextNode(str(configDictionary["seriesNumber"]))) opfMeta.appendChild(refineS3) uuid = str(configDictionary["uuid"]) uuid = uuid.strip("{") uuid = uuid.strip("}") # Append the id, and assign it as the bookID. uniqueID = opfFile.createElement("dc:identifier") uniqueID.appendChild(opfFile.createTextNode("urn:uuid:" + uuid)) uniqueID.setAttribute("id", "BookId") opfMeta.appendChild(uniqueID) if "authorList" in configDictionary.keys(): authorEntry = 0 for authorE in range(len(configDictionary["authorList"])): authorDict = configDictionary["authorList"][authorE] authorType = "dc:creator" if "role" in authorDict.keys(): # This determines if someone was just a contributor, but might need a more thorough version. if str(authorDict["role"]).lower() in [ "editor", "assistant editor", "proofreader", "beta", "patron", "funder" ]: authorType = "dc:contributor" author = opfFile.createElement(authorType) authorName = [] if "last-name" in authorDict.keys(): authorName.append(authorDict["last-name"]) if "first-name" in authorDict.keys(): authorName.append(authorDict["first-name"]) if "initials" in authorDict.keys(): authorName.append(authorDict["initials"]) if "nickname" in authorDict.keys(): authorName.append("(" + authorDict["nickname"] + ")") author.appendChild(opfFile.createTextNode(", ".join(authorName))) author.setAttribute("id", "cre" + str(authorE)) opfMeta.appendChild(author) if "role" in authorDict.keys(): role = opfFile.createElement("meta") role.setAttribute("refines", "#cre" + str(authorE)) role.setAttribute("scheme", "marc:relators") role.setAttribute("property", "role") roleString = str(authorDict["role"]) if roleString in marcRelators.values( ) or roleString in marcRelators.keys(): i = list(marcRelators.values()).index(roleString) roleString = list(marcRelators.keys())[i] else: roleString = "oth" role.appendChild(opfFile.createTextNode(roleString)) opfMeta.appendChild(role) refine = opfFile.createElement("meta") refine.setAttribute("refines", "#cre" + str(authorE)) refine.setAttribute("property", "display-seq") refine.appendChild(opfFile.createTextNode(str(authorE + 1))) opfMeta.appendChild(refine) if "publishingDate" in configDictionary.keys(): date = opfFile.createElement("dc:date") date.appendChild( opfFile.createTextNode(configDictionary["publishingDate"])) opfMeta.appendChild(date) #Creation date modified = opfFile.createElement("meta") modified.setAttribute("property", "dcterms:modified") modified.appendChild( opfFile.createTextNode(QDateTime.currentDateTimeUtc().toString( Qt.ISODate))) opfMeta.appendChild(modified) if "source" in configDictionary.keys(): if len(configDictionary["source"]) > 0: source = opfFile.createElement("dc:source") source.appendChild( opfFile.createTextNode(configDictionary["source"])) opfMeta.appendChild(source) description = opfFile.createElement("dc:description") if "summary" in configDictionary.keys(): description.appendChild( opfFile.createTextNode(configDictionary["summary"])) else: description.appendChild( opfFile.createTextNode( "There was no summary upon generation of this file.")) opfMeta.appendChild(description) # Type can be dictionary or index, or one of those edupub thingies. Not necessary for comics. # typeE = opfFile.createElement("dc:type") # opfMeta.appendChild(typeE) if "publisherName" in configDictionary.keys(): publisher = opfFile.createElement("dc:publisher") publisher.appendChild( opfFile.createTextNode(configDictionary["publisherName"])) opfMeta.appendChild(publisher) if "isbn-number" in configDictionary.keys(): isbnnumber = configDictionary["isbn-number"] if len(isbnnumber) > 0: publishISBN = opfFile.createElement("dc:identifier") publishISBN.appendChild( opfFile.createTextNode(str("urn:isbn:") + isbnnumber)) opfMeta.appendChild(publishISBN) if "license" in configDictionary.keys(): if len(configDictionary["license"]) > 0: rights = opfFile.createElement("dc:rights") rights.appendChild( opfFile.createTextNode(configDictionary["license"])) opfMeta.appendChild(rights) """ Not handled Relation - This is for whether the work has a relationship with another work. It could be fanart, but also adaptation, an academic work, etc. Coverage - This is for the time/place that the work covers. Typically to determine whether an academic work deals with a certain time period or place. For comics you could use this to mark historical comics, but other than that we'd need a much better ui to define this. """ # These are all dublin core subjects. # 3.1 defines the ability to use an authority, but that # might be a bit too complicated right now. if "genre" in configDictionary.keys(): genreListConf = configDictionary["genre"] if isinstance(configDictionary["genre"], dict): genreListConf = configDictionary["genre"].keys() for g in genreListConf: subject = opfFile.createElement("dc:subject") subject.appendChild(opfFile.createTextNode(g)) opfMeta.appendChild(subject) if "characters" in configDictionary.keys(): for name in configDictionary["characters"]: char = opfFile.createElement("dc:subject") char.appendChild(opfFile.createTextNode(name)) opfMeta.appendChild(char) if "format" in configDictionary.keys(): for formatF in configDictionary["format"]: f = opfFile.createElement("dc:subject") f.appendChild(opfFile.createTextNode(formatF)) opfMeta.appendChild(f) if "otherKeywords" in configDictionary.keys(): for key in configDictionary["otherKeywords"]: word = opfFile.createElement("dc:subject") word.appendChild(opfFile.createTextNode(key)) opfMeta.appendChild(word) # Pre-pagination and layout # Comic are always prepaginated. elLayout = opfFile.createElement("meta") elLayout.setAttribute("property", "rendition:layout") elLayout.appendChild(opfFile.createTextNode("pre-paginated")) opfMeta.appendChild(elLayout) # We should figure out if the pages are portrait or not... elOrientation = opfFile.createElement("meta") elOrientation.setAttribute("property", "rendition:orientation") elOrientation.appendChild(opfFile.createTextNode("portrait")) opfMeta.appendChild(elOrientation) elSpread = opfFile.createElement("meta") elSpread.setAttribute("property", "rendition:spread") elSpread.appendChild(opfFile.createTextNode("landscape")) opfMeta.appendChild(elSpread) opfRoot.appendChild(opfMeta) # Manifest opfManifest = opfFile.createElement("manifest") toc = opfFile.createElement("item") toc.setAttribute("id", "ncx") toc.setAttribute("href", "toc.ncx") toc.setAttribute("media-type", "application/x-dtbncx+xml") opfManifest.appendChild(toc) region = opfFile.createElement("item") region.setAttribute("id", "regions") region.setAttribute("href", "region-nav.xhtml") region.setAttribute("media-type", "application/xhtml+xml") region.setAttribute("properties", "data-nav") # Set the propernavmap to use this later) opfManifest.appendChild(region) nav = opfFile.createElement("item") nav.setAttribute("id", "nav") nav.setAttribute("href", "nav.xhtml") nav.setAttribute("media-type", "application/xhtml+xml") nav.setAttribute("properties", "nav") # Set the propernavmap to use this later) opfManifest.appendChild(nav) ids = 0 for p in pagesList: item = opfFile.createElement("item") item.setAttribute("id", "img" + str(ids)) ids += 1 item.setAttribute("href", os.path.relpath(p, str(path))) item.setAttribute("media-type", "image/png") if os.path.basename(p) == os.path.basename(coverpageurl): item.setAttribute("properties", "cover-image") opfManifest.appendChild(item) ids = 0 for p in htmlFiles: item = opfFile.createElement("item") item.setAttribute("id", "p" + str(ids)) ids += 1 item.setAttribute("href", os.path.relpath(p, str(path))) item.setAttribute("media-type", "application/xhtml+xml") opfManifest.appendChild(item) opfRoot.appendChild(opfManifest) # Spine opfSpine = opfFile.createElement("spine") # this sets the table of contents to use the ncx file opfSpine.setAttribute("toc", "ncx") # Reading Direction: spreadRight = True direction = 0 if "readingDirection" in configDictionary.keys(): if configDictionary["readingDirection"] == "rightToLeft": opfSpine.setAttribute("page-progression-direction", "rtl") spreadRight = False direction = 1 else: opfSpine.setAttribute("page-progression-direction", "ltr") # Here we'd need to switch between the two and if spread keywrod use neither but combine with spread-none ids = 0 for p in htmlFiles: item = opfFile.createElement("itemref") item.setAttribute("idref", "p" + str(ids)) ids += 1 props = [] if p in listofSpreads: # Put this one in the center. props.append("rendition:page-spread-center") # Reset the spread boolean. # It needs to point at the first side after the spread. # So ltr -> spread-left, rtl->spread-right if direction == 0: spreadRight = False else: spreadRight = True else: if spreadRight: props.append("page-spread-right") spreadRight = False else: props.append("page-spread-left") spreadRight = True item.setAttribute("properties", " ".join(props)) opfSpine.appendChild(item) opfRoot.appendChild(opfSpine) # Guide opfGuide = opfFile.createElement("guide") if coverpagehtml is not None and coverpagehtml.isspace() is False and len( coverpagehtml) > 0: item = opfFile.createElement("reference") item.setAttribute("type", "cover") item.setAttribute("title", "Cover") item.setAttribute("href", coverpagehtml) opfGuide.appendChild(item) opfRoot.appendChild(opfGuide) docFile = open(str(Path(path / "content.opf")), 'w', newline="", encoding="utf-8") docFile.write(opfFile.toString(indent=2)) docFile.close() return str(Path(path / "content.opf"))
elif density == 'XXXHDPI': height *= 4 coin_id = 0 for coin_data in data['coins']: action = coin_data['action'] coin = dest_model.record() for field in fields: if field.name in ('id', 'image', 'obverseimg', 'reverseimg'): continue if field.name in SKIPPED_FIELDS: continue if field.name == 'updatedat': currentTime = QDateTime.currentDateTimeUtc() coin.setValue('updatedat', currentTime.toString(Qt.ISODate)) continue if field.name in coin_data: coin.setValue(field.name, coin_data[field.name]) image = QImage() for field_name in ('obverseimg', 'reverseimg'): if field_name in coin_data: img_file_name = os.path.join(image_path, coin_data[field_name]) img_file = open(img_file_name, 'rb') img_data = img_file.read() img_file.close()