Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions JxPlugin/answer.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,8 @@ def JxTableDisplay(TupleList,Class,Type=None):
JxHtmlBuffer += u"""<tr class="Tr-Even">"""
Boolean = not(Boolean)
for Index in range(tupleStart,len(Tuple)):
JxHtmlBuffer += u'<td class="Td-' + JxInt2Name(Index) + u'">' + rubify(Tuple[Index].strip()) + u'</td>'
JxHtmlBuffer += u'<td class="Td-' + JxInt2Name(Index) + u'">' + rubify(Tuple[Index].strip(),"notaquestion") + u'</td>' # rubify needs another argument, I don't use ruby anyway...

JxHtmlBuffer += u"</tr>"

if len(JxHtmlBuffer):
Expand Down Expand Up @@ -153,8 +154,11 @@ def append_JxPlugin(Answer,Card):


# Guess the type(s) and the relevant content(s) of the Fact
from database import eDeck
types = eDeck.types[Card.factId]
from database import eDeck
try:
types = eDeck.types[Card.factId]
except KeyError:
return Answer
JxGuessedList = []
####################### the new type system breaks the old answer system : this is a quick and dirty fix ################################
try:
Expand Down
63 changes: 11 additions & 52 deletions JxPlugin/controls.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
# ---------------------------------------------------------------------------
import os
import cPickle
import re

from PyQt4.QtGui import *
from PyQt4.QtCore import *
Expand All @@ -19,6 +20,11 @@
from globalobjects import JxLink
from tools import ensureDirExists
from ui_menu import *
from answer import JxReplace

### apparently, importing stuff in class method makes anki crash in python 2.6... Got to test the software to see if it crashes in other places
from default import Jx__Css__Default
###

JxBase = QObject()

Expand All @@ -29,7 +35,7 @@ class Jx__Settings(QObject):
def __init__(self,name="JxSettings",parent=JxBase):
QObject.__init__(self,parent)
self.setObjectName(name)
self.File = os.path.join(mw.config.configPath, "plugins","JxPlugin", "Settings.pickle")
self.File = os.path.join(os.path.dirname(__file__ ), "Settings.pickle")
self.Load()

@pyqtSignature("QString", result="QString")
Expand All @@ -42,7 +48,7 @@ def Set(self,Key,Value):
self.Update()

def Load(self):
from default import Jx__Css__Default
### from default import Jx__Css__Default This makes Anki crash, funny isn't it ?
self.Dict = {"Mode":"Override","Css":Jx__Css__Default,'reportReset':'1','cacheRebuild':'14'}
if os.path.exists(self.File):
File = open(self.File, 'rb')
Expand Down Expand Up @@ -87,58 +93,13 @@ def set(self,var,value) :
eDeck.set_atomsKnownThreshold(float(value))
elif var =="kanjiMode":
eDeck.set_kanjiMode(int(value))

class Jx__Cache(QObject):
"""Data class for JxKnownThreshold, JxKnownCoefficient, JxCacheRefresh, JxCacheRebuild"""
def __init__(self,name,parent=JxBase):
QObject.__init__(self,parent)
self.setObjectName(name)

def refresh_fset(self,value):
self._cache_refresh = float(value)

#@pyqtSignature("",result="QString")
def refresh_fget(self):
return "%.1f" % self._cache_refresh

@Jx__Prop
def cache_refresh(): return {'fset': lambda self,value:self.refresh_fset(value),'fget': lambda self:self.refresh_fget()}

def rebuild_fset(self,value):
self._cache_rebuild = float(value)

#@pyqtSignature("",result="QString")
def rebuild_fget(self):
return "%.1f" % self._cache_rebuild

@Jx__Prop
def cache_rebuild(): return {'fset': lambda self,value:self.rebuild_fset(value),'fget': lambda self:self.rebuild_fget()}

def load(self):
from database import JxDeck
try:
self._card_threshold = JxDeck['CardThreshold']
self._fact_threshold = JxDeck['FactThreshold']
self._cache_refresh = JxDeck['CacheRefresh']
self._cache_rebuild = JxDeck['CacheRebuild']
except KeyError:
self._card_threshold = 21
self._fact_threshold = 1
self._cache_refresh = 1
self._cache_rebuild = 14
def save(self):
from database import JxDeck
JxDeck['CardThreshold'] = self._card_threshold
JxDeck['FactThreshold'] = self._fact_threshold
JxDeck['CacheRefresh'] = self._cache_refresh
JxDeck['CacheRebuild'] = self._cache_rebuild


