def addClicked(self):
        try:
            model = self.ensureKanjiModelExists()

            fact = mw.deck.newFact(model)
            #TODO pull data from UI field
            fact[u'Kanji'] = self.currentKanji
            fact[u'HeisigFrameID'] = u"heisig:%s" % self.currentKanjiFrame
            fact[u'Keyword'] = unicode(self.fld_keyword.text())
            fact[u'Story'] = unicode(self.fld_story.toPlainText())
            fact[u'PrimitiveMeanings'] = unicode(
                self.fld_primitives.toPlainText())

            strokeDiagramPath = os.path.join(mw.pluginsFolder(),
                                             u'JPdictionaryFiles', u'sod-utf8',
                                             self.currentKanji + u'.png')
            if os.path.exists(strokeDiagramPath):
                ankiDiagramPath = mw.deck.addMedia(strokeDiagramPath)
                fact[u'Image_StrokeOrderDiagram'] = u'<img src="%s"/>' % (
                    ankiDiagramPath)
            else:
                fact[u'Image_StrokeOrderDiagram'] = u""

            strokeAnimationPath = os.path.join(mw.pluginsFolder(),
                                               u'JPdictionaryFiles',
                                               u'soda-utf8',
                                               self.currentKanji + u'.gif')
            if os.path.exists(strokeAnimationPath):
                ankiAnimationPath = mw.deck.addMedia(strokeAnimationPath)
                fact[u'Image_StrokeOrderAnimation'] = u'<img src="%s" />' % (
                    ankiAnimationPath)
            else:
                fact[u'Image_StrokeOrderAnimation'] = u""

            newfact = mw.deck.addFact(fact)
            thecard = None
            for card in newfact.cards:
                thecard = mw.deck.cardFromId(card.id)
                mw.deck.answerCard(thecard, 2)
            mw.deck.save()
            mw.reset()
            self.statusLabel.setText("Added card for kanji: %s" %
                                     self.currentKanji)
            self.reviewerWidget.addQuestionAnswerForReview(
                unicode(self.fld_keyword.text()), self.currentKanji)
            self.incrementKanji()
        except:
            logpath = os.path.join(mw.pluginsFolder(), "log-rtk-importer.txt")
            log = open(logpath, 'a')
            log.write(traceback.format_exc())
            log.flush()
            log.close()
            QMessageBox.warning(
                mw, "Warning",
                "Your card may contain duplicate data. Please check that you have the correct keyword and that you haven't re-used the keyword or story before by accident. If you are sure there is no duplicate, then please contact the developer."
            )
 def addClicked(self):
     try:
         model = self.ensureKanjiModelExists()
         
         fact = mw.deck.newFact(model)
         #TODO pull data from UI field
         fact[u'Kanji'] = self.currentKanji
         fact[u'HeisigFrameID'] = u"heisig:%s" % self.currentKanjiFrame
         fact[u'Keyword'] = unicode(self.fld_keyword.text())
         fact[u'Story'] = unicode(self.fld_story.toPlainText())
         fact[u'PrimitiveMeanings'] = unicode(self.fld_primitives.toPlainText())
         
         strokeDiagramPath = os.path.join(mw.pluginsFolder(), u'JPdictionaryFiles', u'sod-utf8', self.currentKanji + u'.png')
         if os.path.exists(strokeDiagramPath):
             ankiDiagramPath = mw.deck.addMedia(strokeDiagramPath)
             fact[u'Image_StrokeOrderDiagram'] = u'<img src="%s"/>' % (ankiDiagramPath)
         else:
             fact[u'Image_StrokeOrderDiagram'] = u""
         
         strokeAnimationPath = os.path.join(mw.pluginsFolder(), u'JPdictionaryFiles', u'soda-utf8', self.currentKanji + u'.gif')
         if os.path.exists(strokeAnimationPath):
             ankiAnimationPath = mw.deck.addMedia(strokeAnimationPath)
             fact[u'Image_StrokeOrderAnimation'] = u'<img src="%s" />' % (ankiAnimationPath)
         else:
             fact[u'Image_StrokeOrderAnimation'] = u""
         
         newfact = mw.deck.addFact(fact)
         thecard = None
         for card in newfact.cards:
             thecard = mw.deck.cardFromId(card.id)
             mw.deck.answerCard(thecard, 2)
         mw.deck.save()
         mw.reset()
         self.statusLabel.setText("Added card for kanji: %s" % self.currentKanji)
         self.reviewerWidget.addQuestionAnswerForReview(unicode(self.fld_keyword.text()), self.currentKanji)
         self.incrementKanji()
     except:
         logpath = os.path.join(mw.pluginsFolder(), "log-rtk-importer.txt")
         log = open(logpath, 'a')
         log.write(traceback.format_exc())
         log.flush()
         log.close()
         QMessageBox.warning(mw, "Warning","Your card may contain duplicate data. Please check that you have the correct keyword and that you haven't re-used the keyword or story before by accident. If you are sure there is no duplicate, then please contact the developer.")
