Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

#! /usr/bin/env python3 

# -*- coding: utf-8 -*- 

 

#       Copyright 2011-2012, 2014, Marten de Vries 

#       Copyright 2011, Milan Boers 

# 

#       This file is part of OpenTeacher. 

# 

#       OpenTeacher is free software: you can redistribute it and/or modify 

#       it under the terms of the GNU General Public License as published by 

#       the Free Software Foundation, either version 3 of the License, or 

#       (at your option) any later version. 

# 

#       OpenTeacher is distributed in the hope that it will be useful, 

#       but WITHOUT ANY WARRANTY; without even the implied warranty of 

#       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 

#       GNU General Public License for more details. 

# 

#       You should have received a copy of the GNU General Public License 

#       along with OpenTeacher.  If not, see <http://www.gnu.org/licenses/>. 

 

from etree import ElementTree 

 

import datetime 

import re 

import atexit 

import tempfile 

import os 

import base64 

 

class Teach2000LoaderModule: 

        def __init__(self, moduleManager, *args, **kwargs): 

                super().__init__(*args, **kwargs) 

                self._mm = moduleManager 

 

                self.type = "load" 

                self.priorities = { 

                        "default": 648, 

                } 

 

                self.uses = ( 

                        self._mm.mods(type="translator"), 

                ) 

                self.requires = ( 

                        self._mm.mods(type="mimicryTypefaceConverter"), 

                ) 

                self.filesWithTranslations = ("t2k.py",) 

                self._tempPaths = set() 

                atexit.register(self._cleanUp) 

 

        @property 

        def _convertMimicryTypeface(self): 

                return self._modules.default("active", type="mimicryTypefaceConverter").convert 

 

        def _retranslate(self): 

                try: 

                        translator = self._modules.default("active", type="translator") 

                except IndexError: 

exit                        _, ngettext = str, lambda a, b, n: a if n == 1 else b 

                else: 

                        _, ngettext = translator.gettextFunctions( 

                                self._mm.resourcePath("translations") 

                        ) 

                #TRANSLATORS: This is the name of an application. For more info 

                #TRANSLATORS: about Teach2000: http://www.teach2000.org/ 

                self.name = _("Teach2000") 

 

        def enable(self): 

                self._modules = set(self._mm.mods(type="modules")).pop() 

                try: 

                        translator = self._modules.default("active", type="translator") 

                except IndexError: 

                        pass 

                else: 

                        translator.languageChanged.handle(self._retranslate) 

                self._retranslate() 

 

                self.mimetype = "application/x-teach2000" 

                self.loads = {"t2k": ["words"]} 

 

                self.active = True 

 

        def _cleanUp(self): 

                for path in getattr(self, "_tempPaths", []): 

                        os.remove(path) 

 

        def disable(self): 

                self.active = False 

 

                del self._modules 

                del self.name 

                del self.loads 

                del self.mimetype 

 

        def getFileTypeOf(self, path): 

exit                if path.endswith(".t2k"): 

                        with open(path, 'rb') as f: 

                                root = ElementTree.parse(f).getroot() 

100                        if root.find("message_data/items//item/answers[@type='4']") is not None: 

                                return "topo" 

                        else: 

                                #also support other formats in the future? Well, 

                                #everything that's left can be opened like it's of type 'words'... 

                                return "words" 

 

        def load(self, path): 

                """Loads a .t2k file into the OpenTeacher data structure. 

                   http://www.teach2000.nl/help/00513_advanced_file_format.htm 

 

                """ 

                with open(path, 'rb') as f: 

                        root = ElementTree.parse(f).getroot() 

