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

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

309

310

311

312

313

314

315

316

317

318

319

320

321

322

323

324

325

326

327

328

329

330

331

332

333

334

335

336

337

338

339

340

341

342

343

344

345

346

347

348

349

350

351

352

353

354

355

356

357

358

359

360

361

362

363

364

365

366

367

368

369

370

371

372

373

374

375

376

377

378

379

380

381

382

383

384

385

386

387

388

389

390

391

392

393

394

395

396

397

398

399

400

401

402

403

404

405

406

407

408

409

410

411

412

413

414

415

416

417

418

419

420

421

422

423

424

425

426

427

428

429

430

431

432

433

434

435

436

437

438

439

440

441

442

443

444

445

446

447

448

449

450

451

452

453

454

455

456

457

458

459

460

461

462

463

464

465

466

467

468

469

470

471

#! /usr/bin/env python3 

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

 

#       Copyright 2012-2014, Marten de Vries 

# 

#       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/>. 

 

import argparse 

import sys 

import glob 

import os 

 

class DummyLesson: 

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

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

 

                self.list = lessonDict["list"] 

                self.resources = lessonDict["resources"] 

 

def getEnterEdit(Event): 

        class EnterEdit(urwid.Edit): 

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

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

 

                        self.enterPressed = Event() 

 

                def keypress(self, size, key): 

                        if key == "enter": 

                                self.enterPressed.send() 

                        else: 

                                return super().keypress(size, key) 

 

        return EnterEdit 

 

class PractisingInterface: 

        """A command line interface for practising words, using the urwid 

           toolkit. 

 

        """ 

        def __init__(self, createController, lessonType, *args, **kwargs): 

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

 

                self._controller = createController() 

                self._controller.lessonType = lessonType 

                self._connectToEvents() 

                self._setupUi() 

 

        def _connectToEvents(self): 

                self._controller.clearInput.handle(self._clearInput) 

                self._controller.showCorrection.handle(self._showCorrection) 

                self._controller.hideCorrection.handle(self._hideCorrection) 

 

        def _setupUi(self): 

                #setup main UI 

                self._txt = urwid.Text(u"") 

                self._edit = EnterEdit("ANSWER: ") 

                self._edit.enterPressed.handle(self._onCheck) 

                urwid.connect_signal(self._edit, "change", lambda x, y: self._controller.userIsTyping) 

 

                checkButton = urwid.Button("Check", lambda button: self._onCheck()) 

                skipButton = urwid.Button("Skip", lambda button: self._controller.skipTriggered()) 

 

                divider = urwid.Divider() 

                quitButton = urwid.Button("Quit", lambda button: self.quit()) 

 

                widgets = [self._txt, self._edit, divider, checkButton, skipButton, divider, quitButton] 

                listBox = urwid.ListBox(widgets) 

                adapter = urwid.BoxAdapter(listBox, len(widgets)) 

                self._mainFiller = urwid.Filler(adapter, "middle") 

 

                #setup correction dialog 

                self._correctionTxt = urwid.Text(u"") 

                self._correctionFiller = urwid.Filler(self._correctionTxt, "middle") 

 

                self._loop = urwid.MainLoop(self._mainFiller) 

 

        def _clearInput(self): 

                self._edit.edit_text = "" 

 

        def _showCorrection(self, correctAnswer): 

                self._loop.widget = self._correctionFiller 

                self._correctionTxt.set_text(u"WRONG ANSWER. IT SHOULD HAVE BEEN: %s" % correctAnswer) 

                self._loop.set_alarm_in(3, lambda x, y:self._controller.correctionShowingDone()) 

 

        def _hideCorrection(self): 

                self._loop.widget = self._mainFiller 

 

        def run(self): 

                self._controller.lessonType.start() 

                self._loop.run() 

 

        def _onCheck(self): 

                self._controller.checkTriggered(self._edit.edit_text) 

 

        def quit(self): 

                raise urwid.ExitMainLoop() 

 

        def setNextItem(self, question): 

                self._txt.set_text("QUESTION: %s" % question) 

 

