예제 #1
0
    def saveAs(self):
        if settings.get("file_dialog_dir"):
            self.curDir = '~/'
        else:
            self.curDir = settings.get("file_dialog_dir")

        filename = unicode(
            QFileDialog.getSaveFileName(
                self, self.tr("Save document"), self.curDir,
                self.tr("ODT document (*.odt);;Text file (*.txt);;"
                        "HTML file (*.html);;PDF file(*.pdf)")))
        if not filename: return

        self.curDir = os.path.dirname(filename)
        settings.set("file_dialog_dir", self.curDir)

        dw = QtGui.QTextDocumentWriter()
        dw.setFormat('ODF')  # Default format

        # Check for alternative output format
        if filename.rsplit('.', 1)[1] == "txt":
            dw.setFormat('plaintext')
        if filename.rsplit('.', 1)[1] in ("html", "htm"):
            dw.setFormat('HTML')
        if filename.rsplit('.', 1)[1] in ("PDF", "pdf"):
            self.filePrintPdf(filename)
            return
        dw.setFileName(filename)
        dw.write(self.document())
예제 #2
0
    def initSpellchecker(self):
        # TODO: disable spellchecker icon in case of not working enchant
        try:
            import enchant
            spellDictDir = settings.get('spellchecker:directory')
            if spellDictDir:
                if enchant.__ver_major__ >= 1 and enchant.__ver_minor__ >= 6:
                    enchant.set_param("enchant.myspell.dictionary.path",
                                      spellDictDir)
                else:
                    print "Your pyenchant version is to old. Please " \
                          "upgrade to version 1.6.0 or higher, if you want " \
                          "to use spellchecker."
                    return None

            spellLang = settings.get('spellchecker:lang')
            if enchant.dict_exists(spellLang):
                self.dict = enchant.Dict(spellLang)
            else:
                # try dictionary based on the current locale
                try:
                    self.dict = enchant.Dict()
                    settings.set('spellchecker:lang', self.dict.tag)
                except:  # we don not have working dictionary...
                    return None
            if self.dict:
                self.usePWL(self.dict)

        except:
            print "can not start spellchecker!!!"
            import traceback
            traceback.print_exc()
            return None
예제 #3
0
    def saveAs(self):
        if settings.get("file_dialog_dir"):
            self.curDir = '~/'
        else:
            self.curDir = settings.get("file_dialog_dir")

        filename = unicode(QFileDialog.getSaveFileName(self,
                self.tr("Save document"), self.curDir,
                self.tr("ODT document (*.odt);;Text file (*.txt);;"
                        "HTML file (*.html);;PDF file(*.pdf)")
                ))
        if not filename: return

        self.curDir = os.path.dirname(filename)
        settings.set("file_dialog_dir", self.curDir)

        dw = QtGui.QTextDocumentWriter()
        dw.setFormat('ODF')  # Default format

        # Check for alternative output format
        if filename.rsplit('.', 1)[1] == "txt":
            dw.setFormat('plaintext')
        if filename.rsplit('.', 1)[1] in ("html", "htm"):
            dw.setFormat('HTML')
        if filename.rsplit('.', 1)[1] in ("PDF", "pdf"):
            self.filePrintPdf(filename)
            return
        dw.setFileName(filename)
        dw.write(self.document())
예제 #4
0
    def initSpellchecker(self):
        # TODO: disable spellchecker icon in case of not working enchant
        try:
            import enchant
            spellDictDir = settings.get('spellchecker:directory')
            if spellDictDir:
                if enchant.__ver_major__ >= 1 and enchant.__ver_minor__ >= 6:
                    enchant.set_param("enchant.myspell.dictionary.path",
                                      spellDictDir)
                else:
                    print "Your pyenchant version is to old. Please " \
                          "upgrade to version 1.6.0 or higher, if you want " \
                          "to use spellchecker."
                    return None

            spellLang = settings.get('spellchecker:lang')
            if enchant.dict_exists(spellLang):
                self.dict = enchant.Dict(spellLang)
            else:
                # try dictionary based on the current locale
                try:
                    self.dict = enchant.Dict()
                    settings.set('spellchecker:lang', self.dict.tag)
                except:  # we don not have working dictionary...
                    return None
            if self.dict:
                self.usePWL(self.dict)

        except:
            print "can not start spellchecker!!!"
            import traceback
            traceback.print_exc()
            return None
예제 #5
0
def get_tesseract_languages_old():
    """
    make a list of installed language data files
    """

    tess_exec = settings.get('tesseract-ocr:executable')
    if not tess_exec:
        tess_exec = 'tesseract'

    try:
        poTess = Popen([tess_exec, 'a', 'a', '-l', 'invalid'],
                       shell=False, stdout=PIPE, stderr=PIPE)
        stdout_message, lTess = poTess.communicate()
        tess_data_prefix, langdata_ext = \
                                        extract_tesseract_languages_path(lTess)
    except OSError as ex:
        print("ex", ex)
        return None
    # env. setting can help to handle path with spaces
    tess_data_prefix = settings.get('tesseract-ocr:TESSDATA_PREFIX:')
    if not tess_data_prefix:
        tess_data_prefix = os.getenv('TESSDATA_PREFIX')
    tessdata_path = os.path.join(tess_data_prefix, "tessdata")

    if not os.path.exists(tessdata_path):
        print("Tesseract data path ('%s') do not exist!" % tessdata_path)
        return None
    langdata = glob(tess_data_prefix + os.path.sep + '*' + langdata_ext)
    return [os.path.splitext(os.path.split(uc)[1])[0] for uc in langdata]
예제 #6
0
 def openFile(self):
     if settings.get("file_dialog_dir"):
         self.curDir = '~/'
     else:
         self.curDir = settings.get("file_dialog_dir")
     fn = unicode(QFileDialog.getOpenFileName(self,
             self.tr("Open File..."), self.curDir,
             self.tr("HTML-Files (*.htm *.html);;All Files (*)")))
     QtGui.QApplication.setOverrideCursor(QtCore.Qt.WaitCursor)
     if fn:
         self.lastFolder = os.path.dirname(fn)
         if os.path.exists(fn):
             if os.path.isfile(fn):
                 f = QtCore.QFile(fn)
                 if not f.open(QtCore.QIODevice.ReadOnly |
                               QtCore.QIODevice.Text):
                     QtGui.QMessageBox.information(self.parent(),
                     self.tr("Error - Lector"),
                     self.tr("Can't open '%s.'" % fn))
                 else:
                     stream = QtCore.QTextStream(f)
                     text = unicode(stream.readAll())
                     self.setText(text)
             else:
                 QtGui.QMessageBox.information(self.parent(),
                 self.tr("Error - Lector"),
                 self.tr("'%s' is not a file." % fn))
     QtGui.QApplication.restoreOverrideCursor()
예제 #7
0
    def run(self):
        ## geometry
        #tl_x = 0.0
        #tl_y = 0.0
        br_x = settings.get('scanner:width')
        br_y = settings.get('scanner:height')

        resolution = settings.get('scanner:resolution')
        mode = settings.get('scanner:mode')

        self.process = ScanimageProcess(self.device, mode, resolution,
                                        (br_x, br_y))
        QObject.connect(self.process, SIGNAL("finished(int)"), self.scanned)
        QObject.connect(self.process, SIGNAL("readyReadStandardError()"),
                        self.progress)

        #TODO: manage Abort button
        progress = QtGui.QProgressDialog(self.tr("Progress"), self.tr("Abort"),
                                         0, 100)
        progress.setWindowTitle(self.tr("Scanning..."))
        progress.setWindowModality(Qt.WindowModal)
        progress.setMinimumDuration(0)
        progress.setValue(0)
        progress.setAutoClose(True)
        progress.setAutoReset(True)
        progress.forceShow()

        self.progressDialog = progress
        self.loaded = False
