drop i18n references in old stats

This commit is contained in:
Damien Elmes 2020-11-18 08:51:57 +10:00
parent e527d31dfc
commit e9cd956acd
3 changed files with 94 additions and 110 deletions

View file

@ -14,7 +14,6 @@ from xml.dom.minidom import Element, Text
from anki.collection import Collection from anki.collection import Collection
from anki.importing.noteimp import ForeignCard, ForeignNote, NoteImporter from anki.importing.noteimp import ForeignCard, ForeignNote, NoteImporter
from anki.lang import _, ngettext
from anki.stdmodels import addBasicModel from anki.stdmodels import addBasicModel
@ -198,9 +197,7 @@ class SupermemoXmlImporter(NoteImporter):
# Return imported cards # Return imported cards
self.total = len(self.notes) self.total = len(self.notes)
self.log.append( self.log.append("%d cards imported." % self.total)
ngettext("%d card imported.", "%d cards imported.", self.total) % self.total
)
return self.notes return self.notes
def fields(self) -> int: def fields(self) -> int:
@ -295,7 +292,7 @@ class SupermemoXmlImporter(NoteImporter):
+ " - " + " - "
+ dLevels[level].ljust(9) + dLevels[level].ljust(9)
+ " -\t" + " -\t"
+ _(text) + text
) )
# OPEN AND LOAD # OPEN AND LOAD

View file