class CommandLineInterfaceModule: 

        """This module provides a command line interface to a lot of 

           OpenTeacher's functions, including list management, list 

           practising, OCR, and viewing some program metadata. 

 

        """ 

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

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

                self._mm = moduleManager 

 

                self.type = "cli" 

                self.requires = ( 

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

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

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

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

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

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

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

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

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

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

                ) 

                self.uses = ( 

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

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

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

                ) 

                self.priorities = { 

                        "cli": 0, 

                        "default": 960, 

                } 

 

        def _saveExts(self): 

                yielded = set() 

                for mod in self._modules.sort("active", type="save"): 

                        for exts in sorted(mod.saves.values()): 

                                for ext in sorted(exts): 

                                        if ext not in yielded: 

                                                yielded.add(ext) 

                                                yield ext 

 

        def _load(self, path): 

                return self._modules.default("active", type="loader").loadToLesson(path) 

 

        def _expandPaths(self, paths): 

                newPaths = [] 

                for selector in paths: 

                        newPaths.extend(glob.iglob(selector)) 

                return newPaths 

 

        def _reverseList(self, args): 

                type, lesson = self._load(args["input-file"]) 

168                if not lesson: 

                        print("Couldn't load file '%s', not reversing." % args["input-file"], file=sys.stderr) 

                        return 

 

                try: 

                        self._modules.default("active", type="reverser", dataType=type).reverse(lesson["list"]) 

                except IndexError: 

                        print("Couldn't reverse the file '%s'." % args["input-file"], file=sys.stderr) 

                        return 

 

                self._save(type, lesson, args["output-file"]) 

 

        def _merge(self, args): 

                baseType, baseLesson = self._load(args["base-file"]) 

182                if not baseLesson: 

                        print("Couldn't load the base file ('%s'). Not doing the merge." % args["base-file"], file=sys.stderr) 

                        return 

                try: 

                        merge = self._modules.default("active", type="merger", dataType=baseType).merge 

                except IndexError: 

                        print("Can't merge this type of files. Stopping.", file=sys.stderr) 

                        return 

 

                for inputFile in args["other-files"]: 

                        type, lesson = self._load(inputFile) 

193                        if not lesson: 

                                print("Couldn't load the file '%s'. Not doing the merge." % inputFile, file=sys.stderr) 

                                return 

196                        if type != baseType: 

                                print("The type of the base file ('%s') and the input file '%s' ('%s') aren't equal. Not doing the merge." % (baseType, inputFile, type), file=sys.stderr) 

                                return 

                        baseLesson = merge(baseLesson, lesson) 

 

                self._save(baseType, baseLesson, args["output-file"]) 

 

        def _convertOne(self, inputPath, outputFormat): 

                #loading 

                type, lesson = self._load(inputPath) 

206                if not lesson: 

                        print("Couldn't load file '%s', not converting." % inputPath, file=sys.stderr) 

                        #next file 

                        return 

 

                done = False 

                outputPath = os.path.splitext(inputPath)[0] + "." + outputFormat 

213                if os.path.exists(outputPath): 

                        print("The file '{outfile}' already exists, so '{infile}' can't be converted.".format(outfile=outputPath, infile=inputPath), file=sys.stderr) 

                        #next file 

                        return 

 

226                for mod in self._modules.sort("active", type="save"): 

                        for modType, exts in mod.saves.items(): 

                                if modType == type and outputFormat in exts: 

                                        mod.save(type, DummyLesson(lesson), outputPath) 

                                        done = True 

                                        break 

                        if done: 

                                break 

                else: 

                        print("Couldn't save file '{infile}' in the '{format}' format, not converting.".format(infile=inputPath, format=outputFormat), file=sys.stderr) 

                        #next file 

                        return 

                print("Converted file '{infile}' to '{outfile}'.".format(infile=inputPath, outfile=outputPath)) 

 

        def _convert(self, args): 

                inputPaths = self._expandPaths(args["input-files"]) 

                outputFormat = args["output_format"] 

 

                for inputPath in inputPaths: 

                        self._convertOne(inputPath, outputFormat) 

                print("Done.") 

 

        def _viewWordList(self, args): 

                inputPaths = self._expandPaths(args["input-files"]) 

                for inputPath in inputPaths: 

                        type, lesson = self._load(inputPath) 

244                        if type != "words": 

                                print("File '%s' isn't a word list." % inputPath, file=sys.stderr) 

                                continue 

247                        if not lesson: 

                                print("Couldn't load file %s, not showing." % inputPath, file=sys.stderr) 

                                continue 

                        #lambda's for lazy loading. Handy for the compose case which 

                        #is a lot more likely to crash than the others + is 

                        #relatively slow. JS implementation only currently... 

                        print({ 

                                "title": lambda: lesson["list"]["title"], 

                                "question-lang": lambda: lesson["list"]["questionLanguage"], 

                                "answer-lang": lambda: lesson["list"]["answerLanguage"], 

                                "list": lambda: self._composeWordList(lesson), 

                        }[args["part"]]()) 

 

        def _newWordList(self, args): 