114                if self.getFileTypeOf(path) == "topo": 

                        return self._loadTopo(root) 

                else: 

                        return self._loadWords(root) 

 

        def _loadResults(self, root): 

                #create one test to save all results in that are in the t2k file 

                #(t2k doesn't have enough information to know which word was 

                #wrong in which test, so we can have only one test.) 

                test = { 

                        "finished": True, 

                        "results": [], 

                } 

                for item in root.findall("message_data/items/item"): 

                        #add a result for every time this word was wrong 

                        for i in range(int(item.findtext("errors") or 0)): 

                                test["results"].append({ 

                                        "itemId": self._getId(item), "result": "wrong", 

                                }) 

                        #add a result for every time this word was right 

                        for i in range(int(item.findtext("correctcount") or 0)): 

                                test["results"].append({ 

                                        "itemId": self._getId(item), 

                                        "result": "right", 

                                }) 

 

                #if there were results 

                if test["results"]: 

                        #get the time of the first start result and the one of the 

                        #last for a global idea of the time range of this 'mega' 

                        #test. Duration isn't used, since it's way off anyway. 

                        try: 

                                startTime = root.findall("message_data/testresults/testresult")[0].findtext("dt") 

                                endTime = root.findall("message_data/testresults/testresult")[-1].findtext("dt") 

                        except IndexError: 

                                pass 

                        else: 

                                startTime = self._parseDt(startTime) 

                                endTime = self._parseDt(endTime) 

 

                                #store those times in the first and last result. (which may 

                                #be the same, technically, but that doesn't matter...) 

                                test["results"][0]["active"] = { 

                                        "start": startTime, 

                                        "end": startTime, 

                                } 

                                test["results"][-1]["active"] = { 

                                        "start": endTime, 

                                        "end": endTime 

                                } 

                return test 

 

        def _getId(self, item): 

                return int(item.get("id")) 

 

        def _loadTopo(self, root): 

                placesList = { 

                        "items": [], 

                        "tests": [], 

                } 

 

                for item in root.findall("message_data/items/item"): 

                        answers = item.find(".//answers") 

                        answerTexts = [a.text for a in answers.findall(".//answer")] 

                        place = { 

                                "id": self._getId(item), 

                                "x": int(answers.get("x") or 0), 

                                "y": int(answers.get("y") or 0), 

                                "name": self._stripBBCode(u", ".join(answerTexts)), 

                        } 

                        placesList["items"].append(place) 

 

                #append the test to the list 

                test = self._loadResults(root) 

                if test["results"]: 

                        placesList["tests"] = [test] 

 

                mapElement = root.find("message_data/mapquizfile") 

                fd, mapPath = tempfile.mkstemp("." + mapElement.get("ext")) 

                os.close(fd) 

                self._tempPaths.add(mapPath) 

                with open(mapPath, "wb") as f: 

                        f.write(base64.b64decode(mapElement.text)) 

 

                return { 

                        "resources": { 

                                "mapPath": mapPath, 

                        }, 

                        "list": placesList, 

                } 

 

        def _loadWords(self, root): 

                wordList = { 

                        "items": [], 

                        "tests": [], 

                } 

 

                questionFont = root.findtext("message_data/font_question") or u"" 

                answerFont = root.findtext("message_data/answer_question") or u"" 

 

                for item in root.findall("message_data/items/item"): 

                        word = self._loadWordFromTreeItem(questionFont, answerFont, item) 

 

                        wordList["items"].append(word) 

 

                #append the test to the list 

                test = self._loadResults(root) 

                if test["results"]: 

                        wordList["tests"] = [test] 

 

                return { 

                        "resources": {}, 

                        "list": wordList, 

                } 

 

        def _loadWordFromTreeItem(self, questionFont, answerFont, item): 

                word = { 

                        "questions": [], 

                        "answers": [], 

                } 

 

                #id 

                word["id"] = self._getId(item) 

 

                #questions 

                word["questions"].append([]) 

                for question in item.findall(".//question"): 

                        #strip BBCode for now 

                        text = self._stripBBCode(question.text) 

                        convertedText = self._convertMimicryTypeface(questionFont, text) 

                        word["questions"][0].append(convertedText) 

 

                #answers 

                word["answers"].append([]) 

                for answer in item.findall(".//answer"): 

                        #strip BBCode for now 

                        text = self._stripBBCode(answer.text) 

                        convertedText = self._convertMimicryTypeface(answerFont, text) 

                        word["answers"][0].append(convertedText) 

 

                #remarks (comment in OT) 

                comment = item.findtext("remarks") 

256                if comment: 

                        word["comment"] = comment 

 

                #remarks_aa (commentAfterAnswering in OT) 

                commentAfterAnswering = item.findtext("remarks_aa") 

261                if commentAfterAnswering: 

                        word["commentAfterAnswering"] = commentAfterAnswering 

 

                return word 

 

        def _stripBBCode(self, string): 

                """Strips all BBCode tags""" 

                return re.sub(r"\[[\w/]*\]", u"", string) 

 

        def _parseDt(self, string): 

                """Parses a date string as found in T2K files to a datetime 

                   object.""" 

                return datetime.datetime.strptime(string, "%Y-%m-%dT%H:%M:%S.%f") 

 

def init(manager): 

        return Teach2000LoaderModule(manager)