예제 #8
0
def main():
    if settings.get('log:errors'):
        log_filename = settings.get('log:filename')
        if log_filename:
            try:
                log_file = open(log_filename, "w")
                print('Redirecting stderr/stdout... to %s' % log_filename)
                sys.stderr = log_file
                sys.stdout = log_file
            except IOError:
                print("Lector could not open log file '%s'!\n" % log_filename \
                      + " Redirecting will not work.")
        else:
            print("Log file is not set. Please set it in settings.")

    app = QApplication(sys.argv)
    opts = [str(arg) for arg in app.arguments()[1:]]
    if '--no-scanner' in opts:
        scanner = False
    else:
        scanner = True
    qsrand(QTime(0, 0, 0).secsTo(QTime.currentTime()))

    locale = settings.get('ui:lang')
    if not locale:
        locale = QLocale.system().name()
    qtTranslator = QTranslator()
    if qtTranslator.load(":/translations/ts/lector_" + locale, 'ts'):
        app.installTranslator(qtTranslator)

    window = Window(scanner)
    window.show()
    app.exec_()
예제 #9
0
def main():
    if settings.get('log:errors'):
        log_filename = settings.get('log:filename')
        if log_filename:
            try:
                log_file = open(log_filename,"w")
                print ('Redirecting stderr/stdout... to %s' % log_filename)
                sys.stderr = log_file
                sys.stdout = log_file
            except IOError:
                print("Lector could not open log file '%s'!\n" % log_filename \
                      + " Redirecting will not work.")
        else:
            print("Log file is not set. Please set it in settings.")

    app = QApplication(sys.argv)
    opts = [str(arg) for arg in app.arguments()[1:]]
    if '--no-scanner' in opts:
        scanner = False
    else:
        scanner = True
    qsrand(QTime(0, 0, 0).secsTo(QTime.currentTime()))

    locale = settings.get('ui:lang')
    if not locale:
        locale = QLocale.system().name()
    qtTranslator = QTranslator()
    if qtTranslator.load(":/translations/ts/lector_" + locale, 'ts'):
        app.installTranslator(qtTranslator)

    window = Window(scanner)
    window.show()
    app.exec_()
예제 #10
0
    def run(self):
        ## geometry
        # tl_x = 0.0
        # tl_y = 0.0
        br_x = settings.get("scanner:width")
        br_y = settings.get("scanner:height")

        resolution = settings.get("scanner:resolution")
        mode = settings.get("scanner:mode")

        self.process = ScanimageProcess(self.device, mode, resolution, (br_x, br_y))
        # QObject.connect(self.process, SIGNAL("finished(int)"), self.scanned)
        self.process.finished.connect(self.scanned(int))
        self.process.readyReadStandardError.connect(self.progress)

        # TODO: manage Abort button
        progress = QProgressDialog(self.tr("Progress"), self.tr("Abort"), 0, 100)
        progress.setWindowTitle(self.tr("Scanning..."))
        progress.setWindowModality(Qt.WindowModal)
        progress.setMinimumDuration(0)
        progress.setValue(0)
        progress.setAutoClose(True)
        progress.setAutoReset(True)
        progress.forceShow()

        self.progressDialog = progress
        self.loaded = False
예제 #11
0
 def openFile(self):
     if settings.get("file_dialog_dir"):
         self.curDir = '~/'
     else:
         self.curDir = settings.get("file_dialog_dir")
     fn = unicode(
         QFileDialog.getOpenFileName(
             self, self.tr("Open File..."), self.curDir,
             self.tr("HTML-Files (*.htm *.html);;All Files (*)")))
     QtGui.QApplication.setOverrideCursor(QtCore.Qt.WaitCursor)
     if fn:
         self.lastFolder = os.path.dirname(fn)
         if os.path.exists(fn):
             if os.path.isfile(fn):
                 f = QtCore.QFile(fn)
                 if not f.open(QtCore.QIODevice.ReadOnly
                               | QtCore.QIODevice.Text):
                     QtGui.QMessageBox.information(
                         self.parent(), self.tr("Error - Lector"),
                         self.tr("Can't open '%s.'" % fn))
                 else:
                     stream = QtCore.QTextStream(f)
                     text = unicode(stream.readAll())
                     self.setText(text)
             else:
                 QtGui.QMessageBox.information(
                     self.parent(), self.tr("Error - Lector"),
                     self.tr("'%s' is not a file." % fn))
     QtGui.QApplication.restoreOverrideCursor()
def __doLogin():
  """If the megavideo username and password parameters are set, will authenticate with
  megavideo and return the user cookie that megavideo uses to track logged in users"""
  megavideologin = settings.get("megavideouser")
  log.debug("Authenticating on Megavideo with username: '******'" % megavideologin)
  megavideopassword = settings.get("megavideopassword")
  if megavideologin and megavideopassword:
    return __getMegavideoUserCookie(megavideologin, megavideopassword)
  
  return None
예제 #13
0
    def __init__(self, parent=None):
        QtGui.QTextEdit.__init__(self)

        self.setupEditor()
        state = settings.get('editor:spell')
        if state == "":  # no settings
            state = True
        self.toggleSpell(state)

        onOff = settings.get('editor:whiteSpace')
        if onOff == "":  # no settings
            onOff = True
        self.togglewhiteSpace(onOff)

        self.currentCharFormatChanged.connect(self.CharFormatChanged)
예제 #14
0
def get_tesseract_languages():
    """
    get list of lang
    """
    tess_exec = settings.get('tesseract-ocr:executable')
    if not tess_exec:
        tess_exec = 'tesseract'

    try:
        poTess = Popen([tess_exec, '--list-langs'],
                       shell=False, stdout=PIPE, stderr=PIPE)
        stdout_message, lTess = poTess.communicate()
        # we need to remove not needed information e.g. OpenCL performamnce
        if isinstance(lTess, bytes):
            lTess = str(lTess, 'utf-8')
        out_split = lTess.split('\n')
        langlist = list()
        add_lang = False
        for row in out_split:
            if row.startswith('List of'):
                add_lang = True
            if add_lang:
                langlist.append(row.strip())
        if langlist:
            return langlist
        else:
            return get_tesseract_languages_old()
    except OSError as ex:
        print("ex", ex)
        return None
예제 #15
0
def main():
    request_kwargs = None
    token = get('app_token')

    if bool(get('app_use_proxy')):
        request_kwargs = {
            'proxy_url': get('app_proxy_url')
        }

    updater = Updater(token=token, request_kwargs=request_kwargs, use_context=True)
    dispatcher = updater.dispatcher

    init_dispatcher_handlers(dispatcher)

    updater.start_polling()
    updater.idle()
예제 #16
0
    def __init__(self, parent = None):
        QtGui.QTextEdit.__init__(self)

        self.setupEditor()
        state = settings.get('editor:spell')
        if state == "":  # no settings
            state = True
        self.toggleSpell(state)

        onOff = settings.get('editor:whiteSpace')
        if onOff == "":  # no settings
            onOff = True
        self.togglewhiteSpace(onOff)

        self.currentCharFormatChanged.connect(
                self.CharFormatChanged)
예제 #17
0
 def on_actionChangeDevice_triggered(self):
     ##SANE
     message = ''
     try:
         import sane
     except ImportError:
         # sane found no scanner - disable scanning;
         message = self.tr("Sane not found! Scanning is disabled.")
     else:
         from .scannerselect import ScannerSelect
         sane.init()
         sane_list = sane.get_devices()
         saved_device = settings.get('scanner:device')
         if saved_device in [x[0] for x in sane_list]:
             message = self.tr("Sane found configured device...")
             self.scannerSelected()
         elif not sane_list:
             message = self.tr("Sane dit not find any device! "
                               "Scanning is disabled.")
         else:
             # there is not configured device => run configuration
             ss = ScannerSelect(sane_list, parent=self)
             ss.accepted.connect(self.scannerSelected)
             ss.show()
     self.statusBar().showMessage(message, 2000)