261                if args["input-file"] == "-": 

                        data = sys.stdin.read() 

                else: 

                        with open(args["input-file"], "r", encoding='UTF-8') as inputFile: 

                                data = inputFile.read() 

 

                lesson = self._parseWordList(data) 

 

270                if args["title"]: 

                        lesson["list"]["title"] = args["title"] 

272                if args["question_lang"]: 

                        lesson["list"]["questionLanguage"] = args["question_lang"] 

275                if args["answer_lang"]: 

                        lesson["list"]["answerLanguage"] = args["answer_lang"] 

 

                self._save("words", lesson, args["output-file"]) 

 

        def _ocrWordList(self, args): 

                loadWordList = self._modules.default("active", type="ocrWordListLoader").loadWordList 

                lesson = loadWordList(args["input-file"]) 

                self._save("words", lesson, args["output-file"]) 

 

        def _save(self, type, lesson, path): 

                #also strip the dot. 

                ext = os.path.splitext(path)[1][1:] 

 

287                if os.path.isfile(path): 

                        print("Output file already exists. Not saving.", file=sys.stderr) 

                        return 

 

297                for mod in self._modules.sort("active", type="save"): 

                        if not ext in mod.saves.get(type, []): 

                                continue 

                        mod.save("words", DummyLesson(lesson), path) 

                        print("Done.") 

                        break 

                else: 

                        print("Couldn't save your input to '%s'." % path, file=sys.stderr) 

 

        @property 

        def _lessonTypes(self): 

                return [ 

                        mod.name 

                        for mod in self._modules.sort("active", type="lessonType") 

                ] 

 

        def _authors(self, args): 

                authors = self._modules.default("active", type="authors").registeredAuthors 

309                if args["category"] is not None: 

                        authors = [(c, n) for (c, n) in authors if c == args["category"]] 

                output = [] 

                lastCategory = None 

                for category, name in sorted(authors): 

                        if lastCategory is not None and lastCategory != category: 

                                output.append("") 

                        lastCategory = category 

                        output.append("%s: %s" % (name, category)) 

                print("\n".join(output)) 

 

        def _practiseWordList(self, args): 

                inputFile = args["file"] 

 

                type, lesson = self._load(inputFile) 

                if type != "words": 

                        print("File '%s' isn't a word file" % inputFile, file=sys.stderr) 

                if not lesson: 

                        print("The '%s' file can't be loaded." % inputFile, file=sys.stderr) 

 

                lessonTypeMod = self._modules.default("active", type="lessonType", name=args["lesson_type"]) 

                lessonType = lessonTypeMod.createLessonType(lesson["list"], list(range(len(lesson["list"]["items"])))) 

 

                typingInputLogicMod = self._modules.default("active", type="inputTypingLogic") 

                self._ui = PractisingInterface(typingInputLogicMod.createController, lessonType) 

 

                lessonType.newItem.handle(self._setNextItem) 

                lessonType.lessonDone.handle(self._ui.quit) 

                self._ui.run() 

 

        def _setNextItem(self, word): 

                question = self._compose(word["questions"]) 

                self._ui.setNextItem(question) 

 

        def run(self, argList=None): 

                """Runs the command line interface. Called by this module itself 

                   indirectly when in the 'cli' profile. Otherwise, you can call 

                   it with an optional argList. (defaults to sys.argv) 

 

                """ 

349                if argList is None: 

                        argList = sys.argv 

 

                #import urwid only here. That's because it's a relatively heavy 

                #dependency that's only required in a few special cases 

                global urwid, EnterEdit, Event 

                try: 

                        import urwid 

                except ImportError: 

                        urwid = None 

                else: 

                        Event = self._modules.default("active", type="event").createEvent 

                        EnterEdit = getEnterEdit(Event) 

 

                #setup parser: using + instead of - to distinguish from the 

                #execute module's argparse. (the one providing the -p arg). 

                parser = argparse.ArgumentParser(**{ 

                        "prog": argList[0] + " -p cli", 

                        "prefix_chars": "+", 

                }) 

 

                #--version 

                version = self._metadata["name"] + " " + self._metadata["version"] 

                parser.add_argument("+v", "++version", action="version", version=version) 

 

                subparsers = parser.add_subparsers() 

                self._buildSubparsers(subparsers) 

 

                args = parser.parse_args(argList[1:]) 