@ -10,7 +10,6 @@ from typing import Any, Dict, List, Optional, Sequence, Tuple, Union
import anki import anki
from anki.consts import * from anki.consts import *
from anki.lang import _, ngettext
from anki.rsbackend import TR, FormatTimeSpanContext from anki.rsbackend import TR, FormatTimeSpanContext
from anki.utils import ids2str from anki.utils import ids2str
@ -116,7 +115,7 @@ body { direction: ltr !important; }
###################################################################### ######################################################################
def todayStats(self) -> str: def todayStats(self) -> str:
b = self._title(_("Today")) b = self._title("Today")
# studied today # studied today
lim = self._revlogLimit() lim = self._revlogLimit()
if lim: if lim:
@ -149,16 +148,16 @@ from revlog where id > ? """
cards=cards, seconds=float(thetime) cards=cards, seconds=float(thetime)
) )
# again/pass count # again/pass count
b += "<br>" + _("Again count: %s") % bold(failed) b += "<br>" + "Again count: %s" % bold(failed)
if cards: if cards:
b += " " + _("(%s correct)") % bold( b += " " + "(%s correct)" % bold(
"%0.1f%%" % ((1 - failed / float(cards)) * 100) "%0.1f%%" % ((1 - failed / float(cards)) * 100)
) )
# type breakdown # type breakdown
b += "<br>" b += "<br>"
b += _( b += "Learn: %(a)s, Review: %(b)s, Relearn: %(c)s, Filtered: %(d)s" % dict(
"Learn: %(a)s, Review: %(b)s, Relearn: %(c)s, Filtered: %(d)s" a=bold(lrn), b=bold(rev), c=bold(relrn), d=bold(filt)
) % dict(a=bold(lrn), b=bold(rev), c=bold(relrn), d=bold(filt)) )
# mature today # mature today
mcnt, msum = self.col.db.first( mcnt, msum = self.col.db.first(
""" """
@ -169,13 +168,13 @@ from revlog where id > ? """
) )
b += "<br>" b += "<br>"
if mcnt: if mcnt:
b += _( b += "Correct answers on mature cards: %(a)d/%(b)d (%(c).1f%%)" % dict(
"Correct answers on mature cards: %(a)d/%(b)d (%(c).1f%%)" a=msum, b=mcnt, c=(msum / float(mcnt) * 100)
) % dict(a=msum, b=mcnt, c=(msum / float(mcnt) * 100)) )
else: else:
b += _("No mature cards were studied today.") b += "No mature cards were studied today."
else: else:
b += _("No cards have been studied today.") b += "No cards have been studied today."
return b return b
# Due and cumulative due # Due and cumulative due
@ -210,22 +209,22 @@ from revlog where id > ? """
tot += day[1] + day[2] tot += day[1] + day[2]
totd.append((day[0], tot)) totd.append((day[0], tot))
data = [ data = [
dict(data=mtr, color=colMature, label=_("Mature")), dict(data=mtr, color=colMature, label="Mature"),
dict(data=yng, color=colYoung, label=_("Young")), dict(data=yng, color=colYoung, label="Young"),
] ]
if len(totd) > 1: if len(totd) > 1:
data.append( data.append(
dict( dict(
data=totd, data=totd,
color=colCum, color=colCum,
label=_("Cumulative"), label="Cumulative",
yaxis=2, yaxis=2,
bars={"show": False}, bars={"show": False},
lines=dict(show=True), lines=dict(show=True),
stack=False, stack=False,
) )
) )
txt = self._title(_("Forecast"), _("The number of reviews due in the future.")) txt = self._title("Forecast", "The number of reviews due in the future.")
xaxis = dict(tickDecimals=0, min=-0.5) xaxis = dict(tickDecimals=0, min=-0.5)
if end is not None: if end is not None:
xaxis["max"] = end - 0.5 xaxis["max"] = end - 0.5
@ -233,7 +232,7 @@ from revlog where id > ? """
id="due", id="due",
data=data, data=data,
xunit=chunk, xunit=chunk,
ylabel2=_("Cumulative Cards"), ylabel2="Cumulative Cards",
conf=dict( conf=dict(
xaxis=xaxis, xaxis=xaxis,
yaxes=[dict(min=0), dict(min=0, tickDecimals=0, position="right")], yaxes=[dict(min=0), dict(min=0, tickDecimals=0, position="right")],
@ -246,10 +245,10 @@ from revlog where id > ? """
i: List[str] = [] i: List[str] = []
self._line( self._line(
i, i,
_("Total"), "Total",
self.col.tr(TR.STATISTICS_REVIEWS, reviews=tot), self.col.tr(TR.STATISTICS_REVIEWS, reviews=tot),
) )
self._line(i, _("Average"), self._avgDay(tot, num, _("reviews"))) self._line(i, "Average", self._avgDay(tot, num, "reviews"))
tomorrow = self.col.db.scalar( tomorrow = self.col.db.scalar(
f""" f"""
select count() from cards where did in %s and queue in ({QUEUE_TYPE_REV},{QUEUE_TYPE_DAY_LEARN_RELEARN}) select count() from cards where did in %s and queue in ({QUEUE_TYPE_REV},{QUEUE_TYPE_DAY_LEARN_RELEARN})
@ -257,8 +256,8 @@ and due = ?"""
% self._limit(), % self._limit(),
self.col.sched.today + 1, self.col.sched.today + 1,
) )
tomorrow = ngettext("%d card", "%d cards", tomorrow) % tomorrow tomorrow = "%d cards" % tomorrow
self._line(i, _("Due tomorrow"), tomorrow) self._line(i, "Due tomorrow", tomorrow)
return self._lineTbl(i) return self._lineTbl(i)
def _due( def _due(
@ -306,8 +305,8 @@ group by day order by day"""
# graph # graph
repdata, repsum = self._splitRepData(data, ((1, colLearn, ""),)) repdata, repsum = self._splitRepData(data, ((1, colLearn, ""),))
txt = self._title(_("Added"), _("The number of new cards you have added.")) txt = self._title("Added", "The number of new cards you have added.")
txt += plot("intro", repdata, ylabel=_("Cards"), ylabel2=_("Cumulative Cards")) txt += plot("intro", repdata, ylabel="Cards", ylabel2="Cumulative Cards")
# total and per day average # total and per day average
tot = sum([i[1] for i in data]) tot = sum([i[1] for i in data])
period = self._periodDays() period = self._periodDays()
@ -315,8 +314,8 @@ group by day order by day"""
# base off date of earliest added card # base off date of earliest added card
period = self._deckAge("add") period = self._deckAge("add")
i: List[str] = [] i: List[str] = []
self._line(i, _("Total"), ngettext("%d card", "%d cards", tot) % tot) self._line(i, "Total", "%d cards" % tot)
self._line(i, _("Average"), self._avgDay(tot, period, _("cards"))) self._line(i, "Average", self._avgDay(tot, period, "cards"))
txt += self._lineTbl(i) txt += self._lineTbl(i)
return txt return txt
@ -343,45 +342,39 @@ group by day order by day"""
(repdata, repsum) = self._splitRepData( (repdata, repsum) = self._splitRepData(
data, data,
( (
(3, colMature, _("Mature")), (3, colMature, "Mature"),
(2, colYoung, _("Young")), (2, colYoung, "Young"),
(4, colRelearn, _("Relearn")), (4, colRelearn, "Relearn"),
(1, colLearn, _("Learn")), (1, colLearn, "Learn"),
(5, colCram, _("Cram")), (5, colCram, "Cram"),
), ),
) )
txt1 = self._title( txt1 = self._title("Review Count", "The number of questions you have answered.")
_("Review Count"), _("The number of questions you have answered.") txt1 += plot("reps", repdata, ylabel="Answers", ylabel2="Cumulative Answers")
)
txt1 += plot(
"reps", repdata, ylabel=_("Answers"), ylabel2=_("Cumulative Answers")
)
(daysStud, fstDay) = self._daysStudied() (daysStud, fstDay) = self._daysStudied()
rep, tot = self._ansInfo(repsum, daysStud, fstDay, _("reviews")) rep, tot = self._ansInfo(repsum, daysStud, fstDay, "reviews")
txt1 += rep txt1 += rep
# time # time
(timdata, timsum) = self._splitRepData( (timdata, timsum) = self._splitRepData(
data, data,
( (
(8, colMature, _("Mature")), (8, colMature, "Mature"),
(7, colYoung, _("Young")), (7, colYoung, "Young"),
(9, colRelearn, _("Relearn")), (9, colRelearn, "Relearn"),
(6, colLearn, _("Learn")), (6, colLearn, "Learn"),
(10, colCram, _("Cram")), (10, colCram, "Cram"),
), ),
) )
if self.type == PERIOD_MONTH: if self.type == PERIOD_MONTH:
t = _("Minutes") t = "Minutes"
convHours = False convHours = False
else: else:
t = _("Hours") t = "Hours"
convHours = True convHours = True
txt2 = self._title( txt2 = self._title("Review Time", "The time taken to answer the questions.")
_("Review Time"), _("The time taken to answer the questions.") txt2 += plot("time", timdata, ylabel=t, ylabel2="Cumulative %s" % t)
)
txt2 += plot("time", timdata, ylabel=t, ylabel2=_("Cumulative %s") % t)
rep, tot2 = self._ansInfo( rep, tot2 = self._ansInfo(
timsum, daysStud, fstDay, _("minutes"), convHours, total=tot timsum, daysStud, fstDay, "minutes", convHours, total=tot
) )
txt2 += rep txt2 += rep
return self._section(txt1) + self._section(txt2) return self._section(txt1) + self._section(txt2)
@ -404,34 +397,30 @@ group by day order by day"""
i: List[str] = [] i: List[str] = []
self._line( self._line(
i, i,
_("Days studied"), "Days studied",
_("<b>%(pct)d%%</b> (%(x)s of %(y)s)") "<b>%(pct)d%%</b> (%(x)s of %(y)s)"
% dict(x=studied, y=period, pct=studied / float(period) * 100), % dict(x=studied, y=period, pct=studied / float(period) * 100),
bold=False, bold=False,
) )
if convHours: if convHours:
tunit = _("hours") tunit = "hours"
else: else:
tunit = unit tunit = unit
# T: unit: can be hours, minutes, reviews... tot: the number of unit. # T: unit: can be hours, minutes, reviews... tot: the number of unit.
self._line( self._line(i, "Total", "%(tot)s %(unit)s" % dict(unit=tunit, tot=int(tot)))
i, _("Total"), _("%(tot)s %(unit)s") % dict(unit=tunit, tot=int(tot))
)
if convHours: if convHours:
# convert to minutes # convert to minutes
tot *= 60 tot *= 60
self._line(i, _("Average for days studied"), self._avgDay(tot, studied, unit)) self._line(i, "Average for days studied", self._avgDay(tot, studied, unit))
if studied != period: if studied != period:
# don't display if you did study every day # don't display if you did study every day
self._line( self._line(i, "If you studied every day", self._avgDay(tot, period, unit))
i, _("If you studied every day"), self._avgDay(tot, period, unit)
)
if total and tot: if total and tot:
perMin = total / float(tot) perMin = total / float(tot)
average_secs = (tot * 60) / total average_secs = (tot * 60) / total
self._line( self._line(
i, i,
_("Average answer time"), "Average answer time",
self.col.tr( self.col.tr(
TR.STATISTICS_AVERAGE_ANSWER_TIME, TR.STATISTICS_AVERAGE_ANSWER_TIME,
**{"cards-per-minute": perMin, "average-seconds": average_secs}, **{"cards-per-minute": perMin, "average-seconds": average_secs},
@ -593,10 +582,10 @@ group by day order by day)"""
ivlmax = 52 ivlmax = 52
else: else:
ivlmax = max(5, ivls[-1][0]) ivlmax = max(5, ivls[-1][0])
txt = self._title(_("Intervals"), _("Delays until reviews are shown again.")) txt = self._title("Intervals", "Delays until reviews are shown again.")
txt += self._graph( txt += self._graph(
id="ivl", id="ivl",
ylabel2=_("Percentage"), ylabel2="Percentage",
xunit=chunk, xunit=chunk,
data=[ data=[
dict(data=ivls, color=colIvl), dict(data=ivls, color=colIvl),
@ -615,8 +604,8 @@ group by day order by day)"""
), ),
) )
i: List[str] = [] i: List[str] = []
self._line(i, _("Average interval"), self.col.format_timespan(avg * 86400)) self._line(i, "Average interval", self.col.format_timespan(avg * 86400))
self._line(i, _("Longest interval"), self.col.format_timespan(max_ * 86400)) self._line(i, "Longest interval", self.col.format_timespan(max_ * 86400))
return txt + self._lineTbl(i) return txt + self._lineTbl(i)
def _ivls(self) -> Tuple[List[Any], int]: def _ivls(self) -> Tuple[List[Any], int]:
@ -678,18 +667,18 @@ select count(), avg(ivl), max(ivl) from cards where did in %s and queue = {QUEUE
if self.col.schedVer() != 1: if self.col.schedVer() != 1:
ticks.insert(3, [4, 4]) ticks.insert(3, [4, 4])
txt = self._title( txt = self._title(
_("Answer Buttons"), _("The number of times you have pressed each button.") "Answer Buttons", "The number of times you have pressed each button."
) )
txt += self._graph( txt += self._graph(
id="ease", id="ease",
data=[ data=[
dict(data=d["lrn"], color=colLearn, label=_("Learning")), dict(data=d["lrn"], color=colLearn, label="Learning"),
dict(data=d["yng"], color=colYoung, label=_("Young")), dict(data=d["yng"], color=colYoung, label="Young"),
dict(data=d["mtr"], color=colMature, label=_("Mature")), dict(data=d["mtr"], color=colMature, label="Mature"),
], ],
type="bars", type="bars",
conf=dict(xaxis=dict(ticks=ticks, min=0, max=15)), conf=dict(xaxis=dict(ticks=ticks, min=0, max=15)),
ylabel=_("Answers"), ylabel="Answers",
) )
txt += self._easeInfo(eases) txt += self._easeInfo(eases)
return txt return txt
@ -710,7 +699,7 @@ select count(), avg(ivl), max(ivl) from cards where did in %s and queue = {QUEUE
except: except:
pct = 0 pct = 0
i.append( i.append(
_("Correct: <b>%(pct)0.2f%%</b><br>(%(good)d of %(tot)d)") "Correct: <b>%(pct)0.2f%%</b><br>(%(good)d of %(tot)d)"
% dict(pct=pct, good=good, tot=tot) % dict(pct=pct, good=good, tot=tot)
) )
return ( return (
@ -788,16 +777,16 @@ order by thetype, ease"""
diff = round(diff, 1) diff = round(diff, 1)
trend.append((hour, prev + diff)) trend.append((hour, prev + diff))
txt = self._title( txt = self._title(
_("Hourly Breakdown"), _("Review success rate for each hour of the day.") "Hourly Breakdown", "Review success rate for each hour of the day."
) )
txt += self._graph( txt += self._graph(
id="hour", id="hour",
data=[ data=[
dict(data=shifted, color=colCum, label=_("% Correct")), dict(data=shifted, color=colCum, label="% Correct"),
dict( dict(
data=counts, data=counts,
color=colHour, color=colHour,
label=_("Answers"), label="Answers",
yaxis=2, yaxis=2,
bars=dict(barWidth=0.2), bars=dict(barWidth=0.2),
stack=False, stack=False,
@ -806,19 +795,19 @@ order by thetype, ease"""
conf=dict( conf=dict(
xaxis=dict( xaxis=dict(
ticks=[ ticks=[
[0, _("4AM")], [0, "4AM"],
[6, _("10AM")], [6, "10AM"],
[12, _("4PM")], [12, "4PM"],
[18, _("10PM")], [18, "10PM"],
[23, _("3AM")], [23, "3AM"],
] ]
), ),
yaxes=[dict(max=peak), dict(position="right", max=mcount)], yaxes=[dict(max=peak), dict(position="right", max=mcount)],
), ),
ylabel=_("% Correct"), ylabel="% Correct",
ylabel2=_("Reviews"), ylabel2="Reviews",
) )
txt += _("Hours with less than 30 reviews are not shown.") txt += "Hours with less than 30 reviews are not shown."
return txt return txt
def _hourRet(self) -> Any: def _hourRet(self) -> Any:
@ -855,10 +844,10 @@ group by hour having count() > 30 order by hour"""
d = [] d = []
for c, (t, col) in enumerate( for c, (t, col) in enumerate(
( (
(_("Mature"), colMature), ("Mature", colMature),
(_("Young+Learn"), colYoung), ("Young+Learn", colYoung),
(_("Unseen"), colUnseen), ("Unseen", colUnseen),
(_("Suspended+Buried"), colSusp), ("Suspended+Buried", colSusp),
) )
): ):
d.append(dict(data=div[c], label="%s: %s" % (t, div[c]), color=col)) d.append(dict(data=div[c], label="%s: %s" % (t, div[c]), color=col))
@ -870,20 +859,18 @@ select count(id), count(distinct nid) from cards
where did in %s """ where did in %s """
% self._limit() % self._limit()
) )
self._line(i, _("Total cards"), c) self._line(i, "Total cards", c)
self._line(i, _("Total notes"), f) self._line(i, "Total notes", f)
(low, avg, high) = self._factors() (low, avg, high) = self._factors()
if low: if low:
self._line(i, _("Lowest ease"), "%d%%" % low) self._line(i, "Lowest ease", "%d%%" % low)
self._line(i, _("Average ease"), "%d%%" % avg) self._line(i, "Average ease", "%d%%" % avg)
self._line(i, _("Highest ease"), "%d%%" % high) self._line(i, "Highest ease", "%d%%" % high)
info = "<table width=100%>" + "".join(i) + "</table><p>" info = "<table width=100%>" + "".join(i) + "</table><p>"
info += _( info += """\
"""\
A card's <i>ease</i> is the size of the next interval \ A card's <i>ease</i> is the size of the next interval \
when you answer "good" on a review.""" when you answer "good" on a review."""
) txt = self._title("Card Types", "The division of cards in your deck(s).")
txt = self._title(_("Card Types"), _("The division of cards in your deck(s)."))
txt += "<table width=%d><tr><td>%s</td><td>%s</td></table>" % ( txt += "<table width=%d><tr><td>%s</td><td>%s</td></table>" % (
self.width, self.width,
self._graph(id="cards", data=d, type="pie"), self._graph(id="cards", data=d, type="pie"),
@ -895,7 +882,7 @@ when you answer "good" on a review."""
self, i: List[str], a: str, b: Union[int, str], bold: bool = True self, i: List[str], a: str, b: Union[int, str], bold: bool = True
) -> None: ) -> None:
# T: Symbols separating first and second column in a statistics table. Eg in "Total: 3 reviews". # T: Symbols separating first and second column in a statistics table. Eg in "Total: 3 reviews".
colon = _(":") colon = ":"
if bold: if bold:
i.append( i.append(
("<tr><td width=200 align=right>%s%s</td><td><b>%s</b></td></tr>") ("<tr><td width=200 align=right>%s%s</td><td><b>%s</b></td></tr>")
@ -938,15 +925,15 @@ from cards where did in %s"""
def footer(self) -> str: def footer(self) -> str:
b = "<br><br><font size=1>" b = "<br><br><font size=1>"
b += _("Generated on %s") % time.asctime(time.localtime(time.time())) b += "Generated on %s" % time.asctime(time.localtime(time.time()))
b += "<br>" b += "<br>"
if self.wholeCollection: if self.wholeCollection:
deck = _("whole collection") deck = "whole collection"
else: else:
deck = self.col.decks.current()["name"] deck = self.col.decks.current()["name"]
b += _("Scope: %s") % deck b += "Scope: %s" % deck
b += "<br>" b += "<br>"
b += _("Period: %s") % [_("1 month"), _("1 year"), _("deck life")][self.type] b += "Period: %s" % ["1 month", "1 year", "deck life"][self.type]
return b return b
# Tools # Tools
@ -959,7 +946,7 @@ from cards where did in %s"""
conf: Optional[Any] = None, conf: Optional[Any] = None,
type: str = "bars", type: str = "bars",
xunit: int = 1, xunit: int = 1,
ylabel: str = _("Cards"), ylabel: str = "Cards",
ylabel2: str = "", ylabel2: str = "",
) -> str: ) -> str:
if conf is None: if conf is None:
@ -979,11 +966,11 @@ from cards where did in %s"""
conf["timeTicks"] = False conf["timeTicks"] = False
else: else:
# T: abbreviation of day # T: abbreviation of day
d = _("d") d = "d"
# T: abbreviation of week # T: abbreviation of week
w = _("w") w = "w"
# T: abbreviation of month # T: abbreviation of month
mo = _("mo") mo = "mo"
conf["timeTicks"] = {1: d, 7: w, 31: mo}[xunit] conf["timeTicks"] = {1: d, 7: w, 31: mo}[xunit]
# types # types
width = self.width width = self.width
@ -1109,7 +1096,7 @@ $(function () {
def _avgDay(self, tot: float, num: int, unit: str) -> str: def _avgDay(self, tot: float, num: int, unit: str) -> str:
vals = [] vals = []
try: try:
vals.append(_("%(a)0.1f %(b)s/day") % dict(a=tot / float(num), b=unit)) vals.append("%(a)0.1f %(b)s/day" % dict(a=tot / float(num), b=unit))
return ", ".join(vals) return ", ".join(vals)
except ZeroDivisionError: except ZeroDivisionError:
return "" return ""

View file

@ -155,7 +155,7 @@ the legacy addHook() API.
# %s</a><div id="%s" class=hint style="display: none">%s</div> # %s</a><div id="%s" class=hint style="display: none">%s</div>
# """ % ( # """ % (
# domid, # domid,
# _("Show %s") % tag, # "Show %s" % tag,
# domid, # domid,
# txt, # txt,
# ) # )