예제 #18
0
 def on_actionChangeDevice_triggered(self):
     ##SANE
     message = ''
     try:
         import sane
     except ImportError:
         # sane found no scanner - disable scanning;
         message = self.tr("Sane not found! Scanning is disabled.")
     else:
         from .scannerselect import ScannerSelect
         sane.init()
         sane_list = sane.get_devices()
         saved_device = settings.get('scanner:device')
         if saved_device in [x[0] for x in sane_list]:
             message = self.tr("Sane found configured device...")
             self.scannerSelected()
         elif not sane_list:
             message = self.tr("Sane dit not find any device! "
                               "Scanning is disabled.")
         else:
             # there is not configured device => run configuration
             ss = ScannerSelect(sane_list, parent=self)
             ss.accepted.connect(self.scannerSelected)
             ss.show()
     self.statusBar().showMessage(message, 2000)
예제 #19
0
    def scannerSelected(self):
        self.ui.actionScan.setEnabled(True)

        if self.thread is None:
            from .scannerthread import ScannerThread

            self.thread = ScannerThread(self, settings.get('scanner:device'))
            self.thread.scannedImage.connect(self.on_scannedImage)
예제 #20
0
 def process_events(self, events):
     # Optional animation lag-smoothing
     _flag_smoothing = settings.get('animation_lag_smoothing')
     _ping_threshold = settings.get('lag_ping_threshold')
     if _flag_smoothing is True or (_flag_smoothing == 'auto' and
                                    self.pingdelta / 1e6 < _ping_threshold):
         for object_type in ['elevator', 'monster']:
             for obj in self.map.objects[object_type]:
                 obj.move()
         self.my_player.process_pressed(events['key-pressed'],
                                        events['key-down'])
         self.my_player.move(self.map)
     # ALWAYS remember to refresh panning
     self.refresh_pan()
     # send data
     if self.connected['connected']:
         self.send(events)
예제 #21
0
    def usePWL(self, dictionary):
        """ Restart spellchecker with personal private list
        """
        import enchant

        pwlDict = settings.get('spellchecker:pwlDict')
        pwlLang = settings.get('spellchecker:pwlLang')
        if pwlLang:
            try:
                (name, extension) = pwlDict.rsplit('.', 1)
                pwlDict = name + '_'  + dictionary.tag + "." + extension
            except:
                pwlDict = name + '_'  + dictionary.tag

        self.dict = enchant.DictWithPWL(dictionary.tag, pwlDict)
        self.highlighter = Highlighter(self.document())
        self.highlighter.setDict(self.dict)
예제 #22
0
    def scannerSelected(self):
        self.ui.actionScan.setEnabled(True)

        if self.thread is None:
            from .scannerthread import ScannerThread

            self.thread = ScannerThread(self, settings.get('scanner:device'))
            self.thread.scannedImage.connect(self.on_scannedImage)
예제 #23
0
    def usePWL(self, dictionary):
        """ Restart spellchecker with personal private list
        """
        import enchant

        pwlDict = settings.get('spellchecker:pwlDict')
        pwlLang = settings.get('spellchecker:pwlLang')
        if pwlLang:
            try:
                (name, extension) = pwlDict.rsplit('.', 1)
                pwlDict = name + '_' + dictionary.tag + "." + extension
            except:
                pwlDict = name + '_' + dictionary.tag

        self.dict = enchant.DictWithPWL(dictionary.tag, pwlDict)
        self.highlighter = Highlighter(self.document())
        self.highlighter.setDict(self.dict)
예제 #24
0
파일: lector.py 프로젝트: klukonin/lector
    def scannerSelected(self):
        self.ui.actionScan.setEnabled(True)

        if self.thread is None:
            from scannerthread import ScannerThread

            self.thread = ScannerThread(self, settings.get('scanner:device'))
            QObject.connect(self.thread, SIGNAL("scannedImage()"),
                            self.on_scannedImage)
예제 #25
0
파일: lector.py 프로젝트: klukonin/lector
    def scannerSelected(self):
        self.ui.actionScan.setEnabled(True)

        if self.thread is None:
            from scannerthread import ScannerThread

            self.thread = ScannerThread(self, settings.get('scanner:device'))
            QObject.connect(self.thread, SIGNAL("scannedImage()"),
                            self.on_scannedImage)
def getUserNotifier(title, initialMessage):
  """Factory method to create a user notifier according to xbmc-tvshack plugin settings
  @param title: the title to initialize the notifier with
  @param initialMessage: the initial message to display"""
  setting = settings.get("notification-method")
  if setting == METHOD_PROGRESS:
    return ProgressDialogNotifier(title, initialMessage)
  elif setting == METHOD_NATIVE:
    return UserNotificationNotifier(title, initialMessage)
  else:
    return NullNotifier()
def getUserNotifier(title, initialMessage):
    """Factory method to create a user notifier according to xbmc-tvshack plugin settings
  @param title: the title to initialize the notifier with
  @param initialMessage: the initial message to display"""
    setting = settings.get("notification-method")
    if setting == METHOD_PROGRESS:
        return ProgressDialogNotifier(title, initialMessage)
    elif setting == METHOD_NATIVE:
        return UserNotificationNotifier(title, initialMessage)
    else:
        return NullNotifier()
예제 #28
0
파일: rcon.py 프로젝트: zapdos26/Sailvation
 def __init__(self, bot):
     self.bot = bot
     self.config = settings.get('rcon.json')
     self.db = settings.get('db.json')
     self.bot.add_listener(self.memberban, 'on_member_ban')
     self.bot.add_listener(self.memberleave, 'on_member_remove')
     try:
         self.pool = mysql.connector.pooling.MySQLConnectionPool(
             pool_name="RCON",
             pool_size=3,
             host=self.db['host'],
             user=self.db['username'],
             passwd=self.db['password'],
             database=self.db['database'],
         )
         conn = self.pool.get_connection()
         cur = conn.cursor()
         sql = 'CREATE TABLE IF NOT EXISTS `sailvation` (`id` int(11) NOT NULL AUTO_INCREMENT,`discord_id` varchar(18) DEFAULT NULL,`steam64_id` varchar(17) DEFAULT NULL, `timestamp` int(11) DEFAULT NULL,PRIMARY KEY (`id`))'
         cur.execute(sql)
         conn.commit()
         conn.close()
     except Error as e:
         print("Error while connecting to MySQL", e)
 def getCover(self):
   '''
   Get the cover.
   If the cover link is from IMDB, we resize it through it's url
   @return: a cover url, or an emtpy string
   '''
   cover = self.__infoLabels["cover"] or ""
   if not cover.startswith("http://"):
     return ""
   try:
     if re.compile("http://ia\.media-imdb\.com/images/.+?_SX\d+?_SY\d+?_\.jpg").match(cover):
       coversize = settings.get("imdb-cover-size")
       cover = re.sub('_SX\d+_SY\d+_\.jpg', "_SX%s_.jpg" % str(coversize), cover)
   except:
     log.exception("Could not resize cover: '%s'" % cover)
   return cover
예제 #30
0
def resolveFiles(url, name, forceSourceSelection=False):
    """Resolve the files for a movie/episode/... item

    Resolving a file is split into three phases:
    1-Select file source (megavideo, veoh, tudou, youku, ...)
    2-Load parts (if item is split for the selected source)
    3-Resolve file links for the parts from the previous step

    If an item has only one available source, then that source is auto-selected, otherwise
    the user is shown a XBMC dialog to select the source. If the 'autoplay-preferred-source'
    setting is enabled, the first available source that matches the 'preferred-source' setting
    will be auto-selected.

    @param url: the url to resolve files for
    @param label: the label of the playable item being resolved
    @param forceSourceSelection: if the user should be forced to select the source (default False)
    @return: a list of urls of the files to play"""
    log.debug("Listing sources: %s, forceSelection: %s" % (url, forceSourceSelection))
    html = http.get(__url(url), cleanup=True)

    alternateLinks = [(itemUrl, getSourceName(itemSource)) for (itemUrl, itemSource) in
                      re.compile(SOURCE_PATTERN, re.DOTALL).findall(html)]

    # The url on the page is to another primewire page, the actual external url is in a parameter of the url
    outsideLinks = []
    for link, name in alternateLinks:
        match = re.compile(".+?&url=(.+?)&.+?").findall(link)[0]
        outsideLinks.append((match.decode('base-64'), name))

    log.debug("found links in page: %s" % str(outsideLinks))
    from utils.sources import SourceList

    sources = SourceList([(url, name) for url, name in outsideLinks],
                         settings.isSet("filter-unsupported-sources"))

    autoSelectSource = None
    if settings.isSet("autoplay-preferred-source"):
        autoSelectSource = settings.get("preferred-source").split(',')

    selected = sources.selectSource(forceSourceSelection, autoSelectSource)
    if selected:
        link = selected.resolve()
        log.debug("resolved link for video: %s" % str(link))
        return PluginResult(1, [LWTPluginMovieItem(name, link)])