Beispiel #3
0
#-*- coding: utf-8 -*-
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from anki.hooks import addHook
from anki.facts import Fact
from ankiqt import mw

import datetime, os

VERBOSE = False
NO_LOG = False

logPath = os.path.join(mw.pluginsFolder(), 'morph', 'tests', 'auto.log')
dbPath = mw.pluginsFolder() + os.sep + 'morph' + os.sep + 'dbs' + os.sep
knownDbPath = os.path.join(mw.pluginsFolder(), 'morph', 'dbs', 'known.db')
matureDbPath = os.path.join(mw.pluginsFolder(), 'morph', 'dbs', 'mature.db')
deckDbPath = os.path.join(mw.pluginsFolder(), 'morph', 'dbs', 'deck')
deckPaths = mw.config['recentDeckPaths']
updater = None  # updater thread
lastUpdate = None  # last time full update finished in this anki instance


def sigterm(p):
    try:
        p.terminate()
    except AttributeError:
        pass


def killMecab(st):
    sigterm(st['mp'])
Beispiel #4
0
#!/usr/bin/env python
from ankiqt import mw
from ankiqt.ui.main import AnkiQt
from anki.hooks import wrap
from anki import sound
import os
from threading import Timer

d = { 6.0:'SuperMarioBrothers-OutOfTime.mp3'
    , 10.0:'GameshowBellDing3.mp3'
    }
basePath = mw.pluginsFolder() + os.sep + 'timerSounds'
ts = []

# :: FilePath -> Audio ()
def play( sPath ):
   path = basePath + os.sep + sPath
   path = path.replace( os.sep, os.sep*2 ) # fix for windows
   print 'playing:', path
   sound.play( path )

# :: AnkiQt -> Response -> m ()
def onPreCardAnswered( self, r ):
   print 'resetting timers'
   global ts
   [ t.cancel() for t in ts ]
   ts = [ Timer( dur, play, args=[path] ) for dur,path in d.items() ]
   [ t.start() for t in ts ]