378                if not set(vars(args)) - set(["func"]): 

                        parser.print_usage() 

                        return 

                args.func(vars(args)) 

 

        def _buildSubparsers(self, subparsers): 

                #shows authors 

                authors = subparsers.add_parser("authors", help="show OpenTeacher's authors", prefix_chars="+") 

                authors.add_argument("+c", "++category", help="only show authors in the specified category") 

                authors.set_defaults(func=self._authors) 

 

                loadingPossible = bool(set(self._mm.mods("active", type="loader"))) 

                savingPossible = bool(set(self._mm.mods("active", type="save"))) 

                wordListOcrPossible = bool(set(self._mm.mods("active", type="ocrWordListLoader"))) 

 

                #if at least one saver and loader available: 

414                if loadingPossible and savingPossible: 

                        #convert 

                        convert = subparsers.add_parser("convert", help="convert word, topo and media files", prefix_chars="+") 

                        convert.add_argument("+f", "++output-format", help="output format", default="otwd", choices=list(self._saveExts())) 

                        convert.add_argument("input-files", nargs="+", help="input files") 

                        convert.set_defaults(func=self._convert) 

 

                        #merge 

                        merge = subparsers.add_parser("merge", help="merge files of the same file type", prefix_chars="+") 

                        merge.add_argument("output-file", help="output file") 

                        merge.add_argument("base-file", help="base file") 

                        merge.add_argument("other-files", help="files to merge with base file into output file", nargs="+") 

                        merge.set_defaults(func=self._merge) 

 

                        #reverse list 

                        reverseList = subparsers.add_parser("reverse-list", help="reverse list", prefix_chars="+") 

                        reverseList.add_argument("input-file", help="input files") 

                        reverseList.add_argument("output-file", help="output file") 

                        reverseList.set_defaults(func=self._reverseList) 

 

                #if at least a loader is available. 

422                if loadingPossible: 

                        #view-word-list 

                        viewWordList = subparsers.add_parser("view-word-list", help="show a word list", prefix_chars="+") 

                        viewWordList.add_argument("input-files", nargs="+", help="input files") 

                        viewWordList.add_argument("+p", "++part", choices=["list", "title", "question-lang", "answer-lang"], default="list") 

                        viewWordList.set_defaults(func=self._viewWordList) 

 

                #saver & ocrWordListLoader required 

430                if savingPossible and wordListOcrPossible: 

                        #ocr-word-list 

                        ocrWordList = subparsers.add_parser("ocr-word-list", help="load a word list from a scan or photo", prefix_chars="+") 

                        ocrWordList.add_argument("input-file", help="input file") 

                        ocrWordList.add_argument("output-file", help="output file") 

                        ocrWordList.set_defaults(func=self._ocrWordList) 

 

                #if at least a saver is available 

442                if savingPossible: 

                        #new-word-list 

                        newWordList = subparsers.add_parser("new-word-list", help="make a new word list", prefix_chars="+") 

                        newWordList.add_argument("output-file", help="output file") 

                        newWordList.add_argument("input-file", help="input file (default: stdin)", nargs="?", default="-") 

                        newWordList.add_argument("+t", "++title") 

                        newWordList.add_argument("+q", "++question-lang") 

                        newWordList.add_argument("+a", "++answer-lang") 

                        newWordList.set_defaults(func=self._newWordList) 

 

                #if curses framework used for practising and at least one loader 

                #is available. 

exit                if urwid and loadingPossible: 

                        #practise-word-list 

                        practiseWordList = subparsers.add_parser("practise-word-list", help="practise a word list", prefix_chars="+") 

                        practiseWordList.add_argument("file", help="the file to practise") 

                        practiseWordList.add_argument("+l", "++lesson-type", choices=self._lessonTypes, default=self._lessonTypes[0]) 

                        practiseWordList.set_defaults(func=self._practiseWordList) 

 

        def enable(self): 

                self._modules = next(iter(self._mm.mods(type="modules"))) 

452                if self._modules.profile == "cli": 

                        self._modules.default("active", type="execute").startRunning.handle(self.run) 

 

                self._metadata = self._modules.default("active", type="metadata").metadata 

                self._composeWordList = self._modules.default("active", type="wordListStringComposer").composeList 

                self._parseWordList = self._modules.default("active", type="wordListStringParser").parseList 

                self._compose = self._modules.default("active", type="wordsStringComposer").compose 

 

                self.active = True 

 

        def disable(self): 

                self.active = False 

 

                del self._modules 

                del self._metadata 

                del self._composeWordList 

                del self._parseWordList 

                del self._compose 

 

def init(moduleManager): 

        return CommandLineInterfaceModule(moduleManager)