예제 #31
0
 def UItranslations(self):
     """ Get list of available ui translations
     """
     # iterate over resource file to find available translations
     fltr = QDir.Dirs | QDir.Files | QDir.Hidden
     iterator = QDirIterator(':', fltr, QDirIterator.Subdirectories)
     while iterator.hasNext():
         filePath = iterator.next()
         if '/translations/ts/' in filePath:
             fileName  = os.path.basename(unicode(filePath[1:]))
             locale = fileName.replace('lector_','').replace('.qm', '')
             if locale:
                 self.ui.cbLang.addItem(locale)
     locale = settings.get('ui:lang')
     if not locale:
         locale = QLocale.system().name()
     currentIndex = self.ui.cbLang.findText(locale)
     if currentIndex <= -1:
         currentIndex = self.ui.cbLang.findText('en_GB')
     self.ui.cbLang.setCurrentIndex(currentIndex)
예제 #32
0
 def testing(self, package, pattern, stream, deferred=False):
     try:
         # and use custom loader which support ST2 and reloading modules
         tests_dir = plugin_settings.get(
             sublime.active_window().active_view(), 'tests_dir', 'tests')
         loader = TestLoader(deferred)
         test = loader.discover(
             os.path.join(sublime.packages_path(), package, tests_dir),
             pattern)
         # use deferred test runner or default test runner
         if deferred:
             testRunner = DeferringTextTestRunner(stream, verbosity=2)
         else:
             testRunner = TextTestRunner(stream, verbosity=2)
         testRunner.run(test)
     except Exception as e:
         if not stream.closed:
             stream.write("ERROR: %s\n" % e)
     if not deferred:
         stream.close()
예제 #33
0
 def UItranslations(self):
     """ Get list of available ui translations
     """
     # iterate over resource file to find available translations
     fltr = QDir.Dirs | QDir.Files | QDir.Hidden
     iterator = QDirIterator(':', fltr, QDirIterator.Subdirectories)
     while iterator.hasNext():
         filePath = iterator.next()
         if '/translations/ts/' in filePath:
             fileName = os.path.basename(str(filePath[1:]))
             locale = fileName.replace('lector_', '').replace('.qm', '')
             if locale:
                 self.ui.cbLang.addItem(locale)
     locale = settings.get('ui:lang')
     if not locale:
         locale = QLocale.system().name()
     currentIndex = self.ui.cbLang.findText(locale)
     if currentIndex <= -1:
         currentIndex = self.ui.cbLang.findText('en_GB')
     self.ui.cbLang.setCurrentIndex(currentIndex)
예제 #34
0
    def __init__(self, sane_list, parent=None):
        QDialog.__init__(self, parent)

        self.ui = Ui_Scanner()
        self.ui.setupUi(self)

        self.sane_list = sane_list

        self.ui.combScanner.addItems([scanner[2] for scanner in sane_list])
        sane_devices = [scanner[0] for scanner in sane_list]

        scanner_setting = settings.get('scanner:device')
        #TODO: also load color mode, resolution and size
        try:
            self.ui.combScanner.setCurrentIndex(
                sane_devices.index(scanner_setting))
        except ValueError:
            pass
        self.updateForm()
        self.connect(self.ui.combScanner, SIGNAL("currentIndexChanged(int)"),
                     self.updateForm)
예제 #35
0
    def __init__(self, sane_list, parent = None):
        QDialog.__init__(self, parent)

        self.ui = Ui_Scanner()
        self.ui.setupUi(self)

        self.sane_list = sane_list

        self.ui.combScanner.addItems([scanner[2] for scanner in sane_list])
        sane_devices = [scanner[0] for scanner in sane_list]

        scanner_setting = settings.get('scanner:device')
        #TODO: also load color mode, resolution and size
        try:
            self.ui.combScanner.setCurrentIndex(
                    sane_devices.index(scanner_setting)
            )
        except ValueError:
            pass
        self.updateForm()
        self.connect(self.ui.combScanner, SIGNAL("currentIndexChanged(int)"),
                     self.updateForm)
예제 #36
0
    def langList(self, spellDictDir):
        self.ui.dictBox.clear()
        langs = get_spellchecker_languages(spellDictDir)
        if langs == None:
            self.ui.spellInfoLabel.setText(self.tr(
                "Enchant not found. Check if pyenchant is installed!"))
        elif len(langs) == 0:
            self.ui.spellInfoLabel.setText(self.tr(
             "Enchant found but no dictionary. Check your dictionary directory."
             ))
        else:
            for lang in langs:
                self.ui.dictBox.addItem(lang)

            spellLang = settings.get('spellchecker:lang')
            currentIndex = self.ui.dictBox.findText(spellLang)
            if currentIndex > -1:
                self.ui.dictBox.setCurrentIndex(currentIndex)
            else:
                self.ui.spellInfoLabel.setText(self.tr("'%s' was not found in"
                    "available dictionaries. Using other dictionary." \
                    % spellLang ))
예제 #37
0
    def langList(self, spellDictDir):
        self.ui.dictBox.clear()
        langs = get_spellchecker_languages(spellDictDir)
        if langs == None:
            self.ui.spellInfoLabel.setText(
                self.tr("Enchant not found. Check if pyenchant is installed!"))
        elif len(langs) == 0:
            self.ui.spellInfoLabel.setText(
                self.
                tr("Enchant found but no dictionary. Check your dictionary directory."
                   ))
        else:
            for lang in langs:
                self.ui.dictBox.addItem(lang)

            spellLang = settings.get('spellchecker:lang')
            currentIndex = self.ui.dictBox.findText(spellLang)
            if currentIndex > -1:
                self.ui.dictBox.setCurrentIndex(currentIndex)
            else:
                self.ui.spellInfoLabel.setText(self.tr("'%s' was not found in"
                    "available dictionaries. Using other dictionary." \
                    % spellLang ))
예제 #38
0
    def __init__(self, port):
        # TODO: Disabling RabbitMQ as we not currently doing P2P
        message_queue = None
        #message_queue = PikaQueueServer(port)
        #message_queue.start()

        settings = utils.settings.Settings()
        frontend_path = settings.get("frontend_path", "../pangea-poker-frontend/client")
        images_path = urllib.parse.urljoin(frontend_path, "images")

        handlers = [
            (r"/test/css/(.*)", tornado.web.StaticFileHandler, {"path": "./static"}),
            (r"/test/js/(.*)", tornado.web.StaticFileHandler, {"path": "./static"}),
            (r"/test", MainHandler, dict(port=port)),
            (r"/api/ws", WebSocketHandler, dict(message_queue=message_queue)),
            (r"/(.*)", tornado.web.StaticFileHandler, {"path": frontend_path, "default_filename": "index.html"}),
            (r"/images/(.*)", tornado.web.StaticFileHandler, {"path": images_path})
        ]

        settings = {
            "template_path": "static",
        }

        tornado.web.Application.__init__(self, handlers, **settings)