AnkiQt.cardAnswered = wrap(AnkiQt.cardAnswered, onPreCardAnswered, pos="before")
mw.registerPlugin( 'jmrTimer', 2011012918 )
    def __init__(self):
        QtGui.QDialog.__init__(self)
        heisigSqlFile = os.path.join(mw.pluginsFolder(), "JPdictionaryFiles",
                                     "RTKkanji.sqlite")
        self.conn = sqlite.connect(heisigSqlFile)
        self.conn.row_factory = sqlite.Row
        self.cursor = self.conn.cursor()

        self.currentKanjiFrame = None
        self.determineNextKanji()

        self.setObjectName("RTK Kanji Import")
        self.setWindowTitle(_("RTK Kanji Import"))
        self.resize(450, 600)

        #main layout
        self.vboxlayout = QtGui.QVBoxLayout(self)
        self.vboxlayout.setObjectName("vboxlayout")

        #embedded reviewer for added kanji
        self.reviewerWidget = EmbeddedReviewer(mw, self, self.vboxlayout)

        #settings sublayout
        self.settingsBox = QtGui.QGroupBox("Card Details", self)
        self.settingsLayout = QtGui.QVBoxLayout(self.settingsBox)
        self.vboxlayout.addWidget(self.settingsBox)

        #   kanji label
        self.kanjiLabel = QtGui.QLabel("<b>" + _("Kanji") + "</b>" +
                                       (": %s" % self.currentKanji))
        self.settingsLayout.addWidget(self.kanjiLabel)
        #   keyword
        self.settingsLayout.addWidget(QtGui.QLabel(_("Keyword:")))
        self.fld_keyword = QtGui.QLineEdit(self)
        self.fld_keyword.setObjectName("keyword")
        self.fld_keyword.setMinimumSize(100, 20)
        self.settingsLayout.addWidget(self.fld_keyword)
        #   story
        self.settingsLayout.addWidget(QtGui.QLabel(_("Story:")))
        self.fld_story = QtGui.QTextEdit(self)
        self.fld_story.setObjectName("story")
        self.fld_story.setMinimumSize(100, 100)
        self.settingsLayout.addWidget(self.fld_story)
        #   primitive meanings
        self.settingsLayout.addWidget(QtGui.QLabel(_("Primitive Meanings:")))
        self.fld_primitives = QtGui.QTextEdit(self)
        self.fld_primitives.setObjectName("primitives")
        self.fld_primitives.setMinimumSize(100, 100)
        self.settingsLayout.addWidget(self.fld_primitives)

        #   status label
        self.statusLabel = QtGui.QLabel("")
        self.vboxlayout.addWidget(self.statusLabel)

        self.addButton = QtGui.QPushButton(self)
        self.addButton.setText(_("Add Kanji"))
        self.addButton.setDefault(True)
        self.vboxlayout.addWidget(self.addButton)

        self.cancelButton = QtGui.QPushButton(self)
        self.cancelButton.setText(_("Finish"))
        self.vboxlayout.addWidget(self.cancelButton)

        self.connect(self.addButton, QtCore.SIGNAL("clicked()"),
                     self.addClicked)
        self.connect(self.cancelButton, QtCore.SIGNAL("clicked()"),
                     self.cancelClicked)
        self.fld_keyword.setFocus()
        self.exec_()