class Jx__Entry_Source_Target(QObject):
"""Data class for the HtmlJavascript Entry/Name/Source/Target Widget"""
def __init__(self,name,parent=JxBase):
QObject.__init__(self,parent)
self.setObjectName(name)
self.File = os.path.join(mw.config.configPath, "plugins","JxPlugin","User","JxTable.cpickle")
self.File = os.path.join(os.path.dirname(__file__ ),"User","JxTable.cpickle")
if os.path.exists(self.File):
File = open(self.File, 'rb')
self.Table = cPickle.load(File)
Expand Down Expand Up @@ -485,7 +446,7 @@ def onClick(url):
String = unicode(url.toString())
if String.startswith("py:"):
String = String[3:]
from ui_menu import JxShowIn,JxShowOut
from ui_menu import JxShowIn,JxShowOut, JxBrowse
from export import JxAddo, JxDoNothing
eval(String)
else:
Expand All @@ -495,7 +456,6 @@ def onClick(url):
JxSettings = Jx__Settings()
JxTemplateOverride = Jx__Entry_Source_Target("JxTemplateOverride")
Jx_Control_Tags = Jx__MultiSelect('JxTags',JxBase)
Jx_Control_Cache = Jx__Cache('JxCache',JxBase)
Jx_Control_Bridge = PythonJavascript('py',JxBase)

class Jx__Menu(QWebView):
Expand All @@ -521,7 +481,6 @@ def BridgeToJavascript(self): # I should automate this todo
self.page().mainFrame().addToJavaScriptWindowObject("JxTemplateOverride",JxTemplateOverride)
self.page().mainFrame().addToJavaScriptWindowObject("JxSettings",JxSettings)
self.page().mainFrame().addToJavaScriptWindowObject("JxTags",Jx_Control_Tags)
self.page().mainFrame().addToJavaScriptWindowObject("JxCache",Jx_Control_Cache)
self.page().mainFrame().addToJavaScriptWindowObject("py",Jx_Control_Bridge)
@pyqtSignature("")
def Hide(self):
Expand Down
8 changes: 4 additions & 4 deletions JxPlugin/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,7 @@ def reference_data(self):

def load(self):
"""returns the cache if it exists on disk and {} if it doesn't"""
path = os.path.join(mw.config.configPath, "plugins", "JxPlugin", "Cache", mw.deck.name() + ".cache")
path = os.path.join(os.path.dirname(__file__ ), "Cache", mw.deck.name() + ".cache")
if not os.path.exists(path):
self.cache = {}
else:
Expand All @@ -226,7 +226,7 @@ def save(self):
from ui_menu import JxStats
"""saves the cache on disk"""
ensureDirExists("Cache")
path = os.path.join(mw.config.configPath, "plugins", "JxPlugin", "Cache", mw.deck.name() + ".cache")
path = os.path.join(os.path.dirname(__file__ ), "Cache", mw.deck.name() + ".cache")
file = open(path, 'wb')
cPickle.dump(self.cache, file, cPickle.HIGHEST_PROTOCOL)
file.close()
Expand Down Expand Up @@ -680,7 +680,7 @@ def extend_atoms_history(self):
self.extend_graphs(workload)

def extend_graphs(self,load):
"""adds to graphs if sign = 1 and subs to graph if qign = -1"""
"""adds to graphs if sign = 1 and subs to graph if sign = -1"""

loadGet = load.get
for myType in ['words','kanji']:
Expand Down Expand Up @@ -804,7 +804,7 @@ def set_stats(self,sign):


def set_graphs(self,sign):
"""adds to graphs if sign = 1 and subs to graph if qign = -1"""
"""adds to graphs if sign = 1 and subs to graph if sign = -1"""

if sign != 0:
load = self.compute_load(self.graphsWorkload,self.atomsHistory)
Expand Down
2 changes: 1 addition & 1 deletion JxPlugin/hack.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from ankiqt import mw

# directory where QTWebKit will look for resources
JxResourcesUrl = QUrl.fromLocalFile(os.path.join(mw.config.configPath, "plugins","JxPlugin","Resources") + os.sep)
JxResourcesUrl = QUrl.fromLocalFile(os.path.join(os.path.dirname(__file__ ),"Resources") + os.sep)

# "hack" to overload mw.help.anchorClicked
def JxAnchorClicked(url):
Expand Down
16 changes: 8 additions & 8 deletions JxPlugin/html.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@