def resolveFiles(url, name, forceSourceSelection=False):
    '''Resolve the files for a movie/episode/... item
    
    Resolving a file is split into three phases:
    1-Select file source (megavideo, veoh, tudou, youku, ...)
    2-Load parts (if item is split for the selected source)
    3-Resolve file links for the parts from the previous step
    
    If an item has only one available source, then that source is auto-selected, otherwise
    the user is shown a XBMC dialog to select the source. If the 'autoplay-preferred-source'
    setting is enabled, the first available source that matches the 'preferred-source' setting
    will be auto-selected.
    
    @param url: the url to resolve files for
    @param label: the label of the playable item being resolved
    @param forceSourceSelection: if the user should be forced to select the source (default False)
    @return: a list of urls of the files to play'''
    log.debug("Listing sources: %s, forceSelection: %s" % (url, forceSourceSelection))
    html = http.get(__url(url), cleanup=True)

    alternateLinks = [(itemUrl, getSourceName(itemSource)) for (itemUrl, itemSource) in re.compile(SOURCE_PATTERN, re.DOTALL).findall(html)]
    log.debug("found links in page: %s" % str(alternateLinks))
    from linkresolvers import SourceList
    sources = SourceList([(__url(url), name) for url, name in alternateLinks],
                         settings.isSet("filter-unsupported-sources"))

    autoSelectSource = None
    if settings.isSet("autoplay-preferred-source"):
        autoSelectSource = settings.get("preferred-source")

    selected = sources.selectSource(forceSourceSelection, autoSelectSource)
    if selected:
        metadata = __parseTvShowMetadata(html)
        link = selected.resolve()
        log.debug("resolved link for video: %s" % str(link))
        return PluginResult(1, [LWTPluginMovieItem(name, link, metadata=metadata)])
예제 #40
0
 def __init__(self, bot):
     self.bot = bot
     self.config = settings.get('temporarychannels.json')
     self.temporary_channels = set()
예제 #41
0
    def doOcr(self):
        import codecs
        aItems = self.scene().areas
        numItems = len(aItems)

        if settings.get('editor:clear') :
            self.textEditor.clear()

        # clean temp to avoid false imports
        for oldOutPut in glob.glob('/tmp/out.[0-9]*.txt'):
            os.remove(oldOutPut)

        progress = QtGui.QProgressDialog(self.tr("Processing images..."),
                                         self.tr("Abort"), 0, numItems)
        progress.setWindowTitle(self.tr("Processing images..."))
        progress.setWindowModality(QtCore.Qt.WindowModal)
        # on MS Windows dialog has no icon
        progress.setWindowIcon(QtGui.QIcon(":/icons/icons/L.png"))
        progress.setMinimumDuration(0)
        progress.setValue(0)
        progress.setAutoClose(True)
        progress.setAutoReset(True)
        progress.forceShow()

        tess_exec = settings.get('tesseract-ocr:executable')
        if not tess_exec:
            tess_exec = 'tesseract'

        for i, item in enumerate(aItems):
            if progress.wasCanceled():
                break

            progress.setValue(i)
            rect = item.rect()
            pos = item.scenePos()

            box = (int(pos.x()), int(pos.y()), int(rect.width() + pos.x()), \
                    int(rect.height() + pos.y()))
            # TODO: make random filename if we do not debug lector ;-)
            # TODO: use png if tesseract version is > 3.00
            filename = "/tmp/out.%d.png" % i

            region = self.scene().im.crop(box)

            if item.type == 1:
                # Improve quality of text for tesseract
                # TODO: put it as option for OCR because of longer duration
                nx, ny = rect.width(), rect.height()
                region = region.resize((int(nx*3), int(ny*3)), \
                            Image.BICUBIC).convert('L')
                region.save(filename, dpi=(600, 600))
                # TODO: use html/hocr if tesseract version is > 3.01
                command = tess_exec + " %s /tmp/out.%d -l %s" % (filename, i,
                                                              self.language)
                os.popen(command)

                if os.path.exists("/tmp/out.%d.txt" % i):
                    s = codecs.open("/tmp/out.%d.txt" % \
                        (i, ) , 'r', 'utf-8').read()
                    self.textEditor.append(s)
                    # TODO: delete image & OCR result if we do not debug lector
                else:
                    ## TODO: tesseract failed.
                    ## 1. process/print error message
                    ## 2. mark area as problematic
                    print "Tesseract was unabled to process area!"
                    # this can happend if left side of text is blury
            else:
                region = region.resize((region.size[0]/4, region.size[1]/4))
                region.save(filename)

                s = "<img src='%s'>" % filename
                self.textEditor.append(s)

        progress.setValue(numItems)
예제 #42
0
    def initSettings(self):
        self.ui.sbHeight.setValue(settings.get('scanner:height'))
        self.ui.sbWidth.setValue(settings.get('scanner:width'))
        self.ui.sbResolution.setValue(settings.get('scanner:resolution'))
        self.ui.combColor.setCurrentIndex(
            self.colors.index(settings.get('scanner:mode')))

        self.changeFont(QFont(settings.get('editor:font')))
        self.ui.checkBoxClear.setChecked(settings.get('editor:clear'))
        settings_symbols = settings.get('editor:symbols')
        if settings_symbols:
            self.ui.symbolList.setPlainText(settings_symbols)

        spellDictDir = settings.get('spellchecker:directory')
        self.ui.directoryLine.setText(spellDictDir)
        self.langList(spellDictDir)
        self.UItranslations()
        self.ui.checkBoxPWL.setChecked(settings.get('spellchecker:pwlLang'))
        pwlDict = settings.get('spellchecker:pwlDict')
        self.ui.lineEditPWL.setText(pwlDict)

        tessExec = settings.get('tesseract-ocr:executable')
        self.ui.lnTessExec.setText(tessExec)
        tessData = settings.get('tesseract-ocr:TESSDATA_PREFIX:')
        self.ui.lnTessData.setText(tessData)

        self.ui.cbLog.setChecked(settings.get('log:errors'))
        self.ui.lnLog.setText(settings.get('log:filename'))
예제 #43
0
 def __init__(self):
     self.__database = str(settings.get('app_database'))
예제 #44
0
 def setEditorFont(self):
     self.setFont(QtGui.QFont(settings.get('editor:font')))
    def resolve(self, url):
        if url.find('putlocker') < 0:
            raise Exception("not a putlocker link")

        notifier = notification.getUserNotifier('PutLocker', 'Initializing resolver...')

        http = self.getHttpClient()

        try:

            # login to use pro account
            if not self.isLoggedIn():
                from utils import pluginsupport, settings

                username = settings.get("putlocker-user")
                password = settings.get("putlocker-pass")

                if username and password and not self.isLoggedIn():
                    loginData = pluginsupport.encodeArgs({'user': username, 'pass': password, 'login_submit': 'Login'})
                    notifier.update(20, "performing login for premium link...")
                    log.debug("loggin in '%s' to pulocker.com" % str(username))
                    http.get('http://www.putlocker.com/authenticate.php?login', data=loginData)
                    notifier.update(30, "logged in...")
                    self.__loggedIn = True
                    log.debug("logged in? '%s'" % str(self.isLoggedIn()))
                else:
                    # find session hash
                    notifier.update(0, "getting page to parse session hash...")
                    page = http.get(url)
                    hash = re.search('value="([0-9a-f]+?)" name="hash"', page).group(1)
                    notifier.update(10, "got hash '%s'... waiting 5 seconds to POST..." % hash)
                    log.info('now waiting 5 seconds to post confirmation data...')
                    for i in range(0, 5):
                        sleep(1)
                        log.info(i + 1)

                    postData = pluginsupport.encodeArgs({'hash': hash, 'confirm': 'Continue as Free User'})
                    notifier.update(40, "done waiting... now POSTing hash '%s'..." % hash)
                    log.debug("posting hash and confirmation for free user: '******'" % str(postData))
                    page = http.get(url, data=postData)

            notifier.update(50, "getting rss feed url from page")
            page = http.get(url)
            rssFeedUrl = 'http://www.putlocker.com' + re.search("playlist: '(/get_file.php.+?)'", page).group(1)
            # get the rss feed xml to load the video stream location from
            notifier.update(70, "requesting rss feed xml from '%s'" % rssFeedUrl)
            log.debug("now loading rss feed xml. url is '%s'" % str(rssFeedUrl))
            page = http.get(rssFeedUrl)

            mediaUrlMatch = re.search('url="(.+?)"', page)
            if mediaUrlMatch:
                resolvedUrl = mediaUrlMatch.group(1)
                if url.find('expired_link'):
                    raise Exception("link is expired")
                notifier.update(90, "resolved url to play: '%s'" % resolvedUrl)
                log.debug("found stream link: '%s'" % resolvedUrl)
                return resolvedUrl

        finally:
            notifier.close()

        log.debug("url not found for putlocker...")