Beispiel #6
0
def runImport(modelManager, importSettings):
    progress = ProgressTracker(os.path.join(mw.pluginsFolder(), "iknow-smartfm-log.txt"))
    try:
        importSettings.saveToConfig()
        iknow = SmartFMAPI()
        iknowList = iknow.list(importSettings.listId)
        try:
            if iknowList.language and iknowList.language == "ja":
                modelManager.tagModelsAsJapanese()
        except:
            progress.logMsg("Error trying to tag models as Japanese")
            progress.logMsg(traceback.format_exc())
            pass
        iknow.setCallback(progress.downloadCallback)
        items = iknow.listItems(importSettings.listId, (importSettings.importVocab or importSettings.includeItemMeaning), importSettings.importSentences)
        progress.preImportResetProgress(len(items))
        totalImported = 0
        totalDup = 0
        totalFormattingErrors = 0
        totalImportedByType = {"item" : 0, "sentence" : 0}
        for i, item in enumerate(items):
            if importSettings.maxItems > 0 and totalImported >= importSettings.maxItems:
                break
            if not importSettings.importSentences and item.type == "sentence":
                continue
            if not importSettings.importVocab and item.type == "item":
                continue
            if formatIknowItemPreImport(item, iknowList, importSettings, iknowList.isBilingual(), progress):
                progress.importCallback(i, item.expression)
                if importIknowItem(item, modelManager.sentenceModel, modelManager.vocabModel, importSettings, progress):
                    totalImported += 1
                    totalImportedByType[item.type] = totalImportedByType[item.type] + 1
                else:
                    totalDup += 1
            else:
                totalFormattingErrors += 1
        progress.dialog.cancel()
        progress.close()
        mw.deck.save()
        resultStr = "Import complete. Imported %s items, %s sentences, and skipped %s duplicates." % (totalImportedByType["item"], totalImportedByType["sentence"], totalDup)
        if totalFormattingErrors > 0:
            resultStr += " %s items were skipped because there was no translation available on smart.fm." % totalFormattingErrors
        QMessageBox.information(mw, "Summary", resultStr)
        mw.reset(mw.mainWin)
    except AudioDownloadError:
        progress.logMsg(traceback.format_exc())
        progress.dialog.cancel()
        progress.close()
        QMessageBox.warning(mw, "Warning", "Data for one item could not be retrieved even after several retries. This may be caused by a slower internet connection or smart.fm's (occasionally slow) servers. Please try your import again.")
        mw.reset(mw.mainWin)
    except AddMediaException:
        progress.logMsg(traceback.format_exc())
        progress.dialog.cancel()
        progress.close()
        QMessageBox.warning(mw, "Warning", "Anki was unable to add an audio file to your deck. This may be caused by a problem with Anki, the smart.fm! plugin, or both. Please inform the plugin developer.")
        mw.reset(mw.mainWin)
    except SmartFMDownloadError:
        progress.logMsg(traceback.format_exc())
        progress.dialog.cancel()
        progress.close()
        QMessageBox.warning(mw,"Warning","There was a problem retrieving data from Smart.fm. When you hit 'OK', a browser window will open to check that you can reach smart.fm.<br /><br />If this browser window shows an error, then please wait for smart.fm to be fixed, and try importing cards again. If there is no error in the browser window and you see some content relevant to your study list, please notify the plugin developer at http://github.com/ridisculous/anki-iknow-importer/issues")
        try:
            QDesktopServices.openUrl(QUrl(iknow.lastUrlFetched))
        except:
            pass
        mw.reset(mw.mainWin)
    except:
        progress.logMsg(traceback.format_exc())
        progress.dialog.cancel()
        progress.close()
        QMessageBox.warning(mw, "Warning", "There was an unknown error importing items. Please contact the plugin developer at http://github.com/ridisculous/anki-iknow-importer/issues<br /><br />Please be sure to include the file 'iknow-smartfm-log.txt' from your plugins directory with a description of what you tried to do before this error.")
        mw.reset(mw.mainWin)
    def __init__(self):
        QtGui.QDialog.__init__(self)
        heisigSqlFile = os.path.join(mw.pluginsFolder(), "JPdictionaryFiles", "RTKkanji.sqlite")
        self.conn = sqlite.connect(heisigSqlFile)
        self.conn.row_factory = sqlite.Row
        self.cursor = self.conn.cursor()
        
        self.currentKanjiFrame = None
        self.determineNextKanji()
        
        self.setObjectName("RTK Kanji Import")
        self.setWindowTitle(_("RTK Kanji Import"))
        self.resize(450, 600)
        
        #main layout
        self.vboxlayout = QtGui.QVBoxLayout(self)
        self.vboxlayout.setObjectName("vboxlayout")
        
        #embedded reviewer for added kanji
        self.reviewerWidget = EmbeddedReviewer(mw, self, self.vboxlayout)
        
        #settings sublayout
        self.settingsBox = QtGui.QGroupBox("Card Details", self)
        self.settingsLayout = QtGui.QVBoxLayout(self.settingsBox)
        self.vboxlayout.addWidget(self.settingsBox)

        #   kanji label
        self.kanjiLabel = QtGui.QLabel("<b>" + _("Kanji") + "</b>" + (": %s" % self.currentKanji))
        self.settingsLayout.addWidget(self.kanjiLabel)
        #   keyword
        self.settingsLayout.addWidget(QtGui.QLabel(_("Keyword:")))
        self.fld_keyword = QtGui.QLineEdit(self)
        self.fld_keyword.setObjectName("keyword")
        self.fld_keyword.setMinimumSize(100,20)
        self.settingsLayout.addWidget(self.fld_keyword)
        #   story
        self.settingsLayout.addWidget(QtGui.QLabel(_("Story:")))
        self.fld_story = QtGui.QTextEdit(self)
        self.fld_story.setObjectName("story")
        self.fld_story.setMinimumSize(100,100)
        self.settingsLayout.addWidget(self.fld_story)
        #   primitive meanings
        self.settingsLayout.addWidget(QtGui.QLabel(_("Primitive Meanings:")))
        self.fld_primitives = QtGui.QTextEdit(self)
        self.fld_primitives.setObjectName("primitives")
        self.fld_primitives.setMinimumSize(100,100)
        self.settingsLayout.addWidget(self.fld_primitives)
        
        #   status label
        self.statusLabel = QtGui.QLabel("")
        self.vboxlayout.addWidget(self.statusLabel)
        
        self.addButton = QtGui.QPushButton(self)
        self.addButton.setText(_("Add Kanji"))
        self.addButton.setDefault(True)
        self.vboxlayout.addWidget(self.addButton)
        
        self.cancelButton = QtGui.QPushButton(self)
        self.cancelButton.setText(_("Finish"))
        self.vboxlayout.addWidget(self.cancelButton)
        
        self.connect(self.addButton, QtCore.SIGNAL("clicked()"), self.addClicked)
        self.connect(self.cancelButton, QtCore.SIGNAL("clicked()"), self.cancelClicked)
        self.fld_keyword.setFocus()
        self.exec_()