$("#knowncoefficient").slider({
value:py.get('factsKnownThreshold'),
min: 0.01,
min: 0.00,
max: 1,
step: 0.01,
stop: function(event, ui) {
Expand All @@ -164,7 +164,7 @@
$("#atomsknowncoefficientvalue").val(Math.round($("#atomsknowncoefficient").slider("value") *100) + " %");
$("#atomsknowncoefficient").slider({
value:py.get('atomsKnownThreshold'),
min: 0.01,
min: 0.00,
max: 1,
step: 0.01,
stop: function(event, ui) {
Expand Down Expand Up @@ -682,12 +682,12 @@
myReport += series.label + ': ' + format(dataset[j].data[i][1]) +'<br>'
s += dataset[j].data[i][1];
}
if (delta>0)
myString += format(s) + '<sup>&nbsp;<font face="Comic Sans MS" color="green" size=2>+'+format(delta)+'</font></sup><br>'+ myReport
if (delta<0)
myString+= format(s) + '<sup>&nbsp;<font face="Comic Sans MS" color="red" size=2>-'+format(-delta)+'</font></sup><br>'+myReport
if (delta==0)
myString += format(s) +'<br>'+ myReport
if (delta>0)
myString += format(s) + '<sup>&nbsp;<font face="Comic Sans MS" color="green" size=2>+'+format(delta)+'</font></sup><br>'+ myReport
if (delta<0)
myString+= format(s) + '<sup>&nbsp;<font face="Comic Sans MS" color="red" size=2>-'+format(-delta)+'</font></sup><br>'+myReport
if (delta==0)
myString += format(s) +'<br>'+ myReport
showTooltip(item.pageX, item.pageY,myString);
}
}
Expand Down
5 changes: 4 additions & 1 deletion JxPlugin/japan.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
# This file is a plugin for the "anki" flashcard application http://ichi2.net/anki/
# ---------------------------------------------------------------------------
"""Ideally, all japanese specific constants, variables, functions should go in there (in case we want to support other languages in the future)"""
from ankiqt import mw

# beware... if this file is named "japanese", it creates import problems with the japanese support plugin

Expand Down Expand Up @@ -45,7 +46,8 @@ def setup(self):
os.environ['PATH'] += (";%s\\mecab\\bin" % dir)
os.environ['MECABRC'] = ("%s\\mecab\\etc\\mecabrc" % dir)
elif sys.platform.startswith("darwin"):
dir = os.path.abspath(os.path.dirname(__file__) + "/../japanese/") + "/"
dir = os.path.abspath(os.path.dirname(__file__) + "/../japanese/") + "/"
# I should use a path guessing scheme on the module name there
os.environ['PATH'] += ":" + dir + "/osx/mecab/bin"
os.environ['MECABRC'] = dir + "/osx/mecab/etc/mecabrc"
os.environ['DYLD_LIBRARY_PATH'] = dir + "/osx/mecab/bin"
Expand Down Expand Up @@ -122,6 +124,7 @@ def parse_content(string,type,kanjiMode):
# alternative is word/sentence type
# first mecab the string
list = call_mecab(string)

# then we have got to extract relevant info from the mecab output
number = 0
lastType = None
Expand Down
4 changes: 2 additions & 2 deletions JxPlugin/jmdic.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,13 +96,13 @@ def end_element(Name):



File = join(mw.config.configPath, "plugins","JxPlugin","Data", "JMdict.gz")
File = join(os.path.dirname(__file__ ),"Data", "JMdict.gz")



import cPickle, os
import itertools
file_pickle = os.path.join(mw.config.configPath, "plugins","JxPlugin","Data", "JMdict.pickle")
file_pickle = os.path.join(os.path.dirname(__file__ ),"Data", "JMdict.pickle")
if False:#(os.path.exists(file_pickle) and os.stat(file_pickle).st_mtime > os.stat(File).st_mtime):
f = open(file_pickle, 'rb')
JxJMdic = cPickle.load(f)
Expand Down
4 changes: 2 additions & 2 deletions JxPlugin/kanjidic.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,13 +82,13 @@ def end_element(Name):



File = join(mw.config.configPath, "plugins","JxPlugin","Data", "Kanjidic2.xml.gz")
File = join(os.path.dirname(__file__ ),"Data", "Kanjidic2.xml.gz")



import cPickle, os
import itertools
file_pickle = os.path.join(mw.config.configPath, "plugins","JxPlugin","Data", "Kanjidic.pickle")
file_pickle = os.path.join(os.path.dirname(__file__ ),"Data", "Kanjidic.pickle")
if (os.path.exists(file_pickle) and os.stat(file_pickle).st_mtime > os.stat(File).st_mtime):
f = open(file_pickle, 'rb')
JxKanjidic = cPickle.load(f)
Expand Down
10 changes: 5 additions & 5 deletions JxPlugin/loaddata.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ def Tango2Dic(string):
######################################################################

Word2Data = {}
for List in JxReadFile(os.path.join(mw.config.configPath, "plugins","JxPlugin","Data", "JLPT.Word.List.csv")):
for List in JxReadFile(os.path.join(os.path.dirname(__file__ ),"Data", "JLPT.Word.List.csv")):
if List[1].strip():
Word2Data[List[1].strip()] = int(List[4])
else:
Expand All @@ -149,15 +149,15 @@ def Tango2Dic(string):
#
######################################################################

Kanji2Kanken = dict([(List[0].strip(),List[1].strip()) for List in JxReadFile(os.path.join(mw.config.configPath, "plugins","JxPlugin","Data", "Kanken.csv"))])
Kanji2Kanken = dict([(List[0].strip(),List[1].strip()) for List in JxReadFile(os.path.join(os.path.dirname(__file__ ),"Data", "Kanken.csv"))])

######################################################################
#
# Frequency for Kanji
#
######################################################################

Jx_Kanji_Occurences = dict((List[0].strip(),int(List[1])) for List in JxReadFile(os.path.join(mw.config.configPath, "plugins","JxPlugin","Data", "KanjiFrequencyWikipedia.csv")))
Jx_Kanji_Occurences = dict((List[0].strip(),int(List[1])) for List in JxReadFile(os.path.join(os.path.dirname(__file__ ),"Data", "KanjiFrequencyWikipedia.csv")))
Jx_Kanji_MaxOccurences = max(Jx_Kanji_Occurences.values()) #inneficient but pythonic
Jx_Kanji_SumOccurences = sum(Jx_Kanji_Occurences.values())

Expand All @@ -170,7 +170,7 @@ def Tango2Dic(string):
#
######################################################################

Jx_Word_Occurences = dict([(List[0].strip(),int(List[1])) for List in JxReadFile(os.path.join(mw.config.configPath, "plugins","JxPlugin","Data", "CorpusInternet.csv"))])
Jx_Word_Occurences = dict([(List[0].strip(),int(List[1])) for List in JxReadFile(os.path.join(os.path.dirname(__file__ ),"Data", "CorpusInternet.csv"))])

Jx_Word_SumOccurences = sum(Jx_Word_Occurences.values())
Jx_Word_MaxOccurences = max(Jx_Word_Occurences.values())
Expand All @@ -191,7 +191,7 @@ def Tango2Dic(string):

# import cPickle
#import itertools
#file_pickle = os.path.join(mw.config.configPath, "plugins","JxPlugin","Data", "Word2Data.pickle")
#file_pickle = os.path.join(os.path.dirname(__file__ ),"Data", "Word2Data.pickle")
# if (os.path.exists(file_pickle) and
# os.stat(file_pickle).st_mtime > os.stat(file).st_mtime):
# f = open(file_pickle, 'rb')
Expand Down
2 changes: 1 addition & 1 deletion JxPlugin/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@

def ensureDirExists(myDir):
"""creates a dir subdirectory of plugins/JxPlugin/ if it doesn't exist"""
path = os.path.join(mw.config.configPath, "plugins", "JxPlugin", myDir)
path = os.path.join(os.path.dirname(__file__ ), myDir)
if not(os.path.isdir(path)):
try:
os.mkdir(path)
Expand Down
7 changes: 6 additions & 1 deletion JxPlugin/ui_menu.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,11 @@ def init_JxPlugin():
# Adding features through hooks !
mw.addHook('drawAnswer', append_JxPlugin) # additional info in answer cards
mw.addHook('deckClosed', JxWindow.hide) # hides the main Jxplugin window when the current deck is closed

# this is needed for people who open Anki by double clicking on an Anki deck (it bypasses newLoadDeck)
if (mw.deck):
from database import build_JxDeck
build_JxDeck()

# adds JxPlugin to the list of plugin to process in Anki
mw.addHook('init', init_JxPlugin)
Expand All @@ -176,7 +181,7 @@ def init_JxPlugin():
oldLoadDeck = mw.loadDeck

def newLoadDeck(deckPath, sync=True, interactive=True, uprecent=True,media=None):
code = oldLoadDeck(deckPath, sync, interactive, uprecent,media)
code = oldLoadDeck(deckPath, sync, interactive, uprecent)
if code and mw.deck:
from database import build_JxDeck
build_JxDeck()
Expand Down