예제 #46
0
    def contextMenuEvent(self, event):
        """ Creates two context menus:
            1. no modifier -> spellchecker & clear emnu
            2. ctrl modifier -> Text change & Insert symbol
        """
        contextMenu = self.createStandardContextMenu()
        spellMenu = True

        if (QApplication.keyboardModifiers() & Qt.ControlModifier):
            spellMenu = False

        self.clearAction = QtGui.QAction(self.tr("Clear"), contextMenu)
        contextMenu.addSeparator()
        contextMenu.addAction(self.clearAction)
        if not len(self.toPlainText()):
            self.clearAction.setEnabled(False)
        QtCore.QObject.connect(self.clearAction,
                               QtCore.SIGNAL("triggered()"), self.clear)
        if not spellMenu:
            textOpsMenu = QMenu(self.tr("Text change..."))

            removeEOLAction = QtGui.QAction(self.tr("Join lines"),
                                            textOpsMenu, )
            textOpsMenu.addAction(removeEOLAction)
            QtCore.QObject.connect(removeEOLAction,
                                   QtCore.SIGNAL("triggered()"),
                                   self.removeEOL)

            textOpsMenu.addSeparator()

            toUppercaseAction = QtGui.QAction(self.tr("to UPPERCASE"),
                                              textOpsMenu)
            textOpsMenu.addAction(toUppercaseAction)
            QtCore.QObject.connect(toUppercaseAction,
                                   QtCore.SIGNAL("triggered()"),
                                   self.toUppercase)

            toLowercaseAction = QtGui.QAction(self.tr("to lowercase"),
                                              textOpsMenu)
            textOpsMenu.addAction(toLowercaseAction)
            QtCore.QObject.connect(toLowercaseAction,
                                   QtCore.SIGNAL("triggered()"),
                                   self.toLowercase)

            toTitleAction = QtGui.QAction(self.tr("to Title"), textOpsMenu)
            textOpsMenu.addAction(toTitleAction)
            QtCore.QObject.connect(toTitleAction,
                                   QtCore.SIGNAL("triggered()"),
                                   self.toTitlecase)

            toCapsAction = QtGui.QAction(self.tr("to Capitalize"), textOpsMenu)
            textOpsMenu.addAction(toCapsAction)
            QtCore.QObject.connect(toCapsAction,
                                   QtCore.SIGNAL("triggered()"), self.toCaps)

            contextMenu.insertSeparator(contextMenu.actions()[0])
            contextMenu.insertMenu(contextMenu.actions()[0], textOpsMenu)

            insertSymbolMenu = QMenu(self.tr("Insert symbol..."))
            settings_symbols = settings.get('editor:symbols')
            if settings_symbols:
                self.symbols = settings_symbols.split('\n')
            for symbol in self.symbols:
                action = SpellAction(symbol, insertSymbolMenu)
                action.correct.connect( self.insertSymbol)
                insertSymbolMenu.addAction(action)

            contextMenu.insertMenu(contextMenu.actions()[0], insertSymbolMenu)

        if not self.textCursor().hasSelection() and spellMenu:
            # Select the word under the cursor for spellchecker
            cursor = self.textCursor()
            cursor.select(QTextCursor.WordUnderCursor)

            self.setTextCursor(cursor)
            text = unicode(self.textCursor().selectedText())

            #TODO: put to configuration list of ignored starting/ending chars
            # remove u"„" from selection
            if text.startswith(u"„") or text.startswith(u"“"):
                text = text[1:]
                selectionEnd = cursor.selectionEnd()
                cursor.setPosition(cursor.position() - len(text))
                cursor.setPosition(selectionEnd, QTextCursor.KeepAnchor)
                self.setTextCursor(cursor)
            # remove u"”" from selection
            if text.endswith(u"”") or text.startswith(u"“"):
                selectionEnd = cursor.selectionEnd()
                cursor.setPosition(cursor.position() - len(text))
                cursor.setPosition(selectionEnd - 1, QTextCursor.KeepAnchor)
                text = text[:-1]
                self.setTextCursor(cursor)

            # Check if the selected word is misspelled and offer spelling
            # suggestions if it is.
            if self.textCursor().hasSelection():
                if not self.dict.check(text):
                    spell_menu = QMenu(self.tr("Spelling Suggestions"))
                    addWordAcction = QAction(self.tr('Add word...'),
                                             spell_menu)
                    QtCore.QObject.connect(addWordAcction,
                               QtCore.SIGNAL("triggered()"), self.addWord)
                    #addWordAcction.triggered.connect(self.addWord)
                    spell_menu.addAction(addWordAcction)
                    for word in self.dict.suggest(text):
                        action = SpellAction(word, spell_menu)
                        action.correct.connect(self.changeText)
                        spell_menu.addAction(action)
                    contextMenu.insertSeparator(contextMenu.actions()[1])
                    contextMenu.insertMenu(contextMenu.actions()[0],
                                            spell_menu)
                    # Only add the spelling suggests to the menu if there are
                    # suggestions.
                    if len(spell_menu.actions()) != 1:
                        spell_menu.insertSeparator(spell_menu.actions()[1])


        contextMenu.exec_(event.globalPos())
        event.accept()
