BeispielCodeVortragRalf

   1 #!/usr/bin/env python
   2 #coding: ISO-8859-1 -*-'
   3 
   4 #Code aus Vortrag von Ralph Schoenian über Alchemy Protokoll 20070110:
   5 # Datei pyvoc.py
   6 
   7 """ Todo
   8 -- showing error table + vocables
   9 -- debug switch
  10 -- enter negativ category
  11 -- unittest
  12 -- test by category (engl, ger)
  13 
  14 
  15 """
  16 #import os
  17 import random
  18 import sys
  19 from sqlalchemy import *
  20 import unittest
  21 
  22 debug = False
  23 
  24 db = create_engine('sqlite:///english.db')
  25 metadata = BoundMetaData(db)
  26 
  27 category_tbl = Table('category',metadata,
  28     Column('id',Integer,primary_key=True),
  29     Column('category',String(20)),
  30 )
  31 
  32 error_tbl = Table('error',metadata,
  33     #Column('id',Integer,primary_key=True),
  34     Column('id',Integer,ForeignKey('voc.id'),primary_key=True,),
  35     Column('engl',Integer),
  36     Column('ger',Integer),
  37 )
  38 
  39 voc_tbl = Table('voc',metadata,
  40     Column('id',Integer,primary_key=True),
  41     Column('english',String(30)),
  42     Column('german',String(30)),
  43 )
  44 
  45 cross_tbl = Table('cross',metadata,
  46     Column('voc_id',Integer,ForeignKey('voc.id')),
  47     Column('cat_id',Integer,ForeignKey('category.id')),
  48 )
  49 
  50 
  51 class Category(object):
  52     def __init__(self,name=None):
  53         self.category = name
  54         self.session = SessionHandler().get_session()
  55         self.query = self.session.query(Category)
  56 
  57     def get_all(self):
  58         return self.query.select(Category.c.id>0,
  59                                  order_by=[asc(Category.c.category)])
  60 
  61 
  62 Category.mapper = mapper(Category,category_tbl)
  63 
  64 
  65 class Cross(object):
  66     pass
  67 Cross.mapper = mapper(Cross,cross_tbl,
  68                     primary_key = [cross_tbl.c.voc_id, cross_tbl.c.cat_id])
  69 
  70 class Error(object):
  71     def __init__(self):
  72         self.session = SessionHandler().get_session()
  73         self.query = self.session.query(Error)
  74 
  75 
  76     def delete_dispensable(self):
  77         error_tbl.delete(and_(error_tbl.c.engl >= 0,error_tbl.c.ger >= 0)
  78                         ).execute()
  79 
  80     def get_all(self):
  81         return self.query.select()
  82 
  83     def get_by_id(self,id):
  84         obj = self.query.get_by(id=id)
  85         if obj == None:
  86             obj = Error()
  87             obj.id = id
  88             obj.engl = 0
  89             obj.ger = 0
  90 
  91         self.session.save(obj)
  92 
  93         return obj
  94 
  95     def get_max_id(self):
  96         return self.query.count()
  97 
  98     def get_random_voc(self):
  99 
 100         pos = random.randint(0,self.get_max_id()-1)
 101         errorObj = self.query.select()[pos]
 102         if debug: print "ENGL ID: ", errorObj.id
 103         return Voc().get_by_id(id=errorObj.id)
 104 
 105     def add(self,lang,value):
 106         setattr(self,lang,getattr(self,lang,value) + 1)
 107 
 108     def reduce(self,lang,value):
 109         newVal = getattr(self,lang) - value
 110         setattr(self,lang, newVal)
 111 
 112     def set(self,lang,value):
 113         setattr(self,lang,value)
 114 
 115 Error.mapper = mapper(Error,error_tbl)
 116 
 117 
 118 class Voc(object):
 119     def __init__(self):
 120         self.session = SessionHandler().get_session()
 121         self.query = self.session.query(Voc)
 122 
 123     def get_by_id(self,id):
 124         obj = self.query.get_by(id=id)
 125         return obj
 126 
 127     def get_max_id(self):
 128         return self.query.count()
 129 
 130     def get_random_voc(self):
 131         return self.query.get_by(id=random.randint(1,self.get_max_id()))
 132 
 133 Voc.mapper = mapper(Voc,voc_tbl,properties = dict(
 134     category=relation(Category,secondary=cross_tbl,lazy=False)))
 135 
 136 Error.mapper.add_property('vocable',relation(Voc))
 137 
 138 class Singleton(object):
 139     _instance=None
 140     def __new__(cls,*args,**kwargs):
 141         if not cls._instance:
 142             cls._instance =super(Singleton,cls).__new__(cls,*args,**kwargs)
 143         return cls._instance
 144 
 145 class SessionHandler(Singleton):
 146 
 147     def __init__(self):
 148         pass
 149     def get_session(self):
 150         try:
 151             return self.ses
 152         except:
 153             self.ses = create_session()
 154             return self.ses
 155 
 156 
 157 def create_database():
 158     tbl_names=s[\
 159                 category_tbl,
 160                 error_tbl,
 161                 voc_tbl,
 162                 cross_tbl,
 163             ]
 164     for tbl in tbl_names:
 165         try:
 166             tbl.create()
 167         except exceptions.SQLError,msg:
 168             if str(msg).find('already exists') != -1:
 169                 print "%s already exists" %(tbl)
 170             else:
 171                 print "Unhandled error %s" %(msg)
 172         except:
 173             print "Unexpected error:",sys.exc_info()[0]
 174 
 175 
 176 def display_err_list():
 177     e = Error()
 178     v_lst = e.get_all()
 179     print 75*"-"
 180     for v in v_lst:
 181         #print 70*"-"
 182         print "%-30s |%-30s |%3s |%3s |" %(v.vocable.german,
 183                                             v.vocable.english,
 184                                             v.ger,
 185                                         v.engl)
 186     print 75*"-"
 187     selection = raw_input('Press any key ')
 188 
 189 
 190 def clear_screen():
 191     import curses, sys
 192     curses.setupterm()
 193     sys.stdout.write(curses.tigetstr("clear"))
 194     sys.stdout.flush()
 195 
 196 def enter_category():
 197     enter = Enter_Category()
 198     enter.input_loop()
 199 
 200 def enter_voc():
 201     enter=Enter_Voc()
 202     enter.input_loop()
 203 
 204 def test_ger_engl():
 205     Error().delete_dispensable()
 206     test = Ger_Engl()
 207     test.loop()
 208 
 209 def test_engl_ger():
 210     Error().delete_dispensable()
 211     test = Engl_Ger()
 212     test.loop()
 213 
 214 def engl_error_testing():
 215     Error().delete_dispensable()
 216     test  = EnglErrorTest()
 217     test.loop()
 218 
 219 def ger_error_testing():
 220 
 221     Error().delete_dispensable()
 222     test  = GerErrorTest()
 223     test.loop()
 224 
 225 # -------------- View ---------------
 226 
 227 class Trainer(object):
 228 
 229     def __init__(self,title="",container = Voc):
 230         self.title = title
 231         self.container = container
 232         self.session = SessionHandler().get_session()
 233 
 234     def loop(self):
 235         loop = True
 236         counter = 1
 237 
 238 
 239         while loop:
 240             self.show_headline()
 241             testobj = self.container().get_random_voc()
 242             self.show_category(testobj)
 243             self.ask_me(testobj,counter)
 244             selection = raw_input('e) Exit  c) Continue: ')
 245             if selection in ['e','E']: loop=False
 246             else: counter += 1
 247 
 248     def ask_me(self,testobj,counter):
 249         """ Wird ueberladen. """
 250         pass
 251 
 252     def show_headline(self):
 253         clear_screen()
 254         print "               %s" %(self.title)
 255         print 50 * "-"
 256 
 257     def show_category(self,testobj):
 258        print "Kagegorie:", \
 259             ", ".join([str(el.category) for el in testobj.category])
 260        print 50 * "-"
 261 
 262     def update_error_table(self,testobj, lang = None, match = False):
 263         """ engl = 1 => set engl row else german raw """
 264 
 265         assert lang in ('engl','ger')
 266         errorObj = Error().get_by_id(int(testobj.id))
 267 
 268         if debug:
 269             print "ID: ", errorObj.id
 270             print "LANG: ", lang
 271             print "ERROR_COUNTER: ", getattr(errorObj,lang)
 272 
 273         if match:
 274             errorObj.add(lang,1)
 275         else:
 276             if getattr(errorObj,lang) == 0:
 277                errorObj.set(lang,-3)
 278             else:
 279                 errorObj.reduce(lang,1)
 280 
 281         self.session.save_or_update(errorObj)
 282         self.session.flush()
 283 
 284 
 285 class Engl_Ger(Trainer):
 286     def __init__(self,title = "English <==> German",container = Voc ):
 287         Trainer.__init__(self,title,container)
 288 
 289     def ask_me(self,testobj,counter):
 290         german = raw_input(str(counter)+') '+str(testobj.english)+': ')
 291         print 50 * "-"
 292         if german == str(testobj.german):
 293             print "==> correct"
 294             match = True
 295         else:
 296             print "==> Error: ",str(testobj.german)
 297             match = False
 298         self.update_error_table(testobj,lang='engl',match=match)
 299 
 300 class Ger_Engl(Trainer):
 301     def __init__(self,title="German <==> English",container=Voc):
 302         Trainer.__init__(self,title,container)
 303 
 304     def ask_me(self,testobj,counter):
 305         english = raw_input(str(counter)+') '+str(testobj.german)+': ')
 306         print 50 * "-"
 307         if english == str(testobj.english):
 308             print "==> correct"
 309             match = True
 310         else:
 311             print "==> Error: ",str(testobj.english)
 312             match = False
 313 
 314         self.update_error_table(testobj,lang='ger',match=match)
 315 
 316 
 317 class Enter_Voc(Trainer):
 318     def __init__(self):
 319         Trainer.__init__(self,"Enter vocabulary")
 320 
 321     def input_loop(self):
 322         loop = True
 323 
 324         while loop:
 325             self.show_headline()
 326 
 327             input = Voc()
 328             input.german = raw_input('German: ')
 329             input.english = raw_input('English: ')
 330 
 331             c = Category()
 332             l = c.get_all()
 333 
 334 
 335             # catLst = [el.category for el in l]
 336             print
 337             print "Kategorien:"
 338             print "-----------"
 339 
 340             print ", ".join([ str(el.category)+'('+str(el.id)+')' for el in l])
 341 
 342             input.session.save(input)
 343             input.session.flush()
 344 
 345             catSelection = raw_input('Category: ')
 346             catLst = catSelection.split(',')
 347             catLst = map(int,catLst)
 348 
 349             # Save category
 350 
 351             for cat in catLst:
 352                 c = Cross()
 353                 c.cat_id = cat
 354                 c.voc_id = input.id
 355                 self.session.save(c)
 356             self.session.flush()
 357 
 358             selection = raw_input('e) Exit  c) Continue: ')
 359             if selection in ['e','E']: loop=False
 360 
 361 class Enter_Category(Trainer):
 362     def __init__(self):
 363         Trainer.__init__(self,"Enter category")
 364 
 365     def input_loop(self):
 366         loop = True
 367 
 368         while loop:
 369             self.show_headline()
 370 
 371             c = Category()
 372             l = c.get_all()
 373 
 374             print
 375             print "Kategorien:"
 376             print "-----------"
 377 
 378             print ", ".join([ str(el.category)+'('+str(el.id)+')' for el in l])
 379 
 380             #input.category.append(Category(catSelection))
 381 
 382             print
 383             input = Category()
 384             input.category = raw_input('New Category: ')
 385 
 386             input.session.save(input)
 387             input.session.flush()
 388 
 389             selection = raw_input('e) Exit  c) Continue: ')
 390             if selection in ['e','E']: loop=False
 391 
 392 
 393 class EnglErrorTest(Engl_Ger):
 394     def __init__(self):
 395         Engl_Ger.__init__(self,"Testing erraneous English voc",container=Error)
 396 
 397 class GerErrorTest(Ger_Engl):
 398     def __init__(self):
 399         Ger_Engl.__init__(self,"Testing erraneous German voc",container=Error)
 400 
 401 class VocTest(unittest.TestCase):
 402     def setUp(self):
 403         c = Category
 404         c.id = -1
 405         c.category = "test"
 406 
 407         c.session.save(c)
 408         c.session.flush()
 409 
 410     def test_first_german_error(self):
 411         pass
 412 
 413 
 414 
 415 if __name__ == "__main__":
 416     """ Displaying a mini menu here """
 417 
 418 
 419     loop = True
 420     while loop:
 421         clear_screen()
 422         print "1) Create new database"
 423         print "2) Enter category"
 424         print "3) Enter vocabulary"
 425         print "4) Test English <--> German"
 426         print "5) Test German <--> English"
 427         print "   Errortesting"
 428         print "6) Error testing English <--> German"
 429         print "7) Error testing German <--> English "
 430         print "8) Testing by category English <--> German"
 431         print "9) Show list of erraneous vocs"
 432         print "E) Exit"
 433         print ""
 434         selection = raw_input("Your selection:")
 435 
 436         if selection in ['e','E']:
 437             loop=False
 438 
 439         if selection == '1':
 440             create_database()
 441         elif selection == '2':
 442             enter_category()
 443         elif selection == '3':
 444             enter_voc()
 445         elif selection == '4':
 446             test_engl_ger()
 447         elif selection == '5':
 448             test_ger_engl()
 449         elif selection == '6':
 450             engl_error_testing()
 451         elif selection == '7':
 452             ger_error_testing()
 453         elif selection == '9':

BeispielCodeVortragRalf (zuletzt geändert am 2009-06-17 16:14:20 durch anonym)