Beispiel #8
0
#-*- coding: utf-8 -*-
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from anki.hooks import addHook
from anki.facts import Fact
from ankiqt import mw

import datetime, os
import codecs

VERBOSE = False
NO_LOG = False

logPath = os.path.join( mw.pluginsFolder(),'morph','tests','auto.log' )
dbPath = mw.pluginsFolder() + os.sep + 'morph' + os.sep + 'dbs' + os.sep
knownDbPath = os.path.join( mw.pluginsFolder(),'morph','dbs','known.db' )
matureDbPath = os.path.join( mw.pluginsFolder(),'morph','dbs','mature.db' )
deckDbPath = os.path.join( mw.pluginsFolder(),'morph','dbs','deck' )
deckPaths = mw.config['recentDeckPaths']
updater = None # updater thread
lastUpdate = None # last time full update finished in this anki instance

def sigterm( p ):
   try: p.terminate()
   except AttributeError: pass
def killMecab( st ): sigterm( st['mp'] )

def getBlacklist( ed, default=u'記号,助詞' ):
   bs, ok = QInputDialog.getText( ed, 'Comma delimited', 'Blacklist parts of speech', QLineEdit.Normal, default )
   if not ok: bs = default
   return bs.split(',')
Beispiel #9
0
#-*- coding: utf-8 -*-
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from anki.hooks import addHook
from anki.facts import Fact
from ankiqt import mw

import os
import morphemes

dbPath = mw.pluginsFolder() + os.sep + 'morph' + os.sep + 'dbs' + os.sep
knownDbPath = dbPath + 'known.db'

def getBlacklist( ed, default=u'記号,助詞' ):
   bs, ok = QInputDialog.getText( ed, 'Comma delimited', 'Blacklist parts of speech', QLineEdit.Normal, default )
   if not ok: bs = default
   return bs.split(',')

def requireKnownDb(): # returns false if failed
   global knownDbPath
   if os.path.exists( knownDbPath ): return True
   knownDbPath = QFileDialog.getOpenFileName( caption="Can't find known morphemes db", directory=knownDbPath )
   if not knownDbPath:
      QMessageBox.critical( None, 'ERROR!', 'Cannot proceed without a known morphemes db' )
      return False
   return True

def doOnSelection( ed, overviewMsg, progMsg, preF, perF, postF ):
   # init
   st = preF( ed )
   if st == 'BAIL': return
Beispiel #10
0
# -*- coding: utf-8 -*-
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from anki.hooks import addHook
from anki.facts import Fact
from ankiqt import mw

import datetime, os

VERBOSE = False
NO_LOG = False

logPath = os.path.join(mw.pluginsFolder(), "morph", "tests", "auto.log")
dbPath = mw.pluginsFolder() + os.sep + "morph" + os.sep + "dbs" + os.sep
knownDbPath = os.path.join(mw.pluginsFolder(), "morph", "dbs", "known.db")
matureDbPath = os.path.join(mw.pluginsFolder(), "morph", "dbs", "mature.db")
deckDbPath = os.path.join(mw.pluginsFolder(), "morph", "dbs", "deck")
deckPaths = mw.config["recentDeckPaths"]
updater = None  # updater thread
lastUpdate = None  # last time full update finished in this anki instance


def sigterm(p):
    try:
        p.terminate()
    except AttributeError:
        pass


def killMecab(st):
    sigterm(st["mp"])