예제 #47
0
    def contextMenuEvent(self, event):
        """ Creates two context menus:
            1. no modifier -> spellchecker & clear emnu
            2. ctrl modifier -> Text change & Insert symbol
        """
        contextMenu = self.createStandardContextMenu()
        spellMenu = True

        if (QApplication.keyboardModifiers() & Qt.ControlModifier):
            spellMenu = False

        self.clearAction = QtGui.QAction(self.tr("Clear"), contextMenu)
        contextMenu.addSeparator()
        contextMenu.addAction(self.clearAction)
        if not len(self.toPlainText()):
            self.clearAction.setEnabled(False)
        QtCore.QObject.connect(self.clearAction, QtCore.SIGNAL("triggered()"),
                               self.clear)
        if not spellMenu:
            textOpsMenu = QMenu(self.tr("Text change..."))

            removeEOLAction = QtGui.QAction(
                self.tr("Join lines"),
                textOpsMenu,
            )
            textOpsMenu.addAction(removeEOLAction)
            QtCore.QObject.connect(removeEOLAction,
                                   QtCore.SIGNAL("triggered()"),
                                   self.removeEOL)

            textOpsMenu.addSeparator()

            toUppercaseAction = QtGui.QAction(self.tr("to UPPERCASE"),
                                              textOpsMenu)
            textOpsMenu.addAction(toUppercaseAction)
            QtCore.QObject.connect(toUppercaseAction,
                                   QtCore.SIGNAL("triggered()"),
                                   self.toUppercase)

            toLowercaseAction = QtGui.QAction(self.tr("to lowercase"),
                                              textOpsMenu)
            textOpsMenu.addAction(toLowercaseAction)
            QtCore.QObject.connect(toLowercaseAction,
                                   QtCore.SIGNAL("triggered()"),
                                   self.toLowercase)

            toTitleAction = QtGui.QAction(self.tr("to Title"), textOpsMenu)
            textOpsMenu.addAction(toTitleAction)
            QtCore.QObject.connect(toTitleAction, QtCore.SIGNAL("triggered()"),
                                   self.toTitlecase)

            toCapsAction = QtGui.QAction(self.tr("to Capitalize"), textOpsMenu)
            textOpsMenu.addAction(toCapsAction)
            QtCore.QObject.connect(toCapsAction, QtCore.SIGNAL("triggered()"),
                                   self.toCaps)

            contextMenu.insertSeparator(contextMenu.actions()[0])
            contextMenu.insertMenu(contextMenu.actions()[0], textOpsMenu)

            insertSymbolMenu = QMenu(self.tr("Insert symbol..."))
            settings_symbols = settings.get('editor:symbols')
            if settings_symbols:
                self.symbols = settings_symbols.split('\n')
            for symbol in self.symbols:
                action = SpellAction(symbol, insertSymbolMenu)
                action.correct.connect(self.insertSymbol)
                insertSymbolMenu.addAction(action)

            contextMenu.insertMenu(contextMenu.actions()[0], insertSymbolMenu)

        if not self.textCursor().hasSelection() and spellMenu:
            # Select the word under the cursor for spellchecker
            cursor = self.textCursor()
            cursor.select(QTextCursor.WordUnderCursor)

            self.setTextCursor(cursor)
            text = unicode(self.textCursor().selectedText())

            #TODO: put to configuration list of ignored starting/ending chars
            # remove u"„" from selection
            if text.startswith(u"„") or text.startswith(u"“"):
                text = text[1:]
                selectionEnd = cursor.selectionEnd()
                cursor.setPosition(cursor.position() - len(text))
                cursor.setPosition(selectionEnd, QTextCursor.KeepAnchor)
                self.setTextCursor(cursor)
            # remove u"”" from selection
            if text.endswith(u"”") or text.startswith(u"“"):
                selectionEnd = cursor.selectionEnd()
                cursor.setPosition(cursor.position() - len(text))
                cursor.setPosition(selectionEnd - 1, QTextCursor.KeepAnchor)
                text = text[:-1]
                self.setTextCursor(cursor)

            # Check if the selected word is misspelled and offer spelling
            # suggestions if it is.
            if self.textCursor().hasSelection():
                if not self.dict.check(text):
                    spell_menu = QMenu(self.tr("Spelling Suggestions"))
                    addWordAcction = QAction(self.tr('Add word...'),
                                             spell_menu)
                    QtCore.QObject.connect(addWordAcction,
                                           QtCore.SIGNAL("triggered()"),
                                           self.addWord)
                    #addWordAcction.triggered.connect(self.addWord)
                    spell_menu.addAction(addWordAcction)
                    for word in self.dict.suggest(text):
                        action = SpellAction(word, spell_menu)
                        action.correct.connect(self.changeText)
                        spell_menu.addAction(action)
                    contextMenu.insertSeparator(contextMenu.actions()[1])
                    contextMenu.insertMenu(contextMenu.actions()[0],
                                           spell_menu)
                    # Only add the spelling suggests to the menu if there are
                    # suggestions.
                    if len(spell_menu.actions()) != 1:
                        spell_menu.insertSeparator(spell_menu.actions()[1])

        contextMenu.exec_(event.globalPos())
        event.accept()
예제 #48
0
파일: bot.py 프로젝트: zapdos26/Sailvation
import discord
from discord.ext import commands
from utils import settings
import os

bot = commands.Bot(command_prefix='!', description="A bot to assist Sailvation", case_insensitive=True)
config = settings.get('main.json')

for file in os.listdir("cogs"):
    if file.endswith(".py"):
        name = file[:-3]
        bot.load_extension(f"cogs.{name}")


@bot.event
async def on_ready():
    print('Logged in as')
    print(bot.user.name)
    print(bot.user.id)
    print('------')
    print(discord.utils.oauth_url(bot.user.id))
    game = discord.Game("Atlas")
    await bot.change_presence(activity=game)


@bot.event
async def on_command_error(ctx, error):
    if isinstance(error, commands.CommandOnCooldown):
        msg = ':exclamation: This command is on cooldown, please try again in {:.2f}s :exclamation:'.format(
            error.retry_after)
        await ctx.send(msg)
예제 #49
0
    def createActions(self):
        self.settingsAction = QAction(self.tr("Settings"), self)
        self.settingsAction.setIcon(QtGui.QIcon(":/icons/icons/configure.png"))
        self.settingsAction.triggered.connect(self.settings)
        self.addAction(self.settingsAction)

        self.saveDocAsAction = QAction(self.tr("Save As"), self)
        self.saveDocAsAction.triggered.connect(self.SaveDocumentAs)
        self.saveDocAsAction.setIcon(QtGui.QIcon(":/icons/icons/filesave.png"))
        self.addAction(self.saveDocAsAction)

        self.spellAction = QAction(self.tr("Spellchecking"), self)
        self.spellAction.setIcon(
            QtGui.QIcon(":/icons/icons/tools-check-spelling.png"))
        self.spellAction.setCheckable(True)
        self.spellAction.setChecked(settings.get('editor:spell'))
        self.spellAction.toggled.connect(self.spell)
        self.insertSeparator(self.spellAction)
        self.addAction(self.spellAction)

        self.whiteSpaceAction = QAction(self.tr("Show whitespace"), self)
        self.whiteSpaceAction.setIcon(
            QtGui.QIcon(":/icons/icons/whiteSpace.png"))
        self.whiteSpaceAction.setCheckable(True)
        self.whiteSpaceAction.setChecked(settings.get('editor:whiteSpace'))
        self.whiteSpaceAction.toggled.connect(self.whiteSpace)
        self.addAction(self.whiteSpaceAction)

        self.BoldAction = QtGui.QAction(
            QtGui.QIcon(":/icons/icons/format-text-bold.png"),
            self.tr("&Bold"),
            self,
            shortcut=QtCore.Qt.CTRL + QtCore.Qt.Key_B,
            triggered=self.bold,
            checkable=True)
        self.addAction(self.BoldAction)

        self.ItalicAction = QAction(self.tr("Italic"), self)
        self.ItalicAction.setIcon(
            QtGui.QIcon(":/icons/icons/format-text-italic.png"))
        self.ItalicAction.setShortcut(QtCore.Qt.CTRL + QtCore.Qt.Key_I)
        self.ItalicAction.setCheckable(True)
        self.ItalicAction.triggered.connect(self.italic)
        self.addAction(self.ItalicAction)

        self.UnderlineAction = QAction(self.tr("Underline"), self)
        self.UnderlineAction.setIcon(
            QtGui.QIcon(":/icons/icons/format-text-underline.png"))
        self.UnderlineAction.setCheckable(True)
        self.UnderlineAction.setShortcut(QtCore.Qt.CTRL + QtCore.Qt.Key_U)
        self.UnderlineAction.triggered.connect(self.underline)
        self.addAction(self.UnderlineAction)

        self.StrikethroughAction = QAction(self.tr("Strikethrough"), self)
        self.StrikethroughAction.setIcon(
            QtGui.QIcon(":/icons/icons/format-text-strikethrough.png"))
        self.StrikethroughAction.setCheckable(True)
        self.StrikethroughAction.triggered.connect(self.strikethrough)
        self.addAction(self.StrikethroughAction)

        self.SubscriptAction = QAction(self.tr("Subscript"), self)
        self.SubscriptAction.setIcon(
            QtGui.QIcon(":/icons/icons/format-text-subscript.png"))
        self.SubscriptAction.setCheckable(True)
        self.SubscriptAction.triggered.connect(self.subscript)
        self.addAction(self.SubscriptAction)

        self.SuperscriptAction = QAction(self.tr("Superscript"), self)
        self.SuperscriptAction.setIcon(
            QtGui.QIcon(":/icons/icons/format-text-superscript.png"))
        self.SuperscriptAction.setCheckable(True)
        self.SuperscriptAction.triggered.connect(self.superscript)
        self.addAction(self.SuperscriptAction)
예제 #50
0
    def doOcr(self):
        import codecs
        aItems = self.scene().areas
        numItems = len(aItems)

        if settings.get('editor:clear'):
            self.textEditor.clear()

        # clean temp to avoid false imports
        for oldOutPut in glob.glob('/tmp/out.[0-9]*.txt'):
            os.remove(oldOutPut)

        progress = QtGui.QProgressDialog(self.tr("Processing images..."),
                                         self.tr("Abort"), 0, numItems)
        progress.setWindowTitle(self.tr("Processing images..."))
        progress.setWindowModality(QtCore.Qt.WindowModal)
        # on MS Windows dialog has no icon
        progress.setWindowIcon(QtGui.QIcon(":/icons/icons/L.png"))
        progress.setMinimumDuration(0)
        progress.setValue(0)
        progress.setAutoClose(True)
        progress.setAutoReset(True)
        progress.forceShow()

        tess_exec = settings.get('tesseract-ocr:executable')
        if not tess_exec:
            tess_exec = 'tesseract'

        for i, item in enumerate(aItems):
            if progress.wasCanceled():
                break

            progress.setValue(i)
            rect = item.rect()
            pos = item.scenePos()

            box = (int(pos.x()), int(pos.y()), int(rect.width() + pos.x()), \
                    int(rect.height() + pos.y()))
            # TODO: make random filename if we do not debug lector ;-)
            # TODO: use png if tesseract version is > 3.00
            filename = "/tmp/out.%d.png" % i

            region = self.scene().im.crop(box)

            if item.type == 1:
                # Improve quality of text for tesseract
                # TODO: put it as option for OCR because of longer duration
                nx, ny = rect.width(), rect.height()
                region = region.resize((int(nx*3), int(ny*3)), \
                            Image.BICUBIC).convert('L')
                region.save(filename, dpi=(600, 600))
                # TODO: use html/hocr if tesseract version is > 3.01
                command = tess_exec + " %s /tmp/out.%d -l %s" % (filename, i,
                                                                 self.language)
                os.popen(command)

                if os.path.exists("/tmp/out.%d.txt" % i):
                    s = codecs.open("/tmp/out.%d.txt" % \
                        (i, ) , 'r', 'utf-8').read()
                    self.textEditor.append(s)
                    # TODO: delete image & OCR result if we do not debug lector
                else:
                    ## TODO: tesseract failed.
                    ## 1. process/print error message
                    ## 2. mark area as problematic
                    print "Tesseract was unabled to process area!"
                    # this can happend if left side of text is blury
            else:
                region = region.resize(
                    (region.size[0] / 4, region.size[1] / 4))
                region.save(filename)

                s = "<img src='%s'>" % filename
                self.textEditor.append(s)

        progress.setValue(numItems)
예제 #51
0
 def get_ping_color(cls, ping):
     if ping < settings.get('lag_ping_threshold'):
         return 255, 255, 255
     return 255, 100, 100
예제 #52
0
 def setEditorFont(self):
     self.setFont(QtGui.QFont(settings.get('editor:font')))
예제 #53
0
    def initSettings(self):
        self.ui.sbHeight.setValue(settings.get('scanner:height'))
        self.ui.sbWidth.setValue(settings.get('scanner:width'))
        self.ui.sbResolution.setValue(settings.get('scanner:resolution'))
        self.ui.combColor.setCurrentIndex(
            self.colors.index(settings.get('scanner:mode')))

        self.changeFont(QFont(settings.get('editor:font')))
        self.ui.checkBoxClear.setChecked(settings.get('editor:clear'))
        settings_symbols = settings.get('editor:symbols')
        if settings_symbols:
            self.ui.symbolList.setPlainText(settings_symbols)

        spellDictDir = settings.get('spellchecker:directory')
        self.ui.directoryLine.setText(spellDictDir)
        self.langList(spellDictDir)
        self.UItranslations()
        self.ui.checkBoxPWL.setChecked(settings.get('spellchecker:pwlLang'))
        pwlDict = settings.get('spellchecker:pwlDict')
        self.ui.lineEditPWL.setText(pwlDict)

        tessExec = settings.get('tesseract-ocr:executable')
        self.ui.lnTessExec.setText(tessExec)
        tessData = settings.get('tesseract-ocr:TESSDATA_PREFIX:')
        self.ui.lnTessData.setText(tessData)

        self.ui.cbLog.setChecked(settings.get('log:errors'))
        self.ui.lnLog.setText(settings.get('log:filename'))
예제 #54
0
    def createActions(self):
        self.settingsAction = QAction(self.tr("Settings"), self)
        self.settingsAction.setIcon(QtGui.QIcon(":/icons/icons/configure.png"))
        self.settingsAction.triggered.connect(self.settings)
        self.addAction(self.settingsAction)

        self.saveDocAsAction = QAction(self.tr("Save As"), self)
        self.saveDocAsAction.triggered.connect(self.SaveDocumentAs)
        self.saveDocAsAction.setIcon(QtGui.QIcon(":/icons/icons/filesave.png"))
        self.addAction(self.saveDocAsAction)

        self.spellAction = QAction(self.tr("Spellchecking"), self)
        self.spellAction.setIcon(
            QtGui.QIcon(":/icons/icons/tools-check-spelling.png"))
        self.spellAction.setCheckable(True)
        self.spellAction.setChecked(settings.get('editor:spell'))
        self.spellAction.toggled.connect(self.spell)
        self.insertSeparator(self.spellAction)
        self.addAction(self.spellAction)

        self.whiteSpaceAction = QAction(self.tr("Show whitespace"), self)
        self.whiteSpaceAction.setIcon(
            QtGui.QIcon(":/icons/icons/whiteSpace.png"))
        self.whiteSpaceAction.setCheckable(True)
        self.whiteSpaceAction.setChecked(settings.get('editor:whiteSpace'))
        self.whiteSpaceAction.toggled.connect(self.whiteSpace)
        self.addAction(self.whiteSpaceAction)

        self.BoldAction = QtGui.QAction(
                QtGui.QIcon(":/icons/icons/format-text-bold.png"),
                self.tr("&Bold"), self,
                shortcut=QtCore.Qt.CTRL + QtCore.Qt.Key_B,
                triggered=self.bold, checkable=True)
        self.addAction(self.BoldAction)

        self.ItalicAction = QAction(self.tr("Italic"), self)
        self.ItalicAction.setIcon(
            QtGui.QIcon(":/icons/icons/format-text-italic.png"))
        self.ItalicAction.setShortcut(QtCore.Qt.CTRL + QtCore.Qt.Key_I)
        self.ItalicAction.setCheckable(True)
        self.ItalicAction.triggered.connect(self.italic)
        self.addAction(self.ItalicAction)

        self.UnderlineAction = QAction(self.tr("Underline"), self)
        self.UnderlineAction.setIcon(
            QtGui.QIcon(":/icons/icons/format-text-underline.png"))
        self.UnderlineAction.setCheckable(True)
        self.UnderlineAction.setShortcut(QtCore.Qt.CTRL + QtCore.Qt.Key_U)
        self.UnderlineAction.triggered.connect(self.underline)
        self.addAction(self.UnderlineAction)

        self.StrikethroughAction = QAction(self.tr("Strikethrough"), self)
        self.StrikethroughAction.setIcon(
            QtGui.QIcon(":/icons/icons/format-text-strikethrough.png"))
        self.StrikethroughAction.setCheckable(True)
        self.StrikethroughAction.triggered.connect(self.strikethrough)
        self.addAction(self.StrikethroughAction)

        self.SubscriptAction = QAction(self.tr("Subscript"), self)
        self.SubscriptAction.setIcon(
            QtGui.QIcon(":/icons/icons/format-text-subscript.png"))
        self.SubscriptAction.setCheckable(True)
        self.SubscriptAction.triggered.connect(self.subscript)
        self.addAction(self.SubscriptAction)

        self.SuperscriptAction = QAction(self.tr("Superscript"), self)
        self.SuperscriptAction.setIcon(
            QtGui.QIcon(":/icons/icons/format-text-superscript.png"))
        self.SuperscriptAction.setCheckable(True)
        self.SuperscriptAction.triggered.connect(self.superscript)
        self.addAction(self.SuperscriptAction)